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"
51 //#include <Airports/trafficcontroller.hxx>
53 static string tempReg;
55 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
58 groundOffset = trafficRef->getGroundOffset();
59 setCallSign(trafficRef->getCallSign());
74 groundTargetSpeed = 0;
76 // set heading and altitude locks
80 headingChangeRate = 0.0;
86 needsTaxiClearance = false;
88 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
93 FGAIAircraft::~FGAIAircraft() {
96 controller->signOff(getID());
100 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
104 FGAIBase::readFromScenario(scFileNode);
106 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
107 setFlightPlan(scFileNode->getStringValue("flightplan"),
108 scFileNode->getBoolValue("repeat", false));
109 setCallSign(scFileNode->getStringValue("callsign"));
113 void FGAIAircraft::bind() {
116 props->tie("controls/gear/gear-down",
117 SGRawValueMethods<FGAIAircraft,bool>(*this,
118 &FGAIAircraft::_getGearDown));
119 props->tie("transponder-id",
120 SGRawValueMethods<FGAIAircraft,const char*>(*this,
121 &FGAIAircraft::_getTransponderCode));
125 void FGAIAircraft::unbind() {
128 props->untie("controls/gear/gear-down");
129 props->untie("transponder-id");
133 void FGAIAircraft::update(double dt) {
134 FGAIBase::update(dt);
139 void FGAIAircraft::setPerformance(const std::string& acclass) {
140 static PerformanceDB perfdb; //TODO make it a global service
141 setPerformance(perfdb.getDataFor(acclass));
145 void FGAIAircraft::setPerformance(PerformanceData *ps) {
150 void FGAIAircraft::Run(double dt) {
151 FGAIAircraft::dt = dt;
153 bool outOfSight = false,
154 flightplanActive = true;
155 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
160 if (!flightplanActive) {
161 groundTargetSpeed = 0;
164 handleATCRequests(); // ATC also has a word to say
165 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
167 UpdateRadar(manager);
171 void FGAIAircraft::checkVisibility()
173 double visibility_meters = fgGetDouble("/environment/visibility-m");
174 FGViewer* vw = globals->get_current_view();
175 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
180 void FGAIAircraft::AccelTo(double speed) {
185 void FGAIAircraft::PitchTo(double angle) {
191 void FGAIAircraft::RollTo(double angle) {
197 void FGAIAircraft::YawTo(double angle) {
202 void FGAIAircraft::ClimbTo(double alt_ft ) {
203 tgt_altitude_ft = alt_ft;
208 void FGAIAircraft::TurnTo(double heading) {
209 tgt_heading = heading;
214 double FGAIAircraft::sign(double x) {
222 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
223 if (!flightplan.empty()) {
224 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
225 fp->setRepeat(repeat);
231 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
237 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
239 // the one behind you
240 FGAIFlightPlan::waypoint* prev = 0;
242 FGAIFlightPlan::waypoint* curr = 0;
244 FGAIFlightPlan::waypoint* next = 0;
246 prev = fp->getPreviousWaypoint();
247 curr = fp->getCurrentWaypoint();
248 next = fp->getNextWaypoint();
252 ///////////////////////////////////////////////////////////////////////////
253 // Initialize the flightplan
254 //////////////////////////////////////////////////////////////////////////
256 handleFirstWaypoint();
258 } // end of initialization
259 if (! fpExecutable(now))
263 double distanceToDescent;
264 if(reachedEndOfCruise(distanceToDescent)) {
265 if (!loadNextLeg(distanceToDescent)) {
269 prev = fp->getPreviousWaypoint();
270 curr = fp->getCurrentWaypoint();
271 next = fp->getNextWaypoint();
273 if (! leadPointReached(curr)) {
274 controlHeading(curr);
275 controlSpeed(curr, next);
277 if (curr->finished) //end of the flight plan
287 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
288 tgt_heading = fp->getBearing(curr, next);
292 //TODO let the fp handle this (loading of next leg)
293 fp->IncrementWaypoint( trafficRef != 0 );
294 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
295 if (!loadNextLeg()) {
300 prev = fp->getPreviousWaypoint();
301 curr = fp->getCurrentWaypoint();
302 next = fp->getNextWaypoint();
304 // Now that we have incremented the waypoints, excute some traffic manager specific code
306 //TODO isn't this best executed right at the beginning?
307 if (! aiTrafficVisible()) {
312 if (! handleAirportEndPoints(prev, now)) {
317 announcePositionToController();
322 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
325 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
327 tgt_altitude_ft = prev->altitude;
328 if (curr->crossat > -1000.0) {
330 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
331 / 6076.0 / speed*60.0);
332 tgt_altitude_ft = curr->crossat;
337 tgt_speed = prev->speed;
338 hdg_lock = alt_lock = true;
339 no_roll = prev->on_ground;
344 void FGAIAircraft::initializeFlightPlan() {
348 bool FGAIAircraft::_getGearDown() const {
349 return _performance->gearExtensible(this);
353 const char * FGAIAircraft::_getTransponderCode() const {
354 return transponderCode.c_str();
358 bool FGAIAircraft::loadNextLeg(double distance) {
361 if ((leg = fp->getLeg()) == 10) {
362 if (!trafficRef->next()) {
365 setCallSign(trafficRef->getCallSign());
370 FGAirport *dep = trafficRef->getDepartureAirport();
371 FGAirport *arr = trafficRef->getArrivalAirport();
376 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
383 trafficRef->getSpeed(),
387 trafficRef->getRadius(),
388 trafficRef->getFlightType(),
392 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
398 // Note: This code is copied from David Luff's AILocalTraffic
399 // Warning - ground elev determination is CPU intensive
400 // Either this function or the logic of how often it is called
401 // will almost certainly change.
403 void FGAIAircraft::getGroundElev(double dt) {
406 // Update minimally every three secs, but add some randomness
407 // to prevent all AI objects doing this in synchrony
408 if (dt_elev_count < (3.0) + (rand() % 10))
413 // Only do the proper hitlist stuff if we are within visible range of the viewer.
415 double visibility_meters = fgGetDouble("/environment/visibility-m");
416 FGViewer* vw = globals->get_current_view();
418 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
422 double range = 500.0;
423 if (!globals->get_tile_mgr()->scenery_available(pos, range)) {
424 // Try to shedule tiles for that position.
425 globals->get_tile_mgr()->schedule_tiles_at( pos, range );
429 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
430 tgt_altitude_ft = alt * SG_METER_TO_FEET;
435 void FGAIAircraft::doGroundAltitude() {
436 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
437 altitude_ft = (tgt_altitude_ft + groundOffset);
439 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
444 void FGAIAircraft::announcePositionToController() {
446 int leg = fp->getLeg();
448 // Note that leg has been incremented after creating the current leg, so we should use
449 // leg numbers here that are one higher than the number that is used to create the leg
452 case 2: // Startup and Push back
453 if (trafficRef->getDepartureAirport()->getDynamics())
454 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
456 case 3: // Taxiing to runway
457 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
458 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
460 case 4: //Take off tower controller
461 if (trafficRef->getDepartureAirport()->getDynamics()) {
462 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
464 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
468 if (trafficRef->getDepartureAirport()->getDynamics()) {
469 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
472 case 9: // Taxiing for parking
473 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
474 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
481 if ((controller != prevController) && (prevController != 0)) {
482 prevController->signOff(getID());
484 prevController = controller;
486 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
487 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
488 trafficRef->getRadius(), leg, this);
493 // Process ATC instructions and report back
495 void FGAIAircraft::processATC(FGATCInstruction instruction) {
496 if (instruction.getCheckForCircularWait()) {
497 // This is not exactly an elegant solution,
498 // but at least it gives me a chance to check
499 // if circular waits are resolved.
500 // For now, just take the offending aircraft
503 // a more proper way should be - of course - to
504 // let an offending aircraft take an evasive action
505 // for instance taxi back a little bit.
507 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
508 if (instruction.getHoldPattern ()) {}
511 if (instruction.getHoldPosition ()) {
519 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
522 // Change speed Instruction. This can only be excecuted when there is no
523 // Hold position instruction.
524 if (instruction.getChangeSpeed ()) {
526 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
527 AccelTo(instruction.getSpeed());
529 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
532 if (instruction.getChangeHeading ()) {
534 TurnTo(instruction.getHeading());
540 if (instruction.getChangeAltitude()) {}
545 void FGAIAircraft::handleFirstWaypoint() {
546 bool eraseWaypoints; //TODO YAGNI
549 eraseWaypoints = true;
551 eraseWaypoints = false;
554 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
555 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
556 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
561 //TODO fp should handle this
562 fp->IncrementWaypoint(eraseWaypoints);
563 if (!(fp->getNextWaypoint()) && trafficRef)
564 if (!loadNextLeg()) {
569 prev = fp->getPreviousWaypoint(); //first waypoint
570 curr = fp->getCurrentWaypoint(); //second waypoint
571 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
573 setLatitude(prev->latitude);
574 setLongitude(prev->longitude);
575 setSpeed(prev->speed);
576 setAltitude(prev->altitude);
578 if (prev->speed > 0.0)
579 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
581 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
583 // If next doesn't exist, as in incrementally created flightplans for
584 // AI/Trafficmanager created plans,
585 // Make sure lead distance is initialized otherwise
587 fp->setLeadDistance(speed, hdg, curr, next);
589 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
592 tgt_vs = (curr->crossat - prev->altitude)
593 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
594 / 6076.0 / prev->speed*60.0);
595 tgt_altitude_ft = curr->crossat;
598 tgt_altitude_ft = prev->altitude;
600 alt_lock = hdg_lock = true;
601 no_roll = prev->on_ground;
603 Transform(); // make sure aip is initialized.
604 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
607 // Make sure to announce the aircraft's position
608 announcePositionToController();
614 * Check Execution time (currently once every 100 ms)
615 * Add a bit of randomization to prevent the execution of all flight plans
616 * in synchrony, which can add significant periodic framerate flutter.
621 bool FGAIAircraft::fpExecutable(time_t now) {
622 double rand_exec_time = (rand() % 100) / 100;
623 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
628 * Check to see if we've reached the lead point for our next turn
633 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
634 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
636 //cerr << "2" << endl;
637 double lead_dist = fp->getLeadDistance();
638 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
640 if (lead_dist < fabs(2*speed)) {
641 //don't skip over the waypoint
642 lead_dist = fabs(2*speed);
643 //cerr << "Extending lead distance to " << lead_dist << endl;
646 //prev_dist_to_go = dist_to_go;
647 //if (dist_to_go < lead_dist)
648 // cerr << trafficRef->getCallSign() << " Distance : "
649 // << dist_to_go << ": Lead distance "
650 // << lead_dist << " " << curr->name
651 // << " Ground target speed " << groundTargetSpeed << endl;
653 if (speed > 50) { // don't do bearing calculations for ground traffic
654 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
655 if (bearing < minBearing) {
656 minBearing = bearing;
657 if (minBearing < 10) {
660 if ((minBearing < 360.0) && (minBearing > 10.0)) {
661 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
668 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
669 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
670 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
671 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
674 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
683 bool FGAIAircraft::aiTrafficVisible() {
684 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
685 fgGetDouble("/position/latitude-deg")));
687 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
692 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
693 * in the case of an arrival.
699 //TODO the trafficRef is the right place for the method
700 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
701 // prepare routing from one airport to another
702 FGAirport * dep = trafficRef->getDepartureAirport();
703 FGAirport * arr = trafficRef->getArrivalAirport();
708 // This waypoint marks the fact that the aircraft has passed the initial taxi
709 // departure waypoint, so it can release the parking.
710 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
711 if (prev->name == "PushBackPoint") {
712 dep->getDynamics()->releaseParking(fp->getGate());
714 setTaxiClearanceRequest(true);
717 // This is the last taxi waypoint, and marks the the end of the flight plan
718 // so, the schedule should update and wait for the next departure time.
719 if (prev->name == "END") {
720 time_t nextDeparture = trafficRef->getDepartureTime();
721 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
722 if (nextDeparture < (now+1200)) {
723 nextDeparture = now + 1200;
725 fp->setTime(nextDeparture); // should be "next departure"
733 * Check difference between target bearing and current heading and correct if necessary.
737 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
738 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
739 //cerr << "Bearing = " << calc_bearing << endl;
742 if (calc_bearing > 360)
746 if (finite(calc_bearing)) {
747 double hdg_error = calc_bearing - tgt_heading;
748 if (fabs(hdg_error) > 0.01) {
749 TurnTo( calc_bearing );
753 cerr << "calc_bearing is not a finite number : "
755 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
756 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
757 cerr << "waypoint name " << curr->name;
764 * Update the lead distance calculation if speed has changed sufficiently
765 * to prevent spinning (hopefully);
770 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
771 double speed_diff = speed - prevSpeed;
773 if (fabs(speed_diff) > 10) {
776 fp->setLeadDistance(speed, tgt_heading, curr, next);
783 * Update target values (heading, alt, speed) depending on flight plan or control properties
785 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
786 if (fp) // AI object has a flightplan
788 //TODO make this a function of AIBase
789 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
790 //cerr << "UpateTArgetValues() " << endl;
791 ProcessFlightPlan(dt, now);
793 // Do execute Ground elev for inactive aircraft, so they
794 // Are repositioned to the correct ground altitude when the user flies within visibility range.
795 // In addition, check whether we are out of user range, so this aircraft
798 Transform(); // make sure aip is initialized.
802 pos.setElevationFt(altitude_ft);
805 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
806 aiOutOfSight = !aiTrafficVisible();
809 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
814 timeElapsed = now - fp->getStartTime();
815 flightplanActive = fp->isActive(now);
817 // no flight plan, update target heading, speed, and altitude
818 // from control properties. These default to the initial
819 // settings in the config file, but can be changed "on the
821 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
822 if ( lat_mode == "roll" ) {
824 = props->getDoubleValue("controls/flight/target-roll" );
828 = props->getDoubleValue("controls/flight/target-hdg" );
833 = props->getStringValue("controls/flight/longitude-mode");
834 if ( lon_mode == "alt" ) {
835 double alt = props->getDoubleValue("controls/flight/target-alt" );
839 = props->getDoubleValue("controls/flight/target-pitch" );
843 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
847 void FGAIAircraft::updatePosition() {
848 // convert speed to degrees per second
849 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
850 * speed * 1.686 / ft_per_deg_lat;
851 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
852 * speed * 1.686 / ft_per_deg_lon;
855 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
856 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
860 void FGAIAircraft::updateHeading() {
861 // adjust heading based on current bank angle
866 // double turnConstant;
868 // turnConstant = 0.0088362;
870 // turnConstant = 0.088362;
871 // If on ground, calculate heading change directly
873 double headingDiff = fabs(hdg-tgt_heading);
874 double bank_sense = 0.0;
876 double diff = fabs(hdg - tgt_heading);
878 diff = fabs(diff - 360);
880 double sum = hdg + diff;
883 if (fabs(sum - tgt_heading) < 1.0) {
884 bank_sense = 1.0; // right turn
886 bank_sense = -1.0; // left turn
888 if (headingDiff > 180)
889 headingDiff = fabs(headingDiff - 360);
890 double sum = hdg + headingDiff;
893 if (fabs(sum - tgt_heading) > 0.0001) {
899 //cerr << trafficRef->getCallSign() << " Heading "
900 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
901 //if (headingDiff > 60) {
902 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
903 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
905 // groundTargetSpeed = tgt_speed;
907 if (sign(groundTargetSpeed) != sign(tgt_speed))
908 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
910 if (headingDiff > 30.0) {
911 // invert if pushed backward
912 headingChangeRate += 10.0 * dt * sign(roll);
914 // Clamp the maximum steering rate to 30 degrees per second,
915 // But only do this when the heading error is decreasing.
916 if ((headingDiff < headingError)) {
917 if (headingChangeRate > 30)
918 headingChangeRate = 30;
919 else if (headingChangeRate < -30)
920 headingChangeRate = -30;
923 if (fabs(headingChangeRate) > headingDiff)
924 headingChangeRate = headingDiff*sign(roll);
926 headingChangeRate += dt * sign(roll);
929 hdg += headingChangeRate * dt * (fabs(speed) / 15);
930 headingError = headingDiff;
932 if (fabs(speed) > 1.0) {
933 turn_radius_ft = 0.088362 * speed * speed
934 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
936 // Check if turn_radius_ft == 0; this might lead to a division by 0.
937 turn_radius_ft = 1.0;
939 double turn_circum_ft = SGD_2PI * turn_radius_ft;
940 double dist_covered_ft = speed * 1.686 * dt;
941 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
942 hdg += alpha * sign(roll);
944 while ( hdg > 360.0 ) {
956 void FGAIAircraft::updateBankAngleTarget() {
957 // adjust target bank angle if heading lock engaged
959 double bank_sense = 0.0;
960 double diff = fabs(hdg - tgt_heading);
962 diff = fabs(diff - 360);
964 double sum = hdg + diff;
967 if (fabs(sum - tgt_heading) < 1.0) {
968 bank_sense = 1.0; // right turn
970 bank_sense = -1.0; // left turn
972 if (diff < _performance->maximumBankAngle()) {
973 tgt_roll = diff * bank_sense;
975 tgt_roll = _performance->maximumBankAngle() * bank_sense;
977 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
978 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
979 // The only way to resolve this is to make them slow down.
985 void FGAIAircraft::updateVerticalSpeedTarget() {
986 // adjust target Altitude, based on ground elevation when on ground
990 } else if (alt_lock) {
991 // find target vertical speed
993 if (altitude_ft < tgt_altitude_ft) {
994 tgt_vs = tgt_altitude_ft - altitude_ft;
995 if (tgt_vs > _performance->climbRate())
996 tgt_vs = _performance->climbRate();
998 tgt_vs = tgt_altitude_ft - altitude_ft;
999 if (tgt_vs < (-_performance->descentRate()))
1000 tgt_vs = -_performance->descentRate();
1003 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1004 double min_vs = 100;
1005 if (tgt_altitude_ft < altitude_ft)
1007 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1008 && (fabs(max_vs) < fabs(tgt_vs)))
1011 if (fabs(tgt_vs) < fabs(min_vs))
1018 void FGAIAircraft::updatePitchAngleTarget() {
1019 // if on ground and above vRotate -> initial rotation
1020 if (onGround() && (speed > _performance->vRotate()))
1021 tgt_pitch = 8.0; // some rough B737 value
1023 //TODO pitch angle on approach and landing
1025 // match pitch angle to vertical speed
1026 else if (tgt_vs > 0) {
1027 tgt_pitch = tgt_vs * 0.005;
1029 tgt_pitch = tgt_vs * 0.002;
1033 string FGAIAircraft::atGate() {
1035 if (fp->getLeg() < 3) {
1037 if (fp->getGate() > 0) {
1039 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1040 tmp = park->getName();
1047 void FGAIAircraft::handleATCRequests() {
1048 //TODO implement NullController for having no ATC to save the conditionals
1050 controller->update(getID(),
1051 pos.getLatitudeDeg(),
1052 pos.getLongitudeDeg(),
1056 processATC(controller->getInstruction(getID()));
1060 void FGAIAircraft::updateActualState() {
1061 //update current state
1062 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1066 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1068 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1071 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1073 // adjust altitude (meters) based on current vertical speed (fpm)
1074 altitude_ft += vs / 60.0 * dt;
1075 pos.setElevationFt(altitude_ft);
1077 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1078 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1081 void FGAIAircraft::updateSecondaryTargetValues() {
1082 // derived target state values
1083 updateBankAngleTarget();
1084 updateVerticalSpeedTarget();
1085 updatePitchAngleTarget();
1087 //TODO calculate wind correction angle (tgt_yaw)
1091 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1092 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1093 if (curr->name == "BOD") {
1094 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1095 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1096 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1098 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1099 double descentTimeNeeded = verticalDistance / descentRate;
1100 double distanceCovered = descentSpeed * descentTimeNeeded;
1102 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1103 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1104 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1105 cerr << "Descent rate : " << descentRate << endl;
1106 cerr << "Descent speed : " << descentSpeed << endl;
1107 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1108 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1109 cerr << "DistanceCovered : " << distanceCovered << endl;
1111 //cerr << "Distance = " << distance << endl;
1112 distance = distanceCovered;
1113 if (dist < distanceCovered) {
1114 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1126 void FGAIAircraft::resetPositionFromFlightPlan()
1128 // the one behind you
1129 FGAIFlightPlan::waypoint* prev = 0;
1131 FGAIFlightPlan::waypoint* curr = 0;
1133 FGAIFlightPlan::waypoint* next = 0;
1135 prev = fp->getPreviousWaypoint();
1136 curr = fp->getCurrentWaypoint();
1137 next = fp->getNextWaypoint();
1139 setLatitude(prev->latitude);
1140 setLongitude(prev->longitude);
1141 double tgt_heading = fp->getBearing(curr, next);
1142 setHeading(tgt_heading);
1143 setAltitude(prev->altitude);
1144 setSpeed(prev->speed);
1147 double FGAIAircraft::getBearing(double crse)
1149 double hdgDiff = fabs(hdg-crse);
1151 hdgDiff = fabs(hdgDiff - 360);
1155 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1156 FGAIFlightPlan::waypoint* curr = 0;
1157 curr = fp->getCurrentWaypoint();
1159 double tracklength = fp->checkTrackLength(wptName);
1160 if (tracklength > 0.1) {
1161 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1165 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1166 time_t arrivalTime = fp->getArrivalTime();
1168 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1169 time_t secondsToGo = arrivalTime - now;
1170 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1171 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1173 return (ete - secondsToGo); // Positive when we're too slow...