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