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/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.hxx>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 //#include <Airports/trafficcontroller.hxx>
47 static string tempReg;
49 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
50 // cruise_speed, descent_speed, land_speed
52 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
54 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
56 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
58 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
60 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
62 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
63 // ufo (extreme accel/decel)
64 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
68 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
73 groundOffset = trafficRef->getGroundOffset();
88 groundTargetSpeed = 0;
90 // set heading and altitude locks
94 headingChangeRate = 0.0;
100 FGAIAircraft::~FGAIAircraft() {
103 controller->signOff(getID());
107 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
111 FGAIBase::readFromScenario(scFileNode);
113 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
114 setFlightPlan(scFileNode->getStringValue("flightplan"),
115 scFileNode->getBoolValue("repeat", false));
116 setCallSign(scFileNode->getStringValue("callsign"));
117 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
121 bool FGAIAircraft::init() {
122 //refuel_node = fgGetNode("systems/refuel/contact", true);
123 return FGAIBase::init();
127 void FGAIAircraft::bind() {
130 props->tie("controls/gear/gear-down",
131 SGRawValueMethods<FGAIAircraft,bool>(*this,
132 &FGAIAircraft::_getGearDown));
133 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
134 props->setStringValue("callsign", callsign.c_str());
135 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
136 props->setBoolValue("tanker",isTanker);
140 void FGAIAircraft::unbind() {
143 props->untie("controls/gear/gear-down");
144 props->untie("refuel/contact");
148 void FGAIAircraft::update(double dt) {
149 FGAIBase::update(dt);
155 void FGAIAircraft::setPerformance(const std::string& acclass) {
156 if (acclass == "light") {
157 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
158 } else if (acclass == "ww2_fighter") {
159 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
160 } else if (acclass == "jet_transport") {
161 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
162 } else if (acclass == "jet_fighter") {
163 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
164 } else if (acclass == "tanker") {
165 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
167 } else if (acclass == "ufo") {
168 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
170 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
175 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
181 void FGAIAircraft::Run(double dt) {
183 FGAIAircraft::dt = dt;
186 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
187 ProcessFlightPlan(dt, now);
188 if (now < fp->getStartTime()) {
189 // Do execute Ground elev for inactive aircraft, so they
190 // Are repositioned to the correct ground altitude when the user flies within visibility range.
191 // In addition, check whether we are out of user range, so this aircraft
194 Transform(); // make sure aip is initialized.
196 double userLatitude = fgGetDouble("/position/latitude-deg");
197 double userLongitude = fgGetDouble("/position/longitude-deg");
198 double course, distance;
199 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
200 SGWayPoint user (userLongitude, userLatitude, 0);
201 user.CourseAndDistance(current, &course, &distance);
202 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
206 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
207 //getGroundElev(dt); // Need to do this twice.
208 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
210 //cerr << " Actual altitude " << altitude << endl;
212 pos.setElevationFt(altitude_ft);
218 // no flight plan, update target heading, speed, and altitude
219 // from control properties. These default to the initial
220 // settings in the config file, but can be changed "on the
222 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
223 if ( lat_mode == "roll" ) {
225 = props->getDoubleValue("controls/flight/target-roll" );
229 = props->getDoubleValue("controls/flight/target-hdg" );
234 = props->getStringValue("controls/flight/longitude-mode");
235 if ( lon_mode == "alt" ) {
236 double alt = props->getDoubleValue("controls/flight/target-alt" );
240 = props->getDoubleValue("controls/flight/target-pitch" );
244 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
248 controller->update(getID(),
249 pos.getLatitudeDeg(),
250 pos.getLongitudeDeg(),
254 processATC(controller->getInstruction(getID()));
257 double turn_radius_ft;
258 double turn_circum_ft;
259 double speed_north_deg_sec;
260 double speed_east_deg_sec;
261 double dist_covered_ft;
265 double speed_diff; //= tgt_speed - speed;
267 speed_diff = tgt_speed - speed;
269 speed_diff = groundTargetSpeed - speed;
272 if (speed_diff > 0.0) {
273 speed += performance->accel * dt;
274 if (no_roll) { // apply overshoot correction
275 if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
277 if ( speed > tgt_speed ) speed = tgt_speed;
279 } else if (speed_diff < 0.0) {
281 // on ground (aircraft can't roll)
282 // deceleration performance is better due to wheel brakes.
283 speed -= performance->decel * dt * 3;
285 speed -= performance->decel * dt;
287 if (no_roll) { // apply overshoot correction
288 if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
290 if ( speed < tgt_speed ) speed = tgt_speed;
295 // convert speed to degrees per second
296 speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
297 * speed * 1.686 / ft_per_deg_lat;
298 speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
299 * speed * 1.686 / ft_per_deg_lon;
302 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
303 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
305 /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
306 dt, hdg, speed, ft_per_deg_lat,
307 cos( hdg * SGD_DEGREES_TO_RADIANS ),
308 speed * 1.686 / ft_per_deg_lat,
309 speed_north_deg_sec, speed_east_deg_sec,
310 pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
312 //if (!(finite(pos.lat()) && finite(pos.lon())))
314 // cerr << "Position is not finite" << endl;
315 // cerr << "speed = " << speed << endl;
316 // cerr << "dt" << dt << endl;
317 // cerr << "heading " << hdg << endl;
318 // cerr << "speed east " << speed_east_deg_sec << endl;
319 // cerr << "speed nrth " << speed_north_deg_sec << endl;
320 // cerr << "deg_lat " << ft_per_deg_lat << endl;
321 // cerr << "deg_lon " << ft_per_deg_lon << endl;
324 // adjust heading based on current bank angle
329 // double turnConstant;
331 // turnConstant = 0.0088362;
333 // turnConstant = 0.088362;
334 // If on ground, calculate heading change directly
336 double headingDiff = fabs(hdg-tgt_heading);
338 if (headingDiff > 180)
339 headingDiff = fabs(headingDiff - 360);
341 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
342 if (sign(groundTargetSpeed) != sign(tgt_speed))
343 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
345 if (headingDiff > 30.0) {
346 headingChangeRate += dt * sign(roll); // invert if pushed backward
347 // Print some debug statements to find out why aircraft may get stuck
349 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
350 // cerr << "Turning : " << trafficRef->getRegistration()
351 // cerr << " Speed = " << speed << " Heading " << hdg
352 // << " Target Heading " << tgt_heading
353 // << " Lead Distance " << fp->getLeadDistance()
354 // << " Distance to go "
355 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
356 // << "waypoint name " << fp->getCurrentWaypoint()->name
359 if (headingChangeRate > 30)
360 headingChangeRate = 30;
361 else if (headingChangeRate < -30)
362 headingChangeRate = -30;
365 if (fabs(headingChangeRate) > headingDiff)
366 headingChangeRate = headingDiff*sign(roll);
368 headingChangeRate += dt * sign(roll);
370 hdg += headingChangeRate * dt;
371 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
372 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
373 // << headingChangeRate << endl;
376 if (fabs(speed) > 1.0) {
377 turn_radius_ft = 0.088362 * speed * speed
378 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
380 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
382 turn_circum_ft = SGD_2PI * turn_radius_ft;
383 dist_covered_ft = speed * 1.686 * dt;
384 alpha = dist_covered_ft / turn_circum_ft * 360.0;
385 hdg += alpha * sign(roll);
387 while ( hdg > 360.0 ) {
398 // adjust target bank angle if heading lock engaged
400 double bank_sense = 0.0;
401 double diff = fabs(hdg - tgt_heading);
403 diff = fabs(diff - 360);
405 double sum = hdg + diff;
408 if (fabs(sum - tgt_heading) < 1.0) {
409 bank_sense = 1.0; // right turn
411 bank_sense = -1.0; // left turn
414 tgt_roll = diff * bank_sense;
416 tgt_roll = 30.0 * bank_sense;
418 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
419 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
420 // The only way to resolve this is to make them slow down.
421 //if (tempReg.empty())
422 // tempReg = trafficRef->getRegistration();
423 //if (trafficRef->getRegistration() == tempReg) {
424 // cerr << trafficRef->getRegistration()
425 // << " appears to be spinning: " << spinCounter << endl
426 // << " speed " << speed << endl
427 // << " heading " << hdg << endl
428 // << " lead distance " << fp->getLeadDistance() << endl
429 // << " waypoint " << fp->getCurrentWaypoint()->name
430 // << " target heading " << tgt_heading << endl
431 // << " lead in angle " << fp->getLeadInAngle()<< endl
432 // << " roll " << roll << endl
433 // << " target_roll " << tgt_roll << endl;
438 // adjust bank angle, use 9 degrees per second
439 double bank_diff = tgt_roll - roll;
440 if (fabs(bank_diff) > 0.2) {
446 //while (roll > 180) roll -= 360;
447 //while (roll < 180) roll += 360;
450 // adjust altitude (meters) based on current vertical speed (fpm)
451 altitude_ft += vs / 60.0 * dt;
452 pos.setElevationFt(altitude_ft);
454 // adjust target Altitude, based on ground elevation when on ground
459 // find target vertical speed if altitude lock engaged
460 if (alt_lock && use_perf_vs) {
461 if (altitude_ft < tgt_altitude_ft) {
462 tgt_vs = tgt_altitude_ft - altitude_ft;
463 if (tgt_vs > performance->climb_rate)
464 tgt_vs = performance->climb_rate;
466 tgt_vs = tgt_altitude_ft - altitude_ft;
467 if (tgt_vs < (-performance->descent_rate))
468 tgt_vs = -performance->descent_rate;
472 if (alt_lock && !use_perf_vs) {
473 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
475 if (tgt_altitude_ft < altitude_ft)
477 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
478 && (fabs(max_vs) < fabs(tgt_vs)))
481 if (fabs(tgt_vs) < fabs(min_vs))
485 // adjust vertical speed
486 double vs_diff = tgt_vs - vs;
487 if (fabs(vs_diff) > 10.0) {
489 vs += (performance->climb_rate / 3.0) * dt;
494 vs -= (performance->descent_rate / 3.0) * dt;
501 // match pitch angle to vertical speed
508 //###########################//
509 // do calculations for radar //
510 //###########################//
511 double range_ft2 = UpdateRadar(manager);
513 //************************************//
515 //************************************//
518 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
519 && (elevation > 0.0) ) {
520 //refuel_node->setBoolValue(true);
523 //refuel_node->setBoolValue(false);
532 void FGAIAircraft::AccelTo(double speed) {
537 void FGAIAircraft::PitchTo(double angle) {
543 void FGAIAircraft::RollTo(double angle) {
549 void FGAIAircraft::YawTo(double angle) {
554 void FGAIAircraft::ClimbTo(double alt_ft ) {
555 tgt_altitude_ft = alt_ft;
560 void FGAIAircraft::TurnTo(double heading) {
561 tgt_heading = heading;
566 double FGAIAircraft::sign(double x) {
574 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
575 if (!flightplan.empty()) {
576 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
577 fp->setRepeat(repeat);
583 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
589 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
592 eraseWaypoints = true;
594 eraseWaypoints = false;
597 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
598 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
599 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
600 prev = fp->getPreviousWaypoint();
601 curr = fp->getCurrentWaypoint();
602 next = fp->getNextWaypoint();
605 ///////////////////////////////////////////////////////////////////////////
606 // Initialize the flightplan
607 //////////////////////////////////////////////////////////////////////////
612 fp->IncrementWaypoint(eraseWaypoints);
613 if (!(fp->getNextWaypoint()) && trafficRef)
616 prev = fp->getPreviousWaypoint(); //first waypoint
617 curr = fp->getCurrentWaypoint(); //second waypoint
618 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
620 setLatitude(prev->latitude);
621 setLongitude(prev->longitude);
622 setSpeed(prev->speed);
623 setAltitude(prev->altitude);
625 if (prev->speed > 0.0)
626 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
628 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
630 // If next doesn't exist, as in incrementally created flightplans for
631 // AI/Trafficmanager created plans,
632 // Make sure lead distance is initialized otherwise
634 fp->setLeadDistance(speed, hdg, curr, next);
636 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
638 tgt_vs = (curr->crossat - prev->altitude)
639 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
640 / 6076.0 / prev->speed*60.0);
641 tgt_altitude_ft = curr->crossat;
644 tgt_altitude_ft = prev->altitude;
646 alt_lock = hdg_lock = true;
647 no_roll = prev->on_ground;
649 Transform(); // make sure aip is initialized.
650 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
653 // Make sure to announce the aircraft's position
654 announcePositionToController();
657 } // end of initialization
659 ///////////////////////////////////////////////////////////////////////////
660 // Check Execution time (currently once every 100 ms
661 ///////////////////////////////////////////////////////////////////////////
662 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
663 //cerr << "done fp dt" << endl;
668 // check to see if we've reached the lead point for our next turn
669 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
671 //cerr << "2" << endl;
672 double lead_dist = fp->getLeadDistance();
673 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
674 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
676 if (lead_dist < fabs(2*speed)) {
677 lead_dist = fabs(2*speed); //don't skip over the waypoint
678 //cerr << "Extending lead distance to " << lead_dist << endl;
681 //prev_dist_to_go = dist_to_go;
683 if ( dist_to_go < lead_dist ) {
684 if (curr->finished) { //end of the flight plan
693 tgt_heading = fp->getBearing(curr, next);
697 fp->IncrementWaypoint(eraseWaypoints);
698 if (!(fp->getNextWaypoint()) && trafficRef)
701 prev = fp->getPreviousWaypoint();
702 curr = fp->getCurrentWaypoint();
703 next = fp->getNextWaypoint();
705 // Now that we have incremented the waypoints, excute some traffic manager specific code
707 double userLatitude = fgGetDouble("/position/latitude-deg");
708 double userLongitude = fgGetDouble("/position/longitude-deg");
709 double course, distance;
710 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
711 SGWayPoint user (userLongitude, userLatitude, 0);
712 user.CourseAndDistance(current, &course, &distance);
713 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
718 FGAirport * dep = trafficRef->getDepartureAirport();
719 FGAirport * arr = trafficRef->getArrivalAirport();
720 if (!( dep && arr)) {
724 // This waypoint marks the fact that the aircraft has passed the initial taxi
725 // departure waypoint, so it can release the parking.
726 if (prev->name == "park2")
727 dep->getDynamics()->releaseParking(fp->getGate());
728 // This is the last taxi waypoint, and marks the the end of the flight plan
729 // so, the schedule should update and wait for the next departure time.
730 if (prev->name == "END") {
731 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
733 time_t nextDeparture = trafficRef->getDepartureTime();
734 if (nextDeparture < (now+1200)) {
735 nextDeparture = now + 1200;
737 fp->setTime(trafficRef->getDepartureTime());
739 announcePositionToController();
744 //cerr << "Current waypoint" << curr->name << endl;
745 //cerr << "Next waypoint" << next->name << endl;
746 fp->setLeadDistance(speed, tgt_heading, curr, next);
749 //cerr << "5.1" << endl;
750 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
751 tgt_altitude_ft = prev->altitude;
752 if (curr->crossat > -1000.0) {
753 //cerr << "5.1a" << endl;
755 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
756 / 6076.0 / speed*60.0);
757 //cerr << "5.1b" << endl;
758 tgt_altitude_ft = curr->crossat;
760 //cerr << "5.1c" << endl;
762 //cerr << "5.1d" << endl;
763 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
766 //cerr << "6" << endl;
767 tgt_speed = prev->speed;
768 hdg_lock = alt_lock = true;
769 no_roll = prev->on_ground;
770 //cout << "Crossing waypoint: " << prev->name << endl;
771 //cout << " Target speed: " << tgt_speed << endl;
772 //cout << " Target altitude: " << tgt_altitude_ft << endl;
773 //cout << " Target heading: " << tgt_heading << endl << endl;
776 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
777 //cerr << "Bearing = " << calc_bearing << endl;
780 if (calc_bearing > 360)
784 if (finite(calc_bearing)) {
785 double hdg_error = calc_bearing - tgt_heading;
786 if (fabs(hdg_error) > 1.0) {
787 TurnTo( calc_bearing );
791 cerr << "calc_bearing is not a finite number : "
793 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
794 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
795 cerr << "waypoint name " << curr->name;
799 double speed_diff = speed - prevSpeed;
800 // Update the lead distance calculation if speed has changed sufficiently
801 // to prevent spinning (hopefully);
802 if (fabs(speed_diff) > 10) {
804 fp->setLeadDistance(speed, tgt_heading, curr, next);
807 //cerr << "Done Processing FlightPlan"<< endl;
811 void FGAIAircraft::initializeFlightPlan()
817 bool FGAIAircraft::_getGearDown() const {
818 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
819 && (props->getFloatValue("velocities/airspeed-kt")
820 < performance->land_speed*1.25));
824 void FGAIAircraft::loadNextLeg() {
826 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
828 //FGAIModelEntity entity;
829 //entity.m_class = "jet_transport";
830 //entity.path = modelPath.c_str();
831 //entity.flightplan = "none";
832 //entity.latitude = _getLatitude();
833 //entity.longitude = _getLongitude();
834 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
835 //entity.speed = 450; // HACK ALERT
836 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
838 if ((leg = fp->getLeg()) == 10) {
842 //cerr << "Resetting leg : " << leg << endl;
846 //cerr << "Creating leg number : " << leg << endl;
847 FGAirport *dep = trafficRef->getDepartureAirport();
848 FGAirport *arr = trafficRef->getArrivalAirport();
851 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
853 // cerr << "Departure " << dep->getId() << endl;
855 // cerr << "Arrival " << arr->getId() << endl;
858 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
859 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
864 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
865 trafficRef->getSpeed(),
869 trafficRef->getRadius(),
870 trafficRef->getFlightType(),
873 //prev = fp->getPreviousWaypoint();
874 //curr = fp->getCurrentWaypoint();
875 //next = fp->getNextWaypoint();
876 //cerr << "25" << endl;
879 // //cerr << "Next waypoint" << next->name << endl;
880 // fp->setLeadDistance(speed, tgt_heading, curr, next);
882 //cerr << "25.1" << endl;
883 //if (curr->crossat > -1000.0) {
884 // //cerr << "25.1a" << endl;
885 // use_perf_vs = false;
887 // tgt_vs = (curr->crossat - altitude_ft)/
888 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
889 // //cerr << "25.1b" << endl;
890 // tgt_altitude_ft = curr->crossat;
892 // //cerr << "25.1c" << endl;
893 // use_perf_vs = true;
894 // //cerr << "25.1d" << endl;
895 // tgt_altitude_ft = prev->altitude;
896 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
898 //cerr << "26" << endl;
899 //tgt_speed = prev->speed;
900 //hdg_lock = alt_lock = true;
901 //no_roll = prev->on_ground;
906 //entity.fp = new FGAIFlightPlan(&entity,
908 // trafficRef->getDepartureTime(),
909 // trafficRef->getDepartureAirport(),
910 // trafficRef->getArrivalAirport(),
914 //SetFlightPlan(entity.fp);
918 // Note: This code is copied from David Luff's AILocalTraffic
919 // Warning - ground elev determination is CPU intensive
920 // Either this function or the logic of how often it is called
921 // will almost certainly change.
923 void FGAIAircraft::getGroundElev(double dt) {
926 // Update minimally every three secs, but add some randomness
927 // to prevent all IA objects doing this in synchrony
928 if (dt_elev_count < (3.0) + (rand() % 10))
933 // Only do the proper hitlist stuff if we are within visible range of the viewer.
935 double visibility_meters = fgGetDouble("/environment/visibility-m");
937 FGViewer* vw = globals->get_current_view();
938 double course, distance;
940 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
941 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
942 view.CourseAndDistance(current, &course, &distance);
943 if(distance > visibility_meters) {
944 //aip.getSGLocation()->set_cur_elev_m(aptElev);
948 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
949 double range = 500.0;
950 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
951 // Try to shedule tiles for that position.
952 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
955 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
957 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
958 tgt_altitude_ft = alt * SG_METER_TO_FEET;
960 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
961 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
963 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
964 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
969 void FGAIAircraft::setCallSign(const string& s) {
974 void FGAIAircraft::setTACANChannelID(const string& id) {
975 TACAN_channel_id = id;
979 void FGAIAircraft::doGroundAltitude() {
980 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
981 altitude_ft = (tgt_altitude_ft + groundOffset);
983 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
987 void FGAIAircraft::announcePositionToController()
990 //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
992 int leg = fp->getLeg();
994 //if (fp->getCurrentWaypoint()->routeIndex != 0) {
996 //snprintf (buffer, 10, "%d", node);
997 // Note that leg was been incremented after creating the current leg, so we should use
998 // leg numbers here that are one higher than the number that is used to create the leg
1001 case 3: // Taxiing to runway
1002 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
1003 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
1005 case 4: //Take off tower controller
1006 if (trafficRef->getDepartureAirport()->getDynamics())
1008 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
1009 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
1010 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
1011 // << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
1012 // if (controller == 0) {
1013 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
1018 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
1021 case 9: // Taxiing for parking
1022 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
1023 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
1030 if ((controller != prevController) && (prevController != 0)) {
1031 prevController->signOff(getID());
1032 string callsign = trafficRef->getCallSign();
1033 if ( trafficRef->getHeavy())
1034 callsign += "Heavy";
1037 cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
1040 cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
1041 << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
1042 << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
1045 prevController = controller;
1047 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1048 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
1049 trafficRef->getRadius(), leg);
1055 void FGAIAircraft::processATC(FGATCInstruction instruction)
1057 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1058 if (instruction.getHoldPattern ()) {
1062 if (instruction.getHoldPosition ()) {
1065 cerr << trafficRef->getCallSign() << "Holding Position " << endl;
1072 cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
1075 // Change speed Instruction. This can only be excecuted when there is no
1076 // Hold position instruction.
1077 if (instruction.getChangeSpeed ()) {
1078 AccelTo(instruction.getSpeed());
1080 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1083 if (instruction.getChangeHeading ()) {
1085 TurnTo(instruction.getHeading());
1087 if (fp) {hdg_lock = true;}
1089 if (instruction.getChangeAltitude()) {