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;
87 _needsGroundElevation = true;
89 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
94 FGAIAircraft::~FGAIAircraft() {
97 controller->signOff(getID());
101 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
105 FGAIBase::readFromScenario(scFileNode);
107 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
108 setFlightPlan(scFileNode->getStringValue("flightplan"),
109 scFileNode->getBoolValue("repeat", false));
110 setCallSign(scFileNode->getStringValue("callsign"));
114 void FGAIAircraft::bind() {
117 props->tie("controls/gear/gear-down",
118 SGRawValueMethods<FGAIAircraft,bool>(*this,
119 &FGAIAircraft::_getGearDown));
120 props->tie("transponder-id",
121 SGRawValueMethods<FGAIAircraft,const char*>(*this,
122 &FGAIAircraft::_getTransponderCode));
126 void FGAIAircraft::unbind() {
129 props->untie("controls/gear/gear-down");
130 props->untie("transponder-id");
134 void FGAIAircraft::update(double dt) {
135 FGAIBase::update(dt);
140 void FGAIAircraft::setPerformance(const std::string& acclass) {
141 static PerformanceDB perfdb; //TODO make it a global service
142 setPerformance(perfdb.getDataFor(acclass));
146 void FGAIAircraft::setPerformance(PerformanceData *ps) {
151 void FGAIAircraft::Run(double dt) {
152 FGAIAircraft::dt = dt;
154 bool outOfSight = false,
155 flightplanActive = true;
156 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
161 if (!flightplanActive) {
162 groundTargetSpeed = 0;
165 handleATCRequests(); // ATC also has a word to say
166 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
168 UpdateRadar(manager);
172 void FGAIAircraft::checkVisibility()
174 double visibility_meters = fgGetDouble("/environment/visibility-m");
175 FGViewer* vw = globals->get_current_view();
176 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
181 void FGAIAircraft::AccelTo(double speed) {
184 _needsGroundElevation = true;
188 void FGAIAircraft::PitchTo(double angle) {
194 void FGAIAircraft::RollTo(double angle) {
200 void FGAIAircraft::YawTo(double angle) {
205 void FGAIAircraft::ClimbTo(double alt_ft ) {
206 tgt_altitude_ft = alt_ft;
211 void FGAIAircraft::TurnTo(double heading) {
212 tgt_heading = heading;
217 double FGAIAircraft::sign(double x) {
225 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
226 if (!flightplan.empty()) {
227 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
228 fp->setRepeat(repeat);
234 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
240 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
242 // the one behind you
243 FGAIFlightPlan::waypoint* prev = 0;
245 FGAIFlightPlan::waypoint* curr = 0;
247 FGAIFlightPlan::waypoint* next = 0;
249 prev = fp->getPreviousWaypoint();
250 curr = fp->getCurrentWaypoint();
251 next = fp->getNextWaypoint();
255 ///////////////////////////////////////////////////////////////////////////
256 // Initialize the flightplan
257 //////////////////////////////////////////////////////////////////////////
259 handleFirstWaypoint();
261 } // end of initialization
262 if (! fpExecutable(now))
266 double distanceToDescent;
267 if(reachedEndOfCruise(distanceToDescent)) {
268 if (!loadNextLeg(distanceToDescent)) {
272 prev = fp->getPreviousWaypoint();
273 curr = fp->getCurrentWaypoint();
274 next = fp->getNextWaypoint();
276 if (! leadPointReached(curr)) {
277 controlHeading(curr);
278 controlSpeed(curr, next);
280 cerr << getCallSign()
281 << ": verifying lead distance to waypoint : "
282 << fp->getCurrentWaypoint()->name << " "
283 << fp->getLeadDistance() << ". Distance to go "
284 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
285 << ". Target speed = "
287 << ". Current speed = "
289 << ". Minimum Bearing " << minBearing
293 if (curr->finished) //end of the flight plan
303 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
304 tgt_heading = fp->getBearing(curr, next);
308 //TODO let the fp handle this (loading of next leg)
309 fp->IncrementWaypoint( trafficRef != 0 );
310 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
311 if (!loadNextLeg()) {
316 prev = fp->getPreviousWaypoint();
317 curr = fp->getCurrentWaypoint();
318 next = fp->getNextWaypoint();
320 // Now that we have incremented the waypoints, excute some traffic manager specific code
322 //TODO isn't this best executed right at the beginning?
323 if (! aiTrafficVisible()) {
328 if (! handleAirportEndPoints(prev, now)) {
333 announcePositionToController();
338 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
341 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
343 tgt_altitude_ft = prev->altitude;
344 if (curr->crossat > -1000.0) {
346 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
347 / 6076.0 / speed*60.0);
349 tgt_altitude_ft = curr->crossat;
354 AccelTo(prev->speed);
355 hdg_lock = alt_lock = true;
356 no_roll = prev->on_ground;
360 void FGAIAircraft::checkTcas(void)
362 if (props->getIntValue("tcas/threat-level",0)==3)
364 int RASense = props->getIntValue("tcas/ra-sense",0);
365 if ((RASense>0)&&(tgt_vs<4000))
371 // downward RA: descend!
372 if (altitude_ft < 1000)
374 // too low: level off
387 void FGAIAircraft::initializeFlightPlan() {
391 bool FGAIAircraft::_getGearDown() const {
392 return _performance->gearExtensible(this);
396 const char * FGAIAircraft::_getTransponderCode() const {
397 return transponderCode.c_str();
401 bool FGAIAircraft::loadNextLeg(double distance) {
404 if ((leg = fp->getLeg()) == 10) {
405 if (!trafficRef->next()) {
408 setCallSign(trafficRef->getCallSign());
413 FGAirport *dep = trafficRef->getDepartureAirport();
414 FGAirport *arr = trafficRef->getArrivalAirport();
419 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
426 trafficRef->getSpeed(),
430 trafficRef->getRadius(),
431 trafficRef->getFlightType(),
435 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
441 // Note: This code is copied from David Luff's AILocalTraffic
442 // Warning - ground elev determination is CPU intensive
443 // Either this function or the logic of how often it is called
444 // will almost certainly change.
446 void FGAIAircraft::getGroundElev(double dt) {
449 if (!needGroundElevation())
451 // Update minimally every three secs, but add some randomness
452 // to prevent all AI objects doing this in synchrony
453 if (dt_elev_count < (3.0) + (rand() % 10))
458 // Only do the proper hitlist stuff if we are within visible range of the viewer.
460 double visibility_meters = fgGetDouble("/environment/visibility-m");
461 FGViewer* vw = globals->get_current_view();
463 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
467 double range = 500.0;
468 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
471 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
473 tgt_altitude_ft = alt * SG_METER_TO_FEET;
476 // aircraft is stationary and we obtained altitude for this spot - we're done.
477 _needsGroundElevation = false;
485 void FGAIAircraft::doGroundAltitude() {
486 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
488 altitude_ft = (tgt_altitude_ft + groundOffset);
490 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
495 void FGAIAircraft::announcePositionToController() {
497 int leg = fp->getLeg();
499 // Note that leg has been incremented after creating the current leg, so we should use
500 // leg numbers here that are one higher than the number that is used to create the leg
503 case 2: // Startup and Push back
504 if (trafficRef->getDepartureAirport()->getDynamics())
505 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
507 case 3: // Taxiing to runway
508 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
509 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
511 case 4: //Take off tower controller
512 if (trafficRef->getDepartureAirport()->getDynamics()) {
513 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
515 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
519 if (trafficRef->getDepartureAirport()->getDynamics()) {
520 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
523 case 9: // Taxiing for parking
524 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
525 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
532 if ((controller != prevController) && (prevController != 0)) {
533 prevController->signOff(getID());
535 prevController = controller;
537 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
538 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
539 trafficRef->getRadius(), leg, this);
544 // Process ATC instructions and report back
546 void FGAIAircraft::processATC(FGATCInstruction instruction) {
547 if (instruction.getCheckForCircularWait()) {
548 // This is not exactly an elegant solution,
549 // but at least it gives me a chance to check
550 // if circular waits are resolved.
551 // For now, just take the offending aircraft
554 // a more proper way should be - of course - to
555 // let an offending aircraft take an evasive action
556 // for instance taxi back a little bit.
558 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
559 if (instruction.getHoldPattern ()) {}
562 if (instruction.getHoldPosition ()) {
570 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
573 // Change speed Instruction. This can only be excecuted when there is no
574 // Hold position instruction.
575 if (instruction.getChangeSpeed ()) {
577 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
578 AccelTo(instruction.getSpeed());
580 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
583 if (instruction.getChangeHeading ()) {
585 TurnTo(instruction.getHeading());
591 if (instruction.getChangeAltitude()) {}
596 void FGAIAircraft::handleFirstWaypoint() {
597 bool eraseWaypoints; //TODO YAGNI
600 eraseWaypoints = true;
602 eraseWaypoints = false;
605 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
606 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
607 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
612 //TODO fp should handle this
613 fp->IncrementWaypoint(eraseWaypoints);
614 if (!(fp->getNextWaypoint()) && trafficRef)
615 if (!loadNextLeg()) {
620 prev = fp->getPreviousWaypoint(); //first waypoint
621 curr = fp->getCurrentWaypoint(); //second waypoint
622 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
624 setLatitude(prev->latitude);
625 setLongitude(prev->longitude);
626 setSpeed(prev->speed);
627 setAltitude(prev->altitude);
629 if (prev->speed > 0.0)
630 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
632 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
634 // If next doesn't exist, as in incrementally created flightplans for
635 // AI/Trafficmanager created plans,
636 // Make sure lead distance is initialized otherwise
638 fp->setLeadDistance(speed, hdg, curr, next);
640 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
643 tgt_vs = (curr->crossat - prev->altitude)
644 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
645 / 6076.0 / prev->speed*60.0);
647 tgt_altitude_ft = curr->crossat;
650 tgt_altitude_ft = prev->altitude;
652 alt_lock = hdg_lock = true;
653 no_roll = prev->on_ground;
655 Transform(); // make sure aip is initialized.
656 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
658 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
660 // Make sure to announce the aircraft's position
661 announcePositionToController();
667 * Check Execution time (currently once every 100 ms)
668 * Add a bit of randomization to prevent the execution of all flight plans
669 * in synchrony, which can add significant periodic framerate flutter.
674 bool FGAIAircraft::fpExecutable(time_t now) {
675 double rand_exec_time = (rand() % 100) / 100;
676 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
681 * Check to see if we've reached the lead point for our next turn
686 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
687 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
689 //cerr << "2" << endl;
690 double lead_dist = fp->getLeadDistance();
691 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
692 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->name == string("PushBackPoint")) {
693 tgt_speed = -(dist_to_go / 10.0);
694 if (tgt_speed > -0.5) {
697 if (fp->getPreviousWaypoint()->speed < tgt_speed) {
698 fp->getPreviousWaypoint()->speed = tgt_speed;
701 if (lead_dist < fabs(2*speed)) {
702 //don't skip over the waypoint
703 lead_dist = fabs(2*speed);
704 //cerr << "Extending lead distance to " << lead_dist << endl;
707 //prev_dist_to_go = dist_to_go;
708 //if (dist_to_go < lead_dist)
709 // cerr << trafficRef->getCallSign() << " Distance : "
710 // << dist_to_go << ": Lead distance "
711 // << lead_dist << " " << curr->name
712 // << " Ground target speed " << groundTargetSpeed << endl;
714 if (speed > 50) { // don't do bearing calculations for ground traffic
715 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
716 if (bearing < minBearing) {
717 minBearing = bearing;
718 if (minBearing < 10) {
721 if ((minBearing < 360.0) && (minBearing > 10.0)) {
722 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
729 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
730 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
731 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
732 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
735 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
744 bool FGAIAircraft::aiTrafficVisible() {
745 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
746 fgGetDouble("/position/latitude-deg")));
748 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
753 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
754 * in the case of an arrival.
760 //TODO the trafficRef is the right place for the method
761 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
762 // prepare routing from one airport to another
763 FGAirport * dep = trafficRef->getDepartureAirport();
764 FGAirport * arr = trafficRef->getArrivalAirport();
769 // This waypoint marks the fact that the aircraft has passed the initial taxi
770 // departure waypoint, so it can release the parking.
771 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
772 if (prev->name == "PushBackPoint") {
773 dep->getDynamics()->releaseParking(fp->getGate());
775 setTaxiClearanceRequest(true);
778 // This is the last taxi waypoint, and marks the the end of the flight plan
779 // so, the schedule should update and wait for the next departure time.
780 if (prev->name == "END") {
781 time_t nextDeparture = trafficRef->getDepartureTime();
782 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
783 if (nextDeparture < (now+1200)) {
784 nextDeparture = now + 1200;
786 fp->setTime(nextDeparture); // should be "next departure"
794 * Check difference between target bearing and current heading and correct if necessary.
798 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
799 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
800 //cerr << "Bearing = " << calc_bearing << endl;
803 if (calc_bearing > 360)
807 if (finite(calc_bearing)) {
808 double hdg_error = calc_bearing - tgt_heading;
809 if (fabs(hdg_error) > 0.01) {
810 TurnTo( calc_bearing );
814 cerr << "calc_bearing is not a finite number : "
816 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
817 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
818 cerr << "waypoint name " << curr->name;
825 * Update the lead distance calculation if speed has changed sufficiently
826 * to prevent spinning (hopefully);
831 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
832 double speed_diff = speed - prevSpeed;
834 if (fabs(speed_diff) > 10) {
837 fp->setLeadDistance(speed, tgt_heading, curr, next);
844 * Update target values (heading, alt, speed) depending on flight plan or control properties
846 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
847 if (fp) // AI object has a flightplan
849 //TODO make this a function of AIBase
850 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
851 //cerr << "UpateTArgetValues() " << endl;
852 ProcessFlightPlan(dt, now);
854 // Do execute Ground elev for inactive aircraft, so they
855 // Are repositioned to the correct ground altitude when the user flies within visibility range.
856 // In addition, check whether we are out of user range, so this aircraft
859 Transform(); // make sure aip is initialized.
863 pos.setElevationFt(altitude_ft);
866 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
867 aiOutOfSight = !aiTrafficVisible();
870 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
875 timeElapsed = now - fp->getStartTime();
876 flightplanActive = fp->isActive(now);
878 // no flight plan, update target heading, speed, and altitude
879 // from control properties. These default to the initial
880 // settings in the config file, but can be changed "on the
882 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
883 if ( lat_mode == "roll" ) {
885 = props->getDoubleValue("controls/flight/target-roll" );
889 = props->getDoubleValue("controls/flight/target-hdg" );
894 = props->getStringValue("controls/flight/longitude-mode");
895 if ( lon_mode == "alt" ) {
896 double alt = props->getDoubleValue("controls/flight/target-alt" );
900 = props->getDoubleValue("controls/flight/target-pitch" );
904 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
908 void FGAIAircraft::updatePosition() {
909 // convert speed to degrees per second
910 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
911 * speed * 1.686 / ft_per_deg_lat;
912 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
913 * speed * 1.686 / ft_per_deg_lon;
916 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
917 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
921 void FGAIAircraft::updateHeading() {
922 // adjust heading based on current bank angle
927 // double turnConstant;
929 // turnConstant = 0.0088362;
931 // turnConstant = 0.088362;
932 // If on ground, calculate heading change directly
934 double headingDiff = fabs(hdg-tgt_heading);
935 double bank_sense = 0.0;
937 double diff = fabs(hdg - tgt_heading);
939 diff = fabs(diff - 360);
941 double sum = hdg + diff;
944 if (fabs(sum - tgt_heading) < 1.0) {
945 bank_sense = 1.0; // right turn
947 bank_sense = -1.0; // left turn
949 if (headingDiff > 180)
950 headingDiff = fabs(headingDiff - 360);
951 double sum = hdg + headingDiff;
954 if (fabs(sum - tgt_heading) > 0.0001) {
960 // cerr << trafficRef->getCallSign() << " Heading "
961 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
962 //if (headingDiff > 60) {
963 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
964 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
966 // groundTargetSpeed = tgt_speed;
968 if (sign(groundTargetSpeed) != sign(tgt_speed))
969 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
971 // 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.
973 if (headingDiff > 30.0) {
974 // invert if pushed backward
975 headingChangeRate += 10.0 * dt * sign(roll);
977 // Clamp the maximum steering rate to 30 degrees per second,
978 // But only do this when the heading error is decreasing.
979 if ((headingDiff < headingError)) {
980 if (headingChangeRate > 30)
981 headingChangeRate = 30;
982 else if (headingChangeRate < -30)
983 headingChangeRate = -30;
987 if (fabs(headingChangeRate) > headingDiff)
988 headingChangeRate = headingDiff*sign(roll);
990 headingChangeRate += dt * sign(roll);
995 cerr << trafficRef->getCallSign() << " Heading "
996 << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
997 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
998 headingError = headingDiff;
1000 if (fabs(speed) > 1.0) {
1001 turn_radius_ft = 0.088362 * speed * speed
1002 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1004 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1005 turn_radius_ft = 1.0;
1007 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1008 double dist_covered_ft = speed * 1.686 * dt;
1009 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1010 hdg += alpha * sign(roll);
1012 while ( hdg > 360.0 ) {
1016 while ( hdg < 0.0) {
1024 void FGAIAircraft::updateBankAngleTarget() {
1025 // adjust target bank angle if heading lock engaged
1027 double bank_sense = 0.0;
1028 double diff = fabs(hdg - tgt_heading);
1030 diff = fabs(diff - 360);
1032 double sum = hdg + diff;
1035 if (fabs(sum - tgt_heading) < 1.0) {
1036 bank_sense = 1.0; // right turn
1038 bank_sense = -1.0; // left turn
1040 if (diff < _performance->maximumBankAngle()) {
1041 tgt_roll = diff * bank_sense;
1043 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1045 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1046 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1047 // The only way to resolve this is to make them slow down.
1053 void FGAIAircraft::updateVerticalSpeedTarget() {
1054 // adjust target Altitude, based on ground elevation when on ground
1058 } else if (alt_lock) {
1059 // find target vertical speed
1061 if (altitude_ft < tgt_altitude_ft) {
1062 tgt_vs = tgt_altitude_ft - altitude_ft;
1063 if (tgt_vs > _performance->climbRate())
1064 tgt_vs = _performance->climbRate();
1066 tgt_vs = tgt_altitude_ft - altitude_ft;
1067 if (tgt_vs < (-_performance->descentRate()))
1068 tgt_vs = -_performance->descentRate();
1071 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1072 double min_vs = 100;
1073 if (tgt_altitude_ft < altitude_ft)
1075 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1076 && (fabs(max_vs) < fabs(tgt_vs)))
1079 if (fabs(tgt_vs) < fabs(min_vs))
1087 void FGAIAircraft::updatePitchAngleTarget() {
1088 // if on ground and above vRotate -> initial rotation
1089 if (onGround() && (speed > _performance->vRotate()))
1090 tgt_pitch = 8.0; // some rough B737 value
1092 //TODO pitch angle on approach and landing
1094 // match pitch angle to vertical speed
1095 else if (tgt_vs > 0) {
1096 tgt_pitch = tgt_vs * 0.005;
1098 tgt_pitch = tgt_vs * 0.002;
1102 string FGAIAircraft::atGate() {
1104 if (fp->getLeg() < 3) {
1106 if (fp->getGate() > 0) {
1108 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1109 tmp = park->getName();
1116 void FGAIAircraft::handleATCRequests() {
1117 //TODO implement NullController for having no ATC to save the conditionals
1119 controller->updateAircraftInformation(getID(),
1120 pos.getLatitudeDeg(),
1121 pos.getLongitudeDeg(),
1125 processATC(controller->getInstruction(getID()));
1129 void FGAIAircraft::updateActualState() {
1130 //update current state
1131 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1135 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1137 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1140 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1142 // adjust altitude (meters) based on current vertical speed (fpm)
1143 altitude_ft += vs / 60.0 * dt;
1144 pos.setElevationFt(altitude_ft);
1146 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1147 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1150 void FGAIAircraft::updateSecondaryTargetValues() {
1151 // derived target state values
1152 updateBankAngleTarget();
1153 updateVerticalSpeedTarget();
1154 updatePitchAngleTarget();
1156 //TODO calculate wind correction angle (tgt_yaw)
1160 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1161 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1162 if (curr->name == "BOD") {
1163 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1164 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1165 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1167 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1168 double descentTimeNeeded = verticalDistance / descentRate;
1169 double distanceCovered = descentSpeed * descentTimeNeeded;
1171 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1172 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1173 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1174 cerr << "Descent rate : " << descentRate << endl;
1175 cerr << "Descent speed : " << descentSpeed << endl;
1176 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1177 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1178 cerr << "DistanceCovered : " << distanceCovered << endl;
1180 //cerr << "Distance = " << distance << endl;
1181 distance = distanceCovered;
1182 if (dist < distanceCovered) {
1183 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1195 void FGAIAircraft::resetPositionFromFlightPlan()
1197 // the one behind you
1198 FGAIFlightPlan::waypoint* prev = 0;
1200 FGAIFlightPlan::waypoint* curr = 0;
1202 FGAIFlightPlan::waypoint* next = 0;
1204 prev = fp->getPreviousWaypoint();
1205 curr = fp->getCurrentWaypoint();
1206 next = fp->getNextWaypoint();
1208 setLatitude(prev->latitude);
1209 setLongitude(prev->longitude);
1210 double tgt_heading = fp->getBearing(curr, next);
1211 setHeading(tgt_heading);
1212 setAltitude(prev->altitude);
1213 setSpeed(prev->speed);
1216 double FGAIAircraft::getBearing(double crse)
1218 double hdgDiff = fabs(hdg-crse);
1220 hdgDiff = fabs(hdgDiff - 360);
1224 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1225 FGAIFlightPlan::waypoint* curr = 0;
1226 curr = fp->getCurrentWaypoint();
1228 double tracklength = fp->checkTrackLength(wptName);
1229 if (tracklength > 0.1) {
1230 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1234 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1235 time_t arrivalTime = fp->getArrivalTime();
1237 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1238 time_t secondsToGo = arrivalTime - now;
1239 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1240 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1242 return (ete - secondsToGo); // Positive when we're too slow...