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 ///////////////////////////////////////////////////////////////////
153 bool initFromNode(SGPropertyNode* node)
155 type = node->getStringValue("type");
156 enable = sgReadCondition(fgGetNode("/"), node->getChild("enable"));
158 while (node->hasChild("state", n)) {
159 string m = node->getChild("state", n++)->getStringValue();
161 excluded_states.insert(m.substr(1));
163 required_states.insert(m);
165 } // of matches parsing
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);
172 double texSize = node->getFloatValue("texture-size", 1.0);
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;
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);
185 if (node->hasChild("text")) {
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);
194 drawLine = node->getBoolValue("draw-line", false);
195 lineColor = readColor(node->getChild("line-color"), color);
196 drawRouteLeg = node->getBoolValue("draw-line", false);
198 stretchSymbol = node->getBoolValue("stretch-symbol", false);
200 stretchY2 = node->getFloatValue("y2");
201 stretchY3 = node->getFloatValue("y3");
202 stretchV2 = node->getFloatValue("v2");
203 stretchV3 = node->getFloatValue("v3");
210 bool enabled; // cached enabled state
213 string_set required_states;
214 string_set excluded_states;
222 bool rotateToHeading;
223 bool roundPos; ///< should position be rounded to integer values
226 osg::Vec2 textOffset;
227 osgText::Text::AlignmentType alignment;
233 // symbol stretching creates three quads (instead of one) - a start,
234 // middle and end quad, positioned along the line of the symbol.
235 // X (and U) axis values determined by the values above, so we only need
236 // to define the Y (and V) values to build the other quads.
238 double stretchY2, stretchY3;
239 double stretchV2, stretchV3;
243 bool matches(const string_set& states) const
245 string_set::const_iterator it = states.begin(),
247 for (; it != end; ++it) {
248 if (required_states.count(*it) == 0) {
249 // required state not matched
253 if (excluded_states.count(*it) > 0) {
254 // excluded state matched
257 } // of applicable states iteration
259 return true; // matches!
266 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
273 osg::Vec2 pos; // projected position
276 SymbolDef* definition;
277 SGPropertyNode_ptr props;
281 assert(definition->hasText);
287 for (; pos < definition->textTemplate.size();) {
288 pos = definition->textTemplate.find('{', pos);
289 if (pos == string::npos) { // no more replacements
290 r.append(definition->textTemplate.substr(lastPos));
294 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
296 size_t endReplacement = definition->textTemplate.find('}', pos+1);
297 if (endReplacement <= pos) {
298 return "bad replacement";
301 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
302 // look for formatter in spec
303 size_t colonPos = spec.find(':');
304 if (colonPos == string::npos) {
305 // simple replacement
306 r.append(props->getStringValue(spec));
308 string format = spec.substr(colonPos + 1);
309 string prop = spec.substr(0, colonPos);
310 r.append(formatPropertyValue(props->getNode(prop), format));
313 lastPos = endReplacement + 1;
320 //////////////////////////////////////////////////////////////////
322 NavDisplay::NavDisplay(SGPropertyNode *node) :
323 _name(node->getStringValue("name", "nd")),
324 _num(node->getIntValue("number", 0)),
326 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
335 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
336 _font_node = _Instrument->getNode("font", true);
338 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
339 INITFONT("name", DEFAULT_FONT, String);
340 INITFONT("size", 8, Float);
341 INITFONT("line-spacing", 0.25, Float);
342 INITFONT("color/red", 0, Float);
343 INITFONT("color/green", 0.8, Float);
344 INITFONT("color/blue", 0, Float);
345 INITFONT("color/alpha", 1, Float);
348 SGPropertyNode* symbolsNode = node->getNode("symbols");
349 SGPropertyNode* symbol;
351 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
352 SymbolDef* def = new SymbolDef;
353 if (!def->initFromNode(symbol)) {
358 _rules.push_back(def);
359 } // of symbol definition parsing
363 NavDisplay::~NavDisplay()
371 _serviceable_node = _Instrument->getNode("serviceable", true);
373 // texture name to use in 2D and 3D instruments
374 _texture_path = _Instrument->getStringValue("radar-texture-path",
375 "Aircraft/Instruments/Textures/od_wxradar.rgb");
376 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
378 string path = _Instrument->getStringValue("symbol-texture-path",
379 "Aircraft/Instruments/Textures/nd-symbols.png");
380 SGPath tpath = globals->resolve_aircraft_path(path);
382 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
383 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
385 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
386 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
387 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
390 _user_lat_node = fgGetNode("/position/latitude-deg", true);
391 _user_lon_node = fgGetNode("/position/longitude-deg", true);
392 _user_alt_node = fgGetNode("/position/altitude-ft", true);
394 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
396 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
397 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
399 // OSG geometry setup
400 _radarGeode = new osg::Geode;
402 _geom = new osg::Geometry;
403 _geom->setUseDisplayList(false);
405 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
406 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
408 // Initially allocate space for 128 quads
409 _vertices = new osg::Vec2Array;
410 _vertices->setDataVariance(osg::Object::DYNAMIC);
411 _vertices->reserve(128 * 4);
412 _geom->setVertexArray(_vertices);
413 _texCoords = new osg::Vec2Array;
414 _texCoords->setDataVariance(osg::Object::DYNAMIC);
415 _texCoords->reserve(128 * 4);
416 _geom->setTexCoordArray(0, _texCoords);
418 _quadColors = new osg::Vec4Array;
419 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
420 _geom->setColorArray(_quadColors);
422 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
423 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
424 _geom->addPrimitiveSet(_symbolPrimSet);
426 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
427 osg::Vec3f(256.0f, 256.0f, 0.0f)));
428 _radarGeode->addDrawable(_geom);
430 // Texture in the 2D panel system
431 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
433 _lineGeometry = new osg::Geometry;
434 _lineGeometry->setUseDisplayList(false);
435 stateSet = _lineGeometry->getOrCreateStateSet();
436 osg::LineWidth *lw = new osg::LineWidth();
438 stateSet->setAttribute(lw);
440 _lineVertices = new osg::Vec2Array;
441 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
442 _lineVertices->reserve(128 * 4);
443 _lineGeometry->setVertexArray(_lineVertices);
446 _lineColors = new osg::Vec4Array;
447 _lineColors->setDataVariance(osg::Object::DYNAMIC);
448 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
449 _lineGeometry->setColorArray(_lineColors);
451 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
452 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
453 _lineGeometry->addPrimitiveSet(_linePrimSet);
455 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
456 osg::Vec3f(256.0f, 256.0f, 0.0f)));
458 _radarGeode->addDrawable(_lineGeometry);
460 _textGeode = new osg::Geode;
462 osg::Camera *camera = _odg->getCamera();
463 camera->addChild(_radarGeode.get());
464 camera->addChild(_textGeode.get());
465 osg::Texture2D* tex = _odg->getTexture();
466 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
467 0, tex->getTextureHeight());
473 NavDisplay::update (double delta_time_sec)
475 if (!fgGetBool("sim/sceneryloaded", false)) {
479 if (!_odg || !_serviceable_node->getBoolValue()) {
480 _Instrument->setStringValue("status", "");
484 _time += delta_time_sec;
485 if (_time < _updateInterval){
488 _time -= _updateInterval;
490 _rangeNm = _Instrument->getFloatValue("range", 40.0);
491 if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
492 _view_heading = fgGetDouble("/orientation/heading-deg");
494 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
497 _scale = _odg->size() / _rangeNm;
499 double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
500 double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
501 _centerTrans = osg::Matrixf::translate(xCenterFrac * _odg->size(),
502 yCenterFrac * _odg->size(), 0.0);
504 // scale from nm to display units, rotate so aircraft heading is up
505 // (as opposed to north), and compensate for centering
506 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
507 degRotation(-_view_heading) * _centerTrans;
509 _pos = SGGeod::fromDegFt(_user_lon_node->getDoubleValue(),
510 _user_lat_node->getDoubleValue(),
511 _user_alt_node->getDoubleValue());
514 _lineVertices->clear();
515 _lineColors->clear();
517 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
519 BOOST_FOREACH(SymbolDef* def, _rules) {
520 def->enabled = def->enable->test();
527 limitDisplayedSymbols();
530 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
531 _symbolPrimSet->dirty();
532 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
533 _linePrimSet->dirty();
538 NavDisplay::updateFont()
540 float red = _font_node->getFloatValue("color/red");
541 float green = _font_node->getFloatValue("color/green");
542 float blue = _font_node->getFloatValue("color/blue");
543 float alpha = _font_node->getFloatValue("color/alpha");
544 _font_color.set(red, green, blue, alpha);
546 _font_size = _font_node->getFloatValue("size");
547 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
548 string path = _font_node->getStringValue("name", DEFAULT_FONT);
551 if (path[0] != '/') {
552 tpath = globals->get_fg_root();
553 tpath.append("Fonts");
559 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
560 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
564 _font->setMinFilterHint(osg::Texture::NEAREST);
565 _font->setMagFilterHint(osg::Texture::NEAREST);
566 _font->setGlyphImageMargin(0);
567 _font->setGlyphImageMarginRatio(0);
571 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
573 SymbolDef* def = sym->definition;
577 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
579 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
581 if (def->rotateToHeading) {
582 osg::Matrixf m(degRotation(sym->headingDeg));
583 for (int i=0; i<4; ++i) {
584 verts[i] = mult(verts[i], m);
588 osg::Vec2 pos = sym->pos;
590 pos = osg::Vec2((int) pos.x(), (int) pos.y());
593 _texCoords->push_back(def->uv0);
594 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
595 _texCoords->push_back(def->uv1);
596 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
598 for (int i=0; i<4; ++i) {
599 _vertices->push_back(verts[i] + pos);
600 _quadColors->push_back(def->color);
603 if (def->stretchSymbol) {
604 osg::Vec2 stretchVerts[4];
605 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
606 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
607 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
608 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
610 osg::Matrixf m(degRotation(sym->headingDeg));
611 for (int i=0; i<4; ++i) {
612 stretchVerts[i] = mult(stretchVerts[i], m);
616 _vertices->push_back(verts[2] + pos);
617 _vertices->push_back(stretchVerts[1] + sym->endPos);
618 _vertices->push_back(stretchVerts[0] + sym->endPos);
619 _vertices->push_back(verts[3] + pos);
621 _texCoords->push_back(def->uv1);
622 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
623 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
624 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
626 for (int i=0; i<4; ++i) {
627 _quadColors->push_back(def->color);
630 // quad three, for the end portion
631 for (int i=0; i<4; ++i) {
632 _vertices->push_back(stretchVerts[i] + sym->endPos);
633 _quadColors->push_back(def->color);
636 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
637 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
638 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
639 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
643 addLine(sym->pos, sym->endPos, def->lineColor);
650 osgText::Text* t = new osgText::Text;
651 t->setFont(_font.get());
652 t->setFontResolution(12, 12);
653 t->setCharacterSize(_font_size);
654 t->setLineSpacing(_font_spacing);
655 t->setColor(def->textColor);
656 t->setAlignment(def->alignment);
657 t->setText(sym->text());
660 osg::Vec2 textPos = def->textOffset + pos;
661 // ensure we use ints here, or text visual quality goes bad
662 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
663 _textGeode->addDrawable(t);
666 class OrderByPriority
669 bool operator()(SymbolInstance* a, SymbolInstance* b)
671 return a->definition->priority > b->definition->priority;
675 void NavDisplay::limitDisplayedSymbols()
677 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols");
678 if (_symbols.size() <= maxSymbols) {
679 _excessDataNode->setBoolValue(false);
683 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
684 _symbols.resize(maxSymbols);
685 _excessDataNode->setBoolValue(true);
691 bool operator()(SymbolInstance* a, SymbolInstance* b)
693 return a->definition->zOrder > b->definition->zOrder;
697 void NavDisplay::addSymbolsToScene()
699 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
700 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
701 addSymbolToScene(sym);
705 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
707 _lineVertices->push_back(a);
708 _lineVertices->push_back(b);
709 _lineColors->push_back(color);
710 _lineColors->push_back(color);
713 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
715 osg::Vec3 p(0, rangeNm, 0.0);
716 p = degRotation(bearingDeg).preMult(p);
717 p = _projectMat.preMult(p);
718 return osg::Vec2(p.x(), p.y());
721 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
723 double rangeM, bearing, az2;
724 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
725 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
728 class Filter : public FGPositioned::Filter
731 virtual bool pass(FGPositioned* aPos) const
733 if (aPos->type() == FGPositioned::FIX) {
734 string ident(aPos->ident());
735 // ignore fixes which end in digits
736 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
744 virtual FGPositioned::Type minType() const {
745 return FGPositioned::AIRPORT;
748 virtual FGPositioned::Type maxType() const {
749 return FGPositioned::OBSTACLE;
753 void NavDisplay::findItems()
756 FGPositioned::List items =
757 FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
759 FGPositioned::List::const_iterator it;
760 for (it = items.begin(); it != items.end(); ++it) {
761 foundPositionedItem(*it);
765 void NavDisplay::processRoute()
767 _routeSources.clear();
768 RoutePath path(_route->waypts());
769 int current = _route->currentIndex();
771 for (int w=0; w<_route->numWaypts(); ++w) {
772 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
773 _routeSources.insert(wpt->source());
776 state.insert("on-active-route");
779 state.insert("passed");
783 state.insert("current-wp");
787 state.insert("future");
790 if (w == (current + 1)) {
791 state.insert("next-wp");
794 SymbolDefVector rules;
795 findRules(wpt->type() , state, rules);
797 return; // no rules matched, we can skip this item
800 SGGeod g = path.positionForIndex(w);
801 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
803 computeWayptPropsAndHeading(wpt, g, vars, heading);
805 osg::Vec2 projected = projectGeod(g);
806 BOOST_FOREACH(SymbolDef* r, rules) {
807 addSymbolInstance(projected, heading, r, vars);
809 if (r->drawRouteLeg) {
810 SGGeodVec gv(path.pathForIndex(w));
812 osg::Vec2 pr = projectGeod(gv[0]);
813 for (unsigned int i=1; i<gv.size(); ++i) {
814 osg::Vec2 p = projectGeod(gv[i]);
815 addLine(pr, p, r->lineColor);
819 } // of leg drawing enabled
820 } // of matching rules iteration
821 } // of waypoints iteration
824 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
827 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
828 nd->setIntValue("radial", heading);
829 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
831 heading = nd->getDoubleValue("leg-bearing-true-deg");
834 void NavDisplay::processNavRadios()
836 _nav1Station = processNavRadio(_navRadio1Node);
837 _nav2Station = processNavRadio(_navRadio2Node);
839 foundPositionedItem(_nav1Station);
840 foundPositionedItem(_nav2Station);
843 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
845 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
846 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
847 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
848 // station was not found
856 bool NavDisplay::anyRuleForType(const string& type) const
858 BOOST_FOREACH(SymbolDef* r, _rules) {
863 if (r->type == type) {
871 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
873 BOOST_FOREACH(SymbolDef* r, _rules) {
874 if (!r->enabled || (r->type != type)) {
878 if (r->matches(states)) {
881 } // of rules iteration
886 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
888 BOOST_FOREACH(SymbolDef* candidate, _rules) {
889 if (!candidate->enabled) {
893 if (candidate->matches(states)) {
894 rules.push_back(candidate);
899 void NavDisplay::foundPositionedItem(FGPositioned* pos)
905 string type = FGPositioned::nameForType(pos->type());
906 if (!anyRuleForType(type)) {
907 return; // not diplayed at all, we're done
911 computePositionedState(pos, states);
913 SymbolDefVector rules;
914 findRules(type, states, rules);
916 return; // no rules matched, we can skip this item
919 SGPropertyNode_ptr vars(new SGPropertyNode);
921 computePositionedPropsAndHeading(pos, vars, heading);
923 osg::Vec2 projected = projectGeod(pos->geod());
924 BOOST_FOREACH(SymbolDef* r, rules) {
925 addSymbolInstance(projected, heading, r, vars);
929 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
931 nd->setStringValue("id", pos->ident());
932 nd->setStringValue("name", pos->name());
933 nd->setDoubleValue("elevation-ft", pos->elevation());
934 nd->setIntValue("heading-deg", 0);
936 switch (pos->type()) {
937 case FGPositioned::VOR:
938 case FGPositioned::LOC: {
939 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
940 nd->setDoubleValue("frequency-mhz", nav->get_freq());
942 if (pos == _nav1Station) {
943 nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
944 } else if (pos == _nav2Station) {
945 nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
951 case FGPositioned::AIRPORT:
952 case FGPositioned::SEAPORT:
953 case FGPositioned::HELIPORT:
957 case FGPositioned::RUNWAY: {
958 FGRunway* rwy = static_cast<FGRunway*>(pos);
959 nd->setDoubleValue("heading-deg", rwy->headingDeg());
960 nd->setIntValue("length-ft", rwy->lengthFt());
961 nd->setStringValue("airport", rwy->airport()->ident());
970 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
972 if (_routeSources.count(pos) != 0) {
973 states.insert("on-active-route");
976 switch (pos->type()) {
977 case FGPositioned::VOR:
978 case FGPositioned::LOC:
979 if (pos == _nav1Station) {
980 states.insert("tuned");
981 states.insert("nav1");
984 if (pos == _nav2Station) {
985 states.insert("tuned");
986 states.insert("nav2");
990 case FGPositioned::AIRPORT:
991 case FGPositioned::SEAPORT:
992 case FGPositioned::HELIPORT:
994 // once the FMS system has some way to tell us about them, of course
996 if (pos == _route->departureAirport()) {
997 states.insert("departure");
1000 if (pos == _route->destinationAirport()) {
1001 states.insert("destination");
1005 case FGPositioned::RUNWAY:
1006 if (pos == _route->departureRunway()) {
1007 states.insert("departure");
1010 if (pos == _route->destinationRunway()) {
1011 states.insert("destination");
1015 case FGPositioned::OBSTACLE:
1017 FGObstacle* obs = (FGObstacle*) pos;
1019 states.insert("lit");
1022 if (obj->getHeightAGLFt() >= 1000) {
1023 states.insert("greater-1000-ft");
1030 } // FGPositioned::Type switch
1033 void NavDisplay::processAI()
1035 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1036 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1037 SGPropertyNode *model = ai->getChild(i);
1038 if (!model->nChildren()) {
1042 // prefix types with 'ai-', to avoid any chance of namespace collisions
1043 // with fg-positioned.
1045 computeAIStates(model, ss);
1046 SymbolDefVector rules;
1047 findRules(string("ai-") + model->getName(), ss, rules);
1048 if (rules.empty()) {
1049 return; // no rules matched, we can skip this item
1052 double heading = model->getDoubleValue("orientation/true-heading-deg");
1053 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1054 model->getDoubleValue("position/latitude-deg"),
1055 model->getDoubleValue("position/altitude-ft"));
1056 // compute some additional props
1057 int fl = (aiModelPos.getElevationFt() / 1000);
1058 model->setIntValue("flight-level", fl * 10);
1060 osg::Vec2 projected = projectGeod(aiModelPos);
1061 BOOST_FOREACH(SymbolDef* r, rules) {
1062 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1064 } // of ai models iteration
1067 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1069 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1070 if (threatLevel >= 0) {
1071 states.insert("tcas");
1072 // states.insert("tcas-threat-level-" + itoa(threatLevel));
1075 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1076 if (vspeed < -3.0) {
1077 states.insert("descending");
1078 } else if (vspeed > 3.0) {
1079 states.insert("climbing");
1083 void NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1085 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1086 _symbols.push_back(sym);