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>
33 #include <simgear/structure/exception.hxx>
39 // defined in AIShip.cxx
40 extern double fgIsFinite(double x);
42 #include "AIAircraft.hxx"
43 #include "performancedata.hxx"
44 #include "performancedb.hxx"
51 //#include <Airports/trafficcontroller.hxx>
53 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
54 /* HOT must be disabled for AI Aircraft,
55 * otherwise traffic detection isn't working as expected.*/
56 FGAIBase(otAircraft, false)
60 groundOffset = trafficRef->getGroundOffset();
61 setCallSign(trafficRef->getCallSign());
77 groundTargetSpeed = 0;
79 // set heading and altitude locks
83 headingChangeRate = 0.0;
87 prev_dist_to_go = 0.0;
90 needsTaxiClearance = false;
91 _needsGroundElevation = true;
93 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
97 trackCache.remainingLength = 0;
98 trackCache.startWptName = "-";
102 FGAIAircraft::~FGAIAircraft() {
105 controller->signOff(getID());
109 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
113 FGAIBase::readFromScenario(scFileNode);
115 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
116 setFlightPlan(scFileNode->getStringValue("flightplan"),
117 scFileNode->getBoolValue("repeat", false));
118 setCallSign(scFileNode->getStringValue("callsign"));
122 void FGAIAircraft::bind() {
125 tie("transponder-id",
126 SGRawValueMethods<FGAIAircraft,const char*>(*this,
127 &FGAIAircraft::_getTransponderCode));
130 void FGAIAircraft::update(double dt) {
131 FGAIBase::update(dt);
136 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
138 static PerformanceDB perfdb; //TODO make it a global service
139 _performance = perfdb.getDataFor(acType, acclass);
143 void FGAIAircraft::setPerformance(PerformanceData *ps) {
148 void FGAIAircraft::Run(double dt) {
149 FGAIAircraft::dt = dt;
151 bool outOfSight = false,
152 flightplanActive = true;
153 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
158 if (!flightplanActive) {
159 groundTargetSpeed = 0;
162 handleATCRequests(); // ATC also has a word to say
163 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
166 // 25/11/12 - added but disabled, since setting properties isn't
167 // affecting the AI-model as expected.
168 updateModelProperties(dt);
171 // We currently have one situation in which an AIAircraft object is used that is not attached to the
172 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
173 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
176 UpdateRadar(manager);
177 invisible = !manager->isVisible(pos);
182 void FGAIAircraft::AccelTo(double speed) {
184 //assertSpeed(speed);
186 _needsGroundElevation = true;
190 void FGAIAircraft::PitchTo(double angle) {
196 void FGAIAircraft::RollTo(double angle) {
202 void FGAIAircraft::YawTo(double angle) {
207 void FGAIAircraft::ClimbTo(double alt_ft ) {
208 tgt_altitude_ft = alt_ft;
213 void FGAIAircraft::TurnTo(double heading) {
214 tgt_heading = heading;
219 double FGAIAircraft::sign(double x) {
227 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
229 if (flightplan.empty()) {
230 // this is the case for Nasal-scripted aircraft
234 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
235 if (fp->isValidPlan()) {
236 fp->setRepeat(repeat);
239 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
245 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
252 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
254 // the one behind you
255 FGAIWaypoint* prev = 0;
257 FGAIWaypoint* curr = 0;
259 FGAIWaypoint* next = 0;
261 prev = fp->getPreviousWaypoint();
262 curr = fp->getCurrentWaypoint();
263 next = fp->getNextWaypoint();
267 ///////////////////////////////////////////////////////////////////////////
268 // Initialize the flightplan
269 //////////////////////////////////////////////////////////////////////////
271 handleFirstWaypoint();
273 } // end of initialization
274 if (! fpExecutable(now))
278 double distanceToDescent;
279 if(reachedEndOfCruise(distanceToDescent)) {
280 if (!loadNextLeg(distanceToDescent)) {
284 prev = fp->getPreviousWaypoint();
285 curr = fp->getCurrentWaypoint();
286 next = fp->getNextWaypoint();
294 if (! leadPointReached(curr)) {
295 controlHeading(curr);
296 controlSpeed(curr, next);
300 cerr << getCallSign()
301 << ": verifying lead distance to waypoint : "
302 << fp->getCurrentWaypoint()->name << " "
303 << fp->getLeadDistance() << ". Distance to go "
304 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
305 << ". Target speed = "
307 << ". Current speed = "
309 << ". Minimum Bearing " << minBearing
313 if (curr->isFinished()) //end of the flight plan
323 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
324 tgt_heading = fp->getBearing(curr, next);
328 //TODO let the fp handle this (loading of next leg)
329 fp->IncrementWaypoint( trafficRef != 0 );
330 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
331 if (!loadNextLeg()) {
336 prev = fp->getPreviousWaypoint();
337 curr = fp->getCurrentWaypoint();
338 next = fp->getNextWaypoint();
340 // Now that we have incremented the waypoints, excute some traffic manager specific code
342 //TODO isn't this best executed right at the beginning?
343 if (! aiTrafficVisible()) {
348 if (! handleAirportEndPoints(prev, now)) {
353 announcePositionToController();
358 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
362 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
364 tgt_altitude_ft = prev->getAltitude();
365 if (curr->getCrossat() > -1000.0) {
367 // Distance to go in meters
368 double vert_dist_ft = curr->getCrossat() - altitude_ft;
369 double err_dist = prev->getCrossat() - altitude_ft;
370 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
371 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
374 tgt_altitude_ft = curr->getCrossat();
379 AccelTo(prev->getSpeed());
380 hdg_lock = alt_lock = true;
381 no_roll = prev->getOn_ground();
385 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
387 // err is negative when we passed too high
388 double vert_m = vert_ft * SG_FEET_TO_METER;
389 //double err_m = err * SG_FEET_TO_METER;
390 //double angle = atan2(vert_m, dist_m);
391 double speedMs = (speed * SG_NM_TO_METER) / 3600;
392 //double vs = cos(angle) * speedMs; // Now in m/s
394 //cerr << "Error term = " << err_m << endl;
396 vs = ((vert_m) / dist_m) * speedMs;
398 // Convert to feet per minute
399 vs *= (SG_METER_TO_FEET * 60);
400 //if (getCallSign() == "LUFTHANSA2002")
401 //if (fabs(vs) > 100000) {
402 // if (getCallSign() == "LUFTHANSA2057") {
403 // 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;
404 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
405 // // / 6076.0 / speed*60.0);
411 void FGAIAircraft::assertSpeed(double speed)
413 if ((speed < -50) || (speed > 1000)) {
414 cerr << getCallSign() << " "
415 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
416 << "Departure airport " << trafficRef->getDepartureAirport() << " "
417 << "Leg " << fp->getLeg() << " "
418 << "target_speed << " << tgt_speed << " "
419 << "speedFraction << " << speedFraction << " "
420 << "Currecnt speed << " << speed << " "
428 void FGAIAircraft::checkTcas(void)
430 if (props->getIntValue("tcas/threat-level",0)==3)
432 int RASense = props->getIntValue("tcas/ra-sense",0);
433 if ((RASense>0)&&(tgt_vs<4000))
439 // downward RA: descend!
440 if (altitude_ft < 1000)
442 // too low: level off
455 void FGAIAircraft::initializeFlightPlan() {
458 const char * FGAIAircraft::_getTransponderCode() const {
459 return transponderCode.c_str();
462 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
463 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
465 bool FGAIAircraft::loadNextLeg(double distance) {
468 if ((leg = fp->getLeg()) == 9) {
469 if (!trafficRef->next()) {
472 setCallSign(trafficRef->getCallSign());
477 FGAirport *dep = trafficRef->getDepartureAirport();
478 FGAirport *arr = trafficRef->getArrivalAirport();
483 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
490 trafficRef->getSpeed(),
494 trafficRef->getRadius(),
495 trafficRef->getFlightType(),
499 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
505 // Note: This code is copied from David Luff's AILocalTraffic
506 // Warning - ground elev determination is CPU intensive
507 // Either this function or the logic of how often it is called
508 // will almost certainly change.
510 void FGAIAircraft::getGroundElev(double dt) {
513 if (!needGroundElevation())
515 // Update minimally every three secs, but add some randomness
516 // to prevent all AI objects doing this in synchrony
517 if (dt_elev_count < (3.0) + (rand() % 10))
522 // Only do the proper hitlist stuff if we are within visible range of the viewer.
524 double visibility_meters = fgGetDouble("/environment/visibility-m");
525 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
529 double range = 500.0;
530 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
533 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
535 tgt_altitude_ft = alt * SG_METER_TO_FEET;
538 // aircraft is stationary and we obtained altitude for this spot - we're done.
539 _needsGroundElevation = false;
547 void FGAIAircraft::doGroundAltitude() {
548 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
551 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
553 altitude_ft = (tgt_altitude_ft + groundOffset);
555 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
561 void FGAIAircraft::announcePositionToController() {
566 int leg = fp->getLeg();
567 if (!fp->getCurrentWaypoint()) {
568 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
569 // throw an exception so this aircraft gets killed by the AIManager.
570 throw sg_exception("bad AI flight plan");
573 // Note that leg has been incremented after creating the current leg, so we should use
574 // leg numbers here that are one higher than the number that is used to create the leg
575 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
576 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
577 // the original leg numbers here!
579 case 1: // Startup and Push back
580 if (trafficRef->getDepartureAirport()->getDynamics())
581 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
583 case 2: // Taxiing to runway
584 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists())
585 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController();
587 case 3: //Take off tower controller
588 if (trafficRef->getDepartureAirport()->getDynamics()) {
589 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
592 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
596 if (trafficRef->getArrivalAirport()->getDynamics()) {
597 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
600 case 8: // Taxiing for parking
601 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists())
602 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController();
609 if ((controller != prevController) && (prevController != 0)) {
610 prevController->signOff(getID());
612 prevController = controller;
614 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
615 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
616 trafficRef->getRadius(), leg, this);
620 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
621 if (!takeOffStatus) {
622 int leg = fp->getLeg();
624 if (trafficRef->getDepartureAirport()->getDynamics()) {
625 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
627 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
629 if (towerController) {
630 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
631 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
632 trafficRef->getRadius(), leg, this);
633 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
637 takeOffStatus = state;
640 // Process ATC instructions and report back
642 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
643 if (instruction.getCheckForCircularWait()) {
644 // This is not exactly an elegant solution,
645 // but at least it gives me a chance to check
646 // if circular waits are resolved.
647 // For now, just take the offending aircraft
650 // a more proper way should be - of course - to
651 // let an offending aircraft take an evasive action
652 // for instance taxi back a little bit.
654 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
655 if (instruction.getHoldPattern ()) {}
658 if (instruction.getHoldPosition ()) {
666 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
669 // Change speed Instruction. This can only be excecuted when there is no
670 // Hold position instruction.
671 if (instruction.getChangeSpeed ()) {
673 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
674 AccelTo(instruction.getSpeed());
676 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
679 if (instruction.getChangeHeading ()) {
681 TurnTo(instruction.getHeading());
687 if (instruction.getChangeAltitude()) {}
692 void FGAIAircraft::handleFirstWaypoint() {
693 bool eraseWaypoints; //TODO YAGNI
696 eraseWaypoints = true;
698 eraseWaypoints = false;
701 FGAIWaypoint* prev = 0; // the one behind you
702 FGAIWaypoint* curr = 0; // the one ahead
703 FGAIWaypoint* next = 0;// the next plus 1
707 //TODO fp should handle this
708 fp->IncrementWaypoint(eraseWaypoints);
709 if (!(fp->getNextWaypoint()) && trafficRef)
710 if (!loadNextLeg()) {
715 prev = fp->getPreviousWaypoint(); //first waypoint
716 curr = fp->getCurrentWaypoint(); //second waypoint
717 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
719 setLatitude(prev->getLatitude());
720 setLongitude(prev->getLongitude());
721 setSpeed(prev->getSpeed());
722 setAltitude(prev->getAltitude());
724 if (prev->getSpeed() > 0.0)
725 setHeading(fp->getBearing(prev, curr));
727 setHeading(fp->getBearing(curr, prev));
729 // If next doesn't exist, as in incrementally created flightplans for
730 // AI/Trafficmanager created plans,
731 // Make sure lead distance is initialized otherwise
733 fp->setLeadDistance(speed, hdg, curr, next);
735 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
738 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
739 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
740 // / 6076.0 / prev->getSpeed()*60.0);
741 double vert_dist_ft = curr->getCrossat() - altitude_ft;
742 double err_dist = prev->getCrossat() - altitude_ft;
743 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
744 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
746 tgt_altitude_ft = curr->getCrossat();
749 tgt_altitude_ft = prev->getAltitude();
751 alt_lock = hdg_lock = true;
752 no_roll = prev->getOn_ground();
754 Transform(); // make sure aip is initialized.
755 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
757 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
759 // Make sure to announce the aircraft's position
760 announcePositionToController();
766 * Check Execution time (currently once every 100 ms)
767 * Add a bit of randomization to prevent the execution of all flight plans
768 * in synchrony, which can add significant periodic framerate flutter.
773 bool FGAIAircraft::fpExecutable(time_t now) {
774 double rand_exec_time = (rand() % 100) / 100;
775 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
780 * Check to see if we've reached the lead point for our next turn
785 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
786 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
788 //cerr << "2" << endl;
789 double lead_dist = fp->getLeadDistance();
790 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
791 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
792 tgt_speed = -(dist_to_go / 10.0);
793 if (tgt_speed > -0.5) {
796 //assertSpeed(tgt_speed);
797 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
798 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
801 if (lead_dist < fabs(2*speed)) {
802 //don't skip over the waypoint
803 lead_dist = fabs(2*speed);
804 //cerr << "Extending lead distance to " << lead_dist << endl;
807 //prev_dist_to_go = dist_to_go;
808 //if (dist_to_go < lead_dist)
809 // cerr << trafficRef->getCallSign() << " Distance : "
810 // << dist_to_go << ": Lead distance "
811 // << lead_dist << " " << curr->name
812 // << " Ground target speed " << groundTargetSpeed << endl;
814 // don't do bearing calculations for ground traffic
815 bearing = getBearing(fp->getBearing(pos, curr));
816 if (bearing < minBearing) {
817 minBearing = bearing;
818 if (minBearing < 10) {
821 if ((minBearing < 360.0) && (minBearing > 10.0)) {
822 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
828 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
829 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
830 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
831 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
834 if ((dist_to_go < lead_dist) ||
835 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
838 prev_dist_to_go = HUGE_VAL;
841 prev_dist_to_go = dist_to_go;
847 bool FGAIAircraft::aiTrafficVisible()
849 SGVec3d cartPos = SGVec3d::fromGeod(pos);
850 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
851 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
852 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
857 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
858 * in the case of an arrival.
864 //TODO the trafficRef is the right place for the method
865 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
866 // prepare routing from one airport to another
867 FGAirport * dep = trafficRef->getDepartureAirport();
868 FGAirport * arr = trafficRef->getArrivalAirport();
873 // This waypoint marks the fact that the aircraft has passed the initial taxi
874 // departure waypoint, so it can release the parking.
875 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
876 //cerr << "Passing waypoint : " << prev->getName() << endl;
877 if (prev->contains("PushBackPoint")) {
878 // clearing the parking assignment will release the gate
879 fp->setGate(ParkingAssignment());
881 //setTaxiClearanceRequest(true);
883 if (prev->contains("legend")) {
886 if (prev->contains(string("DepartureHold"))) {
887 //cerr << "Passing point DepartureHold" << endl;
888 scheduleForATCTowerDepartureControl(1);
890 if (prev->contains(string("Accel"))) {
893 //if (prev->contains(string("landing"))) {
894 // if (speed < _performance->vTaxi() * 2) {
895 // fp->shortenToFirst(2, "legend");
898 //if (prev->contains(string("final"))) {
900 // cerr << getCallSign() << " "
901 // << fp->getPreviousWaypoint()->getName()
902 // << ". Alt = " << altitude_ft
904 // << " horizontal speed " << speed
905 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
906 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
907 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
909 // This is the last taxi waypoint, and marks the the end of the flight plan
910 // so, the schedule should update and wait for the next departure time.
911 if (prev->contains("END")) {
912 time_t nextDeparture = trafficRef->getDepartureTime();
913 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
914 if (nextDeparture < (now+1200)) {
915 nextDeparture = now + 1200;
917 fp->setTime(nextDeparture);
925 * Check difference between target bearing and current heading and correct if necessary.
929 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
930 double calc_bearing = fp->getBearing(pos, curr);
931 //cerr << "Bearing = " << calc_bearing << endl;
934 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
937 if (fgIsFinite(calc_bearing)) {
938 double hdg_error = calc_bearing - tgt_heading;
939 if (fabs(hdg_error) > 0.01) {
940 TurnTo( calc_bearing );
944 cerr << "calc_bearing is not a finite number : "
946 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
947 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
948 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
955 * Update the lead distance calculation if speed has changed sufficiently
956 * to prevent spinning (hopefully);
961 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
962 double speed_diff = speed - prevSpeed;
964 if (fabs(speed_diff) > 10) {
966 //assertSpeed(speed);
968 fp->setLeadDistance(speed, tgt_heading, curr, next);
975 * Update target values (heading, alt, speed) depending on flight plan or control properties
977 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
978 if (fp) // AI object has a flightplan
980 //TODO make this a function of AIBase
981 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
982 //cerr << "UpateTArgetValues() " << endl;
983 ProcessFlightPlan(dt, now);
985 // Do execute Ground elev for inactive aircraft, so they
986 // Are repositioned to the correct ground altitude when the user flies within visibility range.
987 // In addition, check whether we are out of user range, so this aircraft
990 Transform(); // make sure aip is initialized.
994 pos.setElevationFt(altitude_ft);
997 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
998 aiOutOfSight = !aiTrafficVisible();
1001 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1002 aiOutOfSight = true;
1006 timeElapsed = now - fp->getStartTime();
1007 flightplanActive = fp->isActive(now);
1009 // no flight plan, update target heading, speed, and altitude
1010 // from control properties. These default to the initial
1011 // settings in the config file, but can be changed "on the
1013 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1014 if ( lat_mode == "roll" ) {
1016 = props->getDoubleValue("controls/flight/target-roll" );
1020 = props->getDoubleValue("controls/flight/target-hdg" );
1025 = props->getStringValue("controls/flight/longitude-mode");
1026 if ( lon_mode == "alt" ) {
1027 double alt = props->getDoubleValue("controls/flight/target-alt" );
1031 = props->getDoubleValue("controls/flight/target-pitch" );
1035 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1039 void FGAIAircraft::updateHeading() {
1040 // adjust heading based on current bank angle
1045 // double turnConstant;
1047 // turnConstant = 0.0088362;
1049 // turnConstant = 0.088362;
1050 // If on ground, calculate heading change directly
1052 double headingDiff = fabs(hdg-tgt_heading);
1053 // double bank_sense = 0.0;
1055 double diff = fabs(hdg - tgt_heading);
1057 diff = fabs(diff - 360);
1059 double sum = hdg + diff;
1062 if (fabs(sum - tgt_heading) < 1.0) {
1063 bank_sense = 1.0; // right turn
1065 bank_sense = -1.0; // left turn
1067 if (headingDiff > 180)
1068 headingDiff = fabs(headingDiff - 360);
1069 double sum = hdg + headingDiff;
1072 if (fabs(sum - tgt_heading) > 0.0001) {
1073 // bank_sense = -1.0;
1075 // bank_sense = 1.0;
1078 // cerr << trafficRef->getCallSign() << " Heading "
1079 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1080 //if (headingDiff > 60) {
1081 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1082 //assertSpeed(groundTargetSpeed);
1083 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1085 // groundTargetSpeed = tgt_speed;
1087 if (sign(groundTargetSpeed) != sign(tgt_speed))
1088 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1089 //assertSpeed(groundTargetSpeed);
1090 // 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.
1092 if (headingDiff > 30.0) {
1093 // invert if pushed backward
1094 headingChangeRate += 10.0 * dt * sign(roll);
1096 // Clamp the maximum steering rate to 30 degrees per second,
1097 // But only do this when the heading error is decreasing.
1098 if ((headingDiff < headingError)) {
1099 if (headingChangeRate > 30)
1100 headingChangeRate = 30;
1101 else if (headingChangeRate < -30)
1102 headingChangeRate = -30;
1106 if (fabs(headingChangeRate) > headingDiff)
1107 headingChangeRate = headingDiff*sign(roll);
1109 headingChangeRate += dt * sign(roll);
1114 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1115 headingError = headingDiff;
1116 if (fabs(headingError) < 1.0) {
1120 if (fabs(speed) > 1.0) {
1121 turn_radius_ft = 0.088362 * speed * speed
1122 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1124 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1125 turn_radius_ft = 1.0;
1127 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1128 double dist_covered_ft = speed * 1.686 * dt;
1129 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1130 hdg += alpha * sign(roll);
1132 while ( hdg > 360.0 ) {
1136 while ( hdg < 0.0) {
1144 void FGAIAircraft::updateBankAngleTarget() {
1145 // adjust target bank angle if heading lock engaged
1147 double bank_sense = 0.0;
1148 double diff = fabs(hdg - tgt_heading);
1150 diff = fabs(diff - 360);
1152 double sum = hdg + diff;
1155 if (fabs(sum - tgt_heading) < 1.0) {
1156 bank_sense = 1.0; // right turn
1158 bank_sense = -1.0; // left turn
1160 if (diff < _performance->maximumBankAngle()) {
1161 tgt_roll = diff * bank_sense;
1163 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1165 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1166 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1167 // The only way to resolve this is to make them slow down.
1173 void FGAIAircraft::updateVerticalSpeedTarget() {
1174 // adjust target Altitude, based on ground elevation when on ground
1178 } else if (alt_lock) {
1179 // find target vertical speed
1181 if (altitude_ft < tgt_altitude_ft) {
1182 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1184 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1187 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1188 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1189 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1190 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1191 //cerr << "Target vs before : " << tgt_vs;
1192 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1193 double min_vs = 100;
1194 if (tgt_altitude_ft < altitude_ft)
1196 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1197 && (fabs(max_vs) < fabs(tgt_vs)))
1200 if (fabs(tgt_vs) < fabs(min_vs))
1202 //cerr << "target vs : after " << tgt_vs << endl;
1209 void FGAIAircraft::updatePitchAngleTarget() {
1210 // if on ground and above vRotate -> initial rotation
1211 if (onGround() && (speed > _performance->vRotate()))
1212 tgt_pitch = 8.0; // some rough B737 value
1214 //TODO pitch angle on approach and landing
1216 // match pitch angle to vertical speed
1217 else if (tgt_vs > 0) {
1218 tgt_pitch = tgt_vs * 0.005;
1220 tgt_pitch = tgt_vs * 0.002;
1224 const string& FGAIAircraft::atGate()
1226 if ((fp->getLeg() < 3) && trafficRef) {
1227 if (fp->getParkingGate()) {
1228 return fp->getParkingGate()->ident();
1232 static const string empty;
1236 void FGAIAircraft::handleATCRequests() {
1237 //TODO implement NullController for having no ATC to save the conditionals
1239 controller->updateAircraftInformation(getID(),
1240 pos.getLatitudeDeg(),
1241 pos.getLongitudeDeg(),
1245 processATC(controller->getInstruction(getID()));
1247 if (towerController) {
1248 towerController->updateAircraftInformation(getID(),
1249 pos.getLatitudeDeg(),
1250 pos.getLongitudeDeg(),
1257 void FGAIAircraft::updateActualState() {
1258 //update current state
1259 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1260 double distance = speed * SG_KT_TO_MPS * dt;
1261 pos = SGGeodesy::direct(pos, hdg, distance);
1265 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1267 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1268 //assertSpeed(speed);
1270 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1272 // adjust altitude (meters) based on current vertical speed (fpm)
1273 altitude_ft += vs / 60.0 * dt;
1274 pos.setElevationFt(altitude_ft);
1276 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1277 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1280 void FGAIAircraft::updateSecondaryTargetValues() {
1281 // derived target state values
1282 updateBankAngleTarget();
1283 updateVerticalSpeedTarget();
1284 updatePitchAngleTarget();
1286 //TODO calculate wind correction angle (tgt_yaw)
1290 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1291 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1292 if (curr->getName() == string("BOD")) {
1293 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1294 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1295 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1297 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1298 double descentTimeNeeded = verticalDistance / descentRate;
1299 double distanceCovered = descentSpeed * descentTimeNeeded;
1301 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1302 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1303 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1304 cerr << "Descent rate : " << descentRate << endl;
1305 cerr << "Descent speed : " << descentSpeed << endl;
1306 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1307 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1308 cerr << "DistanceCovered : " << distanceCovered << endl;
1310 //cerr << "Distance = " << distance << endl;
1311 distance = distanceCovered;
1312 if (dist < distanceCovered) {
1313 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1325 void FGAIAircraft::resetPositionFromFlightPlan()
1327 // the one behind you
1328 FGAIWaypoint* prev = 0;
1330 FGAIWaypoint* curr = 0;
1332 FGAIWaypoint* next = 0;
1334 prev = fp->getPreviousWaypoint();
1335 curr = fp->getCurrentWaypoint();
1336 next = fp->getNextWaypoint();
1338 setLatitude(prev->getLatitude());
1339 setLongitude(prev->getLongitude());
1340 double tgt_heading = fp->getBearing(curr, next);
1341 setHeading(tgt_heading);
1342 setAltitude(prev->getAltitude());
1343 setSpeed(prev->getSpeed());
1346 double FGAIAircraft::getBearing(double crse)
1348 double hdgDiff = fabs(hdg-crse);
1350 hdgDiff = fabs(hdgDiff - 360);
1354 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1355 FGAIWaypoint* curr = 0;
1356 curr = fp->getCurrentWaypoint();
1358 // don't recalculate tracklength unless the start/stop waypoint has changed
1360 ((curr->getName() != trackCache.startWptName)||
1361 (wptName != trackCache.finalWptName)))
1363 trackCache.remainingLength = fp->checkTrackLength(wptName);
1364 trackCache.startWptName = curr->getName();
1365 trackCache.finalWptName = wptName;
1367 double tracklength = trackCache.remainingLength;
1368 if (tracklength > 0.1) {
1369 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1373 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1374 time_t arrivalTime = fp->getArrivalTime();
1376 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1377 time_t secondsToGo = arrivalTime - now;
1378 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1379 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1381 return (ete - secondsToGo); // Positive when we're too slow...
1384 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1386 double delta = target - cur;
1387 double maxDelta = maxDeltaSec * dt;
1389 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1390 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1393 // drive various properties in a semi-realistic fashion.
1394 void FGAIAircraft::updateModelProperties(double dt)
1400 SGPropertyNode* gear = props->getChild("gear", 0, true);
1401 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1402 if (!gear->hasValue("gear/position-norm")) {
1403 gear->setDoubleValue("gear/position-norm", targetGearPos);
1406 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1407 if (gearPosNorm != targetGearPos) {
1408 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1409 if (gearPosNorm < 0.001) {
1411 } else if (gearPosNorm > 0.999) {
1415 for (int i=0; i<6; ++i) {
1416 SGPropertyNode* g = gear->getChild("gear", i, true);
1417 g->setDoubleValue("position-norm", gearPosNorm);
1418 } // of gear setting loop
1419 } // of gear in-transit
1421 // double flapPosNorm = props->getDoubleValue();