]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/NavDisplay.cxx
NavDisplay: time-bound the spatial query.
[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     SGPropertyNode* rulesNode = node->getNode("rules");
480     if (rulesNode) {
481         SGPropertyNode* rule;
482         
483         for (int i = 0; (rule = rulesNode->getChild("rule", i)) != NULL; ++i) {
484             SymbolRule* r = new SymbolRule;
485             if (!r->initFromNode(rule, this)) {
486                 delete r;
487                 continue;
488             }
489             
490             const char* id = symbol->getStringValue("symbol");
491             if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
492                 r->setDefinition(definitionDict[id]);
493             } else {
494                 SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
495                 delete r;
496                 continue;
497             }
498             
499             addRule(r);
500         } // of symbol rule parsing
501     }
502     
503 }
504
505
506 NavDisplay::~NavDisplay()
507 {
508   delete _odg;
509 }
510
511 void
512 NavDisplay::init ()
513 {
514     _cachedItemsValid = false;
515     _cacheListener.reset(new CacheListener(this));
516     _forceUpdateListener.reset(new ForceUpdateListener(this));
517   
518     _serviceable_node = _Instrument->getNode("serviceable", true);
519     _rangeNode = _Instrument->getNode("range", true);
520     if (!_rangeNode->hasValue()) {
521       _rangeNode->setDoubleValue(40.0);
522     }
523     _rangeNode->addChangeListener(_cacheListener.get());
524     _rangeNode->addChangeListener(_forceUpdateListener.get());
525   
526     _xCenterNode = _Instrument->getNode("x-center");
527     if (!_xCenterNode->hasValue()) {
528       _xCenterNode->setDoubleValue(0.5);
529     }
530     _xCenterNode->addChangeListener(_forceUpdateListener.get());
531     _yCenterNode = _Instrument->getNode("y-center");
532     if (!_yCenterNode->hasValue()) {
533       _yCenterNode->setDoubleValue(0.5);
534     }
535     _yCenterNode->addChangeListener(_forceUpdateListener.get());
536   
537     // texture name to use in 2D and 3D instruments
538     _texture_path = _Instrument->getStringValue("radar-texture-path",
539         "Aircraft/Instruments/Textures/od_wxradar.rgb");
540
541     string path = _Instrument->getStringValue("symbol-texture-path",
542         "Aircraft/Instruments/Textures/nd-symbols.png");
543     SGPath tpath = globals->resolve_aircraft_path(path);
544     if (!tpath.exists()) {
545       SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
546     }
547   
548     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
549     _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
550
551     _odg = new FGODGauge;
552     _odg->setSize(_Instrument->getIntValue("texture-size", 512));
553
554     _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
555     
556     _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
557     _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
558     
559     _excessDataNode = _Instrument->getChild("excess-data", 0, true);
560     _excessDataNode->setBoolValue(false);
561     _testModeNode = _Instrument->getChild("test-mode", 0, true);
562     _testModeNode->setBoolValue(false);
563   
564     _viewHeadingNode = _Instrument->getChild("view-heading-deg", 0, true);
565     _userLatNode = _Instrument->getChild("user-latitude-deg", 0, true);
566     _userLonNode = _Instrument->getChild("user-longitude-deg", 0, true);
567     _userPositionEnable = _Instrument->getChild("user-position", 0, true);
568     
569     _customSymbols = _Instrument->getChild("symbols", 0, true);
570     
571 // OSG geometry setup
572     _radarGeode = new osg::Geode;
573
574     _geom = new osg::Geometry;
575     _geom->setUseDisplayList(false);
576     
577     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
578     stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
579     stateSet->setDataVariance(osg::Object::STATIC);
580   
581     // Initially allocate space for 128 quads
582     _vertices = new osg::Vec2Array;
583     _vertices->setDataVariance(osg::Object::DYNAMIC);
584     _vertices->reserve(128 * 4);
585     _geom->setVertexArray(_vertices);
586     _texCoords = new osg::Vec2Array;
587     _texCoords->setDataVariance(osg::Object::DYNAMIC);
588     _texCoords->reserve(128 * 4);
589     _geom->setTexCoordArray(0, _texCoords);
590     
591     _quadColors = new osg::Vec4Array;
592     _quadColors->setDataVariance(osg::Object::DYNAMIC);
593     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
594     _geom->setColorArray(_quadColors);
595     
596     _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
597     _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
598     _geom->addPrimitiveSet(_symbolPrimSet);
599     
600     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
601         osg::Vec3f(256.0f, 256.0f, 0.0f)));
602   
603     _radarGeode->addDrawable(_geom);
604     _odg->allocRT();
605     // Texture in the 2D panel system
606     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
607
608     _lineGeometry = new osg::Geometry;
609     _lineGeometry->setUseDisplayList(false);
610     stateSet = _lineGeometry->getOrCreateStateSet();    
611     osg::LineWidth *lw = new osg::LineWidth();
612     lw->setWidth(2.0);
613     stateSet->setAttribute(lw);
614     
615     _lineVertices = new osg::Vec2Array;
616     _lineVertices->setDataVariance(osg::Object::DYNAMIC);
617     _lineVertices->reserve(128 * 4);
618     _lineGeometry->setVertexArray(_lineVertices);
619     
620                   
621     _lineColors = new osg::Vec4Array;
622     _lineColors->setDataVariance(osg::Object::DYNAMIC);
623     _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
624     _lineGeometry->setColorArray(_lineColors);
625     
626     _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
627     _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
628     _lineGeometry->addPrimitiveSet(_linePrimSet);
629     
630     _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
631                                             osg::Vec3f(256.0f, 256.0f, 0.0f)));
632
633     _radarGeode->addDrawable(_lineGeometry);              
634                   
635     _textGeode = new osg::Geode;
636
637     osg::Camera *camera = _odg->getCamera();
638     camera->addChild(_radarGeode.get());
639     camera->addChild(_textGeode.get());
640     osg::Texture2D* tex = _odg->getTexture();
641     camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(), 
642         0, tex->getTextureHeight());
643     
644     updateFont();
645 }
646
647 void
648 NavDisplay::update (double delta_time_sec)
649 {
650   if (!fgGetBool("sim/sceneryloaded", false)) {
651     return;
652   }
653
654   if (!_odg || !_serviceable_node->getBoolValue()) {
655     _Instrument->setStringValue("status", "");
656     return;
657   }
658   
659   if (_forceUpdate) {
660     _forceUpdate = false;
661     _time = 0.0;
662   } else {
663     _time += delta_time_sec;
664     if (_time < _updateInterval){
665       return;
666     }
667     _time -= _updateInterval;
668   }
669
670   _rangeNm = _rangeNode->getFloatValue();
671   if (_testModeNode->getBoolValue()) {
672     _view_heading = 90;
673   } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
674     _view_heading = fgGetDouble("/orientation/heading-deg");
675   } else {
676     _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
677   }
678   _viewHeadingNode->setDoubleValue(_view_heading);
679   
680   double xCenterFrac = _xCenterNode->getDoubleValue();
681   double yCenterFrac = _yCenterNode->getDoubleValue();
682   int pixelSize = _odg->size();
683   
684   int rangePixels = _Instrument->getIntValue("range-pixels", -1);
685   if (rangePixels < 0) {
686     // hacky - assume (as is very common) that x-frac doesn't vary, and
687     // y-frac is used to position the center at either the top or bottom of
688     // the pixel area. Measure from the center to the furthest edge (top or bottom)
689     rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
690   }
691   
692   _scale = rangePixels / _rangeNm;
693   _Instrument->setDoubleValue("scale", _scale);
694   
695   
696   _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize, 
697       yCenterFrac * pixelSize, 0.0);
698
699 // scale from nm to display units, rotate so aircraft heading is up
700 // (as opposed to north), and compensate for centering
701   _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) * 
702       degRotation(-_view_heading) * _centerTrans;
703   
704     if (_userPositionEnable->getBoolValue()) {
705         _pos = SGGeod::fromDeg(_userLonNode->getDoubleValue(), _userLatNode->getDoubleValue());
706     } else {
707         _pos = globals->get_aircraft_position();
708     }
709     
710     // invalidate the cache of positioned items, if we travelled more than 1nm
711     if (_cachedItemsValid) {
712         SGVec3d cartNow(SGVec3d::fromGeod(_pos));
713         double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
714         _cachedItemsValid = (movedNm < 1.0);
715     }
716     
717   _vertices->clear();
718   _lineVertices->clear();
719   _lineColors->clear();
720   _quadColors->clear();
721   _texCoords->clear();
722   _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
723   
724   BOOST_FOREACH(SymbolInstance* si, _symbols) {
725       delete si;
726   }
727   _symbols.clear();
728   
729   BOOST_FOREACH(SymbolDef* d, _definitions) {
730     d->instanceCount = 0;
731     d->textEnabled = d->textEnable.get() ? d->textEnable->test() : true;
732   }
733   
734   bool enableChanged = false;
735   BOOST_FOREACH(SymbolRule* r, _rules) {
736       enableChanged |= r->checkEnabled();
737   }
738   
739   if (enableChanged) {
740     SG_LOG(SG_INSTR, SG_INFO, "NS rule enables changed, rebuilding cache");
741     _cachedItemsValid = false;
742   }
743   
744   if (_testModeNode->getBoolValue()) {
745     addTestSymbols();
746   } else {
747     processRoute();
748     processNavRadios();
749     processAI();
750     processCustomSymbols();
751     findItems();
752     limitDisplayedSymbols();
753   }
754
755   addSymbolsToScene();
756   
757   _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
758   _symbolPrimSet->dirty();
759   _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
760   _linePrimSet->dirty();
761 }
762
763
764 void
765 NavDisplay::updateFont()
766 {
767     float red = _font_node->getFloatValue("color/red");
768     float green = _font_node->getFloatValue("color/green");
769     float blue = _font_node->getFloatValue("color/blue");
770     float alpha = _font_node->getFloatValue("color/alpha");
771     _font_color.set(red, green, blue, alpha);
772
773     _font_size = _font_node->getFloatValue("size");
774     _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
775     string path = _font_node->getStringValue("name", DEFAULT_FONT);
776
777     SGPath tpath;
778     if (path[0] != '/') {
779         tpath = globals->get_fg_root();
780         tpath.append("Fonts");
781         tpath.append(path);
782     } else {
783         tpath = path;
784     }
785
786     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
787     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
788
789     if (font != 0) {
790         _font = font;
791         _font->setMinFilterHint(osg::Texture::NEAREST);
792         _font->setMagFilterHint(osg::Texture::NEAREST);
793         _font->setGlyphImageMargin(0);
794         _font->setGlyphImageMarginRatio(0);
795     }
796 }
797
798 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
799 {
800     SymbolDef* def = sym->definition;
801     
802     osg::Vec2 verts[4];
803     verts[0] = def->xy0;
804     verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
805     verts[2] = def->xy1;
806     verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
807     
808     if (def->rotateToHeading) {
809         osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
810         for (int i=0; i<4; ++i) {
811             verts[i] = mult(verts[i], m);
812         }
813     }
814     
815     osg::Vec2 pos = sym->pos;
816     if (def->roundPos) {
817         pos = osg::Vec2((int) pos.x(), (int) pos.y());
818     }
819     
820     _texCoords->push_back(def->uv0);
821     _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
822     _texCoords->push_back(def->uv1);
823     _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
824
825     for (int i=0; i<4; ++i) {
826         _vertices->push_back(verts[i] + pos);
827         _quadColors->push_back(def->color);
828     }
829     
830     if (def->stretchSymbol) {
831         osg::Vec2 stretchVerts[4];
832         stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
833         stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
834         stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
835         stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
836         
837         osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
838         for (int i=0; i<4; ++i) {
839             stretchVerts[i] = mult(stretchVerts[i], m);
840         }
841         
842     // stretched quad
843         _vertices->push_back(verts[2] + pos);
844         _vertices->push_back(stretchVerts[1] + sym->endPos);
845         _vertices->push_back(stretchVerts[0] + sym->endPos);
846         _vertices->push_back(verts[3] + pos);
847         
848         _texCoords->push_back(def->uv1);
849         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
850         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
851         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
852         
853         for (int i=0; i<4; ++i) {
854             _quadColors->push_back(def->color);
855         }
856         
857     // quad three, for the end portion
858         for (int i=0; i<4; ++i) {
859             _vertices->push_back(stretchVerts[i] + sym->endPos);
860             _quadColors->push_back(def->color);
861         }
862         
863         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
864         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
865         _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
866         _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
867     }
868     
869     if (def->drawLine) {
870         addLine(sym->pos, sym->endPos, def->lineColor);
871     }
872     
873     if (!def->hasText || !def->textEnabled) {
874         return;
875     }
876     
877     osgText::Text* t = new osgText::Text;
878     t->setFont(_font.get());
879     t->setFontResolution(12, 12);
880     t->setCharacterSize(_font_size);
881     t->setLineSpacing(_font_spacing);
882     t->setColor(def->textColor);
883     t->setAlignment(def->alignment);
884     t->setText(sym->text());
885
886
887     osg::Vec2 textPos = def->textOffset + pos;
888 // ensure we use ints here, or text visual quality goes bad
889     t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
890     _textGeode->addDrawable(t);
891 }
892
893 class OrderByPriority
894 {
895 public:
896     bool operator()(SymbolInstance* a, SymbolInstance* b)
897     {
898         return a->definition->priority > b->definition->priority;
899     }    
900 };
901
902 void NavDisplay::limitDisplayedSymbols()
903 {
904 // gloabl symbol limit
905     _maxSymbols= _Instrument->getIntValue("max-symbols", _maxSymbols);
906     if ((int) _symbols.size() <= _maxSymbols) {
907         _excessDataNode->setBoolValue(false);
908         return;
909     }
910     
911     std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
912     _symbols.resize(_maxSymbols);
913     _excessDataNode->setBoolValue(true);
914 }
915
916 class OrderByZ
917 {
918 public:
919     bool operator()(SymbolInstance* a, SymbolInstance* b)
920     {
921         return a->definition->zOrder > b->definition->zOrder;
922     }
923 };
924
925 void NavDisplay::addSymbolsToScene()
926 {
927     std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
928     BOOST_FOREACH(SymbolInstance* sym, _symbols) {
929         addSymbolToScene(sym);
930     }
931 }
932
933 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
934 {    
935     _lineVertices->push_back(a);
936     _lineVertices->push_back(b);
937     _lineColors->push_back(color);
938     _lineColors->push_back(color);
939 }
940
941 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
942 {
943     osg::Vec3 p(0, rangeNm, 0.0);
944     p = degRotation(bearingDeg).preMult(p);
945     p = _projectMat.preMult(p);
946     return osg::Vec2(p.x(), p.y());
947 }
948
949 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
950 {
951     double rangeM, bearing, az2;
952     SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
953     return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
954 }
955
956 class Filter : public FGPositioned::Filter
957 {
958 public:
959     Filter(NavDisplay* nd) : _owner(nd) { }
960   
961     double minRunwayLengthFt;
962   
963     virtual bool pass(FGPositioned* aPos) const
964     {
965         if (aPos->type() == FGPositioned::FIX) {
966             string ident(aPos->ident());
967             // ignore fixes which end in digits
968             if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
969                 return false;
970             }
971         }
972
973         if (aPos->type() == FGPositioned::AIRPORT) {
974           FGAirport* apt = (FGAirport*) aPos;
975           if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
976             return false;
977           }
978         }
979       
980       // check against current rule states
981         return _owner->isPositionedShown(aPos);
982     }
983
984     virtual FGPositioned::Type minType() const {
985         return FGPositioned::AIRPORT;
986     }
987
988     virtual FGPositioned::Type maxType() const {
989         return FGPositioned::OBSTACLE;
990     }
991   
992 private:
993     NavDisplay* _owner;
994 };
995
996 void NavDisplay::findItems()
997 {
998     if (!_cachedItemsValid) {
999         Filter filt(this);
1000         filt.minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
1001         bool wasTimeLimited;
1002         _itemsInRange = FGPositioned::findClosestNPartial(_pos, _maxSymbols, _rangeNm,
1003                                                           &filt, wasTimeLimited);
1004         _cachedItemsValid = true;
1005         _cachedPos = SGVec3d::fromGeod(_pos);
1006         
1007         if (wasTimeLimited) {
1008             // re-query next frame, to load incrementally
1009             _cachedItemsValid = false;
1010         }
1011     }
1012     
1013   // sort by distance from pos, so symbol limits are accurate
1014     FGPositioned::sortByRange(_itemsInRange, _pos);
1015   
1016     BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
1017         foundPositionedItem(pos);
1018     }
1019 }
1020
1021 void NavDisplay::processRoute()
1022 {
1023     _routeSources.clear();
1024     flightgear::FlightPlan* fp = _route->flightPlan();
1025     RoutePath path(fp);
1026     int current = _route->currentIndex();
1027     
1028     for (int l=0; l<fp->numLegs(); ++l) {
1029         flightgear::FlightPlan::Leg* leg = fp->legAtIndex(l);
1030         flightgear::WayptRef wpt(leg->waypoint());
1031         _routeSources.insert(wpt->source());
1032         
1033         string_set state;
1034         state.insert("on-active-route");
1035         
1036         if (l < current) {
1037             state.insert("passed");
1038         }
1039         
1040         if (l == current) {
1041             state.insert("current-wp");
1042         }
1043         
1044         if (l > current) {
1045             state.insert("future");
1046         }
1047         
1048         if (l == (current + 1)) {
1049             state.insert("next-wp");
1050         }
1051         
1052         SymbolRuleVector rules;
1053         findRules("waypoint" , state, rules);
1054         if (rules.empty()) {
1055             return; // no rules matched, we can skip this item
1056         }
1057
1058         SGGeod g = path.positionForIndex(l);
1059         SGPropertyNode* vars = _route->wayptNodeAtIndex(l);
1060         if (!vars) {
1061           continue; // shouldn't happen, but let's guard against it
1062         }
1063       
1064         double heading;
1065         computeWayptPropsAndHeading(wpt, g, vars, heading);
1066
1067         osg::Vec2 projected = projectGeod(g);
1068         BOOST_FOREACH(SymbolRule* r, rules) {
1069             addSymbolInstance(projected, heading, r->getDefinition(), vars);
1070             
1071             if (r->getDefinition()->drawRouteLeg) {
1072                 SGGeodVec gv(path.pathForIndex(l));
1073                 if (!gv.empty()) {
1074                     osg::Vec2 pr = projectGeod(gv[0]);
1075                     for (unsigned int i=1; i<gv.size(); ++i) {
1076                         osg::Vec2 p = projectGeod(gv[i]);
1077                         addLine(pr, p, r->getDefinition()->lineColor);
1078                         pr = p;
1079                     }
1080                 }
1081             } // of leg drawing enabled
1082         } // of matching rules iteration
1083     } // of waypoints iteration
1084 }
1085
1086 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1087 {
1088     double rangeM, az2;
1089     SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1090     nd->setIntValue("radial", heading);
1091     nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1092     
1093     heading = nd->getDoubleValue("leg-bearing-true-deg");
1094 }
1095
1096 void NavDisplay::processNavRadios()
1097 {
1098     _nav1Station = processNavRadio(_navRadio1Node);
1099     _nav2Station = processNavRadio(_navRadio2Node);
1100     
1101     foundPositionedItem(_nav1Station);
1102     foundPositionedItem(_nav2Station);
1103 }
1104
1105 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1106 {
1107   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1108   FGNavRecord* nav = FGNavList::findByFreq(mhz, _pos, FGNavList::navFilter());
1109     if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1110         // station was not found
1111         return NULL;
1112     }
1113     
1114     
1115     return nav;
1116 }
1117
1118 bool NavDisplay::anyRuleForType(const string& type) const
1119 {
1120     BOOST_FOREACH(SymbolRule* r, _rules) {
1121         if (!r->enabled) {
1122             continue;
1123         }
1124     
1125         if (r->type == type) {
1126             return true;
1127         }
1128     }
1129     
1130     return false;
1131 }
1132
1133 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1134 {
1135     BOOST_FOREACH(SymbolRule* candidate, _rules) {
1136         if (!candidate->enabled || (candidate->type != type)) {
1137             continue;
1138         }
1139         
1140         if (candidate->matches(states)) {
1141             rules.push_back(candidate);
1142         }
1143     }
1144 }
1145
1146 bool NavDisplay::isPositionedShown(FGPositioned* pos)
1147 {
1148   SymbolRuleVector rules;
1149   isPositionedShownInner(pos, rules);
1150   return !rules.empty();
1151 }
1152
1153 void NavDisplay::isPositionedShownInner(FGPositioned* pos, SymbolRuleVector& rules)
1154 {
1155   string type = FGPositioned::nameForType(pos->type());
1156   boost::to_lower(type);
1157   if (!anyRuleForType(type)) {
1158     return; // not diplayed at all, we're done
1159   }
1160   
1161   string_set states;
1162   computePositionedState(pos, states);
1163   
1164   findRules(type, states, rules);
1165 }
1166
1167 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1168 {
1169     if (!pos) {
1170         return;
1171     }
1172     
1173     SymbolRuleVector rules;
1174     isPositionedShownInner(pos, rules);
1175     if (rules.empty()) {
1176       return;
1177     }
1178   
1179     SGPropertyNode_ptr vars(new SGPropertyNode);
1180     double heading;
1181     computePositionedPropsAndHeading(pos, vars, heading);
1182     
1183     osg::Vec2 projected = projectGeod(pos->geod());
1184     if (pos->type() == FGPositioned::RUNWAY) {
1185         FGRunway* rwy = (FGRunway*) pos;
1186         projected = projectGeod(rwy->threshold());
1187     }
1188     
1189     BOOST_FOREACH(SymbolRule* r, rules) {
1190         SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1191         if ((ins)&&(pos->type() == FGPositioned::RUNWAY)) {
1192             FGRunway* rwy = (FGRunway*) pos;
1193             ins->endPos = projectGeod(rwy->end());
1194         }
1195     }
1196 }
1197
1198 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1199 {
1200     nd->setStringValue("id", pos->ident());
1201     nd->setStringValue("name", pos->name());
1202     nd->setDoubleValue("elevation-ft", pos->elevation());
1203     nd->setIntValue("heading-deg", 0);
1204     heading = 0.0;
1205     
1206     switch (pos->type()) {
1207     case FGPositioned::VOR:
1208     case FGPositioned::LOC: 
1209     case FGPositioned::TACAN: {
1210         FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1211         nd->setDoubleValue("frequency-mhz", nav->get_freq());
1212         
1213         if (pos == _nav1Station) {
1214             heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1215         } else if (pos == _nav2Station) {
1216             heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1217         }
1218         
1219         nd->setIntValue("heading-deg", heading);
1220         break;
1221     }
1222
1223     case FGPositioned::AIRPORT:
1224     case FGPositioned::SEAPORT:
1225     case FGPositioned::HELIPORT:
1226         
1227         break;
1228         
1229     case FGPositioned::RUNWAY: {
1230         FGRunway* rwy = static_cast<FGRunway*>(pos);
1231         heading = rwy->headingDeg();
1232         nd->setDoubleValue("heading-deg", heading);
1233         nd->setIntValue("length-ft", rwy->lengthFt());
1234         nd->setStringValue("airport", rwy->airport()->ident());
1235         break;
1236     }
1237
1238     default:
1239         break; 
1240     }
1241 }
1242
1243 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1244 {
1245     if (_routeSources.count(pos) != 0) {
1246         states.insert("on-active-route");
1247     }
1248     
1249     flightgear::FlightPlan* fp = _route->flightPlan();
1250     switch (pos->type()) {
1251     case FGPositioned::VOR:
1252     case FGPositioned::LOC:
1253         if (pos == _nav1Station) {
1254             states.insert("tuned");
1255             states.insert("nav1");
1256         }
1257         
1258         if (pos == _nav2Station) {
1259             states.insert("tuned");
1260             states.insert("nav2");
1261         }
1262         break;
1263     
1264     case FGPositioned::AIRPORT:
1265     case FGPositioned::SEAPORT:
1266     case FGPositioned::HELIPORT:
1267         // mark alternates!
1268         // once the FMS system has some way to tell us about them, of course
1269         
1270         if (pos == fp->departureAirport()) {
1271             states.insert("departure");
1272         }
1273         
1274         if (pos == fp->destinationAirport()) {
1275             states.insert("destination");
1276         }
1277         break;
1278     
1279     case FGPositioned::RUNWAY:
1280         if (pos == fp->departureRunway()) {
1281             states.insert("departure");
1282         }
1283         
1284         if (pos == fp->destinationRunway()) {
1285             states.insert("destination");
1286         }
1287         break;
1288     
1289     case FGPositioned::OBSTACLE:
1290     #if 0    
1291         FGObstacle* obs = (FGObstacle*) pos;
1292         if (obj->isLit()) {
1293             states.insert("lit");
1294         }
1295         
1296         if (obj->getHeightAGLFt() >= 1000) {
1297             states.insert("greater-1000-ft");
1298         }
1299     #endif
1300         break;
1301     
1302     default:
1303         break;
1304     } // FGPositioned::Type switch
1305 }
1306
1307 static string mapAINodeToType(SGPropertyNode* model)
1308 {
1309   // assume all multiplayer items are aircraft for the moment. Not ideal.
1310   if (!strcmp(model->getName(), "multiplayer")) {
1311     return "ai-aircraft";
1312   }
1313   
1314   return string("ai-") + model->getName();
1315 }
1316
1317 void NavDisplay::processAI()
1318 {
1319     SGPropertyNode *ai = fgGetNode("/ai/models", true);
1320     for (int i = ai->nChildren() - 1; i >= 0; i--) {
1321         SGPropertyNode *model = ai->getChild(i);
1322         if (!model->nChildren()) {
1323             continue;
1324         }
1325         
1326     // prefix types with 'ai-', to avoid any chance of namespace collisions
1327     // with fg-positioned.
1328         string_set ss;
1329         computeAIStates(model, ss);        
1330         SymbolRuleVector rules;
1331         findRules(mapAINodeToType(model), ss, rules);
1332         if (rules.empty()) {
1333             return; // no rules matched, we can skip this item
1334         }
1335
1336         double heading = model->getDoubleValue("orientation/true-heading-deg");
1337         SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"), 
1338                                             model->getDoubleValue("position/latitude-deg"), 
1339                                             model->getDoubleValue("position/altitude-ft"));
1340     // compute some additional props
1341         int fl = (aiModelPos.getElevationFt() / 1000);
1342         model->setIntValue("flight-level", fl * 10);
1343                                             
1344         osg::Vec2 projected = projectGeod(aiModelPos);
1345         BOOST_FOREACH(SymbolRule* r, rules) {
1346             addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1347         }
1348     } // of ai models iteration
1349 }
1350
1351 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1352 {
1353     int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1354     if (threatLevel < 1)
1355       threatLevel = 0;
1356   
1357     states.insert("tcas");
1358   
1359     std::ostringstream os;
1360     os << "tcas-threat-level-" << threatLevel;
1361     states.insert(os.str());
1362
1363     double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1364     if (vspeed < -3.0) {
1365         states.insert("descending");
1366     } else if (vspeed > 3.0) {
1367         states.insert("climbing");
1368     }
1369 }
1370
1371 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1372 {
1373     if (isProjectedClipped(proj)) {
1374         return NULL;
1375     }
1376     
1377     if ((def->limitCount > 0) && (def->instanceCount >= def->limitCount)) {
1378       return NULL;
1379     }
1380   
1381     ++def->instanceCount;
1382     SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1383     _symbols.push_back(sym);
1384     return sym;
1385 }
1386
1387 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1388 {
1389     double size = _odg->size();
1390     return (projected.x() < 0.0) ||
1391         (projected.y() < 0.0) ||
1392         (projected.x() >= size) ||
1393             (projected.y() >= size);
1394 }
1395
1396 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1397 {
1398   string_set stateSet;
1399   BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1400     stateSet.insert(s);
1401   }
1402   
1403   SymbolRuleVector rules;
1404   findRules(type, stateSet, rules);
1405   if (rules.empty()) {
1406     return; // no rules matched, we can skip this item
1407   }
1408     
1409   osg::Vec2 projected = projectGeod(pos);
1410   BOOST_FOREACH(SymbolRule* r, rules) {
1411     addSymbolInstance(projected, heading, r->getDefinition(), vars);
1412   }
1413 }
1414
1415 void NavDisplay::addTestSymbols()
1416 {
1417   _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1418   
1419   SGGeod a1;
1420   double dummy;
1421   SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1422   
1423   addTestSymbol("airport", "", a1, 0.0, NULL);
1424   
1425   SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1426   
1427   addTestSymbol("vor", "", a1, 0.0, NULL);
1428   
1429   SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1430   
1431   addTestSymbol("airport", "destination", a1, 0.0, NULL);
1432   
1433   SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1434   addTestSymbol("fix", "", a1, 0.0, NULL);
1435
1436   
1437   SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);  
1438   addTestSymbol("fix", "", a1, 0.0, NULL);
1439   
1440   SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);  
1441   addTestSymbol("fix", "", a1, 0.0, NULL);
1442   
1443   SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);  
1444   addTestSymbol("fix", "", a1, 0.0, NULL);
1445 }
1446
1447 void NavDisplay::addRule(SymbolRule* r)
1448 {
1449     _rules.push_back(r);
1450 }
1451
1452 void NavDisplay::computeCustomSymbolStates(const SGPropertyNode* sym, string_set& states)
1453 {
1454   BOOST_FOREACH(SGPropertyNode* st, sym->getChildren("state")) {
1455     states.insert(st->getStringValue());
1456   }
1457 }
1458
1459 void NavDisplay::processCustomSymbols()
1460 {
1461   for (int i = _customSymbols->nChildren() - 1; i >= 0; i--) {
1462     SGPropertyNode *symNode = _customSymbols->getChild(i);
1463     if (!symNode->nChildren()) {
1464       continue;
1465     }
1466     string_set ss;
1467     computeCustomSymbolStates(symNode, ss);
1468     SymbolRuleVector rules;
1469     findRules(symNode->getName(), ss, rules);
1470     if (rules.empty()) {
1471       return; // no rules matched, we can skip this item
1472     }
1473     
1474     double heading = symNode->getDoubleValue("true-heading-deg", 0.0);
1475     SGGeod pos = SGGeod::fromDegFt(symNode->getDoubleValue("longitude-deg"),
1476                                           symNode->getDoubleValue("latitude-deg"),
1477                                           symNode->getDoubleValue("altitude-ft"));
1478  
1479     
1480     osg::Vec2 projected = projectGeod(pos);
1481     BOOST_FOREACH(SymbolRule* r, rules) {
1482       addSymbolInstance(projected, heading, r->getDefinition(), symNode);
1483     }
1484   } // of custom symbols iteration
1485 }
1486
1487