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