]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
Merge branch 'ehofman/rename'
[flightgear.git] / src / Instrumentation / navradio.cxx
1 // navradio.cxx -- class to manage a nav radio instance
2 //
3 // Written by Curtis Olson, started April 2000.
4 //
5 // Copyright (C) 2000 - 2002  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include "navradio.hxx"
29
30 #include <sstream>
31
32 #include <simgear/sg_inlines.h>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/math/vector.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/math/interpolater.hxx>
40
41 #include <Navaids/navrecord.hxx>
42
43 #include <Airports/runways.hxx>
44 #include <Navaids/navlist.hxx>
45 #include <Main/util.hxx>
46
47
48 using std::string;
49
50 // General-purpose sawtooth function.  Graph looks like this:
51 //         /\                                    .
52 //       \/
53 // Odd symmetry, inversion symmetry about the origin.
54 // Unit slope at the origin.
55 // Max 1, min -1, period 4.
56 // Two zero-crossings per period, one with + slope, one with - slope.
57 // Useful for false localizer courses.
58 static double sawtooth(double xx)
59 {
60   return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
61 }
62
63 // Calculate a unit vector in the horizontal tangent plane
64 // starting at the given "tail" of the vector and going off 
65 // with the given heading.
66 static SGVec3d tangentVector(const SGGeod& tail, const SGVec3d& tail_xyz, 
67           const double heading)
68 {
69 // The fudge factor here is presumably intended to improve
70 // numerical stability.  I don't know if it is necessary.
71 // It gets divided out later.
72   double fudge(100.0);
73   SGGeod head;
74   double az2; // ignored
75   SGGeodesy::direct(tail, heading, fudge, head, az2);
76   head.setElevationM(tail.getElevationM());
77   SGVec3d head_xyz = SGVec3d::fromGeod(head);
78   return (head_xyz - tail_xyz) * (1.0/fudge);
79 }
80
81 // Create a "serviceable" node with a default value of "true"
82 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, const char* aName)
83 {
84   SGPropertyNode_ptr n = (aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true));
85   simgear::props::Type typ = n->getType();
86   if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
87     n->setBoolValue(true);
88   }
89   return n;  
90 }
91
92 // Constructor
93 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
94     lon_node(fgGetNode("/position/longitude-deg", true)),
95     lat_node(fgGetNode("/position/latitude-deg", true)),
96     alt_node(fgGetNode("/position/altitude-ft", true)),
97     is_valid_node(NULL),
98     power_btn_node(NULL),
99     freq_node(NULL),
100     alt_freq_node(NULL),
101     sel_radial_node(NULL),
102     vol_btn_node(NULL),
103     ident_btn_node(NULL),
104     audio_btn_node(NULL),
105     backcourse_node(NULL),
106     nav_serviceable_node(NULL),
107     cdi_serviceable_node(NULL),
108     gs_serviceable_node(NULL),
109     tofrom_serviceable_node(NULL),
110     dme_serviceable_node(NULL),
111     fmt_freq_node(NULL),
112     fmt_alt_freq_node(NULL),
113     heading_node(NULL),
114     radial_node(NULL),
115     recip_radial_node(NULL),
116     target_radial_true_node(NULL),
117     target_auto_hdg_node(NULL),
118     time_to_intercept(NULL),
119     to_flag_node(NULL),
120     from_flag_node(NULL),
121     inrange_node(NULL),
122     signal_quality_norm_node(NULL),
123     cdi_deflection_node(NULL),
124     cdi_deflection_norm_node(NULL),
125     cdi_xtrack_error_node(NULL),
126     cdi_xtrack_hdg_err_node(NULL),
127     has_gs_node(NULL),
128     loc_node(NULL),
129     loc_dist_node(NULL),
130     gs_deflection_node(NULL),
131     gs_deflection_deg_node(NULL),
132     gs_deflection_norm_node(NULL),
133     gs_rate_of_climb_node(NULL),
134     gs_dist_node(NULL),
135     gs_inrange_node(NULL),
136     nav_id_node(NULL),
137     id_c1_node(NULL),
138     id_c2_node(NULL),
139     id_c3_node(NULL),
140     id_c4_node(NULL),
141     nav_slaved_to_gps_node(NULL),
142     gps_cdi_deflection_node(NULL),
143     gps_to_flag_node(NULL),
144     gps_from_flag_node(NULL),
145     gps_has_gs_node(NULL),
146     gps_xtrack_error_nm_node(NULL),
147     play_count(0),
148     last_time(0),
149     target_radial(0.0),
150     horiz_vel(0.0),
151     last_x(0.0),
152     last_loc_dist(0.0),
153     last_xtrack_error(0.0),
154     xrate_ms(0.0),
155     _localizerWidth(5.0),
156     _name(node->getStringValue("name", "nav")),
157     _num(node->getIntValue("number", 0)),
158     _time_before_search_sec(-1.0),
159     _falseCoursesEnabled(true),
160     _sgr(NULL)
161 {
162     SGPath path( globals->get_fg_root() );
163     SGPath term = path;
164     term.append( "Navaids/range.term" );
165     SGPath low = path;
166     low.append( "Navaids/range.low" );
167     SGPath high = path;
168     high.append( "Navaids/range.high" );
169
170     term_tbl = new SGInterpTable( term.str() );
171     low_tbl = new SGInterpTable( low.str() );
172     high_tbl = new SGInterpTable( high.str() );
173 }
174
175
176 // Destructor
177 FGNavRadio::~FGNavRadio() 
178 {
179     delete term_tbl;
180     delete low_tbl;
181     delete high_tbl;
182 }
183
184
185 void
186 FGNavRadio::init ()
187 {
188     SGSoundMgr *smgr = globals->get_soundmgr();
189     _sgr = smgr->find("avionics", true);
190     _sgr->tie_to_listener();
191
192     morse.init();
193
194     string branch;
195     branch = "/instrumentation/" + _name;
196
197     SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
198
199     bus_power_node = 
200         fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
201
202     // inputs
203     is_valid_node = node->getChild("data-is-valid", 0, true);
204     power_btn_node = node->getChild("power-btn", 0, true);
205     power_btn_node->setBoolValue( true );
206     vol_btn_node = node->getChild("volume", 0, true);
207     ident_btn_node = node->getChild("ident", 0, true);
208     ident_btn_node->setBoolValue( true );
209     audio_btn_node = node->getChild("audio-btn", 0, true);
210     audio_btn_node->setBoolValue( true );
211     backcourse_node = node->getChild("back-course-btn", 0, true);
212     backcourse_node->setBoolValue( false );
213     
214     nav_serviceable_node = node->getChild("serviceable", 0, true);
215     cdi_serviceable_node = createServiceableProp(node, "cdi");
216     gs_serviceable_node = createServiceableProp(node, "gs");
217     tofrom_serviceable_node = createServiceableProp(node, "to-from");
218     dme_serviceable_node = createServiceableProp(node, "dme");
219     
220     globals->get_props()->tie("sim/realism/false-radio-courses-enabled", 
221       SGRawValuePointer<bool>(&_falseCoursesEnabled));
222     
223     // frequencies
224     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
225     freq_node = subnode->getChild("selected-mhz", 0, true);
226     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
227     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
228     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
229
230     // radials
231     subnode = node->getChild("radials", 0, true);
232     sel_radial_node = subnode->getChild("selected-deg", 0, true);
233     radial_node = subnode->getChild("actual-deg", 0, true);
234     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
235     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
236     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
237
238     // outputs
239     heading_node = node->getChild("heading-deg", 0, true);
240     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
241     to_flag_node = node->getChild("to-flag", 0, true);
242     from_flag_node = node->getChild("from-flag", 0, true);
243     inrange_node = node->getChild("in-range", 0, true);
244     signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
245     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
246     cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
247     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
248     cdi_xtrack_hdg_err_node
249         = node->getChild("crosstrack-heading-error-deg", 0, true);
250     has_gs_node = node->getChild("has-gs", 0, true);
251     loc_node = node->getChild("nav-loc", 0, true);
252     loc_dist_node = node->getChild("nav-distance", 0, true);
253     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
254     gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
255     gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
256     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
257     gs_dist_node = node->getChild("gs-distance", 0, true);
258     gs_inrange_node = node->getChild("gs-in-range", 0, true);
259     
260     nav_id_node = node->getChild("nav-id", 0, true);
261     id_c1_node = node->getChild("nav-id_asc1", 0, true);
262     id_c2_node = node->getChild("nav-id_asc2", 0, true);
263     id_c3_node = node->getChild("nav-id_asc3", 0, true);
264     id_c4_node = node->getChild("nav-id_asc4", 0, true);
265
266     node->tie("dme-in-range", SGRawValuePointer<bool>(&_dmeInRange));
267         
268     // gps slaving support
269     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
270     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
271     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
272     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
273     gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
274     gps_course_node = fgGetNode("/instrumentation/gps/selected-course-deg", true);
275     gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
276     _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
277     
278     std::ostringstream temp;
279     temp << _name << "nav-ident" << _num;
280     nav_fx_name = temp.str();
281     temp << _name << "dme-ident" << _num;
282     dme_fx_name = temp.str();
283 }
284
285 void
286 FGNavRadio::bind ()
287 {
288   
289 }
290
291
292 void
293 FGNavRadio::unbind ()
294 {
295 }
296
297
298 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
299 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
300                                  double nominalRange )
301 {
302     if (nominalRange <= 0.0) {
303       nominalRange = FG_NAV_DEFAULT_RANGE;
304     }
305     
306     // extend out actual usable range to be 1.3x the published safe range
307     const double usability_factor = 1.3;
308
309     // assumptions we model the standard service volume, plus
310     // ... rather than specifying a cylinder, we model a cone that
311     // contains the cylinder.  Then we put an upside down cone on top
312     // to model diminishing returns at too-high altitudes.
313
314     // altitude difference
315     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
316     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
317     //      << " station elev = " << stationElev << endl;
318
319     if ( nominalRange < 25.0 + SG_EPSILON ) {
320         // Standard Terminal Service Volume
321         return term_tbl->interpolate( alt ) * usability_factor;
322     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
323         // Standard Low Altitude Service Volume
324         // table is based on range of 40, scale to actual range
325         return low_tbl->interpolate( alt ) * nominalRange / 40.0
326             * usability_factor;
327     } else {
328         // Standard High Altitude Service Volume
329         // table is based on range of 130, scale to actual range
330         return high_tbl->interpolate( alt ) * nominalRange / 130.0
331             * usability_factor;
332     }
333 }
334
335
336 // model standard ILS service volumes as per AIM 1-1-9
337 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
338                                  double offsetDegrees, double distance )
339 {
340     // assumptions we model the standard service volume, plus
341
342     // altitude difference
343     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
344 //     double offset = fabs( offsetDegrees );
345
346 //     if ( offset < 10 ) {
347 //      return FG_ILS_DEFAULT_RANGE;
348 //     } else if ( offset < 35 ) {
349 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
350 //     } else if ( offset < 45 ) {
351 //      return (45 - offset);
352 //     } else if ( offset > 170 ) {
353 //         return FG_ILS_DEFAULT_RANGE;
354 //     } else if ( offset > 145 ) {
355 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
356 //     } else if ( offset > 135 ) {
357 //         return (offset - 135);
358 //     } else {
359 //      return 0;
360 //     }
361     return FG_LOC_DEFAULT_RANGE;
362 }
363
364
365 //////////////////////////////////////////////////////////////////////////
366 // Update the various nav values based on position and valid tuned in navs
367 //////////////////////////////////////////////////////////////////////////
368 void 
369 FGNavRadio::update(double dt) 
370 {
371   if (dt <= 0.0) {
372     return; // paused
373   }
374     
375   // Create "formatted" versions of the nav frequencies for
376   // instrument displays.
377   char tmp[16];
378   sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
379   fmt_freq_node->setStringValue(tmp);
380   sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
381   fmt_alt_freq_node->setStringValue(tmp);
382
383   if (power_btn_node->getBoolValue() 
384       && (bus_power_node->getDoubleValue() > 1.0)
385       && nav_serviceable_node->getBoolValue() )
386   {   
387     if (nav_slaved_to_gps_node->getBoolValue()) {
388       updateGPSSlaved();
389     } else {
390       updateReceiver(dt);
391     }
392     
393     updateCDI(dt);
394   } else {
395     clearOutputs();
396   }
397   
398   updateAudio();
399 }
400
401 void FGNavRadio::clearOutputs()
402 {
403   inrange_node->setBoolValue( false );
404   cdi_deflection_node->setDoubleValue( 0.0 );
405   cdi_deflection_norm_node->setDoubleValue( 0.0 );
406   cdi_xtrack_error_node->setDoubleValue( 0.0 );
407   cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
408   time_to_intercept->setDoubleValue( 0.0 );
409   gs_deflection_node->setDoubleValue( 0.0 );
410   gs_deflection_deg_node->setDoubleValue(0.0);
411   gs_deflection_norm_node->setDoubleValue(0.0);
412   gs_inrange_node->setBoolValue( false );
413   
414   to_flag_node->setBoolValue( false );
415   from_flag_node->setBoolValue( false );
416   
417   _dmeInRange = false;
418 }
419
420 void FGNavRadio::updateReceiver(double dt)
421 {
422   // Do a nav station search only once a second to reduce
423   // unnecessary work. (Also, make sure to do this before caching
424   // any values!)
425   _time_before_search_sec -= dt;
426   if ( _time_before_search_sec < 0 ) {
427    search();
428   }
429
430   if (!_navaid) {
431     _cdiDeflection = 0.0;
432     _cdiCrossTrackErrorM = 0.0;
433     _toFlag = _fromFlag = false;
434     _gsNeedleDeflection = 0.0;
435     _gsNeedleDeflectionNorm = 0.0;
436     inrange_node->setBoolValue(false);
437     return;
438   }
439
440   SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
441                                lat_node->getDoubleValue(),
442                                alt_node->getDoubleValue());
443                                
444   double nav_elev = _navaid->get_elev_ft();
445   SGVec3d aircraft = SGVec3d::fromGeod(pos);
446   double loc_dist = dist(aircraft, _navaid->cart());
447   loc_dist_node->setDoubleValue( loc_dist );
448   bool is_loc = loc_node->getBoolValue();
449   double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
450   
451   double az2, s;
452   //////////////////////////////////////////////////////////
453         // compute forward and reverse wgs84 headings to localizer
454   //////////////////////////////////////////////////////////
455   double hdg;
456   SGGeodesy::inverse(pos, _navaid->geod(), hdg, az2, s);
457   heading_node->setDoubleValue(hdg);
458   double radial = az2 - twist;
459   double recip = radial + 180.0;
460   SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
461   radial_node->setDoubleValue( radial );
462   recip_radial_node->setDoubleValue( recip );
463   
464   //////////////////////////////////////////////////////////
465   // compute the target/selected radial in "true" heading
466   //////////////////////////////////////////////////////////
467   if (!is_loc) {
468     target_radial = sel_radial_node->getDoubleValue();
469   }
470   
471   // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
472   double trtrue = target_radial + twist;
473   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
474   target_radial_true_node->setDoubleValue( trtrue );
475
476   //////////////////////////////////////////////////////////
477   // adjust reception range for altitude
478   // FIXME: make sure we are using the navdata range now that
479   //        it is valid in the data file
480   //////////////////////////////////////////////////////////
481         if ( is_loc ) {
482             double offset = radial - target_radial;
483       SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
484             effective_range
485                 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
486                                   loc_dist * SG_METER_TO_NM );
487         } else {
488             effective_range
489                 = adjustNavRange( nav_elev, pos.getElevationM(), _navaid->get_range() );
490         }
491   
492   double effective_range_m = effective_range * SG_NM_TO_METER;
493
494   //////////////////////////////////////////////////////////
495   // compute signal quality
496   // 100% within effective_range
497   // decreases 1/x^2 further out
498   //////////////////////////////////////////////////////////  
499   double last_signal_quality_norm = signal_quality_norm;
500
501   if ( loc_dist < effective_range_m ) {
502     signal_quality_norm = 1.0;
503   } else {
504     double range_exceed_norm = loc_dist/effective_range_m;
505     signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
506   }
507
508   signal_quality_norm = fgGetLowPass( last_signal_quality_norm, 
509            signal_quality_norm, dt );
510   
511   signal_quality_norm_node->setDoubleValue( signal_quality_norm );
512   bool inrange = signal_quality_norm > 0.2;
513   inrange_node->setBoolValue( inrange );
514   
515   //////////////////////////////////////////////////////////
516   // compute to/from flag status
517   //////////////////////////////////////////////////////////
518   if (inrange) {
519     if (is_loc) {
520       _toFlag = true;
521     } else {
522       double offset = fabs(radial - target_radial);
523       _toFlag = (offset > 90.0 && offset < 270.0);
524     }
525     _fromFlag = !_toFlag;
526   } else {
527     _toFlag = _fromFlag = false;
528   }
529   
530   // CDI deflection
531   double r = target_radial - radial;
532   SG_NORMALIZE_RANGE(r, -180.0, 180.0);
533   
534   if ( is_loc ) {
535     if (_falseCoursesEnabled) {
536       // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six 
537       // zeros i.e. six courses: one front course, one back course, and four 
538       // false courses. Three of the six are reverse sensing.
539       _cdiDeflection = 30.0 * sawtooth(r / 30.0);
540     } else {
541       // no false courses, but we do need to create a back course
542       if (fabs(r) > 90.0) { // front course
543         _cdiDeflection = r - copysign(180.0, r);
544       } else {
545         _cdiDeflection = r; // back course
546       }
547       
548       _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
549     } // of false courses disabled
550     
551     const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
552     _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
553     
554     if (backcourse_node->getBoolValue()) {
555       _cdiDeflection = -_cdiDeflection;
556     }
557   } else {
558     // handle the TO side of the VOR
559     if (fabs(r) > 90.0) {
560       r = ( r<0.0 ? -r-180.0 : -r+180.0 );
561     }
562     _cdiDeflection = r;
563   } // of non-localiser case
564   
565   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
566   _cdiDeflection *= signal_quality_norm;
567   
568   // cross-track error (in metres)
569   _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
570   
571   updateGlideSlope(dt, aircraft, signal_quality_norm);
572   updateDME(aircraft);
573   
574   last_loc_dist = loc_dist;
575 }
576
577 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
578 {
579   _gsNeedleDeflection = 0.0;
580   if (!_gs || !inrange_node->getBoolValue()) {
581     gs_dist_node->setDoubleValue( 0.0 );
582     gs_inrange_node->setBoolValue(false);
583     _gsNeedleDeflection = 0.0;
584     _gsNeedleDeflectionNorm = 0.0;
585     return;
586   }
587   
588   double gsDist = dist(aircraft, _gsCart);
589   gs_dist_node->setDoubleValue(gsDist);
590   bool gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
591   gs_inrange_node->setBoolValue(gsInRange);
592         
593   if (!gsInRange) {
594     _gsNeedleDeflection = 0.0;
595     _gsNeedleDeflectionNorm = 0.0;
596     return;
597   }
598   
599   SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
600   // The positive GS axis points along the runway in the landing direction,
601   // toward the far end, not toward the approach area, so we need a - sign here:
602   double dot_h = -dot(pos, _gsAxis);
603   double dot_v = dot(pos, _gsVertical);
604   double angle = atan2(dot_v, dot_h) * SGD_RADIANS_TO_DEGREES;
605   double deflectionAngle = target_gs - angle;
606   
607   if (_falseCoursesEnabled) {
608     // Construct false glideslopes.  The scale factor of 1.5 
609     // in the sawtooth gives a period of 6 degrees.
610     // There will be zeros at 3, 6r, 9, 12r et cetera
611     // where "r" indicates reverse sensing.
612     // This is is consistent with conventional pilot lore
613     // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
614     // but inconsistent with
615     // http://www.freepatentsonline.com/3757338.html
616     //
617     // It may be that some of each exist.
618     if (deflectionAngle < 0) {
619       deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
620     } else {
621       // no false GS below the true GS
622     }
623   }
624   
625   _gsNeedleDeflection = deflectionAngle * 5.0;
626   _gsNeedleDeflection *= signal_quality_norm;
627   
628   SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
629   _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
630   
631   //////////////////////////////////////////////////////////
632   // Calculate desired rate of climb for intercepting the GS
633   //////////////////////////////////////////////////////////
634   double gs_diff = target_gs - angle;
635   // convert desired vertical path angle into a climb rate
636   double des_angle = angle - 10 * gs_diff;
637
638   // estimate horizontal speed towards ILS in meters per minute
639   double elapsedDistance = last_x - gsDist;
640   last_x = gsDist;
641       
642   double new_vel = ( elapsedDistance / dt );
643   horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
644
645   gs_rate_of_climb_node
646       ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
647                         * horiz_vel * SG_METER_TO_FEET );
648 }
649
650 void FGNavRadio::updateDME(const SGVec3d& aircraft)
651 {
652   if (!_dme || !dme_serviceable_node->getBoolValue()) {
653     _dmeInRange = false;
654     return;
655   }
656   
657   double dme_distance = dist(aircraft, _dme->cart()); 
658   _dmeInRange =  (dme_distance < _dme->get_range() * SG_NM_TO_METER);
659 }
660
661 void FGNavRadio::updateGPSSlaved()
662 {
663   has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
664  
665   _toFlag = gps_to_flag_node->getBoolValue();
666   _fromFlag = gps_from_flag_node->getBoolValue();
667
668   bool gpsValid = (_toFlag | _fromFlag);
669   inrange_node->setBoolValue(gpsValid);
670   if (!gpsValid) {
671     signal_quality_norm_node->setDoubleValue(0.0);
672     _cdiDeflection = 0.0;
673     _cdiCrossTrackErrorM = 0.0;
674     _gsNeedleDeflection = 0.0;
675     return;
676   }
677   
678   // this is unfortunate, but panel instruments use this value to decide
679   // if the navradio output is valid.
680   signal_quality_norm_node->setDoubleValue(1.0);
681   
682   _cdiDeflection =  gps_cdi_deflection_node->getDoubleValue();
683   // clmap to some range (+/- 10 degrees) as the regular deflection
684   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
685   
686   _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
687   _gsNeedleDeflection = 0.0; // FIXME, supply this
688   
689   double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
690   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
691   target_radial_true_node->setDoubleValue( trtrue );
692 }
693
694 void FGNavRadio::updateCDI(double dt)
695 {
696   bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
697   bool inrange = inrange_node->getBoolValue();
698                                
699   if (tofrom_serviceable_node->getBoolValue()) {
700     to_flag_node->setBoolValue(_toFlag);
701     from_flag_node->setBoolValue(_fromFlag);
702   } else {
703     to_flag_node->setBoolValue(false);
704     from_flag_node->setBoolValue(false);
705   }
706   
707   if (!cdi_serviceable) {
708     _cdiDeflection = 0.0;
709     _cdiCrossTrackErrorM = 0.0;
710   }
711   
712   cdi_deflection_node->setDoubleValue(_cdiDeflection);
713   cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
714   cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
715
716   //////////////////////////////////////////////////////////
717   // compute an approximate ground track heading error
718   //////////////////////////////////////////////////////////
719   double hdg_error = 0.0;
720   if ( inrange && cdi_serviceable ) {
721     double vn = fgGetDouble( "/velocities/speed-north-fps" );
722     double ve = fgGetDouble( "/velocities/speed-east-fps" );
723     double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
724     if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
725
726     SGPropertyNode *true_hdg
727         = fgGetNode("/orientation/heading-deg", true);
728     hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
729
730     // cout << "ground track = " << gnd_trk_true
731     //      << " orientation = " << true_hdg->getDoubleValue() << endl;
732   }
733   cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
734
735   //////////////////////////////////////////////////////////
736   // Calculate a suggested target heading to smoothly intercept
737   // a nav/ils radial.
738   //////////////////////////////////////////////////////////
739
740   // Now that we have cross track heading adjustment built in,
741   // we shouldn't need to overdrive the heading angle within 8km
742   // of the station.
743   //
744   // The cdi deflection should be +/-10 for a full range of deflection
745   // so multiplying this by 3 gives us +/- 30 degrees heading
746   // compensation.
747   double adjustment = _cdiDeflection * 3.0;
748   SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
749
750   // determine the target heading to fly to intercept the
751   // tgt_radial = target radial (true) + cdi offset adjustmest -
752   // xtrack heading error adjustment
753   double nta_hdg;
754   double trtrue = target_radial_true_node->getDoubleValue();
755   if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
756       // tuned to a localizer and backcourse mode activated
757       trtrue += 180.0;   // reverse the target localizer heading
758       SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
759       nta_hdg = trtrue - adjustment - hdg_error;
760   } else {
761       nta_hdg = trtrue + adjustment - hdg_error;
762   }
763
764   SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
765   target_auto_hdg_node->setDoubleValue( nta_hdg );
766
767   //////////////////////////////////////////////////////////
768   // compute the time to intercept selected radial (based on
769   // current and last cross track errors and dt
770   //////////////////////////////////////////////////////////
771   double t = 0.0;
772   if ( inrange && cdi_serviceable ) {
773     double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
774     xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
775     if ( fabs(xrate_ms) > 0.00001 ) {
776         t = _cdiCrossTrackErrorM / xrate_ms;
777     } else {
778         t = 9999.9;
779     }
780   }
781   time_to_intercept->setDoubleValue( t );
782
783   if (!gs_serviceable_node->getBoolValue() ) {
784     _gsNeedleDeflection = 0.0;
785     _gsNeedleDeflectionNorm = 0.0;
786   }
787   gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
788   gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
789   gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
790   
791   last_xtrack_error = _cdiCrossTrackErrorM;
792 }
793
794 void FGNavRadio::updateAudio()
795 {
796   if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
797     return;
798   }
799   
800         // play station ident via audio system if on + ident,
801         // otherwise turn it off
802   if (!power_btn_node->getBoolValue()
803       || !(bus_power_node->getDoubleValue() > 1.0)
804       || !ident_btn_node->getBoolValue()
805       || !audio_btn_node->getBoolValue() ) {
806     _sgr->stop( nav_fx_name );
807     _sgr->stop( dme_fx_name );
808     return;
809   }
810
811   SGSoundSample *sound = _sgr->find( nav_fx_name );
812   double vol = vol_btn_node->getFloatValue();
813   SG_CLAMP_RANGE(vol, 0.0, 1.0);
814   
815   if ( sound != NULL ) {
816     sound->set_volume( vol );
817   } else {
818     SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-vor-ident sound" );
819   }
820   
821   sound = _sgr->find( dme_fx_name );
822   if ( sound != NULL ) {
823     sound->set_volume( vol );
824   } else {
825     SG_LOG( SG_COCKPIT, SG_ALERT, "Can't find nav-dme-ident sound" );
826   }
827   
828   const int NUM_IDENT_SLOTS = 5;
829   const time_t SLOT_LENGTH = 5; // seconds
830
831   // There are N slots numbered 0 through (NUM_IDENT_SLOTS-1) inclusive.
832   // Each slot is 5 seconds long.
833   // Slots 0 is for DME
834   // the rest are for azimuth.
835   time_t now = globals->get_time_params()->get_cur_time();
836   if ((now >= last_time) && (now < last_time + SLOT_LENGTH)) {
837     return; // wait longer
838   }
839   
840   last_time = now;
841   play_count = ++play_count % NUM_IDENT_SLOTS;
842     
843   // Previous ident is out of time;  if still playing, cut it off:
844   _sgr->stop( nav_fx_name );
845   _sgr->stop( dme_fx_name );
846   if (play_count == 0) { // the DME slot
847     if (_dmeInRange && dme_serviceable_node->getBoolValue()) {
848       // play DME ident
849       if (vol > 0.05) _sgr->play_once( dme_fx_name );
850     }
851   } else { // NAV slot
852     if (inrange_node->getBoolValue() && nav_serviceable_node->getBoolValue()) {
853       if (vol > 0.05) _sgr->play_once(nav_fx_name);
854     }
855   }
856 }
857
858 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
859 {
860   FGNavRecord* nav = globals->get_navlist()->findByFreq(aFreqMHz, aPos);
861   if (nav) {
862     return nav;
863   }
864   
865   return globals->get_loclist()->findByFreq(aFreqMHz, aPos);
866 }
867
868 // Update current nav/adf radio stations based on current postition
869 void FGNavRadio::search() 
870 {
871   _time_before_search_sec = 1.0;
872   SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
873     lat_node->getDoubleValue(), alt_node->getDoubleValue());
874   double freq = freq_node->getDoubleValue();
875   
876   FGNavRecord* nav = findPrimaryNavaid(pos, freq);
877   if (nav == _navaid) {
878     return; // found the same as last search, we're done
879   }
880   
881   _navaid = nav;
882   char identBuffer[5] = "    ";
883   if (nav) {
884     _dme = globals->get_dmelist()->findByFreq(freq, pos);
885     
886     nav_id_node->setStringValue(nav->get_ident());
887     strncpy(identBuffer, nav->ident().c_str(), 5);
888     
889     effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range());
890     loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
891     twist = nav->get_multiuse();
892
893     if (nav->type() == FGPositioned::VOR) {
894       target_radial = sel_radial_node->getDoubleValue();
895       _gs = NULL;
896       has_gs_node->setBoolValue(false);
897     } else { // ILS or LOC
898       _gs = globals->get_gslist()->findByFreq(freq, pos);
899       has_gs_node->setBoolValue(_gs != NULL);
900       _localizerWidth = localizerWidth(nav);
901       twist = 0.0;
902             effective_range = nav->get_range();
903       
904       target_radial = nav->get_multiuse();
905       SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
906       
907       if (_gs) {
908         int tmp = (int)(_gs->get_multiuse() / 1000.0);
909         target_gs = (double)tmp / 100.0;
910         
911         // until penaltyForNav goes away, we cannot assume we always pick
912         // paired LOC/GS trasmsitters. As we pass over a runway threshold, we
913         // often end up picking the 'wrong' LOC, but the correct GS. To avoid
914         // breaking the basis computation, ensure we use the GS radial and not
915         // the (potentially reversed) LOC radial.
916         double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
917         SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
918                 
919         // GS axis unit tangent vector
920         // (along the runway)
921         _gsCart = _gs->cart();
922         _gsAxis = tangentVector(_gs->geod(), _gsCart, gs_radial);
923
924         // GS baseline unit tangent vector
925         // (perpendicular to the runay along the ground)
926         SGVec3d baseline = tangentVector(_gs->geod(), _gsCart, gs_radial + 90.0);
927         _gsVertical = cross(baseline, _gsAxis);
928       } // of have glideslope
929     } // of found LOC or ILS
930     
931     audioNavidChanged();
932   } else { // found nothing
933     _gs = NULL;
934     _dme = NULL;
935     nav_id_node->setStringValue("");
936
937     _sgr->remove( nav_fx_name );
938     _sgr->remove( dme_fx_name );
939   }
940
941   is_valid_node->setBoolValue(nav != NULL);
942   id_c1_node->setIntValue( (int)identBuffer[0] );
943   id_c2_node->setIntValue( (int)identBuffer[1] );
944   id_c3_node->setIntValue( (int)identBuffer[2] );
945   id_c4_node->setIntValue( (int)identBuffer[3] );
946 }
947
948 double FGNavRadio::localizerWidth(FGNavRecord* aLOC)
949 {
950   FGRunway* rwy = aLOC->runway();
951   assert(rwy);
952   
953   SGVec3d thresholdCart(SGVec3d::fromGeod(rwy->threshold()));
954   double axisLength = dist(aLOC->cart(), thresholdCart);
955   double landingLength = dist(thresholdCart, SGVec3d::fromGeod(rwy->end()));
956   
957 // Reference: http://dcaa.slv.dk:8000/icaodocs/
958 // ICAO standard width at threshold is 210 m = 689 feet = approx 700 feet.
959 // ICAO 3.1.1 half course = DDM = 0.0775
960 // ICAO 3.1.3.7.1 Sensitivity 0.00145 DDM/m at threshold
961 //  implies peg-to-peg of 214 m ... we will stick with 210.
962 // ICAO 3.1.3.7.1 "Course sector angle shall not exceed 6 degrees."
963               
964 // Very short runway:  less than 1200 m (4000 ft) landing length:
965   if (landingLength < 1200.0) {
966 // ICAO fudges localizer sensitivity for very short runways.
967 // This produces a non-monotonic sensitivity-versus length relation.
968     axisLength += 1050.0;
969   }
970
971 // Example: very short: San Diego   KMYF (Montgomery Field) ILS RWY 28R
972 // Example: short:      Tom's River KMJX (Robert J. Miller) ILS RWY 6
973 // Example: very long:  Denver      KDEN (Denver)           ILS RWY 16R
974   double raw_width = 210.0 / axisLength * SGD_RADIANS_TO_DEGREES;
975   return raw_width < 6.0? raw_width : 6.0;
976 }
977
978 void FGNavRadio::audioNavidChanged()
979 {
980   if (_sgr->exists(nav_fx_name)) {
981                 _sgr->remove(nav_fx_name);
982   }
983   
984   try {
985     string trans_ident(_navaid->get_trans_ident());
986     SGSoundSample* sound = morse.make_ident(trans_ident, LO_FREQUENCY);
987     sound->set_volume( 0.3 );
988     if (!_sgr->add( sound, nav_fx_name )) {
989       SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
990     }
991
992           if ( _sgr->exists( dme_fx_name ) ) {
993       _sgr->remove( dme_fx_name );
994     }
995      
996     sound = morse.make_ident( trans_ident, HI_FREQUENCY );
997     sound->set_volume( 0.3 );
998     _sgr->add( sound, dme_fx_name );
999
1000           int offset = (int)(sg_random() * 30.0);
1001           play_count = offset / 4;
1002     last_time = globals->get_time_params()->get_cur_time() - offset;
1003   } catch (sg_io_exception& e) {
1004     SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());
1005   }
1006 }