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