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