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