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/misc/strutils.hxx>
46 #include <simgear/math/sg_geodesy.hxx>
50 #include <iostream> // for cout, endl
52 using std::stringstream;
54 using std::setprecision;
61 #include <Main/fg_props.hxx>
62 #include <Main/globals.hxx>
63 #include <Cockpit/panel.hxx>
64 #include <Navaids/routePath.hxx>
65 #include <Autopilot/route_mgr.hxx>
66 #include <Navaids/navrecord.hxx>
67 #include <Navaids/navlist.hxx>
68 #include <Navaids/fix.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/runways.hxx>
72 #include "instrument_mgr.hxx"
73 #include "od_gauge.hxx"
75 static const char *DEFAULT_FONT = "typewriter.txf";
78 osg::Matrixf degRotation(float angle)
80 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
83 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
86 result.r() = colorNode->getDoubleValue("red", c.r());
87 result.g() = colorNode->getDoubleValue("green", c.g());
88 result.b() = colorNode->getDoubleValue("blue", c.b());
89 result.a() = colorNode->getDoubleValue("alpha", c.a());
93 static osgText::Text::AlignmentType readAlignment(const std::string& t)
95 if (t == "left-top") {
96 return osgText::Text::LEFT_TOP;
97 } else if (t == "left-center") {
98 return osgText::Text::LEFT_CENTER;
99 } else if (t == "left-bottom") {
100 return osgText::Text::LEFT_BOTTOM;
101 } else if (t == "center-top") {
102 return osgText::Text::CENTER_TOP;
103 } else if (t == "center-center") {
104 return osgText::Text::CENTER_CENTER;
105 } else if (t == "center-bottom") {
106 return osgText::Text::CENTER_BOTTOM;
107 } else if (t == "right-top") {
108 return osgText::Text::RIGHT_TOP;
109 } else if (t == "right-center") {
110 return osgText::Text::RIGHT_CENTER;
111 } else if (t == "right-bottom") {
112 return osgText::Text::RIGHT_BOTTOM;
113 } else if (t == "left-baseline") {
114 return osgText::Text::LEFT_BASE_LINE;
115 } else if (t == "center-baseline") {
116 return osgText::Text::CENTER_BASE_LINE;
117 } else if (t == "right-baseline") {
118 return osgText::Text::RIGHT_BASE_LINE;
121 return osgText::Text::BASE_LINE;
124 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
127 static char buf[512];
128 if (format.find('d') != string::npos) {
129 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
133 if (format.find('s') != string::npos) {
134 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
138 // assume it's a double/float
139 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
143 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
145 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
146 return osg::Vec2(r.x(), r.y());
149 class NavDisplay::CacheListener : public SGPropertyChangeListener
152 CacheListener(NavDisplay *nd) :
156 virtual void valueChanged (SGPropertyNode * prop)
158 _nd->invalidatePositionedCache();
159 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache");
165 ///////////////////////////////////////////////////////////////////
174 bool initFromNode(SGPropertyNode* node)
176 type = node->getStringValue("type");
177 SGPropertyNode* enableNode = node->getChild("enable");
179 enable = sgReadCondition(fgGetNode("/"), enableNode);
183 while (node->hasChild("state", n)) {
184 string m = node->getChild("state", n++)->getStringValue();
186 excluded_states.insert(m.substr(1));
188 required_states.insert(m);
190 } // of matches parsing
192 if (node->hasChild("width")) {
193 float w = node->getFloatValue("width");
194 float h = node->getFloatValue("height", w);
200 xy0.x() = node->getFloatValue("x0", 0.0);
201 xy0.y() = node->getFloatValue("y0", 0.0);
202 xy1.x() = node->getFloatValue("x1", 5);
203 xy1.y() = node->getFloatValue("y1", 5);
206 double texSize = node->getFloatValue("texture-size", 1.0);
208 uv0.x() = node->getFloatValue("u0", 0) / texSize;
209 uv0.y() = node->getFloatValue("v0", 0) / texSize;
210 uv1.x() = node->getFloatValue("u1", 1) / texSize;
211 uv1.y() = node->getFloatValue("v1", 1) / texSize;
213 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
214 priority = node->getIntValue("priority", 0);
215 zOrder = node->getIntValue("zOrder", 0);
216 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
217 roundPos = node->getBoolValue("round-position", true);
219 if (node->hasChild("text")) {
221 alignment = readAlignment(node->getStringValue("text-align"));
222 textTemplate = node->getStringValue("text");
223 textOffset.x() = node->getFloatValue("text-offset-x", 0);
224 textOffset.y() = node->getFloatValue("text-offset-y", 0);
225 textColor = readColor(node->getChild("text-color"), color);
228 drawLine = node->getBoolValue("draw-line", false);
229 lineColor = readColor(node->getChild("line-color"), color);
230 drawRouteLeg = node->getBoolValue("draw-leg", false);
232 stretchSymbol = node->getBoolValue("stretch-symbol", false);
234 stretchY2 = node->getFloatValue("y2");
235 stretchY3 = node->getFloatValue("y3");
236 stretchV2 = node->getFloatValue("v2");
237 stretchV3 = node->getFloatValue("v3");
244 bool enabled; // cached enabled state
247 string_set required_states;
248 string_set excluded_states;
256 bool rotateToHeading;
257 bool roundPos; ///< should position be rounded to integer values
260 osg::Vec2 textOffset;
261 osgText::Text::AlignmentType alignment;
267 // symbol stretching creates three quads (instead of one) - a start,
268 // middle and end quad, positioned along the line of the symbol.
269 // X (and U) axis values determined by the values above, so we only need
270 // to define the Y (and V) values to build the other quads.
272 double stretchY2, stretchY3;
273 double stretchV2, stretchV3;
277 bool matches(const string_set& states) const
279 BOOST_FOREACH(const string& s, required_states) {
280 if (states.count(s) == 0) {
285 BOOST_FOREACH(const string& s, excluded_states) {
286 if (states.count(s) != 0) {
298 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
305 osg::Vec2 pos; // projected position
308 SymbolDef* definition;
309 SGPropertyNode_ptr props;
313 assert(definition->hasText);
318 size_t pos = definition->textTemplate.find('{', lastPos);
319 if (pos == string::npos) { // no more replacements
320 r.append(definition->textTemplate.substr(lastPos));
324 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
326 size_t endReplacement = definition->textTemplate.find('}', pos+1);
327 if (endReplacement <= pos) {
328 return "bad replacement";
331 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
332 // look for formatter in spec
333 size_t colonPos = spec.find(':');
334 if (colonPos == string::npos) {
335 // simple replacement
336 r.append(props->getStringValue(spec));
338 string format = spec.substr(colonPos + 1);
339 string prop = spec.substr(0, colonPos);
340 r.append(formatPropertyValue(props->getNode(prop), format));
343 lastPos = endReplacement + 1;
350 //////////////////////////////////////////////////////////////////
352 NavDisplay::NavDisplay(SGPropertyNode *node) :
353 _name(node->getStringValue("name", "nd")),
354 _num(node->getIntValue("number", 0)),
356 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
365 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
366 _font_node = _Instrument->getNode("font", true);
368 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
369 INITFONT("name", DEFAULT_FONT, String);
370 INITFONT("size", 8, Float);
371 INITFONT("line-spacing", 0.25, Float);
372 INITFONT("color/red", 0, Float);
373 INITFONT("color/green", 0.8, Float);
374 INITFONT("color/blue", 0, Float);
375 INITFONT("color/alpha", 1, Float);
378 SGPropertyNode* symbolsNode = node->getNode("symbols");
379 SGPropertyNode* symbol;
381 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
382 SymbolDef* def = new SymbolDef;
383 if (!def->initFromNode(symbol)) {
388 _rules.push_back(def);
389 } // of symbol definition parsing
393 NavDisplay::~NavDisplay()
401 _cachedItemsValid = false;
402 _cacheListener.reset(new CacheListener(this));
404 _serviceable_node = _Instrument->getNode("serviceable", true);
405 _rangeNode = _Instrument->getNode("range", true);
406 _rangeNode->setDoubleValue(40.0);
407 _rangeNode->addChangeListener(_cacheListener.get());
409 // texture name to use in 2D and 3D instruments
410 _texture_path = _Instrument->getStringValue("radar-texture-path",
411 "Aircraft/Instruments/Textures/od_wxradar.rgb");
412 _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
414 string path = _Instrument->getStringValue("symbol-texture-path",
415 "Aircraft/Instruments/Textures/nd-symbols.png");
416 SGPath tpath = globals->resolve_aircraft_path(path);
417 if (!tpath.exists()) {
418 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
421 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
422 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
424 FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
425 _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
426 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
428 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
430 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
431 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
433 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
434 _excessDataNode->setBoolValue(false);
435 _testModeNode = _Instrument->getChild("test-mode", 0, true);
436 _testModeNode->setBoolValue(false);
438 // OSG geometry setup
439 _radarGeode = new osg::Geode;
441 _geom = new osg::Geometry;
442 _geom->setUseDisplayList(false);
444 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
445 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
446 stateSet->setDataVariance(osg::Object::STATIC);
448 // Initially allocate space for 128 quads
449 _vertices = new osg::Vec2Array;
450 _vertices->setDataVariance(osg::Object::DYNAMIC);
451 _vertices->reserve(128 * 4);
452 _geom->setVertexArray(_vertices);
453 _texCoords = new osg::Vec2Array;
454 _texCoords->setDataVariance(osg::Object::DYNAMIC);
455 _texCoords->reserve(128 * 4);
456 _geom->setTexCoordArray(0, _texCoords);
458 _quadColors = new osg::Vec4Array;
459 _quadColors->setDataVariance(osg::Object::DYNAMIC);
460 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
461 _geom->setColorArray(_quadColors);
463 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
464 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
465 _geom->addPrimitiveSet(_symbolPrimSet);
467 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
468 osg::Vec3f(256.0f, 256.0f, 0.0f)));
470 _radarGeode->addDrawable(_geom);
472 // Texture in the 2D panel system
473 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
475 _lineGeometry = new osg::Geometry;
476 _lineGeometry->setUseDisplayList(false);
477 stateSet = _lineGeometry->getOrCreateStateSet();
478 osg::LineWidth *lw = new osg::LineWidth();
480 stateSet->setAttribute(lw);
482 _lineVertices = new osg::Vec2Array;
483 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
484 _lineVertices->reserve(128 * 4);
485 _lineGeometry->setVertexArray(_lineVertices);
488 _lineColors = new osg::Vec4Array;
489 _lineColors->setDataVariance(osg::Object::DYNAMIC);
490 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
491 _lineGeometry->setColorArray(_lineColors);
493 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
494 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
495 _lineGeometry->addPrimitiveSet(_linePrimSet);
497 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
498 osg::Vec3f(256.0f, 256.0f, 0.0f)));
500 _radarGeode->addDrawable(_lineGeometry);
502 _textGeode = new osg::Geode;
504 osg::Camera *camera = _odg->getCamera();
505 camera->addChild(_radarGeode.get());
506 camera->addChild(_textGeode.get());
507 osg::Texture2D* tex = _odg->getTexture();
508 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
509 0, tex->getTextureHeight());
515 NavDisplay::update (double delta_time_sec)
517 if (!fgGetBool("sim/sceneryloaded", false)) {
521 if (!_odg || !_serviceable_node->getBoolValue()) {
522 _Instrument->setStringValue("status", "");
526 _time += delta_time_sec;
527 if (_time < _updateInterval){
530 _time -= _updateInterval;
532 _rangeNm = _rangeNode->getFloatValue();
533 if (_testModeNode->getBoolValue()) {
535 } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
536 _view_heading = fgGetDouble("/orientation/heading-deg");
538 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
541 double xCenterFrac = _Instrument->getDoubleValue("x-center", 0.5);
542 double yCenterFrac = _Instrument->getDoubleValue("y-center", 0.5);
543 int pixelSize = _odg->size();
545 int rangePixels = _Instrument->getIntValue("range-pixels", -1);
546 if (rangePixels < 0) {
547 // hacky - assume (as is very common) that x-frac doesn't vary, and
548 // y-frac is used to position the center at either the top or bottom of
549 // the pixel area. Measure from the center to the furthest edge (top or bottom)
550 rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
553 _scale = rangePixels / _rangeNm;
554 _Instrument->setDoubleValue("scale", _scale);
557 _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize,
558 yCenterFrac * pixelSize, 0.0);
560 // scale from nm to display units, rotate so aircraft heading is up
561 // (as opposed to north), and compensate for centering
562 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
563 degRotation(-_view_heading) * _centerTrans;
565 _pos = globals->get_aircraft_position();
567 // invalidate the cache of positioned items, if we travelled more than 1nm
568 if (_cachedItemsValid) {
569 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
570 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
571 _cachedItemsValid = (movedNm < 1.0);
572 if (!_cachedItemsValid) {
573 SG_LOG(SG_INSTR, SG_INFO, "invalidating NavDisplay cache due to moving: " << movedNm);
578 _lineVertices->clear();
579 _lineColors->clear();
580 _quadColors->clear();
582 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
584 BOOST_FOREACH(SymbolInstance* si, _symbols) {
589 BOOST_FOREACH(SymbolDef* def, _rules) {
591 def->enabled = def->enable->test();
597 if (_testModeNode->getBoolValue()) {
604 limitDisplayedSymbols();
609 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
610 _symbolPrimSet->dirty();
611 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
612 _linePrimSet->dirty();
617 NavDisplay::updateFont()
619 float red = _font_node->getFloatValue("color/red");
620 float green = _font_node->getFloatValue("color/green");
621 float blue = _font_node->getFloatValue("color/blue");
622 float alpha = _font_node->getFloatValue("color/alpha");
623 _font_color.set(red, green, blue, alpha);
625 _font_size = _font_node->getFloatValue("size");
626 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
627 string path = _font_node->getStringValue("name", DEFAULT_FONT);
630 if (path[0] != '/') {
631 tpath = globals->get_fg_root();
632 tpath.append("Fonts");
638 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
639 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
643 _font->setMinFilterHint(osg::Texture::NEAREST);
644 _font->setMagFilterHint(osg::Texture::NEAREST);
645 _font->setGlyphImageMargin(0);
646 _font->setGlyphImageMarginRatio(0);
650 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
652 SymbolDef* def = sym->definition;
656 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
658 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
660 if (def->rotateToHeading) {
661 osg::Matrixf m(degRotation(sym->headingDeg));
662 for (int i=0; i<4; ++i) {
663 verts[i] = mult(verts[i], m);
667 osg::Vec2 pos = sym->pos;
669 pos = osg::Vec2((int) pos.x(), (int) pos.y());
672 _texCoords->push_back(def->uv0);
673 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
674 _texCoords->push_back(def->uv1);
675 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
677 for (int i=0; i<4; ++i) {
678 _vertices->push_back(verts[i] + pos);
679 _quadColors->push_back(def->color);
682 if (def->stretchSymbol) {
683 osg::Vec2 stretchVerts[4];
684 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
685 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
686 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
687 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
689 osg::Matrixf m(degRotation(sym->headingDeg));
690 for (int i=0; i<4; ++i) {
691 stretchVerts[i] = mult(stretchVerts[i], m);
695 _vertices->push_back(verts[2] + pos);
696 _vertices->push_back(stretchVerts[1] + sym->endPos);
697 _vertices->push_back(stretchVerts[0] + sym->endPos);
698 _vertices->push_back(verts[3] + pos);
700 _texCoords->push_back(def->uv1);
701 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
702 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
703 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
705 for (int i=0; i<4; ++i) {
706 _quadColors->push_back(def->color);
709 // quad three, for the end portion
710 for (int i=0; i<4; ++i) {
711 _vertices->push_back(stretchVerts[i] + sym->endPos);
712 _quadColors->push_back(def->color);
715 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
716 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
717 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
718 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
722 addLine(sym->pos, sym->endPos, def->lineColor);
729 osgText::Text* t = new osgText::Text;
730 t->setFont(_font.get());
731 t->setFontResolution(12, 12);
732 t->setCharacterSize(_font_size);
733 t->setLineSpacing(_font_spacing);
734 t->setColor(def->textColor);
735 t->setAlignment(def->alignment);
736 t->setText(sym->text());
739 osg::Vec2 textPos = def->textOffset + pos;
740 // ensure we use ints here, or text visual quality goes bad
741 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
742 _textGeode->addDrawable(t);
745 class OrderByPriority
748 bool operator()(SymbolInstance* a, SymbolInstance* b)
750 return a->definition->priority > b->definition->priority;
754 void NavDisplay::limitDisplayedSymbols()
756 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
757 if (_symbols.size() <= maxSymbols) {
758 _excessDataNode->setBoolValue(false);
762 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
763 _symbols.resize(maxSymbols);
764 _excessDataNode->setBoolValue(true);
770 bool operator()(SymbolInstance* a, SymbolInstance* b)
772 return a->definition->zOrder > b->definition->zOrder;
776 void NavDisplay::addSymbolsToScene()
778 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
779 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
780 addSymbolToScene(sym);
784 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
786 _lineVertices->push_back(a);
787 _lineVertices->push_back(b);
788 _lineColors->push_back(color);
789 _lineColors->push_back(color);
792 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
794 osg::Vec3 p(0, rangeNm, 0.0);
795 p = degRotation(bearingDeg).preMult(p);
796 p = _projectMat.preMult(p);
797 return osg::Vec2(p.x(), p.y());
800 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
802 double rangeM, bearing, az2;
803 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
804 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
807 class Filter : public FGPositioned::Filter
810 double minRunwayLengthFt;
812 virtual bool pass(FGPositioned* aPos) const
814 if (aPos->type() == FGPositioned::FIX) {
815 string ident(aPos->ident());
816 // ignore fixes which end in digits
817 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
822 if (aPos->type() == FGPositioned::AIRPORT) {
823 FGAirport* apt = (FGAirport*) aPos;
824 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
832 virtual FGPositioned::Type minType() const {
833 return FGPositioned::AIRPORT;
836 virtual FGPositioned::Type maxType() const {
837 return FGPositioned::OBSTACLE;
841 void NavDisplay::findItems()
843 if (!_cachedItemsValid) {
844 SG_LOG(SG_INSTR, SG_INFO, "re-validating NavDisplay cache");
846 filt.minRunwayLengthFt = 2000;
847 _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
848 _cachedItemsValid = true;
849 _cachedPos = SGVec3d::fromGeod(_pos);
852 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
853 foundPositionedItem(pos);
857 void NavDisplay::processRoute()
859 _routeSources.clear();
860 RoutePath path(_route->waypts());
861 int current = _route->currentIndex();
863 for (int w=0; w<_route->numWaypts(); ++w) {
864 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
865 _routeSources.insert(wpt->source());
868 state.insert("on-active-route");
871 state.insert("passed");
875 state.insert("current-wp");
879 state.insert("future");
882 if (w == (current + 1)) {
883 state.insert("next-wp");
886 SymbolDefVector rules;
887 findRules("waypoint" , state, rules);
889 return; // no rules matched, we can skip this item
892 SGGeod g = path.positionForIndex(w);
893 SGPropertyNode* vars = _route->wayptNodeAtIndex(w);
895 computeWayptPropsAndHeading(wpt, g, vars, heading);
897 osg::Vec2 projected = projectGeod(g);
898 BOOST_FOREACH(SymbolDef* r, rules) {
899 addSymbolInstance(projected, heading, r, vars);
901 if (r->drawRouteLeg) {
902 SGGeodVec gv(path.pathForIndex(w));
904 osg::Vec2 pr = projectGeod(gv[0]);
905 for (unsigned int i=1; i<gv.size(); ++i) {
906 osg::Vec2 p = projectGeod(gv[i]);
907 addLine(pr, p, r->lineColor);
911 } // of leg drawing enabled
912 } // of matching rules iteration
913 } // of waypoints iteration
916 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
919 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
920 nd->setIntValue("radial", heading);
921 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
923 heading = nd->getDoubleValue("leg-bearing-true-deg");
926 void NavDisplay::processNavRadios()
928 _nav1Station = processNavRadio(_navRadio1Node);
929 _nav2Station = processNavRadio(_navRadio2Node);
931 foundPositionedItem(_nav1Station);
932 foundPositionedItem(_nav2Station);
935 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
937 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
938 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
939 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
940 // station was not found
948 bool NavDisplay::anyRuleForType(const string& type) const
950 BOOST_FOREACH(SymbolDef* r, _rules) {
955 if (r->type == type) {
963 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
965 BOOST_FOREACH(SymbolDef* r, _rules) {
966 if (!r->enabled || (r->type != type)) {
970 if (r->matches(states)) {
973 } // of rules iteration
978 void NavDisplay::findRules(const string& type, const string_set& states, SymbolDefVector& rules)
980 BOOST_FOREACH(SymbolDef* candidate, _rules) {
981 if (!candidate->enabled || (candidate->type != type)) {
985 if (candidate->matches(states)) {
986 rules.push_back(candidate);
991 void NavDisplay::foundPositionedItem(FGPositioned* pos)
997 string type = FGPositioned::nameForType(pos->type());
998 if (!anyRuleForType(type)) {
999 return; // not diplayed at all, we're done
1003 computePositionedState(pos, states);
1005 SymbolDefVector rules;
1006 findRules(type, states, rules);
1007 if (rules.empty()) {
1008 return; // no rules matched, we can skip this item
1011 SGPropertyNode_ptr vars(new SGPropertyNode);
1013 computePositionedPropsAndHeading(pos, vars, heading);
1015 osg::Vec2 projected = projectGeod(pos->geod());
1016 BOOST_FOREACH(SymbolDef* r, rules) {
1017 addSymbolInstance(projected, heading, r, vars);
1021 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1023 nd->setStringValue("id", pos->ident());
1024 nd->setStringValue("name", pos->name());
1025 nd->setDoubleValue("elevation-ft", pos->elevation());
1026 nd->setIntValue("heading-deg", 0);
1028 switch (pos->type()) {
1029 case FGPositioned::VOR:
1030 case FGPositioned::LOC:
1031 case FGPositioned::TACAN: {
1032 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1033 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1035 if (pos == _nav1Station) {
1036 nd->setIntValue("heading-deg", _navRadio1Node->getDoubleValue("radials/target-radial-deg"));
1037 } else if (pos == _nav2Station) {
1038 nd->setIntValue("heading-deg", _navRadio2Node->getDoubleValue("radials/target-radial-deg"));
1044 case FGPositioned::AIRPORT:
1045 case FGPositioned::SEAPORT:
1046 case FGPositioned::HELIPORT:
1050 case FGPositioned::RUNWAY: {
1051 FGRunway* rwy = static_cast<FGRunway*>(pos);
1052 nd->setDoubleValue("heading-deg", rwy->headingDeg());
1053 nd->setIntValue("length-ft", rwy->lengthFt());
1054 nd->setStringValue("airport", rwy->airport()->ident());
1063 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1065 if (_routeSources.count(pos) != 0) {
1066 states.insert("on-active-route");
1069 switch (pos->type()) {
1070 case FGPositioned::VOR:
1071 case FGPositioned::LOC:
1072 if (pos == _nav1Station) {
1073 states.insert("tuned");
1074 states.insert("nav1");
1077 if (pos == _nav2Station) {
1078 states.insert("tuned");
1079 states.insert("nav2");
1083 case FGPositioned::AIRPORT:
1084 case FGPositioned::SEAPORT:
1085 case FGPositioned::HELIPORT:
1087 // once the FMS system has some way to tell us about them, of course
1089 if (pos == _route->departureAirport()) {
1090 states.insert("departure");
1093 if (pos == _route->destinationAirport()) {
1094 states.insert("destination");
1098 case FGPositioned::RUNWAY:
1099 if (pos == _route->departureRunway()) {
1100 states.insert("departure");
1103 if (pos == _route->destinationRunway()) {
1104 states.insert("destination");
1108 case FGPositioned::OBSTACLE:
1110 FGObstacle* obs = (FGObstacle*) pos;
1112 states.insert("lit");
1115 if (obj->getHeightAGLFt() >= 1000) {
1116 states.insert("greater-1000-ft");
1123 } // FGPositioned::Type switch
1126 static string mapAINodeToType(SGPropertyNode* model)
1128 // assume all multiplayer items are aircraft for the moment. Not ideal.
1129 if (!strcmp(model->getName(), "multiplayer")) {
1130 return "ai-aircraft";
1133 return string("ai-") + model->getName();
1136 void NavDisplay::processAI()
1138 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1139 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1140 SGPropertyNode *model = ai->getChild(i);
1141 if (!model->nChildren()) {
1145 // prefix types with 'ai-', to avoid any chance of namespace collisions
1146 // with fg-positioned.
1148 computeAIStates(model, ss);
1149 SymbolDefVector rules;
1150 findRules(mapAINodeToType(model), ss, rules);
1151 if (rules.empty()) {
1152 return; // no rules matched, we can skip this item
1155 double heading = model->getDoubleValue("orientation/true-heading-deg");
1156 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1157 model->getDoubleValue("position/latitude-deg"),
1158 model->getDoubleValue("position/altitude-ft"));
1159 // compute some additional props
1160 int fl = (aiModelPos.getElevationFt() / 1000);
1161 model->setIntValue("flight-level", fl * 10);
1163 osg::Vec2 projected = projectGeod(aiModelPos);
1164 BOOST_FOREACH(SymbolDef* r, rules) {
1165 addSymbolInstance(projected, heading, r, (SGPropertyNode*) model);
1167 } // of ai models iteration
1170 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1172 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1173 if (threatLevel < 1)
1176 states.insert("tcas");
1178 std::ostringstream os;
1179 os << "tcas-threat-level-" << threatLevel;
1180 states.insert(os.str());
1182 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1183 if (vspeed < -3.0) {
1184 states.insert("descending");
1185 } else if (vspeed > 3.0) {
1186 states.insert("climbing");
1190 bool NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1192 if (isProjectedClipped(proj)) {
1196 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1197 _symbols.push_back(sym);
1201 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1203 double size = _odg->size();
1204 return (projected.x() < 0.0) ||
1205 (projected.y() < 0.0) ||
1206 (projected.x() >= size) ||
1207 (projected.y() >= size);
1210 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1212 string_set stateSet;
1213 BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1217 SymbolDefVector rules;
1218 findRules(type, stateSet, rules);
1219 if (rules.empty()) {
1220 return; // no rules matched, we can skip this item
1223 osg::Vec2 projected = projectGeod(pos);
1224 BOOST_FOREACH(SymbolDef* r, rules) {
1225 addSymbolInstance(projected, heading, r, vars);
1229 void NavDisplay::addTestSymbols()
1231 _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1235 SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1237 addTestSymbol("airport", "", a1, 0.0, NULL);
1239 SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1241 addTestSymbol("vor", "", a1, 0.0, NULL);
1243 SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1245 addTestSymbol("airport", "destination", a1, 0.0, NULL);
1247 SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1248 addTestSymbol("fix", "", a1, 0.0, NULL);
1251 SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1252 addTestSymbol("fix", "", a1, 0.0, NULL);
1254 SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);
1255 addTestSymbol("fix", "", a1, 0.0, NULL);
1257 SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);
1258 addTestSymbol("fix", "", a1, 0.0, NULL);