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 <simgear/route/waypoint.hxx>
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <Main/viewer.hxx>
29 #include <Scenery/scenery.hxx>
30 #include <Scenery/tilemgr.hxx>
31 #include <Airports/dynamics.hxx>
32 #include <Airports/simple.hxx>
40 # define finite _finite
41 #elif defined(__sun) || defined(sgi)
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
52 //#include <Airports/trafficcontroller.hxx>
54 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
55 /* HOT must be disabled for AI Aircraft,
56 * otherwise traffic detection isn't working as expected.*/
57 FGAIBase(otAircraft, false)
61 groundOffset = trafficRef->getGroundOffset();
62 setCallSign(trafficRef->getCallSign());
78 groundTargetSpeed = 0;
80 // set heading and altitude locks
84 headingChangeRate = 0.0;
90 needsTaxiClearance = false;
91 _needsGroundElevation = true;
93 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
99 FGAIAircraft::~FGAIAircraft() {
102 controller->signOff(getID());
106 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
110 FGAIBase::readFromScenario(scFileNode);
112 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
113 setFlightPlan(scFileNode->getStringValue("flightplan"),
114 scFileNode->getBoolValue("repeat", false));
115 setCallSign(scFileNode->getStringValue("callsign"));
119 void FGAIAircraft::bind() {
122 props->tie("controls/gear/gear-down",
123 SGRawValueMethods<FGAIAircraft,bool>(*this,
124 &FGAIAircraft::_getGearDown));
125 props->tie("transponder-id",
126 SGRawValueMethods<FGAIAircraft,const char*>(*this,
127 &FGAIAircraft::_getTransponderCode));
131 void FGAIAircraft::unbind() {
134 props->untie("controls/gear/gear-down");
135 props->untie("transponder-id");
139 void FGAIAircraft::update(double dt) {
140 FGAIBase::update(dt);
145 void FGAIAircraft::setPerformance(const std::string& acclass) {
146 static PerformanceDB perfdb; //TODO make it a global service
147 setPerformance(perfdb.getDataFor(acclass));
151 void FGAIAircraft::setPerformance(PerformanceData *ps) {
156 void FGAIAircraft::Run(double dt) {
157 FGAIAircraft::dt = dt;
159 bool outOfSight = false,
160 flightplanActive = true;
161 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
166 if (!flightplanActive) {
167 groundTargetSpeed = 0;
170 handleATCRequests(); // ATC also has a word to say
171 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
173 // We currently have one situation in which an AIAircraft object is used that is not attached to the
174 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
175 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
178 UpdateRadar(manager);
182 void FGAIAircraft::checkVisibility()
184 double visibility_meters = fgGetDouble("/environment/visibility-m");
185 FGViewer* vw = globals->get_current_view();
186 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
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) {
237 if (!flightplan.empty()) {
238 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
239 fp->setRepeat(repeat);
245 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
251 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
253 // the one behind you
254 FGAIWaypoint* prev = 0;
256 FGAIWaypoint* curr = 0;
258 FGAIWaypoint* next = 0;
260 prev = fp->getPreviousWaypoint();
261 curr = fp->getCurrentWaypoint();
262 next = fp->getNextWaypoint();
266 ///////////////////////////////////////////////////////////////////////////
267 // Initialize the flightplan
268 //////////////////////////////////////////////////////////////////////////
270 handleFirstWaypoint();
272 } // end of initialization
273 if (! fpExecutable(now))
277 double distanceToDescent;
278 if(reachedEndOfCruise(distanceToDescent)) {
279 if (!loadNextLeg(distanceToDescent)) {
283 prev = fp->getPreviousWaypoint();
284 curr = fp->getCurrentWaypoint();
285 next = fp->getNextWaypoint();
287 if (! leadPointReached(curr)) {
288 controlHeading(curr);
289 controlSpeed(curr, next);
293 cerr << getCallSign()
294 << ": verifying lead distance to waypoint : "
295 << fp->getCurrentWaypoint()->name << " "
296 << fp->getLeadDistance() << ". Distance to go "
297 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
298 << ". Target speed = "
300 << ". Current speed = "
302 << ". Minimum Bearing " << minBearing
306 if (curr->isFinished()) //end of the flight plan
316 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
317 tgt_heading = fp->getBearing(curr, next);
321 //TODO let the fp handle this (loading of next leg)
322 fp->IncrementWaypoint( trafficRef != 0 );
323 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
324 if (!loadNextLeg()) {
329 prev = fp->getPreviousWaypoint();
330 curr = fp->getCurrentWaypoint();
331 next = fp->getNextWaypoint();
333 // Now that we have incremented the waypoints, excute some traffic manager specific code
335 //TODO isn't this best executed right at the beginning?
336 if (! aiTrafficVisible()) {
341 if (! handleAirportEndPoints(prev, now)) {
346 announcePositionToController();
351 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
355 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
357 tgt_altitude_ft = prev->getAltitude();
358 if (curr->getCrossat() > -1000.0) {
360 // Distance to go in meters
361 double vert_dist_ft = curr->getCrossat() - altitude_ft;
362 double err_dist = prev->getCrossat() - altitude_ft;
363 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
364 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
367 tgt_altitude_ft = curr->getCrossat();
372 AccelTo(prev->getSpeed());
373 hdg_lock = alt_lock = true;
374 no_roll = prev->getOn_ground();
378 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
380 // err is negative when we passed too high
381 double vert_m = vert_ft * SG_FEET_TO_METER;
382 //double err_m = err * SG_FEET_TO_METER;
383 //double angle = atan2(vert_m, dist_m);
384 double speedMs = (speed * SG_NM_TO_METER) / 3600;
385 //double vs = cos(angle) * speedMs; // Now in m/s
387 //cerr << "Error term = " << err_m << endl;
389 vs = ((vert_m) / dist_m) * speedMs;
391 // Convert to feet per minute
392 vs *= (SG_METER_TO_FEET * 60);
393 //if (getCallSign() == "LUFTHANSA2002")
394 //if (fabs(vs) > 100000) {
395 // if (getCallSign() == "LUFTHANSA2057") {
396 // 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;
397 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
398 // // / 6076.0 / speed*60.0);
404 void FGAIAircraft::assertSpeed(double speed)
406 if ((speed < -50) || (speed > 1000)) {
407 cerr << getCallSign() << " "
408 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
409 << "Departure airport " << trafficRef->getDepartureAirport() << " "
410 << "Leg " << fp->getLeg() << " "
411 << "target_speed << " << tgt_speed << " "
412 << "speedFraction << " << speedFraction << " "
413 << "Currecnt speed << " << speed << " "
421 void FGAIAircraft::checkTcas(void)
423 if (props->getIntValue("tcas/threat-level",0)==3)
425 int RASense = props->getIntValue("tcas/ra-sense",0);
426 if ((RASense>0)&&(tgt_vs<4000))
432 // downward RA: descend!
433 if (altitude_ft < 1000)
435 // too low: level off
448 void FGAIAircraft::initializeFlightPlan() {
452 bool FGAIAircraft::_getGearDown() const {
453 return _performance->gearExtensible(this);
457 const char * FGAIAircraft::_getTransponderCode() const {
458 return transponderCode.c_str();
461 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
462 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
464 bool FGAIAircraft::loadNextLeg(double distance) {
467 if ((leg = fp->getLeg()) == 9) {
468 if (!trafficRef->next()) {
471 setCallSign(trafficRef->getCallSign());
476 FGAirport *dep = trafficRef->getDepartureAirport();
477 FGAirport *arr = trafficRef->getArrivalAirport();
482 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
489 trafficRef->getSpeed(),
493 trafficRef->getRadius(),
494 trafficRef->getFlightType(),
498 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
504 // Note: This code is copied from David Luff's AILocalTraffic
505 // Warning - ground elev determination is CPU intensive
506 // Either this function or the logic of how often it is called
507 // will almost certainly change.
509 void FGAIAircraft::getGroundElev(double dt) {
512 if (!needGroundElevation())
514 // Update minimally every three secs, but add some randomness
515 // to prevent all AI objects doing this in synchrony
516 if (dt_elev_count < (3.0) + (rand() % 10))
521 // Only do the proper hitlist stuff if we are within visible range of the viewer.
523 double visibility_meters = fgGetDouble("/environment/visibility-m");
524 FGViewer* vw = globals->get_current_view();
526 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
530 double range = 500.0;
531 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
534 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
536 tgt_altitude_ft = alt * SG_METER_TO_FEET;
539 // aircraft is stationary and we obtained altitude for this spot - we're done.
540 _needsGroundElevation = false;
548 void FGAIAircraft::doGroundAltitude() {
549 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
552 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
554 altitude_ft = (tgt_altitude_ft + groundOffset);
556 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
562 void FGAIAircraft::announcePositionToController() {
564 int leg = fp->getLeg();
566 // Note that leg has been incremented after creating the current leg, so we should use
567 // leg numbers here that are one higher than the number that is used to create the leg
568 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
569 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
570 // the original leg numbers here!
572 case 1: // Startup and Push back
573 if (trafficRef->getDepartureAirport()->getDynamics())
574 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
576 case 2: // Taxiing to runway
577 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
578 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
580 case 3: //Take off tower controller
581 if (trafficRef->getDepartureAirport()->getDynamics()) {
582 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
585 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
589 if (trafficRef->getDepartureAirport()->getDynamics()) {
590 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
593 case 8: // Taxiing for parking
594 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
595 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
602 if ((controller != prevController) && (prevController != 0)) {
603 prevController->signOff(getID());
605 prevController = controller;
607 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
608 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
609 trafficRef->getRadius(), leg, this);
614 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
615 if (!takeOffStatus) {
616 int leg = fp->getLeg();
618 if (trafficRef->getDepartureAirport()->getDynamics()) {
619 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
621 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
623 if (towerController) {
624 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
625 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
626 trafficRef->getRadius(), leg, this);
627 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
631 takeOffStatus = state;
634 // Process ATC instructions and report back
636 void FGAIAircraft::processATC(FGATCInstruction instruction) {
637 if (instruction.getCheckForCircularWait()) {
638 // This is not exactly an elegant solution,
639 // but at least it gives me a chance to check
640 // if circular waits are resolved.
641 // For now, just take the offending aircraft
644 // a more proper way should be - of course - to
645 // let an offending aircraft take an evasive action
646 // for instance taxi back a little bit.
648 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
649 if (instruction.getHoldPattern ()) {}
652 if (instruction.getHoldPosition ()) {
660 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
663 // Change speed Instruction. This can only be excecuted when there is no
664 // Hold position instruction.
665 if (instruction.getChangeSpeed ()) {
667 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
668 AccelTo(instruction.getSpeed());
670 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
673 if (instruction.getChangeHeading ()) {
675 TurnTo(instruction.getHeading());
681 if (instruction.getChangeAltitude()) {}
686 void FGAIAircraft::handleFirstWaypoint() {
687 bool eraseWaypoints; //TODO YAGNI
690 eraseWaypoints = true;
692 eraseWaypoints = false;
695 FGAIWaypoint* prev = 0; // the one behind you
696 FGAIWaypoint* curr = 0; // the one ahead
697 FGAIWaypoint* next = 0;// the next plus 1
701 //TODO fp should handle this
702 fp->IncrementWaypoint(eraseWaypoints);
703 if (!(fp->getNextWaypoint()) && trafficRef)
704 if (!loadNextLeg()) {
709 prev = fp->getPreviousWaypoint(); //first waypoint
710 curr = fp->getCurrentWaypoint(); //second waypoint
711 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
713 setLatitude(prev->getLatitude());
714 setLongitude(prev->getLongitude());
715 setSpeed(prev->getSpeed());
716 setAltitude(prev->getAltitude());
718 if (prev->getSpeed() > 0.0)
719 setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
721 setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
723 // If next doesn't exist, as in incrementally created flightplans for
724 // AI/Trafficmanager created plans,
725 // Make sure lead distance is initialized otherwise
727 fp->setLeadDistance(speed, hdg, curr, next);
729 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
732 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
733 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
734 // / 6076.0 / prev->getSpeed()*60.0);
735 double vert_dist_ft = curr->getCrossat() - altitude_ft;
736 double err_dist = prev->getCrossat() - altitude_ft;
737 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
738 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
740 tgt_altitude_ft = curr->getCrossat();
743 tgt_altitude_ft = prev->getAltitude();
745 alt_lock = hdg_lock = true;
746 no_roll = prev->getOn_ground();
748 Transform(); // make sure aip is initialized.
749 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
751 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
753 // Make sure to announce the aircraft's position
754 announcePositionToController();
760 * Check Execution time (currently once every 100 ms)
761 * Add a bit of randomization to prevent the execution of all flight plans
762 * in synchrony, which can add significant periodic framerate flutter.
767 bool FGAIAircraft::fpExecutable(time_t now) {
768 double rand_exec_time = (rand() % 100) / 100;
769 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
774 * Check to see if we've reached the lead point for our next turn
779 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
780 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
782 //cerr << "2" << endl;
783 double lead_dist = fp->getLeadDistance();
784 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
785 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
786 tgt_speed = -(dist_to_go / 10.0);
787 if (tgt_speed > -0.5) {
790 //assertSpeed(tgt_speed);
791 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
792 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
795 if (lead_dist < fabs(2*speed)) {
796 //don't skip over the waypoint
797 lead_dist = fabs(2*speed);
798 //cerr << "Extending lead distance to " << lead_dist << endl;
801 //prev_dist_to_go = dist_to_go;
802 //if (dist_to_go < lead_dist)
803 // cerr << trafficRef->getCallSign() << " Distance : "
804 // << dist_to_go << ": Lead distance "
805 // << lead_dist << " " << curr->name
806 // << " Ground target speed " << groundTargetSpeed << endl;
808 // don't do bearing calculations for ground traffic
809 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
810 if (bearing < minBearing) {
811 minBearing = bearing;
812 if (minBearing < 10) {
815 if ((minBearing < 360.0) && (minBearing > 10.0)) {
816 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
822 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
823 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
824 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
825 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
828 if ((dist_to_go < lead_dist) ||
829 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
832 prev_dist_to_go = HUGE_VAL;
835 prev_dist_to_go = dist_to_go;
841 bool FGAIAircraft::aiTrafficVisible()
843 SGVec3d cartPos = SGVec3d::fromGeod(pos);
844 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
845 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
846 return (distSqr(cartPos, globals->get_aircraft_positon_cart()) < d2);
851 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
852 * in the case of an arrival.
858 //TODO the trafficRef is the right place for the method
859 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
860 // prepare routing from one airport to another
861 FGAirport * dep = trafficRef->getDepartureAirport();
862 FGAirport * arr = trafficRef->getArrivalAirport();
867 // This waypoint marks the fact that the aircraft has passed the initial taxi
868 // departure waypoint, so it can release the parking.
869 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
870 //cerr << "Passing waypoint : " << prev->getName() << endl;
871 if (prev->contains("PushBackPoint")) {
872 dep->getDynamics()->releaseParking(fp->getGate());
874 //setTaxiClearanceRequest(true);
876 if (prev->contains("legend")) {
879 if (prev->contains(string("DepartureHold"))) {
880 //cerr << "Passing point DepartureHold" << endl;
881 scheduleForATCTowerDepartureControl(1);
883 if (prev->contains(string("Accel"))) {
886 //if (prev->contains(string("landing"))) {
887 // if (speed < _performance->vTaxi() * 2) {
888 // fp->shortenToFirst(2, "legend");
891 //if (prev->contains(string("final"))) {
893 // cerr << getCallSign() << " "
894 // << fp->getPreviousWaypoint()->getName()
895 // << ". Alt = " << altitude_ft
897 // << " horizontal speed " << speed
898 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
899 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
900 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
902 // This is the last taxi waypoint, and marks the the end of the flight plan
903 // so, the schedule should update and wait for the next departure time.
904 if (prev->contains("END")) {
905 time_t nextDeparture = trafficRef->getDepartureTime();
906 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
907 if (nextDeparture < (now+1200)) {
908 nextDeparture = now + 1200;
910 fp->setTime(nextDeparture);
918 * Check difference between target bearing and current heading and correct if necessary.
922 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
923 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
924 //cerr << "Bearing = " << calc_bearing << endl;
927 if (calc_bearing > 360)
931 if (finite(calc_bearing)) {
932 double hdg_error = calc_bearing - tgt_heading;
933 if (fabs(hdg_error) > 0.01) {
934 TurnTo( calc_bearing );
938 cerr << "calc_bearing is not a finite number : "
940 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
941 << "waypoint " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
942 cerr << "waypoint name " << curr->getName();
949 * Update the lead distance calculation if speed has changed sufficiently
950 * to prevent spinning (hopefully);
955 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
956 double speed_diff = speed - prevSpeed;
958 if (fabs(speed_diff) > 10) {
960 //assertSpeed(speed);
962 fp->setLeadDistance(speed, tgt_heading, curr, next);
969 * Update target values (heading, alt, speed) depending on flight plan or control properties
971 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
972 if (fp) // AI object has a flightplan
974 //TODO make this a function of AIBase
975 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
976 //cerr << "UpateTArgetValues() " << endl;
977 ProcessFlightPlan(dt, now);
979 // Do execute Ground elev for inactive aircraft, so they
980 // Are repositioned to the correct ground altitude when the user flies within visibility range.
981 // In addition, check whether we are out of user range, so this aircraft
984 Transform(); // make sure aip is initialized.
988 pos.setElevationFt(altitude_ft);
991 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
992 aiOutOfSight = !aiTrafficVisible();
995 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1000 timeElapsed = now - fp->getStartTime();
1001 flightplanActive = fp->isActive(now);
1003 // no flight plan, update target heading, speed, and altitude
1004 // from control properties. These default to the initial
1005 // settings in the config file, but can be changed "on the
1007 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
1008 if ( lat_mode == "roll" ) {
1010 = props->getDoubleValue("controls/flight/target-roll" );
1014 = props->getDoubleValue("controls/flight/target-hdg" );
1019 = props->getStringValue("controls/flight/longitude-mode");
1020 if ( lon_mode == "alt" ) {
1021 double alt = props->getDoubleValue("controls/flight/target-alt" );
1025 = props->getDoubleValue("controls/flight/target-pitch" );
1029 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1033 void FGAIAircraft::updatePosition() {
1034 // convert speed to degrees per second
1035 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
1036 * speed * 1.686 / ft_per_deg_lat;
1037 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
1038 * speed * 1.686 / ft_per_deg_lon;
1041 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
1042 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
1046 void FGAIAircraft::updateHeading() {
1047 // adjust heading based on current bank angle
1052 // double turnConstant;
1054 // turnConstant = 0.0088362;
1056 // turnConstant = 0.088362;
1057 // If on ground, calculate heading change directly
1059 double headingDiff = fabs(hdg-tgt_heading);
1060 // double bank_sense = 0.0;
1062 double diff = fabs(hdg - tgt_heading);
1064 diff = fabs(diff - 360);
1066 double sum = hdg + diff;
1069 if (fabs(sum - tgt_heading) < 1.0) {
1070 bank_sense = 1.0; // right turn
1072 bank_sense = -1.0; // left turn
1074 if (headingDiff > 180)
1075 headingDiff = fabs(headingDiff - 360);
1076 double sum = hdg + headingDiff;
1079 if (fabs(sum - tgt_heading) > 0.0001) {
1080 // bank_sense = -1.0;
1082 // bank_sense = 1.0;
1085 // cerr << trafficRef->getCallSign() << " Heading "
1086 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1087 //if (headingDiff > 60) {
1088 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1089 //assertSpeed(groundTargetSpeed);
1090 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1092 // groundTargetSpeed = tgt_speed;
1094 if (sign(groundTargetSpeed) != sign(tgt_speed))
1095 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1096 //assertSpeed(groundTargetSpeed);
1097 // 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.
1099 if (headingDiff > 30.0) {
1100 // invert if pushed backward
1101 headingChangeRate += 10.0 * dt * sign(roll);
1103 // Clamp the maximum steering rate to 30 degrees per second,
1104 // But only do this when the heading error is decreasing.
1105 if ((headingDiff < headingError)) {
1106 if (headingChangeRate > 30)
1107 headingChangeRate = 30;
1108 else if (headingChangeRate < -30)
1109 headingChangeRate = -30;
1113 if (fabs(headingChangeRate) > headingDiff)
1114 headingChangeRate = headingDiff*sign(roll);
1116 headingChangeRate += dt * sign(roll);
1121 //cerr << trafficRef->getCallSign() << " Heading "
1122 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1123 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1124 headingError = headingDiff;
1125 if (fabs(headingError) < 1.0) {
1129 if (fabs(speed) > 1.0) {
1130 turn_radius_ft = 0.088362 * speed * speed
1131 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1133 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1134 turn_radius_ft = 1.0;
1136 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1137 double dist_covered_ft = speed * 1.686 * dt;
1138 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1139 hdg += alpha * sign(roll);
1141 while ( hdg > 360.0 ) {
1145 while ( hdg < 0.0) {
1153 void FGAIAircraft::updateBankAngleTarget() {
1154 // adjust target bank angle if heading lock engaged
1156 double bank_sense = 0.0;
1157 double diff = fabs(hdg - tgt_heading);
1159 diff = fabs(diff - 360);
1161 double sum = hdg + diff;
1164 if (fabs(sum - tgt_heading) < 1.0) {
1165 bank_sense = 1.0; // right turn
1167 bank_sense = -1.0; // left turn
1169 if (diff < _performance->maximumBankAngle()) {
1170 tgt_roll = diff * bank_sense;
1172 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1174 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1175 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1176 // The only way to resolve this is to make them slow down.
1182 void FGAIAircraft::updateVerticalSpeedTarget() {
1183 // adjust target Altitude, based on ground elevation when on ground
1187 } else if (alt_lock) {
1188 // find target vertical speed
1190 if (altitude_ft < tgt_altitude_ft) {
1191 tgt_vs = tgt_altitude_ft - altitude_ft;
1192 if (tgt_vs > _performance->climbRate())
1193 tgt_vs = _performance->climbRate();
1195 tgt_vs = tgt_altitude_ft - altitude_ft;
1196 if (tgt_vs < (-_performance->descentRate()))
1197 tgt_vs = -_performance->descentRate();
1200 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1201 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1202 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1203 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1204 //cerr << "Target vs before : " << tgt_vs;
1205 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1206 double min_vs = 100;
1207 if (tgt_altitude_ft < altitude_ft)
1209 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1210 && (fabs(max_vs) < fabs(tgt_vs)))
1213 if (fabs(tgt_vs) < fabs(min_vs))
1215 //cerr << "target vs : after " << tgt_vs << endl;
1222 void FGAIAircraft::updatePitchAngleTarget() {
1223 // if on ground and above vRotate -> initial rotation
1224 if (onGround() && (speed > _performance->vRotate()))
1225 tgt_pitch = 8.0; // some rough B737 value
1227 //TODO pitch angle on approach and landing
1229 // match pitch angle to vertical speed
1230 else if (tgt_vs > 0) {
1231 tgt_pitch = tgt_vs * 0.005;
1233 tgt_pitch = tgt_vs * 0.002;
1237 string FGAIAircraft::atGate() {
1239 if (fp->getLeg() < 3) {
1241 if (fp->getGate() > 0) {
1243 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1244 tmp = park->getName();
1251 void FGAIAircraft::handleATCRequests() {
1252 //TODO implement NullController for having no ATC to save the conditionals
1254 controller->updateAircraftInformation(getID(),
1255 pos.getLatitudeDeg(),
1256 pos.getLongitudeDeg(),
1260 processATC(controller->getInstruction(getID()));
1262 if (towerController) {
1263 towerController->updateAircraftInformation(getID(),
1264 pos.getLatitudeDeg(),
1265 pos.getLongitudeDeg(),
1272 void FGAIAircraft::updateActualState() {
1273 //update current state
1274 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1278 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1280 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1281 //assertSpeed(speed);
1283 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1285 // adjust altitude (meters) based on current vertical speed (fpm)
1286 altitude_ft += vs / 60.0 * dt;
1287 pos.setElevationFt(altitude_ft);
1289 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1290 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1293 void FGAIAircraft::updateSecondaryTargetValues() {
1294 // derived target state values
1295 updateBankAngleTarget();
1296 updateVerticalSpeedTarget();
1297 updatePitchAngleTarget();
1299 //TODO calculate wind correction angle (tgt_yaw)
1303 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1304 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1305 if (curr->getName() == string("BOD")) {
1306 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1307 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1308 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1310 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1311 double descentTimeNeeded = verticalDistance / descentRate;
1312 double distanceCovered = descentSpeed * descentTimeNeeded;
1314 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1315 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1316 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1317 cerr << "Descent rate : " << descentRate << endl;
1318 cerr << "Descent speed : " << descentSpeed << endl;
1319 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1320 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1321 cerr << "DistanceCovered : " << distanceCovered << endl;
1323 //cerr << "Distance = " << distance << endl;
1324 distance = distanceCovered;
1325 if (dist < distanceCovered) {
1326 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1338 void FGAIAircraft::resetPositionFromFlightPlan()
1340 // the one behind you
1341 FGAIWaypoint* prev = 0;
1343 FGAIWaypoint* curr = 0;
1345 FGAIWaypoint* next = 0;
1347 prev = fp->getPreviousWaypoint();
1348 curr = fp->getCurrentWaypoint();
1349 next = fp->getNextWaypoint();
1351 setLatitude(prev->getLatitude());
1352 setLongitude(prev->getLongitude());
1353 double tgt_heading = fp->getBearing(curr, next);
1354 setHeading(tgt_heading);
1355 setAltitude(prev->getAltitude());
1356 setSpeed(prev->getSpeed());
1359 double FGAIAircraft::getBearing(double crse)
1361 double hdgDiff = fabs(hdg-crse);
1363 hdgDiff = fabs(hdgDiff - 360);
1367 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1368 FGAIWaypoint* curr = 0;
1369 curr = fp->getCurrentWaypoint();
1371 double tracklength = fp->checkTrackLength(wptName);
1372 if (tracklength > 0.1) {
1373 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1377 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1378 time_t arrivalTime = fp->getArrivalTime();
1380 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1381 time_t secondsToGo = arrivalTime - now;
1382 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1383 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1385 return (ete - secondsToGo); // Positive when we're too slow...