1 // navigation display texture
3 // Written by James Turner, forked from wxradar code
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.
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.
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.
26 #include "NavDisplay.hxx"
29 #include <boost/foreach.hpp>
33 #include <osg/Geometry>
34 #include <osg/Matrixf>
35 #include <osg/PrimitiveSet>
36 #include <osg/StateSet>
37 #include <osg/LineWidth>
38 #include <osg/Version>
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>
49 #include <iostream> // for cout, endl
51 using std::stringstream;
53 using std::setprecision;
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>
71 #include "instrument_mgr.hxx"
72 #include "od_gauge.hxx"
74 static const char *DEFAULT_FONT = "typewriter.txf";
77 osg::Matrixf degRotation(float angle)
79 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
82 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
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());
92 static osgText::Text::AlignmentType readAlignment(const std::string& t)
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;
120 return osgText::Text::BASE_LINE;
123 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
126 static char buf[512];
127 if (format.find('d') != string::npos) {
128 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
132 if (format.find('s') != string::npos) {
133 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
137 // assume it's a double/float
138 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
142 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
144 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
145 return osg::Vec2(r.x(), r.y());
148 ///////////////////////////////////////////////////////////////////
157 bool initFromNode(SGPropertyNode* node)
159 type = node->getStringValue("type");
160 SGPropertyNode* enableNode = node->getChild("enable");
162 enable = sgReadCondition(fgGetNode("/"), enableNode);
166 while (node->hasChild("state", n)) {
167 string m = node->getChild("state", n++)->getStringValue();
169 excluded_states.insert(m.substr(1));
171 required_states.insert(m);
173 } // of matches parsing
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);
180 double texSize = node->getFloatValue("texture-size", 1.0);
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;
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);
193 if (node->hasChild("text")) {
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);
202 drawLine = node->getBoolValue("draw-line", false);
203 lineColor = readColor(node->getChild("line-color"), color);
204 drawRouteLeg = node->getBoolValue("draw-line", false);
206 stretchSymbol = node->getBoolValue("stretch-symbol", false);
208 stretchY2 = node->getFloatValue("y2");
209 stretchY3 = node->getFloatValue("y3");
210 stretchV2 = node->getFloatValue("v2");
211 stretchV3 = node->getFloatValue("v3");
218 bool enabled; // cached enabled state
221 string_set required_states;
222 string_set excluded_states;
230 bool rotateToHeading;
231 bool roundPos; ///< should position be rounded to integer values
234 osg::Vec2 textOffset;
235 osgText::Text::AlignmentType alignment;
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.
246 double stretchY2, stretchY3;
247 double stretchV2, stretchV3;
251 bool matches(const string_set& states) const
253 string_set::const_iterator it = states.begin(),
255 for (; it != end; ++it) {
256 if (!required_states.empty() && (required_states.count(*it) == 0)) {
257 // required state not matched
261 if (excluded_states.count(*it) > 0) {
262 // excluded state matched
265 } // of applicable states iteration
267 return true; // matches!
274 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
281 osg::Vec2 pos; // projected position
284 SymbolDef* definition;
285 SGPropertyNode_ptr props;
289 assert(definition->hasText);
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));
302 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
304 size_t endReplacement = definition->textTemplate.find('}', pos+1);
305 if (endReplacement <= pos) {
306 return "bad replacement";
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));
316 string format = spec.substr(colonPos + 1);
317 string prop = spec.substr(0, colonPos);
318 r.append(formatPropertyValue(props->getNode(prop), format));
321 lastPos = endReplacement + 1;
328 //////////////////////////////////////////////////////////////////
330 NavDisplay::NavDisplay(SGPropertyNode *node) :
331 _name(node->getStringValue("name", "nd")),
332 _num(node->getIntValue("number", 0)),
334 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
343 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
344 _font_node = _Instrument->getNode("font", true);
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);
356 SGPropertyNode* symbolsNode = node->getNode("symbols");
357 SGPropertyNode* symbol;
359 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
360 SymbolDef* def = new SymbolDef;
361 if (!def->initFromNode(symbol)) {
366 _rules.push_back(def);
367 } // of symbol definition parsing
371 NavDisplay::~NavDisplay()
379 _serviceable_node = _Instrument->getNode("serviceable", true);
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);
386 string path = _Instrument->getStringValue("symbol-texture-path",
387 "Aircraft/Instruments/Textures/nd-symbols.png");
388 SGPath tpath = globals->resolve_aircraft_path(path);
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);
393 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
394 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
395 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
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);
402 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
404 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
405 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
407 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
408 _excessDataNode->setBoolValue(false);
410 // OSG geometry setup
411 _radarGeode = new osg::Geode;
413 _geom = new osg::Geometry;
414 _geom->setUseDisplayList(false);
416 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
417 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
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);
429 _quadColors = new osg::Vec4Array;
430 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
431 _geom->setColorArray(_quadColors);
433 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
434 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
435 _geom->addPrimitiveSet(_symbolPrimSet);
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);
441 // Texture in the 2D panel system
442 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
444 _lineGeometry = new osg::Geometry;
445 _lineGeometry->setUseDisplayList(false);
446 stateSet = _lineGeometry->getOrCreateStateSet();
447 osg::LineWidth *lw = new osg::LineWidth();
449 stateSet->setAttribute(lw);
451 _lineVertices = new osg::Vec2Array;
452 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
453 _lineVertices->reserve(128 * 4);
454 _lineGeometry->setVertexArray(_lineVertices);
457 _lineColors = new osg::Vec4Array;
458 _lineColors->setDataVariance(osg::Object::DYNAMIC);
459 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
460 _lineGeometry->setColorArray(_lineColors);
462 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
463 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
464 _lineGeometry->addPrimitiveSet(_linePrimSet);
466 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
467 osg::Vec3f(256.0f, 256.0f, 0.0f)));
469 _radarGeode->addDrawable(_lineGeometry);
471 _textGeode = new osg::Geode;
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());
484 NavDisplay::update (double delta_time_sec)
486 if (!fgGetBool("sim/sceneryloaded", false)) {
490 if (!_odg || !_serviceable_node->getBoolValue()) {
491 _Instrument->setStringValue("status", "");
495 _time += delta_time_sec;
496 if (_time < _updateInterval){
499 _time -= _updateInterval;
501 _rangeNm = _Instrument->getFloatValue("range", 40.0);
502 if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
503 _view_heading = fgGetDouble("/orientation/heading-deg");
505 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
508 _scale = _odg->size() / _rangeNm;
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);
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;
520 _pos = SGGeod::fromDegFt(_user_lon_node->getDoubleValue(),
521 _user_lat_node->getDoubleValue(),
522 _user_alt_node->getDoubleValue());
525 _lineVertices->clear();
526 _lineColors->clear();
528 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
530 BOOST_FOREACH(SymbolDef* def, _rules) {
532 def->enabled = def->enable->test();
542 limitDisplayedSymbols();
545 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
546 _symbolPrimSet->dirty();
547 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
548 _linePrimSet->dirty();
553 NavDisplay::updateFont()
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);
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);
566 if (path[0] != '/') {
567 tpath = globals->get_fg_root();
568 tpath.append("Fonts");
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());
579 _font->setMinFilterHint(osg::Texture::NEAREST);
580 _font->setMagFilterHint(osg::Texture::NEAREST);
581 _font->setGlyphImageMargin(0);
582 _font->setGlyphImageMarginRatio(0);
586 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
588 SymbolDef* def = sym->definition;
592 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
594 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
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);
603 osg::Vec2 pos = sym->pos;
605 pos = osg::Vec2((int) pos.x(), (int) pos.y());
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()));
613 for (int i=0; i<4; ++i) {
614 _vertices->push_back(verts[i] + pos);
615 _quadColors->push_back(def->color);
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);
625 osg::Matrixf m(degRotation(sym->headingDeg));
626 for (int i=0; i<4; ++i) {
627 stretchVerts[i] = mult(stretchVerts[i], m);
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);
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()));
641 for (int i=0; i<4; ++i) {
642 _quadColors->push_back(def->color);
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);
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));
658 addLine(sym->pos, sym->endPos, def->lineColor);
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());
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);
681 class OrderByPriority
684 bool operator()(SymbolInstance* a, SymbolInstance* b)
686 return a->definition->priority > b->definition->priority;
690 void NavDisplay::limitDisplayedSymbols()
692 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
693 if (_symbols.size() <= maxSymbols) {
694 _excessDataNode->setBoolValue(false);
698 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
699 _symbols.resize(maxSymbols);
700 _excessDataNode->setBoolValue(true);
706 bool operator()(SymbolInstance* a, SymbolInstance* b)
708 return a->definition->zOrder > b->definition->zOrder;
712 void NavDisplay::addSymbolsToScene()
714 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
715 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
716 addSymbolToScene(sym);
720 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
722 _lineVertices->push_back(a);
723 _lineVertices->push_back(b);
724 _lineColors->push_back(color);
725 _lineColors->push_back(color);
728 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
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());
736 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
738 double rangeM, bearing, az2;
739 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
740 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
743 class Filter : public FGPositioned::Filter
746 virtual bool pass(FGPositioned* aPos) const
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])) {
759 virtual FGPositioned::Type minType() const {
760 return FGPositioned::AIRPORT;
763 virtual FGPositioned::Type maxType() const {
764 return FGPositioned::OBSTACLE;
768 void NavDisplay::findItems()
771 FGPositioned::List items =
772 FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
774 FGPositioned::List::const_iterator it;
775 for (it = items.begin(); it != items.end(); ++it) {
776 foundPositionedItem(*it);
780 void NavDisplay::processRoute()
782 _routeSources.clear();
783 RoutePath path(_route->waypts());
784 int current = _route->currentIndex();
786 for (int w=0; w<_route->numWaypts(); ++w) {
787 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
788 _routeSources.insert(wpt->source());
791 state.insert("on-active-route");
794 state.insert("passed");
798 state.insert("current-wp");
802 state.insert("future");
805 if (w == (current + 1)) {
806 state.insert("next-wp");
809 SymbolDefVector rules;
810 findRules("waypoint" , state, rules);
812 return; // no rules matched, we can skip this item
815 SGGeod g = path.positionForIndex(w);
816 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
818 computeWayptPropsAndHeading(wpt, g, vars, heading);
820 osg::Vec2 projected = projectGeod(g);
821 BOOST_FOREACH(SymbolDef* r, rules) {
822 addSymbolInstance(projected, heading, r, vars);
824 if (r->drawRouteLeg) {
825 SGGeodVec gv(path.pathForIndex(w));
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);
834 } // of leg drawing enabled
835 } // of matching rules iteration
836 } // of waypoints iteration
839 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
842 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
843 nd->setIntValue("radial", heading);
844 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
846 heading = nd->getDoubleValue("leg-bearing-true-deg");
849 void NavDisplay::processNavRadios()
851 _nav1Station = processNavRadio(_navRadio1Node);
852 _nav2Station = processNavRadio(_navRadio2Node);
854 foundPositionedItem(_nav1Station);
855 foundPositionedItem(_nav2Station);
858 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
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
871 bool NavDisplay::anyRuleForType(const string& type) const
873 BOOST_FOREACH(SymbolDef* r, _rules) {
878 if (r->type == type) {
886 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
888 BOOST_FOREACH(SymbolDef* r, _rules) {
889 if (!r->enabled || (r->type != type)) {
893 if (r->matches(states)) {
896 } // of rules iteration
901 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
903 BOOST_FOREACH(SymbolDef* candidate, _rules) {
904 if (!candidate->enabled || (candidate->type != type)) {
908 if (candidate->matches(states)) {
909 rules.push_back(candidate);
914 void NavDisplay::foundPositionedItem(FGPositioned* pos)
920 string type = FGPositioned::nameForType(pos->type());
921 if (!anyRuleForType(type)) {
922 return; // not diplayed at all, we're done
926 computePositionedState(pos, states);
928 SymbolDefVector rules;
929 findRules(type, states, rules);
931 return; // no rules matched, we can skip this item
934 SGPropertyNode_ptr vars(new SGPropertyNode);
936 computePositionedPropsAndHeading(pos, vars, heading);
938 osg::Vec2 projected = projectGeod(pos->geod());
939 BOOST_FOREACH(SymbolDef* r, rules) {
940 addSymbolInstance(projected, heading, r, vars);
944 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
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);
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());
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"));
966 case FGPositioned::AIRPORT:
967 case FGPositioned::SEAPORT:
968 case FGPositioned::HELIPORT:
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());
985 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
987 if (_routeSources.count(pos) != 0) {
988 states.insert("on-active-route");
991 switch (pos->type()) {
992 case FGPositioned::VOR:
993 case FGPositioned::LOC:
994 if (pos == _nav1Station) {
995 states.insert("tuned");
996 states.insert("nav1");
999 if (pos == _nav2Station) {
1000 states.insert("tuned");
1001 states.insert("nav2");
1005 case FGPositioned::AIRPORT:
1006 case FGPositioned::SEAPORT:
1007 case FGPositioned::HELIPORT:
1009 // once the FMS system has some way to tell us about them, of course
1011 if (pos == _route->departureAirport()) {
1012 states.insert("departure");
1015 if (pos == _route->destinationAirport()) {
1016 states.insert("destination");
1020 case FGPositioned::RUNWAY:
1021 if (pos == _route->departureRunway()) {
1022 states.insert("departure");
1025 if (pos == _route->destinationRunway()) {
1026 states.insert("destination");
1030 case FGPositioned::OBSTACLE:
1032 FGObstacle* obs = (FGObstacle*) pos;
1034 states.insert("lit");
1037 if (obj->getHeightAGLFt() >= 1000) {
1038 states.insert("greater-1000-ft");
1045 } // FGPositioned::Type switch
1048 void NavDisplay::processAI()
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()) {
1057 // prefix types with 'ai-', to avoid any chance of namespace collisions
1058 // with fg-positioned.
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
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);
1075 osg::Vec2 projected = projectGeod(aiModelPos);
1076 BOOST_FOREACH(SymbolDef* r, rules) {
1077 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1079 } // of ai models iteration
1082 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
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));
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");
1098 void NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1100 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1101 _symbols.push_back(sym);