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