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