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/simple.hxx>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
44 #include "AIAircraft.hxx"
45 #include "performancedata.hxx"
46 #include "performancedb.hxx"
53 //#include <Airports/trafficcontroller.hxx>
55 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
56 /* HOT must be disabled for AI Aircraft,
57 * otherwise traffic detection isn't working as expected.*/
58 FGAIBase(otAircraft, false)
62 groundOffset = trafficRef->getGroundOffset();
63 setCallSign(trafficRef->getCallSign());
79 groundTargetSpeed = 0;
81 // set heading and altitude locks
85 headingChangeRate = 0.0;
91 needsTaxiClearance = false;
92 _needsGroundElevation = true;
94 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
100 FGAIAircraft::~FGAIAircraft() {
103 controller->signOff(getID());
107 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
111 FGAIBase::readFromScenario(scFileNode);
113 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
114 setFlightPlan(scFileNode->getStringValue("flightplan"),
115 scFileNode->getBoolValue("repeat", false));
116 setCallSign(scFileNode->getStringValue("callsign"));
120 void FGAIAircraft::bind() {
123 tie("controls/gear/gear-down",
124 SGRawValueMethods<FGAIAircraft,bool>(*this,
125 &FGAIAircraft::_getGearDown));
126 tie("transponder-id",
127 SGRawValueMethods<FGAIAircraft,const char*>(*this,
128 &FGAIAircraft::_getTransponderCode));
131 void FGAIAircraft::update(double dt) {
132 FGAIBase::update(dt);
137 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
139 static PerformanceDB perfdb; //TODO make it a global service
140 _performance = perfdb.getDataFor(acType, acclass);
144 void FGAIAircraft::setPerformance(PerformanceData *ps) {
149 void FGAIAircraft::Run(double dt) {
150 FGAIAircraft::dt = dt;
152 bool outOfSight = false,
153 flightplanActive = true;
154 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
159 if (!flightplanActive) {
160 groundTargetSpeed = 0;
163 handleATCRequests(); // ATC also has a word to say
164 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
166 // We currently have one situation in which an AIAircraft object is used that is not attached to the
167 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
168 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
171 UpdateRadar(manager);
175 void FGAIAircraft::checkVisibility()
177 double visibility_meters = fgGetDouble("/environment/visibility-m");
178 invisible = (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters);
183 void FGAIAircraft::AccelTo(double speed) {
185 //assertSpeed(speed);
187 _needsGroundElevation = true;
191 void FGAIAircraft::PitchTo(double angle) {
197 void FGAIAircraft::RollTo(double angle) {
203 void FGAIAircraft::YawTo(double angle) {
208 void FGAIAircraft::ClimbTo(double alt_ft ) {
209 tgt_altitude_ft = alt_ft;
214 void FGAIAircraft::TurnTo(double heading) {
215 tgt_heading = heading;
220 double FGAIAircraft::sign(double x) {
228 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
229 if (!flightplan.empty()) {
230 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
231 fp->setRepeat(repeat);
237 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
243 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
245 // the one behind you
246 FGAIWaypoint* prev = 0;
248 FGAIWaypoint* curr = 0;
250 FGAIWaypoint* next = 0;
252 prev = fp->getPreviousWaypoint();
253 curr = fp->getCurrentWaypoint();
254 next = fp->getNextWaypoint();
258 ///////////////////////////////////////////////////////////////////////////
259 // Initialize the flightplan
260 //////////////////////////////////////////////////////////////////////////
262 handleFirstWaypoint();
264 } // end of initialization
265 if (! fpExecutable(now))
269 double distanceToDescent;
270 if(reachedEndOfCruise(distanceToDescent)) {
271 if (!loadNextLeg(distanceToDescent)) {
275 prev = fp->getPreviousWaypoint();
276 curr = fp->getCurrentWaypoint();
277 next = fp->getNextWaypoint();
285 if (! leadPointReached(curr)) {
286 controlHeading(curr);
287 controlSpeed(curr, next);
291 cerr << getCallSign()
292 << ": verifying lead distance to waypoint : "
293 << fp->getCurrentWaypoint()->name << " "
294 << fp->getLeadDistance() << ". Distance to go "
295 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
296 << ". Target speed = "
298 << ". Current speed = "
300 << ". Minimum Bearing " << minBearing
304 if (curr->isFinished()) //end of the flight plan
314 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
315 tgt_heading = fp->getBearing(curr, next);
319 //TODO let the fp handle this (loading of next leg)
320 fp->IncrementWaypoint( trafficRef != 0 );
321 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
322 if (!loadNextLeg()) {
327 prev = fp->getPreviousWaypoint();
328 curr = fp->getCurrentWaypoint();
329 next = fp->getNextWaypoint();
331 // Now that we have incremented the waypoints, excute some traffic manager specific code
333 //TODO isn't this best executed right at the beginning?
334 if (! aiTrafficVisible()) {
339 if (! handleAirportEndPoints(prev, now)) {
344 announcePositionToController();
349 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
353 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
355 tgt_altitude_ft = prev->getAltitude();
356 if (curr->getCrossat() > -1000.0) {
358 // Distance to go in meters
359 double vert_dist_ft = curr->getCrossat() - altitude_ft;
360 double err_dist = prev->getCrossat() - altitude_ft;
361 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
362 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
365 tgt_altitude_ft = curr->getCrossat();
370 AccelTo(prev->getSpeed());
371 hdg_lock = alt_lock = true;
372 no_roll = prev->getOn_ground();
376 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
378 // err is negative when we passed too high
379 double vert_m = vert_ft * SG_FEET_TO_METER;
380 //double err_m = err * SG_FEET_TO_METER;
381 //double angle = atan2(vert_m, dist_m);
382 double speedMs = (speed * SG_NM_TO_METER) / 3600;
383 //double vs = cos(angle) * speedMs; // Now in m/s
385 //cerr << "Error term = " << err_m << endl;
387 vs = ((vert_m) / dist_m) * speedMs;
389 // Convert to feet per minute
390 vs *= (SG_METER_TO_FEET * 60);
391 //if (getCallSign() == "LUFTHANSA2002")
392 //if (fabs(vs) > 100000) {
393 // if (getCallSign() == "LUFTHANSA2057") {
394 // 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;
395 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
396 // // / 6076.0 / speed*60.0);
402 void FGAIAircraft::assertSpeed(double speed)
404 if ((speed < -50) || (speed > 1000)) {
405 cerr << getCallSign() << " "
406 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
407 << "Departure airport " << trafficRef->getDepartureAirport() << " "
408 << "Leg " << fp->getLeg() << " "
409 << "target_speed << " << tgt_speed << " "
410 << "speedFraction << " << speedFraction << " "
411 << "Currecnt speed << " << speed << " "
419 void FGAIAircraft::checkTcas(void)
421 if (props->getIntValue("tcas/threat-level",0)==3)
423 int RASense = props->getIntValue("tcas/ra-sense",0);
424 if ((RASense>0)&&(tgt_vs<4000))
430 // downward RA: descend!
431 if (altitude_ft < 1000)
433 // too low: level off
446 void FGAIAircraft::initializeFlightPlan() {
450 bool FGAIAircraft::_getGearDown() const {
451 return _performance->gearExtensible(this);
455 const char * FGAIAircraft::_getTransponderCode() const {
456 return transponderCode.c_str();
459 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
460 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
462 bool FGAIAircraft::loadNextLeg(double distance) {
465 if ((leg = fp->getLeg()) == 9) {
466 if (!trafficRef->next()) {
469 setCallSign(trafficRef->getCallSign());
474 FGAirport *dep = trafficRef->getDepartureAirport();
475 FGAirport *arr = trafficRef->getArrivalAirport();
480 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
487 trafficRef->getSpeed(),
491 trafficRef->getRadius(),
492 trafficRef->getFlightType(),
496 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
502 // Note: This code is copied from David Luff's AILocalTraffic
503 // Warning - ground elev determination is CPU intensive
504 // Either this function or the logic of how often it is called
505 // will almost certainly change.
507 void FGAIAircraft::getGroundElev(double dt) {
510 if (!needGroundElevation())
512 // Update minimally every three secs, but add some randomness
513 // to prevent all AI objects doing this in synchrony
514 if (dt_elev_count < (3.0) + (rand() % 10))
519 // Only do the proper hitlist stuff if we are within visible range of the viewer.
521 double visibility_meters = fgGetDouble("/environment/visibility-m");
522 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
526 double range = 500.0;
527 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
530 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
532 tgt_altitude_ft = alt * SG_METER_TO_FEET;
535 // aircraft is stationary and we obtained altitude for this spot - we're done.
536 _needsGroundElevation = false;
544 void FGAIAircraft::doGroundAltitude() {
545 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
548 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
550 altitude_ft = (tgt_altitude_ft + groundOffset);
552 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
558 void FGAIAircraft::announcePositionToController() {
560 int leg = fp->getLeg();
562 // Note that leg has been incremented after creating the current leg, so we should use
563 // leg numbers here that are one higher than the number that is used to create the leg
564 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
565 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
566 // the original leg numbers here!
568 case 1: // Startup and Push back
569 if (trafficRef->getDepartureAirport()->getDynamics())
570 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
572 case 2: // Taxiing to runway
573 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
574 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
576 case 3: //Take off tower controller
577 if (trafficRef->getDepartureAirport()->getDynamics()) {
578 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
581 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
585 if (trafficRef->getDepartureAirport()->getDynamics()) {
586 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
589 case 8: // Taxiing for parking
590 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
591 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
598 if ((controller != prevController) && (prevController != 0)) {
599 prevController->signOff(getID());
601 prevController = controller;
603 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
604 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
605 trafficRef->getRadius(), leg, this);
610 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
611 if (!takeOffStatus) {
612 int leg = fp->getLeg();
614 if (trafficRef->getDepartureAirport()->getDynamics()) {
615 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
617 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
619 if (towerController) {
620 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
621 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
622 trafficRef->getRadius(), leg, this);
623 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
627 takeOffStatus = state;
630 // Process ATC instructions and report back
632 void FGAIAircraft::processATC(FGATCInstruction instruction) {
633 if (instruction.getCheckForCircularWait()) {
634 // This is not exactly an elegant solution,
635 // but at least it gives me a chance to check
636 // if circular waits are resolved.
637 // For now, just take the offending aircraft
640 // a more proper way should be - of course - to
641 // let an offending aircraft take an evasive action
642 // for instance taxi back a little bit.
644 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
645 if (instruction.getHoldPattern ()) {}
648 if (instruction.getHoldPosition ()) {
656 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
659 // Change speed Instruction. This can only be excecuted when there is no
660 // Hold position instruction.
661 if (instruction.getChangeSpeed ()) {
663 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
664 AccelTo(instruction.getSpeed());
666 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
669 if (instruction.getChangeHeading ()) {
671 TurnTo(instruction.getHeading());
677 if (instruction.getChangeAltitude()) {}
682 void FGAIAircraft::handleFirstWaypoint() {
683 bool eraseWaypoints; //TODO YAGNI
686 eraseWaypoints = true;
688 eraseWaypoints = false;
691 FGAIWaypoint* prev = 0; // the one behind you
692 FGAIWaypoint* curr = 0; // the one ahead
693 FGAIWaypoint* next = 0;// the next plus 1
697 //TODO fp should handle this
698 fp->IncrementWaypoint(eraseWaypoints);
699 if (!(fp->getNextWaypoint()) && trafficRef)
700 if (!loadNextLeg()) {
705 prev = fp->getPreviousWaypoint(); //first waypoint
706 curr = fp->getCurrentWaypoint(); //second waypoint
707 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
709 setLatitude(prev->getLatitude());
710 setLongitude(prev->getLongitude());
711 setSpeed(prev->getSpeed());
712 setAltitude(prev->getAltitude());
714 if (prev->getSpeed() > 0.0)
715 setHeading(fp->getBearing(prev, curr));
717 setHeading(fp->getBearing(curr, prev));
719 // If next doesn't exist, as in incrementally created flightplans for
720 // AI/Trafficmanager created plans,
721 // Make sure lead distance is initialized otherwise
723 fp->setLeadDistance(speed, hdg, curr, next);
725 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
728 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
729 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
730 // / 6076.0 / prev->getSpeed()*60.0);
731 double vert_dist_ft = curr->getCrossat() - altitude_ft;
732 double err_dist = prev->getCrossat() - altitude_ft;
733 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
734 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
736 tgt_altitude_ft = curr->getCrossat();
739 tgt_altitude_ft = prev->getAltitude();
741 alt_lock = hdg_lock = true;
742 no_roll = prev->getOn_ground();
744 Transform(); // make sure aip is initialized.
745 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
747 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
749 // Make sure to announce the aircraft's position
750 announcePositionToController();
756 * Check Execution time (currently once every 100 ms)
757 * Add a bit of randomization to prevent the execution of all flight plans
758 * in synchrony, which can add significant periodic framerate flutter.
763 bool FGAIAircraft::fpExecutable(time_t now) {
764 double rand_exec_time = (rand() % 100) / 100;
765 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
770 * Check to see if we've reached the lead point for our next turn
775 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
776 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
778 //cerr << "2" << endl;
779 double lead_dist = fp->getLeadDistance();
780 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
781 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
782 tgt_speed = -(dist_to_go / 10.0);
783 if (tgt_speed > -0.5) {
786 //assertSpeed(tgt_speed);
787 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
788 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
791 if (lead_dist < fabs(2*speed)) {
792 //don't skip over the waypoint
793 lead_dist = fabs(2*speed);
794 //cerr << "Extending lead distance to " << lead_dist << endl;
797 //prev_dist_to_go = dist_to_go;
798 //if (dist_to_go < lead_dist)
799 // cerr << trafficRef->getCallSign() << " Distance : "
800 // << dist_to_go << ": Lead distance "
801 // << lead_dist << " " << curr->name
802 // << " Ground target speed " << groundTargetSpeed << endl;
804 // don't do bearing calculations for ground traffic
805 bearing = getBearing(fp->getBearing(pos, curr));
806 if (bearing < minBearing) {
807 minBearing = bearing;
808 if (minBearing < 10) {
811 if ((minBearing < 360.0) && (minBearing > 10.0)) {
812 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
818 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
819 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
820 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
821 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
824 if ((dist_to_go < lead_dist) ||
825 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
828 prev_dist_to_go = HUGE_VAL;
831 prev_dist_to_go = dist_to_go;
837 bool FGAIAircraft::aiTrafficVisible()
839 SGVec3d cartPos = SGVec3d::fromGeod(pos);
840 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
841 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
842 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
847 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
848 * in the case of an arrival.
854 //TODO the trafficRef is the right place for the method
855 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
856 // prepare routing from one airport to another
857 FGAirport * dep = trafficRef->getDepartureAirport();
858 FGAirport * arr = trafficRef->getArrivalAirport();
863 // This waypoint marks the fact that the aircraft has passed the initial taxi
864 // departure waypoint, so it can release the parking.
865 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
866 //cerr << "Passing waypoint : " << prev->getName() << endl;
867 if (prev->contains("PushBackPoint")) {
868 // clearing the parking assignment will release the gate
869 fp->setGate(ParkingAssignment());
871 //setTaxiClearanceRequest(true);
873 if (prev->contains("legend")) {
876 if (prev->contains(string("DepartureHold"))) {
877 //cerr << "Passing point DepartureHold" << endl;
878 scheduleForATCTowerDepartureControl(1);
880 if (prev->contains(string("Accel"))) {
883 //if (prev->contains(string("landing"))) {
884 // if (speed < _performance->vTaxi() * 2) {
885 // fp->shortenToFirst(2, "legend");
888 //if (prev->contains(string("final"))) {
890 // cerr << getCallSign() << " "
891 // << fp->getPreviousWaypoint()->getName()
892 // << ". Alt = " << altitude_ft
894 // << " horizontal speed " << speed
895 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
896 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
897 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
899 // This is the last taxi waypoint, and marks the the end of the flight plan
900 // so, the schedule should update and wait for the next departure time.
901 if (prev->contains("END")) {
902 time_t nextDeparture = trafficRef->getDepartureTime();
903 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
904 if (nextDeparture < (now+1200)) {
905 nextDeparture = now + 1200;
907 fp->setTime(nextDeparture);
915 * Check difference between target bearing and current heading and correct if necessary.
919 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
920 double calc_bearing = fp->getBearing(pos, curr);
921 //cerr << "Bearing = " << calc_bearing << endl;
924 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
927 if (finite(calc_bearing)) {
928 double hdg_error = calc_bearing - tgt_heading;
929 if (fabs(hdg_error) > 0.01) {
930 TurnTo( calc_bearing );
934 cerr << "calc_bearing is not a finite number : "
936 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
937 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
938 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
945 * Update the lead distance calculation if speed has changed sufficiently
946 * to prevent spinning (hopefully);
951 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
952 double speed_diff = speed - prevSpeed;
954 if (fabs(speed_diff) > 10) {
956 //assertSpeed(speed);
958 fp->setLeadDistance(speed, tgt_heading, curr, next);
965 * Update target values (heading, alt, speed) depending on flight plan or control properties
967 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
968 if (fp) // AI object has a flightplan
970 //TODO make this a function of AIBase
971 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
972 //cerr << "UpateTArgetValues() " << endl;
973 ProcessFlightPlan(dt, now);
975 // Do execute Ground elev for inactive aircraft, so they
976 // Are repositioned to the correct ground altitude when the user flies within visibility range.
977 // In addition, check whether we are out of user range, so this aircraft
980 Transform(); // make sure aip is initialized.
984 pos.setElevationFt(altitude_ft);
987 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
988 aiOutOfSight = !aiTrafficVisible();
991 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
996 timeElapsed = now - fp->getStartTime();
997 flightplanActive = fp->isActive(now);
999 // no flight plan, update target heading, speed, and altitude
1000 // from control properties. These default to the initial
1001 // settings in the config file, but can be changed "on the
1003 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1004 if ( lat_mode == "roll" ) {
1006 = props->getDoubleValue("controls/flight/target-roll" );
1010 = props->getDoubleValue("controls/flight/target-hdg" );
1015 = props->getStringValue("controls/flight/longitude-mode");
1016 if ( lon_mode == "alt" ) {
1017 double alt = props->getDoubleValue("controls/flight/target-alt" );
1021 = props->getDoubleValue("controls/flight/target-pitch" );
1025 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1029 void FGAIAircraft::updateHeading() {
1030 // adjust heading based on current bank angle
1035 // double turnConstant;
1037 // turnConstant = 0.0088362;
1039 // turnConstant = 0.088362;
1040 // If on ground, calculate heading change directly
1042 double headingDiff = fabs(hdg-tgt_heading);
1043 // double bank_sense = 0.0;
1045 double diff = fabs(hdg - tgt_heading);
1047 diff = fabs(diff - 360);
1049 double sum = hdg + diff;
1052 if (fabs(sum - tgt_heading) < 1.0) {
1053 bank_sense = 1.0; // right turn
1055 bank_sense = -1.0; // left turn
1057 if (headingDiff > 180)
1058 headingDiff = fabs(headingDiff - 360);
1059 double sum = hdg + headingDiff;
1062 if (fabs(sum - tgt_heading) > 0.0001) {
1063 // bank_sense = -1.0;
1065 // bank_sense = 1.0;
1068 // cerr << trafficRef->getCallSign() << " Heading "
1069 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1070 //if (headingDiff > 60) {
1071 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1072 //assertSpeed(groundTargetSpeed);
1073 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1075 // groundTargetSpeed = tgt_speed;
1077 if (sign(groundTargetSpeed) != sign(tgt_speed))
1078 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1079 //assertSpeed(groundTargetSpeed);
1080 // 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.
1082 if (headingDiff > 30.0) {
1083 // invert if pushed backward
1084 headingChangeRate += 10.0 * dt * sign(roll);
1086 // Clamp the maximum steering rate to 30 degrees per second,
1087 // But only do this when the heading error is decreasing.
1088 if ((headingDiff < headingError)) {
1089 if (headingChangeRate > 30)
1090 headingChangeRate = 30;
1091 else if (headingChangeRate < -30)
1092 headingChangeRate = -30;
1096 if (fabs(headingChangeRate) > headingDiff)
1097 headingChangeRate = headingDiff*sign(roll);
1099 headingChangeRate += dt * sign(roll);
1104 //cerr << trafficRef->getCallSign() << " Heading "
1105 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1106 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1107 headingError = headingDiff;
1108 if (fabs(headingError) < 1.0) {
1112 if (fabs(speed) > 1.0) {
1113 turn_radius_ft = 0.088362 * speed * speed
1114 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1116 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1117 turn_radius_ft = 1.0;
1119 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1120 double dist_covered_ft = speed * 1.686 * dt;
1121 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1122 hdg += alpha * sign(roll);
1124 while ( hdg > 360.0 ) {
1128 while ( hdg < 0.0) {
1136 void FGAIAircraft::updateBankAngleTarget() {
1137 // adjust target bank angle if heading lock engaged
1139 double bank_sense = 0.0;
1140 double diff = fabs(hdg - tgt_heading);
1142 diff = fabs(diff - 360);
1144 double sum = hdg + diff;
1147 if (fabs(sum - tgt_heading) < 1.0) {
1148 bank_sense = 1.0; // right turn
1150 bank_sense = -1.0; // left turn
1152 if (diff < _performance->maximumBankAngle()) {
1153 tgt_roll = diff * bank_sense;
1155 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1157 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1158 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1159 // The only way to resolve this is to make them slow down.
1165 void FGAIAircraft::updateVerticalSpeedTarget() {
1166 // adjust target Altitude, based on ground elevation when on ground
1170 } else if (alt_lock) {
1171 // find target vertical speed
1173 if (altitude_ft < tgt_altitude_ft) {
1174 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1176 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1179 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1180 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1181 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1182 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1183 //cerr << "Target vs before : " << tgt_vs;
1184 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1185 double min_vs = 100;
1186 if (tgt_altitude_ft < altitude_ft)
1188 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1189 && (fabs(max_vs) < fabs(tgt_vs)))
1192 if (fabs(tgt_vs) < fabs(min_vs))
1194 //cerr << "target vs : after " << tgt_vs << endl;
1201 void FGAIAircraft::updatePitchAngleTarget() {
1202 // if on ground and above vRotate -> initial rotation
1203 if (onGround() && (speed > _performance->vRotate()))
1204 tgt_pitch = 8.0; // some rough B737 value
1206 //TODO pitch angle on approach and landing
1208 // match pitch angle to vertical speed
1209 else if (tgt_vs > 0) {
1210 tgt_pitch = tgt_vs * 0.005;
1212 tgt_pitch = tgt_vs * 0.002;
1216 const string& FGAIAircraft::atGate()
1218 if ((fp->getLeg() < 3) && trafficRef) {
1219 if (fp->getParkingGate()) {
1220 return fp->getParkingGate()->ident();
1224 static const string empty;
1228 void FGAIAircraft::handleATCRequests() {
1229 //TODO implement NullController for having no ATC to save the conditionals
1231 controller->updateAircraftInformation(getID(),
1232 pos.getLatitudeDeg(),
1233 pos.getLongitudeDeg(),
1237 processATC(controller->getInstruction(getID()));
1239 if (towerController) {
1240 towerController->updateAircraftInformation(getID(),
1241 pos.getLatitudeDeg(),
1242 pos.getLongitudeDeg(),
1249 void FGAIAircraft::updateActualState() {
1250 //update current state
1251 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1252 double distance = speed * SG_KT_TO_MPS * dt;
1253 pos = SGGeodesy::direct(pos, hdg, distance);
1257 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1259 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1260 //assertSpeed(speed);
1262 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1264 // adjust altitude (meters) based on current vertical speed (fpm)
1265 altitude_ft += vs / 60.0 * dt;
1266 pos.setElevationFt(altitude_ft);
1268 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1269 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1272 void FGAIAircraft::updateSecondaryTargetValues() {
1273 // derived target state values
1274 updateBankAngleTarget();
1275 updateVerticalSpeedTarget();
1276 updatePitchAngleTarget();
1278 //TODO calculate wind correction angle (tgt_yaw)
1282 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1283 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1284 if (curr->getName() == string("BOD")) {
1285 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1286 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1287 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1289 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1290 double descentTimeNeeded = verticalDistance / descentRate;
1291 double distanceCovered = descentSpeed * descentTimeNeeded;
1293 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1294 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1295 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1296 cerr << "Descent rate : " << descentRate << endl;
1297 cerr << "Descent speed : " << descentSpeed << endl;
1298 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1299 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1300 cerr << "DistanceCovered : " << distanceCovered << endl;
1302 //cerr << "Distance = " << distance << endl;
1303 distance = distanceCovered;
1304 if (dist < distanceCovered) {
1305 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1317 void FGAIAircraft::resetPositionFromFlightPlan()
1319 // the one behind you
1320 FGAIWaypoint* prev = 0;
1322 FGAIWaypoint* curr = 0;
1324 FGAIWaypoint* next = 0;
1326 prev = fp->getPreviousWaypoint();
1327 curr = fp->getCurrentWaypoint();
1328 next = fp->getNextWaypoint();
1330 setLatitude(prev->getLatitude());
1331 setLongitude(prev->getLongitude());
1332 double tgt_heading = fp->getBearing(curr, next);
1333 setHeading(tgt_heading);
1334 setAltitude(prev->getAltitude());
1335 setSpeed(prev->getSpeed());
1338 double FGAIAircraft::getBearing(double crse)
1340 double hdgDiff = fabs(hdg-crse);
1342 hdgDiff = fabs(hdgDiff - 360);
1346 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1347 FGAIWaypoint* curr = 0;
1348 curr = fp->getCurrentWaypoint();
1350 double tracklength = fp->checkTrackLength(wptName);
1351 if (tracklength > 0.1) {
1352 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1356 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1357 time_t arrivalTime = fp->getArrivalTime();
1359 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1360 time_t secondsToGo = arrivalTime - now;
1361 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1362 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1364 return (ete - secondsToGo); // Positive when we're too slow...