]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/wxradar.cxx
30680b9d2898391267cac2fe71b6c02752172ff6
[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 SG_USING_STD(stringstream);
50 SG_USING_STD(endl);
51 SG_USING_STD(setprecision);
52 SG_USING_STD(fixed);
53 SG_USING_STD(setw);
54 SG_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 #include <AIModel/AIBase.hxx>
61 #include <AIModel/AIManager.hxx>
62 #include <AIModel/AIBallistic.hxx>
63
64 #include <Include/general.hxx>
65 #include "instrument_mgr.hxx"
66 #include "od_gauge.hxx"
67 #include "wxradar.hxx"
68
69
70 typedef list <osg::ref_ptr<FGAIBase> > radar_list_type;
71 typedef radar_list_type::iterator radar_list_iterator;
72 typedef radar_list_type::const_iterator radar_list_const_iterator;
73
74
75 static const float UNIT = 1.0f / 8.0f;  // 8 symbols in a row/column in the texture
76 static const char *DEFAULT_FONT = "typewriter.txf";
77
78
79 wxRadarBg::wxRadarBg(SGPropertyNode *node) :
80     _name(node->getStringValue("name", "radar")),
81     _num(node->getIntValue("number", 0)),
82     _interval(node->getDoubleValue("update-interval-sec", 1.0)),
83     _time(0.0),
84     _sim_init_done(false),
85     _odg(0),
86     _last_switchKnob("off"),
87     _resultTexture(0),
88     _wxEcho(0)
89 {
90     string branch;
91     branch = "/instrumentation/" + _name;
92     _Instrument = fgGetNode(branch.c_str(), _num, true);
93
94     const char *tacan_source = node->getStringValue("tacan-source", "/instrumentation/tacan");
95     _Tacan = fgGetNode(tacan_source, true);
96
97     _font_node = _Instrument->getNode("font", true);
98     _font_node->addChangeListener(this, true);
99
100 #define INITFONT(p, val, type) if (!_font_node->hasValue(p)) _font_node->set##type##Value(p, val)
101     INITFONT("name", DEFAULT_FONT, String);
102     INITFONT("size", 8, Float);
103     INITFONT("line-spacing", 0.25, Float);
104     INITFONT("color/red", 0, Float);
105     INITFONT("color/green", 0.8, Float);
106     INITFONT("color/blue", 0, Float);
107     INITFONT("color/alpha", 1, Float);
108 #undef INITFONT
109 }
110
111
112 wxRadarBg::~wxRadarBg ()
113 {
114     _font_node->removeChangeListener(this);
115 }
116
117
118 void
119 wxRadarBg::init ()
120 {
121     _serviceable_node = _Instrument->getNode("serviceable", true);
122
123     // texture name to use in 2D and 3D instruments
124     _texture_path = _Instrument->getStringValue("radar-texture-path",
125             "Aircraft/Instruments/Textures/od_wxradar.rgb");
126     _resultTexture = FGTextureManager::createTexture(_texture_path.c_str(), false);
127
128     SGPath tpath(globals->get_fg_root());
129     string path = _Instrument->getStringValue("echo-texture-path",
130             "Aircraft/Instruments/Textures/wxecho.rgb");
131     tpath.append(path);
132
133     // no mipmap or else alpha will mix with pixels on the border of shapes, ruining the effect
134     _wxEcho = SGLoadTexture2D(tpath, false, false);
135
136
137     _Instrument->setFloatValue("trk", 0.0);
138     _Instrument->setFloatValue("tilt", 0.0);
139     _Instrument->setStringValue("status", "");
140     // those properties are used by a radar instrument of a MFD
141     // input switch = OFF | TST | STBY | ON
142     // input mode = WX | WXA | MAP
143     // output status = STBY | TEST | WX | WXA | MAP | blank
144     // input lightning = true | false
145     // input TRK = +/- n degrees
146     // input TILT = +/- n degree
147     // input autotilt = true | false
148     // input range = n nm (20/40/80)
149     // input display-mode = arc | rose | map | plan
150
151     FGInstrumentMgr *imgr = (FGInstrumentMgr *)globals->get_subsystem("instrumentation");
152     _odg = (FGODGauge *)imgr->get_subsystem("od_gauge");
153     _odg->setSize(512);
154
155     _ai = (FGAIManager*)globals->get_subsystem("ai_model");
156     _ai_enabled_node = fgGetNode("/sim/ai/enabled", true);
157
158     _user_lat_node = fgGetNode("/position/latitude-deg", true);
159     _user_lon_node = fgGetNode("/position/longitude-deg", true);
160     _user_alt_node = fgGetNode("/position/altitude-ft", true);
161
162     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
163     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
164
165     _tacan_serviceable_node = _Tacan->getNode("serviceable", true);
166     _tacan_distance_node    = _Tacan->getNode("indicated-distance-nm", true);
167     _tacan_name_node        = _Tacan->getNode("name", true);
168     _tacan_bearing_node     = _Tacan->getNode("indicated-bearing-true-deg", true);
169     _tacan_in_range_node    = _Tacan->getNode("in-range", true);
170
171     _radar_mode_control_node = _Instrument->getNode("mode-control", true);
172     _radar_coverage_node     = _Instrument->getNode("limit-deg", true);
173     _radar_ref_rng_node      = _Instrument->getNode("reference-range-nm", true);
174     _radar_hdg_marker_node   = _Instrument->getNode("heading-marker", true);
175
176     SGPropertyNode *n = _Instrument->getNode("display-controls", true);
177     _radar_weather_node     = n->getNode("WX", true);
178     _radar_position_node    = n->getNode("pos", true);
179     _radar_data_node        = n->getNode("data", true);
180     _radar_symbol_node      = n->getNode("symbol", true);
181     _radar_centre_node      = n->getNode("centre", true);
182     _radar_rotate_node      = n->getNode("rotate", true);
183
184     _radar_centre_node->setBoolValue(false);
185     if (!_radar_coverage_node->hasValue())
186         _radar_coverage_node->setFloatValue(120);
187     if (!_radar_ref_rng_node->hasValue())
188         _radar_ref_rng_node->setDoubleValue(35);
189     if (!_radar_hdg_marker_node->hasValue())
190         _radar_hdg_marker_node->setBoolValue(true);
191
192     _x_offset = 0;
193     _y_offset = 0;
194
195     // OSG geometry setup. The polygons for the radar returns will be
196     // stored in a single Geometry. The geometry will have several
197     // primitive sets so we can have different kinds of polys and
198     // choose a different overall color for each set.
199     _radarGeode = new osg::Geode;
200     osg::StateSet *stateSet = _radarGeode->getOrCreateStateSet();
201     stateSet->setTextureAttributeAndModes(0, _wxEcho.get());
202     _geom = new osg::Geometry;
203     _geom->setUseDisplayList(false);
204     // Initially allocate space for 128 quads
205     _vertices = new osg::Vec2Array;
206     _vertices->setDataVariance(osg::Object::DYNAMIC);
207     _vertices->reserve(128 * 4);
208     _geom->setVertexArray(_vertices);
209     _texCoords = new osg::Vec2Array;
210     _texCoords->setDataVariance(osg::Object::DYNAMIC);
211     _texCoords->reserve(128 * 4);
212     _geom->setTexCoordArray(0, _texCoords);
213     osg::Vec3Array *colors = new osg::Vec3Array;
214     colors->push_back(osg::Vec3(1.0f, 1.0f, 1.0f)); // color of echos
215     colors->push_back(osg::Vec3(1.0f, 0.0f, 0.0f)); // arc mask
216     colors->push_back(osg::Vec3(0.0f, 0.0f, 0.0f)); // rest of mask
217     _geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
218     _geom->setColorArray(colors);
219     osg::PrimitiveSet *pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
220     pset->setDataVariance(osg::Object::DYNAMIC);
221     _geom->addPrimitiveSet(pset);
222     pset = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
223     pset->setDataVariance(osg::Object::DYNAMIC);
224     _geom->addPrimitiveSet(pset);
225     pset = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES);
226     pset->setDataVariance(osg::Object::DYNAMIC);
227     _geom->addPrimitiveSet(pset);
228     _geom->setInitialBound(osg::BoundingBox(osg::Vec3f(-256.0f, -256.0f, 0.0f),
229             osg::Vec3f(256.0f, 256.0f, 0.0f)));
230     _radarGeode->addDrawable(_geom);
231     _odg->allocRT();
232     // Texture in the 2D panel system
233     FGTextureManager::addTexture(_texture_path.c_str(), _odg->getTexture());
234
235     _textGeode = new osg::Geode;
236
237     osg::Camera *camera = _odg->getCamera();
238     camera->addChild(_radarGeode.get());
239     camera->addChild(_textGeode.get());
240 }
241
242
243 // Local coordinates for each echo
244 const osg::Vec3f echoCoords[4] = {
245     osg::Vec3f(-.7f, -.7f, 0.0f), osg::Vec3f(.7f, -.7f, 0.0f),
246     osg::Vec3f(.7f, .7f, 0.0f), osg::Vec3f(-.7f, .7f, 0.0f)
247 };
248
249
250 const osg::Vec2f echoTexCoords[4] = {
251     osg::Vec2f(0.0f, 0.0f), osg::Vec2f(UNIT, 0.0f),
252     osg::Vec2f(UNIT, UNIT), osg::Vec2f(0.0f, UNIT)
253 };
254
255
256 // helper
257 static void
258 addQuad(osg::Vec2Array *vertices, osg::Vec2Array *texCoords,
259         const osg::Matrixf& transform, const osg::Vec2f& texBase)
260 {
261     for (int i = 0; i < 4; i++) {
262         const osg::Vec3f coords = transform.preMult(echoCoords[i]);
263         texCoords->push_back(texBase + echoTexCoords[i]);
264         vertices->push_back(osg::Vec2f(coords.x(), coords.y()));
265     }
266 }
267
268
269 // Rotate by a heading value
270 static inline
271 osg::Matrixf wxRotate(float angle)
272 {
273     return osg::Matrixf::rotate(angle, 0.0f, 0.0f, -1.0f);
274 }
275
276
277 void
278 wxRadarBg::update (double delta_time_sec)
279 {
280     if (!_sim_init_done) {
281         if (!fgGetBool("sim/sceneryloaded", false))
282             return;
283
284         _sim_init_done = true;
285     }
286     if (!_odg || !_serviceable_node->getBoolValue()) {
287         _Instrument->setStringValue("status", "");
288         return;
289     }
290     _time += delta_time_sec;
291     if (_time < _interval)
292         return;
293
294     _time = 0.0;
295
296     string mode = _Instrument->getStringValue("display-mode", "arc");
297     if (mode == "map") {
298         if (_display_mode != MAP) {
299             _display_mode = MAP;
300             center_map();
301         }
302     } else if (mode == "plan") {
303         _display_mode = PLAN;
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 {
369             // rose
370         }
371
372         _vertices->clear();
373         _texCoords->clear();
374         _textGeode->removeDrawables(0, _textGeode->getNumDrawables());
375
376
377         update_weather();
378
379
380         osg::DrawArrays *quadPSet
381                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(0));
382         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
383         quadPSet->dirty();
384
385         // erase what is out of sight of antenna
386         /*
387             |\     /|
388             | \   / |
389             |  \ /  |
390             ---------
391             |       |
392             |       |
393             ---------
394         */
395
396         osg::DrawArrays *maskPSet
397                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(1));
398         osg::DrawArrays *trimaskPSet
399                 = static_cast<osg::DrawArrays*>(_geom->getPrimitiveSet(2));
400
401         if (_display_mode == ARC) {
402             float xOffset = 256.0f;
403             float yOffset = 200.0f;
404
405             int firstQuadVert = _vertices->size();
406             _texCoords->push_back(osg::Vec2f(0.5f, 0.25f));
407             _vertices->push_back(osg::Vec2f(-xOffset, 0.0 + yOffset));
408             _texCoords->push_back(osg::Vec2f(1.0f, 0.25f));
409             _vertices->push_back(osg::Vec2f(xOffset, 0.0 + yOffset));
410             _texCoords->push_back(osg::Vec2f(1.0f, 0.5f));
411             _vertices->push_back(osg::Vec2f(xOffset, 256.0 + yOffset));
412             _texCoords->push_back(osg::Vec2f(0.5f, 0.5f));
413             _vertices->push_back(osg::Vec2f(-xOffset, 256.0 + yOffset));
414             maskPSet->set(osg::PrimitiveSet::QUADS, firstQuadVert, 4);
415
416             // The triangles aren't supposed to be textured, but there's
417             // no need to set up a different Geometry, switch modes,
418             // etc. I happen to know that there's a white pixel in the
419             // texture at 1.0, 0.0 :)
420             float centerY = tan(30 * SG_DEGREES_TO_RADIANS);
421             _vertices->push_back(osg::Vec2f(0.0, 0.0));
422             _vertices->push_back(osg::Vec2f(-256.0, 0.0));
423             _vertices->push_back(osg::Vec2f(-256.0, 256.0 * centerY));
424
425             _vertices->push_back(osg::Vec2f(0.0, 0.0));
426             _vertices->push_back(osg::Vec2f(256.0, 0.0));
427             _vertices->push_back(osg::Vec2f(256.0, 256.0 * centerY));
428
429             _vertices->push_back(osg::Vec2f(-256, 0.0));
430             _vertices->push_back(osg::Vec2f(256.0, 0.0));
431             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
432
433             _vertices->push_back(osg::Vec2f(256, 0.0));
434             _vertices->push_back(osg::Vec2f(256.0, -256.0));
435             _vertices->push_back(osg::Vec2f(-256.0, -256.0));
436
437             const osg::Vec2f whiteSpot(1.0f, 0.0f);
438             for (int i = 0; i < 3 * 4; i++)
439                 _texCoords->push_back(whiteSpot);
440
441             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, firstQuadVert + 4, 3 * 4);
442
443         } else {
444             maskPSet->set(osg::PrimitiveSet::QUADS, 0, 0);
445             trimaskPSet->set(osg::PrimitiveSet::TRIANGLES, 0, 0);
446         }
447
448         maskPSet->dirty();
449         trimaskPSet->dirty();
450
451         // draw without mask
452         _vertices->clear();
453         _texCoords->clear();
454
455         update_aircraft();
456         update_tacan();
457         update_heading_marker();
458
459         quadPSet->set(osg::PrimitiveSet::QUADS, 0, _vertices->size());
460         quadPSet->dirty();
461     }
462 }
463
464
465 void
466 wxRadarBg::update_weather()
467 {
468     string modeButton = _Instrument->getStringValue("mode", "wx");
469     _radarEchoBuffer = *sgEnviro.get_radar_echo();
470
471     // pretend we have a scan angle bigger then the FOV
472     // TODO:check real fov, enlarge if < nn, and do clipping if > mm
473     const float fovFactor = 1.45f;
474     _Instrument->setStringValue("status", modeButton.c_str());
475
476     list_of_SGWxRadarEcho *radarEcho = &_radarEchoBuffer;
477     list_of_SGWxRadarEcho::iterator iradarEcho, end = radarEcho->end();
478     const float LWClevel[] = { 0.1f, 0.5f, 2.1f };
479
480     // draw the cloud radar echo
481     bool drawClouds = _radar_weather_node->getBoolValue();
482     if (drawClouds) {
483
484         // we do that in 3 passes, one for each color level
485         // this is to 'merge' same colors together
486         for (int level = 0; level <= 2; level++) {
487             float col = level * UNIT;
488
489             for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
490                 int cloudId = iradarEcho->cloudId;
491                 bool upgrade = (cloudId >> 5) & 1;
492                 float lwc = iradarEcho->LWC + (upgrade ? 1.0f : 0.0f);
493
494                 // skip ns
495                 if (iradarEcho->LWC >= 0.5 && iradarEcho->LWC <= 0.6)
496                     continue;
497
498                 if (iradarEcho->lightning || lwc < LWClevel[level])
499                     continue;
500
501                 float radius = sgSqrt(iradarEcho->dist) * SG_METER_TO_NM * _scale;
502                 float size = iradarEcho->radius * 2.0 * SG_METER_TO_NM * _scale;
503
504                 if (radius - size > 180)
505                     continue;
506
507                 float angle = (iradarEcho->heading - _angle_offset) //* fovFactor
508                         + 0.5 * SG_PI;
509
510                 // Rotate echo into position, and rotate echo to have
511                 // a constant orientation towards the
512                 // airplane. Compass headings increase in clockwise
513                 // direction, while graphics rotations follow
514                 // right-hand (counter-clockwise) rule.
515                 const osg::Vec2f texBase(col, (UNIT * (float) (4 + (cloudId & 3))));
516
517                 osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
518                         * osg::Matrixf::translate(0.0f, radius, 0.0f)
519                         * wxRotate(angle) * _centerTrans);
520                 addQuad(_vertices, _texCoords, m, texBase);
521
522                 //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: drawing clouds"
523                 //        << " ID=" << cloudId
524                 //        << " x=" << x
525                 //        << " y="<< y
526                 //        << " radius=" << radius
527                 //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
528                 //        << " heading=" << iradarEcho->heading * SG_RADIANS_TO_DEGREES
529                 //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
530             }
531         }
532     }
533
534     // draw lightning echos
535     bool drawLightning = _Instrument->getBoolValue("lightning", true);
536     if (drawLightning) {
537         const osg::Vec2f texBase(3 * UNIT, 4 * UNIT);
538
539         for (iradarEcho = radarEcho->begin(); iradarEcho != end; ++iradarEcho) {
540             if (!iradarEcho->lightning)
541                 continue;
542
543             float size = UNIT * 0.5f;
544             float radius = iradarEcho->dist * _scale;
545             float angle = iradarEcho->heading * SG_DEGREES_TO_RADIANS
546                     - _angle_offset;
547
548             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
549                     * wxRotate(-angle)
550                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
551                     * wxRotate(angle) * _centerTrans);
552             addQuad(_vertices, _texCoords, m, texBase);
553         }
554     }
555 }
556
557
558 void
559 wxRadarBg::update_data(FGAIBase *ac, double radius, double bearing, bool selected)
560 {
561     osgText::Text *callsign = new osgText::Text;
562     callsign->setFont(_font.get());
563     callsign->setFontResolution(12, 12);
564     callsign->setCharacterSize(_font_size);
565     callsign->setColor(selected ? osg::Vec4(1, 1, 1, 1) : _font_color);
566     osg::Matrixf m(wxRotate(-bearing)
567             * osg::Matrixf::translate(0.0f, radius, 0.0f)
568             * wxRotate(bearing) * _centerTrans);
569
570     osg::Vec3 pos = m.preMult(osg::Vec3(16, 16, 0));
571     // cast to int's, otherwise text comes out ugly
572     callsign->setPosition(osg::Vec3((int)pos.x(), (int)pos.y(), 0));
573     callsign->setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE);
574     callsign->setLineSpacing(_font_spacing);
575
576     stringstream text;
577     text << ac->_getCallsign() << endl
578             << setprecision(0) << fixed
579             << setw(3) << setfill('0') << ac->_getHeading() << "\xB0 "
580             << setw(0) << ac->_getAltitude() << "ft" << endl
581             << ac->_getSpeed() << "kts";
582
583     callsign->setText(text.str());
584     _textGeode->addDrawable(callsign);
585 }
586
587
588 void
589 wxRadarBg::update_aircraft()
590 {
591     if (!_ai_enabled_node->getBoolValue())
592         return;
593
594     bool draw_echoes = _radar_position_node->getBoolValue();
595     bool draw_symbols = _radar_symbol_node->getBoolValue();
596     bool draw_data = _radar_data_node->getBoolValue();
597     if (!draw_echoes && !draw_symbols && !draw_data)
598         return;
599
600     radar_list_type radar_list = _ai->get_ai_list();
601     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: AI submodel list size" << radar_list.size());
602     if (radar_list.empty())
603         return;
604
605     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: Loading AI submodels ");
606     const double echo_radii[] = {0, 1, 1.5, 1.5, 0.001, 0.1, 1.5, 2, 1.5, 1.5, 1.5};
607
608     double user_lat = _user_lat_node->getDoubleValue();
609     double user_lon = _user_lon_node->getDoubleValue();
610     double user_alt = _user_alt_node->getDoubleValue();
611
612     float limit = _radar_coverage_node->getFloatValue();
613     if (limit > 180)
614         limit = 180;
615     else if (limit < 0)
616         limit = 0;
617     limit *= SG_DEGREES_TO_RADIANS;
618
619     radar_list_iterator it = radar_list.begin();
620     radar_list_iterator end = radar_list.end();
621     FGAIBase *selected_ac = 0;
622     double selected_radius = 0;
623     double selected_bearing = 0;
624     int selected_id = fgGetInt("/instrumentation/radar/selected-id", -1);
625
626     for (; it != end; ++it) {
627         FGAIBase *ac = (*it).get();
628         int type       = ac->getType();
629         double lat     = ac->_getLatitude();
630         double lon     = ac->_getLongitude();
631         double alt     = ac->_getAltitude();
632         double heading = ac->_getHeading();
633
634         double range, bearing;
635         calcRangeBearing(user_lat, user_lon, lat, lon, range, bearing);
636
637         //SG_LOG(SG_GENERAL, SG_DEBUG,
638         /*        "Radar: ID=" << ac->getID() << "(" << radar_list.size() << ")"
639                 << " type=" << type
640                 << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
641                 << " alt=" << alt
642                 << " heading=" << heading
643                 << " range=" << range
644                 << " bearing=" << bearing);*/
645
646         bool isVisible = withinRadarHorizon(user_alt, alt, range);
647         //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: visible " << isVisible);
648         if (!isVisible)
649             continue;
650
651         if (!inRadarRange(type, range))
652             continue;
653
654         bearing *= SG_DEGREES_TO_RADIANS;
655         heading *= SG_DEGREES_TO_RADIANS;
656
657         float radius = range * _scale;
658         float angle = calcRelBearing(bearing, _view_heading);
659
660         if (angle > limit || angle < -limit)
661             continue;
662
663         bearing += _angle_offset;
664         heading += _angle_offset;
665
666         // pos mode
667         if (draw_echoes) {
668             float echo_radius = echo_radii[type] * 120;
669             float size = echo_radius * UNIT;
670
671             const osg::Vec2f texBase(3 * UNIT, 3 * UNIT);
672             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
673                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
674                     * wxRotate(bearing) * _centerTrans);
675             addQuad(_vertices, _texCoords, m, texBase);
676
677             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing AI"
678                 //<< " ID=" << ac->getID()
679                 //<< " type=" << type
680             //        << " radius=" << radius
681             //        << " angle=" << angle * SG_RADIANS_TO_DEGREES);
682         }
683
684         // data mode
685         if (draw_symbols) {
686             const osg::Vec2f texBase(0, 3 * UNIT);
687             float size = 600 * UNIT;
688             osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
689                     * wxRotate(heading - bearing)
690                     * osg::Matrixf::translate(0.0f, radius, 0.0f)
691                     * wxRotate(bearing) * _centerTrans);
692             addQuad(_vertices, _texCoords, m, texBase);
693
694             //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:    drawing data"
695             //        << " x=" << x <<" y="<< y
696             //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
697             //        << " radius=" << radius);
698         }
699
700         if (draw_data) {
701             if (ac->getID() == selected_id) {
702                 selected_ac = ac;
703                 selected_radius = radius;
704                 selected_bearing = bearing;
705             } else {
706                 update_data(ac, radius, bearing, false);
707             }
708         }
709     }
710     if (selected_ac) {
711         update_data(selected_ac, selected_radius, selected_bearing, true);
712     }
713 }
714
715
716 void
717 wxRadarBg::update_tacan()
718 {
719     // draw TACAN symbol
720     int mode = _radar_mode_control_node->getIntValue();
721     bool inRange = _tacan_in_range_node->getBoolValue();
722
723     if (mode != 1 || !inRange)
724         return;
725
726     float size = 600 * UNIT;
727     float radius = _tacan_distance_node->getFloatValue() * _scale;
728     float angle = _tacan_bearing_node->getFloatValue() * SG_DEGREES_TO_RADIANS
729             + _angle_offset;
730
731     const osg::Vec2f texBase(1 * UNIT, 3 * UNIT);
732     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
733             * wxRotate(-angle)
734             * osg::Matrixf::translate(0.0f, radius, 0.0f)
735             * wxRotate(angle) * _centerTrans);
736     addQuad(_vertices, _texCoords, m, texBase);
737
738     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:     drawing TACAN"
739     //        << " dist=" << radius
740     //        << " view_heading=" << _view_heading * SG_RADIANS_TO_DEGREES
741     //        << " bearing=" << angle * SG_RADIANS_TO_DEGREES
742     //        << " x=" << x << " y="<< y
743     //        << " size=" << size);
744 }
745
746
747 void
748 wxRadarBg::update_heading_marker()
749 {
750     if (!_radar_hdg_marker_node->getBoolValue())
751         return;
752
753     const osg::Vec2f texBase(2 * UNIT, 3 * UNIT);
754     float size = 600 * UNIT;
755     osg::Matrixf m(osg::Matrixf::scale(size, size, 1.0f)
756             * wxRotate(_view_heading + _angle_offset));
757
758     m *= _centerTrans;
759     addQuad(_vertices, _texCoords, m, texBase);
760
761     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar:   drawing heading marker"
762     //        << " x,y " << x <<","<< y
763     //        << " dist" << dist
764     //        << " view_heading" << _view_heading * SG_RADIANS_TO_DEGREES
765     //        << " heading " << iradarEcho->heading * SG_RADIANS_TO_DEGREES
766     //        << " angle " << angle * SG_RADIANS_TO_DEGREES);
767 }
768
769
770 void
771 wxRadarBg::center_map()
772 {
773     _lat = _user_lat_node->getDoubleValue();
774     _lon = _user_lon_node->getDoubleValue();
775     _x_offset = _y_offset = 0;
776 }
777
778
779 void
780 wxRadarBg::apply_map_offset()
781 {
782     double lat = _user_lat_node->getDoubleValue();
783     double lon = _user_lon_node->getDoubleValue();
784     double bearing, distance, az2;
785     geo_inverse_wgs_84(_lat, _lon, lat, lon, &bearing, &az2, &distance);
786     distance *= SG_METER_TO_NM * _scale;
787     bearing *= SG_DEGREES_TO_RADIANS;
788     _x_offset += sin(bearing) * distance;
789     _y_offset += cos(bearing) * distance;
790     _lat = lat;
791     _lon = lon;
792 }
793
794
795 bool
796 wxRadarBg::withinRadarHorizon(double user_alt, double alt, double range_nm)
797 {
798     // Radar Horizon  = 1.23(ht^1/2 + hr^1/2),
799     //don't allow negative altitudes (an approximation - yes altitudes can be negative)
800
801     if (user_alt < 0)
802         user_alt = 0;
803
804     if (alt < 0)
805         alt = 0;
806
807     double radarhorizon = 1.23 * (sqrt(alt) + sqrt(user_alt));
808     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: horizon " << radarhorizon);
809     return radarhorizon >= range_nm;
810 }
811
812
813 bool
814 wxRadarBg::inRadarRange(int type, double range_nm)
815 {
816     //The Radar Equation:
817     //
818     // MaxRange^4 = (TxPower * AntGain^2 * lambda^2 * sigma)/((constant) * MDS)
819     //
820     // Where (constant) = (4*pi)3 and MDS is the Minimum Detectable Signal power.
821     //
822     // For a given radar we can assume that the only variable is sigma,
823     // the target radar cross section.
824     //
825     // Here, we will use a normalised rcs (sigma) for a standard taget and assume that this
826     // will provide a maximum range of 35nm;
827     //
828     // TODO - make the maximum range adjustable at runtime
829
830     const double sigma[] = {0, 1, 100, 100, 0.001, 0.1, 100, 100, 1, 1, 1};
831     double constant = _radar_ref_rng;
832
833     if (constant <= 0)
834         constant = 35;
835
836     double maxrange = constant * pow(sigma[type], 0.25);
837     //SG_LOG(SG_GENERAL, SG_DEBUG, "Radar: max range " << maxrange);
838     return maxrange >= range_nm;
839 }
840
841
842 void
843 wxRadarBg::calcRangeBearing(double lat, double lon, double lat2, double lon2,
844         double &range, double &bearing) const
845 {
846     // calculate the bearing and range of the second pos from the first
847     double az2, distance;
848     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
849     range = distance *= SG_METER_TO_NM;
850 }
851
852
853 float
854 wxRadarBg::calcRelBearing(float bearing, float heading)
855 {
856     float angle = bearing - heading;
857
858     if (angle >= SG_PI)
859         angle -= 2.0 * SG_PI;
860
861     if (angle < -SG_PI)
862         angle += 2.0 * SG_PI;
863
864     return angle;
865 }
866
867
868 void
869 wxRadarBg::updateFont()
870 {
871     float red = _font_node->getFloatValue("color/red");
872     float green = _font_node->getFloatValue("color/green");
873     float blue = _font_node->getFloatValue("color/blue");
874     float alpha = _font_node->getFloatValue("color/alpha");
875     _font_color.set(red, green, blue, alpha);
876
877     _font_size = _font_node->getFloatValue("size");
878     _font_spacing = _font_size * _font_node->getFloatValue("line-spacing");
879     string path = _font_node->getStringValue("name", DEFAULT_FONT);
880
881     SGPath tpath;
882     if (path[0] != '/') {
883         tpath = globals->get_fg_root();
884         tpath.append("Fonts");
885         tpath.append(path);
886     } else {
887         tpath = path;
888     }
889
890 #if (FG_OSG_VERSION >= 21000)
891     osg::ref_ptr<osgDB::ReaderWriter::Options> fontOptions = new osgDB::ReaderWriter::Options("monochrome");
892     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str(), fontOptions.get());
893 #else
894     osg::ref_ptr<osgText::Font> font = osgText::readFontFile(tpath.c_str());
895 #endif
896
897     if (font != 0) {
898         _font = font;
899         _font->setMinFilterHint(osg::Texture::NEAREST);
900         _font->setMagFilterHint(osg::Texture::NEAREST);
901         _font->setGlyphImageMargin(0);
902         _font->setGlyphImageMarginRatio(0);
903     }
904 }
905
906 void
907 wxRadarBg::valueChanged(SGPropertyNode*)
908 {
909     updateFont();
910 }
911