]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/NavDisplay.cxx
Allow ND rules to occur in the symbols file.
[flightgear.git] / src / Cockpit / NavDisplay.cxx
1 // navigation display texture
2 //
3 // Written by James Turner, forked from wxradar code
4 //
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 //
20 //
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include "NavDisplay.hxx"
27
28 #include <cassert>
29 #include <boost/foreach.hpp>
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <algorithm>
32
33 #include <osg/Array>
34 #include <osg/Geometry>
35 #include <osg/Matrixf>
36 #include <osg/PrimitiveSet>
37 #include <osg/StateSet>
38 #include <osg/LineWidth>
39 #include <osg/Version>
40
41 #include <simgear/constants.h>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/scene/model/model.hxx>
44 #include <simgear/structure/exception.hxx>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/misc/strutils.hxx>
47 #include <simgear/math/sg_geodesy.hxx>
48
49 #include <sstream>
50 #include <iomanip>
51 #include <iostream>             // for cout, endl
52
53 using std::stringstream;
54 using std::endl;
55 using std::setprecision;
56 using std::fixed;
57 using std::setw;
58 using std::setfill;
59 using std::cout;
60 using std::endl;
61 using std::map;
62 using std::string;
63
64 #include <Main/fg_props.hxx>
65 #include <Main/globals.hxx>
66 #include "panel.hxx"
67 #include <Navaids/routePath.hxx>
68 #include <Autopilot/route_mgr.hxx>
69 #include <Navaids/navrecord.hxx>
70 #include <Navaids/navlist.hxx>
71 #include <Navaids/fix.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/runways.hxx>
74 #include "od_gauge.hxx"
75
76 static const char *DEFAULT_FONT = "typewriter.txf";
77
78 static
79 osg::Matrixf degRotation(float angle)
80 {
81     return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
82 }
83
84 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
85 {
86     osg::Vec4 result;
87     result.r() = colorNode->getDoubleValue("red",   c.r());
88     result.g() = colorNode->getDoubleValue("green", c.g());
89     result.b() = colorNode->getDoubleValue("blue",  c.b());
90     result.a() = colorNode->getDoubleValue("alpha", c.a());
91     return result;
92 }
93
94 static osgText::Text::AlignmentType readAlignment(const std::string& t)
95 {
96     if (t == "left-top") {
97         return osgText::Text::LEFT_TOP;
98     } else if (t == "left-center") {
99         return osgText::Text::LEFT_CENTER;
100     } else if (t == "left-bottom") {
101         return osgText::Text::LEFT_BOTTOM;
102     } else if (t == "center-top") {
103         return osgText::Text::CENTER_TOP;
104     } else if (t == "center-center") {
105         return osgText::Text::CENTER_CENTER;
106     } else if (t == "center-bottom") {
107         return osgText::Text::CENTER_BOTTOM;
108     } else if (t == "right-top") {
109         return osgText::Text::RIGHT_TOP;
110     } else if (t == "right-center") {
111         return osgText::Text::RIGHT_CENTER;
112     } else if (t == "right-bottom") {
113         return osgText::Text::RIGHT_BOTTOM;
114     } else if (t == "left-baseline") {
115         return osgText::Text::LEFT_BASE_LINE;
116     } else if (t == "center-baseline") {
117         return osgText::Text::CENTER_BASE_LINE;
118     } else if (t == "right-baseline") {
119         return osgText::Text::RIGHT_BASE_LINE;
120     }
121     
122     return osgText::Text::BASE_LINE;
123 }
124
125 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
126 {
127     assert(nd);
128     static char buf[512];
129     if (format.find('d') != string::npos) {
130         ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
131         return buf;
132     }
133     
134     if (format.find('s') != string::npos) {
135         ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
136         return buf;
137     }
138     
139 // assume it's a double/float
140     ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
141     return buf;
142 }
143
144 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
145 {
146     osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
147     return osg::Vec2(r.x(), r.y());
148 }
149
150 class NavDisplay::CacheListener : public SGPropertyChangeListener
151 {
152 public:
153     CacheListener(NavDisplay *nd) : 
154         _nd(nd)
155     {}
156     
157     virtual void valueChanged (SGPropertyNode * prop)
158     {
159         _nd->invalidatePositionedCache();
160     }
161 private:
162     NavDisplay* _nd;
163 };
164
165 class NavDisplay::ForceUpdateListener : public SGPropertyChangeListener
166 {
167 public:
168   ForceUpdateListener(NavDisplay *nd) : 
169     _nd(nd)
170   {}
171   
172   virtual void valueChanged (SGPropertyNode * prop)
173   {
174     _nd->forceUpdate();
175   }
176 private:
177   NavDisplay* _nd;
178 };
179
180 ///////////////////////////////////////////////////////////////////
181
182 class SymbolRule
183 {
184 public:
185   SymbolRule()
186     {
187         
188     }
189     
190     bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
191     {
192         if (!node->getChild("type")) {
193             return false;
194         }
195         
196         type = node->getStringValue("type");
197         boost::to_lower(type);
198         SGPropertyNode* enableNode = node->getChild("enable");
199         if (enableNode) { 
200             enable.reset(sgReadCondition(fgGetNode("/"), enableNode));
201         }
202         
203         int n=0;
204         while (node->hasChild("state", n)) {
205             string m = node->getChild("state", n++)->getStringValue();
206             if (m[0] == '!') {
207                 excluded_states.insert(m.substr(1));
208             } else {
209                 required_states.insert(m);
210             }
211         } // of matches parsing
212         
213           
214         return true;
215     }
216     
217     void setDefinition(SymbolDef* d)
218     {
219         definition = d;
220     }
221     
222     SymbolDef* getDefinition() const
223     { return definition; }
224     
225     bool matches(const string_set& states) const
226     {
227         BOOST_FOREACH(const string& s, required_states) {
228             if (states.count(s) == 0) {
229                 return false;
230             }
231         }
232         
233         BOOST_FOREACH(const string& s, excluded_states) {
234             if (states.count(s) != 0) {
235                 return false;
236             }
237         }
238         
239         return true;
240     }
241     
242   // return if the enabled state changed (needs a cache update)
243     bool checkEnabled()
244     {
245         if (enable.get()) {
246             bool wasEnabled = enabled;
247             enabled = enable->test();
248             return (enabled != wasEnabled);
249         } else {
250             enabled = true;
251             return false;
252         }
253     }
254     
255     bool enabled; // cached enabled state
256     std::string type;
257     
258   // record instances for limiting by count
259     int instanceCount;
260 private:
261     SymbolDef* definition;
262     
263     std::auto_ptr<SGCondition> enable;
264     string_set required_states;
265     string_set excluded_states;
266 };
267
268 class SymbolDef
269 {
270 public:
271     SymbolDef() : limitCount(0) { }
272   
273     bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
274     {
275         if (node->getChild("type")) {
276             SymbolRule* builtinRule = new SymbolRule;
277             builtinRule->initFromNode(node, owner);
278             builtinRule->setDefinition(this);
279             owner->addRule(builtinRule);
280         }
281         
282         if (node->hasChild("width")) {
283             float w = node->getFloatValue("width");
284             float h = node->getFloatValue("height", w);
285             xy0.x() = -w * 0.5;
286             xy0.y() = -h * 0.5;
287             xy1.x() = w * 0.5;
288             xy1.y() = h * 0.5;
289         } else {
290             xy0.x()  = node->getFloatValue("x0", 0.0);
291             xy0.y()  = node->getFloatValue("y0", 0.0);
292             xy1.x()  = node->getFloatValue("x1", 5);
293             xy1.y()  = node->getFloatValue("y1", 5);
294         }
295       
296         double texSize = node->getFloatValue("texture-size", owner->textureSize());
297         
298         uv0.x()  = node->getFloatValue("u0", 0) / texSize;
299         uv0.y()  = node->getFloatValue("v0", 0) / texSize;
300         uv1.x()  = node->getFloatValue("u1", 1) / texSize;
301         uv1.y()  = node->getFloatValue("v1", 1) / texSize;
302         
303         color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
304         priority = node->getIntValue("priority", 0);
305         zOrder = node->getIntValue("zOrder", 0);
306         rotateToHeading = node->getBoolValue("rotate-to-heading", false);
307         roundPos = node->getBoolValue("round-position", true);
308         hasText = false;
309         if (node->hasChild("text")) {
310             hasText = true;
311             alignment = readAlignment(node->getStringValue("text-align"));
312             textTemplate = node->getStringValue("text");
313             textOffset.x() = node->getFloatValue("text-offset-x", 0);
314             textOffset.y() = node->getFloatValue("text-offset-y", 0);
315             textColor = readColor(node->getChild("text-color"), color);
316           
317             SGPropertyNode* enableNode = node->getChild("text-enable");
318             if (enableNode) { 
319               textEnable.reset(sgReadCondition(fgGetNode("/"), enableNode));
320             }
321         }
322         
323         drawLine = node->getBoolValue("draw-line", false);
324         lineColor = readColor(node->getChild("line-color"), color);
325         drawRouteLeg = node->getBoolValue("draw-leg", false);
326         
327         stretchSymbol = node->getBoolValue("stretch-symbol", false);
328         if (stretchSymbol) {
329             stretchY2 = node->getFloatValue("y2");
330             stretchY3 = node->getFloatValue("y3");
331             stretchV2 = node->getFloatValue("v2") / texSize;
332             stretchV3 = node->getFloatValue("v3") / texSize;
333         }
334       
335         SGPropertyNode* limitNode = node->getChild("limit");
336         if (limitNode) {
337           limitCount = limitNode->getIntValue();
338         }
339
340         return true;
341     }
342     
343     osg::Vec2 xy0, xy1;
344     osg::Vec2 uv0, uv1;
345     osg::Vec4 color;
346     
347     int priority;
348     int zOrder;
349     bool rotateToHeading;
350     bool roundPos; ///< should position be rounded to integer values
351     bool hasText;
352     std::auto_ptr<SGCondition> textEnable;
353     bool textEnabled; ///< cache condition result
354     osg::Vec4 textColor;
355     osg::Vec2 textOffset;
356     osgText::Text::AlignmentType alignment;
357     string textTemplate;
358     
359     bool drawLine;
360     osg::Vec4 lineColor;
361     
362 // symbol stretching creates three quads (instead of one) - a start,
363 // middle and end quad, positioned along the line of the symbol.
364 // X (and U) axis values determined by the values above, so we only need
365 // to define the Y (and V) values to build the other quads.
366     bool stretchSymbol;
367     double stretchY2, stretchY3;
368     double stretchV2, stretchV3;
369     
370     bool drawRouteLeg;
371     
372     int limitCount, instanceCount;
373 };
374
375 class SymbolInstance
376 {
377 public:
378     SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
379         pos(p),
380         headingDeg(h),
381         definition(def),
382         props(vars)
383     { }
384     
385     osg::Vec2 pos; // projected position
386     osg::Vec2 endPos;
387     double headingDeg;
388     SymbolDef* definition;
389     SGPropertyNode_ptr props;
390     
391     string text() const
392     {
393         assert(definition->hasText);
394         string r;        
395         size_t lastPos = 0;
396         
397         while (true) {
398             size_t pos = definition->textTemplate.find('{', lastPos);
399             if (pos == string::npos) { // no more replacements
400                 r.append(definition->textTemplate.substr(lastPos));
401                 break;
402             }
403             
404             r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
405             
406             size_t endReplacement = definition->textTemplate.find('}', pos+1);
407             if (endReplacement <= pos) {
408                 return "bad replacement";
409             }
410
411             string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
412         // look for formatter in spec
413             size_t colonPos = spec.find(':');
414             if (colonPos == string::npos) {
415             // simple replacement
416                 r.append(props->getStringValue(spec));
417             } else {
418                 string format = spec.substr(colonPos + 1);
419                 string prop = spec.substr(0, colonPos);
420                 r.append(formatPropertyValue(props->getNode(prop), format));
421             }
422             
423             lastPos = endReplacement + 1;
424         }
425         
426         return r;
427     }
428 };
429
430 //////////////////////////////////////////////////////////////////
431
432 NavDisplay::NavDisplay(SGPropertyNode *node) :
433     _name(node->getStringValue("name", "nd")),
434     _num(node->getIntValue("number", 0)),
435     _time(0.0),
436     _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
437     _forceUpdate(true),
438     _odg(0),
439     _scale(0),
440     _view_heading(0),
441     _font_size(0),
442     _font_spacing(0),
443     _rangeNm(0),
444     _maxSymbols(100)
445 {
446     _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
447     _font_node = _Instrument->getNode("font", true);
448
449 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
450     INITFONT("name", DEFAULT_FONT, String);
451     INITFONT("size", 8, Float);
452     INITFONT("line-spacing", 0.25, Float);
453     INITFONT("color/red", 0, Float);
454     INITFONT("color/green", 0.8, Float);
455     INITFONT("color/blue", 0, Float);
456     INITFONT("color/alpha", 1, Float);
457 #undef INITFONT
458
459     _textureSize = _Instrument->getNode("symbol-texture-size", true)->getIntValue();
460     SGPropertyNode* symbolsNode = node->getNode("symbols");
461     SGPropertyNode* symbol;
462
463     map<string, SymbolDef*> definitionDict;
464     for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
465         SymbolDef* def = new SymbolDef;
466         if (!def->initFromNode(symbol, this)) {
467           delete def;
468           continue;
469         }
470         
471         const char* id = symbol->getStringValue("id");
472         if (id && strlen(id)) {
473             definitionDict[id] = def;
474         }
475         
476         _definitions.push_back(def);
477     } // of symbol definition parsing
478     
479     BOOST_FOREACH(SGPropertyNode* rule, symbolsNode->getChildren("rule")) {
480         SymbolRule* r = new SymbolRule;
481         if (!r->initFromNode(rule, this)) {
482             delete r;
483             continue;
484         }
485         
486         const char* id = rule->getStringValue("symbol");
487         if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
488             r->setDefinition(definitionDict[id]);
489         } else {
490             SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
491             delete r;
492             continue;
493         }
494         
495         addRule(r);
496     }
497     
498 }
499
500
501 NavDisplay::~NavDisplay()
502 {
503   delete _odg;
504 }
505
506 void
507 NavDisplay::init ()
508 {
509     _cachedItemsValid = false;
510     _cacheListener.reset(new CacheListener(this));
511     _forceUpdateListener.reset(new ForceUpdateListener(this));
512   
513     _serviceable_node = _Instrument->getNode("serviceable", true);
514     _rangeNode = _Instrument->getNode("range", true);
515     if (!_rangeNode->hasValue()) {
516       _rangeNode->setDoubleValue(40.0);
517     }
518     _rangeNode->addChangeListener(_cacheListener.get());
519     _rangeNode->addChangeListener(_forceUpdateListener.get());
520   
521     _xCenterNode = _Instrument->getNode("x-center");
522     if (!_xCenterNode->hasValue()) {
523       _xCenterNode->setDoubleValue(0.5);
524     }
525     _xCenterNode->addChangeListener(_forceUpdateListener.get());
526     _yCenterNode = _Instrument->getNode("y-center");
527     if (!_yCenterNode->hasValue()) {
528       _yCenterNode->setDoubleValue(0.5);
529     }
530     _yCenterNode->addChangeListener(_forceUpdateListener.get());
531   
532     // texture name to use in 2D and 3D instruments
533     _texture_path = _Instrument->getStringValue("radar-texture-path",
534         "Aircraft/Instruments/Textures/od_wxradar.rgb");
535
536     string path = _Instrument->getStringValue("symbol-texture-path",
537         "Aircraft/Instruments/Textures/nd-symbols.png");
538     SGPath tpath = globals->resolve_aircraft_path(path);
539     if (!tpath.exists()) {
540       SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
541     }
542   
543     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
544     _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
545
546     _odg = new FGODGauge;
547     _odg->setSize(_Instrument->getIntValue("texture-size", 512));
548
549     _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
550     
551     _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
552     _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
553     
554     _excessDataNode = _Instrument->getChild("excess-data", 0, true);
555     _excessDataNode->setBoolValue(false);
556     _testModeNode = _Instrument->getChild("test-mode", 0, true);
557     _testModeNode->setBoolValue(false);
558   
559     _viewHeadingNode = _Instrument->getChild("view-heading-deg", 0, true);
560     _userLatNode = _Instrument->getChild("user-latitude-deg", 0, true);
561     _userLonNode = _Instrument->getChild("user-longitude-deg", 0, true);
562     _userPositionEnable = _Instrument->getChild("user-position", 0, true);
563     
564     _customSymbols = _Instrument->getChild("symbols", 0, true);
565     
566 // OSG geometry setup
567     _radarGeode = new osg::Geode;
568
569     _geom = new osg::Geometry;
570     _geom->setUseDisplayList(false);
571     
572     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
573     stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
574     stateSet->setDataVariance(osg::Object::STATIC);
575   
576     // Initially allocate space for 128 quads
577     _vertices = new osg::Vec2Array;
578     _vertices->setDataVariance(osg::Object::DYNAMIC);
579     _vertices->reserve(128 * 4);
580     _geom->setVertexArray(_vertices);
581     _texCoords = new osg::Vec2Array;
582     _texCoords->setDataVariance(osg::Object::DYNAMIC);
583     _texCoords->reserve(128 * 4);
584     _geom->setTexCoordArray(0, _texCoords);
585     
586     _quadColors = new osg::Vec4Array;
587     _quadColors->setDataVariance(osg::Object::DYNAMIC);
588     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
589     _geom->setColorArray(_quadColors);
590     
591     _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
592     _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
593     _geom->addPrimitiveSet(_symbolPrimSet);
594     
595     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
596         osg::Vec3f(256.0f, 256.0f, 0.0f)));
597   
598     _radarGeode->addDrawable(_geom);
599     _odg->allocRT();
600     // Texture in the 2D panel system
601     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
602
603     _lineGeometry = new osg::Geometry;
604     _lineGeometry->setUseDisplayList(false);
605     stateSet = _lineGeometry->getOrCreateStateSet();    
606     osg::LineWidth *lw = new osg::LineWidth();
607     lw->setWidth(2.0);
608     stateSet->setAttribute(lw);
609     
610     _lineVertices = new osg::Vec2Array;
611     _lineVertices->setDataVariance(osg::Object::DYNAMIC);
612     _lineVertices->reserve(128 * 4);
613     _lineGeometry->setVertexArray(_lineVertices);
614     
615                   
616     _lineColors = new osg::Vec4Array;
617     _lineColors->setDataVariance(osg::Object::DYNAMIC);
618     _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
619     _lineGeometry->setColorArray(_lineColors);
620     
621     _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
622     _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
623     _lineGeometry->addPrimitiveSet(_linePrimSet);
624     
625     _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
626                                             osg::Vec3f(256.0f, 256.0f, 0.0f)));
627
628     _radarGeode->addDrawable(_lineGeometry);              
629                   
630     _textGeode = new osg::Geode;
631
632     osg::Camera *camera = _odg->getCamera();
633     camera->addChild(_radarGeode.get());
634     camera->addChild(_textGeode.get());
635     osg::Texture2D* tex = _odg->getTexture();
636     camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(), 
637         0, tex->getTextureHeight());
638     
639     updateFont();
640 }
641
642 void
643 NavDisplay::update (double delta_time_sec)
644 {
645   if (!fgGetBool("sim/sceneryloaded", false)) {
646     return;
647   }
648
649   if (!_odg || !_serviceable_node->getBoolValue()) {
650     _Instrument->setStringValue("status", "");
651     return;
652   }
653   
654   if (_forceUpdate) {
655     _forceUpdate = false;
656     _time = 0.0;
657   } else {
658     _time += delta_time_sec;
659     if (_time < _updateInterval){
660       return;
661     }
662     _time -= _updateInterval;
663   }
664
665   _rangeNm = _rangeNode->getFloatValue();
666   if (_testModeNode->getBoolValue()) {
667     _view_heading = 90;
668   } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
669     _view_heading = fgGetDouble("/orientation/heading-deg");
670   } else {
671     _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
672   }
673   _viewHeadingNode->setDoubleValue(_view_heading);
674   
675   double xCenterFrac = _xCenterNode->getDoubleValue();
676   double yCenterFrac = _yCenterNode->getDoubleValue();
677   int pixelSize = _odg->size();
678   
679   int rangePixels = _Instrument->getIntValue("range-pixels", -1);
680   if (rangePixels < 0) {
681     // hacky - assume (as is very common) that x-frac doesn't vary, and
682     // y-frac is used to position the center at either the top or bottom of
683     // the pixel area. Measure from the center to the furthest edge (top or bottom)
684     rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
685   }
686   
687   _scale = rangePixels / _rangeNm;
688   _Instrument->setDoubleValue("scale", _scale);
689   
690   
691   _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize, 
692       yCenterFrac * pixelSize, 0.0);
693
694 // scale from nm to display units, rotate so aircraft heading is up
695 // (as opposed to north), and compensate for centering
696   _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) * 
697       degRotation(-_view_heading) * _centerTrans;
698   
699     if (_userPositionEnable->getBoolValue()) {
700         _pos = SGGeod::fromDeg(_userLonNode->getDoubleValue(), _userLatNode->getDoubleValue());
701     } else {
702         _pos = globals->get_aircraft_position();
703     }
704     
705     // invalidate the cache of positioned items, if we travelled more than 1nm
706     if (_cachedItemsValid) {
707         SGVec3d cartNow(SGVec3d::fromGeod(_pos));
708         double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
709         _cachedItemsValid = (movedNm < 1.0);
710     }
711     
712   _vertices->clear();
713   _lineVertices->clear();
714   _lineColors->clear();
715   _quadColors->clear();
716   _texCoords->clear();
717   _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
718   
719   BOOST_FOREACH(SymbolInstance* si, _symbols) {
720       delete si;
721   }
722   _symbols.clear();
723   
724   BOOST_FOREACH(SymbolDef* d, _definitions) {
725     d->instanceCount = 0;
726     d->textEnabled = d->textEnable.get() ? d->textEnable->test() : true;
727   }
728   
729   bool enableChanged = false;
730   BOOST_FOREACH(SymbolRule* r, _rules) {
731       enableChanged |= r->checkEnabled();
732   }
733   
734   if (enableChanged) {
735     SG_LOG(SG_INSTR, SG_INFO, "NS rule enables changed, rebuilding cache");
736     _cachedItemsValid = false;
737   }
738   
739   if (_testModeNode->getBoolValue()) {
740     addTestSymbols();
741   } else {
742     processRoute();
743     processNavRadios();
744     processAI();
745     processCustomSymbols();
746     findItems();
747     limitDisplayedSymbols();
748   }
749
750   addSymbolsToScene();
751   
752   _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
753   _symbolPrimSet->dirty();
754   _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
755   _linePrimSet->dirty();
756 }
757
758
759 void
760 NavDisplay::updateFont()
761 {
762     float red = _font_node->getFloatValue("color/red");
763     float green = _font_node->getFloatValue("color/green");
764     float blue = _font_node->getFloatValue("color/blue");
765     float alpha = _font_node->getFloatValue("color/alpha");
766     _font_color.set(red, green, blue, alpha);
767
768     _font_size = _font_node->getFloatValue("size");
769     _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
770     string path = _font_node->getStringValue("name", DEFAULT_FONT);
771
772     SGPath tpath;
773     if (path[0] != '/') {
774         tpath = globals->get_fg_root();
775         tpath.append("Fonts");
776         tpath.append(path);
777     } else {
778         tpath = path;
779     }
780
781     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
782     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
783
784     if (font != 0) {
785         _font = font;
786         _font->setMinFilterHint(osg::Texture::NEAREST);
787         _font->setMagFilterHint(osg::Texture::NEAREST);
788         _font->setGlyphImageMargin(0);
789         _font->setGlyphImageMarginRatio(0);
790     }
791 }
792
793 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
794 {
795     SymbolDef* def = sym->definition;
796     
797     osg::Vec2 verts[4];
798     verts[0] = def->xy0;
799     verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
800     verts[2] = def->xy1;
801     verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
802     
803     if (def->rotateToHeading) {
804         osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
805         for (int i=0; i<4; ++i) {
806             verts[i] = mult(verts[i], m);
807         }
808     }
809     
810     osg::Vec2 pos = sym->pos;
811     if (def->roundPos) {
812         pos = osg::Vec2((int) pos.x(), (int) pos.y());
813     }
814     
815     _texCoords->push_back(def->uv0);
816     _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
817     _texCoords->push_back(def->uv1);
818     _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
819
820     for (int i=0; i<4; ++i) {
821         _vertices->push_back(verts[i] + pos);
822         _quadColors->push_back(def->color);
823     }
824     
825     if (def->stretchSymbol) {
826         osg::Vec2 stretchVerts[4];
827         stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
828         stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
829         stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
830         stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
831         
832         osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
833         for (int i=0; i<4; ++i) {
834             stretchVerts[i] = mult(stretchVerts[i], m);
835         }
836         
837     // stretched quad
838         _vertices->push_back(verts[2] + pos);
839         _vertices->push_back(stretchVerts[1] + sym->endPos);
840         _vertices->push_back(stretchVerts[0] + sym->endPos);
841         _vertices->push_back(verts[3] + pos);
842         
843         _texCoords->push_back(def->uv1);
844         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
845         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
846         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
847         
848         for (int i=0; i<4; ++i) {
849             _quadColors->push_back(def->color);
850         }
851         
852     // quad three, for the end portion
853         for (int i=0; i<4; ++i) {
854             _vertices->push_back(stretchVerts[i] + sym->endPos);
855             _quadColors->push_back(def->color);
856         }
857         
858         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
859         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
860         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
861         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
862     }
863     
864     if (def->drawLine) {
865         addLine(sym->pos, sym->endPos, def->lineColor);
866     }
867     
868     if (!def->hasText || !def->textEnabled) {
869         return;
870     }
871     
872     osgText::Text* t = new osgText::Text;
873     t->setFont(_font.get());
874     t->setFontResolution(12, 12);
875     t->setCharacterSize(_font_size);
876     t->setLineSpacing(_font_spacing);
877     t->setColor(def->textColor);
878     t->setAlignment(def->alignment);
879     t->setText(sym->text());
880
881
882     osg::Vec2 textPos = def->textOffset + pos;
883 // ensure we use ints here, or text visual quality goes bad
884     t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
885     _textGeode->addDrawable(t);
886 }
887
888 class OrderByPriority
889 {
890 public:
891     bool operator()(SymbolInstance* a, SymbolInstance* b)
892     {
893         return a->definition->priority > b->definition->priority;
894     }    
895 };
896
897 void NavDisplay::limitDisplayedSymbols()
898 {
899 // gloabl symbol limit
900     _maxSymbols= _Instrument->getIntValue("max-symbols", _maxSymbols);
901     if ((int) _symbols.size() <= _maxSymbols) {
902         _excessDataNode->setBoolValue(false);
903         return;
904     }
905     
906     std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
907     _symbols.resize(_maxSymbols);
908     _excessDataNode->setBoolValue(true);
909 }
910
911 class OrderByZ
912 {
913 public:
914     bool operator()(SymbolInstance* a, SymbolInstance* b)
915     {
916         return a->definition->zOrder > b->definition->zOrder;
917     }
918 };
919
920 void NavDisplay::addSymbolsToScene()
921 {
922     std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
923     BOOST_FOREACH(SymbolInstance* sym, _symbols) {
924         addSymbolToScene(sym);
925     }
926 }
927
928 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
929 {    
930     _lineVertices->push_back(a);
931     _lineVertices->push_back(b);
932     _lineColors->push_back(color);
933     _lineColors->push_back(color);
934 }
935
936 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
937 {
938     osg::Vec3 p(0, rangeNm, 0.0);
939     p = degRotation(bearingDeg).preMult(p);
940     p = _projectMat.preMult(p);
941     return osg::Vec2(p.x(), p.y());
942 }
943
944 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
945 {
946     double rangeM, bearing, az2;
947     SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
948     return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
949 }
950
951 class Filter : public FGPositioned::Filter
952 {
953 public:
954     Filter(NavDisplay* nd) : _owner(nd) { }
955   
956     double minRunwayLengthFt;
957   
958     virtual bool pass(FGPositioned* aPos) const
959     {
960         if (aPos->type() == FGPositioned::FIX) {
961             string ident(aPos->ident());
962             // ignore fixes which end in digits
963             if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
964                 return false;
965             }
966         }
967
968         if (aPos->type() == FGPositioned::AIRPORT) {
969           FGAirport* apt = (FGAirport*) aPos;
970           if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
971             return false;
972           }
973         }
974       
975       // check against current rule states
976         return _owner->isPositionedShown(aPos);
977     }
978
979     virtual FGPositioned::Type minType() const {
980         return FGPositioned::AIRPORT;
981     }
982
983     virtual FGPositioned::Type maxType() const {
984         return FGPositioned::OBSTACLE;
985     }
986   
987 private:
988     NavDisplay* _owner;
989 };
990
991 void NavDisplay::findItems()
992 {
993     if (!_cachedItemsValid) {
994         Filter filt(this);
995         filt.minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
996         bool wasTimeLimited;
997         _itemsInRange = FGPositioned::findClosestNPartial(_pos, _maxSymbols, _rangeNm,
998                                                           &filt, wasTimeLimited);
999         _cachedItemsValid = true;
1000         _cachedPos = SGVec3d::fromGeod(_pos);
1001         
1002         if (wasTimeLimited) {
1003             // re-query next frame, to load incrementally
1004             _cachedItemsValid = false;
1005         }
1006     }
1007     
1008   // sort by distance from pos, so symbol limits are accurate
1009     FGPositioned::sortByRange(_itemsInRange, _pos);
1010   
1011     BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
1012         foundPositionedItem(pos);
1013     }
1014 }
1015
1016 void NavDisplay::processRoute()
1017 {
1018     _routeSources.clear();
1019     flightgear::FlightPlan* fp = _route->flightPlan();
1020     RoutePath path(fp);
1021     int current = _route->currentIndex();
1022     
1023     for (int l=0; l<fp->numLegs(); ++l) {
1024         flightgear::FlightPlan::Leg* leg = fp->legAtIndex(l);
1025         flightgear::WayptRef wpt(leg->waypoint());
1026         _routeSources.insert(wpt->source());
1027         
1028         string_set state;
1029         state.insert("on-active-route");
1030         
1031         if (l < current) {
1032             state.insert("passed");
1033         }
1034         
1035         if (l == current) {
1036             state.insert("current-wp");
1037         }
1038         
1039         if (l > current) {
1040             state.insert("future");
1041         }
1042         
1043         if (l == (current + 1)) {
1044             state.insert("next-wp");
1045         }
1046         
1047         SymbolRuleVector rules;
1048         findRules("waypoint" , state, rules);
1049         if (rules.empty()) {
1050             return; // no rules matched, we can skip this item
1051         }
1052
1053         SGGeod g = path.positionForIndex(l);
1054         SGPropertyNode* vars = _route->wayptNodeAtIndex(l);
1055         if (!vars) {
1056           continue; // shouldn't happen, but let's guard against it
1057         }
1058       
1059         double heading;
1060         computeWayptPropsAndHeading(wpt, g, vars, heading);
1061
1062         osg::Vec2 projected = projectGeod(g);
1063         BOOST_FOREACH(SymbolRule* r, rules) {
1064             addSymbolInstance(projected, heading, r->getDefinition(), vars);
1065             
1066             if (r->getDefinition()->drawRouteLeg) {
1067                 SGGeodVec gv(path.pathForIndex(l));
1068                 if (!gv.empty()) {
1069                     osg::Vec2 pr = projectGeod(gv[0]);
1070                     for (unsigned int i=1; i<gv.size(); ++i) {
1071                         osg::Vec2 p = projectGeod(gv[i]);
1072                         addLine(pr, p, r->getDefinition()->lineColor);
1073                         pr = p;
1074                     }
1075                 }
1076             } // of leg drawing enabled
1077         } // of matching rules iteration
1078     } // of waypoints iteration
1079 }
1080
1081 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1082 {
1083     double rangeM, az2;
1084     SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1085     nd->setIntValue("radial", heading);
1086     nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1087     
1088     heading = nd->getDoubleValue("leg-bearing-true-deg");
1089 }
1090
1091 void NavDisplay::processNavRadios()
1092 {
1093     _nav1Station = processNavRadio(_navRadio1Node);
1094     _nav2Station = processNavRadio(_navRadio2Node);
1095     
1096     foundPositionedItem(_nav1Station);
1097     foundPositionedItem(_nav2Station);
1098 }
1099
1100 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1101 {
1102   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1103   FGNavRecord* nav = FGNavList::findByFreq(mhz, _pos, FGNavList::navFilter());
1104     if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1105         // station was not found
1106         return NULL;
1107     }
1108     
1109     
1110     return nav;
1111 }
1112
1113 bool NavDisplay::anyRuleForType(const string& type) const
1114 {
1115     BOOST_FOREACH(SymbolRule* r, _rules) {
1116         if (!r->enabled) {
1117             continue;
1118         }
1119     
1120         if (r->type == type) {
1121             return true;
1122         }
1123     }
1124     
1125     return false;
1126 }
1127
1128 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1129 {
1130     BOOST_FOREACH(SymbolRule* candidate, _rules) {
1131         if (!candidate->enabled || (candidate->type != type)) {
1132             continue;
1133         }
1134         
1135         if (candidate->matches(states)) {
1136             rules.push_back(candidate);
1137         }
1138     }
1139 }
1140
1141 bool NavDisplay::isPositionedShown(FGPositioned* pos)
1142 {
1143   SymbolRuleVector rules;
1144   isPositionedShownInner(pos, rules);
1145   return !rules.empty();
1146 }
1147
1148 void NavDisplay::isPositionedShownInner(FGPositioned* pos, SymbolRuleVector& rules)
1149 {
1150   string type = FGPositioned::nameForType(pos->type());
1151   boost::to_lower(type);
1152   if (!anyRuleForType(type)) {
1153     return; // not diplayed at all, we're done
1154   }
1155   
1156   string_set states;
1157   computePositionedState(pos, states);
1158   
1159   findRules(type, states, rules);
1160 }
1161
1162 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1163 {
1164     if (!pos) {
1165         return;
1166     }
1167     
1168     SymbolRuleVector rules;
1169     isPositionedShownInner(pos, rules);
1170     if (rules.empty()) {
1171       return;
1172     }
1173   
1174     SGPropertyNode_ptr vars(new SGPropertyNode);
1175     double heading;
1176     computePositionedPropsAndHeading(pos, vars, heading);
1177     
1178     osg::Vec2 projected = projectGeod(pos->geod());
1179     if (pos->type() == FGPositioned::RUNWAY) {
1180         FGRunway* rwy = (FGRunway*) pos;
1181         projected = projectGeod(rwy->threshold());
1182     }
1183     
1184     BOOST_FOREACH(SymbolRule* r, rules) {
1185         SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1186         if ((ins)&&(pos->type() == FGPositioned::RUNWAY)) {
1187             FGRunway* rwy = (FGRunway*) pos;
1188             ins->endPos = projectGeod(rwy->end());
1189         }
1190     }
1191 }
1192
1193 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1194 {
1195     nd->setStringValue("id", pos->ident());
1196     nd->setStringValue("name", pos->name());
1197     nd->setDoubleValue("elevation-ft", pos->elevation());
1198     nd->setIntValue("heading-deg", 0);
1199     heading = 0.0;
1200     
1201     switch (pos->type()) {
1202     case FGPositioned::VOR:
1203     case FGPositioned::LOC: 
1204     case FGPositioned::TACAN: {
1205         FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1206         nd->setDoubleValue("frequency-mhz", nav->get_freq());
1207         
1208         if (pos == _nav1Station) {
1209             heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1210         } else if (pos == _nav2Station) {
1211             heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1212         }
1213         
1214         nd->setIntValue("heading-deg", heading);
1215         break;
1216     }
1217
1218     case FGPositioned::AIRPORT:
1219     case FGPositioned::SEAPORT:
1220     case FGPositioned::HELIPORT:
1221         
1222         break;
1223         
1224     case FGPositioned::RUNWAY: {
1225         FGRunway* rwy = static_cast<FGRunway*>(pos);
1226         heading = rwy->headingDeg();
1227         nd->setDoubleValue("heading-deg", heading);
1228         nd->setIntValue("length-ft", rwy->lengthFt());
1229         nd->setStringValue("airport", rwy->airport()->ident());
1230         break;
1231     }
1232
1233     default:
1234         break; 
1235     }
1236 }
1237
1238 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1239 {
1240     if (_routeSources.count(pos) != 0) {
1241         states.insert("on-active-route");
1242     }
1243     
1244     flightgear::FlightPlan* fp = _route->flightPlan();
1245     switch (pos->type()) {
1246     case FGPositioned::VOR:
1247     case FGPositioned::LOC:
1248         if (pos == _nav1Station) {
1249             states.insert("tuned");
1250             states.insert("nav1");
1251         }
1252         
1253         if (pos == _nav2Station) {
1254             states.insert("tuned");
1255             states.insert("nav2");
1256         }
1257         break;
1258     
1259     case FGPositioned::AIRPORT:
1260     case FGPositioned::SEAPORT:
1261     case FGPositioned::HELIPORT:
1262         // mark alternates!
1263         // once the FMS system has some way to tell us about them, of course
1264         
1265         if (pos == fp->departureAirport()) {
1266             states.insert("departure");
1267         }
1268         
1269         if (pos == fp->destinationAirport()) {
1270             states.insert("destination");
1271         }
1272         break;
1273     
1274     case FGPositioned::RUNWAY:
1275         if (pos == fp->departureRunway()) {
1276             states.insert("departure");
1277         }
1278         
1279         if (pos == fp->destinationRunway()) {
1280             states.insert("destination");
1281         }
1282         break;
1283     
1284     case FGPositioned::OBSTACLE:
1285     #if 0    
1286         FGObstacle* obs = (FGObstacle*) pos;
1287         if (obj->isLit()) {
1288             states.insert("lit");
1289         }
1290         
1291         if (obj->getHeightAGLFt() >= 1000) {
1292             states.insert("greater-1000-ft");
1293         }
1294     #endif
1295         break;
1296     
1297     default:
1298         break;
1299     } // FGPositioned::Type switch
1300 }
1301
1302 static string mapAINodeToType(SGPropertyNode* model)
1303 {
1304   // assume all multiplayer items are aircraft for the moment. Not ideal.
1305   if (!strcmp(model->getName(), "multiplayer")) {
1306     return "ai-aircraft";
1307   }
1308   
1309   return string("ai-") + model->getName();
1310 }
1311
1312 void NavDisplay::processAI()
1313 {
1314     SGPropertyNode *ai = fgGetNode("/ai/models", true);
1315     for (int i = ai->nChildren() - 1; i >= 0; i--) {
1316         SGPropertyNode *model = ai->getChild(i);
1317         if (!model->nChildren()) {
1318             continue;
1319         }
1320         
1321     // prefix types with 'ai-', to avoid any chance of namespace collisions
1322     // with fg-positioned.
1323         string_set ss;
1324         computeAIStates(model, ss);        
1325         SymbolRuleVector rules;
1326         findRules(mapAINodeToType(model), ss, rules);
1327         if (rules.empty()) {
1328             return; // no rules matched, we can skip this item
1329         }
1330
1331         double heading = model->getDoubleValue("orientation/true-heading-deg");
1332         SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"), 
1333                                             model->getDoubleValue("position/latitude-deg"), 
1334                                             model->getDoubleValue("position/altitude-ft"));
1335     // compute some additional props
1336         int fl = (aiModelPos.getElevationFt() / 1000);
1337         model->setIntValue("flight-level", fl * 10);
1338                                             
1339         osg::Vec2 projected = projectGeod(aiModelPos);
1340         BOOST_FOREACH(SymbolRule* r, rules) {
1341             addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1342         }
1343     } // of ai models iteration
1344 }
1345
1346 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1347 {
1348     int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1349     if (threatLevel < 1)
1350       threatLevel = 0;
1351   
1352     states.insert("tcas");
1353   
1354     std::ostringstream os;
1355     os << "tcas-threat-level-" << threatLevel;
1356     states.insert(os.str());
1357
1358     double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1359     if (vspeed < -3.0) {
1360         states.insert("descending");
1361     } else if (vspeed > 3.0) {
1362         states.insert("climbing");
1363     }
1364 }
1365
1366 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1367 {
1368     if (isProjectedClipped(proj)) {
1369         return NULL;
1370     }
1371     
1372     if ((def->limitCount > 0) && (def->instanceCount >= def->limitCount)) {
1373       return NULL;
1374     }
1375   
1376     ++def->instanceCount;
1377     SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1378     _symbols.push_back(sym);
1379     return sym;
1380 }
1381
1382 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1383 {
1384     double size = _odg->size();
1385     return (projected.x() < 0.0) ||
1386         (projected.y() < 0.0) ||
1387         (projected.x() >= size) ||
1388             (projected.y() >= size);
1389 }
1390
1391 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1392 {
1393   string_set stateSet;
1394   BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1395     stateSet.insert(s);
1396   }
1397   
1398   SymbolRuleVector rules;
1399   findRules(type, stateSet, rules);
1400   if (rules.empty()) {
1401     return; // no rules matched, we can skip this item
1402   }
1403     
1404   osg::Vec2 projected = projectGeod(pos);
1405   BOOST_FOREACH(SymbolRule* r, rules) {
1406     addSymbolInstance(projected, heading, r->getDefinition(), vars);
1407   }
1408 }
1409
1410 void NavDisplay::addTestSymbols()
1411 {
1412   _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1413   
1414   SGGeod a1;
1415   double dummy;
1416   SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1417   
1418   addTestSymbol("airport", "", a1, 0.0, NULL);
1419   
1420   SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1421   
1422   addTestSymbol("vor", "", a1, 0.0, NULL);
1423   
1424   SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1425   
1426   addTestSymbol("airport", "destination", a1, 0.0, NULL);
1427   
1428   SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1429   addTestSymbol("fix", "", a1, 0.0, NULL);
1430
1431   
1432   SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1433   addTestSymbol("fix", "", a1, 0.0, NULL);
1434   
1435   SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);  
1436   addTestSymbol("fix", "", a1, 0.0, NULL);
1437   
1438   SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);  
1439   addTestSymbol("fix", "", a1, 0.0, NULL);
1440 }
1441
1442 void NavDisplay::addRule(SymbolRule* r)
1443 {
1444     _rules.push_back(r);
1445 }
1446
1447 void NavDisplay::computeCustomSymbolStates(const SGPropertyNode* sym, string_set& states)
1448 {
1449   BOOST_FOREACH(SGPropertyNode* st, sym->getChildren("state")) {
1450     states.insert(st->getStringValue());
1451   }
1452 }
1453
1454 void NavDisplay::processCustomSymbols()
1455 {
1456   for (int i = _customSymbols->nChildren() - 1; i >= 0; i--) {
1457     SGPropertyNode *symNode = _customSymbols->getChild(i);
1458     if (!symNode->nChildren()) {
1459       continue;
1460     }
1461     string_set ss;
1462     computeCustomSymbolStates(symNode, ss);
1463     SymbolRuleVector rules;
1464     findRules(symNode->getName(), ss, rules);
1465     if (rules.empty()) {
1466       return; // no rules matched, we can skip this item
1467     }
1468     
1469     double heading = symNode->getDoubleValue("true-heading-deg", 0.0);
1470     SGGeod pos = SGGeod::fromDegFt(symNode->getDoubleValue("longitude-deg"),
1471                                           symNode->getDoubleValue("latitude-deg"),
1472                                           symNode->getDoubleValue("altitude-ft"));
1473  
1474     
1475     osg::Vec2 projected = projectGeod(pos);
1476     BOOST_FOREACH(SymbolRule* r, rules) {
1477       addSymbolInstance(projected, heading, r->getDefinition(), symNode);
1478     }
1479   } // of custom symbols iteration
1480 }
1481
1482