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