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