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)
45 #include "AIAircraft.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
50 //#include <Airports/trafficcontroller.hxx>
52 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
53 /* HOT must be disabled for AI Aircraft,
54 * otherwise traffic detection isn't working as expected.*/
55 FGAIBase(otAircraft, false)
59 groundOffset = trafficRef->getGroundOffset();
60 setCallSign(trafficRef->getCallSign());
76 groundTargetSpeed = 0;
78 // set heading and altitude locks
82 headingChangeRate = 0.0;
88 needsTaxiClearance = false;
89 _needsGroundElevation = true;
91 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
97 FGAIAircraft::~FGAIAircraft() {
100 controller->signOff(getID());
104 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
108 FGAIBase::readFromScenario(scFileNode);
110 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
111 setFlightPlan(scFileNode->getStringValue("flightplan"),
112 scFileNode->getBoolValue("repeat", false));
113 setCallSign(scFileNode->getStringValue("callsign"));
117 void FGAIAircraft::bind() {
120 tie("controls/gear/gear-down",
121 SGRawValueMethods<FGAIAircraft,bool>(*this,
122 &FGAIAircraft::_getGearDown));
123 tie("transponder-id",
124 SGRawValueMethods<FGAIAircraft,const char*>(*this,
125 &FGAIAircraft::_getTransponderCode));
128 void FGAIAircraft::update(double dt) {
129 FGAIBase::update(dt);
134 void FGAIAircraft::setPerformance(const std::string& acclass) {
135 static PerformanceDB perfdb; //TODO make it a global service
136 setPerformance(perfdb.getDataFor(acclass));
140 void FGAIAircraft::setPerformance(PerformanceData *ps) {
145 void FGAIAircraft::Run(double dt) {
146 FGAIAircraft::dt = dt;
148 bool outOfSight = false,
149 flightplanActive = true;
150 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
155 if (!flightplanActive) {
156 groundTargetSpeed = 0;
159 handleATCRequests(); // ATC also has a word to say
160 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
162 // We currently have one situation in which an AIAircraft object is used that is not attached to the
163 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
164 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
167 UpdateRadar(manager);
171 void FGAIAircraft::checkVisibility()
173 double visibility_meters = fgGetDouble("/environment/visibility-m");
174 invisible = (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters);
179 void FGAIAircraft::AccelTo(double speed) {
181 //assertSpeed(speed);
183 _needsGroundElevation = true;
187 void FGAIAircraft::PitchTo(double angle) {
193 void FGAIAircraft::RollTo(double angle) {
199 void FGAIAircraft::YawTo(double angle) {
204 void FGAIAircraft::ClimbTo(double alt_ft ) {
205 tgt_altitude_ft = alt_ft;
210 void FGAIAircraft::TurnTo(double heading) {
211 tgt_heading = heading;
216 double FGAIAircraft::sign(double x) {
224 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
225 if (!flightplan.empty()) {
226 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
227 fp->setRepeat(repeat);
233 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
239 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
241 // the one behind you
242 FGAIWaypoint* prev = 0;
244 FGAIWaypoint* curr = 0;
246 FGAIWaypoint* next = 0;
248 prev = fp->getPreviousWaypoint();
249 curr = fp->getCurrentWaypoint();
250 next = fp->getNextWaypoint();
254 ///////////////////////////////////////////////////////////////////////////
255 // Initialize the flightplan
256 //////////////////////////////////////////////////////////////////////////
258 handleFirstWaypoint();
260 } // end of initialization
261 if (! fpExecutable(now))
265 double distanceToDescent;
266 if(reachedEndOfCruise(distanceToDescent)) {
267 if (!loadNextLeg(distanceToDescent)) {
271 prev = fp->getPreviousWaypoint();
272 curr = fp->getCurrentWaypoint();
273 next = fp->getNextWaypoint();
281 if (! leadPointReached(curr)) {
282 controlHeading(curr);
283 controlSpeed(curr, next);
287 cerr << getCallSign()
288 << ": verifying lead distance to waypoint : "
289 << fp->getCurrentWaypoint()->name << " "
290 << fp->getLeadDistance() << ". Distance to go "
291 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
292 << ". Target speed = "
294 << ". Current speed = "
296 << ". Minimum Bearing " << minBearing
300 if (curr->isFinished()) //end of the flight plan
310 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
311 tgt_heading = fp->getBearing(curr, next);
315 //TODO let the fp handle this (loading of next leg)
316 fp->IncrementWaypoint( trafficRef != 0 );
317 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
318 if (!loadNextLeg()) {
323 prev = fp->getPreviousWaypoint();
324 curr = fp->getCurrentWaypoint();
325 next = fp->getNextWaypoint();
327 // Now that we have incremented the waypoints, excute some traffic manager specific code
329 //TODO isn't this best executed right at the beginning?
330 if (! aiTrafficVisible()) {
335 if (! handleAirportEndPoints(prev, now)) {
340 announcePositionToController();
345 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
349 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
351 tgt_altitude_ft = prev->getAltitude();
352 if (curr->getCrossat() > -1000.0) {
354 // Distance to go in meters
355 double vert_dist_ft = curr->getCrossat() - altitude_ft;
356 double err_dist = prev->getCrossat() - altitude_ft;
357 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
358 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
361 tgt_altitude_ft = curr->getCrossat();
366 AccelTo(prev->getSpeed());
367 hdg_lock = alt_lock = true;
368 no_roll = prev->getOn_ground();
372 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
374 // err is negative when we passed too high
375 double vert_m = vert_ft * SG_FEET_TO_METER;
376 //double err_m = err * SG_FEET_TO_METER;
377 //double angle = atan2(vert_m, dist_m);
378 double speedMs = (speed * SG_NM_TO_METER) / 3600;
379 //double vs = cos(angle) * speedMs; // Now in m/s
381 //cerr << "Error term = " << err_m << endl;
383 vs = ((vert_m) / dist_m) * speedMs;
385 // Convert to feet per minute
386 vs *= (SG_METER_TO_FEET * 60);
387 //if (getCallSign() == "LUFTHANSA2002")
388 //if (fabs(vs) > 100000) {
389 // if (getCallSign() == "LUFTHANSA2057") {
390 // 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;
391 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
392 // // / 6076.0 / speed*60.0);
398 void FGAIAircraft::assertSpeed(double speed)
400 if ((speed < -50) || (speed > 1000)) {
401 cerr << getCallSign() << " "
402 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
403 << "Departure airport " << trafficRef->getDepartureAirport() << " "
404 << "Leg " << fp->getLeg() << " "
405 << "target_speed << " << tgt_speed << " "
406 << "speedFraction << " << speedFraction << " "
407 << "Currecnt speed << " << speed << " "
415 void FGAIAircraft::checkTcas(void)
417 if (props->getIntValue("tcas/threat-level",0)==3)
419 int RASense = props->getIntValue("tcas/ra-sense",0);
420 if ((RASense>0)&&(tgt_vs<4000))
426 // downward RA: descend!
427 if (altitude_ft < 1000)
429 // too low: level off
442 void FGAIAircraft::initializeFlightPlan() {
446 bool FGAIAircraft::_getGearDown() const {
447 return _performance->gearExtensible(this);
451 const char * FGAIAircraft::_getTransponderCode() const {
452 return transponderCode.c_str();
455 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
456 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
458 bool FGAIAircraft::loadNextLeg(double distance) {
461 if ((leg = fp->getLeg()) == 9) {
462 if (!trafficRef->next()) {
465 setCallSign(trafficRef->getCallSign());
470 FGAirport *dep = trafficRef->getDepartureAirport();
471 FGAirport *arr = trafficRef->getArrivalAirport();
476 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
483 trafficRef->getSpeed(),
487 trafficRef->getRadius(),
488 trafficRef->getFlightType(),
492 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
498 // Note: This code is copied from David Luff's AILocalTraffic
499 // Warning - ground elev determination is CPU intensive
500 // Either this function or the logic of how often it is called
501 // will almost certainly change.
503 void FGAIAircraft::getGroundElev(double dt) {
506 if (!needGroundElevation())
508 // Update minimally every three secs, but add some randomness
509 // to prevent all AI objects doing this in synchrony
510 if (dt_elev_count < (3.0) + (rand() % 10))
515 // Only do the proper hitlist stuff if we are within visible range of the viewer.
517 double visibility_meters = fgGetDouble("/environment/visibility-m");
518 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
522 double range = 500.0;
523 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
526 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
528 tgt_altitude_ft = alt * SG_METER_TO_FEET;
531 // aircraft is stationary and we obtained altitude for this spot - we're done.
532 _needsGroundElevation = false;
540 void FGAIAircraft::doGroundAltitude() {
541 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
544 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
546 altitude_ft = (tgt_altitude_ft + groundOffset);
548 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
554 void FGAIAircraft::announcePositionToController() {
556 int leg = fp->getLeg();
558 // Note that leg has been incremented after creating the current leg, so we should use
559 // leg numbers here that are one higher than the number that is used to create the leg
560 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
561 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
562 // the original leg numbers here!
564 case 1: // Startup and Push back
565 if (trafficRef->getDepartureAirport()->getDynamics())
566 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
568 case 2: // Taxiing to runway
569 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
570 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
572 case 3: //Take off tower controller
573 if (trafficRef->getDepartureAirport()->getDynamics()) {
574 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
577 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
581 if (trafficRef->getDepartureAirport()->getDynamics()) {
582 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
585 case 8: // Taxiing for parking
586 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
587 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
594 if ((controller != prevController) && (prevController != 0)) {
595 prevController->signOff(getID());
597 prevController = controller;
599 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
600 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
601 trafficRef->getRadius(), leg, this);
606 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
607 if (!takeOffStatus) {
608 int leg = fp->getLeg();
610 if (trafficRef->getDepartureAirport()->getDynamics()) {
611 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
613 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
615 if (towerController) {
616 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
617 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
618 trafficRef->getRadius(), leg, this);
619 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
623 takeOffStatus = state;
626 // Process ATC instructions and report back
628 void FGAIAircraft::processATC(FGATCInstruction instruction) {
629 if (instruction.getCheckForCircularWait()) {
630 // This is not exactly an elegant solution,
631 // but at least it gives me a chance to check
632 // if circular waits are resolved.
633 // For now, just take the offending aircraft
636 // a more proper way should be - of course - to
637 // let an offending aircraft take an evasive action
638 // for instance taxi back a little bit.
640 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
641 if (instruction.getHoldPattern ()) {}
644 if (instruction.getHoldPosition ()) {
652 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
655 // Change speed Instruction. This can only be excecuted when there is no
656 // Hold position instruction.
657 if (instruction.getChangeSpeed ()) {
659 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
660 AccelTo(instruction.getSpeed());
662 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
665 if (instruction.getChangeHeading ()) {
667 TurnTo(instruction.getHeading());
673 if (instruction.getChangeAltitude()) {}
678 void FGAIAircraft::handleFirstWaypoint() {
679 bool eraseWaypoints; //TODO YAGNI
682 eraseWaypoints = true;
684 eraseWaypoints = false;
687 FGAIWaypoint* prev = 0; // the one behind you
688 FGAIWaypoint* curr = 0; // the one ahead
689 FGAIWaypoint* next = 0;// the next plus 1
693 //TODO fp should handle this
694 fp->IncrementWaypoint(eraseWaypoints);
695 if (!(fp->getNextWaypoint()) && trafficRef)
696 if (!loadNextLeg()) {
701 prev = fp->getPreviousWaypoint(); //first waypoint
702 curr = fp->getCurrentWaypoint(); //second waypoint
703 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
705 setLatitude(prev->getLatitude());
706 setLongitude(prev->getLongitude());
707 setSpeed(prev->getSpeed());
708 setAltitude(prev->getAltitude());
710 if (prev->getSpeed() > 0.0)
711 setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
713 setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
715 // If next doesn't exist, as in incrementally created flightplans for
716 // AI/Trafficmanager created plans,
717 // Make sure lead distance is initialized otherwise
719 fp->setLeadDistance(speed, hdg, curr, next);
721 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
724 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
725 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
726 // / 6076.0 / prev->getSpeed()*60.0);
727 double vert_dist_ft = curr->getCrossat() - altitude_ft;
728 double err_dist = prev->getCrossat() - altitude_ft;
729 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
730 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
732 tgt_altitude_ft = curr->getCrossat();
735 tgt_altitude_ft = prev->getAltitude();
737 alt_lock = hdg_lock = true;
738 no_roll = prev->getOn_ground();
740 Transform(); // make sure aip is initialized.
741 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
743 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
745 // Make sure to announce the aircraft's position
746 announcePositionToController();
752 * Check Execution time (currently once every 100 ms)
753 * Add a bit of randomization to prevent the execution of all flight plans
754 * in synchrony, which can add significant periodic framerate flutter.
759 bool FGAIAircraft::fpExecutable(time_t now) {
760 double rand_exec_time = (rand() % 100) / 100;
761 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
766 * Check to see if we've reached the lead point for our next turn
771 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
772 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
774 //cerr << "2" << endl;
775 double lead_dist = fp->getLeadDistance();
776 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
777 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
778 tgt_speed = -(dist_to_go / 10.0);
779 if (tgt_speed > -0.5) {
782 //assertSpeed(tgt_speed);
783 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
784 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
787 if (lead_dist < fabs(2*speed)) {
788 //don't skip over the waypoint
789 lead_dist = fabs(2*speed);
790 //cerr << "Extending lead distance to " << lead_dist << endl;
793 //prev_dist_to_go = dist_to_go;
794 //if (dist_to_go < lead_dist)
795 // cerr << trafficRef->getCallSign() << " Distance : "
796 // << dist_to_go << ": Lead distance "
797 // << lead_dist << " " << curr->name
798 // << " Ground target speed " << groundTargetSpeed << endl;
800 // don't do bearing calculations for ground traffic
801 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
802 if (bearing < minBearing) {
803 minBearing = bearing;
804 if (minBearing < 10) {
807 if ((minBearing < 360.0) && (minBearing > 10.0)) {
808 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
814 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
815 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
816 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
817 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
820 if ((dist_to_go < lead_dist) ||
821 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
824 prev_dist_to_go = HUGE_VAL;
827 prev_dist_to_go = dist_to_go;
833 bool FGAIAircraft::aiTrafficVisible()
835 SGVec3d cartPos = SGVec3d::fromGeod(pos);
836 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
837 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
838 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
843 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
844 * in the case of an arrival.
850 //TODO the trafficRef is the right place for the method
851 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
852 // prepare routing from one airport to another
853 FGAirport * dep = trafficRef->getDepartureAirport();
854 FGAirport * arr = trafficRef->getArrivalAirport();
859 // This waypoint marks the fact that the aircraft has passed the initial taxi
860 // departure waypoint, so it can release the parking.
861 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
862 //cerr << "Passing waypoint : " << prev->getName() << endl;
863 if (prev->contains("PushBackPoint")) {
864 dep->getDynamics()->releaseParking(fp->getGate());
866 //setTaxiClearanceRequest(true);
868 if (prev->contains("legend")) {
871 if (prev->contains(string("DepartureHold"))) {
872 //cerr << "Passing point DepartureHold" << endl;
873 scheduleForATCTowerDepartureControl(1);
875 if (prev->contains(string("Accel"))) {
878 //if (prev->contains(string("landing"))) {
879 // if (speed < _performance->vTaxi() * 2) {
880 // fp->shortenToFirst(2, "legend");
883 //if (prev->contains(string("final"))) {
885 // cerr << getCallSign() << " "
886 // << fp->getPreviousWaypoint()->getName()
887 // << ". Alt = " << altitude_ft
889 // << " horizontal speed " << speed
890 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
891 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
892 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
894 // This is the last taxi waypoint, and marks the the end of the flight plan
895 // so, the schedule should update and wait for the next departure time.
896 if (prev->contains("END")) {
897 time_t nextDeparture = trafficRef->getDepartureTime();
898 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
899 if (nextDeparture < (now+1200)) {
900 nextDeparture = now + 1200;
902 fp->setTime(nextDeparture);
910 * Check difference between target bearing and current heading and correct if necessary.
914 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
915 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
916 //cerr << "Bearing = " << calc_bearing << endl;
919 if (calc_bearing > 360)
923 if (finite(calc_bearing)) {
924 double hdg_error = calc_bearing - tgt_heading;
925 if (fabs(hdg_error) > 0.01) {
926 TurnTo( calc_bearing );
930 cerr << "calc_bearing is not a finite number : "
932 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
933 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
934 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
941 * Update the lead distance calculation if speed has changed sufficiently
942 * to prevent spinning (hopefully);
947 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
948 double speed_diff = speed - prevSpeed;
950 if (fabs(speed_diff) > 10) {
952 //assertSpeed(speed);
954 fp->setLeadDistance(speed, tgt_heading, curr, next);
961 * Update target values (heading, alt, speed) depending on flight plan or control properties
963 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
964 if (fp) // AI object has a flightplan
966 //TODO make this a function of AIBase
967 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
968 //cerr << "UpateTArgetValues() " << endl;
969 ProcessFlightPlan(dt, now);
971 // Do execute Ground elev for inactive aircraft, so they
972 // Are repositioned to the correct ground altitude when the user flies within visibility range.
973 // In addition, check whether we are out of user range, so this aircraft
976 Transform(); // make sure aip is initialized.
980 pos.setElevationFt(altitude_ft);
983 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
984 aiOutOfSight = !aiTrafficVisible();
987 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
992 timeElapsed = now - fp->getStartTime();
993 flightplanActive = fp->isActive(now);
995 // no flight plan, update target heading, speed, and altitude
996 // from control properties. These default to the initial
997 // settings in the config file, but can be changed "on the
999 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
1000 if ( lat_mode == "roll" ) {
1002 = props->getDoubleValue("controls/flight/target-roll" );
1006 = props->getDoubleValue("controls/flight/target-hdg" );
1011 = props->getStringValue("controls/flight/longitude-mode");
1012 if ( lon_mode == "alt" ) {
1013 double alt = props->getDoubleValue("controls/flight/target-alt" );
1017 = props->getDoubleValue("controls/flight/target-pitch" );
1021 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1025 void FGAIAircraft::updatePosition() {
1026 // convert speed to degrees per second
1027 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
1028 * speed * 1.686 / ft_per_deg_lat;
1029 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
1030 * speed * 1.686 / ft_per_deg_lon;
1033 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
1034 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
1038 void FGAIAircraft::updateHeading() {
1039 // adjust heading based on current bank angle
1044 // double turnConstant;
1046 // turnConstant = 0.0088362;
1048 // turnConstant = 0.088362;
1049 // If on ground, calculate heading change directly
1051 double headingDiff = fabs(hdg-tgt_heading);
1052 // double bank_sense = 0.0;
1054 double diff = fabs(hdg - tgt_heading);
1056 diff = fabs(diff - 360);
1058 double sum = hdg + diff;
1061 if (fabs(sum - tgt_heading) < 1.0) {
1062 bank_sense = 1.0; // right turn
1064 bank_sense = -1.0; // left turn
1066 if (headingDiff > 180)
1067 headingDiff = fabs(headingDiff - 360);
1068 double sum = hdg + headingDiff;
1071 if (fabs(sum - tgt_heading) > 0.0001) {
1072 // bank_sense = -1.0;
1074 // bank_sense = 1.0;
1077 // cerr << trafficRef->getCallSign() << " Heading "
1078 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1079 //if (headingDiff > 60) {
1080 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1081 //assertSpeed(groundTargetSpeed);
1082 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1084 // groundTargetSpeed = tgt_speed;
1086 if (sign(groundTargetSpeed) != sign(tgt_speed))
1087 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1088 //assertSpeed(groundTargetSpeed);
1089 // 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.
1091 if (headingDiff > 30.0) {
1092 // invert if pushed backward
1093 headingChangeRate += 10.0 * dt * sign(roll);
1095 // Clamp the maximum steering rate to 30 degrees per second,
1096 // But only do this when the heading error is decreasing.
1097 if ((headingDiff < headingError)) {
1098 if (headingChangeRate > 30)
1099 headingChangeRate = 30;
1100 else if (headingChangeRate < -30)
1101 headingChangeRate = -30;
1105 if (fabs(headingChangeRate) > headingDiff)
1106 headingChangeRate = headingDiff*sign(roll);
1108 headingChangeRate += dt * sign(roll);
1113 //cerr << trafficRef->getCallSign() << " Heading "
1114 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1115 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1116 headingError = headingDiff;
1117 if (fabs(headingError) < 1.0) {
1121 if (fabs(speed) > 1.0) {
1122 turn_radius_ft = 0.088362 * speed * speed
1123 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1125 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1126 turn_radius_ft = 1.0;
1128 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1129 double dist_covered_ft = speed * 1.686 * dt;
1130 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1131 hdg += alpha * sign(roll);
1133 while ( hdg > 360.0 ) {
1137 while ( hdg < 0.0) {
1145 void FGAIAircraft::updateBankAngleTarget() {
1146 // adjust target bank angle if heading lock engaged
1148 double bank_sense = 0.0;
1149 double diff = fabs(hdg - tgt_heading);
1151 diff = fabs(diff - 360);
1153 double sum = hdg + diff;
1156 if (fabs(sum - tgt_heading) < 1.0) {
1157 bank_sense = 1.0; // right turn
1159 bank_sense = -1.0; // left turn
1161 if (diff < _performance->maximumBankAngle()) {
1162 tgt_roll = diff * bank_sense;
1164 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1166 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1167 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1168 // The only way to resolve this is to make them slow down.
1174 void FGAIAircraft::updateVerticalSpeedTarget() {
1175 // adjust target Altitude, based on ground elevation when on ground
1179 } else if (alt_lock) {
1180 // find target vertical speed
1182 if (altitude_ft < tgt_altitude_ft) {
1183 tgt_vs = tgt_altitude_ft - altitude_ft;
1184 if (tgt_vs > _performance->climbRate())
1185 tgt_vs = _performance->climbRate();
1187 tgt_vs = tgt_altitude_ft - altitude_ft;
1188 if (tgt_vs < (-_performance->descentRate()))
1189 tgt_vs = -_performance->descentRate();
1192 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1193 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1194 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1195 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1196 //cerr << "Target vs before : " << tgt_vs;
1197 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1198 double min_vs = 100;
1199 if (tgt_altitude_ft < altitude_ft)
1201 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1202 && (fabs(max_vs) < fabs(tgt_vs)))
1205 if (fabs(tgt_vs) < fabs(min_vs))
1207 //cerr << "target vs : after " << tgt_vs << endl;
1214 void FGAIAircraft::updatePitchAngleTarget() {
1215 // if on ground and above vRotate -> initial rotation
1216 if (onGround() && (speed > _performance->vRotate()))
1217 tgt_pitch = 8.0; // some rough B737 value
1219 //TODO pitch angle on approach and landing
1221 // match pitch angle to vertical speed
1222 else if (tgt_vs > 0) {
1223 tgt_pitch = tgt_vs * 0.005;
1225 tgt_pitch = tgt_vs * 0.002;
1229 string FGAIAircraft::atGate() {
1231 if (fp->getLeg() < 3) {
1233 if (fp->getGate() > 0) {
1235 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1236 tmp = park->getName();
1243 void FGAIAircraft::handleATCRequests() {
1244 //TODO implement NullController for having no ATC to save the conditionals
1246 controller->updateAircraftInformation(getID(),
1247 pos.getLatitudeDeg(),
1248 pos.getLongitudeDeg(),
1252 processATC(controller->getInstruction(getID()));
1254 if (towerController) {
1255 towerController->updateAircraftInformation(getID(),
1256 pos.getLatitudeDeg(),
1257 pos.getLongitudeDeg(),
1264 void FGAIAircraft::updateActualState() {
1265 //update current state
1266 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1270 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1272 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1273 //assertSpeed(speed);
1275 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1277 // adjust altitude (meters) based on current vertical speed (fpm)
1278 altitude_ft += vs / 60.0 * dt;
1279 pos.setElevationFt(altitude_ft);
1281 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1282 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1285 void FGAIAircraft::updateSecondaryTargetValues() {
1286 // derived target state values
1287 updateBankAngleTarget();
1288 updateVerticalSpeedTarget();
1289 updatePitchAngleTarget();
1291 //TODO calculate wind correction angle (tgt_yaw)
1295 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1296 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1297 if (curr->getName() == string("BOD")) {
1298 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1299 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1300 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1302 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1303 double descentTimeNeeded = verticalDistance / descentRate;
1304 double distanceCovered = descentSpeed * descentTimeNeeded;
1306 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1307 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1308 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1309 cerr << "Descent rate : " << descentRate << endl;
1310 cerr << "Descent speed : " << descentSpeed << endl;
1311 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1312 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1313 cerr << "DistanceCovered : " << distanceCovered << endl;
1315 //cerr << "Distance = " << distance << endl;
1316 distance = distanceCovered;
1317 if (dist < distanceCovered) {
1318 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1330 void FGAIAircraft::resetPositionFromFlightPlan()
1332 // the one behind you
1333 FGAIWaypoint* prev = 0;
1335 FGAIWaypoint* curr = 0;
1337 FGAIWaypoint* next = 0;
1339 prev = fp->getPreviousWaypoint();
1340 curr = fp->getCurrentWaypoint();
1341 next = fp->getNextWaypoint();
1343 setLatitude(prev->getLatitude());
1344 setLongitude(prev->getLongitude());
1345 double tgt_heading = fp->getBearing(curr, next);
1346 setHeading(tgt_heading);
1347 setAltitude(prev->getAltitude());
1348 setSpeed(prev->getSpeed());
1351 double FGAIAircraft::getBearing(double crse)
1353 double hdgDiff = fabs(hdg-crse);
1355 hdgDiff = fabs(hdgDiff - 360);
1359 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1360 FGAIWaypoint* curr = 0;
1361 curr = fp->getCurrentWaypoint();
1363 double tracklength = fp->checkTrackLength(wptName);
1364 if (tracklength > 0.1) {
1365 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1369 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1370 time_t arrivalTime = fp->getArrivalTime();
1372 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1373 time_t secondsToGo = arrivalTime - now;
1374 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1375 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1377 return (ete - secondsToGo); // Positive when we're too slow...