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