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