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/timing/sg_time.hxx>
35 #include <simgear/structure/exception.hxx>
41 // defined in AIShip.cxx
42 extern double fgIsFinite(double x);
44 #include "AIManager.hxx"
45 #include "AIAircraft.hxx"
46 #include "AIFlightPlan.hxx"
47 #include "performancedata.hxx"
48 #include "performancedb.hxx"
55 //#include <Airports/trafficcontroller.hxx>
57 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
58 /* HOT must be disabled for AI Aircraft,
59 * otherwise traffic detection isn't working as expected.*/
60 FGAIBase(otAircraft, false),
65 groundOffset = trafficRef->getGroundOffset();
66 setCallSign(trafficRef->getCallSign());
82 groundTargetSpeed = 0;
84 // set heading and altitude locks
88 headingChangeRate = 0.0;
92 prev_dist_to_go = 0.0;
95 needsTaxiClearance = false;
96 _needsGroundElevation = true;
98 PerformanceDB* perfDB = globals->get_subsystem<PerformanceDB>();
100 _performance = perfDB->getDefaultPerformance();
102 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)
168 bool outOfSight = false,
169 flightplanActive = true;
170 updatePrimaryTargetValues(dt, flightplanActive, outOfSight); // target hdg, alt, speed
175 if (!flightplanActive) {
176 groundTargetSpeed = 0;
179 handleATCRequests(dt); // ATC also has a word to say
180 updateSecondaryTargetValues(dt); // target roll, vertical speed, pitch
181 updateActualState(dt);
183 // 25/11/12 - added but disabled, since setting properties isn't
184 // affecting the AI-model as expected.
185 updateModelProperties(dt);
188 // We currently have one situation in which an AIAircraft object is used that is not attached to the
189 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
190 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
193 UpdateRadar(manager);
194 invisible = !manager->isVisible(pos);
199 void FGAIAircraft::AccelTo(double speed) {
201 //assertSpeed(speed);
203 _needsGroundElevation = true;
207 void FGAIAircraft::PitchTo(double angle) {
213 void FGAIAircraft::RollTo(double angle) {
219 void FGAIAircraft::YawTo(double angle) {
224 void FGAIAircraft::ClimbTo(double alt_ft ) {
225 tgt_altitude_ft = alt_ft;
230 void FGAIAircraft::TurnTo(double heading) {
231 tgt_heading = heading;
236 double FGAIAircraft::sign(double x) {
244 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
246 if (flightplan.empty()) {
247 // this is the case for Nasal-scripted aircraft
251 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
252 if (fp->isValidPlan()) {
253 fp->setRepeat(repeat);
256 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
262 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
269 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
271 // the one behind you
272 FGAIWaypoint* prev = 0;
274 FGAIWaypoint* curr = 0;
276 FGAIWaypoint* next = 0;
278 prev = fp->getPreviousWaypoint();
279 curr = fp->getCurrentWaypoint();
280 next = fp->getNextWaypoint();
284 ///////////////////////////////////////////////////////////////////////////
285 // Initialize the flightplan
286 //////////////////////////////////////////////////////////////////////////
288 handleFirstWaypoint();
290 } // end of initialization
291 if (! fpExecutable(now))
295 double distanceToDescent;
296 if(reachedEndOfCruise(distanceToDescent)) {
297 if (!loadNextLeg(distanceToDescent)) {
301 prev = fp->getPreviousWaypoint();
302 curr = fp->getCurrentWaypoint();
303 next = fp->getNextWaypoint();
311 if (! leadPointReached(curr)) {
312 controlHeading(curr);
313 controlSpeed(curr, next);
317 cerr << getCallSign()
318 << ": verifying lead distance to waypoint : "
319 << fp->getCurrentWaypoint()->name << " "
320 << fp->getLeadDistance() << ". Distance to go "
321 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
322 << ". Target speed = "
324 << ". Current speed = "
326 << ". Minimum Bearing " << minBearing
330 if (curr->isFinished()) //end of the flight plan
340 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
341 tgt_heading = fp->getBearing(curr, next);
345 //TODO let the fp handle this (loading of next leg)
346 fp->IncrementWaypoint( trafficRef != 0 );
347 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
348 if (!loadNextLeg()) {
353 prev = fp->getPreviousWaypoint();
354 curr = fp->getCurrentWaypoint();
355 next = fp->getNextWaypoint();
357 // Now that we have incremented the waypoints, excute some traffic manager specific code
359 //TODO isn't this best executed right at the beginning?
360 if (! aiTrafficVisible()) {
365 if (! handleAirportEndPoints(prev, now)) {
370 announcePositionToController();
375 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
379 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
381 tgt_altitude_ft = prev->getAltitude();
382 if (curr->getCrossat() > -1000.0) {
384 // Distance to go in meters
385 double vert_dist_ft = curr->getCrossat() - altitude_ft;
386 double err_dist = prev->getCrossat() - altitude_ft;
387 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
388 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
391 tgt_altitude_ft = curr->getCrossat();
396 AccelTo(prev->getSpeed());
397 hdg_lock = alt_lock = true;
398 no_roll = prev->getOn_ground();
402 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
404 // err is negative when we passed too high
405 double vert_m = vert_ft * SG_FEET_TO_METER;
406 //double err_m = err * SG_FEET_TO_METER;
407 //double angle = atan2(vert_m, dist_m);
408 double speedMs = (speed * SG_NM_TO_METER) / 3600;
409 //double vs = cos(angle) * speedMs; // Now in m/s
411 //cerr << "Error term = " << err_m << endl;
413 vs = ((vert_m) / dist_m) * speedMs;
415 // Convert to feet per minute
416 vs *= (SG_METER_TO_FEET * 60);
417 //if (getCallSign() == "LUFTHANSA2002")
418 //if (fabs(vs) > 100000) {
419 // if (getCallSign() == "LUFTHANSA2057") {
420 // 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;
421 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
422 // // / 6076.0 / speed*60.0);
428 void FGAIAircraft::clearATCController()
435 void FGAIAircraft::assertSpeed(double speed)
437 if ((speed < -50) || (speed > 1000)) {
438 cerr << getCallSign() << " "
439 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
440 << "Departure airport " << trafficRef->getDepartureAirport() << " "
441 << "Leg " << fp->getLeg() << " "
442 << "target_speed << " << tgt_speed << " "
443 << "speedFraction << " << speedFraction << " "
444 << "Currecnt speed << " << speed << " "
452 void FGAIAircraft::checkTcas(void)
454 if (props->getIntValue("tcas/threat-level",0)==3)
456 int RASense = props->getIntValue("tcas/ra-sense",0);
457 if ((RASense>0)&&(tgt_vs<4000))
463 // downward RA: descend!
464 if (altitude_ft < 1000)
466 // too low: level off
479 void FGAIAircraft::initializeFlightPlan() {
482 const char * FGAIAircraft::_getTransponderCode() const {
483 return transponderCode.c_str();
486 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
487 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
489 bool FGAIAircraft::loadNextLeg(double distance) {
492 if ((leg = fp->getLeg()) == 9) {
493 if (!trafficRef->next()) {
496 setCallSign(trafficRef->getCallSign());
501 FGAirport *dep = trafficRef->getDepartureAirport();
502 FGAirport *arr = trafficRef->getArrivalAirport();
507 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
514 trafficRef->getSpeed(),
518 trafficRef->getRadius(),
519 trafficRef->getFlightType(),
523 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
529 // Note: This code is copied from David Luff's AILocalTraffic
530 // Warning - ground elev determination is CPU intensive
531 // Either this function or the logic of how often it is called
532 // will almost certainly change.
534 void FGAIAircraft::getGroundElev(double dt) {
537 if (!needGroundElevation())
539 // Update minimally every three secs, but add some randomness
540 // to prevent all AI objects doing this in synchrony
541 if (dt_elev_count < (3.0) + (rand() % 10))
546 // Only do the proper hitlist stuff if we are within visible range of the viewer.
548 double visibility_meters = fgGetDouble("/environment/visibility-m");
549 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
553 double range = 500.0;
554 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
557 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
559 tgt_altitude_ft = alt * SG_METER_TO_FEET;
562 // aircraft is stationary and we obtained altitude for this spot - we're done.
563 _needsGroundElevation = false;
571 void FGAIAircraft::doGroundAltitude() {
572 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
575 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
577 altitude_ft = (tgt_altitude_ft + groundOffset);
579 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
585 void FGAIAircraft::announcePositionToController() {
590 int leg = fp->getLeg();
591 if (!fp->getCurrentWaypoint()) {
592 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
593 // throw an exception so this aircraft gets killed by the AIManager.
594 throw sg_exception("bad AI flight plan");
597 // Note that leg has been incremented after creating the current leg, so we should use
598 // leg numbers here that are one higher than the number that is used to create the leg
599 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
600 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
601 // the original leg numbers here!
603 case 1: // Startup and Push back
604 if (trafficRef->getDepartureAirport()->getDynamics())
605 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
607 case 2: // Taxiing to runway
608 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists())
609 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController();
611 case 3: //Take off tower controller
612 if (trafficRef->getDepartureAirport()->getDynamics()) {
613 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
616 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
620 if (trafficRef->getArrivalAirport()->getDynamics()) {
621 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
624 case 8: // Taxiing for parking
625 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists())
626 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController();
633 if ((controller != prevController) && (prevController != 0)) {
634 prevController->signOff(getID());
636 prevController = controller;
638 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
639 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
640 trafficRef->getRadius(), leg, this);
644 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
645 if (!takeOffStatus) {
646 int leg = fp->getLeg();
648 if (trafficRef->getDepartureAirport()->getDynamics()) {
649 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
651 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
653 if (towerController) {
654 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
655 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
656 trafficRef->getRadius(), leg, this);
657 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
661 takeOffStatus = state;
664 // Process ATC instructions and report back
666 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
667 if (instruction.getCheckForCircularWait()) {
668 // This is not exactly an elegant solution,
669 // but at least it gives me a chance to check
670 // if circular waits are resolved.
671 // For now, just take the offending aircraft
674 // a more proper way should be - of course - to
675 // let an offending aircraft take an evasive action
676 // for instance taxi back a little bit.
678 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
679 if (instruction.getHoldPattern ()) {}
682 if (instruction.getHoldPosition ()) {
690 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
693 // Change speed Instruction. This can only be excecuted when there is no
694 // Hold position instruction.
695 if (instruction.getChangeSpeed ()) {
697 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
698 AccelTo(instruction.getSpeed());
700 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
703 if (instruction.getChangeHeading ()) {
705 TurnTo(instruction.getHeading());
711 if (instruction.getChangeAltitude()) {}
716 void FGAIAircraft::handleFirstWaypoint() {
717 bool eraseWaypoints; //TODO YAGNI
720 eraseWaypoints = true;
722 eraseWaypoints = false;
725 FGAIWaypoint* prev = 0; // the one behind you
726 FGAIWaypoint* curr = 0; // the one ahead
727 FGAIWaypoint* next = 0;// the next plus 1
731 //TODO fp should handle this
732 fp->IncrementWaypoint(eraseWaypoints);
733 if (!(fp->getNextWaypoint()) && trafficRef)
734 if (!loadNextLeg()) {
739 prev = fp->getPreviousWaypoint(); //first waypoint
740 curr = fp->getCurrentWaypoint(); //second waypoint
741 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
743 setLatitude(prev->getLatitude());
744 setLongitude(prev->getLongitude());
745 setSpeed(prev->getSpeed());
746 setAltitude(prev->getAltitude());
748 if (prev->getSpeed() > 0.0)
749 setHeading(fp->getBearing(prev, curr));
751 setHeading(fp->getBearing(curr, prev));
753 // If next doesn't exist, as in incrementally created flightplans for
754 // AI/Trafficmanager created plans,
755 // Make sure lead distance is initialized otherwise
757 fp->setLeadDistance(speed, hdg, curr, next);
759 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
762 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
763 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
764 // / 6076.0 / prev->getSpeed()*60.0);
765 double vert_dist_ft = curr->getCrossat() - altitude_ft;
766 double err_dist = prev->getCrossat() - altitude_ft;
767 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
768 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
770 tgt_altitude_ft = curr->getCrossat();
773 tgt_altitude_ft = prev->getAltitude();
775 alt_lock = hdg_lock = true;
776 no_roll = prev->getOn_ground();
778 Transform(); // make sure aip is initialized.
779 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
781 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
783 // Make sure to announce the aircraft's position
784 announcePositionToController();
790 * Check Execution time (currently once every 100 ms)
791 * Add a bit of randomization to prevent the execution of all flight plans
792 * in synchrony, which can add significant periodic framerate flutter.
797 bool FGAIAircraft::fpExecutable(time_t now) {
798 double rand_exec_time = (rand() % 100) / 100;
799 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
804 * Check to see if we've reached the lead point for our next turn
809 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
810 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
812 //cerr << "2" << endl;
813 double lead_dist = fp->getLeadDistance();
814 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
815 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
816 tgt_speed = -(dist_to_go / 10.0);
817 if (tgt_speed > -0.5) {
820 //assertSpeed(tgt_speed);
821 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
822 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
825 if (lead_dist < fabs(2*speed)) {
826 //don't skip over the waypoint
827 lead_dist = fabs(2*speed);
828 //cerr << "Extending lead distance to " << lead_dist << endl;
831 //prev_dist_to_go = dist_to_go;
832 //if (dist_to_go < lead_dist)
833 // cerr << trafficRef->getCallSign() << " Distance : "
834 // << dist_to_go << ": Lead distance "
835 // << lead_dist << " " << curr->name
836 // << " Ground target speed " << groundTargetSpeed << endl;
838 // don't do bearing calculations for ground traffic
839 bearing = getBearing(fp->getBearing(pos, curr));
840 if (bearing < minBearing) {
841 minBearing = bearing;
842 if (minBearing < 10) {
845 if ((minBearing < 360.0) && (minBearing > 10.0)) {
846 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
852 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
853 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
854 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
855 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
858 if ((dist_to_go < lead_dist) ||
859 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
862 prev_dist_to_go = HUGE_VAL;
865 prev_dist_to_go = dist_to_go;
871 bool FGAIAircraft::aiTrafficVisible()
873 SGVec3d cartPos = SGVec3d::fromGeod(pos);
874 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
875 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
876 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
881 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
882 * in the case of an arrival.
888 //TODO the trafficRef is the right place for the method
889 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
890 // prepare routing from one airport to another
891 FGAirport * dep = trafficRef->getDepartureAirport();
892 FGAirport * arr = trafficRef->getArrivalAirport();
897 // This waypoint marks the fact that the aircraft has passed the initial taxi
898 // departure waypoint, so it can release the parking.
899 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
900 //cerr << "Passing waypoint : " << prev->getName() << endl;
901 if (prev->contains("PushBackPoint")) {
902 // clearing the parking assignment will release the gate
903 fp->setGate(ParkingAssignment());
905 //setTaxiClearanceRequest(true);
907 if (prev->contains("legend")) {
910 if (prev->contains(string("DepartureHold"))) {
911 //cerr << "Passing point DepartureHold" << endl;
912 scheduleForATCTowerDepartureControl(1);
914 if (prev->contains(string("Accel"))) {
917 //if (prev->contains(string("landing"))) {
918 // if (speed < _performance->vTaxi() * 2) {
919 // fp->shortenToFirst(2, "legend");
922 //if (prev->contains(string("final"))) {
924 // cerr << getCallSign() << " "
925 // << fp->getPreviousWaypoint()->getName()
926 // << ". Alt = " << altitude_ft
928 // << " horizontal speed " << speed
929 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
930 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
931 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
933 // This is the last taxi waypoint, and marks the the end of the flight plan
934 // so, the schedule should update and wait for the next departure time.
935 if (prev->contains("END")) {
936 time_t nextDeparture = trafficRef->getDepartureTime();
937 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
938 if (nextDeparture < (now+1200)) {
939 nextDeparture = now + 1200;
941 fp->setTime(nextDeparture);
949 * Check difference between target bearing and current heading and correct if necessary.
953 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
954 double calc_bearing = fp->getBearing(pos, curr);
955 //cerr << "Bearing = " << calc_bearing << endl;
958 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
961 if (fgIsFinite(calc_bearing)) {
962 double hdg_error = calc_bearing - tgt_heading;
963 if (fabs(hdg_error) > 0.01) {
964 TurnTo( calc_bearing );
968 cerr << "calc_bearing is not a finite number : "
970 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
971 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
972 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
979 * Update the lead distance calculation if speed has changed sufficiently
980 * to prevent spinning (hopefully);
985 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
986 double speed_diff = speed - prevSpeed;
988 if (fabs(speed_diff) > 10) {
990 //assertSpeed(speed);
992 fp->setLeadDistance(speed, tgt_heading, curr, next);
999 * Update target values (heading, alt, speed) depending on flight plan or control properties
1001 void FGAIAircraft::updatePrimaryTargetValues(double dt, bool& flightplanActive, bool& aiOutOfSight) {
1002 if (fp) // AI object has a flightplan
1004 //TODO make this a function of AIBase
1005 time_t now = globals->get_time_params()->get_cur_time();
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(double dt) {
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(double dt) {
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(double dt)
1263 //TODO implement NullController for having no ATC to save the conditionals
1265 controller->updateAircraftInformation(getID(),
1266 pos.getLatitudeDeg(),
1267 pos.getLongitudeDeg(),
1271 processATC(controller->getInstruction(getID()));
1273 if (towerController) {
1274 towerController->updateAircraftInformation(getID(),
1275 pos.getLatitudeDeg(),
1276 pos.getLongitudeDeg(),
1283 void FGAIAircraft::updateActualState(double dt)
1285 //update current state
1286 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1287 double distance = speed * SG_KT_TO_MPS * dt;
1288 pos = SGGeodesy::direct(pos, hdg, distance);
1292 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1294 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1295 //assertSpeed(speed);
1297 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1299 // adjust altitude (meters) based on current vertical speed (fpm)
1300 altitude_ft += vs / 60.0 * dt;
1301 pos.setElevationFt(altitude_ft);
1303 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1304 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1307 void FGAIAircraft::updateSecondaryTargetValues(double dt) {
1308 // derived target state values
1309 updateBankAngleTarget();
1310 updateVerticalSpeedTarget(dt);
1311 updatePitchAngleTarget();
1313 //TODO calculate wind correction angle (tgt_yaw)
1317 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1318 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1319 if (curr->getName() == string("BOD")) {
1320 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1321 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1322 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1324 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1325 double descentTimeNeeded = verticalDistance / descentRate;
1326 double distanceCovered = descentSpeed * descentTimeNeeded;
1328 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1329 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1330 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1331 cerr << "Descent rate : " << descentRate << endl;
1332 cerr << "Descent speed : " << descentSpeed << endl;
1333 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1334 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1335 cerr << "DistanceCovered : " << distanceCovered << endl;
1337 //cerr << "Distance = " << distance << endl;
1338 distance = distanceCovered;
1339 if (dist < distanceCovered) {
1340 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1352 void FGAIAircraft::resetPositionFromFlightPlan()
1354 // the one behind you
1355 FGAIWaypoint* prev = 0;
1357 FGAIWaypoint* curr = 0;
1359 FGAIWaypoint* next = 0;
1361 prev = fp->getPreviousWaypoint();
1362 curr = fp->getCurrentWaypoint();
1363 next = fp->getNextWaypoint();
1365 setLatitude(prev->getLatitude());
1366 setLongitude(prev->getLongitude());
1367 double tgt_heading = fp->getBearing(curr, next);
1368 setHeading(tgt_heading);
1369 setAltitude(prev->getAltitude());
1370 setSpeed(prev->getSpeed());
1373 double FGAIAircraft::getBearing(double crse)
1375 double hdgDiff = fabs(hdg-crse);
1377 hdgDiff = fabs(hdgDiff - 360);
1381 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1382 FGAIWaypoint* curr = 0;
1383 curr = fp->getCurrentWaypoint();
1385 // don't recalculate tracklength unless the start/stop waypoint has changed
1387 ((curr->getName() != trackCache.startWptName)||
1388 (wptName != trackCache.finalWptName)))
1390 trackCache.remainingLength = fp->checkTrackLength(wptName);
1391 trackCache.startWptName = curr->getName();
1392 trackCache.finalWptName = wptName;
1394 double tracklength = trackCache.remainingLength;
1395 if (tracklength > 0.1) {
1396 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1400 time_t now = globals->get_time_params()->get_cur_time();
1401 time_t arrivalTime = fp->getArrivalTime();
1403 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1404 time_t secondsToGo = arrivalTime - now;
1405 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1406 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1408 return (ete - secondsToGo); // Positive when we're too slow...
1411 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1413 double delta = target - cur;
1414 double maxDelta = maxDeltaSec * dt;
1416 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1417 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1420 // drive various properties in a semi-realistic fashion.
1421 void FGAIAircraft::updateModelProperties(double dt)
1427 SGPropertyNode* gear = props->getChild("gear", 0, true);
1428 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1429 if (!gear->hasValue("gear/position-norm")) {
1430 gear->setDoubleValue("gear/position-norm", targetGearPos);
1433 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1434 if (gearPosNorm != targetGearPos) {
1435 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1436 if (gearPosNorm < 0.001) {
1438 } else if (gearPosNorm > 0.999) {
1442 for (int i=0; i<6; ++i) {
1443 SGPropertyNode* g = gear->getChild("gear", i, true);
1444 g->setDoubleValue("position-norm", gearPosNorm);
1445 } // of gear setting loop
1446 } // of gear in-transit
1448 // double flapPosNorm = props->getDoubleValue();