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>
52 #include <iostream> // for cout, endl
54 using std::stringstream;
56 using std::setprecision;
65 #include <Main/fg_props.hxx>
66 #include <Main/globals.hxx>
68 #include <Navaids/routePath.hxx>
69 #include <Autopilot/route_mgr.hxx>
70 #include <Navaids/navrecord.hxx>
71 #include <Navaids/navlist.hxx>
72 #include <Navaids/fix.hxx>
73 #include <Airports/airport.hxx>
74 #include <Airports/runways.hxx>
75 #include "od_gauge.hxx"
77 static const char *DEFAULT_FONT = "typewriter.txf";
80 osg::Matrixf degRotation(float angle)
82 return osg::Matrixf::rotate(angle * SG_DEGREES_TO_RADIANS, 0.0f, 0.0f, -1.0f);
85 static osg::Vec4 readColor(SGPropertyNode* colorNode, const osg::Vec4& c)
88 result.r() = colorNode->getDoubleValue("red", c.r());
89 result.g() = colorNode->getDoubleValue("green", c.g());
90 result.b() = colorNode->getDoubleValue("blue", c.b());
91 result.a() = colorNode->getDoubleValue("alpha", c.a());
95 static osgText::Text::AlignmentType readAlignment(const std::string& t)
97 if (t == "left-top") {
98 return osgText::Text::LEFT_TOP;
99 } else if (t == "left-center") {
100 return osgText::Text::LEFT_CENTER;
101 } else if (t == "left-bottom") {
102 return osgText::Text::LEFT_BOTTOM;
103 } else if (t == "center-top") {
104 return osgText::Text::CENTER_TOP;
105 } else if (t == "center-center") {
106 return osgText::Text::CENTER_CENTER;
107 } else if (t == "center-bottom") {
108 return osgText::Text::CENTER_BOTTOM;
109 } else if (t == "right-top") {
110 return osgText::Text::RIGHT_TOP;
111 } else if (t == "right-center") {
112 return osgText::Text::RIGHT_CENTER;
113 } else if (t == "right-bottom") {
114 return osgText::Text::RIGHT_BOTTOM;
115 } else if (t == "left-baseline") {
116 return osgText::Text::LEFT_BASE_LINE;
117 } else if (t == "center-baseline") {
118 return osgText::Text::CENTER_BASE_LINE;
119 } else if (t == "right-baseline") {
120 return osgText::Text::RIGHT_BASE_LINE;
123 return osgText::Text::BASE_LINE;
126 static string formatPropertyValue(SGPropertyNode* nd, const string& format)
129 static char buf[512];
130 if (format.find('d') != string::npos) {
131 ::snprintf(buf, 512, format.c_str(), nd->getIntValue());
135 if (format.find('s') != string::npos) {
136 ::snprintf(buf, 512, format.c_str(), nd->getStringValue());
140 // assume it's a double/float
141 ::snprintf(buf, 512, format.c_str(), nd->getDoubleValue());
145 static osg::Vec2 mult(const osg::Vec2& v, const osg::Matrixf& m)
147 osg::Vec3 r = m.preMult(osg::Vec3(v.x(), v.y(), 0.0));
148 return osg::Vec2(r.x(), r.y());
151 class NavDisplay::CacheListener : public SGPropertyChangeListener
154 CacheListener(NavDisplay *nd) :
158 virtual void valueChanged (SGPropertyNode * prop)
160 _nd->invalidatePositionedCache();
166 class NavDisplay::ForceUpdateListener : public SGPropertyChangeListener
169 ForceUpdateListener(NavDisplay *nd) :
173 virtual void valueChanged (SGPropertyNode * prop)
181 ///////////////////////////////////////////////////////////////////
191 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
193 if (!node->getChild("type")) {
197 type = node->getStringValue("type");
198 boost::to_lower(type);
199 SGPropertyNode* enableNode = node->getChild("enable");
201 enable.reset(sgReadCondition(fgGetNode("/"), enableNode));
205 while (node->hasChild("state", n)) {
206 string m = node->getChild("state", n++)->getStringValue();
208 excluded_states.insert(m.substr(1));
210 required_states.insert(m);
212 } // 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) {
243 // return if the enabled state changed (needs a cache update)
247 bool wasEnabled = enabled;
248 enabled = enable->test();
249 return (enabled != wasEnabled);
256 bool enabled; // cached enabled state
259 // record instances for limiting by count
262 SymbolDef* definition;
264 std::auto_ptr<SGCondition> enable;
265 string_set required_states;
266 string_set excluded_states;
272 SymbolDef() : limitCount(0) { }
274 bool initFromNode(SGPropertyNode* node, NavDisplay* owner)
276 if (node->getChild("type")) {
277 SymbolRule* builtinRule = new SymbolRule;
278 builtinRule->initFromNode(node, owner);
279 builtinRule->setDefinition(this);
280 owner->addRule(builtinRule);
283 if (node->hasChild("width")) {
284 float w = node->getFloatValue("width");
285 float h = node->getFloatValue("height", w);
291 xy0.x() = node->getFloatValue("x0", 0.0);
292 xy0.y() = node->getFloatValue("y0", 0.0);
293 xy1.x() = node->getFloatValue("x1", 5);
294 xy1.y() = node->getFloatValue("y1", 5);
297 double texSize = node->getFloatValue("texture-size", owner->textureSize());
299 uv0.x() = node->getFloatValue("u0", 0) / texSize;
300 uv0.y() = node->getFloatValue("v0", 0) / texSize;
301 uv1.x() = node->getFloatValue("u1", 1) / texSize;
302 uv1.y() = node->getFloatValue("v1", 1) / texSize;
304 color = readColor(node->getChild("color"), osg::Vec4(1, 1, 1, 1));
305 priority = node->getIntValue("priority", 0);
306 zOrder = node->getIntValue("zOrder", 0);
307 rotateToHeading = node->getBoolValue("rotate-to-heading", false);
308 roundPos = node->getBoolValue("round-position", true);
310 if (node->hasChild("text")) {
312 alignment = readAlignment(node->getStringValue("text-align"));
313 textTemplate = node->getStringValue("text");
314 textOffset.x() = node->getFloatValue("text-offset-x", 0);
315 textOffset.y() = node->getFloatValue("text-offset-y", 0);
316 textColor = readColor(node->getChild("text-color"), color);
318 SGPropertyNode* enableNode = node->getChild("text-enable");
320 textEnable.reset(sgReadCondition(fgGetNode("/"), enableNode));
324 drawLine = node->getBoolValue("draw-line", false);
325 lineColor = readColor(node->getChild("line-color"), color);
326 drawRouteLeg = node->getBoolValue("draw-leg", false);
328 stretchSymbol = node->getBoolValue("stretch-symbol", false);
330 stretchY2 = node->getFloatValue("y2");
331 stretchY3 = node->getFloatValue("y3");
332 stretchV2 = node->getFloatValue("v2") / texSize;
333 stretchV3 = node->getFloatValue("v3") / texSize;
336 SGPropertyNode* limitNode = node->getChild("limit");
338 limitCount = limitNode->getIntValue();
350 bool rotateToHeading;
351 bool roundPos; ///< should position be rounded to integer values
353 std::auto_ptr<SGCondition> textEnable;
354 bool textEnabled; ///< cache condition result
356 osg::Vec2 textOffset;
357 osgText::Text::AlignmentType alignment;
363 // symbol stretching creates three quads (instead of one) - a start,
364 // middle and end quad, positioned along the line of the symbol.
365 // X (and U) axis values determined by the values above, so we only need
366 // to define the Y (and V) values to build the other quads.
368 double stretchY2, stretchY3;
369 double stretchV2, stretchV3;
373 int limitCount, instanceCount;
379 SymbolInstance(const osg::Vec2& p, double h, SymbolDef* def, SGPropertyNode* vars) :
386 osg::Vec2 pos; // projected position
389 SymbolDef* definition;
390 SGPropertyNode_ptr props;
394 assert(definition->hasText);
399 size_t pos = definition->textTemplate.find('{', lastPos);
400 if (pos == string::npos) { // no more replacements
401 r.append(definition->textTemplate.substr(lastPos));
405 r.append(definition->textTemplate.substr(lastPos, pos - lastPos));
407 size_t endReplacement = definition->textTemplate.find('}', pos+1);
408 if (endReplacement <= pos) {
409 return "bad replacement";
412 string spec = definition->textTemplate.substr(pos + 1, endReplacement - (pos + 1));
413 // look for formatter in spec
414 size_t colonPos = spec.find(':');
415 if (colonPos == string::npos) {
416 // simple replacement
417 r.append(props->getStringValue(spec));
419 string format = spec.substr(colonPos + 1);
420 string prop = spec.substr(0, colonPos);
421 r.append(formatPropertyValue(props->getNode(prop), format));
424 lastPos = endReplacement + 1;
431 //////////////////////////////////////////////////////////////////
433 NavDisplay::NavDisplay(SGPropertyNode *node) :
434 _name(node->getStringValue("name", "nd")),
435 _num(node->getIntValue("number", 0)),
437 _updateInterval(node->getDoubleValue("update-interval-sec", 0.1)),
447 _Instrument = fgGetNode(string("/instrumentation/" + _name).c_str(), _num, true);
448 _font_node = _Instrument->getNode("font", true);
450 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
451 INITFONT("name", DEFAULT_FONT, String);
452 INITFONT("size", 8, Float);
453 INITFONT("line-spacing", 0.25, Float);
454 INITFONT("color/red", 0, Float);
455 INITFONT("color/green", 0.8, Float);
456 INITFONT("color/blue", 0, Float);
457 INITFONT("color/alpha", 1, Float);
460 _textureSize = _Instrument->getNode("symbol-texture-size", true)->getIntValue();
461 SGPropertyNode* symbolsNode = node->getNode("symbols");
462 SGPropertyNode* symbol;
464 map<string, SymbolDef*> definitionDict;
465 for (int i = 0; (symbol = symbolsNode->getChild("symbol", i)) != NULL; ++i) {
466 SymbolDef* def = new SymbolDef;
467 if (!def->initFromNode(symbol, this)) {
472 const char* id = symbol->getStringValue("id");
473 if (id && strlen(id)) {
474 definitionDict[id] = def;
477 _definitions.push_back(def);
478 } // of symbol definition parsing
480 BOOST_FOREACH(SGPropertyNode* rule, symbolsNode->getChildren("rule")) {
481 SymbolRule* r = new SymbolRule;
482 if (!r->initFromNode(rule, this)) {
487 const char* id = rule->getStringValue("symbol");
488 if (id && strlen(id) && (definitionDict.find(id) != definitionDict.end())) {
489 r->setDefinition(definitionDict[id]);
491 SG_LOG(SG_INSTR, SG_WARN, "symbol rule has missing/unknown definition id:" << id);
502 NavDisplay::~NavDisplay()
510 _cachedItemsValid = false;
511 _cacheListener.reset(new CacheListener(this));
512 _forceUpdateListener.reset(new ForceUpdateListener(this));
514 _serviceable_node = _Instrument->getNode("serviceable", true);
515 _rangeNode = _Instrument->getNode("range", true);
516 if (!_rangeNode->hasValue()) {
517 _rangeNode->setDoubleValue(40.0);
519 _rangeNode->addChangeListener(_cacheListener.get());
520 _rangeNode->addChangeListener(_forceUpdateListener.get());
522 _xCenterNode = _Instrument->getNode("x-center");
523 if (!_xCenterNode->hasValue()) {
524 _xCenterNode->setDoubleValue(0.5);
526 _xCenterNode->addChangeListener(_forceUpdateListener.get());
527 _yCenterNode = _Instrument->getNode("y-center");
528 if (!_yCenterNode->hasValue()) {
529 _yCenterNode->setDoubleValue(0.5);
531 _yCenterNode->addChangeListener(_forceUpdateListener.get());
533 // texture name to use in 2D and 3D instruments
534 _texture_path = _Instrument->getStringValue("radar-texture-path",
535 "Aircraft/Instruments/Textures/od_wxradar.rgb");
537 string path = _Instrument->getStringValue("symbol-texture-path",
538 "Aircraft/Instruments/Textures/nd-symbols.png");
539 SGPath tpath = globals->resolve_aircraft_path(path);
540 if (!tpath.exists()) {
541 SG_LOG(SG_INSTR, SG_WARN, "ND symbol texture not found:" << path);
544 // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
545 _symbolTexture = SGLoadTexture2D(tpath, NULL, false, false);
547 _odg = new FGODGauge;
548 _odg->setSize(_Instrument->getIntValue("texture-size", 512));
550 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
552 _navRadio1Node = fgGetNode("/instrumentation/nav[0]", true);
553 _navRadio2Node = fgGetNode("/instrumentation/nav[1]", true);
555 _excessDataNode = _Instrument->getChild("excess-data", 0, true);
556 _excessDataNode->setBoolValue(false);
557 _testModeNode = _Instrument->getChild("test-mode", 0, true);
558 _testModeNode->setBoolValue(false);
560 _viewHeadingNode = _Instrument->getChild("view-heading-deg", 0, true);
561 _userLatNode = _Instrument->getChild("user-latitude-deg", 0, true);
562 _userLonNode = _Instrument->getChild("user-longitude-deg", 0, true);
563 _userPositionEnable = _Instrument->getChild("user-position", 0, true);
565 _customSymbols = _Instrument->getChild("symbols", 0, true);
567 // OSG geometry setup
568 _radarGeode = new osg::Geode;
570 _geom = new osg::Geometry;
571 _geom->setUseDisplayList(false);
573 osg::StateSet *stateSet = _geom->getOrCreateStateSet();
574 stateSet->setTextureAttributeAndModes(0, _symbolTexture.get());
575 stateSet->setDataVariance(osg::Object::STATIC);
577 // Initially allocate space for 128 quads
578 _vertices = new osg::Vec2Array;
579 _vertices->setDataVariance(osg::Object::DYNAMIC);
580 _vertices->reserve(128 * 4);
581 _geom->setVertexArray(_vertices);
582 _texCoords = new osg::Vec2Array;
583 _texCoords->setDataVariance(osg::Object::DYNAMIC);
584 _texCoords->reserve(128 * 4);
585 _geom->setTexCoordArray(0, _texCoords);
587 _quadColors = new osg::Vec4Array;
588 _quadColors->setDataVariance(osg::Object::DYNAMIC);
589 _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
590 _geom->setColorArray(_quadColors);
592 _symbolPrimSet = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
593 _symbolPrimSet->setDataVariance(osg::Object::DYNAMIC);
594 _geom->addPrimitiveSet(_symbolPrimSet);
596 _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
597 osg::Vec3f(256.0f, 256.0f, 0.0f)));
599 _radarGeode->addDrawable(_geom);
601 // Texture in the 2D panel system
602 FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
604 _lineGeometry = new osg::Geometry;
605 _lineGeometry->setUseDisplayList(false);
606 stateSet = _lineGeometry->getOrCreateStateSet();
607 osg::LineWidth *lw = new osg::LineWidth();
609 stateSet->setAttribute(lw);
611 _lineVertices = new osg::Vec2Array;
612 _lineVertices->setDataVariance(osg::Object::DYNAMIC);
613 _lineVertices->reserve(128 * 4);
614 _lineGeometry->setVertexArray(_lineVertices);
617 _lineColors = new osg::Vec4Array;
618 _lineColors->setDataVariance(osg::Object::DYNAMIC);
619 _lineGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
620 _lineGeometry->setColorArray(_lineColors);
622 _linePrimSet = new osg::DrawArrays(osg::PrimitiveSet::LINES);
623 _linePrimSet->setDataVariance(osg::Object::DYNAMIC);
624 _lineGeometry->addPrimitiveSet(_linePrimSet);
626 _lineGeometry->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
627 osg::Vec3f(256.0f, 256.0f, 0.0f)));
629 _radarGeode->addDrawable(_lineGeometry);
631 _textGeode = new osg::Geode;
633 osg::Camera *camera = _odg->getCamera();
634 camera->addChild(_radarGeode.get());
635 camera->addChild(_textGeode.get());
636 osg::Texture2D* tex = _odg->getTexture();
637 camera->setProjectionMatrixAsOrtho2D(0, tex->getTextureWidth(),
638 0, tex->getTextureHeight());
644 NavDisplay::update (double delta_time_sec)
646 if (!fgGetBool("sim/sceneryloaded", false)) {
650 if (!_odg || !_serviceable_node->getBoolValue()) {
651 _Instrument->setStringValue("status", "");
656 _forceUpdate = false;
659 _time += delta_time_sec;
660 if (_time < _updateInterval){
663 _time -= _updateInterval;
666 _rangeNm = _rangeNode->getFloatValue();
667 if (_testModeNode->getBoolValue()) {
669 } else if (_Instrument->getBoolValue("aircraft-heading-up", true)) {
670 _view_heading = fgGetDouble("/orientation/heading-deg");
672 _view_heading = _Instrument->getFloatValue("heading-up-deg", 0.0);
674 _viewHeadingNode->setDoubleValue(_view_heading);
676 double xCenterFrac = _xCenterNode->getDoubleValue();
677 double yCenterFrac = _yCenterNode->getDoubleValue();
678 int pixelSize = _odg->size();
680 int rangePixels = _Instrument->getIntValue("range-pixels", -1);
681 if (rangePixels < 0) {
682 // hacky - assume (as is very common) that x-frac doesn't vary, and
683 // y-frac is used to position the center at either the top or bottom of
684 // the pixel area. Measure from the center to the furthest edge (top or bottom)
685 rangePixels = pixelSize * std::max(fabs(1.0 - yCenterFrac), fabs(yCenterFrac));
688 _scale = rangePixels / _rangeNm;
689 _Instrument->setDoubleValue("scale", _scale);
692 _centerTrans = osg::Matrixf::translate(xCenterFrac * pixelSize,
693 yCenterFrac * pixelSize, 0.0);
695 // scale from nm to display units, rotate so aircraft heading is up
696 // (as opposed to north), and compensate for centering
697 _projectMat = osg::Matrixf::scale(_scale, _scale, 1.0) *
698 degRotation(-_view_heading) * _centerTrans;
700 if (_userPositionEnable->getBoolValue()) {
701 _pos = SGGeod::fromDeg(_userLonNode->getDoubleValue(), _userLatNode->getDoubleValue());
703 _pos = globals->get_aircraft_position();
706 // invalidate the cache of positioned items, if we travelled more than 1nm
707 if (_cachedItemsValid) {
708 SGVec3d cartNow(SGVec3d::fromGeod(_pos));
709 double movedNm = dist(_cachedPos, cartNow) * SG_METER_TO_NM;
710 _cachedItemsValid = (movedNm < 1.0);
714 _lineVertices->clear();
715 _lineColors->clear();
716 _quadColors->clear();
718 _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
720 BOOST_FOREACH(SymbolInstance* si, _symbols) {
725 BOOST_FOREACH(SymbolDef* d, _definitions) {
726 d->instanceCount = 0;
727 d->textEnabled = d->textEnable.get() ? d->textEnable->test() : true;
730 bool enableChanged = false;
731 BOOST_FOREACH(SymbolRule* r, _rules) {
732 enableChanged |= r->checkEnabled();
736 SG_LOG(SG_INSTR, SG_INFO, "NS rule enables changed, rebuilding cache");
737 _cachedItemsValid = false;
740 if (_testModeNode->getBoolValue()) {
746 processCustomSymbols();
748 limitDisplayedSymbols();
753 _symbolPrimSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
754 _symbolPrimSet->dirty();
755 _linePrimSet->set(osg::PrimitiveSet::LINES, 0, _lineVertices->size());
756 _linePrimSet->dirty();
761 NavDisplay::updateFont()
763 float red = _font_node->getFloatValue("color/red");
764 float green = _font_node->getFloatValue("color/green");
765 float blue = _font_node->getFloatValue("color/blue");
766 float alpha = _font_node->getFloatValue("color/alpha");
767 _font_color.set(red, green, blue, alpha);
769 _font_size = _font_node->getFloatValue("size");
770 _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
771 string path = _font_node->getStringValue("name", DEFAULT_FONT);
774 if (path[0] != '/') {
775 tpath = globals->get_fg_root();
776 tpath.append("Fonts");
782 osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
783 osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
787 _font->setMinFilterHint(osg::Texture::NEAREST);
788 _font->setMagFilterHint(osg::Texture::NEAREST);
789 _font->setGlyphImageMargin(0);
790 _font->setGlyphImageMarginRatio(0);
794 void NavDisplay::addSymbolToScene(SymbolInstance* sym)
796 SymbolDef* def = sym->definition;
800 verts[1] = osg::Vec2(def->xy1.x(), def->xy0.y());
802 verts[3] = osg::Vec2(def->xy0.x(), def->xy1.y());
804 if (def->rotateToHeading) {
805 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
806 for (int i=0; i<4; ++i) {
807 verts[i] = mult(verts[i], m);
811 osg::Vec2 pos = sym->pos;
813 pos = osg::Vec2((int) pos.x(), (int) pos.y());
816 _texCoords->push_back(def->uv0);
817 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->uv0.y()));
818 _texCoords->push_back(def->uv1);
819 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
821 for (int i=0; i<4; ++i) {
822 _vertices->push_back(verts[i] + pos);
823 _quadColors->push_back(def->color);
826 if (def->stretchSymbol) {
827 osg::Vec2 stretchVerts[4];
828 stretchVerts[0] = osg::Vec2(def->xy0.x(), def->stretchY2);
829 stretchVerts[1] = osg::Vec2(def->xy1.x(), def->stretchY2);
830 stretchVerts[2] = osg::Vec2(def->xy1.x(), def->stretchY3);
831 stretchVerts[3] = osg::Vec2(def->xy0.x(), def->stretchY3);
833 osg::Matrixf m(degRotation(sym->headingDeg - _view_heading));
834 for (int i=0; i<4; ++i) {
835 stretchVerts[i] = mult(stretchVerts[i], m);
839 _vertices->push_back(verts[2] + pos);
840 _vertices->push_back(stretchVerts[1] + sym->endPos);
841 _vertices->push_back(stretchVerts[0] + sym->endPos);
842 _vertices->push_back(verts[3] + pos);
844 _texCoords->push_back(def->uv1);
845 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
846 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
847 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->uv1.y()));
849 for (int i=0; i<4; ++i) {
850 _quadColors->push_back(def->color);
853 // quad three, for the end portion
854 for (int i=0; i<4; ++i) {
855 _vertices->push_back(stretchVerts[i] + sym->endPos);
856 _quadColors->push_back(def->color);
859 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV2));
860 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV2));
861 _texCoords->push_back(osg::Vec2(def->uv1.x(), def->stretchV3));
862 _texCoords->push_back(osg::Vec2(def->uv0.x(), def->stretchV3));
866 addLine(sym->pos, sym->endPos, def->lineColor);
869 if (!def->hasText || !def->textEnabled) {
873 osgText::Text* t = new osgText::Text;
874 t->setFont(_font.get());
875 t->setFontResolution(12, 12);
876 t->setCharacterSize(_font_size);
877 t->setLineSpacing(_font_spacing);
878 t->setColor(def->textColor);
879 t->setAlignment(def->alignment);
880 t->setText(sym->text());
883 osg::Vec2 textPos = def->textOffset + pos;
884 // ensure we use ints here, or text visual quality goes bad
885 t->setPosition(osg::Vec3((int)textPos.x(), (int)textPos.y(), 0));
886 _textGeode->addDrawable(t);
889 class OrderByPriority
892 bool operator()(SymbolInstance* a, SymbolInstance* b)
894 return a->definition->priority > b->definition->priority;
898 void NavDisplay::limitDisplayedSymbols()
900 // gloabl symbol limit
901 _maxSymbols= _Instrument->getIntValue("max-symbols", _maxSymbols);
902 if ((int) _symbols.size() <= _maxSymbols) {
903 _excessDataNode->setBoolValue(false);
907 std::sort(_symbols.begin(), _symbols.end(), OrderByPriority());
908 _symbols.resize(_maxSymbols);
909 _excessDataNode->setBoolValue(true);
915 bool operator()(SymbolInstance* a, SymbolInstance* b)
917 return a->definition->zOrder > b->definition->zOrder;
921 void NavDisplay::addSymbolsToScene()
923 std::sort(_symbols.begin(), _symbols.end(), OrderByZ());
924 BOOST_FOREACH(SymbolInstance* sym, _symbols) {
925 addSymbolToScene(sym);
929 void NavDisplay::addLine(osg::Vec2 a, osg::Vec2 b, const osg::Vec4& color)
931 _lineVertices->push_back(a);
932 _lineVertices->push_back(b);
933 _lineColors->push_back(color);
934 _lineColors->push_back(color);
937 osg::Vec2 NavDisplay::projectBearingRange(double bearingDeg, double rangeNm) const
939 osg::Vec3 p(0, rangeNm, 0.0);
940 p = degRotation(bearingDeg).preMult(p);
941 p = _projectMat.preMult(p);
942 return osg::Vec2(p.x(), p.y());
945 osg::Vec2 NavDisplay::projectGeod(const SGGeod& geod) const
947 double rangeM, bearing, az2;
948 SGGeodesy::inverse(_pos, geod, bearing, az2, rangeM);
949 return projectBearingRange(bearing, rangeM * SG_METER_TO_NM);
952 class Filter : public FGPositioned::Filter
955 Filter(NavDisplay* nd) : _owner(nd) { }
957 double minRunwayLengthFt;
959 virtual bool pass(FGPositioned* aPos) const
961 if (aPos->type() == FGPositioned::FIX) {
962 string ident(aPos->ident());
963 // ignore fixes which end in digits
964 if ((ident.size() > 4) && isdigit(ident[3]) && isdigit(ident[4])) {
969 if (aPos->type() == FGPositioned::AIRPORT) {
970 FGAirport* apt = (FGAirport*) aPos;
971 if (!apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
976 // check against current rule states
977 return _owner->isPositionedShown(aPos);
980 virtual FGPositioned::Type minType() const {
981 return FGPositioned::AIRPORT;
984 virtual FGPositioned::Type maxType() const {
985 return FGPositioned::OBSTACLE;
992 void NavDisplay::findItems()
994 if (!_cachedItemsValid) {
996 filt.minRunwayLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
998 _itemsInRange = FGPositioned::findClosestNPartial(_pos, _maxSymbols, _rangeNm,
999 &filt, wasTimeLimited);
1000 _cachedItemsValid = true;
1001 _cachedPos = SGVec3d::fromGeod(_pos);
1003 if (wasTimeLimited) {
1004 // re-query next frame, to load incrementally
1005 _cachedItemsValid = false;
1009 // sort by distance from pos, so symbol limits are accurate
1010 FGPositioned::sortByRange(_itemsInRange, _pos);
1012 BOOST_FOREACH(FGPositioned* pos, _itemsInRange) {
1013 foundPositionedItem(pos);
1017 void NavDisplay::processRoute()
1019 _routeSources.clear();
1020 flightgear::FlightPlan* fp = _route->flightPlan();
1022 int current = _route->currentIndex();
1024 for (int l=0; l<fp->numLegs(); ++l) {
1025 flightgear::FlightPlan::Leg* leg = fp->legAtIndex(l);
1026 flightgear::WayptRef wpt(leg->waypoint());
1027 _routeSources.insert(wpt->source());
1030 state.insert("on-active-route");
1033 state.insert("passed");
1037 state.insert("current-wp");
1041 state.insert("future");
1044 if (l == (current + 1)) {
1045 state.insert("next-wp");
1048 SymbolRuleVector rules;
1049 findRules("waypoint" , state, rules);
1050 if (rules.empty()) {
1051 return; // no rules matched, we can skip this item
1054 SGGeod g = path.positionForIndex(l);
1055 SGPropertyNode* vars = _route->wayptNodeAtIndex(l);
1057 continue; // shouldn't happen, but let's guard against it
1061 computeWayptPropsAndHeading(wpt, g, vars, heading);
1063 osg::Vec2 projected = projectGeod(g);
1064 BOOST_FOREACH(SymbolRule* r, rules) {
1065 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1067 if (r->getDefinition()->drawRouteLeg) {
1068 SGGeodVec gv(path.pathForIndex(l));
1070 osg::Vec2 pr = projectGeod(gv[0]);
1071 for (unsigned int i=1; i<gv.size(); ++i) {
1072 osg::Vec2 p = projectGeod(gv[i]);
1073 addLine(pr, p, r->getDefinition()->lineColor);
1077 } // of leg drawing enabled
1078 } // of matching rules iteration
1079 } // of waypoints iteration
1082 void NavDisplay::computeWayptPropsAndHeading(flightgear::Waypt* wpt, const SGGeod& pos, SGPropertyNode* nd, double& heading)
1085 SGGeodesy::inverse(_pos, pos, heading, az2, rangeM);
1086 nd->setIntValue("radial", heading);
1087 nd->setDoubleValue("distance-nm", rangeM * SG_METER_TO_NM);
1089 heading = nd->getDoubleValue("leg-bearing-true-deg");
1092 void NavDisplay::processNavRadios()
1094 _nav1Station = processNavRadio(_navRadio1Node);
1095 _nav2Station = processNavRadio(_navRadio2Node);
1097 foundPositionedItem(_nav1Station);
1098 foundPositionedItem(_nav2Station);
1101 FGNavRecord* NavDisplay::processNavRadio(const SGPropertyNode_ptr& radio)
1103 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1104 FGNavRecord* nav = FGNavList::findByFreq(mhz, _pos, FGNavList::navFilter());
1105 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1106 // station was not found
1114 bool NavDisplay::anyRuleForType(const string& type) const
1116 BOOST_FOREACH(SymbolRule* r, _rules) {
1121 if (r->type == type) {
1129 void NavDisplay::findRules(const string& type, const string_set& states, SymbolRuleVector& rules)
1131 BOOST_FOREACH(SymbolRule* candidate, _rules) {
1132 if (!candidate->enabled || (candidate->type != type)) {
1136 if (candidate->matches(states)) {
1137 rules.push_back(candidate);
1142 bool NavDisplay::isPositionedShown(FGPositioned* pos)
1144 SymbolRuleVector rules;
1145 isPositionedShownInner(pos, rules);
1146 return !rules.empty();
1149 void NavDisplay::isPositionedShownInner(FGPositioned* pos, SymbolRuleVector& rules)
1151 string type = FGPositioned::nameForType(pos->type());
1152 boost::to_lower(type);
1153 if (!anyRuleForType(type)) {
1154 return; // not diplayed at all, we're done
1158 computePositionedState(pos, states);
1160 findRules(type, states, rules);
1163 void NavDisplay::foundPositionedItem(FGPositioned* pos)
1169 SymbolRuleVector rules;
1170 isPositionedShownInner(pos, rules);
1171 if (rules.empty()) {
1175 SGPropertyNode_ptr vars(new SGPropertyNode);
1177 computePositionedPropsAndHeading(pos, vars, heading);
1179 osg::Vec2 projected = projectGeod(pos->geod());
1180 if (pos->type() == FGPositioned::RUNWAY) {
1181 FGRunway* rwy = (FGRunway*) pos;
1182 projected = projectGeod(rwy->threshold());
1185 BOOST_FOREACH(SymbolRule* r, rules) {
1186 SymbolInstance* ins = addSymbolInstance(projected, heading, r->getDefinition(), vars);
1187 if ((ins)&&(pos->type() == FGPositioned::RUNWAY)) {
1188 FGRunway* rwy = (FGRunway*) pos;
1189 ins->endPos = projectGeod(rwy->end());
1194 void NavDisplay::computePositionedPropsAndHeading(FGPositioned* pos, SGPropertyNode* nd, double& heading)
1196 nd->setStringValue("id", pos->ident());
1197 nd->setStringValue("name", pos->name());
1198 nd->setDoubleValue("elevation-ft", pos->elevation());
1199 nd->setIntValue("heading-deg", 0);
1202 switch (pos->type()) {
1203 case FGPositioned::VOR:
1204 case FGPositioned::LOC:
1205 case FGPositioned::TACAN: {
1206 FGNavRecord* nav = static_cast<FGNavRecord*>(pos);
1207 nd->setDoubleValue("frequency-mhz", nav->get_freq());
1209 if (pos == _nav1Station) {
1210 heading = _navRadio1Node->getDoubleValue("radials/target-radial-deg");
1211 } else if (pos == _nav2Station) {
1212 heading = _navRadio2Node->getDoubleValue("radials/target-radial-deg");
1215 nd->setIntValue("heading-deg", heading);
1219 case FGPositioned::AIRPORT:
1220 case FGPositioned::SEAPORT:
1221 case FGPositioned::HELIPORT:
1225 case FGPositioned::RUNWAY: {
1226 FGRunway* rwy = static_cast<FGRunway*>(pos);
1227 heading = rwy->headingDeg();
1228 nd->setDoubleValue("heading-deg", heading);
1229 nd->setIntValue("length-ft", rwy->lengthFt());
1230 nd->setStringValue("airport", rwy->airport()->ident());
1239 void NavDisplay::computePositionedState(FGPositioned* pos, string_set& states)
1241 if (_routeSources.count(pos) != 0) {
1242 states.insert("on-active-route");
1245 flightgear::FlightPlan* fp = _route->flightPlan();
1246 switch (pos->type()) {
1247 case FGPositioned::VOR:
1248 case FGPositioned::LOC:
1249 if (pos == _nav1Station) {
1250 states.insert("tuned");
1251 states.insert("nav1");
1254 if (pos == _nav2Station) {
1255 states.insert("tuned");
1256 states.insert("nav2");
1260 case FGPositioned::AIRPORT:
1261 case FGPositioned::SEAPORT:
1262 case FGPositioned::HELIPORT:
1264 // once the FMS system has some way to tell us about them, of course
1266 if (pos == fp->departureAirport()) {
1267 states.insert("departure");
1270 if (pos == fp->destinationAirport()) {
1271 states.insert("destination");
1275 case FGPositioned::RUNWAY:
1276 if (pos == fp->departureRunway()) {
1277 states.insert("departure");
1280 if (pos == fp->destinationRunway()) {
1281 states.insert("destination");
1285 case FGPositioned::OBSTACLE:
1287 FGObstacle* obs = (FGObstacle*) pos;
1289 states.insert("lit");
1292 if (obj->getHeightAGLFt() >= 1000) {
1293 states.insert("greater-1000-ft");
1300 } // FGPositioned::Type switch
1303 static string mapAINodeToType(SGPropertyNode* model)
1305 // assume all multiplayer items are aircraft for the moment. Not ideal.
1306 if (!strcmp(model->getName(), "multiplayer")) {
1307 return "ai-aircraft";
1310 return string("ai-") + model->getName();
1313 void NavDisplay::processAI()
1315 SGPropertyNode *ai = fgGetNode("/ai/models", true);
1316 for (int i = ai->nChildren() - 1; i >= 0; i--) {
1317 SGPropertyNode *model = ai->getChild(i);
1318 if (!model->nChildren()) {
1322 // prefix types with 'ai-', to avoid any chance of namespace collisions
1323 // with fg-positioned.
1325 computeAIStates(model, ss);
1326 SymbolRuleVector rules;
1327 findRules(mapAINodeToType(model), ss, rules);
1328 if (rules.empty()) {
1329 return; // no rules matched, we can skip this item
1332 double heading = model->getDoubleValue("orientation/true-heading-deg");
1333 SGGeod aiModelPos = SGGeod::fromDegFt(model->getDoubleValue("position/longitude-deg"),
1334 model->getDoubleValue("position/latitude-deg"),
1335 model->getDoubleValue("position/altitude-ft"));
1336 // compute some additional props
1337 int fl = (aiModelPos.getElevationFt() / 1000);
1338 model->setIntValue("flight-level", fl * 10);
1340 osg::Vec2 projected = projectGeod(aiModelPos);
1341 BOOST_FOREACH(SymbolRule* r, rules) {
1342 addSymbolInstance(projected, heading, r->getDefinition(), (SGPropertyNode*) model);
1344 } // of ai models iteration
1347 void NavDisplay::computeAIStates(const SGPropertyNode* ai, string_set& states)
1349 int threatLevel = ai->getIntValue("tcas/threat-level",-1);
1350 if (threatLevel < 1)
1353 states.insert("tcas");
1355 std::ostringstream os;
1356 os << "tcas-threat-level-" << threatLevel;
1357 states.insert(os.str());
1359 double vspeed = ai->getDoubleValue("velocities/vertical-speed-fps");
1360 if (vspeed < -3.0) {
1361 states.insert("descending");
1362 } else if (vspeed > 3.0) {
1363 states.insert("climbing");
1367 SymbolInstance* NavDisplay::addSymbolInstance(const osg::Vec2& proj, double heading, SymbolDef* def, SGPropertyNode* vars)
1369 if (isProjectedClipped(proj)) {
1373 if ((def->limitCount > 0) && (def->instanceCount >= def->limitCount)) {
1377 ++def->instanceCount;
1378 SymbolInstance* sym = new SymbolInstance(proj, heading, def, vars);
1379 _symbols.push_back(sym);
1383 bool NavDisplay::isProjectedClipped(const osg::Vec2& projected) const
1385 double size = _odg->size();
1386 return (projected.x() < 0.0) ||
1387 (projected.y() < 0.0) ||
1388 (projected.x() >= size) ||
1389 (projected.y() >= size);
1392 void NavDisplay::addTestSymbol(const std::string& type, const std::string& states, const SGGeod& pos, double heading, SGPropertyNode* vars)
1394 string_set stateSet;
1395 BOOST_FOREACH(std::string s, simgear::strutils::split(states, ",")) {
1399 SymbolRuleVector rules;
1400 findRules(type, stateSet, rules);
1401 if (rules.empty()) {
1402 return; // no rules matched, we can skip this item
1405 osg::Vec2 projected = projectGeod(pos);
1406 BOOST_FOREACH(SymbolRule* r, rules) {
1407 addSymbolInstance(projected, heading, r->getDefinition(), vars);
1411 void NavDisplay::addTestSymbols()
1413 _pos = SGGeod::fromDeg(-122.3748889, 37.6189722); // KSFO
1417 SGGeodesy::direct(_pos, 45.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1419 addTestSymbol("airport", "", a1, 0.0, NULL);
1421 SGGeodesy::direct(_pos, 95.0, 40.0 * SG_NM_TO_METER, a1, dummy);
1423 addTestSymbol("vor", "", a1, 0.0, NULL);
1425 SGGeodesy::direct(_pos, 120, 80.0 * SG_NM_TO_METER, a1, dummy);
1427 addTestSymbol("airport", "destination", a1, 0.0, NULL);
1429 SGGeodesy::direct(_pos, 80.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1430 addTestSymbol("fix", "", a1, 0.0, NULL);
1433 SGGeodesy::direct(_pos, 140.0, 20.0 * SG_NM_TO_METER, a1, dummy);
1434 addTestSymbol("fix", "", a1, 0.0, NULL);
1436 SGGeodesy::direct(_pos, 110.0, 10.0 * SG_NM_TO_METER, a1, dummy);
1437 addTestSymbol("fix", "", a1, 0.0, NULL);
1439 SGGeodesy::direct(_pos, 110.0, 5.0 * SG_NM_TO_METER, a1, dummy);
1440 addTestSymbol("fix", "", a1, 0.0, NULL);
1443 void NavDisplay::addRule(SymbolRule* r)
1445 _rules.push_back(r);
1448 void NavDisplay::computeCustomSymbolStates(const SGPropertyNode* sym, string_set& states)
1450 BOOST_FOREACH(SGPropertyNode* st, sym->getChildren("state")) {
1451 states.insert(st->getStringValue());
1455 void NavDisplay::processCustomSymbols()
1457 for (int i = _customSymbols->nChildren() - 1; i >= 0; i--) {
1458 SGPropertyNode *symNode = _customSymbols->getChild(i);
1459 if (!symNode->nChildren()) {
1463 computeCustomSymbolStates(symNode, ss);
1464 SymbolRuleVector rules;
1465 findRules(symNode->getName(), ss, rules);
1466 if (rules.empty()) {
1467 return; // no rules matched, we can skip this item
1470 double heading = symNode->getDoubleValue("true-heading-deg", 0.0);
1471 SGGeod pos = SGGeod::fromDegFt(symNode->getDoubleValue("longitude-deg"),
1472 symNode->getDoubleValue("latitude-deg"),
1473 symNode->getDoubleValue("altitude-ft"));
1476 osg::Vec2 projected = projectGeod(pos);
1477 BOOST_FOREACH(SymbolRule* r, rules) {
1478 addSymbolInstance(projected, heading, r->getDefinition(), symNode);
1480 } // of custom symbols iteration