1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
3 // Written by David Culp, started October 2003.
5 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <Main/fg_props.hxx>
26 #include <Main/globals.hxx>
27 #include <Scenery/scenery.hxx>
28 #include <Scenery/tilemgr.hxx>
29 #include <Airports/dynamics.hxx>
30 #include <Airports/airport.hxx>
31 #include <Main/util.hxx>
32 #include <Traffic/Schedule.hxx>
34 #include <simgear/structure/exception.hxx>
40 // defined in AIShip.cxx
41 extern double fgIsFinite(double x);
43 #include "AIManager.hxx"
44 #include "AIAircraft.hxx"
45 #include "AIFlightPlan.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
54 //#include <Airports/trafficcontroller.hxx>
56 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
57 /* HOT must be disabled for AI Aircraft,
58 * otherwise traffic detection isn't working as expected.*/
59 FGAIBase(otAircraft, false)
63 groundOffset = trafficRef->getGroundOffset();
64 setCallSign(trafficRef->getCallSign());
80 groundTargetSpeed = 0;
82 // set heading and altitude locks
86 headingChangeRate = 0.0;
90 prev_dist_to_go = 0.0;
93 needsTaxiClearance = false;
94 _needsGroundElevation = true;
96 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
100 trackCache.remainingLength = 0;
101 trackCache.startWptName = "-";
105 FGAIAircraft::~FGAIAircraft() {
108 controller->signOff(getID());
112 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
116 FGAIBase::readFromScenario(scFileNode);
118 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
119 setFlightPlan(scFileNode->getStringValue("flightplan"),
120 scFileNode->getBoolValue("repeat", false));
121 setCallSign(scFileNode->getStringValue("callsign"));
125 void FGAIAircraft::bind() {
128 tie("transponder-id",
129 SGRawValueMethods<FGAIAircraft,const char*>(*this,
130 &FGAIAircraft::_getTransponderCode));
133 void FGAIAircraft::update(double dt) {
134 FGAIBase::update(dt);
139 void FGAIAircraft::unbind()
142 clearATCController();
145 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
147 static PerformanceDB perfdb; //TODO make it a global service
148 _performance = perfdb.getDataFor(acType, acclass);
152 void FGAIAircraft::setPerformance(PerformanceData *ps) {
157 void FGAIAircraft::Run(double dt) {
158 FGAIAircraft::dt = dt;
160 bool outOfSight = false,
161 flightplanActive = true;
162 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
167 if (!flightplanActive) {
168 groundTargetSpeed = 0;
171 handleATCRequests(); // ATC also has a word to say
172 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
175 // 25/11/12 - added but disabled, since setting properties isn't
176 // affecting the AI-model as expected.
177 updateModelProperties(dt);
180 // We currently have one situation in which an AIAircraft object is used that is not attached to the
181 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
182 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
185 UpdateRadar(manager);
186 invisible = !manager->isVisible(pos);
191 void FGAIAircraft::AccelTo(double speed) {
193 //assertSpeed(speed);
195 _needsGroundElevation = true;
199 void FGAIAircraft::PitchTo(double angle) {
205 void FGAIAircraft::RollTo(double angle) {
211 void FGAIAircraft::YawTo(double angle) {
216 void FGAIAircraft::ClimbTo(double alt_ft ) {
217 tgt_altitude_ft = alt_ft;
222 void FGAIAircraft::TurnTo(double heading) {
223 tgt_heading = heading;
228 double FGAIAircraft::sign(double x) {
236 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
238 if (flightplan.empty()) {
239 // this is the case for Nasal-scripted aircraft
243 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
244 if (fp->isValidPlan()) {
245 fp->setRepeat(repeat);
248 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
254 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
261 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
263 // the one behind you
264 FGAIWaypoint* prev = 0;
266 FGAIWaypoint* curr = 0;
268 FGAIWaypoint* next = 0;
270 prev = fp->getPreviousWaypoint();
271 curr = fp->getCurrentWaypoint();
272 next = fp->getNextWaypoint();
276 ///////////////////////////////////////////////////////////////////////////
277 // Initialize the flightplan
278 //////////////////////////////////////////////////////////////////////////
280 handleFirstWaypoint();
282 } // end of initialization
283 if (! fpExecutable(now))
287 double distanceToDescent;
288 if(reachedEndOfCruise(distanceToDescent)) {
289 if (!loadNextLeg(distanceToDescent)) {
293 prev = fp->getPreviousWaypoint();
294 curr = fp->getCurrentWaypoint();
295 next = fp->getNextWaypoint();
303 if (! leadPointReached(curr)) {
304 controlHeading(curr);
305 controlSpeed(curr, next);
309 cerr << getCallSign()
310 << ": verifying lead distance to waypoint : "
311 << fp->getCurrentWaypoint()->name << " "
312 << fp->getLeadDistance() << ". Distance to go "
313 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
314 << ". Target speed = "
316 << ". Current speed = "
318 << ". Minimum Bearing " << minBearing
322 if (curr->isFinished()) //end of the flight plan
332 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
333 tgt_heading = fp->getBearing(curr, next);
337 //TODO let the fp handle this (loading of next leg)
338 fp->IncrementWaypoint( trafficRef != 0 );
339 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
340 if (!loadNextLeg()) {
345 prev = fp->getPreviousWaypoint();
346 curr = fp->getCurrentWaypoint();
347 next = fp->getNextWaypoint();
349 // Now that we have incremented the waypoints, excute some traffic manager specific code
351 //TODO isn't this best executed right at the beginning?
352 if (! aiTrafficVisible()) {
357 if (! handleAirportEndPoints(prev, now)) {
362 announcePositionToController();
367 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
371 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
373 tgt_altitude_ft = prev->getAltitude();
374 if (curr->getCrossat() > -1000.0) {
376 // Distance to go in meters
377 double vert_dist_ft = curr->getCrossat() - altitude_ft;
378 double err_dist = prev->getCrossat() - altitude_ft;
379 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
380 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
383 tgt_altitude_ft = curr->getCrossat();
388 AccelTo(prev->getSpeed());
389 hdg_lock = alt_lock = true;
390 no_roll = prev->getOn_ground();
394 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
396 // err is negative when we passed too high
397 double vert_m = vert_ft * SG_FEET_TO_METER;
398 //double err_m = err * SG_FEET_TO_METER;
399 //double angle = atan2(vert_m, dist_m);
400 double speedMs = (speed * SG_NM_TO_METER) / 3600;
401 //double vs = cos(angle) * speedMs; // Now in m/s
403 //cerr << "Error term = " << err_m << endl;
405 vs = ((vert_m) / dist_m) * speedMs;
407 // Convert to feet per minute
408 vs *= (SG_METER_TO_FEET * 60);
409 //if (getCallSign() == "LUFTHANSA2002")
410 //if (fabs(vs) > 100000) {
411 // if (getCallSign() == "LUFTHANSA2057") {
412 // 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;
413 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
414 // // / 6076.0 / speed*60.0);
420 void FGAIAircraft::clearATCController()
427 void FGAIAircraft::assertSpeed(double speed)
429 if ((speed < -50) || (speed > 1000)) {
430 cerr << getCallSign() << " "
431 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
432 << "Departure airport " << trafficRef->getDepartureAirport() << " "
433 << "Leg " << fp->getLeg() << " "
434 << "target_speed << " << tgt_speed << " "
435 << "speedFraction << " << speedFraction << " "
436 << "Currecnt speed << " << speed << " "
444 void FGAIAircraft::checkTcas(void)
446 if (props->getIntValue("tcas/threat-level",0)==3)
448 int RASense = props->getIntValue("tcas/ra-sense",0);
449 if ((RASense>0)&&(tgt_vs<4000))
455 // downward RA: descend!
456 if (altitude_ft < 1000)
458 // too low: level off
471 void FGAIAircraft::initializeFlightPlan() {
474 const char * FGAIAircraft::_getTransponderCode() const {
475 return transponderCode.c_str();
478 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
479 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
481 bool FGAIAircraft::loadNextLeg(double distance) {
484 if ((leg = fp->getLeg()) == 9) {
485 if (!trafficRef->next()) {
488 setCallSign(trafficRef->getCallSign());
493 FGAirport *dep = trafficRef->getDepartureAirport();
494 FGAirport *arr = trafficRef->getArrivalAirport();
499 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
506 trafficRef->getSpeed(),
510 trafficRef->getRadius(),
511 trafficRef->getFlightType(),
515 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
521 // Note: This code is copied from David Luff's AILocalTraffic
522 // Warning - ground elev determination is CPU intensive
523 // Either this function or the logic of how often it is called
524 // will almost certainly change.
526 void FGAIAircraft::getGroundElev(double dt) {
529 if (!needGroundElevation())
531 // Update minimally every three secs, but add some randomness
532 // to prevent all AI objects doing this in synchrony
533 if (dt_elev_count < (3.0) + (rand() % 10))
538 // Only do the proper hitlist stuff if we are within visible range of the viewer.
540 double visibility_meters = fgGetDouble("/environment/visibility-m");
541 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
545 double range = 500.0;
546 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
549 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
551 tgt_altitude_ft = alt * SG_METER_TO_FEET;
554 // aircraft is stationary and we obtained altitude for this spot - we're done.
555 _needsGroundElevation = false;
563 void FGAIAircraft::doGroundAltitude() {
564 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
567 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
569 altitude_ft = (tgt_altitude_ft + groundOffset);
571 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
577 void FGAIAircraft::announcePositionToController() {
582 int leg = fp->getLeg();
583 if (!fp->getCurrentWaypoint()) {
584 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
585 // throw an exception so this aircraft gets killed by the AIManager.
586 throw sg_exception("bad AI flight plan");
589 // Note that leg has been incremented after creating the current leg, so we should use
590 // leg numbers here that are one higher than the number that is used to create the leg
591 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
592 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
593 // the original leg numbers here!
595 case 1: // Startup and Push back
596 if (trafficRef->getDepartureAirport()->getDynamics())
597 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
599 case 2: // Taxiing to runway
600 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists())
601 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController();
603 case 3: //Take off tower controller
604 if (trafficRef->getDepartureAirport()->getDynamics()) {
605 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
608 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
612 if (trafficRef->getArrivalAirport()->getDynamics()) {
613 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
616 case 8: // Taxiing for parking
617 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists())
618 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController();
625 if ((controller != prevController) && (prevController != 0)) {
626 prevController->signOff(getID());
628 prevController = controller;
630 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
631 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
632 trafficRef->getRadius(), leg, this);
636 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
637 if (!takeOffStatus) {
638 int leg = fp->getLeg();
640 if (trafficRef->getDepartureAirport()->getDynamics()) {
641 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
643 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
645 if (towerController) {
646 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
647 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
648 trafficRef->getRadius(), leg, this);
649 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
653 takeOffStatus = state;
656 // Process ATC instructions and report back
658 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
659 if (instruction.getCheckForCircularWait()) {
660 // This is not exactly an elegant solution,
661 // but at least it gives me a chance to check
662 // if circular waits are resolved.
663 // For now, just take the offending aircraft
666 // a more proper way should be - of course - to
667 // let an offending aircraft take an evasive action
668 // for instance taxi back a little bit.
670 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
671 if (instruction.getHoldPattern ()) {}
674 if (instruction.getHoldPosition ()) {
682 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
685 // Change speed Instruction. This can only be excecuted when there is no
686 // Hold position instruction.
687 if (instruction.getChangeSpeed ()) {
689 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
690 AccelTo(instruction.getSpeed());
692 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
695 if (instruction.getChangeHeading ()) {
697 TurnTo(instruction.getHeading());
703 if (instruction.getChangeAltitude()) {}
708 void FGAIAircraft::handleFirstWaypoint() {
709 bool eraseWaypoints; //TODO YAGNI
712 eraseWaypoints = true;
714 eraseWaypoints = false;
717 FGAIWaypoint* prev = 0; // the one behind you
718 FGAIWaypoint* curr = 0; // the one ahead
719 FGAIWaypoint* next = 0;// the next plus 1
723 //TODO fp should handle this
724 fp->IncrementWaypoint(eraseWaypoints);
725 if (!(fp->getNextWaypoint()) && trafficRef)
726 if (!loadNextLeg()) {
731 prev = fp->getPreviousWaypoint(); //first waypoint
732 curr = fp->getCurrentWaypoint(); //second waypoint
733 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
735 setLatitude(prev->getLatitude());
736 setLongitude(prev->getLongitude());
737 setSpeed(prev->getSpeed());
738 setAltitude(prev->getAltitude());
740 if (prev->getSpeed() > 0.0)
741 setHeading(fp->getBearing(prev, curr));
743 setHeading(fp->getBearing(curr, prev));
745 // If next doesn't exist, as in incrementally created flightplans for
746 // AI/Trafficmanager created plans,
747 // Make sure lead distance is initialized otherwise
749 fp->setLeadDistance(speed, hdg, curr, next);
751 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
754 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
755 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
756 // / 6076.0 / prev->getSpeed()*60.0);
757 double vert_dist_ft = curr->getCrossat() - altitude_ft;
758 double err_dist = prev->getCrossat() - altitude_ft;
759 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
760 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
762 tgt_altitude_ft = curr->getCrossat();
765 tgt_altitude_ft = prev->getAltitude();
767 alt_lock = hdg_lock = true;
768 no_roll = prev->getOn_ground();
770 Transform(); // make sure aip is initialized.
771 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
773 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
775 // Make sure to announce the aircraft's position
776 announcePositionToController();
782 * Check Execution time (currently once every 100 ms)
783 * Add a bit of randomization to prevent the execution of all flight plans
784 * in synchrony, which can add significant periodic framerate flutter.
789 bool FGAIAircraft::fpExecutable(time_t now) {
790 double rand_exec_time = (rand() % 100) / 100;
791 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
796 * Check to see if we've reached the lead point for our next turn
801 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
802 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
804 //cerr << "2" << endl;
805 double lead_dist = fp->getLeadDistance();
806 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
807 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
808 tgt_speed = -(dist_to_go / 10.0);
809 if (tgt_speed > -0.5) {
812 //assertSpeed(tgt_speed);
813 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
814 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
817 if (lead_dist < fabs(2*speed)) {
818 //don't skip over the waypoint
819 lead_dist = fabs(2*speed);
820 //cerr << "Extending lead distance to " << lead_dist << endl;
823 //prev_dist_to_go = dist_to_go;
824 //if (dist_to_go < lead_dist)
825 // cerr << trafficRef->getCallSign() << " Distance : "
826 // << dist_to_go << ": Lead distance "
827 // << lead_dist << " " << curr->name
828 // << " Ground target speed " << groundTargetSpeed << endl;
830 // don't do bearing calculations for ground traffic
831 bearing = getBearing(fp->getBearing(pos, curr));
832 if (bearing < minBearing) {
833 minBearing = bearing;
834 if (minBearing < 10) {
837 if ((minBearing < 360.0) && (minBearing > 10.0)) {
838 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
844 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
845 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
846 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
847 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
850 if ((dist_to_go < lead_dist) ||
851 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
854 prev_dist_to_go = HUGE_VAL;
857 prev_dist_to_go = dist_to_go;
863 bool FGAIAircraft::aiTrafficVisible()
865 SGVec3d cartPos = SGVec3d::fromGeod(pos);
866 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
867 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
868 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
873 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
874 * in the case of an arrival.
880 //TODO the trafficRef is the right place for the method
881 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
882 // prepare routing from one airport to another
883 FGAirport * dep = trafficRef->getDepartureAirport();
884 FGAirport * arr = trafficRef->getArrivalAirport();
889 // This waypoint marks the fact that the aircraft has passed the initial taxi
890 // departure waypoint, so it can release the parking.
891 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
892 //cerr << "Passing waypoint : " << prev->getName() << endl;
893 if (prev->contains("PushBackPoint")) {
894 // clearing the parking assignment will release the gate
895 fp->setGate(ParkingAssignment());
897 //setTaxiClearanceRequest(true);
899 if (prev->contains("legend")) {
902 if (prev->contains(string("DepartureHold"))) {
903 //cerr << "Passing point DepartureHold" << endl;
904 scheduleForATCTowerDepartureControl(1);
906 if (prev->contains(string("Accel"))) {
909 //if (prev->contains(string("landing"))) {
910 // if (speed < _performance->vTaxi() * 2) {
911 // fp->shortenToFirst(2, "legend");
914 //if (prev->contains(string("final"))) {
916 // cerr << getCallSign() << " "
917 // << fp->getPreviousWaypoint()->getName()
918 // << ". Alt = " << altitude_ft
920 // << " horizontal speed " << speed
921 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
922 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
923 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
925 // This is the last taxi waypoint, and marks the the end of the flight plan
926 // so, the schedule should update and wait for the next departure time.
927 if (prev->contains("END")) {
928 time_t nextDeparture = trafficRef->getDepartureTime();
929 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
930 if (nextDeparture < (now+1200)) {
931 nextDeparture = now + 1200;
933 fp->setTime(nextDeparture);
941 * Check difference between target bearing and current heading and correct if necessary.
945 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
946 double calc_bearing = fp->getBearing(pos, curr);
947 //cerr << "Bearing = " << calc_bearing << endl;
950 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
953 if (fgIsFinite(calc_bearing)) {
954 double hdg_error = calc_bearing - tgt_heading;
955 if (fabs(hdg_error) > 0.01) {
956 TurnTo( calc_bearing );
960 cerr << "calc_bearing is not a finite number : "
962 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
963 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
964 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
971 * Update the lead distance calculation if speed has changed sufficiently
972 * to prevent spinning (hopefully);
977 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
978 double speed_diff = speed - prevSpeed;
980 if (fabs(speed_diff) > 10) {
982 //assertSpeed(speed);
984 fp->setLeadDistance(speed, tgt_heading, curr, next);
991 * Update target values (heading, alt, speed) depending on flight plan or control properties
993 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
994 if (fp) // AI object has a flightplan
996 //TODO make this a function of AIBase
997 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
998 //cerr << "UpateTArgetValues() " << endl;
999 ProcessFlightPlan(dt, now);
1001 // Do execute Ground elev for inactive aircraft, so they
1002 // Are repositioned to the correct ground altitude when the user flies within visibility range.
1003 // In addition, check whether we are out of user range, so this aircraft
1006 Transform(); // make sure aip is initialized.
1010 pos.setElevationFt(altitude_ft);
1013 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
1014 aiOutOfSight = !aiTrafficVisible();
1017 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1018 aiOutOfSight = true;
1022 timeElapsed = now - fp->getStartTime();
1023 flightplanActive = fp->isActive(now);
1025 // no flight plan, update target heading, speed, and altitude
1026 // from control properties. These default to the initial
1027 // settings in the config file, but can be changed "on the
1029 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1030 if ( lat_mode == "roll" ) {
1032 = props->getDoubleValue("controls/flight/target-roll" );
1036 = props->getDoubleValue("controls/flight/target-hdg" );
1041 = props->getStringValue("controls/flight/longitude-mode");
1042 if ( lon_mode == "alt" ) {
1043 double alt = props->getDoubleValue("controls/flight/target-alt" );
1047 = props->getDoubleValue("controls/flight/target-pitch" );
1051 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1055 void FGAIAircraft::updateHeading() {
1056 // adjust heading based on current bank angle
1061 // double turnConstant;
1063 // turnConstant = 0.0088362;
1065 // turnConstant = 0.088362;
1066 // If on ground, calculate heading change directly
1068 double headingDiff = fabs(hdg-tgt_heading);
1069 // double bank_sense = 0.0;
1071 double diff = fabs(hdg - tgt_heading);
1073 diff = fabs(diff - 360);
1075 double sum = hdg + diff;
1078 if (fabs(sum - tgt_heading) < 1.0) {
1079 bank_sense = 1.0; // right turn
1081 bank_sense = -1.0; // left turn
1083 if (headingDiff > 180)
1084 headingDiff = fabs(headingDiff - 360);
1085 double sum = hdg + headingDiff;
1088 if (fabs(sum - tgt_heading) > 0.0001) {
1089 // bank_sense = -1.0;
1091 // bank_sense = 1.0;
1094 // cerr << trafficRef->getCallSign() << " Heading "
1095 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1096 //if (headingDiff > 60) {
1097 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1098 //assertSpeed(groundTargetSpeed);
1099 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1101 // groundTargetSpeed = tgt_speed;
1103 if (sign(groundTargetSpeed) != sign(tgt_speed))
1104 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1105 //assertSpeed(groundTargetSpeed);
1106 // 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.
1108 if (headingDiff > 30.0) {
1109 // invert if pushed backward
1110 headingChangeRate += 10.0 * dt * sign(roll);
1112 // Clamp the maximum steering rate to 30 degrees per second,
1113 // But only do this when the heading error is decreasing.
1114 if ((headingDiff < headingError)) {
1115 if (headingChangeRate > 30)
1116 headingChangeRate = 30;
1117 else if (headingChangeRate < -30)
1118 headingChangeRate = -30;
1122 if (fabs(headingChangeRate) > headingDiff)
1123 headingChangeRate = headingDiff*sign(roll);
1125 headingChangeRate += dt * sign(roll);
1130 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1131 headingError = headingDiff;
1132 if (fabs(headingError) < 1.0) {
1136 if (fabs(speed) > 1.0) {
1137 turn_radius_ft = 0.088362 * speed * speed
1138 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1140 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1141 turn_radius_ft = 1.0;
1143 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1144 double dist_covered_ft = speed * 1.686 * dt;
1145 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1146 hdg += alpha * sign(roll);
1148 while ( hdg > 360.0 ) {
1152 while ( hdg < 0.0) {
1160 void FGAIAircraft::updateBankAngleTarget() {
1161 // adjust target bank angle if heading lock engaged
1163 double bank_sense = 0.0;
1164 double diff = fabs(hdg - tgt_heading);
1166 diff = fabs(diff - 360);
1168 double sum = hdg + diff;
1171 if (fabs(sum - tgt_heading) < 1.0) {
1172 bank_sense = 1.0; // right turn
1174 bank_sense = -1.0; // left turn
1176 if (diff < _performance->maximumBankAngle()) {
1177 tgt_roll = diff * bank_sense;
1179 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1181 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1182 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1183 // The only way to resolve this is to make them slow down.
1189 void FGAIAircraft::updateVerticalSpeedTarget() {
1190 // adjust target Altitude, based on ground elevation when on ground
1194 } else if (alt_lock) {
1195 // find target vertical speed
1197 if (altitude_ft < tgt_altitude_ft) {
1198 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1200 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1203 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1204 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1205 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1206 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1207 //cerr << "Target vs before : " << tgt_vs;
1208 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1209 double min_vs = 100;
1210 if (tgt_altitude_ft < altitude_ft)
1212 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1213 && (fabs(max_vs) < fabs(tgt_vs)))
1216 if (fabs(tgt_vs) < fabs(min_vs))
1218 //cerr << "target vs : after " << tgt_vs << endl;
1225 void FGAIAircraft::updatePitchAngleTarget() {
1226 // if on ground and above vRotate -> initial rotation
1227 if (onGround() && (speed > _performance->vRotate()))
1228 tgt_pitch = 8.0; // some rough B737 value
1230 //TODO pitch angle on approach and landing
1232 // match pitch angle to vertical speed
1233 else if (tgt_vs > 0) {
1234 tgt_pitch = tgt_vs * 0.005;
1236 tgt_pitch = tgt_vs * 0.002;
1240 const string& FGAIAircraft::atGate()
1242 if ((fp->getLeg() < 3) && trafficRef) {
1243 if (fp->getParkingGate()) {
1244 return fp->getParkingGate()->ident();
1248 static const string empty;
1252 void FGAIAircraft::handleATCRequests() {
1253 //TODO implement NullController for having no ATC to save the conditionals
1255 controller->updateAircraftInformation(getID(),
1256 pos.getLatitudeDeg(),
1257 pos.getLongitudeDeg(),
1261 processATC(controller->getInstruction(getID()));
1263 if (towerController) {
1264 towerController->updateAircraftInformation(getID(),
1265 pos.getLatitudeDeg(),
1266 pos.getLongitudeDeg(),
1273 void FGAIAircraft::updateActualState() {
1274 //update current state
1275 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1276 double distance = speed * SG_KT_TO_MPS * dt;
1277 pos = SGGeodesy::direct(pos, hdg, distance);
1281 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1283 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1284 //assertSpeed(speed);
1286 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1288 // adjust altitude (meters) based on current vertical speed (fpm)
1289 altitude_ft += vs / 60.0 * dt;
1290 pos.setElevationFt(altitude_ft);
1292 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1293 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1296 void FGAIAircraft::updateSecondaryTargetValues() {
1297 // derived target state values
1298 updateBankAngleTarget();
1299 updateVerticalSpeedTarget();
1300 updatePitchAngleTarget();
1302 //TODO calculate wind correction angle (tgt_yaw)
1306 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1307 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1308 if (curr->getName() == string("BOD")) {
1309 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1310 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1311 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1313 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1314 double descentTimeNeeded = verticalDistance / descentRate;
1315 double distanceCovered = descentSpeed * descentTimeNeeded;
1317 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1318 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1319 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1320 cerr << "Descent rate : " << descentRate << endl;
1321 cerr << "Descent speed : " << descentSpeed << endl;
1322 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1323 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1324 cerr << "DistanceCovered : " << distanceCovered << endl;
1326 //cerr << "Distance = " << distance << endl;
1327 distance = distanceCovered;
1328 if (dist < distanceCovered) {
1329 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1341 void FGAIAircraft::resetPositionFromFlightPlan()
1343 // the one behind you
1344 FGAIWaypoint* prev = 0;
1346 FGAIWaypoint* curr = 0;
1348 FGAIWaypoint* next = 0;
1350 prev = fp->getPreviousWaypoint();
1351 curr = fp->getCurrentWaypoint();
1352 next = fp->getNextWaypoint();
1354 setLatitude(prev->getLatitude());
1355 setLongitude(prev->getLongitude());
1356 double tgt_heading = fp->getBearing(curr, next);
1357 setHeading(tgt_heading);
1358 setAltitude(prev->getAltitude());
1359 setSpeed(prev->getSpeed());
1362 double FGAIAircraft::getBearing(double crse)
1364 double hdgDiff = fabs(hdg-crse);
1366 hdgDiff = fabs(hdgDiff - 360);
1370 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1371 FGAIWaypoint* curr = 0;
1372 curr = fp->getCurrentWaypoint();
1374 // don't recalculate tracklength unless the start/stop waypoint has changed
1376 ((curr->getName() != trackCache.startWptName)||
1377 (wptName != trackCache.finalWptName)))
1379 trackCache.remainingLength = fp->checkTrackLength(wptName);
1380 trackCache.startWptName = curr->getName();
1381 trackCache.finalWptName = wptName;
1383 double tracklength = trackCache.remainingLength;
1384 if (tracklength > 0.1) {
1385 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1389 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1390 time_t arrivalTime = fp->getArrivalTime();
1392 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1393 time_t secondsToGo = arrivalTime - now;
1394 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1395 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1397 return (ete - secondsToGo); // Positive when we're too slow...
1400 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1402 double delta = target - cur;
1403 double maxDelta = maxDeltaSec * dt;
1405 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1406 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1409 // drive various properties in a semi-realistic fashion.
1410 void FGAIAircraft::updateModelProperties(double dt)
1416 SGPropertyNode* gear = props->getChild("gear", 0, true);
1417 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1418 if (!gear->hasValue("gear/position-norm")) {
1419 gear->setDoubleValue("gear/position-norm", targetGearPos);
1422 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1423 if (gearPosNorm != targetGearPos) {
1424 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1425 if (gearPosNorm < 0.001) {
1427 } else if (gearPosNorm > 0.999) {
1431 for (int i=0; i<6; ++i) {
1432 SGPropertyNode* g = gear->getChild("gear", i, true);
1433 g->setDoubleValue("position-norm", gearPosNorm);
1434 } // of gear setting loop
1435 } // of gear in-transit
1437 // double flapPosNorm = props->getDoubleValue();