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