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>
30 #include <boost/algorithm/string/case_conv.hpp>
34 #include <osg/Geometry>
35 #include <osg/Matrixf>
36 #include <osg/PrimitiveSet>
37 #include <osg/StateSet>
38 #include <osg/LineWidth>
39 #include <osg/Version>
41 #include <simgear/constants.h>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/scene/model/model.hxx>
44 #include <simgear/structure/exception.hxx>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/misc/strutils.hxx>
47 #include <simgear/math/sg_geodesy.hxx>
51 #include <iostream> // for cout, endl
53 using std::stringstream;
55 using std::setprecision;
64 #include <Main/fg_props.hxx>
65 #include <Main/globals.hxx>
67 #include <Navaids/routePath.hxx>
68 #include <Autopilot/route_mgr.hxx>
69 #include <Navaids/navrecord.hxx>
70 #include <Navaids/navlist.hxx>
71 #include <Navaids/fix.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/runways.hxx>
74 #include "od_gauge.hxx"
76 static const char *DEFAULT_FONT = "typewriter.txf";
79 osg::Matrixf degRotation(float angle)
81 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
84 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
87 result.r() = colorNode->getDoubleValue("red", c.r());
88 result.g() = colorNode->getDoubleValue("green", c.g());
89 result.b() = colorNode->getDoubleValue("blue", c.b());
90 result.a() = colorNode->getDoubleValue("alpha", c.a());
94 static osgText::Text::AlignmentType readAlignment(const std::string& t)
96 if (t == "left-top") {
97 return osgText::Text::LEFT_TOP;
98 } else if (t == "left-center") {
99 return osgText::Text::LEFT_CENTER;
100 } else if (t == "left-bottom") {
101 return osgText::Text::LEFT_BOTTOM;
102 } else if (t == "center-top") {
103 return osgText::Text::CENTER_TOP;
104 } else if (t == "center-center") {
105 return osgText::Text::CENTER_CENTER;
106 } else if (t == "center-bottom") {
107 return osgText::Text::CENTER_BOTTOM;
108 } else if (t == "right-top") {
109 return osgText::Text::RIGHT_TOP;
110 } else if (t == "right-center") {
111 return osgText::Text::RIGHT_CENTER;
112 } else if (t == "right-bottom") {
113 return osgText::Text::RIGHT_BOTTOM;
114 } else if (t == "left-baseline") {
115 return osgText::Text::LEFT_BASE_LINE;
116 } else if (t == "center-baseline") {
117 return osgText::Text::CENTER_BASE_LINE;
118 } else if (t == "right-baseline") {
119 return osgText::Text::RIGHT_BASE_LINE;
122 return osgText::Text::BASE_LINE;
125 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
128 static char buf[512];
129 if (format.find('d') != string::npos) {
130 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
134 if (format.find('s') != string::npos) {
135 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
139 // assume it's a double/float
140 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
144 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
146 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
147 return osg::Vec2(r.x(), r.y());
150 class NavDisplay::CacheListener : public SGPropertyChangeListener
153 CacheListener(NavDisplay *nd) :
157 virtual void valueChanged (SGPropertyNode * prop)
159 _nd->invalidatePositionedCache();
165 class NavDisplay::ForceUpdateListener : public SGPropertyChangeListener
168 ForceUpdateListener(NavDisplay *nd) :
172 virtual void valueChanged (SGPropertyNode * prop)
180 ///////////////////////////////////////////////////////////////////
190 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
192 if (!node->getChild("type")) {
196 type = node->getStringValue("type");
197 boost::to_lower(type);
198 SGPropertyNode* enableNode = node->getChild("enable");
200 enable.reset(sgReadCondition(fgGetNode("/"), enableNode));
204 while (node->hasChild("state", n)) {
205 string m = node->getChild("state", n++)->getStringValue();
207 excluded_states.insert(m.substr(1));
209 required_states.insert(m);
211 } // of matches parsing
217 void setDefinition(SymbolDef* d)
222 SymbolDef* getDefinition() const
223 { return definition; }
225 bool matches(const string_set& states) const
227 BOOST_FOREACH(const string& s, required_states) {
228 if (states.count(s) == 0) {
233 BOOST_FOREACH(const string& s, excluded_states) {
234 if (states.count(s) != 0) {
242 // return if the enabled state changed (needs a cache update)
246 bool wasEnabled = enabled;
247 enabled = enable->test();
248 return (enabled != wasEnabled);
255 bool enabled; // cached enabled state
258 // record instances for limiting by count
261 SymbolDef* definition;
263 std::auto_ptr<SGCondition> enable;
264 string_set required_states;
265 string_set excluded_states;
271 SymbolDef() : limitCount(0) { }
273 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
275 if (node->getChild("type")) {
276 SymbolRule* builtinRule = new SymbolRule;
277 builtinRule->initFromNode(node, owner);
278 builtinRule->setDefinition(this);
279 owner->addRule(builtinRule);
282 if (node->hasChild("width")) {
283 float w = node->getFloatValue("width");
284 float h = node->getFloatValue("height", w);
290 xy0.x() = node->getFloatValue("x0", 0.0);
291 xy0.y() = node->getFloatValue("y0", 0.0);
292 xy1.x() = node->getFloatValue("x1", 5);
293 xy1.y() = node->getFloatValue("y1", 5);
296 double texSize = node->getFloatValue("texture-size", owner->textureSize());
298 uv0.x() = node->getFloatValue("u0", 0) / texSize;
299 uv0.y() = node->getFloatValue("v0", 0) / texSize;
300 uv1.x() = node->getFloatValue("u1", 1) / texSize;
301 uv1.y() = node->getFloatValue("v1", 1) / texSize;
303 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
304 priority = node->getIntValue("priority", 0);
305 zOrder = node->getIntValue("zOrder", 0);
306 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
307 roundPos = node->getBoolValue("round-position", true);
309 if (node->hasChild("text")) {
311 alignment = readAlignment(node->getStringValue("text-align"));
312 textTemplate = node->getStringValue("text");
313 textOffset.x() = node->getFloatValue("text-offset-x", 0);
314 textOffset.y() = node->getFloatValue("text-offset-y", 0);
315 textColor = readColor(node->getChild("text-color"), color);
317 SGPropertyNode* enableNode = node->getChild("text-enable");
319 textEnable.reset(sgReadCondition(fgGetNode("/"), enableNode));
323 drawLine = node->getBoolValue("draw-line", false);
324 lineColor = readColor(node->getChild("line-color"), color);
325 drawRouteLeg = node->getBoolValue("draw-leg", false);
327 stretchSymbol = node->getBoolValue("stretch-symbol", false);
329 stretchY2 = node->getFloatValue("y2");
330 stretchY3 = node->getFloatValue("y3");
331 stretchV2 = node->getFloatValue("v2") / texSize;
332 stretchV3 = node->getFloatValue("v3") / texSize;
335 SGPropertyNode* limitNode = node->getChild("limit");
337 limitCount = limitNode->getIntValue();
349 bool rotateToHeading;
350 bool roundPos; ///< should position be rounded to integer values
352 std::auto_ptr<SGCondition> textEnable;
353 bool textEnabled; ///< cache condition result
355 osg::Vec2 textOffset;
356 osgText::Text::AlignmentType alignment;
362 // symbol stretching creates three quads (instead of one) - a start,
363 // middle and end quad, positioned along the line of the symbol.
364 // X (and U) axis values determined by the values above, so we only need
365 // to define the Y (and V) values to build the other quads.
367 double stretchY2, stretchY3;
368 double stretchV2, stretchV3;
372 int limitCount, instanceCount;
378 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
385 osg::Vec2 pos; // projected position
388 SymbolDef* definition;
389 SGPropertyNode_ptr props;
393 assert(definition->hasText);
398 size_t pos = definition->textTemplate.find('{', lastPos);
399 if (pos == string::npos) { // no more replacements
400 r.append(definition->textTemplate.substr(lastPos));
404 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
406 size_t endReplacement = definition->textTemplate.find('}', pos+1);
407 if (endReplacement <= pos) {
408 return "bad replacement";
411 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
412 // look for formatter in spec
413 size_t colonPos = spec.find(':');
414 if (colonPos == string::npos) {
415 // simple replacement
416 r.append(props->getStringValue(spec));
418 string format = spec.substr(colonPos + 1);
419 string prop = spec.substr(0, colonPos);
420 r.append(formatPropertyValue(props->getNode(prop), format));
423 lastPos = endReplacement + 1;
430 //////////////////////////////////////////////////////////////////
432 NavDisplay::NavDisplay(SGPropertyNode *node) :
433 _name(node->getStringValue("name", "nd")),
434 _num(node->getIntValue("number", 0)),
436 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
446 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
447 _font_node = _Instrument->getNode("font", true);
449 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
450 INITFONT("name", DEFAULT_FONT, String);
451 INITFONT("size", 8, Float);
452 INITFONT("line-spacing", 0.25, Float);
453 INITFONT("color/red", 0, Float);
454 INITFONT("color/green", 0.8, Float);
455 INITFONT("color/blue", 0, Float);
456 INITFONT("color/alpha", 1, Float);
459 _textureSize = _Instrument->getNode("symbol-texture-size", true)->getIntValue();
460 SGPropertyNode* symbolsNode = node->getNode("symbols");
461 SGPropertyNode* symbol;
463 map<string, SymbolDef*> definitionDict;
464 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
465 SymbolDef* def = new SymbolDef;
466 if (!def->initFromNode(symbol, this)) {
471 const char* id = symbol->getStringValue("id");
472 if (id && strlen(id)) {
473 definitionDict[id] = def;
476 _definitions.push_back(def);
477 } // of symbol definition parsing
479 SGPropertyNode* rulesNode = node->getNode("rules");
481 SGPropertyNode* rule;
483 for (int i = 0; (rule = rulesNode->getChild("rule", i)) != NULL; ++i) {
484 SymbolRule* r = new SymbolRule;
485 if (!r->initFromNode(rule, this)) {
490 const char* id = symbol->getStringValue("symbol");
491 if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
492 r->setDefinition(definitionDict[id]);
494 SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
500 } // of symbol rule parsing
506 NavDisplay::~NavDisplay()
514 _cachedItemsValid = false;
515 _cacheListener.reset(new CacheListener(this));
516 _forceUpdateListener.reset(new ForceUpdateListener(this));
518 _serviceable_node = _Instrument->getNode("serviceable", true);
519 _rangeNode = _Instrument->getNode("range", true);
520 if (!_rangeNode->hasValue()) {
521 _rangeNode->setDoubleValue(40.0);
523 _rangeNode->addChangeListener(_cacheListener.get());
524 _rangeNode->addChangeListener(_forceUpdateListener.get());
526 _xCenterNode = _Instrument->getNode("x-center");
527 if (!_xCenterNode->hasValue()) {
528 _xCenterNode->setDoubleValue(0.5);
530 _xCenterNode->addChangeListener(_forceUpdateListener.get());
531 _yCenterNode = _Instrument->getNode("y-center");
532 if (!_yCenterNode->hasValue()) {
533 _yCenterNode->setDoubleValue(0.5);
535 _yCenterNode->addChangeListener(_forceUpdateListener.get());
537 // texture name to use in 2D and 3D instruments
538 _texture_path = _Instrument->getStringValue("radar-texture-path",
539 "Aircraft/Instruments/Textures/od_wxradar.rgb");
541 string path = _Instrument->getStringValue("symbol-texture-path",
542 "Aircraft/Instruments/Textures/nd-symbols.png");
543 SGPath tpath = globals->resolve_aircraft_path(path);
544 if (!tpath.exists()) {
545 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
548 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
549 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
551 _odg = new FGODGauge;
552 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
554 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
556 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
557 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
559 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
560 _excessDataNode->setBoolValue(false);
561 _testModeNode = _Instrument->getChild("test-mode", 0, true);
562 _testModeNode->setBoolValue(false);
564 _viewHeadingNode = _Instrument->getChild("view-heading-deg", 0, true);
565 _userLatNode = _Instrument->getChild("user-latitude-deg", 0, true);
566 _userLonNode = _Instrument->getChild("user-longitude-deg", 0, true);
567 _userPositionEnable = _Instrument->getChild("user-position", 0, true);
569 // OSG geometry setup
570 _radarGeode = new osg::Geode;
572 _geom = new osg::Geometry;
573 _geom->setUseDisplayList(false);
575 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
576 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
577 stateSet->setDataVariance(osg::Object::STATIC);
579 // Initially allocate space for 128 quads
580 _vertices = new osg::Vec2Array;
581 _vertices->setDataVariance(osg::Object::DYNAMIC);
582 _vertices->reserve(128 * 4);
583 _geom->setVertexArray(_vertices);
584 _texCoords = new osg::Vec2Array;
585 _texCoords->setDataVariance(osg::Object::DYNAMIC);
586 _texCoords->reserve(128 * 4);
587 _geom->setTexCoordArray(0, _texCoords);
589 _quadColors = new osg::Vec4Array;
590 _quadColors->setDataVariance(osg::Object::DYNAMIC);
591 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
592 _geom->setColorArray(_quadColors);
594 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
595 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
596 _geom->addPrimitiveSet(_symbolPrimSet);
598 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
599 osg::Vec3f(256.0f, 256.0f, 0.0f)));
601 _radarGeode->addDrawable(_geom);
603 // Texture in the 2D panel system
604 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
606 _lineGeometry = new osg::Geometry;
607 _lineGeometry->setUseDisplayList(false);
608 stateSet = _lineGeometry->getOrCreateStateSet();
609 osg::LineWidth *lw = new osg::LineWidth();
611 stateSet->setAttribute(lw);
613 _lineVertices = new osg::Vec2Array;
614 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
615 _lineVertices->reserve(128 * 4);
616 _lineGeometry->setVertexArray(_lineVertices);
619 _lineColors = new osg::Vec4Array;
620 _lineColors->setDataVariance(osg::Object::DYNAMIC);
621 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
622 _lineGeometry->setColorArray(_lineColors);
624 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
625 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
626 _lineGeometry->addPrimitiveSet(_linePrimSet);
628 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
629 osg::Vec3f(256.0f, 256.0f, 0.0f)));
631 _radarGeode->addDrawable(_lineGeometry);
633 _textGeode = new osg::Geode;
635 osg::Camera *camera = _odg->getCamera();
636 camera->addChild(_radarGeode.get());
637 camera->addChild(_textGeode.get());
638 osg::Texture2D* tex = _odg->getTexture();
639 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
640 0, tex->getTextureHeight());
646 NavDisplay::update (double delta_time_sec)
648 if (!fgGetBool("sim/sceneryloaded", false)) {
652 if (!_odg || !_serviceable_node->getBoolValue()) {
653 _Instrument->setStringValue("status", "");
658 _forceUpdate = false;
661 _time += delta_time_sec;
662 if (_time < _updateInterval){
665 _time -= _updateInterval;
668 _rangeNm = _rangeNode->getFloatValue();
669 if (_testModeNode->getBoolValue()) {
671 } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
672 _view_heading = fgGetDouble("/orientation/heading-deg");
674 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
676 _viewHeadingNode->setDoubleValue(_view_heading);
678 double xCenterFrac = _xCenterNode->getDoubleValue();
679 double yCenterFrac = _yCenterNode->getDoubleValue();
680 int pixelSize = _odg->size();
682 int rangePixels = _Instrument->getIntValue("range-pixels", -1);
683 if (rangePixels < 0) {
684 // hacky - assume (as is very common) that x-frac doesn't vary, and
685 // y-frac is used to position the center at either the top or bottom of
686 // the pixel area. Measure from the center to the furthest edge (top or bottom)
687 rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
690 _scale = rangePixels / _rangeNm;
691 _Instrument->setDoubleValue("scale", _scale);
694 _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize,
695 yCenterFrac * pixelSize, 0.0);
697 // scale from nm to display units, rotate so aircraft heading is up
698 // (as opposed to north), and compensate for centering
699 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
700 degRotation(-_view_heading) * _centerTrans;
702 if (_userPositionEnable->getBoolValue()) {
703 _pos = SGGeod::fromDeg(_userLonNode->getDoubleValue(), _userLatNode->getDoubleValue());
705 _pos = globals->get_aircraft_position();
708 // invalidate the cache of positioned items, if we travelled more than 1nm
709 if (_cachedItemsValid) {
710 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
711 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
712 _cachedItemsValid = (movedNm < 1.0);
716 _lineVertices->clear();
717 _lineColors->clear();
718 _quadColors->clear();
720 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
722 BOOST_FOREACH(SymbolInstance* si, _symbols) {
727 BOOST_FOREACH(SymbolDef* d, _definitions) {
728 d->instanceCount = 0;
729 d->textEnabled = d->textEnable.get() ? d->textEnable->test() : true;
732 bool enableChanged = false;
733 BOOST_FOREACH(SymbolRule* r, _rules) {
734 enableChanged |= r->checkEnabled();
738 SG_LOG(SG_INSTR, SG_INFO, "NS rule enables changed, rebuilding cache");
739 _cachedItemsValid = false;
742 if (_testModeNode->getBoolValue()) {
749 limitDisplayedSymbols();
754 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
755 _symbolPrimSet->dirty();
756 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
757 _linePrimSet->dirty();
762 NavDisplay::updateFont()
764 float red = _font_node->getFloatValue("color/red");
765 float green = _font_node->getFloatValue("color/green");
766 float blue = _font_node->getFloatValue("color/blue");
767 float alpha = _font_node->getFloatValue("color/alpha");
768 _font_color.set(red, green, blue, alpha);
770 _font_size = _font_node->getFloatValue("size");
771 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
772 string path = _font_node->getStringValue("name", DEFAULT_FONT);
775 if (path[0] != '/') {
776 tpath = globals->get_fg_root();
777 tpath.append("Fonts");
783 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
784 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
788 _font->setMinFilterHint(osg::Texture::NEAREST);
789 _font->setMagFilterHint(osg::Texture::NEAREST);
790 _font->setGlyphImageMargin(0);
791 _font->setGlyphImageMarginRatio(0);
795 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
797 SymbolDef* def = sym->definition;
801 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
803 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
805 if (def->rotateToHeading) {
806 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
807 for (int i=0; i<4; ++i) {
808 verts[i] = mult(verts[i], m);
812 osg::Vec2 pos = sym->pos;
814 pos = osg::Vec2((int) pos.x(), (int) pos.y());
817 _texCoords->push_back(def->uv0);
818 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
819 _texCoords->push_back(def->uv1);
820 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
822 for (int i=0; i<4; ++i) {
823 _vertices->push_back(verts[i] + pos);
824 _quadColors->push_back(def->color);
827 if (def->stretchSymbol) {
828 osg::Vec2 stretchVerts[4];
829 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
830 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
831 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
832 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
834 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
835 for (int i=0; i<4; ++i) {
836 stretchVerts[i] = mult(stretchVerts[i], m);
840 _vertices->push_back(verts[2] + pos);
841 _vertices->push_back(stretchVerts[1] + sym->endPos);
842 _vertices->push_back(stretchVerts[0] + sym->endPos);
843 _vertices->push_back(verts[3] + pos);
845 _texCoords->push_back(def->uv1);
846 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
847 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
848 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
850 for (int i=0; i<4; ++i) {
851 _quadColors->push_back(def->color);
854 // quad three, for the end portion
855 for (int i=0; i<4; ++i) {
856 _vertices->push_back(stretchVerts[i] + sym->endPos);
857 _quadColors->push_back(def->color);
860 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
861 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
862 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
863 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
867 addLine(sym->pos, sym->endPos, def->lineColor);
870 if (!def->hasText || !def->textEnabled) {
874 osgText::Text* t = new osgText::Text;
875 t->setFont(_font.get());
876 t->setFontResolution(12, 12);
877 t->setCharacterSize(_font_size);
878 t->setLineSpacing(_font_spacing);
879 t->setColor(def->textColor);
880 t->setAlignment(def->alignment);
881 t->setText(sym->text());
884 osg::Vec2 textPos = def->textOffset + pos;
885 // ensure we use ints here, or text visual quality goes bad
886 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
887 _textGeode->addDrawable(t);
890 class OrderByPriority
893 bool operator()(SymbolInstance* a, SymbolInstance* b)
895 return a->definition->priority > b->definition->priority;
899 void NavDisplay::limitDisplayedSymbols()
901 // gloabl symbol limit
902 _maxSymbols= _Instrument->getIntValue("max-symbols", _maxSymbols);
903 if ((int) _symbols.size() <= _maxSymbols) {
904 _excessDataNode->setBoolValue(false);
908 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
909 _symbols.resize(_maxSymbols);
910 _excessDataNode->setBoolValue(true);
916 bool operator()(SymbolInstance* a, SymbolInstance* b)
918 return a->definition->zOrder > b->definition->zOrder;
922 void NavDisplay::addSymbolsToScene()
924 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
925 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
926 addSymbolToScene(sym);
930 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
932 _lineVertices->push_back(a);
933 _lineVertices->push_back(b);
934 _lineColors->push_back(color);
935 _lineColors->push_back(color);
938 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
940 osg::Vec3 p(0, rangeNm, 0.0);
941 p = degRotation(bearingDeg).preMult(p);
942 p = _projectMat.preMult(p);
943 return osg::Vec2(p.x(), p.y());
946 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
948 double rangeM, bearing, az2;
949 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
950 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
953 class Filter : public FGPositioned::Filter
956 Filter(NavDisplay* nd) : _owner(nd) { }
958 double minRunwayLengthFt;
960 virtual bool pass(FGPositioned* aPos) const
962 if (aPos->type() == FGPositioned::FIX) {
963 string ident(aPos->ident());
964 // ignore fixes which end in digits
965 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
970 if (aPos->type() == FGPositioned::AIRPORT) {
971 FGAirport* apt = (FGAirport*) aPos;
972 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
977 // check against current rule states
978 return _owner->isPositionedShown(aPos);
981 virtual FGPositioned::Type minType() const {
982 return FGPositioned::AIRPORT;
985 virtual FGPositioned::Type maxType() const {
986 return FGPositioned::OBSTACLE;
993 void NavDisplay::findItems()
995 if (!_cachedItemsValid) {
997 filt.minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
998 _itemsInRange = FGPositioned::findClosestN(_pos, _maxSymbols, _rangeNm, &filt);
999 _cachedItemsValid = true;
1000 _cachedPos = SGVec3d::fromGeod(_pos);
1003 // sort by distance from pos, so symbol limits are accurate
1004 FGPositioned::sortByRange(_itemsInRange, _pos);
1006 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
1007 foundPositionedItem(pos);
1011 void NavDisplay::processRoute()
1013 _routeSources.clear();
1014 flightgear::FlightPlan* fp = _route->flightPlan();
1016 int current = _route->currentIndex();
1018 for (int l=0; l<fp->numLegs(); ++l) {
1019 flightgear::FlightPlan::Leg* leg = fp->legAtIndex(l);
1020 flightgear::WayptRef wpt(leg->waypoint());
1021 _routeSources.insert(wpt->source());
1024 state.insert("on-active-route");
1027 state.insert("passed");
1031 state.insert("current-wp");
1035 state.insert("future");
1038 if (l == (current + 1)) {
1039 state.insert("next-wp");
1042 SymbolRuleVector rules;
1043 findRules("waypoint" , state, rules);
1044 if (rules.empty()) {
1045 return; // no rules matched, we can skip this item
1048 SGGeod g = path.positionForIndex(l);
1049 SGPropertyNode* vars = _route->wayptNodeAtIndex(l);
1051 continue; // shouldn't happen, but let's guard against it
1055 computeWayptPropsAndHeading(wpt, g, vars, heading);
1057 osg::Vec2 projected = projectGeod(g);
1058 BOOST_FOREACH(SymbolRule* r, rules) {
1059 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1061 if (r->getDefinition()->drawRouteLeg) {
1062 SGGeodVec gv(path.pathForIndex(l));
1064 osg::Vec2 pr = projectGeod(gv[0]);
1065 for (unsigned int i=1; i<gv.size(); ++i) {
1066 osg::Vec2 p = projectGeod(gv[i]);
1067 addLine(pr, p, r->getDefinition()->lineColor);
1071 } // of leg drawing enabled
1072 } // of matching rules iteration
1073 } // of waypoints iteration
1076 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1079 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1080 nd->setIntValue("radial", heading);
1081 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1083 heading = nd->getDoubleValue("leg-bearing-true-deg");
1086 void NavDisplay::processNavRadios()
1088 _nav1Station = processNavRadio(_navRadio1Node);
1089 _nav2Station = processNavRadio(_navRadio2Node);
1091 foundPositionedItem(_nav1Station);
1092 foundPositionedItem(_nav2Station);
1095 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1097 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1098 FGNavRecord* nav = FGNavList::findByFreq(mhz, _pos, FGNavList::navFilter());
1099 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1100 // station was not found
1108 bool NavDisplay::anyRuleForType(const string& type) const
1110 BOOST_FOREACH(SymbolRule* r, _rules) {
1115 if (r->type == type) {
1123 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1125 BOOST_FOREACH(SymbolRule* candidate, _rules) {
1126 if (!candidate->enabled || (candidate->type != type)) {
1130 if (candidate->matches(states)) {
1131 rules.push_back(candidate);
1136 bool NavDisplay::isPositionedShown(FGPositioned* pos)
1138 SymbolRuleVector rules;
1139 isPositionedShownInner(pos, rules);
1140 return !rules.empty();
1143 void NavDisplay::isPositionedShownInner(FGPositioned* pos, SymbolRuleVector& rules)
1145 string type = FGPositioned::nameForType(pos->type());
1146 boost::to_lower(type);
1147 if (!anyRuleForType(type)) {
1148 return; // not diplayed at all, we're done
1152 computePositionedState(pos, states);
1154 findRules(type, states, rules);
1157 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1163 SymbolRuleVector rules;
1164 isPositionedShownInner(pos, rules);
1165 if (rules.empty()) {
1169 SGPropertyNode_ptr vars(new SGPropertyNode);
1171 computePositionedPropsAndHeading(pos, vars, heading);
1173 osg::Vec2 projected = projectGeod(pos->geod());
1174 if (pos->type() == FGPositioned::RUNWAY) {
1175 FGRunway* rwy = (FGRunway*) pos;
1176 projected = projectGeod(rwy->threshold());
1179 BOOST_FOREACH(SymbolRule* r, rules) {
1180 SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1181 if ((ins)&&(pos->type() == FGPositioned::RUNWAY)) {
1182 FGRunway* rwy = (FGRunway*) pos;
1183 ins->endPos = projectGeod(rwy->end());
1188 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1190 nd->setStringValue("id", pos->ident());
1191 nd->setStringValue("name", pos->name());
1192 nd->setDoubleValue("elevation-ft", pos->elevation());
1193 nd->setIntValue("heading-deg", 0);
1196 switch (pos->type()) {
1197 case FGPositioned::VOR:
1198 case FGPositioned::LOC:
1199 case FGPositioned::TACAN: {
1200 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1201 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1203 if (pos == _nav1Station) {
1204 heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1205 } else if (pos == _nav2Station) {
1206 heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1209 nd->setIntValue("heading-deg", heading);
1213 case FGPositioned::AIRPORT:
1214 case FGPositioned::SEAPORT:
1215 case FGPositioned::HELIPORT:
1219 case FGPositioned::RUNWAY: {
1220 FGRunway* rwy = static_cast<FGRunway*>(pos);
1221 heading = rwy->headingDeg();
1222 nd->setDoubleValue("heading-deg", heading);
1223 nd->setIntValue("length-ft", rwy->lengthFt());
1224 nd->setStringValue("airport", rwy->airport()->ident());
1233 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1235 if (_routeSources.count(pos) != 0) {
1236 states.insert("on-active-route");
1239 flightgear::FlightPlan* fp = _route->flightPlan();
1240 switch (pos->type()) {
1241 case FGPositioned::VOR:
1242 case FGPositioned::LOC:
1243 if (pos == _nav1Station) {
1244 states.insert("tuned");
1245 states.insert("nav1");
1248 if (pos == _nav2Station) {
1249 states.insert("tuned");
1250 states.insert("nav2");
1254 case FGPositioned::AIRPORT:
1255 case FGPositioned::SEAPORT:
1256 case FGPositioned::HELIPORT:
1258 // once the FMS system has some way to tell us about them, of course
1260 if (pos == fp->departureAirport()) {
1261 states.insert("departure");
1264 if (pos == fp->destinationAirport()) {
1265 states.insert("destination");
1269 case FGPositioned::RUNWAY:
1270 if (pos == fp->departureRunway()) {
1271 states.insert("departure");
1274 if (pos == fp->destinationRunway()) {
1275 states.insert("destination");
1279 case FGPositioned::OBSTACLE:
1281 FGObstacle* obs = (FGObstacle*) pos;
1283 states.insert("lit");
1286 if (obj->getHeightAGLFt() >= 1000) {
1287 states.insert("greater-1000-ft");
1294 } // FGPositioned::Type switch
1297 static string mapAINodeToType(SGPropertyNode* model)
1299 // assume all multiplayer items are aircraft for the moment. Not ideal.
1300 if (!strcmp(model->getName(), "multiplayer")) {
1301 return "ai-aircraft";
1304 return string("ai-") + model->getName();
1307 void NavDisplay::processAI()
1309 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1310 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1311 SGPropertyNode *model = ai->getChild(i);
1312 if (!model->nChildren()) {
1316 // prefix types with 'ai-', to avoid any chance of namespace collisions
1317 // with fg-positioned.
1319 computeAIStates(model, ss);
1320 SymbolRuleVector rules;
1321 findRules(mapAINodeToType(model), ss, rules);
1322 if (rules.empty()) {
1323 return; // no rules matched, we can skip this item
1326 double heading = model->getDoubleValue("orientation/true-heading-deg");
1327 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1328 model->getDoubleValue("position/latitude-deg"),
1329 model->getDoubleValue("position/altitude-ft"));
1330 // compute some additional props
1331 int fl = (aiModelPos.getElevationFt() / 1000);
1332 model->setIntValue("flight-level", fl * 10);
1334 osg::Vec2 projected = projectGeod(aiModelPos);
1335 BOOST_FOREACH(SymbolRule* r, rules) {
1336 addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1338 } // of ai models iteration
1341 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1343 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1344 if (threatLevel < 1)
1347 states.insert("tcas");
1349 std::ostringstream os;
1350 os << "tcas-threat-level-" << threatLevel;
1351 states.insert(os.str());
1353 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1354 if (vspeed < -3.0) {
1355 states.insert("descending");
1356 } else if (vspeed > 3.0) {
1357 states.insert("climbing");
1361 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1363 if (isProjectedClipped(proj)) {
1367 if ((def->limitCount > 0) && (def->instanceCount >= def->limitCount)) {
1371 ++def->instanceCount;
1372 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1373 _symbols.push_back(sym);
1377 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1379 double size = _odg->size();
1380 return (projected.x() < 0.0) ||
1381 (projected.y() < 0.0) ||
1382 (projected.x() >= size) ||
1383 (projected.y() >= size);
1386 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1388 string_set stateSet;
1389 BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1393 SymbolRuleVector rules;
1394 findRules(type, stateSet, rules);
1395 if (rules.empty()) {
1396 return; // no rules matched, we can skip this item
1399 osg::Vec2 projected = projectGeod(pos);
1400 BOOST_FOREACH(SymbolRule* r, rules) {
1401 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1405 void NavDisplay::addTestSymbols()
1407 _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1411 SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1413 addTestSymbol("airport", "", a1, 0.0, NULL);
1415 SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1417 addTestSymbol("vor", "", a1, 0.0, NULL);
1419 SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1421 addTestSymbol("airport", "destination", a1, 0.0, NULL);
1423 SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1424 addTestSymbol("fix", "", a1, 0.0, NULL);
1427 SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1428 addTestSymbol("fix", "", a1, 0.0, NULL);
1430 SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);
1431 addTestSymbol("fix", "", a1, 0.0, NULL);
1433 SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);
1434 addTestSymbol("fix", "", a1, 0.0, NULL);
1437 void NavDisplay::addRule(SymbolRule* r)
1439 _rules.push_back(r);