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