]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/dclgps.hxx
KLN89: Move some KLN89 specific configuration from dclgps to kln89
[flightgear.git] / src / Instrumentation / dclgps.hxx
1 // dclgps.hxx - a class to extend the operation of FG's current GPS
2 // code, and provide support for a KLN89-specific instrument.  It
3 // is envisioned that eventually this file and class will be split
4 // up between current FG code and new KLN89-specific code and removed.
5 //
6 // Written by David Luff, started 2005.
7 //
8 // Copyright (C) 2005 - David C Luff:  daveluff --AT-- ntlworld --D0T-- com
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #ifndef _DCLGPS_HXX
27 #define _DCLGPS_HXX
28
29 #include "render_area_2d.hxx"
30 #include <string>
31 #include <list>
32 #include <vector>
33 #include <map>
34
35 #include <simgear/structure/subsystem_mgr.hxx>
36 #include <Navaids/positioned.hxx>
37
38 class SGTime;
39 class FGPositioned;
40
41 // XXX fix me
42 class FGNavRecord;
43 class FGAirport;
44 class FGFix;
45
46 enum GPSDistanceUnits {
47         GPS_DIST_UNITS_NM = 0,
48         GPS_DIST_UNITS_KM
49 };
50
51 enum GPSSpeedUnits {
52         GPS_VEL_UNITS_KT,
53         GPS_VEL_UNITS_KPH
54 };
55
56 enum GPSAltitudeUnits {
57         GPS_ALT_UNITS_FT,
58         GPS_ALT_UNITS_M
59 };
60
61 enum GPSPressureUnits {
62         GPS_PRES_UNITS_IN = 1,
63         GPS_PRES_UNITS_MB,
64         GPS_PRES_UNITS_HP
65 };
66
67 // --------------------- Waypoint / Flightplan stuff -----------------------------
68 // This should be merged with other similar stuff in FG at some point.
69
70 // NOTE - ORDERING IS IMPORTANT HERE - it matches the Bendix-King page ordering!
71 enum GPSWpType {
72         GPS_WP_APT = 0,
73         GPS_WP_VOR,
74         GPS_WP_NDB,
75         GPS_WP_INT,
76         GPS_WP_USR,
77         GPS_WP_VIRT             // Used for virtual waypoints, such as the start of DTO operation.
78 };
79
80 enum GPSAppWpType {
81         GPS_IAF,                // Initial approach fix
82         GPS_IAP,                // Waypoint on approach sequence that isn't any of the others.
83         GPS_FAF,                // Final approach fix
84         GPS_MAP,                // Missed approach point
85         GPS_MAHP,               // Initial missed approach holding point.
86     GPS_HDR,        // A virtual 'waypoint' to represent the approach header in the fpl page
87     GPS_FENCE,      // A virtual 'waypoint' to represent the NO WPT SEQ fence.
88     GPS_APP_NONE    // Not part of the approach sequence - the default.
89 };
90
91 ostream& operator << (ostream& os, GPSAppWpType type);
92
93 struct GPSWaypoint {
94     GPSWaypoint();
95   
96   GPSWaypoint(const std::string& aIdent, float lat, float lon, GPSWpType aType);
97   
98   static GPSWaypoint* createFromPositioned(const FGPositioned* aFix);
99   
100     ~GPSWaypoint();
101         string GetAprId();      // Returns the id with i, f, m or h added if appropriate. (Initial approach fix, final approach fix, etc)
102         string id;
103         float lat;      // Radians
104         float lon;      // Radians
105         GPSWpType type;
106         GPSAppWpType appType;   // only used for waypoints that are part of an approach sequence
107 };
108
109 typedef vector < GPSWaypoint* > gps_waypoint_array;
110 typedef gps_waypoint_array::iterator gps_waypoint_array_iterator;
111 typedef map < string, gps_waypoint_array > gps_waypoint_map;
112 typedef gps_waypoint_map::iterator gps_waypoint_map_iterator;
113 typedef gps_waypoint_map::const_iterator gps_waypoint_map_const_iterator;
114
115 class GPSFlightPlan {
116 public:
117         vector<GPSWaypoint*> waypoints;
118         inline bool IsEmpty() { return(waypoints.size() == 0); }
119 };
120
121 // TODO - probably de-public the internals of the next 2 classes and add some methods!
122 // Instrument approach procedure base class
123 class FGIAP {
124 public:
125         FGIAP();
126         virtual ~FGIAP() = 0;
127 //protected:
128
129         string _aptIdent;       // The ident of the airport this approach is for
130         string _ident;  // The approach ident.
131         string _name;   // The full approach name.
132         string _rwyStr; // The string used to specify the rwy - eg "B" in this instance.
133         bool _precision;        // True for precision approach, false for non-precision.
134 };
135
136 // Non-precision instrument approach procedure
137 class FGNPIAP : public FGIAP {
138 public:
139         FGNPIAP();
140         ~FGNPIAP();
141 //private:
142 public:
143         vector<GPSFlightPlan*> _approachRoutes; // The approach route(s) from the IAF(s) to the IF.
144                                                                                         // NOTE: It is an assumption in the code that uses this that there is a unique IAF per approach route.
145         vector<GPSWaypoint*> _IAP;      // The compulsory waypoints of the approach procedure (may duplicate one of the above).
146                                                                 // _IAP includes the FAF and MAF, and the missed approach waypoints.
147 };
148
149 typedef vector < FGIAP* > iap_list_type;
150 typedef map < string, iap_list_type > iap_map_type;
151 typedef iap_map_type::iterator iap_map_iterator;
152
153 //      A class to encapsulate hr:min representation of time. 
154
155 class ClockTime {
156 public:
157     ClockTime();
158     ClockTime(int hr, int min);
159     ~ClockTime();
160     inline void set_hr(int hr) { _hr = hr; }
161     inline int hr() const { return(_hr); } 
162     inline void set_min(int min) { _min = min; }
163     inline int min() const { return(_min); }
164     
165     ClockTime operator+ (const ClockTime& t) {
166         int cumMin = _hr * 60 + _min + t.hr() * 60 + t.min();
167         ClockTime t2(cumMin / 60, cumMin % 60);
168         return(t2);
169     }
170     // Operator - has a max difference of 23:59,
171     // and assumes the day has wrapped if the second operand
172     // is larger that the first.
173     // eg. 2:59 - 3:00 = 23:59
174     ClockTime operator- (const ClockTime& t) {
175         int diff = (_hr * 60 + _min) - (t.hr() * 60 + t.min());
176         if(diff < 0) { diff += 24 * 60; }
177         ClockTime t2(diff / 60, diff % 60);
178         return(t2);
179     }
180     friend ostream& operator<< (ostream& out, const ClockTime& t);
181
182 private:
183     int _hr;
184     int _min;
185 };
186
187 // ------------------------------------------------------------------------------
188
189 // TODO - merge generic GPS functions instead and split out KLN specific stuff.
190 class DCLGPS : public SGSubsystem {
191         
192 public:
193         DCLGPS(RenderArea2D* instrument);
194         virtual ~DCLGPS() = 0;
195         
196         virtual void draw(osg::State& state);
197         
198         virtual void init();
199         virtual void bind();
200         virtual void unbind();
201         virtual void update(double dt);
202         
203         // Expand a SIAP ident to the full procedure name.
204         string ExpandSIAPIdent(const string& ident);
205
206         // Render string s in display field field at position x, y
207         // WHERE POSITION IS IN CHARACTER UNITS!
208         // zero y at bottom?
209         virtual void DrawText(const string& s, int field, int px, int py, bool bold = false);
210         
211         // Render a char at a given position as above
212         virtual void DrawChar(char c, int field, int px, int py, bool bold = false);
213         
214         virtual void ToggleOBSMode();
215         
216         // Set the number of fields
217         inline void SetNumFields(int n) { _nFields = (n > _maxFields ? _maxFields : (n < 1 ? 1 : n)); }
218         
219         // Set Units
220         // m if true, ft if false
221         inline void SetAltUnitsSI(bool b) { _altUnits = (b ? GPS_ALT_UNITS_M : GPS_ALT_UNITS_FT); }
222         // Returns true if alt units are SI (m), false if ft
223         inline bool GetAltUnitsSI() { return(_altUnits == GPS_ALT_UNITS_M ? true : false); }
224         // km and k/h if true, nm and kt if false
225         inline void SetDistVelUnitsSI(bool b) { _distUnits = (b ? GPS_DIST_UNITS_KM : GPS_DIST_UNITS_NM); _velUnits = (b ? GPS_VEL_UNITS_KPH : GPS_VEL_UNITS_KT); }
226         // Returns true if dist/vel units are SI
227         inline bool GetDistVelUnitsSI() { return(_distUnits == GPS_DIST_UNITS_KM && _velUnits == GPS_VEL_UNITS_KPH ? true : false); }
228         // Set baro units - 1 = in, 2 = mB, 3 = hP   Wrapping if for the convienience of the GPS setter.
229         void SetBaroUnits(int n, bool wrap = false);
230         // Get baro units: 1 = in, 2 = mB, 3 = hP
231         inline int GetBaroUnits() { return((int)_baroUnits); }
232         
233         // It is expected that specific GPS units will override these functions.
234         // Increase the CDI full-scale deflection (ie. increase the nm per dot) one (GPS unit dependent) increment.  Wraps if necessary (GPS unit dependent).
235         virtual void CDIFSDIncrease();
236         // Ditto for decrease the distance per dot
237         virtual void CDIFSDDecrease();
238         
239         // Host specifc
240         ////inline void SetOverlays(Overlays* overlays) { _overlays = overlays; }
241         
242         virtual void CreateDefaultFlightPlans();
243         
244         void SetOBSFromWaypoint();
245         
246         GPSWaypoint* GetActiveWaypoint();
247         // Get the (zero-based) position of the active waypoint in the active flightplan
248         // Returns -1 if no active waypoint.
249         int GetActiveWaypointIndex();
250         // Ditto for an arbitrary waypoint id
251         int GetWaypointIndex(const string& id);
252         
253         // Returns meters
254         float GetDistToActiveWaypoint();
255         // Returns degrees (magnetic)
256         float GetHeadingToActiveWaypoint();
257         // Returns degrees (magnetic)
258         float GetHeadingFromActiveWaypoint();
259         // Get the time to the active waypoint in seconds.
260         // Returns -1 if groundspeed < 30 kts
261         double GetTimeToActiveWaypoint();
262         // Get the time to the final waypoint in seconds.
263         // Returns -1 if groundspeed < 30 kts
264         double GetETE();
265         // Get the time to a given waypoint (spec'd by ID) in seconds.
266         // returns -1 if groundspeed is less than 30kts.
267         // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
268         // otherwise it will be a direct-to time.
269         double GetTimeToWaypoint(const string& id);
270         
271         // Return true if waypoint alerting is occuring
272         inline bool GetWaypointAlert() const { return(_waypointAlert); }
273         // Return true if in OBS mode
274         inline bool GetOBSMode() const { return(_obsMode); }
275         // Return true if in Leg mode
276         inline bool GetLegMode() const { return(!_obsMode); }
277         
278         // Clear a flightplan
279         void ClearFlightPlan(int n);
280         void ClearFlightPlan(GPSFlightPlan* fp);
281         
282         // Returns true if an approach is loaded/armed/active in the active flight plan
283         inline bool ApproachLoaded() const { return(_approachLoaded); }
284         inline bool GetApproachArm() const { return(_approachArm); }
285         inline bool GetApproachActive() const { return(_approachActive); }
286         double GetCDIDeflection() const;
287         inline bool GetToFlag() const { return(_headingBugTo); }
288         
289         // Initiate Direct To operation to the supplied ID.
290         virtual void DtoInitiate(const string& id);
291         // Cancel Direct To operation
292         void DtoCancel();
293         
294 protected:
295         // Maximum number of display fields for this device
296         int _maxFields;
297         // Current number of on-screen fields
298         int _nFields;
299         // Full x border
300         int _xBorder;
301         // Full y border
302         int _yBorder;
303         // Lower (y) border per field
304         int _yFieldBorder[4];
305         // Left (x) border per field
306         int _xFieldBorder[4];
307         // Field start in x dir (border is part of field since it is the normal char border - sometimes map mode etc draws in it)
308         int _xFieldStart[4];
309         // Field start in y dir (for completeness - KLN89 only has vertical divider.
310         int _yFieldStart[4];
311         
312         // The number of pages on the cyclic knob control
313         unsigned int _nPages;
314         // The current page we're on (Not sure how this ties in with extra pages such as direct or nearest).
315         unsigned int _curPage;
316         
317         // 2D rendering area
318         RenderArea2D* _instrument;
319         
320         // Units
321         GPSSpeedUnits _velUnits;
322         GPSDistanceUnits _distUnits;
323         GPSPressureUnits _baroUnits;
324         GPSAltitudeUnits _altUnits;
325         
326         // CDI full-scale deflection, specified either as an index into a vector of values (standard values) or as a double precision float (intermediate values).
327         // This will influence how an externally driven CDI will display as well as the NAV1 page.
328         // Hence the variables are located here, not in the nav page class.
329         vector<float> _cdiScales;
330         unsigned int _currentCdiScaleIndex;
331         bool _cdiScaleTransition;               // Set true when the floating CDI value is used during transitions
332         double _currentCdiScale;        // The floating value to use.
333         unsigned int _targetCdiScaleIndex;      // The target indexed value to attain during a transition.
334         unsigned int _sourceCdiScaleIndex;      // The source indexed value during a transition - so we know which way we're heading!
335         // Timers to handle the transitions - not sure if we need these.
336         double _apprArmTimer;
337         double _apprActvTimer;
338         double _cdiTransitionTime;      // Time for transition to occur in - normally 30sec but may be quicker if time to FAF < 30sec?
339         // 
340         
341         // Data and lookup functions
342
343
344 protected:
345         void LoadApproachData();
346
347         // Find first of any type of waypoint by id.  (TODO - Possibly we should return multiple waypoints here).
348         GPSWaypoint* FindFirstById(const string& id) const;
349         GPSWaypoint* FindFirstByExactId(const string& id) const;
350    
351         FGNavRecord* FindFirstVorById(const string& id, bool &multi, bool exact = false);
352         FGNavRecord* FindFirstNDBById(const string& id, bool &multi, bool exact = false);
353         const FGAirport* FindFirstAptById(const string& id, bool &multi, bool exact = false);
354         const FGFix* FindFirstIntById(const string& id, bool &multi, bool exact = false);
355         // Find the closest VOR to a position in RADIANS.
356         FGNavRecord* FindClosestVor(double lat_rad, double lon_rad);
357
358         // helper to implement the above FindFirstXXX methods
359         FGPositioned* FindTypedFirstById(const std::string& id, FGPositioned::Type ty, bool &multi, bool exact);
360
361         // Position, orientation and velocity.
362         // These should be read from FG's built-in GPS logic if possible.
363         // Use the property node pointers below to do this.
364     SGPropertyNode_ptr _lon_node;
365     SGPropertyNode_ptr _lat_node;
366     SGPropertyNode_ptr _alt_node;
367         SGPropertyNode_ptr _grnd_speed_node;
368         SGPropertyNode_ptr _true_track_node;
369         SGPropertyNode_ptr _mag_track_node;
370         // Present position. (Radians)
371         double _lat, _lon;
372         // Present altitude (ft). (Yuk! but it saves converting ft->m->ft every update).
373         double _alt;
374         // Reported position as measured by GPS.  For now this is the same
375         // as present position, but in the future we might want to model
376         // GPS lat and lon errors.
377         // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
378         // gps code and not our own.
379         double _gpsLat, _gpsLon;  //(Radians)
380         // Hack - it seems that the GPS gets initialised before FG's initial position is properly set.
381         // By checking for abnormal slew in the position we can force a re-initialisation of active flight
382         // plan leg and anything else that might be affected.
383         // TODO - sort FlightGear's initialisation order properly!!!
384         double _checkLat, _checkLon;    // (Radians)
385         double _groundSpeed_ms; // filtered groundspeed (m/s)
386         double _groundSpeed_kts;        // ditto in knots
387         double _track;                  // filtered true track (degrees)
388         double _magTrackDeg;    // magnetic track in degrees calculated from true track above
389         
390         // _navFlagged is set true when GPS navigation is either not possible or not logical.
391         // This includes not receiving adequate signals, and not having an active flightplan entered.
392         bool _navFlagged;
393         
394         // Positional functions copied from ATCutils that might get replaced
395         // INPUT in RADIANS, returns DEGREES!
396         // Magnetic
397         double GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB);
398         // True
399         //double GetHeadingFromTo(double latA, double lonA, double latB, double lonB);
400         
401         // Given two positions (lat & lon in RADIANS), get the HORIZONTAL separation (in meters)
402         //double GetHorizontalSeparation(double lat1, double lon1, double lat2, double lon2);
403         
404         // Proper great circle positional functions from The Aviation Formulary
405         // Returns distance in Nm, input in RADIANS.
406         double GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const;
407         
408         // Input in RADIANS, output in DEGREES.
409         // True
410         double GetGreatCircleCourse(double lat1, double lon1, double lat2, double lon2) const;
411         
412         // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
413         // Note that d should be less that 1/4 Earth diameter!
414         GPSWaypoint GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h);
415         
416         // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
417         // Note that d should be less that 1/4 Earth diameter!
418         GPSWaypoint GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h);
419         
420         // Calculate the current cross-track deviation in nm.
421         // Returns zero if a sensible value cannot be calculated.
422         double CalcCrossTrackDeviation() const;
423         
424         // Calculate the cross-track deviation between 2 arbitrary waypoints in nm.
425         // Returns zero if a sensible value cannot be calculated.
426         double CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const;
427         
428         // Flightplans
429         // GPS can have up to _maxFlightPlans flightplans stored, PLUS an active FP which may or my not be one of the stored ones.
430         // This is from KLN89, but is probably not far off the mark for most if not all GPS.
431         vector<GPSFlightPlan*> _flightPlans;
432         unsigned int _maxFlightPlans;
433         GPSFlightPlan* _activeFP;
434         
435         // Modes of operation.
436         // This is currently somewhat Bendix-King specific, but probably applies fundamentally to other units as well
437         // Mode defaults to leg, but is OBS if _obsMode is true.
438         bool _obsMode;
439         // _dto is set true for DTO operation
440         bool _dto;
441         // In leg mode, we need to know if we are displaying a from and to waypoint, or just the to waypoint (eg. when OBS mode is cancelled).
442         bool _fullLegMode;
443         // In OBS mode we need to know the set OBS heading
444         int _obsHeading;
445         
446         // Operational variables
447         GPSWaypoint _activeWaypoint;
448         GPSWaypoint _fromWaypoint;
449         float _dist2Act;
450         float _crosstrackDist;  // UNITS ??????????
451         double _eta;    // ETA in SECONDS to active waypoint.
452         // Desired track for active leg, true and magnetic, in degrees
453         double _dtkTrue, _dtkMag;
454         bool _headingBugTo;             // Set true when the heading bug is TO, false when FROM.
455         bool _waypointAlert;    // Set true when waypoint alerting is happening. (This is a variable NOT a user-setting).
456         bool _departed;         // Set when groundspeed first exceeds 30kts.
457         string _departureTimeString;    // Ditto.
458         double _elapsedTime;    // Elapsed time in seconds since departure
459         ClockTime _powerOnTime;         // Time (hr:min) of unit power-up.
460         bool _powerOnTimerSet;          // Indicates that we have set the above following power-up.
461         void SetPowerOnTimer();
462 public:
463         void ResetPowerOnTimer();
464         // Set the alarm to go off at a given time.
465         inline void SetAlarm(int hr, int min) {
466                 _alarmTime.set_hr(hr);
467                 _alarmTime.set_min(min);
468                 _alarmSet = true;
469         }
470 protected:
471         ClockTime _alarmTime;
472         bool _alarmSet;
473         
474         // Configuration that affects flightplan operation
475         bool _turnAnticipationEnabled;
476         
477         // Magvar stuff.  Might get some of this stuff (such as time) from FG in future.
478         SGTime* _time;
479         
480         list<string> _messageStack;
481         
482         virtual void CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps);
483         
484         // Orientate the GPS unit to a flightplan - ie. figure out from current position
485         // and possibly orientation which leg of the FP we are on.
486         virtual void OrientateToFlightPlan(GPSFlightPlan* fp);
487         
488         // Ditto for active fp.  Probably all we need really!
489         virtual void OrientateToActiveFlightPlan();
490         
491         int _cleanUpPage;       // -1 => no cleanup required.
492         
493         // IAP stuff
494         iap_map_type _np_iap;   // Non-precision approaches
495         iap_map_type _pr_iap;   // Precision approaches
496         bool _approachLoaded;   // Set true when an approach is loaded in the active flightplan
497         bool _approachArm;              // Set true when in approach-arm mode
498         bool _approachReallyArmed;      // Apparently, approach-arm mode can be set from an external GPS-APR switch outside 30nm from airport,
499                                                                 // but the CDI scale change doesn't happen until 30nm from airport.  Bizarre that it can be armed without
500                                                                 // the scale change, but it's in the manual...
501         bool _approachActive;   // Set true when in approach-active mode
502         GPSFlightPlan* _approachFP;     // Current approach - not necessarily loaded.
503         string _approachID;             // ID of the airport we have an approach loaded for - bit of a hack that can hopefully be removed in future.
504         // More hackery since we aren't actually storing an approach class... Doh!
505         string _approachAbbrev;
506         string _approachRwyStr;
507 };
508
509 #endif  // _DCLGPS_HXX