1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
3 // Written by David Culp, started October 2003.
5 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
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.
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.
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.
25 #include <Main/fg_props.hxx>
26 #include <Main/globals.hxx>
27 #include <Scenery/scenery.hxx>
28 #include <Scenery/tilemgr.hxx>
29 #include <Airports/dynamics.hxx>
30 #include <Airports/airport.hxx>
31 #include <Main/util.hxx>
32 #include <Traffic/Schedule.hxx>
34 #include <simgear/structure/exception.hxx>
40 // defined in AIShip.cxx
41 extern double fgIsFinite(double x);
43 #include "AIManager.hxx"
44 #include "AIAircraft.hxx"
45 #include "AIFlightPlan.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
54 //#include <Airports/trafficcontroller.hxx>
56 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
57 /* HOT must be disabled for AI Aircraft,
58 * otherwise traffic detection isn't working as expected.*/
59 FGAIBase(otAircraft, false),
64 groundOffset = trafficRef->getGroundOffset();
65 setCallSign(trafficRef->getCallSign());
81 groundTargetSpeed = 0;
83 // set heading and altitude locks
87 headingChangeRate = 0.0;
91 prev_dist_to_go = 0.0;
94 needsTaxiClearance = false;
95 _needsGroundElevation = true;
97 PerformanceDB* perfDB = globals->get_subsystem<PerformanceDB>();
99 _performance = perfDB->getDefaultPerformance();
101 SG_LOG(SG_AI, SG_ALERT, "no performance DB found");
107 trackCache.remainingLength = 0;
108 trackCache.startWptName = "-";
112 FGAIAircraft::~FGAIAircraft() {
115 controller->signOff(getID());
119 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
123 FGAIBase::readFromScenario(scFileNode);
125 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
126 setFlightPlan(scFileNode->getStringValue("flightplan"),
127 scFileNode->getBoolValue("repeat", false));
128 setCallSign(scFileNode->getStringValue("callsign"));
132 void FGAIAircraft::bind() {
135 tie("transponder-id",
136 SGRawValueMethods<FGAIAircraft,const char*>(*this,
137 &FGAIAircraft::_getTransponderCode));
140 void FGAIAircraft::update(double dt) {
141 FGAIBase::update(dt);
146 void FGAIAircraft::unbind()
149 clearATCController();
152 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
154 PerformanceDB* perfDB = globals->get_subsystem<PerformanceDB>();
156 _performance = perfDB->getDataFor(acType, acclass);
161 void FGAIAircraft::setPerformance(PerformanceData *ps) {
166 void FGAIAircraft::Run(double dt) {
167 FGAIAircraft::dt = dt;
169 bool outOfSight = false,
170 flightplanActive = true;
171 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
176 if (!flightplanActive) {
177 groundTargetSpeed = 0;
180 handleATCRequests(); // ATC also has a word to say
181 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
184 // 25/11/12 - added but disabled, since setting properties isn't
185 // affecting the AI-model as expected.
186 updateModelProperties(dt);
189 // We currently have one situation in which an AIAircraft object is used that is not attached to the
190 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
191 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
194 UpdateRadar(manager);
195 invisible = !manager->isVisible(pos);
200 void FGAIAircraft::AccelTo(double speed) {
202 //assertSpeed(speed);
204 _needsGroundElevation = true;
208 void FGAIAircraft::PitchTo(double angle) {
214 void FGAIAircraft::RollTo(double angle) {
220 void FGAIAircraft::YawTo(double angle) {
225 void FGAIAircraft::ClimbTo(double alt_ft ) {
226 tgt_altitude_ft = alt_ft;
231 void FGAIAircraft::TurnTo(double heading) {
232 tgt_heading = heading;
237 double FGAIAircraft::sign(double x) {
245 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
247 if (flightplan.empty()) {
248 // this is the case for Nasal-scripted aircraft
252 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
253 if (fp->isValidPlan()) {
254 fp->setRepeat(repeat);
257 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
263 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
270 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
272 // the one behind you
273 FGAIWaypoint* prev = 0;
275 FGAIWaypoint* curr = 0;
277 FGAIWaypoint* next = 0;
279 prev = fp->getPreviousWaypoint();
280 curr = fp->getCurrentWaypoint();
281 next = fp->getNextWaypoint();
285 ///////////////////////////////////////////////////////////////////////////
286 // Initialize the flightplan
287 //////////////////////////////////////////////////////////////////////////
289 handleFirstWaypoint();
291 } // end of initialization
292 if (! fpExecutable(now))
296 double distanceToDescent;
297 if(reachedEndOfCruise(distanceToDescent)) {
298 if (!loadNextLeg(distanceToDescent)) {
302 prev = fp->getPreviousWaypoint();
303 curr = fp->getCurrentWaypoint();
304 next = fp->getNextWaypoint();
312 if (! leadPointReached(curr)) {
313 controlHeading(curr);
314 controlSpeed(curr, next);
318 cerr << getCallSign()
319 << ": verifying lead distance to waypoint : "
320 << fp->getCurrentWaypoint()->name << " "
321 << fp->getLeadDistance() << ". Distance to go "
322 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
323 << ". Target speed = "
325 << ". Current speed = "
327 << ". Minimum Bearing " << minBearing
331 if (curr->isFinished()) //end of the flight plan
341 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
342 tgt_heading = fp->getBearing(curr, next);
346 //TODO let the fp handle this (loading of next leg)
347 fp->IncrementWaypoint( trafficRef != 0 );
348 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
349 if (!loadNextLeg()) {
354 prev = fp->getPreviousWaypoint();
355 curr = fp->getCurrentWaypoint();
356 next = fp->getNextWaypoint();
358 // Now that we have incremented the waypoints, excute some traffic manager specific code
360 //TODO isn't this best executed right at the beginning?
361 if (! aiTrafficVisible()) {
366 if (! handleAirportEndPoints(prev, now)) {
371 announcePositionToController();
376 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
380 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
382 tgt_altitude_ft = prev->getAltitude();
383 if (curr->getCrossat() > -1000.0) {
385 // Distance to go in meters
386 double vert_dist_ft = curr->getCrossat() - altitude_ft;
387 double err_dist = prev->getCrossat() - altitude_ft;
388 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
389 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
392 tgt_altitude_ft = curr->getCrossat();
397 AccelTo(prev->getSpeed());
398 hdg_lock = alt_lock = true;
399 no_roll = prev->getOn_ground();
403 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
405 // err is negative when we passed too high
406 double vert_m = vert_ft * SG_FEET_TO_METER;
407 //double err_m = err * SG_FEET_TO_METER;
408 //double angle = atan2(vert_m, dist_m);
409 double speedMs = (speed * SG_NM_TO_METER) / 3600;
410 //double vs = cos(angle) * speedMs; // Now in m/s
412 //cerr << "Error term = " << err_m << endl;
414 vs = ((vert_m) / dist_m) * speedMs;
416 // Convert to feet per minute
417 vs *= (SG_METER_TO_FEET * 60);
418 //if (getCallSign() == "LUFTHANSA2002")
419 //if (fabs(vs) > 100000) {
420 // if (getCallSign() == "LUFTHANSA2057") {
421 // cerr << getCallSign() << " " << fp->getPreviousWaypoint()->getName() << ". Alt = " << altitude_ft << " vertical dist = " << vert_m << " horiz dist = " << dist_m << " << angle = " << angle * SG_RADIANS_TO_DEGREES << " vs " << vs << " horizontal speed " << speed << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat() << endl;
422 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
423 // // / 6076.0 / speed*60.0);
429 void FGAIAircraft::clearATCController()
436 void FGAIAircraft::assertSpeed(double speed)
438 if ((speed < -50) || (speed > 1000)) {
439 cerr << getCallSign() << " "
440 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
441 << "Departure airport " << trafficRef->getDepartureAirport() << " "
442 << "Leg " << fp->getLeg() << " "
443 << "target_speed << " << tgt_speed << " "
444 << "speedFraction << " << speedFraction << " "
445 << "Currecnt speed << " << speed << " "
453 void FGAIAircraft::checkTcas(void)
455 if (props->getIntValue("tcas/threat-level",0)==3)
457 int RASense = props->getIntValue("tcas/ra-sense",0);
458 if ((RASense>0)&&(tgt_vs<4000))
464 // downward RA: descend!
465 if (altitude_ft < 1000)
467 // too low: level off
480 void FGAIAircraft::initializeFlightPlan() {
483 const char * FGAIAircraft::_getTransponderCode() const {
484 return transponderCode.c_str();
487 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
488 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
490 bool FGAIAircraft::loadNextLeg(double distance) {
493 if ((leg = fp->getLeg()) == 9) {
494 if (!trafficRef->next()) {
497 setCallSign(trafficRef->getCallSign());
502 FGAirport *dep = trafficRef->getDepartureAirport();
503 FGAirport *arr = trafficRef->getArrivalAirport();
508 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
515 trafficRef->getSpeed(),
519 trafficRef->getRadius(),
520 trafficRef->getFlightType(),
524 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
530 // Note: This code is copied from David Luff's AILocalTraffic
531 // Warning - ground elev determination is CPU intensive
532 // Either this function or the logic of how often it is called
533 // will almost certainly change.
535 void FGAIAircraft::getGroundElev(double dt) {
538 if (!needGroundElevation())
540 // Update minimally every three secs, but add some randomness
541 // to prevent all AI objects doing this in synchrony
542 if (dt_elev_count < (3.0) + (rand() % 10))
547 // Only do the proper hitlist stuff if we are within visible range of the viewer.
549 double visibility_meters = fgGetDouble("/environment/visibility-m");
550 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
554 double range = 500.0;
555 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
558 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
560 tgt_altitude_ft = alt * SG_METER_TO_FEET;
563 // aircraft is stationary and we obtained altitude for this spot - we're done.
564 _needsGroundElevation = false;
572 void FGAIAircraft::doGroundAltitude() {
573 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
576 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
578 altitude_ft = (tgt_altitude_ft + groundOffset);
580 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
586 void FGAIAircraft::announcePositionToController() {
591 int leg = fp->getLeg();
592 if (!fp->getCurrentWaypoint()) {
593 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
594 // throw an exception so this aircraft gets killed by the AIManager.
595 throw sg_exception("bad AI flight plan");
598 // Note that leg has been incremented after creating the current leg, so we should use
599 // leg numbers here that are one higher than the number that is used to create the leg
600 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
601 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
602 // the original leg numbers here!
604 case 1: // Startup and Push back
605 if (trafficRef->getDepartureAirport()->getDynamics())
606 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
608 case 2: // Taxiing to runway
609 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists())
610 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController();
612 case 3: //Take off tower controller
613 if (trafficRef->getDepartureAirport()->getDynamics()) {
614 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
617 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
621 if (trafficRef->getArrivalAirport()->getDynamics()) {
622 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
625 case 8: // Taxiing for parking
626 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists())
627 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController();
634 if ((controller != prevController) && (prevController != 0)) {
635 prevController->signOff(getID());
637 prevController = controller;
639 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
640 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
641 trafficRef->getRadius(), leg, this);
645 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
646 if (!takeOffStatus) {
647 int leg = fp->getLeg();
649 if (trafficRef->getDepartureAirport()->getDynamics()) {
650 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
652 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
654 if (towerController) {
655 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
656 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
657 trafficRef->getRadius(), leg, this);
658 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
662 takeOffStatus = state;
665 // Process ATC instructions and report back
667 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
668 if (instruction.getCheckForCircularWait()) {
669 // This is not exactly an elegant solution,
670 // but at least it gives me a chance to check
671 // if circular waits are resolved.
672 // For now, just take the offending aircraft
675 // a more proper way should be - of course - to
676 // let an offending aircraft take an evasive action
677 // for instance taxi back a little bit.
679 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
680 if (instruction.getHoldPattern ()) {}
683 if (instruction.getHoldPosition ()) {
691 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
694 // Change speed Instruction. This can only be excecuted when there is no
695 // Hold position instruction.
696 if (instruction.getChangeSpeed ()) {
698 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
699 AccelTo(instruction.getSpeed());
701 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
704 if (instruction.getChangeHeading ()) {
706 TurnTo(instruction.getHeading());
712 if (instruction.getChangeAltitude()) {}
717 void FGAIAircraft::handleFirstWaypoint() {
718 bool eraseWaypoints; //TODO YAGNI
721 eraseWaypoints = true;
723 eraseWaypoints = false;
726 FGAIWaypoint* prev = 0; // the one behind you
727 FGAIWaypoint* curr = 0; // the one ahead
728 FGAIWaypoint* next = 0;// the next plus 1
732 //TODO fp should handle this
733 fp->IncrementWaypoint(eraseWaypoints);
734 if (!(fp->getNextWaypoint()) && trafficRef)
735 if (!loadNextLeg()) {
740 prev = fp->getPreviousWaypoint(); //first waypoint
741 curr = fp->getCurrentWaypoint(); //second waypoint
742 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
744 setLatitude(prev->getLatitude());
745 setLongitude(prev->getLongitude());
746 setSpeed(prev->getSpeed());
747 setAltitude(prev->getAltitude());
749 if (prev->getSpeed() > 0.0)
750 setHeading(fp->getBearing(prev, curr));
752 setHeading(fp->getBearing(curr, prev));
754 // If next doesn't exist, as in incrementally created flightplans for
755 // AI/Trafficmanager created plans,
756 // Make sure lead distance is initialized otherwise
758 fp->setLeadDistance(speed, hdg, curr, next);
760 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
763 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
764 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
765 // / 6076.0 / prev->getSpeed()*60.0);
766 double vert_dist_ft = curr->getCrossat() - altitude_ft;
767 double err_dist = prev->getCrossat() - altitude_ft;
768 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
769 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
771 tgt_altitude_ft = curr->getCrossat();
774 tgt_altitude_ft = prev->getAltitude();
776 alt_lock = hdg_lock = true;
777 no_roll = prev->getOn_ground();
779 Transform(); // make sure aip is initialized.
780 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
782 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
784 // Make sure to announce the aircraft's position
785 announcePositionToController();
791 * Check Execution time (currently once every 100 ms)
792 * Add a bit of randomization to prevent the execution of all flight plans
793 * in synchrony, which can add significant periodic framerate flutter.
798 bool FGAIAircraft::fpExecutable(time_t now) {
799 double rand_exec_time = (rand() % 100) / 100;
800 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
805 * Check to see if we've reached the lead point for our next turn
810 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
811 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
813 //cerr << "2" << endl;
814 double lead_dist = fp->getLeadDistance();
815 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
816 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
817 tgt_speed = -(dist_to_go / 10.0);
818 if (tgt_speed > -0.5) {
821 //assertSpeed(tgt_speed);
822 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
823 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
826 if (lead_dist < fabs(2*speed)) {
827 //don't skip over the waypoint
828 lead_dist = fabs(2*speed);
829 //cerr << "Extending lead distance to " << lead_dist << endl;
832 //prev_dist_to_go = dist_to_go;
833 //if (dist_to_go < lead_dist)
834 // cerr << trafficRef->getCallSign() << " Distance : "
835 // << dist_to_go << ": Lead distance "
836 // << lead_dist << " " << curr->name
837 // << " Ground target speed " << groundTargetSpeed << endl;
839 // don't do bearing calculations for ground traffic
840 bearing = getBearing(fp->getBearing(pos, curr));
841 if (bearing < minBearing) {
842 minBearing = bearing;
843 if (minBearing < 10) {
846 if ((minBearing < 360.0) && (minBearing > 10.0)) {
847 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
853 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
854 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
855 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
856 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
859 if ((dist_to_go < lead_dist) ||
860 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
863 prev_dist_to_go = HUGE_VAL;
866 prev_dist_to_go = dist_to_go;
872 bool FGAIAircraft::aiTrafficVisible()
874 SGVec3d cartPos = SGVec3d::fromGeod(pos);
875 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
876 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
877 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
882 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
883 * in the case of an arrival.
889 //TODO the trafficRef is the right place for the method
890 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
891 // prepare routing from one airport to another
892 FGAirport * dep = trafficRef->getDepartureAirport();
893 FGAirport * arr = trafficRef->getArrivalAirport();
898 // This waypoint marks the fact that the aircraft has passed the initial taxi
899 // departure waypoint, so it can release the parking.
900 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
901 //cerr << "Passing waypoint : " << prev->getName() << endl;
902 if (prev->contains("PushBackPoint")) {
903 // clearing the parking assignment will release the gate
904 fp->setGate(ParkingAssignment());
906 //setTaxiClearanceRequest(true);
908 if (prev->contains("legend")) {
911 if (prev->contains(string("DepartureHold"))) {
912 //cerr << "Passing point DepartureHold" << endl;
913 scheduleForATCTowerDepartureControl(1);
915 if (prev->contains(string("Accel"))) {
918 //if (prev->contains(string("landing"))) {
919 // if (speed < _performance->vTaxi() * 2) {
920 // fp->shortenToFirst(2, "legend");
923 //if (prev->contains(string("final"))) {
925 // cerr << getCallSign() << " "
926 // << fp->getPreviousWaypoint()->getName()
927 // << ". Alt = " << altitude_ft
929 // << " horizontal speed " << speed
930 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
931 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
932 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
934 // This is the last taxi waypoint, and marks the the end of the flight plan
935 // so, the schedule should update and wait for the next departure time.
936 if (prev->contains("END")) {
937 time_t nextDeparture = trafficRef->getDepartureTime();
938 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
939 if (nextDeparture < (now+1200)) {
940 nextDeparture = now + 1200;
942 fp->setTime(nextDeparture);
950 * Check difference between target bearing and current heading and correct if necessary.
954 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
955 double calc_bearing = fp->getBearing(pos, curr);
956 //cerr << "Bearing = " << calc_bearing << endl;
959 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
962 if (fgIsFinite(calc_bearing)) {
963 double hdg_error = calc_bearing - tgt_heading;
964 if (fabs(hdg_error) > 0.01) {
965 TurnTo( calc_bearing );
969 cerr << "calc_bearing is not a finite number : "
971 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
972 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
973 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
980 * Update the lead distance calculation if speed has changed sufficiently
981 * to prevent spinning (hopefully);
986 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
987 double speed_diff = speed - prevSpeed;
989 if (fabs(speed_diff) > 10) {
991 //assertSpeed(speed);
993 fp->setLeadDistance(speed, tgt_heading, curr, next);
1000 * Update target values (heading, alt, speed) depending on flight plan or control properties
1002 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
1003 if (fp) // AI object has a flightplan
1005 //TODO make this a function of AIBase
1006 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1007 //cerr << "UpateTArgetValues() " << endl;
1008 ProcessFlightPlan(dt, now);
1010 // Do execute Ground elev for inactive aircraft, so they
1011 // Are repositioned to the correct ground altitude when the user flies within visibility range.
1012 // In addition, check whether we are out of user range, so this aircraft
1015 Transform(); // make sure aip is initialized.
1019 pos.setElevationFt(altitude_ft);
1022 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
1023 aiOutOfSight = !aiTrafficVisible();
1026 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1027 aiOutOfSight = true;
1031 timeElapsed = now - fp->getStartTime();
1032 flightplanActive = fp->isActive(now);
1034 // no flight plan, update target heading, speed, and altitude
1035 // from control properties. These default to the initial
1036 // settings in the config file, but can be changed "on the
1038 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1039 if ( lat_mode == "roll" ) {
1041 = props->getDoubleValue("controls/flight/target-roll" );
1045 = props->getDoubleValue("controls/flight/target-hdg" );
1050 = props->getStringValue("controls/flight/longitude-mode");
1051 if ( lon_mode == "alt" ) {
1052 double alt = props->getDoubleValue("controls/flight/target-alt" );
1056 = props->getDoubleValue("controls/flight/target-pitch" );
1060 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1064 void FGAIAircraft::updateHeading() {
1065 // adjust heading based on current bank angle
1070 // double turnConstant;
1072 // turnConstant = 0.0088362;
1074 // turnConstant = 0.088362;
1075 // If on ground, calculate heading change directly
1077 double headingDiff = fabs(hdg-tgt_heading);
1078 // double bank_sense = 0.0;
1080 double diff = fabs(hdg - tgt_heading);
1082 diff = fabs(diff - 360);
1084 double sum = hdg + diff;
1087 if (fabs(sum - tgt_heading) < 1.0) {
1088 bank_sense = 1.0; // right turn
1090 bank_sense = -1.0; // left turn
1092 if (headingDiff > 180)
1093 headingDiff = fabs(headingDiff - 360);
1094 double sum = hdg + headingDiff;
1097 if (fabs(sum - tgt_heading) > 0.0001) {
1098 // bank_sense = -1.0;
1100 // bank_sense = 1.0;
1103 // cerr << trafficRef->getCallSign() << " Heading "
1104 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1105 //if (headingDiff > 60) {
1106 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1107 //assertSpeed(groundTargetSpeed);
1108 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1110 // groundTargetSpeed = tgt_speed;
1112 if (sign(groundTargetSpeed) != sign(tgt_speed))
1113 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1114 //assertSpeed(groundTargetSpeed);
1115 // Only update the target values when we're not moving because otherwise we might introduce an enormous target change rate while waiting a the gate, or holding.
1117 if (headingDiff > 30.0) {
1118 // invert if pushed backward
1119 headingChangeRate += 10.0 * dt * sign(roll);
1121 // Clamp the maximum steering rate to 30 degrees per second,
1122 // But only do this when the heading error is decreasing.
1123 if ((headingDiff < headingError)) {
1124 if (headingChangeRate > 30)
1125 headingChangeRate = 30;
1126 else if (headingChangeRate < -30)
1127 headingChangeRate = -30;
1131 if (fabs(headingChangeRate) > headingDiff)
1132 headingChangeRate = headingDiff*sign(roll);
1134 headingChangeRate += dt * sign(roll);
1139 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1140 headingError = headingDiff;
1141 if (fabs(headingError) < 1.0) {
1145 if (fabs(speed) > 1.0) {
1146 turn_radius_ft = 0.088362 * speed * speed
1147 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1149 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1150 turn_radius_ft = 1.0;
1152 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1153 double dist_covered_ft = speed * 1.686 * dt;
1154 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1155 hdg += alpha * sign(roll);
1157 while ( hdg > 360.0 ) {
1161 while ( hdg < 0.0) {
1169 void FGAIAircraft::updateBankAngleTarget() {
1170 // adjust target bank angle if heading lock engaged
1172 double bank_sense = 0.0;
1173 double diff = fabs(hdg - tgt_heading);
1175 diff = fabs(diff - 360);
1177 double sum = hdg + diff;
1180 if (fabs(sum - tgt_heading) < 1.0) {
1181 bank_sense = 1.0; // right turn
1183 bank_sense = -1.0; // left turn
1185 if (diff < _performance->maximumBankAngle()) {
1186 tgt_roll = diff * bank_sense;
1188 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1190 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1191 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1192 // The only way to resolve this is to make them slow down.
1198 void FGAIAircraft::updateVerticalSpeedTarget() {
1199 // adjust target Altitude, based on ground elevation when on ground
1203 } else if (alt_lock) {
1204 // find target vertical speed
1206 if (altitude_ft < tgt_altitude_ft) {
1207 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1209 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1212 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1213 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1214 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1215 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1216 //cerr << "Target vs before : " << tgt_vs;
1217 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1218 double min_vs = 100;
1219 if (tgt_altitude_ft < altitude_ft)
1221 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1222 && (fabs(max_vs) < fabs(tgt_vs)))
1225 if (fabs(tgt_vs) < fabs(min_vs))
1227 //cerr << "target vs : after " << tgt_vs << endl;
1234 void FGAIAircraft::updatePitchAngleTarget() {
1235 // if on ground and above vRotate -> initial rotation
1236 if (onGround() && (speed > _performance->vRotate()))
1237 tgt_pitch = 8.0; // some rough B737 value
1239 //TODO pitch angle on approach and landing
1241 // match pitch angle to vertical speed
1242 else if (tgt_vs > 0) {
1243 tgt_pitch = tgt_vs * 0.005;
1245 tgt_pitch = tgt_vs * 0.002;
1249 const string& FGAIAircraft::atGate()
1251 if ((fp->getLeg() < 3) && trafficRef) {
1252 if (fp->getParkingGate()) {
1253 return fp->getParkingGate()->ident();
1257 static const string empty;
1261 void FGAIAircraft::handleATCRequests() {
1262 //TODO implement NullController for having no ATC to save the conditionals
1264 controller->updateAircraftInformation(getID(),
1265 pos.getLatitudeDeg(),
1266 pos.getLongitudeDeg(),
1270 processATC(controller->getInstruction(getID()));
1272 if (towerController) {
1273 towerController->updateAircraftInformation(getID(),
1274 pos.getLatitudeDeg(),
1275 pos.getLongitudeDeg(),
1282 void FGAIAircraft::updateActualState() {
1283 //update current state
1284 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1285 double distance = speed * SG_KT_TO_MPS * dt;
1286 pos = SGGeodesy::direct(pos, hdg, distance);
1290 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1292 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1293 //assertSpeed(speed);
1295 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1297 // adjust altitude (meters) based on current vertical speed (fpm)
1298 altitude_ft += vs / 60.0 * dt;
1299 pos.setElevationFt(altitude_ft);
1301 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1302 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1305 void FGAIAircraft::updateSecondaryTargetValues() {
1306 // derived target state values
1307 updateBankAngleTarget();
1308 updateVerticalSpeedTarget();
1309 updatePitchAngleTarget();
1311 //TODO calculate wind correction angle (tgt_yaw)
1315 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1316 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1317 if (curr->getName() == string("BOD")) {
1318 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1319 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1320 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1322 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1323 double descentTimeNeeded = verticalDistance / descentRate;
1324 double distanceCovered = descentSpeed * descentTimeNeeded;
1326 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1327 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1328 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1329 cerr << "Descent rate : " << descentRate << endl;
1330 cerr << "Descent speed : " << descentSpeed << endl;
1331 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1332 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1333 cerr << "DistanceCovered : " << distanceCovered << endl;
1335 //cerr << "Distance = " << distance << endl;
1336 distance = distanceCovered;
1337 if (dist < distanceCovered) {
1338 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1350 void FGAIAircraft::resetPositionFromFlightPlan()
1352 // the one behind you
1353 FGAIWaypoint* prev = 0;
1355 FGAIWaypoint* curr = 0;
1357 FGAIWaypoint* next = 0;
1359 prev = fp->getPreviousWaypoint();
1360 curr = fp->getCurrentWaypoint();
1361 next = fp->getNextWaypoint();
1363 setLatitude(prev->getLatitude());
1364 setLongitude(prev->getLongitude());
1365 double tgt_heading = fp->getBearing(curr, next);
1366 setHeading(tgt_heading);
1367 setAltitude(prev->getAltitude());
1368 setSpeed(prev->getSpeed());
1371 double FGAIAircraft::getBearing(double crse)
1373 double hdgDiff = fabs(hdg-crse);
1375 hdgDiff = fabs(hdgDiff - 360);
1379 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1380 FGAIWaypoint* curr = 0;
1381 curr = fp->getCurrentWaypoint();
1383 // don't recalculate tracklength unless the start/stop waypoint has changed
1385 ((curr->getName() != trackCache.startWptName)||
1386 (wptName != trackCache.finalWptName)))
1388 trackCache.remainingLength = fp->checkTrackLength(wptName);
1389 trackCache.startWptName = curr->getName();
1390 trackCache.finalWptName = wptName;
1392 double tracklength = trackCache.remainingLength;
1393 if (tracklength > 0.1) {
1394 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1398 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1399 time_t arrivalTime = fp->getArrivalTime();
1401 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1402 time_t secondsToGo = arrivalTime - now;
1403 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1404 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1406 return (ete - secondsToGo); // Positive when we're too slow...
1409 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1411 double delta = target - cur;
1412 double maxDelta = maxDeltaSec * dt;
1414 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1415 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1418 // drive various properties in a semi-realistic fashion.
1419 void FGAIAircraft::updateModelProperties(double dt)
1425 SGPropertyNode* gear = props->getChild("gear", 0, true);
1426 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1427 if (!gear->hasValue("gear/position-norm")) {
1428 gear->setDoubleValue("gear/position-norm", targetGearPos);
1431 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1432 if (gearPosNorm != targetGearPos) {
1433 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1434 if (gearPosNorm < 0.001) {
1436 } else if (gearPosNorm > 0.999) {
1440 for (int i=0; i<6; ++i) {
1441 SGPropertyNode* g = gear->getChild("gear", i, true);
1442 g->setDoubleValue("position-norm", gearPosNorm);
1443 } // of gear setting loop
1444 } // of gear in-transit
1446 // double flapPosNorm = props->getDoubleValue();