1 // rnav_waypt_controller.cxx - Waypoint-specific behaviours for RNAV systems
2 // Written by James Turner, started 2009.
4 // Copyright (C) 2009 Curtis L. Olson
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 #include "rnav_waypt_controller.hxx"
24 #include <simgear/sg_inlines.h>
25 #include <simgear/structure/exception.hxx>
27 #include <Airports/runways.hxx>
32 const double KNOTS_TO_METRES_PER_SECOND = SG_NM_TO_METER / 3600.0;
34 double pmod(double x, double y)
44 // http://williams.best.vwh.net/avform.htm#Intersection
45 bool geocRadialIntersection(const SGGeoc& a, double r1, const SGGeoc& b, double r2, SGGeoc& result)
47 double crs13 = r1 * SG_DEGREES_TO_RADIANS;
48 double crs23 = r2 * SG_DEGREES_TO_RADIANS;
49 double dst12 = SGGeodesy::distanceRad(a, b);
52 // crs12=acos((sin(lat2)-sin(lat1)*cos(dst12))/(sin(dst12)*cos(lat1)))
53 // crs21=2.*pi-acos((sin(lat1)-sin(lat2)*cos(dst12))/(sin(dst12)*cos(lat2)))
55 // crs12=2.*pi-acos((sin(lat2)-sin(lat1)*cos(dst12))/(sin(dst12)*cos(lat1)))
56 // crs21=acos((sin(lat1)-sin(lat2)*cos(dst12))/(sin(dst12)*cos(lat2)))
60 // double diffLon = b.getLongitudeRad() - a.getLongitudeRad();
62 double sinLat1 = sin(a.getLatitudeRad());
63 double cosLat1 = cos(a.getLatitudeRad());
64 // double sinLat2 = sin(b.getLatitudeRad());
65 //double cosLat2 = cos(b.getLatitudeRad());
66 double sinDst12 = sin(dst12);
67 double cosDst12 = cos(dst12);
69 double crs12 = SGGeodesy::courseRad(a, b),
70 crs21 = SGGeodesy::courseRad(b, a);
72 //double degCrs12 = crs12 * SG_RADIANS_TO_DEGREES;
73 //double degCrs21 = crs21 * SG_RADIANS_TO_DEGREES;
76 if (sin(diffLon) < 0.0) {
77 crs12 = acos((sinLat2 - sinLat1 * cosDst12) / (sinDst12 * cosLat1));
78 crs21 = SGMiscd::twopi() - acos((sinLat1 - sinLat2*cosDst12)/(sinDst12*cosLat2));
80 crs12 = SGMiscd::twopi() - acos((sinLat2 - sinLat1 * cosDst12)/(sinDst12 * cosLat1));
81 crs21 = acos((sinLat1 - sinLat2 * cosDst12)/(sinDst12 * cosLat2));
85 double ang1 = SGMiscd::normalizeAngle2(crs13-crs12);
86 double ang2 = SGMiscd::normalizeAngle2(crs21-crs23);
88 if ((sin(ang1) == 0.0) && (sin(ang2) == 0.0)) {
89 SG_LOG(SG_INSTR, SG_WARN, "geocRadialIntersection: infinity of intersections");
93 if ((sin(ang1)*sin(ang2))<0.0) {
94 SG_LOG(SG_INSTR, SG_WARN, "geocRadialIntersection: intersection ambiguous");
101 //ang3=acos(-cos(ang1)*cos(ang2)+sin(ang1)*sin(ang2)*cos(dst12))
102 //dst13=atan2(sin(dst12)*sin(ang1)*sin(ang2),cos(ang2)+cos(ang1)*cos(ang3))
103 //lat3=asin(sin(lat1)*cos(dst13)+cos(lat1)*sin(dst13)*cos(crs13))
105 //lon3=mod(lon1-dlon+pi,2*pi)-pi
107 double ang3 = acos(-cos(ang1) * cos(ang2) + sin(ang1) * sin(ang2) * cosDst12);
108 double dst13 = atan2(sinDst12 * sin(ang1) * sin(ang2), cos(ang2) + cos(ang1)*cos(ang3));
111 SGGeodesy::advanceRadM(a, crs13, dst13 * SG_RAD_TO_NM * SG_NM_TO_METER, pt3);
113 double lat3 = asin(sinLat1 * cos(dst13) + cosLat1 * sin(dst13) * cos(crs13));
115 //dlon=atan2(sin(crs13)*sin(dst13)*cos(lat1),cos(dst13)-sin(lat1)*sin(lat3))
116 double dlon = atan2(sin(crs13)*sin(dst13)*cosLat1, cos(dst13)- (sinLat1 * sin(lat3)));
117 double lon3 = SGMiscd::normalizeAngle(-a.getLongitudeRad()-dlon);
119 result = SGGeoc::fromRadM(-lon3, lat3, a.getRadiusM());
126 * Helper function Cross track error:
127 * http://williams.best.vwh.net/avform.htm#XTE
129 * param distanceOriginToPosition in Nautical Miles
130 * param courseDev difference between courseOriginToAircraft(AD) and courseOriginToTarget(AB)
131 * return XTE in Nautical Miles
135 * D(aircraft) perhaps off course
143 double greatCircleCrossTrackError(double distanceOriginToPosition,double courseDev){
144 double crossTrackError = asin(
145 sin(distanceOriginToPosition * SG_NM_TO_RAD) *
146 sin(courseDev * SG_DEGREES_TO_RADIANS)
148 return crossTrackError * SG_RAD_TO_NM;
152 ////////////////////////////////////////////////////////////////////////////
154 WayptController::~WayptController()
158 void WayptController::init()
162 void WayptController::setDone()
165 SG_LOG(SG_AUTOPILOT, SG_WARN, "already done @ WayptController::setDone");
171 double WayptController::timeToWaypt() const
173 double gs = _rnav->groundSpeedKts();
175 return -1.0; // stationary
178 gs*= KNOTS_TO_METRES_PER_SECOND;
179 return (distanceToWayptM() / gs);
184 class BasicWayptCtl : public WayptController
187 BasicWayptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
188 WayptController(aRNAV, aWpt),
189 _distanceAircraftTargetMeter(0.0),
192 if (aWpt->flag(WPT_DYNAMIC)) {
193 throw sg_exception("BasicWayptCtrl doesn't work with dynamic waypoints");
199 _targetTrack = SGGeodesy::courseDeg(_rnav->position(), _waypt->position());
202 virtual void update()
204 double bearingAircraftToTarget;
206 bearingAircraftToTarget = SGGeodesy::courseDeg(_rnav->position(), _waypt->position());
207 _distanceAircraftTargetMeter = SGGeodesy::distanceM(_rnav->position(), _waypt->position());
209 _courseDev = bearingAircraftToTarget - _targetTrack;
210 SG_NORMALIZE_RANGE(_courseDev, -180.0, 180.0);
212 if ((fabs(_courseDev) > _rnav->overflightArmAngleDeg()) && (_distanceAircraftTargetMeter < _rnav->overflightArmDistanceM())) {
217 virtual double distanceToWayptM() const
219 return _distanceAircraftTargetMeter;
222 virtual double xtrackErrorNm() const
224 double x = sin(courseDeviationDeg() * SG_DEGREES_TO_RADIANS) * _distanceAircraftTargetMeter;
225 return x * SG_METER_TO_NM;
228 virtual bool toFlag() const
230 return (fabs(_courseDev) < _rnav->overflightArmAngleDeg());
233 virtual double courseDeviationDeg() const
238 virtual double trueBearingDeg() const
240 return SGGeodesy::courseDeg(_rnav->position(), _waypt->position());
243 virtual SGGeod position() const
245 return _waypt->position();
249 double _distanceAircraftTargetMeter;
254 * Controller for leg course interception.
255 * In leg mode, we want to intercept the leg between 2 waypoints(A->B).
256 * If we can't reach the the selected waypoint leg,we going direct to B.
259 class LegWayptCtl : public WayptController
262 LegWayptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
263 WayptController(aRNAV, aWpt),
265 _distanceOriginAircraftMeter(0.0),
266 _distanceAircraftTargetMeter(0.0),
267 _courseOriginToAircraft(0.0),
268 _courseAircraftToTarget(0.0),
272 if (aWpt->flag(WPT_DYNAMIC)) {
273 throw sg_exception("LegWayptCtl doesn't work with dynamic waypoints");
279 double courseOriginTarget;
280 bool isPreviousLegValid = false;
282 _waypointOrigin = _rnav->previousLegWaypointPosition(isPreviousLegValid);
284 courseOriginTarget = SGGeodesy::courseDeg(_waypointOrigin,_waypt->position());
286 _courseAircraftToTarget = SGGeodesy::courseDeg(_rnav->position(),_waypt->position());
287 _distanceAircraftTargetMeter = SGGeodesy::distanceM(_rnav->position(),_waypt->position());
290 // check reach the leg in 45Deg or going direct
291 bool canReachLeg = (fabs(courseOriginTarget -_courseAircraftToTarget) < 45.0);
293 if ( isPreviousLegValid && canReachLeg){
294 _targetTrack = courseOriginTarget;
296 _targetTrack = _courseAircraftToTarget;
297 _waypointOrigin = _rnav->position();
302 virtual void update()
304 _courseOriginToAircraft = SGGeodesy::courseDeg(_waypointOrigin,_rnav->position());
305 _distanceOriginAircraftMeter = SGGeodesy::distanceM(_waypointOrigin,_rnav->position());
307 _courseAircraftToTarget = SGGeodesy::courseDeg(_rnav->position(),_waypt->position());
308 _distanceAircraftTargetMeter = SGGeodesy::distanceM(_rnav->position(),_waypt->position());
310 _courseDev = -(_courseOriginToAircraft - _targetTrack);
312 bool isMinimumOverFlightDistanceReached = _distanceAircraftTargetMeter < _rnav->overflightDistanceM();
313 bool isOverFlightConeArmed = _distanceAircraftTargetMeter < ( _rnav->overflightArmDistanceM() + _rnav->overflightDistanceM() );
314 bool leavingOverFlightCone = (fabs(_courseAircraftToTarget - _targetTrack) > _rnav->overflightArmAngleDeg());
316 if( isMinimumOverFlightDistanceReached ){
320 if( isOverFlightConeArmed ){
322 if ( leavingOverFlightCone ) {
331 virtual double distanceToWayptM() const
333 return _distanceAircraftTargetMeter;
336 virtual double xtrackErrorNm() const
338 return greatCircleCrossTrackError(_distanceOriginAircraftMeter * SG_METER_TO_NM, _courseDev);
341 virtual bool toFlag() const
346 virtual double courseDeviationDeg() const
351 virtual double trueBearingDeg() const
353 return _courseAircraftToTarget;
356 virtual SGGeod position() const
358 return _waypt->position();
365 * A(from), B(to), D(position) perhaps off course
367 SGGeod _waypointOrigin;
368 double _distanceOriginAircraftMeter;
369 double _distanceAircraftTargetMeter;
370 double _courseOriginToAircraft;
371 double _courseAircraftToTarget;
378 * Special controller for runways. For runways, we want very narrow deviation
379 * constraints, and to understand that any point along the paved area is
380 * equivalent to being 'at' the runway.
382 class RunwayCtl : public WayptController
385 RunwayCtl(RNAV* aRNAV, const WayptRef& aWpt) :
386 WayptController(aRNAV, aWpt),
388 _distanceAircraftRunwayEnd(0.0),
395 _runway = static_cast<RunwayWaypt*>(_waypt.get())->runway();
396 _targetTrack = _runway->headingDeg();
399 virtual void update()
401 double bearingAircraftRunwayEnd;
402 // use the far end of the runway for course deviation calculations.
403 // this should do the correct thing both for takeoffs (including entering
404 // the runway at a taxiway after the threshold) and also landings.
405 // seperately compute the distance to the threshold for timeToWaypt calc
407 bearingAircraftRunwayEnd = SGGeodesy::courseDeg(_rnav->position(), _runway->end());
408 _distanceAircraftRunwayEnd = SGGeodesy::distanceM(_rnav->position(), _runway->end());
410 double _courseDev = bearingAircraftRunwayEnd - _targetTrack;
411 SG_NORMALIZE_RANGE(_courseDev, -180.0, 180.0);
413 if ((fabs(_courseDev) > _rnav->overflightArmAngleDeg()) && (_distanceAircraftRunwayEnd < _rnav->overflightArmDistanceM())) {
418 virtual double distanceToWayptM() const
420 return SGGeodesy::distanceM(_rnav->position(), _runway->threshold());
423 virtual double xtrackErrorNm() const
425 double x = sin(_courseDev * SG_RADIANS_TO_DEGREES) * _distanceAircraftRunwayEnd;
426 return x * SG_METER_TO_NM;
429 virtual double courseDeviationDeg() const
434 virtual double trueBearingDeg() const
436 // as in update(), use runway->end here, so the value remains
437 // sensible whether taking off or landing.
438 return SGGeodesy::courseDeg(_rnav->position(), _runway->end());
441 virtual SGGeod position() const
443 return _runway->threshold();
447 double _distanceAircraftRunwayEnd;
451 class ConstHdgToAltCtl : public WayptController
454 ConstHdgToAltCtl(RNAV* aRNAV, const WayptRef& aWpt) :
455 WayptController(aRNAV, aWpt)
458 if (_waypt->type() != "hdgToAlt") {
459 throw sg_exception("invalid waypoint type", "ConstHdgToAltCtl ctor");
462 if (_waypt->altitudeRestriction() == RESTRICT_NONE) {
463 throw sg_exception("invalid waypoint alt restriction", "ConstHdgToAltCtl ctor");
469 HeadingToAltitude* w = (HeadingToAltitude*) _waypt.get();
470 _targetTrack = w->headingDegMagnetic() + _rnav->magvarDeg();
473 virtual void update()
475 double curAlt = _rnav->position().getElevationFt();
477 switch (_waypt->altitudeRestriction()) {
479 case RESTRICT_COMPUTED:
481 double d = curAlt - _waypt->altitudeFt();
482 if (fabs(d) < 50.0) {
483 SG_LOG(SG_INSTR, SG_INFO, "ConstHdgToAltCtl, reached target altitude " << _waypt->altitudeFt());
489 if (curAlt >= _waypt->altitudeFt()) {
490 SG_LOG(SG_INSTR, SG_INFO, "ConstHdgToAltCtl, above target altitude " << _waypt->altitudeFt());
496 if (curAlt <= _waypt->altitudeFt()) {
497 SG_LOG(SG_INSTR, SG_INFO, "ConstHdgToAltCtl, below target altitude " << _waypt->altitudeFt());
507 virtual double timeToWaypt() const
509 double d = fabs(_rnav->position().getElevationFt() - _waypt->altitudeFt());
510 return (d / _rnav->vspeedFPM()) * 60.0; // low pass filter here, probably
513 virtual double distanceToWayptM() const
515 double gsMsec = _rnav->groundSpeedKts() * KNOTS_TO_METRES_PER_SECOND;
516 return timeToWaypt() * gsMsec;
519 virtual SGGeod position() const
523 SGGeodesy::direct(_rnav->position(), _targetTrack, distanceToWayptM(), p, az2);
528 class InterceptCtl : public WayptController
531 InterceptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
532 WayptController(aRNAV, aWpt),
535 if (_waypt->type() != "radialIntercept") {
536 throw sg_exception("invalid waypoint type", "InterceptCtl ctor");
542 RadialIntercept* w = (RadialIntercept*) _waypt.get();
543 _trueRadial = w->radialDegMagnetic() + _rnav->magvarDeg();
544 _targetTrack = w->courseDegMagnetic() + _rnav->magvarDeg();
547 virtual void update()
549 // note we want the outbound radial from the waypt, hence the ordering
550 // of arguments to courseDeg
551 double r = SGGeodesy::courseDeg(_waypt->position(), _rnav->position());
552 SG_LOG(SG_AUTOPILOT, SG_INFO, "current radial=" << r);
553 if (fabs(r - _trueRadial) < 0.5) {
554 SG_LOG(SG_INSTR, SG_INFO, "InterceptCtl, intercepted radial " << _trueRadial);
559 virtual double distanceToWayptM() const
561 return SGGeodesy::distanceM(_rnav->position(), position());
564 virtual SGGeod position() const
567 geocRadialIntersection(SGGeoc::fromGeod(_rnav->position()), _rnav->trackDeg(),
568 SGGeoc::fromGeod(_waypt->position()), _trueRadial, c);
569 return SGGeod::fromGeoc(c);
575 class DMEInterceptCtl : public WayptController
578 DMEInterceptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
579 WayptController(aRNAV, aWpt),
583 if (_waypt->type() != "dmeIntercept") {
584 throw sg_exception("invalid waypoint type", "DMEInterceptCtl ctor");
590 _dme = (DMEIntercept*) _waypt.get();
591 _targetTrack = _dme->courseDegMagnetic() + _rnav->magvarDeg();
594 virtual void update()
596 _distanceNm = SGGeodesy::distanceNm(_rnav->position(), _dme->position());
597 double d = fabs(_distanceNm - _dme->dmeDistanceNm());
599 SG_LOG(SG_INSTR, SG_INFO, "DMEInterceptCtl, intercepted DME " << _dme->dmeDistanceNm());
604 virtual double distanceToWayptM() const
606 return fabs(_distanceNm - _dme->dmeDistanceNm()) * SG_NM_TO_METER;
609 virtual SGGeod position() const
613 SGGeodesy::direct(_rnav->position(), _targetTrack, distanceToWayptM(), p, az2);
622 class HoldCtl : public WayptController
625 HoldCtl(RNAV* aRNAV, const WayptRef& aWpt) :
626 WayptController(aRNAV, aWpt)
636 virtual void update()
638 // fly inbound / outbound sides, or execute the turn
642 targetTrack += dt * turnRateSec * turnDirection;
644 if .. targetTrack has passed inbound radial, doen with this turn
646 if target track has passed reciprocal radial done with turn
649 check time / distance elapsed
654 nextHeading = inbound;
656 nextHeading += 180.0;
657 SG_NORMALIZE_RANGE(nextHeading, 0.0, 360.0);
667 virtual double distanceToWayptM() const
672 virtual SGGeod position() const
674 return _waypt->position();
678 class VectorsCtl : public WayptController
681 VectorsCtl(RNAV* aRNAV, const WayptRef& aWpt) :
682 WayptController(aRNAV, aWpt)
692 virtual void update()
697 virtual double distanceToWayptM() const
702 virtual SGGeod position() const
704 return _waypt->position();
710 ///////////////////////////////////////////////////////////////////////////////
712 DirectToController::DirectToController(RNAV* aRNAV, const WayptRef& aWpt, const SGGeod& aOrigin) :
713 WayptController(aRNAV, aWpt),
715 _distanceAircraftTargetMeter(0.0),
717 _courseAircraftToTarget(0.0)
721 void DirectToController::init()
723 if (_waypt->flag(WPT_DYNAMIC)) {
724 throw sg_exception("can't direct-to a dynamic waypoint");
727 _targetTrack = SGGeodesy::courseDeg(_origin, _waypt->position());
730 void DirectToController::update()
732 double courseOriginToAircraft;
734 courseOriginToAircraft = SGGeodesy::courseDeg(_origin,_rnav->position());
736 _courseAircraftToTarget = SGGeodesy::courseDeg(_rnav->position(),_waypt->position());
737 _distanceAircraftTargetMeter = SGGeodesy::distanceM(_rnav->position(),_waypt->position());
739 _courseDev = -(courseOriginToAircraft - _targetTrack);
741 SG_NORMALIZE_RANGE(_courseDev, -180.0, 180.0);
743 bool isMinimumOverFlightDistanceReached = _distanceAircraftTargetMeter < _rnav->overflightDistanceM();
744 bool isOverFlightConeArmed = _distanceAircraftTargetMeter < ( _rnav->overflightArmDistanceM() + _rnav->overflightDistanceM() );
745 bool leavingOverFlightCone = (fabs(_courseAircraftToTarget - _targetTrack) > _rnav->overflightArmAngleDeg());
747 if( isMinimumOverFlightDistanceReached ){
750 if( isOverFlightConeArmed && leavingOverFlightCone ){
756 double DirectToController::distanceToWayptM() const
758 return _distanceAircraftTargetMeter;
761 double DirectToController::xtrackErrorNm() const
763 return greatCircleCrossTrackError(_distanceAircraftTargetMeter * SG_METER_TO_NM, _courseDev);
766 double DirectToController::courseDeviationDeg() const
771 double DirectToController::trueBearingDeg() const
773 return _courseAircraftToTarget;
776 SGGeod DirectToController::position() const
778 return _waypt->position();
781 ///////////////////////////////////////////////////////////////////////////////
783 OBSController::OBSController(RNAV* aRNAV, const WayptRef& aWpt) :
784 WayptController(aRNAV, aWpt),
785 _distanceAircraftTargetMeter(0.0),
787 _courseAircraftToTarget(0.0)
791 void OBSController::init()
793 if (_waypt->flag(WPT_DYNAMIC)) {
794 throw sg_exception("can't use a dynamic waypoint for OBS mode");
797 _targetTrack = _rnav->selectedMagCourse() + _rnav->magvarDeg();
800 void OBSController::update()
802 _targetTrack = _rnav->selectedMagCourse() + _rnav->magvarDeg();
804 _courseAircraftToTarget = SGGeodesy::courseDeg(_rnav->position(),_waypt->position());
805 _distanceAircraftTargetMeter = SGGeodesy::distanceM(_rnav->position(),_waypt->position());
807 // _courseDev inverted we use point target as origin
808 _courseDev = (_courseAircraftToTarget - _targetTrack);
809 SG_NORMALIZE_RANGE(_courseDev, -180.0, 180.0);
812 bool OBSController::toFlag() const
814 return (fabs(_courseDev) < _rnav->overflightArmAngleDeg());
817 double OBSController::distanceToWayptM() const
819 return _distanceAircraftTargetMeter;
822 double OBSController::xtrackErrorNm() const
824 return greatCircleCrossTrackError(_distanceAircraftTargetMeter * SG_METER_TO_NM, _courseDev);
827 double OBSController::courseDeviationDeg() const
829 // if (fabs(_courseDev) > 90.0) {
830 // double d = -_courseDev;
831 // SG_NORMALIZE_RANGE(d, -90.0, 90.0);
838 double OBSController::trueBearingDeg() const
840 return _courseAircraftToTarget;
843 SGGeod OBSController::position() const
845 return _waypt->position();
848 ///////////////////////////////////////////////////////////////////////////////
850 WayptController* WayptController::createForWaypt(RNAV* aRNAV, const WayptRef& aWpt)
853 throw sg_exception("Passed null waypt", "WayptController::createForWaypt");
856 const std::string& wty(aWpt->type());
857 if (wty == "runway") {
858 return new RunwayCtl(aRNAV, aWpt);
861 if (wty == "radialIntercept") {
862 return new InterceptCtl(aRNAV, aWpt);
865 if (wty == "dmeIntercept") {
866 return new DMEInterceptCtl(aRNAV, aWpt);
869 if (wty == "hdgToAlt") {
870 return new ConstHdgToAltCtl(aRNAV, aWpt);
873 if (wty == "vectors") {
874 return new VectorsCtl(aRNAV, aWpt);
878 return new HoldCtl(aRNAV, aWpt);
881 return new LegWayptCtl(aRNAV, aWpt);
884 } // of namespace flightgear