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