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>
66 #include <Cockpit/panel.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>
75 #include "instrument_mgr.hxx"
76 #include "od_gauge.hxx"
78 static const char *DEFAULT_FONT = "typewriter.txf";
81 osg::Matrixf degRotation(float angle)
83 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
86 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
89 result.r() = colorNode->getDoubleValue("red", c.r());
90 result.g() = colorNode->getDoubleValue("green", c.g());
91 result.b() = colorNode->getDoubleValue("blue", c.b());
92 result.a() = colorNode->getDoubleValue("alpha", c.a());
96 static osgText::Text::AlignmentType readAlignment(const std::string& t)
98 if (t == "left-top") {
99 return osgText::Text::LEFT_TOP;
100 } else if (t == "left-center") {
101 return osgText::Text::LEFT_CENTER;
102 } else if (t == "left-bottom") {
103 return osgText::Text::LEFT_BOTTOM;
104 } else if (t == "center-top") {
105 return osgText::Text::CENTER_TOP;
106 } else if (t == "center-center") {
107 return osgText::Text::CENTER_CENTER;
108 } else if (t == "center-bottom") {
109 return osgText::Text::CENTER_BOTTOM;
110 } else if (t == "right-top") {
111 return osgText::Text::RIGHT_TOP;
112 } else if (t == "right-center") {
113 return osgText::Text::RIGHT_CENTER;
114 } else if (t == "right-bottom") {
115 return osgText::Text::RIGHT_BOTTOM;
116 } else if (t == "left-baseline") {
117 return osgText::Text::LEFT_BASE_LINE;
118 } else if (t == "center-baseline") {
119 return osgText::Text::CENTER_BASE_LINE;
120 } else if (t == "right-baseline") {
121 return osgText::Text::RIGHT_BASE_LINE;
124 return osgText::Text::BASE_LINE;
127 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
130 static char buf[512];
131 if (format.find('d') != string::npos) {
132 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
136 if (format.find('s') != string::npos) {
137 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
141 // assume it's a double/float
142 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
146 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
148 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
149 return osg::Vec2(r.x(), r.y());
152 class NavDisplay::CacheListener : public SGPropertyChangeListener
155 CacheListener(NavDisplay *nd) :
159 virtual void valueChanged (SGPropertyNode * prop)
161 _nd->invalidatePositionedCache();
167 class NavDisplay::ForceUpdateListener : public SGPropertyChangeListener
170 ForceUpdateListener(NavDisplay *nd) :
174 virtual void valueChanged (SGPropertyNode * prop)
182 ///////////////////////////////////////////////////////////////////
192 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
194 if (!node->getChild("type")) {
198 type = node->getStringValue("type");
199 boost::to_lower(type);
200 SGPropertyNode* enableNode = node->getChild("enable");
202 enable.reset(sgReadCondition(fgGetNode("/"), enableNode));
206 while (node->hasChild("state", n)) {
207 string m = node->getChild("state", n++)->getStringValue();
209 excluded_states.insert(m.substr(1));
211 required_states.insert(m);
213 } // of matches parsing
218 void setDefinition(SymbolDef* d)
223 SymbolDef* getDefinition() const
224 { return definition; }
226 bool matches(const string_set& states) const
228 BOOST_FOREACH(const string& s, required_states) {
229 if (states.count(s) == 0) {
234 BOOST_FOREACH(const string& s, excluded_states) {
235 if (states.count(s) != 0) {
246 enabled = enable->test();
252 bool enabled; // cached enabled state
255 SymbolDef* definition;
257 std::auto_ptr<SGCondition> enable;
258 string_set required_states;
259 string_set excluded_states;
266 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
268 if (node->getChild("type")) {
269 SymbolRule* builtinRule = new SymbolRule;
270 builtinRule->initFromNode(node, owner);
271 builtinRule->setDefinition(this);
272 owner->addRule(builtinRule);
275 if (node->hasChild("width")) {
276 float w = node->getFloatValue("width");
277 float h = node->getFloatValue("height", w);
283 xy0.x() = node->getFloatValue("x0", 0.0);
284 xy0.y() = node->getFloatValue("y0", 0.0);
285 xy1.x() = node->getFloatValue("x1", 5);
286 xy1.y() = node->getFloatValue("y1", 5);
289 double texSize = node->getFloatValue("texture-size", owner->textureSize());
291 uv0.x() = node->getFloatValue("u0", 0) / texSize;
292 uv0.y() = node->getFloatValue("v0", 0) / texSize;
293 uv1.x() = node->getFloatValue("u1", 1) / texSize;
294 uv1.y() = node->getFloatValue("v1", 1) / texSize;
296 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
297 priority = node->getIntValue("priority", 0);
298 zOrder = node->getIntValue("zOrder", 0);
299 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
300 roundPos = node->getBoolValue("round-position", true);
302 if (node->hasChild("text")) {
304 alignment = readAlignment(node->getStringValue("text-align"));
305 textTemplate = node->getStringValue("text");
306 textOffset.x() = node->getFloatValue("text-offset-x", 0);
307 textOffset.y() = node->getFloatValue("text-offset-y", 0);
308 textColor = readColor(node->getChild("text-color"), color);
311 drawLine = node->getBoolValue("draw-line", false);
312 lineColor = readColor(node->getChild("line-color"), color);
313 drawRouteLeg = node->getBoolValue("draw-leg", false);
315 stretchSymbol = node->getBoolValue("stretch-symbol", false);
317 stretchY2 = node->getFloatValue("y2");
318 stretchY3 = node->getFloatValue("y3");
319 stretchV2 = node->getFloatValue("v2") / texSize;
320 stretchV3 = node->getFloatValue("v3") / texSize;
332 bool rotateToHeading;
333 bool roundPos; ///< should position be rounded to integer values
336 osg::Vec2 textOffset;
337 osgText::Text::AlignmentType alignment;
343 // symbol stretching creates three quads (instead of one) - a start,
344 // middle and end quad, positioned along the line of the symbol.
345 // X (and U) axis values determined by the values above, so we only need
346 // to define the Y (and V) values to build the other quads.
348 double stretchY2, stretchY3;
349 double stretchV2, stretchV3;
358 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
365 osg::Vec2 pos; // projected position
368 SymbolDef* definition;
369 SGPropertyNode_ptr props;
373 assert(definition->hasText);
378 size_t pos = definition->textTemplate.find('{', lastPos);
379 if (pos == string::npos) { // no more replacements
380 r.append(definition->textTemplate.substr(lastPos));
384 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
386 size_t endReplacement = definition->textTemplate.find('}', pos+1);
387 if (endReplacement <= pos) {
388 return "bad replacement";
391 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
392 // look for formatter in spec
393 size_t colonPos = spec.find(':');
394 if (colonPos == string::npos) {
395 // simple replacement
396 r.append(props->getStringValue(spec));
398 string format = spec.substr(colonPos + 1);
399 string prop = spec.substr(0, colonPos);
400 r.append(formatPropertyValue(props->getNode(prop), format));
403 lastPos = endReplacement + 1;
410 //////////////////////////////////////////////////////////////////
412 NavDisplay::NavDisplay(SGPropertyNode *node) :
413 _name(node->getStringValue("name", "nd")),
414 _num(node->getIntValue("number", 0)),
416 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
425 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
426 _font_node = _Instrument->getNode("font", true);
428 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
429 INITFONT("name", DEFAULT_FONT, String);
430 INITFONT("size", 8, Float);
431 INITFONT("line-spacing", 0.25, Float);
432 INITFONT("color/red", 0, Float);
433 INITFONT("color/green", 0.8, Float);
434 INITFONT("color/blue", 0, Float);
435 INITFONT("color/alpha", 1, Float);
438 _textureSize = _Instrument->getNode("symbol-texture-size", true)->getIntValue();
439 SGPropertyNode* symbolsNode = node->getNode("symbols");
440 SGPropertyNode* symbol;
442 map<string, SymbolDef*> definitionDict;
443 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
444 SymbolDef* def = new SymbolDef;
445 if (!def->initFromNode(symbol, this)) {
450 const char* id = symbol->getStringValue("id");
451 if (id && strlen(id)) {
452 definitionDict[id] = def;
455 _definitions.push_back(def);
456 } // of symbol definition parsing
458 SGPropertyNode* rulesNode = node->getNode("rules");
460 SGPropertyNode* rule;
462 for (int i = 0; (rule = rulesNode->getChild("rule", i)) != NULL; ++i) {
463 SymbolRule* r = new SymbolRule;
464 if (!r->initFromNode(rule, this)) {
469 const char* id = symbol->getStringValue("symbol");
470 if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
471 r->setDefinition(definitionDict[id]);
473 SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
479 } // of symbol rule parsing
485 NavDisplay::~NavDisplay()
493 _cachedItemsValid = false;
494 _cacheListener.reset(new CacheListener(this));
495 _forceUpdateListener.reset(new ForceUpdateListener(this));
497 _serviceable_node = _Instrument->getNode("serviceable", true);
498 _rangeNode = _Instrument->getNode("range", true);
499 if (!_rangeNode->hasValue()) {
500 _rangeNode->setDoubleValue(40.0);
502 _rangeNode->addChangeListener(_cacheListener.get());
503 _rangeNode->addChangeListener(_forceUpdateListener.get());
505 _xCenterNode = _Instrument->getNode("x-center");
506 if (!_xCenterNode->hasValue()) {
507 _xCenterNode->setDoubleValue(0.5);
509 _xCenterNode->addChangeListener(_forceUpdateListener.get());
510 _yCenterNode = _Instrument->getNode("y-center");
511 if (!_yCenterNode->hasValue()) {
512 _yCenterNode->setDoubleValue(0.5);
514 _yCenterNode->addChangeListener(_forceUpdateListener.get());
516 // texture name to use in 2D and 3D instruments
517 _texture_path = _Instrument->getStringValue("radar-texture-path",
518 "Aircraft/Instruments/Textures/od_wxradar.rgb");
520 string path = _Instrument->getStringValue("symbol-texture-path",
521 "Aircraft/Instruments/Textures/nd-symbols.png");
522 SGPath tpath = globals->resolve_aircraft_path(path);
523 if (!tpath.exists()) {
524 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
527 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
528 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
530 _odg = new FGODGauge;
531 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
533 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
535 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
536 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
538 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
539 _excessDataNode->setBoolValue(false);
540 _testModeNode = _Instrument->getChild("test-mode", 0, true);
541 _testModeNode->setBoolValue(false);
543 _viewHeadingNode = _Instrument->getChild("view-heading-deg", 0, true);
544 // OSG geometry setup
545 _radarGeode = new osg::Geode;
547 _geom = new osg::Geometry;
548 _geom->setUseDisplayList(false);
550 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
551 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
552 stateSet->setDataVariance(osg::Object::STATIC);
554 // Initially allocate space for 128 quads
555 _vertices = new osg::Vec2Array;
556 _vertices->setDataVariance(osg::Object::DYNAMIC);
557 _vertices->reserve(128 * 4);
558 _geom->setVertexArray(_vertices);
559 _texCoords = new osg::Vec2Array;
560 _texCoords->setDataVariance(osg::Object::DYNAMIC);
561 _texCoords->reserve(128 * 4);
562 _geom->setTexCoordArray(0, _texCoords);
564 _quadColors = new osg::Vec4Array;
565 _quadColors->setDataVariance(osg::Object::DYNAMIC);
566 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
567 _geom->setColorArray(_quadColors);
569 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
570 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
571 _geom->addPrimitiveSet(_symbolPrimSet);
573 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
574 osg::Vec3f(256.0f, 256.0f, 0.0f)));
576 _radarGeode->addDrawable(_geom);
578 // Texture in the 2D panel system
579 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
581 _lineGeometry = new osg::Geometry;
582 _lineGeometry->setUseDisplayList(false);
583 stateSet = _lineGeometry->getOrCreateStateSet();
584 osg::LineWidth *lw = new osg::LineWidth();
586 stateSet->setAttribute(lw);
588 _lineVertices = new osg::Vec2Array;
589 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
590 _lineVertices->reserve(128 * 4);
591 _lineGeometry->setVertexArray(_lineVertices);
594 _lineColors = new osg::Vec4Array;
595 _lineColors->setDataVariance(osg::Object::DYNAMIC);
596 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
597 _lineGeometry->setColorArray(_lineColors);
599 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
600 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
601 _lineGeometry->addPrimitiveSet(_linePrimSet);
603 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
604 osg::Vec3f(256.0f, 256.0f, 0.0f)));
606 _radarGeode->addDrawable(_lineGeometry);
608 _textGeode = new osg::Geode;
610 osg::Camera *camera = _odg->getCamera();
611 camera->addChild(_radarGeode.get());
612 camera->addChild(_textGeode.get());
613 osg::Texture2D* tex = _odg->getTexture();
614 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
615 0, tex->getTextureHeight());
621 NavDisplay::update (double delta_time_sec)
623 if (!fgGetBool("sim/sceneryloaded", false)) {
627 if (!_odg || !_serviceable_node->getBoolValue()) {
628 _Instrument->setStringValue("status", "");
633 _forceUpdate = false;
636 _time += delta_time_sec;
637 if (_time < _updateInterval){
640 _time -= _updateInterval;
643 _rangeNm = _rangeNode->getFloatValue();
644 if (_testModeNode->getBoolValue()) {
646 } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
647 _view_heading = fgGetDouble("/orientation/heading-deg");
649 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
651 _viewHeadingNode->setDoubleValue(_view_heading);
653 double xCenterFrac = _xCenterNode->getDoubleValue();
654 double yCenterFrac = _yCenterNode->getDoubleValue();
655 int pixelSize = _odg->size();
657 int rangePixels = _Instrument->getIntValue("range-pixels", -1);
658 if (rangePixels < 0) {
659 // hacky - assume (as is very common) that x-frac doesn't vary, and
660 // y-frac is used to position the center at either the top or bottom of
661 // the pixel area. Measure from the center to the furthest edge (top or bottom)
662 rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
665 _scale = rangePixels / _rangeNm;
666 _Instrument->setDoubleValue("scale", _scale);
669 _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize,
670 yCenterFrac * pixelSize, 0.0);
672 // scale from nm to display units, rotate so aircraft heading is up
673 // (as opposed to north), and compensate for centering
674 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
675 degRotation(-_view_heading) * _centerTrans;
677 _pos = globals->get_aircraft_position();
679 // invalidate the cache of positioned items, if we travelled more than 1nm
680 if (_cachedItemsValid) {
681 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
682 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
683 _cachedItemsValid = (movedNm < 1.0);
687 _lineVertices->clear();
688 _lineColors->clear();
689 _quadColors->clear();
691 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
693 BOOST_FOREACH(SymbolInstance* si, _symbols) {
698 BOOST_FOREACH(SymbolRule* r, _rules) {
702 if (_testModeNode->getBoolValue()) {
709 limitDisplayedSymbols();
714 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
715 _symbolPrimSet->dirty();
716 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
717 _linePrimSet->dirty();
722 NavDisplay::updateFont()
724 float red = _font_node->getFloatValue("color/red");
725 float green = _font_node->getFloatValue("color/green");
726 float blue = _font_node->getFloatValue("color/blue");
727 float alpha = _font_node->getFloatValue("color/alpha");
728 _font_color.set(red, green, blue, alpha);
730 _font_size = _font_node->getFloatValue("size");
731 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
732 string path = _font_node->getStringValue("name", DEFAULT_FONT);
735 if (path[0] != '/') {
736 tpath = globals->get_fg_root();
737 tpath.append("Fonts");
743 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
744 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
748 _font->setMinFilterHint(osg::Texture::NEAREST);
749 _font->setMagFilterHint(osg::Texture::NEAREST);
750 _font->setGlyphImageMargin(0);
751 _font->setGlyphImageMarginRatio(0);
755 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
757 SymbolDef* def = sym->definition;
761 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
763 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
765 if (def->rotateToHeading) {
766 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
767 for (int i=0; i<4; ++i) {
768 verts[i] = mult(verts[i], m);
772 osg::Vec2 pos = sym->pos;
774 pos = osg::Vec2((int) pos.x(), (int) pos.y());
777 _texCoords->push_back(def->uv0);
778 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
779 _texCoords->push_back(def->uv1);
780 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
782 for (int i=0; i<4; ++i) {
783 _vertices->push_back(verts[i] + pos);
784 _quadColors->push_back(def->color);
787 if (def->stretchSymbol) {
788 osg::Vec2 stretchVerts[4];
789 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
790 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
791 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
792 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
794 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
795 for (int i=0; i<4; ++i) {
796 stretchVerts[i] = mult(stretchVerts[i], m);
800 _vertices->push_back(verts[2] + pos);
801 _vertices->push_back(stretchVerts[1] + sym->endPos);
802 _vertices->push_back(stretchVerts[0] + sym->endPos);
803 _vertices->push_back(verts[3] + pos);
805 _texCoords->push_back(def->uv1);
806 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
807 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
808 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
810 for (int i=0; i<4; ++i) {
811 _quadColors->push_back(def->color);
814 // quad three, for the end portion
815 for (int i=0; i<4; ++i) {
816 _vertices->push_back(stretchVerts[i] + sym->endPos);
817 _quadColors->push_back(def->color);
820 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
821 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
822 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
823 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
827 addLine(sym->pos, sym->endPos, def->lineColor);
834 osgText::Text* t = new osgText::Text;
835 t->setFont(_font.get());
836 t->setFontResolution(12, 12);
837 t->setCharacterSize(_font_size);
838 t->setLineSpacing(_font_spacing);
839 t->setColor(def->textColor);
840 t->setAlignment(def->alignment);
841 t->setText(sym->text());
844 osg::Vec2 textPos = def->textOffset + pos;
845 // ensure we use ints here, or text visual quality goes bad
846 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
847 _textGeode->addDrawable(t);
850 class OrderByPriority
853 bool operator()(SymbolInstance* a, SymbolInstance* b)
855 return a->definition->priority > b->definition->priority;
859 void NavDisplay::limitDisplayedSymbols()
861 unsigned int maxSymbols = _Instrument->getIntValue("max-symbols", 100);
862 if (_symbols.size() <= maxSymbols) {
863 _excessDataNode->setBoolValue(false);
867 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
868 _symbols.resize(maxSymbols);
869 _excessDataNode->setBoolValue(true);
875 bool operator()(SymbolInstance* a, SymbolInstance* b)
877 return a->definition->zOrder > b->definition->zOrder;
881 void NavDisplay::addSymbolsToScene()
883 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
884 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
885 addSymbolToScene(sym);
889 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
891 _lineVertices->push_back(a);
892 _lineVertices->push_back(b);
893 _lineColors->push_back(color);
894 _lineColors->push_back(color);
897 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
899 osg::Vec3 p(0, rangeNm, 0.0);
900 p = degRotation(bearingDeg).preMult(p);
901 p = _projectMat.preMult(p);
902 return osg::Vec2(p.x(), p.y());
905 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
907 double rangeM, bearing, az2;
908 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
909 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
912 class Filter : public FGPositioned::Filter
915 double minRunwayLengthFt;
917 virtual bool pass(FGPositioned* aPos) const
919 if (aPos->type() == FGPositioned::FIX) {
920 string ident(aPos->ident());
921 // ignore fixes which end in digits
922 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
927 if (aPos->type() == FGPositioned::AIRPORT) {
928 FGAirport* apt = (FGAirport*) aPos;
929 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
937 virtual FGPositioned::Type minType() const {
938 return FGPositioned::AIRPORT;
941 virtual FGPositioned::Type maxType() const {
942 return FGPositioned::OBSTACLE;
946 void NavDisplay::findItems()
948 if (!_cachedItemsValid) {
950 filt.minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
951 _itemsInRange = FGPositioned::findWithinRange(_pos, _rangeNm, &filt);
952 _cachedItemsValid = true;
953 _cachedPos = SGVec3d::fromGeod(_pos);
956 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
957 foundPositionedItem(pos);
961 void NavDisplay::processRoute()
963 _routeSources.clear();
964 flightgear::FlightPlan* fp = _route->flightPlan();
966 int current = _route->currentIndex();
968 for (int l=0; l<fp->numLegs(); ++l) {
969 flightgear::FlightPlan::Leg* leg = fp->legAtIndex(l);
970 flightgear::WayptRef wpt(leg->waypoint());
971 _routeSources.insert(wpt->source());
974 state.insert("on-active-route");
977 state.insert("passed");
981 state.insert("current-wp");
985 state.insert("future");
988 if (l == (current + 1)) {
989 state.insert("next-wp");
992 SymbolRuleVector rules;
993 findRules("waypoint" , state, rules);
995 return; // no rules matched, we can skip this item
998 SGGeod g = path.positionForIndex(l);
999 SGPropertyNode* vars = _route->wayptNodeAtIndex(l);
1001 continue; // shouldn't happen, but let's guard against it
1005 computeWayptPropsAndHeading(wpt, g, vars, heading);
1007 osg::Vec2 projected = projectGeod(g);
1008 BOOST_FOREACH(SymbolRule* r, rules) {
1009 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1011 if (r->getDefinition()->drawRouteLeg) {
1012 SGGeodVec gv(path.pathForIndex(l));
1014 osg::Vec2 pr = projectGeod(gv[0]);
1015 for (unsigned int i=1; i<gv.size(); ++i) {
1016 osg::Vec2 p = projectGeod(gv[i]);
1017 addLine(pr, p, r->getDefinition()->lineColor);
1021 } // of leg drawing enabled
1022 } // of matching rules iteration
1023 } // of waypoints iteration
1026 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1029 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1030 nd->setIntValue("radial", heading);
1031 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1033 heading = nd->getDoubleValue("leg-bearing-true-deg");
1036 void NavDisplay::processNavRadios()
1038 _nav1Station = processNavRadio(_navRadio1Node);
1039 _nav2Station = processNavRadio(_navRadio2Node);
1041 foundPositionedItem(_nav1Station);
1042 foundPositionedItem(_nav2Station);
1045 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1047 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1048 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _pos);
1049 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1050 // station was not found
1058 bool NavDisplay::anyRuleForType(const string& type) const
1060 BOOST_FOREACH(SymbolRule* r, _rules) {
1065 if (r->type == type) {
1073 bool NavDisplay::anyRuleMatches(const string& type, const string_set& states) const
1075 BOOST_FOREACH(SymbolRule* r, _rules) {
1076 if (!r->enabled || (r->type != type)) {
1080 if (r->matches(states)) {
1083 } // of rules iteration
1088 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1090 BOOST_FOREACH(SymbolRule* candidate, _rules) {
1091 if (!candidate->enabled || (candidate->type != type)) {
1095 if (candidate->matches(states)) {
1096 rules.push_back(candidate);
1101 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1107 string type = FGPositioned::nameForType(pos->type());
1108 //boost::to_lower(type);
1109 if (!anyRuleForType(type)) {
1110 return; // not diplayed at all, we're done
1114 computePositionedState(pos, states);
1116 SymbolRuleVector rules;
1117 findRules(type, states, rules);
1118 if (rules.empty()) {
1119 return; // no rules matched, we can skip this item
1122 SGPropertyNode_ptr vars(new SGPropertyNode);
1124 computePositionedPropsAndHeading(pos, vars, heading);
1126 osg::Vec2 projected = projectGeod(pos->geod());
1127 if (pos->type() == FGPositioned::RUNWAY) {
1128 FGRunway* rwy = (FGRunway*) pos;
1129 projected = projectGeod(rwy->threshold());
1132 BOOST_FOREACH(SymbolRule* r, rules) {
1133 SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1134 if (pos->type() == FGPositioned::RUNWAY) {
1135 FGRunway* rwy = (FGRunway*) pos;
1136 ins->endPos = projectGeod(rwy->end());
1141 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1143 nd->setStringValue("id", pos->ident());
1144 nd->setStringValue("name", pos->name());
1145 nd->setDoubleValue("elevation-ft", pos->elevation());
1146 nd->setIntValue("heading-deg", 0);
1149 switch (pos->type()) {
1150 case FGPositioned::VOR:
1151 case FGPositioned::LOC:
1152 case FGPositioned::TACAN: {
1153 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1154 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1156 if (pos == _nav1Station) {
1157 heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1158 } else if (pos == _nav2Station) {
1159 heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1162 nd->setIntValue("heading-deg", heading);
1166 case FGPositioned::AIRPORT:
1167 case FGPositioned::SEAPORT:
1168 case FGPositioned::HELIPORT:
1172 case FGPositioned::RUNWAY: {
1173 FGRunway* rwy = static_cast<FGRunway*>(pos);
1174 heading = rwy->headingDeg();
1175 nd->setDoubleValue("heading-deg", heading);
1176 nd->setIntValue("length-ft", rwy->lengthFt());
1177 nd->setStringValue("airport", rwy->airport()->ident());
1186 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1188 if (_routeSources.count(pos) != 0) {
1189 states.insert("on-active-route");
1192 flightgear::FlightPlan* fp = _route->flightPlan();
1193 switch (pos->type()) {
1194 case FGPositioned::VOR:
1195 case FGPositioned::LOC:
1196 if (pos == _nav1Station) {
1197 states.insert("tuned");
1198 states.insert("nav1");
1201 if (pos == _nav2Station) {
1202 states.insert("tuned");
1203 states.insert("nav2");
1207 case FGPositioned::AIRPORT:
1208 case FGPositioned::SEAPORT:
1209 case FGPositioned::HELIPORT:
1211 // once the FMS system has some way to tell us about them, of course
1213 if (pos == fp->departureAirport()) {
1214 states.insert("departure");
1217 if (pos == fp->destinationAirport()) {
1218 states.insert("destination");
1222 case FGPositioned::RUNWAY:
1223 if (pos == fp->departureRunway()) {
1224 states.insert("departure");
1227 if (pos == fp->destinationRunway()) {
1228 states.insert("destination");
1232 case FGPositioned::OBSTACLE:
1234 FGObstacle* obs = (FGObstacle*) pos;
1236 states.insert("lit");
1239 if (obj->getHeightAGLFt() >= 1000) {
1240 states.insert("greater-1000-ft");
1247 } // FGPositioned::Type switch
1250 static string mapAINodeToType(SGPropertyNode* model)
1252 // assume all multiplayer items are aircraft for the moment. Not ideal.
1253 if (!strcmp(model->getName(), "multiplayer")) {
1254 return "ai-aircraft";
1257 return string("ai-") + model->getName();
1260 void NavDisplay::processAI()
1262 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1263 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1264 SGPropertyNode *model = ai->getChild(i);
1265 if (!model->nChildren()) {
1269 // prefix types with 'ai-', to avoid any chance of namespace collisions
1270 // with fg-positioned.
1272 computeAIStates(model, ss);
1273 SymbolRuleVector rules;
1274 findRules(mapAINodeToType(model), ss, rules);
1275 if (rules.empty()) {
1276 return; // no rules matched, we can skip this item
1279 double heading = model->getDoubleValue("orientation/true-heading-deg");
1280 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1281 model->getDoubleValue("position/latitude-deg"),
1282 model->getDoubleValue("position/altitude-ft"));
1283 // compute some additional props
1284 int fl = (aiModelPos.getElevationFt() / 1000);
1285 model->setIntValue("flight-level", fl * 10);
1287 osg::Vec2 projected = projectGeod(aiModelPos);
1288 BOOST_FOREACH(SymbolRule* r, rules) {
1289 addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1291 } // of ai models iteration
1294 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1296 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1297 if (threatLevel < 1)
1300 states.insert("tcas");
1302 std::ostringstream os;
1303 os << "tcas-threat-level-" << threatLevel;
1304 states.insert(os.str());
1306 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1307 if (vspeed < -3.0) {
1308 states.insert("descending");
1309 } else if (vspeed > 3.0) {
1310 states.insert("climbing");
1314 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1316 if (isProjectedClipped(proj)) {
1320 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1321 _symbols.push_back(sym);
1325 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1327 double size = _odg->size();
1328 return (projected.x() < 0.0) ||
1329 (projected.y() < 0.0) ||
1330 (projected.x() >= size) ||
1331 (projected.y() >= size);
1334 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1336 string_set stateSet;
1337 BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1341 SymbolRuleVector rules;
1342 findRules(type, stateSet, rules);
1343 if (rules.empty()) {
1344 return; // no rules matched, we can skip this item
1347 osg::Vec2 projected = projectGeod(pos);
1348 BOOST_FOREACH(SymbolRule* r, rules) {
1349 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1353 void NavDisplay::addTestSymbols()
1355 _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1359 SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1361 addTestSymbol("airport", "", a1, 0.0, NULL);
1363 SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1365 addTestSymbol("vor", "", a1, 0.0, NULL);
1367 SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1369 addTestSymbol("airport", "destination", a1, 0.0, NULL);
1371 SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1372 addTestSymbol("fix", "", a1, 0.0, NULL);
1375 SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1376 addTestSymbol("fix", "", a1, 0.0, NULL);
1378 SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);
1379 addTestSymbol("fix", "", a1, 0.0, NULL);
1381 SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);
1382 addTestSymbol("fix", "", a1, 0.0, NULL);
1385 void NavDisplay::addRule(SymbolRule* r)
1387 _rules.push_back(r);