]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/wxradar.cxx
Fix wxradar to use path resolution
[flightgear.git] / src / Instrumentation / wxradar.cxx
1 // Wx Radar background texture
2 //
3 // Written by Harald JOHNSEN, started May 2005.
4 // With major amendments by Vivian MEAZZA May 2007
5 // Ported to OSG by Tim Moore Jun 2007
6 //
7 //
8 // Copyright (C) 2005  Harald JOHNSEN
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 //
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include <osg/Array>
31 #include <osg/Geometry>
32 #include <osg/Matrixf>
33 #include <osg/PrimitiveSet>
34 #include <osg/StateSet>
35 #include <osg/Version>
36 #include <osgDB/ReaderWriter>
37 #include <osgDB/WriteFile>
38
39 #include <simgear/constants.h>
40 #include <simgear/misc/sg_path.hxx>
41 #include <simgear/environment/visual_enviro.hxx>
42 #include <simgear/scene/model/model.hxx>
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/math/sg_geodesy.hxx>
46
47 #include <sstream>
48 #include <iomanip>
49 using std::stringstream;
50 using std::endl;
51 using std::setprecision;
52 using std::fixed;
53 using std::setw;
54 using std::setfill;
55
56 #include <Main/fg_props.hxx>
57 #include <Main/globals.hxx>
58 #include <Cockpit/panel.hxx>
59 #include <Cockpit/hud.hxx>
60
61 #include "instrument_mgr.hxx"
62 #include "od_gauge.hxx"
63 #include "wxradar.hxx"
64
65 #include <iostream>             // for cout, endl
66
67 using std::cout;
68 using std::endl;
69
70 static const float UNIT = 1.0f / 8.0f;  // 8 symbols in a row/column in the texture
71 static const char *DEFAULT_FONT = "typewriter.txf";
72
73
74 wxRadarBg::wxRadarBg(SGPropertyNode *node) :
75     _name(node->getStringValue("name", "radar")),
76     _num(node->getIntValue("number", 0)),
77     _time(0.0),
78     _interval(node->getDoubleValue("update-interval-sec", 1.0)),
79     _sim_init_done(false),
80     _odg(0),
81     _last_switchKnob("off"),
82     _antenna_ht(node->getDoubleValue("antenna-ht-ft", 0.0)),
83     _resultTexture(0),
84     _wxEcho(0)
85 {
86     string branch;
87     branch = "/instrumentation/" + _name;
88     _Instrument = fgGetNode(branch.c_str(), _num, true);
89
90     const char *tacan_source = node->getStringValue("tacan-source", "/instrumentation/tacan");
91     _Tacan = fgGetNode(tacan_source, true);
92
93     _font_node = _Instrument->getNode("font", true);
94
95 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
96     INITFONT("name", DEFAULT_FONT, String);
97     INITFONT("size", 8, Float);
98     INITFONT("line-spacing", 0.25, Float);
99     INITFONT("color/red", 0, Float);
100     INITFONT("color/green", 0.8, Float);
101     INITFONT("color/blue", 0, Float);
102     INITFONT("color/alpha", 1, Float);
103 #undef INITFONT
104
105     _font_node->addChangeListener(this, true);
106 }
107
108
109 wxRadarBg::~wxRadarBg ()
110 {
111     _font_node->removeChangeListener(this);
112 }
113
114
115 void
116 wxRadarBg::init ()
117 {
118     _serviceable_node = _Instrument->getNode("serviceable", true);
119
120     // texture name to use in 2D and 3D instruments
121     _texture_path = _Instrument->getStringValue("radar-texture-path",
122         "Aircraft/Instruments/Textures/od_wxradar.rgb");
123     _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
124
125     string path = _Instrument->getStringValue("echo-texture-path",
126         "Aircraft/Instruments/Textures/wxecho.rgb");
127     SGPath tpath = globals->resolve_aircraft_path(path);
128
129     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
130     _wxEcho = SGLoadTexture2D(tpath, false, false);
131
132
133     _Instrument->setFloatValue("trk", 0.0);
134     _Instrument->setFloatValue("tilt", 0.0);
135     _Instrument->setStringValue("status", "");
136     // those properties are used by a radar instrument of a MFD
137     // input switch = OFF | TST | STBY | ON
138     // input mode = WX | WXA | MAP
139     // output status = STBY | TEST | WX | WXA | MAP | blank
140     // input lightning = true | false
141     // input TRK = +/- n degrees
142     // input TILT = +/- n degree
143     // input autotilt = true | false
144     // input range = n nm (20/40/80)
145     // input display-mode = arc | rose | map | plan
146
147     FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
148     _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
149     _odg->setSize(512);
150
151     _ai_enabled_node = fgGetNode("/sim/ai/enabled", true);
152
153     _user_lat_node = fgGetNode("/position/latitude-deg", true);
154     _user_lon_node = fgGetNode("/position/longitude-deg", true);
155     _user_alt_node = fgGetNode("/position/altitude-ft", true);
156
157     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
158     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
159
160     _tacan_serviceable_node = _Tacan->getNode("serviceable", true);
161     _tacan_distance_node    = _Tacan->getNode("indicated-distance-nm", true);
162     _tacan_name_node        = _Tacan->getNode("name", true);
163     _tacan_bearing_node     = _Tacan->getNode("indicated-bearing-true-deg", true);
164     _tacan_in_range_node    = _Tacan->getNode("in-range", true);
165
166     _radar_mode_control_node = _Instrument->getNode("mode-control", true);
167     _radar_coverage_node     = _Instrument->getNode("limit-deg", true);
168     _radar_ref_rng_node      = _Instrument->getNode("reference-range-nm", true);
169     _radar_hdg_marker_node   = _Instrument->getNode("heading-marker", true);
170
171     SGPropertyNode *n = _Instrument->getNode("display-controls", true);
172     _radar_weather_node     = n->getNode("WX", true);
173     _radar_position_node    = n->getNode("pos", true);
174     _radar_data_node        = n->getNode("data", true);
175     _radar_symbol_node      = n->getNode("symbol", true);
176     _radar_centre_node      = n->getNode("centre", true);
177     _radar_rotate_node      = n->getNode("rotate", true);
178
179     _radar_centre_node->setBoolValue(false);
180     if (!_radar_coverage_node->hasValue())
181         _radar_coverage_node->setFloatValue(120);
182     if (!_radar_ref_rng_node->hasValue())
183         _radar_ref_rng_node->setDoubleValue(35);
184     if (!_radar_hdg_marker_node->hasValue())
185         _radar_hdg_marker_node->setBoolValue(true);
186
187     _x_offset = 0;
188     _y_offset = 0;
189
190     // OSG geometry setup. The polygons for the radar returns will be
191     // stored in a single Geometry. The geometry will have several
192     // primitive sets so we can have different kinds of polys and
193     // choose a different overall color for each set.
194     _radarGeode = new osg::Geode;
195     osg::StateSet *stateSet = _radarGeode->getOrCreateStateSet();
196     stateSet->setTextureAttributeAndModes(0, _wxEcho.get());
197     _geom = new osg::Geometry;
198     _geom->setUseDisplayList(false);
199     // Initially allocate space for 128 quads
200     _vertices = new osg::Vec2Array;
201     _vertices->setDataVariance(osg::Object::DYNAMIC);
202     _vertices->reserve(128 * 4);
203     _geom->setVertexArray(_vertices);
204     _texCoords = new osg::Vec2Array;
205     _texCoords->setDataVariance(osg::Object::DYNAMIC);
206     _texCoords->reserve(128 * 4);
207     _geom->setTexCoordArray(0, _texCoords);
208     osg::Vec3Array *colors = new osg::Vec3Array;
209     colors->push_back(osg::Vec3(1.0f, 1.0f, 1.0f)); // color of echos
210     colors->push_back(osg::Vec3(1.0f, 0.0f, 0.0f)); // arc mask
211     colors->push_back(osg::Vec3(0.0f, 0.0f, 0.0f)); // rest of mask
212     _geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
213     _geom->setColorArray(colors);
214     osg::PrimitiveSet *pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
215     pset->setDataVariance(osg::Object::DYNAMIC);
216     _geom->addPrimitiveSet(pset);
217     pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
218     pset->setDataVariance(osg::Object::DYNAMIC);
219     _geom->addPrimitiveSet(pset);
220     pset = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES);
221     pset->setDataVariance(osg::Object::DYNAMIC);
222     _geom->addPrimitiveSet(pset);
223     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
224         osg::Vec3f(256.0f, 256.0f, 0.0f)));
225     _radarGeode->addDrawable(_geom);
226     _odg->allocRT();
227     // Texture in the 2D panel system
228     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
229
230     _textGeode = new osg::Geode;
231
232     osg::Camera *camera = _odg->getCamera();
233     camera->addChild(_radarGeode.get());
234     camera->addChild(_textGeode.get());
235 }
236
237
238 // Local coordinates for each echo
239 const osg::Vec3f echoCoords[4] = {
240     osg::Vec3f(-.7f, -.7f, 0.0f), osg::Vec3f(.7f, -.7f, 0.0f),
241     osg::Vec3f(.7f, .7f, 0.0f), osg::Vec3f(-.7f, .7f, 0.0f)
242 };
243
244
245 const osg::Vec2f echoTexCoords[4] = {
246     osg::Vec2f(0.0f, 0.0f), osg::Vec2f(UNIT, 0.0f),
247     osg::Vec2f(UNIT, UNIT), osg::Vec2f(0.0f, UNIT)
248 };
249
250
251 // helper
252 static void
253 addQuad(osg::Vec2Array *vertices, osg::Vec2Array *texCoords,
254         const osg::Matrixf& transform, const osg::Vec2f& texBase)
255 {
256     for (int i = 0; i < 4; i++) {
257         const osg::Vec3f coords = transform.preMult(echoCoords[i]);
258         texCoords->push_back(texBase + echoTexCoords[i]);
259         vertices->push_back(osg::Vec2f(coords.x(), coords.y()));
260     }
261 }
262
263
264 // Rotate by a heading value
265 static inline
266 osg::Matrixf wxRotate(float angle)
267 {
268     return osg::Matrixf::rotate(angle, 0.0f, 0.0f, -1.0f);
269 }
270
271
272 void
273 wxRadarBg::update (double delta_time_sec)
274 {
275     if (!_sim_init_done) {
276         if (!fgGetBool("sim/sceneryloaded", false))
277             return;
278
279         _sim_init_done = true;
280     }
281     if (!_odg || !_serviceable_node->getBoolValue()) {
282         _Instrument->setStringValue("status", "");
283         return;
284     }
285     _time += delta_time_sec;
286     if (_time < _interval){
287 //        cout << "WXradar update too soon " << _time << endl;
288         return;
289     }
290 //        cout << "WXradar updating" << _time<< endl;
291
292     _time = 0.0;
293
294     string mode = _Instrument->getStringValue("display-mode", "arc");
295     if (mode == "map") {
296         if (_display_mode != MAP) {
297             _display_mode = MAP;
298             center_map();
299         }
300     } else if (mode == "plan") {
301         _display_mode = PLAN;}
302     else if (mode == "bscan") {
303         _display_mode = BSCAN;
304     } else {
305         _display_mode = ARC;
306     }
307
308     string switchKnob = _Instrument->getStringValue("switch", "on");
309     if (_last_switchKnob != switchKnob) {
310         // since 3D models don't share textures with the rest of the world
311         // we must locate them and replace their handle by hand
312         // only do that when the instrument is turned on
313         //if (_last_switchKnob == "off")
314         //_odg->set_texture(_texture_path.c_str(), _resultTexture->getHandle());
315
316         _last_switchKnob = switchKnob;
317     }
318
319     if (switchKnob == "off") {
320         _Instrument->setStringValue("status", "");
321     } else if (switchKnob == "stby") {
322         _Instrument->setStringValue("status", "STBY");
323     } else if (switchKnob == "tst") {
324         _Instrument->setStringValue("status", "TST");
325         // find something interesting to do...
326     } else {
327         float r = _Instrument->getFloatValue("range", 40.0);
328         if (r != _range_nm) {
329             center_map();
330             _range_nm = r;
331         }
332
333         _radar_ref_rng = _radar_ref_rng_node->getDoubleValue();
334         _view_heading = get_heading() * SG_DEGREES_TO_RADIANS;
335         _centerTrans.makeTranslate(0.0f, 0.0f, 0.0f);
336
337         _scale = 200.0 / _range_nm;
338         _angle_offset = 0;
339
340         if (_display_mode == ARC) {
341             _scale = 2*200.0f / _range_nm;
342             _angle_offset = -_view_heading;
343             _centerTrans.makeTranslate(0.0f, -200.0f, 0.0f);
344
345         } else if (_display_mode == MAP) {
346             apply_map_offset();
347
348             bool centre = _radar_centre_node->getBoolValue();
349             if (centre) {
350                 center_map();
351                 _radar_centre_node->setBoolValue(false);
352             }
353
354             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: displacement "
355             //        << _x_offset <<", "<<_y_offset
356             //        << " user_speed_east_fps * SG_FPS_TO_KT "
357             //        << user_speed_east_fps * SG_FPS_TO_KT
358             //        << " user_speed_north_fps * SG_FPS_TO_KT "
359             //        << user_speed_north_fps * SG_FPS_TO_KT
360             //        << " dt " << delta_time_sec);
361
362             _centerTrans.makeTranslate(_x_offset, _y_offset, 0.0f);
363
364         } else if (_display_mode == PLAN) {
365             if (_radar_rotate_node->getBoolValue()) {
366                 _angle_offset = -_view_heading;
367             }
368         } else if (_display_mode == BSCAN) {
369             _angle_offset = -_view_heading;
370         } else {
371             // rose
372         }
373
374         _vertices->clear();
375         _texCoords->clear();
376         _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
377
378
379         update_weather();
380
381
382         osg::DrawArrays *quadPSet
383             = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(0));
384         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
385         quadPSet->dirty();
386
387         // erase what is out of sight of antenna
388         /*
389         |\     /|
390         | \   / |
391         |  \ /  |
392         ---------
393         |       |
394         |       |
395         ---------
396         */
397
398         osg::DrawArrays *maskPSet
399             = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(1));
400         osg::DrawArrays *trimaskPSet
401             = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(2));
402
403         if (_display_mode == ARC) {
404             float xOffset = 256.0f;
405             float yOffset = 200.0f;
406
407             int firstQuadVert = _vertices->size();
408             _texCoords->push_back(osg::Vec2f(0.5f, 0.25f));
409             _vertices->push_back(osg::Vec2f(-xOffset, 0.0 + yOffset));
410             _texCoords->push_back(osg::Vec2f(1.0f, 0.25f));
411             _vertices->push_back(osg::Vec2f(xOffset, 0.0 + yOffset));
412             _texCoords->push_back(osg::Vec2f(1.0f, 0.5f));
413             _vertices->push_back(osg::Vec2f(xOffset, 256.0 + yOffset));
414             _texCoords->push_back(osg::Vec2f(0.5f, 0.5f));
415             _vertices->push_back(osg::Vec2f(-xOffset, 256.0 + yOffset));
416             maskPSet->set(osg::PrimitiveSet::QUADS, firstQuadVert, 4);
417
418             // The triangles aren't supposed to be textured, but there's
419             // no need to set up a different Geometry, switch modes,
420             // etc. I happen to know that there's a white pixel in the
421             // texture at 1.0, 0.0 :)
422             float centerY = tan(30 * SG_DEGREES_TO_RADIANS);
423             _vertices->push_back(osg::Vec2f(0.0, 0.0));
424             _vertices->push_back(osg::Vec2f(-256.0, 0.0));
425             _vertices->push_back(osg::Vec2f(-256.0, 256.0 * centerY));
426
427             _vertices->push_back(osg::Vec2f(0.0, 0.0));
428             _vertices->push_back(osg::Vec2f(256.0, 0.0));
429             _vertices->push_back(osg::Vec2f(256.0, 256.0 * centerY));
430
431             _vertices->push_back(osg::Vec2f(-256, 0.0));
432             _vertices->push_back(osg::Vec2f(256.0, 0.0));
433             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
434
435             _vertices->push_back(osg::Vec2f(256, 0.0));
436             _vertices->push_back(osg::Vec2f(256.0, -256.0));
437             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
438
439             const osg::Vec2f whiteSpot(1.0f, 0.0f);
440             for (int i = 0; i < 3 * 4; i++)
441                 _texCoords->push_back(whiteSpot);
442
443             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, firstQuadVert + 4, 3 * 4);
444
445         } else {
446             maskPSet->set(osg::PrimitiveSet::QUADS, 0, 0);
447             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, 0, 0);
448         }
449
450         maskPSet->dirty();
451         trimaskPSet->dirty();
452
453         // draw without mask
454         _vertices->clear();
455         _texCoords->clear();
456
457         update_aircraft();
458         update_tacan();
459         update_heading_marker();
460
461         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
462         quadPSet->dirty();
463     }
464 }
465
466
467 void
468 wxRadarBg::update_weather()
469 {
470     string modeButton = _Instrument->getStringValue("mode", "WX");
471     _radarEchoBuffer = *sgEnviro.get_radar_echo();
472
473     // pretend we have a scan angle bigger then the FOV
474     // TODO:check real fov, enlarge if < nn, and do clipping if > mm
475 //    const float fovFactor = 1.45f;
476     _Instrument->setStringValue("status", modeButton.c_str());
477
478     list_of_SGWxRadarEcho *radarEcho = &_radarEchoBuffer;
479     list_of_SGWxRadarEcho::iterator iradarEcho, end = radarEcho->end();
480     const float LWClevel[] = { 0.1f, 0.5f, 2.1f };
481
482     // draw the cloud radar echo
483     bool drawClouds = _radar_weather_node->getBoolValue();
484     if (drawClouds) {
485
486         // we do that in 3 passes, one for each color level
487         // this is to 'merge' same colors together
488         for (int level = 0; level <= 2; level++) {
489             float col = level * UNIT;
490
491             for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
492                 int cloudId = iradarEcho->cloudId;
493                 bool upgrade = (cloudId >> 5) & 1;
494                 float lwc = iradarEcho->LWC + (upgrade ? 1.0f : 0.0f);
495
496                 // skip ns
497                 if (iradarEcho->LWC >= 0.5 && iradarEcho->LWC <= 0.6)
498                     continue;
499
500                 if (iradarEcho->lightning || lwc < LWClevel[level])
501                     continue;
502
503                 float radius = sgSqrt(iradarEcho->dist) * SG_METER_TO_NM * _scale;
504                 float size = iradarEcho->radius * 2.0 * SG_METER_TO_NM * _scale;
505
506                 if (radius - size > 180)
507                     continue;
508
509                 float angle = (iradarEcho->heading - _angle_offset) //* fovFactor
510                     + 0.5 * SG_PI;
511
512                 // Rotate echo into position, and rotate echo to have
513                 // a constant orientation towards the
514                 // airplane. Compass headings increase in clockwise
515                 // direction, while graphics rotations follow
516                 // right-hand (counter-clockwise) rule.
517                 const osg::Vec2f texBase(col, (UNIT * (float) (4 + (cloudId & 3))));
518
519                 osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
520                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
521                     * wxRotate(angle) * _centerTrans);
522                 addQuad(_vertices, _texCoords, m, texBase);
523
524                 //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: drawing clouds"
525                 //        << " ID=" << cloudId
526                 //        << " x=" << x
527                 //        << " y="<< y
528                 //        << " radius=" << radius
529                 //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
530                 //        << " heading=" << iradarEcho->heading * SG_RADIANS_TO_DEGREES
531                 //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
532             }
533         }
534     }
535
536     // draw lightning echos
537     bool drawLightning = _Instrument->getBoolValue("lightning", true);
538     if (drawLightning) {
539         const osg::Vec2f texBase(3 * UNIT, 4 * UNIT);
540
541         for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
542             if (!iradarEcho->lightning)
543                 continue;
544
545             float size = UNIT * 0.5f;
546             float radius = iradarEcho->dist * _scale;
547             float angle = iradarEcho->heading * SG_DEGREES_TO_RADIANS
548                 - _angle_offset;
549
550             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
551                 * wxRotate(-angle)
552                 * osg::Matrixf::translate(0.0f, radius, 0.0f)
553                 * wxRotate(angle) * _centerTrans);
554             addQuad(_vertices, _texCoords, m, texBase);
555         }
556     }
557 }
558
559
560 void
561 wxRadarBg::update_data(const SGPropertyNode *ac, double altitude, double heading,
562                        double radius, double bearing, bool selected)
563 {
564     osgText::Text *callsign = new osgText::Text;
565     callsign->setFont(_font.get());
566     callsign->setFontResolution(12, 12);
567     callsign->setCharacterSize(_font_size);
568     callsign->setColor(selected ? osg::Vec4(1, 1, 1, 1) : _font_color);
569     osg::Matrixf m(wxRotate(-bearing)
570         * osg::Matrixf::translate(0.0f, radius, 0.0f)
571         * wxRotate(bearing) * _centerTrans);
572
573     osg::Vec3 pos = m.preMult(osg::Vec3(16, 16, 0));
574     // cast to int's, otherwise text comes out ugly
575     callsign->setPosition(osg::Vec3((int)pos.x(), (int)pos.y(), 0));
576     callsign->setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE);
577     callsign->setLineSpacing(_font_spacing);
578
579     const char *identity = ac->getStringValue("transponder-id");
580     if (!identity[0])
581         identity = ac->getStringValue("callsign");
582
583     stringstream text;
584     text << identity << endl
585         << setprecision(0) << fixed
586         << setw(3) << setfill('0') << heading * SG_RADIANS_TO_DEGREES << "\xB0 "
587         << setw(0) << altitude << "ft" << endl
588         << ac->getDoubleValue("velocities/true-airspeed-kt") << "kts";
589
590     callsign->setText(text.str());
591     _textGeode->addDrawable(callsign);
592 }
593
594
595 void
596 wxRadarBg::update_aircraft()
597 {
598     double diff;
599     double age_factor = 1.0;
600     double test_rng;
601     double test_brg;
602     double range;
603     double bearing;
604     float echo_radius;
605     double angle;
606
607     if (!ground_echoes.empty()){
608         ground_echoes_iterator = ground_echoes.begin();
609
610         while(ground_echoes_iterator != ground_echoes.end()) {
611             diff = _elapsed_time - (*ground_echoes_iterator)->elapsed_time;
612
613             if( diff > _persistance) {
614                 ground_echoes.erase(ground_echoes_iterator);
615             } else {
616 //                double test_brg = (*ground_echoes_iterator)->bearing;
617 //                double bearing = test_brg * SG_DEGREES_TO_RADIANS;
618 //                float angle = calcRelBearing(bearing, _view_heading);
619                 double bumpinessFactor  = (*ground_echoes_iterator)->bumpiness;
620                 float heading = get_heading();
621                 if ( _display_mode == BSCAN ){
622                     test_rng = (*ground_echoes_iterator)->elevation * 6;
623                     test_brg = (*ground_echoes_iterator)->bearing;
624                     angle = calcRelBearingDeg(test_brg, heading) * 6;
625                     range = sqrt(test_rng * test_rng + angle * angle);
626                     bearing = atan2(angle, test_rng);
627                     //cout << "angle " << angle <<" bearing "
628                     //    << bearing / SG_DEGREES_TO_RADIANS <<  endl;
629                     echo_radius = (0.1 + (1.9 * bumpinessFactor)) * 240 * age_factor;
630                 } else {
631                     test_rng = (*ground_echoes_iterator)->range;
632                     range = test_rng * SG_METER_TO_NM;
633                     test_brg = (*ground_echoes_iterator)->bearing;
634                     bearing = test_brg * SG_DEGREES_TO_RADIANS;
635                     echo_radius = (0.1 + (1.9 * bumpinessFactor)) * 120 * age_factor;
636                     bearing += _angle_offset;
637                 }
638
639                 float radius = range * _scale;
640                 //double heading = 90 * SG_DEGREES_TO_RADIANS;
641                 //heading += _angle_offset;
642
643                 age_factor = 1;
644
645                 if (diff != 0)
646                     age_factor = 1 - (0.5 * diff/_persistance);
647
648                 float size = echo_radius * UNIT;
649
650                 const osg::Vec2f texBase(3 * UNIT, 3 * UNIT);
651                 osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
652                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
653                     * wxRotate(bearing) * _centerTrans);
654                 addQuad(_vertices, _texCoords, m, texBase);
655
656                 ++ground_echoes_iterator;
657
658                 //cout << "test bearing " << test_brg 
659                 //<< " test_rng " << test_rng * SG_METER_TO_NM
660                 //<< " persistance " << _persistance
661                 //<< endl;
662             }
663
664         }
665
666     }
667     if (!_ai_enabled_node->getBoolValue())
668         return;
669
670     bool draw_echoes = _radar_position_node->getBoolValue();
671     bool draw_symbols = _radar_symbol_node->getBoolValue();
672     bool draw_data = _radar_data_node->getBoolValue();
673     if (!draw_echoes && !draw_symbols && !draw_data)
674         return;
675
676     double user_lat = _user_lat_node->getDoubleValue();
677     double user_lon = _user_lon_node->getDoubleValue();
678     double user_alt = _user_alt_node->getDoubleValue();
679
680     float limit = _radar_coverage_node->getFloatValue();
681     if (limit > 180)
682         limit = 180;
683     else if (limit < 0)
684         limit = 0;
685     limit *= SG_DEGREES_TO_RADIANS;
686
687     int selected_id = fgGetInt("/instrumentation/radar/selected-id", -1);
688
689     const SGPropertyNode *selected_ac = 0;
690     const SGPropertyNode *ai = fgGetNode("/ai/models", true);
691
692     for (int i = ai->nChildren() - 1; i >= -1; i--) {
693         const SGPropertyNode *model;
694
695         if (i < 0) { // last iteration: selected model
696             model = selected_ac;
697         } else {
698             model = ai->getChild(i);
699             if (!model->nChildren())
700                 continue;
701             if (model->getIntValue("id") == selected_id) {
702                 selected_ac = model;  // save selected model for last iteration
703                 continue;
704             }
705         }
706         if (!model)
707             continue;
708
709         double echo_radius, sigma;
710         const string name = model->getName();
711
712         //cout << "name "<<name << endl;
713         if (name == "aircraft" || name == "tanker")
714             echo_radius = 1, sigma = 1;
715         else if (name == "multiplayer" || name == "wingman" || name == "static")
716             echo_radius = 1.5, sigma = 1;
717         else if (name == "ship" || name == "carrier" || name == "escort" ||name == "storm")
718             echo_radius = 1.5, sigma = 100;
719         else if (name == "thermal")
720             echo_radius = 2, sigma = 100;
721         else if (name == "rocket")
722             echo_radius = 0.1, sigma = 0.1;
723         else if (name == "ballistic")
724             echo_radius = 0.001, sigma = 0.001;
725         else
726             continue;
727
728         double lat = model->getDoubleValue("position/latitude-deg");
729         double lon = model->getDoubleValue("position/longitude-deg");
730         double alt = model->getDoubleValue("position/altitude-ft");
731         double heading = model->getDoubleValue("orientation/true-heading-deg");
732
733         double range, bearing;
734         calcRangeBearing(user_lat, user_lon, lat, lon, range, bearing);
735         //cout << _antenna_ht << _interval<< endl;
736         bool isVisible = withinRadarHorizon(user_alt, alt, range);
737
738         if (!isVisible)
739             continue;
740
741         if (!inRadarRange(sigma, range))
742             continue;
743
744         bearing *= SG_DEGREES_TO_RADIANS;
745         heading *= SG_DEGREES_TO_RADIANS;
746
747         float radius = range * _scale;
748         float angle = calcRelBearing(bearing, _view_heading);
749
750         if (angle > limit || angle < -limit)
751             continue;
752
753         bearing += _angle_offset;
754         heading += _angle_offset;
755
756         // pos mode
757         if (draw_echoes) {
758             float size = echo_radius * 120 * UNIT;
759
760             const osg::Vec2f texBase(3 * UNIT, 3 * UNIT);
761             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
762                 * osg::Matrixf::translate(0.0f, radius, 0.0f)
763                 * wxRotate(bearing) * _centerTrans);
764             addQuad(_vertices, _texCoords, m, texBase);
765         }
766
767         // data mode
768         if (draw_symbols) {
769             const osg::Vec2f texBase(0, 3 * UNIT);
770             float size = 600 * UNIT;
771             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
772                 * wxRotate(heading - bearing)
773                 * osg::Matrixf::translate(0.0f, radius, 0.0f)
774                 * wxRotate(bearing) * _centerTrans);
775             addQuad(_vertices, _texCoords, m, texBase);
776         }
777
778         if (draw_data || i < 0)  // selected one (i == -1) is always drawn
779             update_data(model, alt, heading, radius, bearing, i < 0);
780     }
781 }
782
783
784 void
785 wxRadarBg::update_tacan()
786 {
787     // draw TACAN symbol
788     int mode = _radar_mode_control_node->getIntValue();
789     bool inRange = _tacan_in_range_node->getBoolValue();
790
791     if (mode != 1 || !inRange)
792         return;
793
794     float size = 600 * UNIT;
795     float radius = _tacan_distance_node->getFloatValue() * _scale;
796     float angle = _tacan_bearing_node->getFloatValue() * SG_DEGREES_TO_RADIANS
797         + _angle_offset;
798
799     const osg::Vec2f texBase(1 * UNIT, 3 * UNIT);
800     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
801         * wxRotate(-angle)
802         * osg::Matrixf::translate(0.0f, radius, 0.0f)
803         * wxRotate(angle) * _centerTrans);
804     addQuad(_vertices, _texCoords, m, texBase);
805
806     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:     drawing TACAN"
807     //        << " dist=" << radius
808     //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
809     //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
810     //        << " x=" << x << " y="<< y
811     //        << " size=" << size);
812 }
813
814
815 void
816 wxRadarBg::update_heading_marker()
817 {
818     if (!_radar_hdg_marker_node->getBoolValue())
819         return;
820
821     const osg::Vec2f texBase(2 * UNIT, 3 * UNIT);
822     float size = 600 * UNIT;
823     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
824         * wxRotate(_view_heading + _angle_offset));
825
826     m *= _centerTrans;
827     addQuad(_vertices, _texCoords, m, texBase);
828
829     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:   drawing heading marker"
830     //        << " x,y " << x <<","<< y
831     //        << " dist" << dist
832     //        << " view_heading" << _view_heading * SG_RADIANS_TO_DEGREES
833     //        << " heading " << iradarEcho->heading * SG_RADIANS_TO_DEGREES
834     //        << " angle " << angle * SG_RADIANS_TO_DEGREES);
835 }
836
837
838 void
839 wxRadarBg::center_map()
840 {
841     _lat = _user_lat_node->getDoubleValue();
842     _lon = _user_lon_node->getDoubleValue();
843     _x_offset = _y_offset = 0;
844 }
845
846
847 void
848 wxRadarBg::apply_map_offset()
849 {
850     double lat = _user_lat_node->getDoubleValue();
851     double lon = _user_lon_node->getDoubleValue();
852     double bearing, distance, az2;
853     geo_inverse_wgs_84(_lat, _lon, lat, lon, &bearing, &az2, &distance);
854     distance *= SG_METER_TO_NM * _scale;
855     bearing *= SG_DEGREES_TO_RADIANS;
856     _x_offset += sin(bearing) * distance;
857     _y_offset += cos(bearing) * distance;
858     _lat = lat;
859     _lon = lon;
860 }
861
862
863 bool
864 wxRadarBg::withinRadarHorizon(double user_alt, double alt, double range_nm)
865 {
866     // Radar Horizon  = 1.23(ht^1/2 + hr^1/2),
867     //don't allow negative altitudes (an approximation - yes altitudes can be negative)
868     // Allow antenna ht to be set, but only on ground
869     _antenna_ht = _Instrument->getDoubleValue("antenna-ht-ft");
870
871     if (user_alt <= 0)
872         user_alt = _antenna_ht;
873
874     if (alt <= 0)
875         alt = 0; // to allow some vertical extent of target
876
877     double radarhorizon = 1.23 * (sqrt(alt) + sqrt(user_alt));
878 //    SG_LOG(SG_GENERAL, SG_ALERT, "Radar: radar horizon " << radarhorizon);
879     return radarhorizon >= range_nm;
880 }
881
882
883 bool
884 wxRadarBg::inRadarRange(double sigma, double range_nm)
885 {
886     //The Radar Equation:
887     //
888     // MaxRange^4 = (TxPower * AntGain^2 * lambda^2 * sigma)/((constant) * MDS)
889     //
890     // Where (constant) = (4*pi)3 and MDS is the Minimum Detectable Signal power.
891     //
892     // For a given radar we can assume that the only variable is sigma,
893     // the target radar cross section.
894     //
895     // Here, we will use a normalised rcs (sigma) for a standard taget and assume that this
896     // will provide a maximum range of 35nm;
897     //
898     // TODO - make the maximum range adjustable at runtime
899
900     double constant = _radar_ref_rng;
901
902     if (constant <= 0)
903         constant = 35;
904
905     double maxrange = constant * pow(sigma, 0.25);
906     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: max range " << maxrange);
907     return maxrange >= range_nm;
908 }
909
910
911 void
912 wxRadarBg::calcRangeBearing(double lat, double lon, double lat2, double lon2,
913                             double &range, double &bearing) const
914 {
915     // calculate the bearing and range of the second pos from the first
916     double az2, distance;
917     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
918     range = distance *= SG_METER_TO_NM;
919 }
920
921
922 float
923 wxRadarBg::calcRelBearing(float bearing, float heading)
924 {
925     float angle = bearing - heading;
926
927     if (angle >= SG_PI)
928         angle -= 2.0 * SG_PI;
929
930     if (angle < -SG_PI)
931         angle += 2.0 * SG_PI;
932
933     return angle;
934 }
935
936 float
937 wxRadarBg::calcRelBearingDeg(float bearing, float heading)
938 {
939     float angle = bearing - heading;
940
941     if (angle >= 180)
942         return angle -= 360;
943
944     if (angle < -180)
945         return angle += 360;
946
947     return angle;
948 }
949
950
951 void
952 wxRadarBg::updateFont()
953 {
954     float red = _font_node->getFloatValue("color/red");
955     float green = _font_node->getFloatValue("color/green");
956     float blue = _font_node->getFloatValue("color/blue");
957     float alpha = _font_node->getFloatValue("color/alpha");
958     _font_color.set(red, green, blue, alpha);
959
960     _font_size = _font_node->getFloatValue("size");
961     _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
962     string path = _font_node->getStringValue("name", DEFAULT_FONT);
963
964     SGPath tpath;
965     if (path[0] != '/') {
966         tpath = globals->get_fg_root();
967         tpath.append("Fonts");
968         tpath.append(path);
969     } else {
970         tpath = path;
971     }
972
973 #if (FG_OSG_VERSION >= 21000)
974     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
975     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
976 #else
977     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str());
978 #endif
979
980     if (font != 0) {
981         _font = font;
982         _font->setMinFilterHint(osg::Texture::NEAREST);
983         _font->setMagFilterHint(osg::Texture::NEAREST);
984         _font->setGlyphImageMargin(0);
985         _font->setGlyphImageMarginRatio(0);
986     }
987 }
988
989 void
990 wxRadarBg::valueChanged(SGPropertyNode*)
991 {
992     updateFont();
993 }
994