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>
39 # define finite _finite
40 #elif defined(__sun) || defined(sgi)
46 #include "AIAircraft.hxx"
47 #include "performancedata.hxx"
48 #include "performancedb.hxx"
50 //#include <Airports/trafficcontroller.hxx>
52 static string tempReg;
54 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
57 groundOffset = trafficRef->getGroundOffset();
58 setCallSign(trafficRef->getCallSign());
73 groundTargetSpeed = 0;
75 // set heading and altitude locks
79 headingChangeRate = 0.0;
85 needsTaxiClearance = false;
87 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
92 FGAIAircraft::~FGAIAircraft() {
95 controller->signOff(getID());
99 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
103 FGAIBase::readFromScenario(scFileNode);
105 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
106 setFlightPlan(scFileNode->getStringValue("flightplan"),
107 scFileNode->getBoolValue("repeat", false));
108 setCallSign(scFileNode->getStringValue("callsign"));
112 void FGAIAircraft::bind() {
115 props->tie("controls/gear/gear-down",
116 SGRawValueMethods<FGAIAircraft,bool>(*this,
117 &FGAIAircraft::_getGearDown));
118 props->tie("transponder-id",
119 SGRawValueMethods<FGAIAircraft,const char*>(*this,
120 &FGAIAircraft::_getTransponderCode));
124 void FGAIAircraft::unbind() {
127 props->untie("controls/gear/gear-down");
128 props->untie("transponder-id");
132 void FGAIAircraft::update(double dt) {
133 FGAIBase::update(dt);
138 void FGAIAircraft::setPerformance(const std::string& acclass) {
139 static PerformanceDB perfdb; //TODO make it a global service
140 setPerformance(perfdb.getDataFor(acclass));
144 void FGAIAircraft::setPerformance(PerformanceData *ps) {
149 void FGAIAircraft::Run(double dt) {
150 FGAIAircraft::dt = dt;
152 bool outOfSight = false,
153 flightplanActive = true;
154 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
159 if (!flightplanActive) {
160 groundTargetSpeed = 0;
163 handleATCRequests(); // ATC also has a word to say
164 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
166 UpdateRadar(manager);
170 void FGAIAircraft::checkVisibility()
172 double visibility_meters = fgGetDouble("/environment/visibility-m");
173 FGViewer* vw = globals->get_current_view();
174 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
179 void FGAIAircraft::AccelTo(double speed) {
184 void FGAIAircraft::PitchTo(double angle) {
190 void FGAIAircraft::RollTo(double angle) {
196 void FGAIAircraft::YawTo(double angle) {
201 void FGAIAircraft::ClimbTo(double alt_ft ) {
202 tgt_altitude_ft = alt_ft;
207 void FGAIAircraft::TurnTo(double heading) {
208 tgt_heading = heading;
213 double FGAIAircraft::sign(double x) {
221 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
222 if (!flightplan.empty()) {
223 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
224 fp->setRepeat(repeat);
230 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
236 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
238 // the one behind you
239 FGAIFlightPlan::waypoint* prev = 0;
241 FGAIFlightPlan::waypoint* curr = 0;
243 FGAIFlightPlan::waypoint* next = 0;
245 prev = fp->getPreviousWaypoint();
246 curr = fp->getCurrentWaypoint();
247 next = fp->getNextWaypoint();
251 ///////////////////////////////////////////////////////////////////////////
252 // Initialize the flightplan
253 //////////////////////////////////////////////////////////////////////////
255 handleFirstWaypoint();
257 } // end of initialization
258 if (! fpExecutable(now))
262 double distanceToDescent;
263 if(reachedEndOfCruise(distanceToDescent)) {
264 if (!loadNextLeg(distanceToDescent)) {
268 prev = fp->getPreviousWaypoint();
269 curr = fp->getCurrentWaypoint();
270 next = fp->getNextWaypoint();
272 if (! leadPointReached(curr)) {
273 controlHeading(curr);
274 controlSpeed(curr, next);
276 if (curr->finished) //end of the flight plan
286 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
287 tgt_heading = fp->getBearing(curr, next);
291 //TODO let the fp handle this (loading of next leg)
292 fp->IncrementWaypoint( trafficRef != 0 );
293 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
294 if (!loadNextLeg()) {
299 prev = fp->getPreviousWaypoint();
300 curr = fp->getCurrentWaypoint();
301 next = fp->getNextWaypoint();
303 // Now that we have incremented the waypoints, excute some traffic manager specific code
305 //TODO isn't this best executed right at the beginning?
306 if (! aiTrafficVisible()) {
311 if (! handleAirportEndPoints(prev, now)) {
316 announcePositionToController();
321 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
324 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
326 tgt_altitude_ft = prev->altitude;
327 if (curr->crossat > -1000.0) {
329 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
330 / 6076.0 / speed*60.0);
331 tgt_altitude_ft = curr->crossat;
336 tgt_speed = prev->speed;
337 hdg_lock = alt_lock = true;
338 no_roll = prev->on_ground;
343 void FGAIAircraft::initializeFlightPlan() {
347 bool FGAIAircraft::_getGearDown() const {
348 return _performance->gearExtensible(this);
352 const char * FGAIAircraft::_getTransponderCode() const {
353 return transponderCode.c_str();
357 bool FGAIAircraft::loadNextLeg(double distance) {
360 if ((leg = fp->getLeg()) == 10) {
361 if (!trafficRef->next()) {
364 setCallSign(trafficRef->getCallSign());
369 FGAirport *dep = trafficRef->getDepartureAirport();
370 FGAirport *arr = trafficRef->getArrivalAirport();
375 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
382 trafficRef->getSpeed(),
386 trafficRef->getRadius(),
387 trafficRef->getFlightType(),
391 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
397 // Note: This code is copied from David Luff's AILocalTraffic
398 // Warning - ground elev determination is CPU intensive
399 // Either this function or the logic of how often it is called
400 // will almost certainly change.
402 void FGAIAircraft::getGroundElev(double dt) {
405 // Update minimally every three secs, but add some randomness
406 // to prevent all AI objects doing this in synchrony
407 if (dt_elev_count < (3.0) + (rand() % 10))
412 // Only do the proper hitlist stuff if we are within visible range of the viewer.
414 double visibility_meters = fgGetDouble("/environment/visibility-m");
415 FGViewer* vw = globals->get_current_view();
417 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
421 double range = 500.0;
422 if (!globals->get_tile_mgr()->scenery_available(pos, range)) {
423 // Try to shedule tiles for that position.
424 globals->get_tile_mgr()->update( pos, range );
428 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
429 tgt_altitude_ft = alt * SG_METER_TO_FEET;
434 void FGAIAircraft::doGroundAltitude() {
435 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
436 altitude_ft = (tgt_altitude_ft + groundOffset);
438 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
443 void FGAIAircraft::announcePositionToController() {
445 int leg = fp->getLeg();
447 // Note that leg has been incremented after creating the current leg, so we should use
448 // leg numbers here that are one higher than the number that is used to create the leg
451 case 2: // Startup and Push back
452 if (trafficRef->getDepartureAirport()->getDynamics())
453 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
455 case 3: // Taxiing to runway
456 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
457 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
459 case 4: //Take off tower controller
460 if (trafficRef->getDepartureAirport()->getDynamics()) {
461 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
463 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
467 if (trafficRef->getDepartureAirport()->getDynamics()) {
468 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
471 case 9: // Taxiing for parking
472 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
473 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
480 if ((controller != prevController) && (prevController != 0)) {
481 prevController->signOff(getID());
483 prevController = controller;
485 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
486 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
487 trafficRef->getRadius(), leg, this);
492 // Process ATC instructions and report back
494 void FGAIAircraft::processATC(FGATCInstruction instruction) {
495 if (instruction.getCheckForCircularWait()) {
496 // This is not exactly an elegant solution,
497 // but at least it gives me a chance to check
498 // if circular waits are resolved.
499 // For now, just take the offending aircraft
502 // a more proper way should be - of course - to
503 // let an offending aircraft take an evasive action
504 // for instance taxi back a little bit.
506 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
507 if (instruction.getHoldPattern ()) {}
510 if (instruction.getHoldPosition ()) {
518 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
521 // Change speed Instruction. This can only be excecuted when there is no
522 // Hold position instruction.
523 if (instruction.getChangeSpeed ()) {
525 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
526 AccelTo(instruction.getSpeed());
528 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
531 if (instruction.getChangeHeading ()) {
533 TurnTo(instruction.getHeading());
539 if (instruction.getChangeAltitude()) {}
544 void FGAIAircraft::handleFirstWaypoint() {
545 bool eraseWaypoints; //TODO YAGNI
548 eraseWaypoints = true;
550 eraseWaypoints = false;
553 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
554 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
555 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
560 //TODO fp should handle this
561 fp->IncrementWaypoint(eraseWaypoints);
562 if (!(fp->getNextWaypoint()) && trafficRef)
563 if (!loadNextLeg()) {
568 prev = fp->getPreviousWaypoint(); //first waypoint
569 curr = fp->getCurrentWaypoint(); //second waypoint
570 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
572 setLatitude(prev->latitude);
573 setLongitude(prev->longitude);
574 setSpeed(prev->speed);
575 setAltitude(prev->altitude);
577 if (prev->speed > 0.0)
578 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
580 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
582 // If next doesn't exist, as in incrementally created flightplans for
583 // AI/Trafficmanager created plans,
584 // Make sure lead distance is initialized otherwise
586 fp->setLeadDistance(speed, hdg, curr, next);
588 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
591 tgt_vs = (curr->crossat - prev->altitude)
592 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
593 / 6076.0 / prev->speed*60.0);
594 tgt_altitude_ft = curr->crossat;
597 tgt_altitude_ft = prev->altitude;
599 alt_lock = hdg_lock = true;
600 no_roll = prev->on_ground;
602 Transform(); // make sure aip is initialized.
603 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
606 // Make sure to announce the aircraft's position
607 announcePositionToController();
613 * Check Execution time (currently once every 100 ms)
614 * Add a bit of randomization to prevent the execution of all flight plans
615 * in synchrony, which can add significant periodic framerate flutter.
620 bool FGAIAircraft::fpExecutable(time_t now) {
621 double rand_exec_time = (rand() % 100) / 100;
622 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
627 * Check to see if we've reached the lead point for our next turn
632 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
633 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
635 //cerr << "2" << endl;
636 double lead_dist = fp->getLeadDistance();
637 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
639 if (lead_dist < fabs(2*speed)) {
640 //don't skip over the waypoint
641 lead_dist = fabs(2*speed);
642 //cerr << "Extending lead distance to " << lead_dist << endl;
645 //prev_dist_to_go = dist_to_go;
646 //if (dist_to_go < lead_dist)
647 // cerr << trafficRef->getCallSign() << " Distance : "
648 // << dist_to_go << ": Lead distance "
649 // << lead_dist << " " << curr->name
650 // << " Ground target speed " << groundTargetSpeed << endl;
652 if (speed > 50) { // don't do bearing calculations for ground traffic
653 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
654 if (bearing < minBearing) {
655 minBearing = bearing;
656 if (minBearing < 10) {
659 if ((minBearing < 360.0) && (minBearing > 10.0)) {
660 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
667 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
668 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
669 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
670 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
673 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
682 bool FGAIAircraft::aiTrafficVisible() {
683 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
684 fgGetDouble("/position/latitude-deg")));
686 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
691 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
692 * in the case of an arrival.
698 //TODO the trafficRef is the right place for the method
699 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
700 // prepare routing from one airport to another
701 FGAirport * dep = trafficRef->getDepartureAirport();
702 FGAirport * arr = trafficRef->getArrivalAirport();
707 // This waypoint marks the fact that the aircraft has passed the initial taxi
708 // departure waypoint, so it can release the parking.
709 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
710 if (prev->name == "PushBackPoint") {
711 dep->getDynamics()->releaseParking(fp->getGate());
713 setTaxiClearanceRequest(true);
716 // This is the last taxi waypoint, and marks the the end of the flight plan
717 // so, the schedule should update and wait for the next departure time.
718 if (prev->name == "END") {
719 time_t nextDeparture = trafficRef->getDepartureTime();
720 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
721 if (nextDeparture < (now+1200)) {
722 nextDeparture = now + 1200;
724 fp->setTime(nextDeparture); // should be "next departure"
732 * Check difference between target bearing and current heading and correct if necessary.
736 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
737 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
738 //cerr << "Bearing = " << calc_bearing << endl;
741 if (calc_bearing > 360)
745 if (finite(calc_bearing)) {
746 double hdg_error = calc_bearing - tgt_heading;
747 if (fabs(hdg_error) > 0.01) {
748 TurnTo( calc_bearing );
752 cerr << "calc_bearing is not a finite number : "
754 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
755 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
756 cerr << "waypoint name " << curr->name;
763 * Update the lead distance calculation if speed has changed sufficiently
764 * to prevent spinning (hopefully);
769 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
770 double speed_diff = speed - prevSpeed;
772 if (fabs(speed_diff) > 10) {
775 fp->setLeadDistance(speed, tgt_heading, curr, next);
782 * Update target values (heading, alt, speed) depending on flight plan or control properties
784 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
785 if (fp) // AI object has a flightplan
787 //TODO make this a function of AIBase
788 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
789 //cerr << "UpateTArgetValues() " << endl;
790 ProcessFlightPlan(dt, now);
792 // Do execute Ground elev for inactive aircraft, so they
793 // Are repositioned to the correct ground altitude when the user flies within visibility range.
794 // In addition, check whether we are out of user range, so this aircraft
797 Transform(); // make sure aip is initialized.
801 pos.setElevationFt(altitude_ft);
804 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
805 aiOutOfSight = !aiTrafficVisible();
808 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
813 timeElapsed = now - fp->getStartTime();
814 flightplanActive = fp->isActive(now);
816 // no flight plan, update target heading, speed, and altitude
817 // from control properties. These default to the initial
818 // settings in the config file, but can be changed "on the
820 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
821 if ( lat_mode == "roll" ) {
823 = props->getDoubleValue("controls/flight/target-roll" );
827 = props->getDoubleValue("controls/flight/target-hdg" );
832 = props->getStringValue("controls/flight/longitude-mode");
833 if ( lon_mode == "alt" ) {
834 double alt = props->getDoubleValue("controls/flight/target-alt" );
838 = props->getDoubleValue("controls/flight/target-pitch" );
842 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
846 void FGAIAircraft::updatePosition() {
847 // convert speed to degrees per second
848 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
849 * speed * 1.686 / ft_per_deg_lat;
850 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
851 * speed * 1.686 / ft_per_deg_lon;
854 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
855 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
859 void FGAIAircraft::updateHeading() {
860 // adjust heading based on current bank angle
865 // double turnConstant;
867 // turnConstant = 0.0088362;
869 // turnConstant = 0.088362;
870 // If on ground, calculate heading change directly
872 double headingDiff = fabs(hdg-tgt_heading);
873 double bank_sense = 0.0;
875 double diff = fabs(hdg - tgt_heading);
877 diff = fabs(diff - 360);
879 double sum = hdg + diff;
882 if (fabs(sum - tgt_heading) < 1.0) {
883 bank_sense = 1.0; // right turn
885 bank_sense = -1.0; // left turn
887 if (headingDiff > 180)
888 headingDiff = fabs(headingDiff - 360);
889 double sum = hdg + headingDiff;
892 if (fabs(sum - tgt_heading) > 0.0001) {
898 //cerr << trafficRef->getCallSign() << " Heading "
899 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
900 //if (headingDiff > 60) {
901 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
902 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
904 // groundTargetSpeed = tgt_speed;
906 if (sign(groundTargetSpeed) != sign(tgt_speed))
907 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
909 if (headingDiff > 30.0) {
910 // invert if pushed backward
911 headingChangeRate += 10.0 * dt * sign(roll);
913 // Clamp the maximum steering rate to 30 degrees per second,
914 // But only do this when the heading error is decreasing.
915 if ((headingDiff < headingError)) {
916 if (headingChangeRate > 30)
917 headingChangeRate = 30;
918 else if (headingChangeRate < -30)
919 headingChangeRate = -30;
922 if (fabs(headingChangeRate) > headingDiff)
923 headingChangeRate = headingDiff*sign(roll);
925 headingChangeRate += dt * sign(roll);
928 hdg += headingChangeRate * dt * (fabs(speed) / 15);
929 headingError = headingDiff;
931 if (fabs(speed) > 1.0) {
932 turn_radius_ft = 0.088362 * speed * speed
933 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
935 // Check if turn_radius_ft == 0; this might lead to a division by 0.
936 turn_radius_ft = 1.0;
938 double turn_circum_ft = SGD_2PI * turn_radius_ft;
939 double dist_covered_ft = speed * 1.686 * dt;
940 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
941 hdg += alpha * sign(roll);
943 while ( hdg > 360.0 ) {
955 void FGAIAircraft::updateBankAngleTarget() {
956 // adjust target bank angle if heading lock engaged
958 double bank_sense = 0.0;
959 double diff = fabs(hdg - tgt_heading);
961 diff = fabs(diff - 360);
963 double sum = hdg + diff;
966 if (fabs(sum - tgt_heading) < 1.0) {
967 bank_sense = 1.0; // right turn
969 bank_sense = -1.0; // left turn
971 if (diff < _performance->maximumBankAngle()) {
972 tgt_roll = diff * bank_sense;
974 tgt_roll = _performance->maximumBankAngle() * bank_sense;
976 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
977 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
978 // The only way to resolve this is to make them slow down.
984 void FGAIAircraft::updateVerticalSpeedTarget() {
985 // adjust target Altitude, based on ground elevation when on ground
989 } else if (alt_lock) {
990 // find target vertical speed
992 if (altitude_ft < tgt_altitude_ft) {
993 tgt_vs = tgt_altitude_ft - altitude_ft;
994 if (tgt_vs > _performance->climbRate())
995 tgt_vs = _performance->climbRate();
997 tgt_vs = tgt_altitude_ft - altitude_ft;
998 if (tgt_vs < (-_performance->descentRate()))
999 tgt_vs = -_performance->descentRate();
1002 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1003 double min_vs = 100;
1004 if (tgt_altitude_ft < altitude_ft)
1006 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1007 && (fabs(max_vs) < fabs(tgt_vs)))
1010 if (fabs(tgt_vs) < fabs(min_vs))
1017 void FGAIAircraft::updatePitchAngleTarget() {
1018 // if on ground and above vRotate -> initial rotation
1019 if (onGround() && (speed > _performance->vRotate()))
1020 tgt_pitch = 8.0; // some rough B737 value
1022 //TODO pitch angle on approach and landing
1024 // match pitch angle to vertical speed
1025 else if (tgt_vs > 0) {
1026 tgt_pitch = tgt_vs * 0.005;
1028 tgt_pitch = tgt_vs * 0.002;
1032 string FGAIAircraft::atGate() {
1034 if (fp->getLeg() < 3) {
1036 if (fp->getGate() > 0) {
1038 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1039 tmp = park->getName();
1046 void FGAIAircraft::handleATCRequests() {
1047 //TODO implement NullController for having no ATC to save the conditionals
1049 controller->update(getID(),
1050 pos.getLatitudeDeg(),
1051 pos.getLongitudeDeg(),
1055 processATC(controller->getInstruction(getID()));
1059 void FGAIAircraft::updateActualState() {
1060 //update current state
1061 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1065 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1067 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1070 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1072 // adjust altitude (meters) based on current vertical speed (fpm)
1073 altitude_ft += vs / 60.0 * dt;
1074 pos.setElevationFt(altitude_ft);
1076 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1077 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1080 void FGAIAircraft::updateSecondaryTargetValues() {
1081 // derived target state values
1082 updateBankAngleTarget();
1083 updateVerticalSpeedTarget();
1084 updatePitchAngleTarget();
1086 //TODO calculate wind correction angle (tgt_yaw)
1090 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1091 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1092 if (curr->name == "BOD") {
1093 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1094 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1095 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1097 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1098 double descentTimeNeeded = verticalDistance / descentRate;
1099 double distanceCovered = descentSpeed * descentTimeNeeded;
1101 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1102 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1103 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1104 cerr << "Descent rate : " << descentRate << endl;
1105 cerr << "Descent speed : " << descentSpeed << endl;
1106 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1107 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1108 cerr << "DistanceCovered : " << distanceCovered << endl;
1110 //cerr << "Distance = " << distance << endl;
1111 distance = distanceCovered;
1112 if (dist < distanceCovered) {
1113 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1125 void FGAIAircraft::resetPositionFromFlightPlan()
1127 // the one behind you
1128 FGAIFlightPlan::waypoint* prev = 0;
1130 FGAIFlightPlan::waypoint* curr = 0;
1132 FGAIFlightPlan::waypoint* next = 0;
1134 prev = fp->getPreviousWaypoint();
1135 curr = fp->getCurrentWaypoint();
1136 next = fp->getNextWaypoint();
1138 setLatitude(prev->latitude);
1139 setLongitude(prev->longitude);
1140 double tgt_heading = fp->getBearing(curr, next);
1141 setHeading(tgt_heading);
1142 setAltitude(prev->altitude);
1143 setSpeed(prev->speed);
1146 double FGAIAircraft::getBearing(double crse)
1148 double hdgDiff = fabs(hdg-crse);
1150 hdgDiff = fabs(hdgDiff - 360);
1154 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1155 FGAIFlightPlan::waypoint* curr = 0;
1156 curr = fp->getCurrentWaypoint();
1158 double tracklength = fp->checkTrackLength(wptName);
1159 if (tracklength > 0.1) {
1160 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1164 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1165 time_t arrivalTime = fp->getArrivalTime();
1167 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1168 time_t secondsToGo = arrivalTime - now;
1169 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1170 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1172 return (ete - secondsToGo); // Positive when we're too slow...