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 static string tempReg;
48 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
49 // cruise_speed, descent_speed, land_speed
51 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
53 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
55 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
57 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
59 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
61 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0}
65 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
70 groundOffset = trafficRef->getGroundOffset();
80 // set heading and altitude locks
84 headingChangeRate = 0.0;
88 FGAIAircraft::~FGAIAircraft() {
93 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
97 FGAIBase::readFromScenario(scFileNode);
99 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
100 setFlightPlan(scFileNode->getStringValue("flightplan"),
101 scFileNode->getBoolValue("repeat", false));
102 setCallSign(scFileNode->getStringValue("callsign"));
103 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
107 bool FGAIAircraft::init() {
108 //refuel_node = fgGetNode("systems/refuel/contact", true);
109 return FGAIBase::init();
113 void FGAIAircraft::bind() {
116 props->tie("controls/gear/gear-down",
117 SGRawValueMethods<FGAIAircraft,bool>(*this,
118 &FGAIAircraft::_getGearDown));
119 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
120 props->setStringValue("callsign", callsign.c_str());
121 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
122 props->setBoolValue("tanker",isTanker);
126 void FGAIAircraft::unbind() {
129 props->untie("controls/gear/gear-down");
130 props->untie("refuel/contact");
134 void FGAIAircraft::update(double dt) {
135 FGAIBase::update(dt);
141 void FGAIAircraft::setPerformance(const std::string& acclass) {
142 if (acclass == "light") {
143 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
144 } else if (acclass == "ww2_fighter") {
145 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
146 } else if (acclass == "jet_transport") {
147 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
148 } else if (acclass == "jet_fighter") {
149 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
150 } else if (acclass == "tanker") {
151 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
154 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
159 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
165 void FGAIAircraft::Run(double dt) {
167 FGAIAircraft::dt = dt;
170 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
171 ProcessFlightPlan(dt, now);
172 if (now < fp->getStartTime()) {
173 // Do execute Ground elev for inactive aircraft, so they
174 // Are repositioned to the correct ground altitude when the user flies within visibility range.
176 Transform(); // make sure aip is initialized.
177 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
178 //getGroundElev(dt); // Need to do this twice.
179 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
181 //cerr << " Actual altitude " << altitude << endl;
183 pos.setElevationFt(altitude_ft);
188 // no flight plan, update target heading, speed, and altitude
189 // from control properties. These default to the initial
190 // settings in the config file, but can be changed "on the
193 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
194 if ( lat_mode == "roll" ) {
196 = props->getDoubleValue("controls/flight/target-roll" );
200 = props->getDoubleValue("controls/flight/target-hdg" );
205 = props->getStringValue("controls/flight/longitude-mode");
206 if ( lon_mode == "alt" ) {
207 double alt = props->getDoubleValue("controls/flight/target-alt" );
211 = props->getDoubleValue("controls/flight/target-pitch" );
215 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
218 double turn_radius_ft;
219 double turn_circum_ft;
220 double speed_north_deg_sec;
221 double speed_east_deg_sec;
222 double dist_covered_ft;
226 double speed_diff; //= tgt_speed - speed;
228 speed_diff = tgt_speed - speed;
230 speed_diff = groundTargetSpeed - speed;
232 if (fabs(speed_diff) > 0.2) {
233 if (speed_diff > 0.0)
234 speed += performance->accel * dt;
235 if (speed_diff < 0.0) {
236 if (no_roll) { // was (!no_roll) but seems more logical this way (ground brakes).
237 speed -= performance->decel * dt * 3;
239 speed -= performance->decel * dt;
244 // convert speed to degrees per second
245 speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
246 * speed * 1.686 / ft_per_deg_lat;
247 speed_east_deg_sec = sin( hdg / SG_RADIANS_TO_DEGREES )
248 * speed * 1.686 / ft_per_deg_lon;
251 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
252 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
253 //if (!(finite(pos.lat()) && finite(pos.lon())))
255 // cerr << "Position is not finite" << endl;
256 // cerr << "speed = " << speed << endl;
257 // cerr << "dt" << dt << endl;
258 // cerr << "heading " << hdg << endl;
259 // cerr << "speed east " << speed_east_deg_sec << endl;
260 // cerr << "speed nrth " << speed_north_deg_sec << endl;
261 // cerr << "deg_lat " << ft_per_deg_lat << endl;
262 // cerr << "deg_lon " << ft_per_deg_lon << endl;
265 // adjust heading based on current bank angle
270 // double turnConstant;
272 // turnConstant = 0.0088362;
274 // turnConstant = 0.088362;
275 // If on ground, calculate heading change directly
277 double headingDiff = fabs(hdg-tgt_heading);
279 if (headingDiff > 180)
280 headingDiff = fabs(headingDiff - 360);
282 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
283 if (sign(groundTargetSpeed) != sign(tgt_speed))
284 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
286 if (headingDiff > 30.0) {
287 headingChangeRate += dt * sign(roll); // invert if pushed backward
288 // Print some debug statements to find out why aircraft may get stuck
290 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
291 // cerr << "Turning : " << trafficRef->getRegistration()
292 // cerr << " Speed = " << speed << " Heading " << hdg
293 // << " Target Heading " << tgt_heading
294 // << " Lead Distance " << fp->getLeadDistance()
295 // << " Distance to go "
296 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
297 // << "waypoint name " << fp->getCurrentWaypoint()->name
300 if (headingChangeRate > 30)
301 headingChangeRate = 30;
302 else if (headingChangeRate < -30)
303 headingChangeRate = -30;
306 if (fabs(headingChangeRate) > headingDiff)
307 headingChangeRate = headingDiff*sign(roll);
309 headingChangeRate += dt * sign(roll);
311 hdg += headingChangeRate * dt;
312 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
313 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
314 // << headingChangeRate << endl;
317 if (fabs(speed) > 1.0) {
318 turn_radius_ft = 0.088362 * speed * speed
319 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
321 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
323 turn_circum_ft = SGD_2PI * turn_radius_ft;
324 dist_covered_ft = speed * 1.686 * dt;
325 alpha = dist_covered_ft / turn_circum_ft * 360.0;
326 hdg += alpha * sign(roll);
328 while ( hdg > 360.0 ) {
339 // adjust target bank angle if heading lock engaged
341 double bank_sense = 0.0;
342 double diff = fabs(hdg - tgt_heading);
344 diff = fabs(diff - 360);
346 double sum = hdg + diff;
349 if (fabs(sum - tgt_heading) < 1.0) {
350 bank_sense = 1.0; // right turn
352 bank_sense = -1.0; // left turn
355 tgt_roll = diff * bank_sense;
357 tgt_roll = 30.0 * bank_sense;
359 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
360 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
361 // The only way to resolve this is to make them slow down.
362 //if (tempReg.empty())
363 // tempReg = trafficRef->getRegistration();
364 //if (trafficRef->getRegistration() == tempReg) {
365 // cerr << trafficRef->getRegistration()
366 // << " appears to be spinning: " << spinCounter << endl
367 // << " speed " << speed << endl
368 // << " heading " << hdg << endl
369 // << " lead distance " << fp->getLeadDistance() << endl
370 // << " waypoint " << fp->getCurrentWaypoint()->name
371 // << " target heading " << tgt_heading << endl
372 // << " lead in angle " << fp->getLeadInAngle()<< endl
373 // << " roll " << roll << endl
374 // << " target_roll " << tgt_roll << endl;
379 // adjust bank angle, use 9 degrees per second
380 double bank_diff = tgt_roll - roll;
381 if (fabs(bank_diff) > 0.2) {
387 //while (roll > 180) roll -= 360;
388 //while (roll < 180) roll += 360;
391 // adjust altitude (meters) based on current vertical speed (fpm)
392 altitude_ft += vs / 60.0 * dt;
393 pos.setElevationFt(altitude_ft);
395 // adjust target Altitude, based on ground elevation when on ground
400 // find target vertical speed if altitude lock engaged
401 if (alt_lock && use_perf_vs) {
402 if (altitude_ft < tgt_altitude_ft) {
403 tgt_vs = tgt_altitude_ft - altitude_ft;
404 if (tgt_vs > performance->climb_rate)
405 tgt_vs = performance->climb_rate;
407 tgt_vs = tgt_altitude_ft - altitude_ft;
408 if (tgt_vs < (-performance->descent_rate))
409 tgt_vs = -performance->descent_rate;
413 if (alt_lock && !use_perf_vs) {
414 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
416 if (tgt_altitude_ft < altitude_ft)
418 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
419 && (fabs(max_vs) < fabs(tgt_vs)))
422 if (fabs(tgt_vs) < fabs(min_vs))
426 // adjust vertical speed
427 double vs_diff = tgt_vs - vs;
428 if (fabs(vs_diff) > 10.0) {
442 // match pitch angle to vertical speed
449 //###########################//
450 // do calculations for radar //
451 //###########################//
452 double range_ft2 = UpdateRadar(manager);
454 //************************************//
456 //************************************//
459 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
460 && (elevation > 0.0) ) {
461 //refuel_node->setBoolValue(true);
464 //refuel_node->setBoolValue(false);
473 void FGAIAircraft::AccelTo(double speed) {
478 void FGAIAircraft::PitchTo(double angle) {
484 void FGAIAircraft::RollTo(double angle) {
490 void FGAIAircraft::YawTo(double angle) {
495 void FGAIAircraft::ClimbTo(double alt_ft ) {
496 tgt_altitude_ft = alt_ft;
501 void FGAIAircraft::TurnTo(double heading) {
502 tgt_heading = heading;
507 double FGAIAircraft::sign(double x) {
515 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
516 if (!flightplan.empty()) {
517 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
518 fp->setRepeat(repeat);
524 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
530 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
535 eraseWaypoints = true;
536 // cerr << trafficRef->getRegistration();
537 // cerr << "Departure airport " << endl;
538 // dep = trafficRef->getDepartureAirport();
540 // cerr << dep->getId() << endl;
541 // cerr << "Arrival airport " << endl;
542 // arr = trafficRef->getArrivalAirport();
544 // cerr << arr->getId() <<endl << endl;;
546 eraseWaypoints = false;
548 //cerr << "Processing Flightplan" << endl;
549 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
550 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
551 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
552 prev = fp->getPreviousWaypoint();
553 curr = fp->getCurrentWaypoint();
554 next = fp->getNextWaypoint();
557 if (!prev) { //beginning of flightplan, do this initialization once
561 //prev_dist_to_go = HUGE;
562 //cerr << "Before increment " << curr-> name << endl;
563 fp->IncrementWaypoint(eraseWaypoints);
564 //prev = fp->getPreviousWaypoint(); //first waypoint
565 //curr = fp->getCurrentWaypoint(); //second waypoint
566 //next = fp->getNextWaypoint(); //third waypoint (might not exist!)
567 //cerr << "After increment " << prev-> name << endl;
568 if (!(fp->getNextWaypoint()) && trafficRef)
571 //cerr << "After load " << prev-> name << endl;
572 prev = fp->getPreviousWaypoint(); //first waypoint
573 curr = fp->getCurrentWaypoint(); //second waypoint
574 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
575 //cerr << "After load " << prev-> name << endl;
576 setLatitude(prev->latitude);
577 setLongitude(prev->longitude);
578 setSpeed(prev->speed);
579 setAltitude(prev->altitude);
581 if (prev->speed > 0.0)
582 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
584 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
586 // If next doesn't exist, as in incrementally created flightplans for
587 // AI/Trafficmanager created plans,
588 // Make sure lead distance is initialized otherwise
590 fp->setLeadDistance(speed, hdg, curr, next);
592 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
594 tgt_vs = (curr->crossat - prev->altitude)
595 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
596 / 6076.0 / prev->speed*60.0);
597 tgt_altitude_ft = curr->crossat;
600 tgt_altitude_ft = prev->altitude;
602 alt_lock = hdg_lock = true;
603 no_roll = prev->on_ground;
605 Transform(); // make sure aip is initialized.
606 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
607 //getGroundElev(60.1); // Need to do this twice.
608 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
609 doGroundAltitude(); //(tgt_altitude);
612 //cout << "First waypoint: " << prev->name << endl;
613 //cout << " Target speed: " << tgt_speed << endl;
614 //cout << " Target altitude: " << tgt_altitude << endl;
615 //cout << " Target heading: " << tgt_heading << endl << endl;
616 //cerr << "Done Flightplan init" << endl;
618 } // end of initialization
620 // let's only process the flight plan every 100 ms.
621 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
622 //cerr << "done fp dt" << endl;
627 // check to see if we've reached the lead point for our next turn
628 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
630 //cerr << "2" << endl;
631 double lead_dist = fp->getLeadDistance();
632 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
633 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
635 if (lead_dist < fabs(2*speed)) {
636 lead_dist = fabs(2*speed); //don't skip over the waypoint
637 //cerr << "Extending lead distance to " << lead_dist << endl;
639 // FGAirport * apt = trafficRef->getDepartureAirport();
640 // if ((dist_to_go > prev_dist_to_go) && trafficRef && apt) {
641 // if (apt->getId() == string("EHAM"))
642 // cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name << endl
643 // << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
644 // << "Lead distance : " << lead_dist << endl
645 // << "Distance to go: " << dist_to_go << endl;
648 prev_dist_to_go = dist_to_go;
649 //cerr << "2" << endl;
652 //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ", lead_dist: "
653 // << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading
654 // << " speed " << speed << " hdg " << hdg << ". Altitude " << altitude << " TAget alt :"
655 // << tgt_altitude << endl;
657 if ( dist_to_go < lead_dist ) {
658 //prev_dist_to_go = HUGE;
659 // For traffic manager generated aircraft:
660 // check if the aircraft flies of of user range. And adjust the
661 // Current waypoint's elevation according to Terrain Elevation
662 if (curr->finished) { //end of the flight plan
668 //cerr << "Done die end of fp" << endl;
672 // we've reached the lead-point for the waypoint ahead
673 //cerr << "4" << endl;
674 //cerr << "Situation after lead point" << endl;
675 //cerr << "Prviious: " << prev->name << endl;
676 //cerr << "Current : " << curr->name << endl;
677 //cerr << "Next : " << next->name << endl;
679 tgt_heading = fp->getBearing(curr, next);
683 fp->IncrementWaypoint(eraseWaypoints);
684 if (!(fp->getNextWaypoint()) && trafficRef)
687 prev = fp->getPreviousWaypoint();
688 curr = fp->getCurrentWaypoint();
689 next = fp->getNextWaypoint();
691 // Now that we have incremented the waypoints, excute some traffic manager specific code
692 // based on the name of the waypoint we just passed.
694 double userLatitude = fgGetDouble("/position/latitude-deg");
695 double userLongitude = fgGetDouble("/position/longitude-deg");
696 double course, distance;
697 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
698 SGWayPoint user (userLongitude, userLatitude, 0);
699 user.CourseAndDistance(current, &course, &distance);
700 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
702 //cerr << "done fp die out of range" << endl;
706 FGAirport * dep = trafficRef->getDepartureAirport();
707 FGAirport * arr = trafficRef->getArrivalAirport();
708 // At parking the beginning of the airport
709 if (!( dep && arr)) {
714 //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM")))) {
715 // cerr << trafficRef->getRegistration()
716 // << " Enroute from " << dep->getId()
717 // << " to " << arr->getId()
718 // << " just crossed " << prev->name
719 // << " Assigned rwy " << fp->getRunwayId()
720 // << " " << fp->getRunway() << endl;
722 //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
723 // cerr << "Schiphol ground "
724 // << trafficRef->getCallSign();
725 // if (trafficRef->getHeavy())
727 // cerr << ", is type "
728 // << trafficRef->getAircraft()
729 // << " ready to go. IFR to "
730 // << arr->getId() <<endl;
733 if (prev->name == "park2")
734 dep->getDynamics()->releaseParking(fp->getGate());
736 // Some debug messages, specific to testing the Logical networks.
737 // if ((arr->getId() == string("EHAM")) && (prev->name == "Center")) {
738 // cerr << "Schiphol ground "
739 // << trafficRef->getRegistration() << " "
740 // << trafficRef->getCallSign();
741 // if (trafficRef->getHeavy())
743 // cerr << ", arriving from " << dep->getName() ;
744 // cerr << " landed runway "
745 // << fp->getRunway()
746 // << " request taxi to gate "
747 // << arr->getDynamics()->getParkingName(fp->getGate())
750 if (prev->name == "END")
751 fp->setTime(trafficRef->getDepartureTime());
752 //cerr << "5" << endl;
756 //cerr << "Current waypoint" << curr->name << endl;
757 //cerr << "Next waypoint" << next->name << endl;
758 fp->setLeadDistance(speed, tgt_heading, curr, next);
761 //cerr << "5.1" << endl;
762 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
763 tgt_altitude_ft = prev->altitude;
764 if (curr->crossat > -1000.0) {
765 //cerr << "5.1a" << endl;
767 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
768 / 6076.0 / speed*60.0);
769 //cerr << "5.1b" << endl;
770 tgt_altitude_ft = curr->crossat;
772 //cerr << "5.1c" << endl;
774 //cerr << "5.1d" << endl;
775 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
778 //cerr << "6" << endl;
779 tgt_speed = prev->speed;
780 hdg_lock = alt_lock = true;
781 no_roll = prev->on_ground;
782 //cout << "Crossing waypoint: " << prev->name << endl;
783 //cout << " Target speed: " << tgt_speed << endl;
784 //cout << " Target altitude: " << tgt_altitude_ft << endl;
785 //cout << " Target heading: " << tgt_heading << endl << endl;
788 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
789 //cerr << "Bearing = " << calc_bearing << endl;
792 if (calc_bearing > 360)
796 if (finite(calc_bearing)) {
797 double hdg_error = calc_bearing - tgt_heading;
798 if (fabs(hdg_error) > 1.0) {
799 TurnTo( calc_bearing );
803 cerr << "calc_bearing is not a finite number : "
805 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
806 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
807 cerr << "waypoint name " << curr->name;
811 double speed_diff = speed - prevSpeed;
812 // Update the lead distance calculation if speed has changed sufficiently
813 // to prevent spinning (hopefully);
814 if (fabs(speed_diff) > 10) {
816 fp->setLeadDistance(speed, tgt_heading, curr, next);
819 //cerr << "Done Processing FlightPlan"<< endl;
824 bool FGAIAircraft::_getGearDown() const {
825 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
826 && (props->getFloatValue("velocities/airspeed-kt")
827 < performance->land_speed*1.25));
831 void FGAIAircraft::loadNextLeg() {
833 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
835 //FGAIModelEntity entity;
836 //entity.m_class = "jet_transport";
837 //entity.path = modelPath.c_str();
838 //entity.flightplan = "none";
839 //entity.latitude = _getLatitude();
840 //entity.longitude = _getLongitude();
841 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
842 //entity.speed = 450; // HACK ALERT
843 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
845 if ((leg = fp->getLeg()) == 10) {
849 //cerr << "Resetting leg : " << leg << endl;
853 //cerr << "Creating leg number : " << leg << endl;
854 FGAirport *dep = trafficRef->getDepartureAirport();
855 FGAirport *arr = trafficRef->getArrivalAirport();
858 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
860 // cerr << "Departure " << dep->getId() << endl;
862 // cerr << "Arrival " << arr->getId() << endl;
865 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
866 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
871 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
872 trafficRef->getSpeed(),
876 trafficRef->getRadius(),
877 trafficRef->getFlightType(),
880 //prev = fp->getPreviousWaypoint();
881 //curr = fp->getCurrentWaypoint();
882 //next = fp->getNextWaypoint();
883 //cerr << "25" << endl;
886 // //cerr << "Next waypoint" << next->name << endl;
887 // fp->setLeadDistance(speed, tgt_heading, curr, next);
889 //cerr << "25.1" << endl;
890 //if (curr->crossat > -1000.0) {
891 // //cerr << "25.1a" << endl;
892 // use_perf_vs = false;
894 // tgt_vs = (curr->crossat - altitude_ft)/
895 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
896 // //cerr << "25.1b" << endl;
897 // tgt_altitude_ft = curr->crossat;
899 // //cerr << "25.1c" << endl;
900 // use_perf_vs = true;
901 // //cerr << "25.1d" << endl;
902 // tgt_altitude_ft = prev->altitude;
903 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
905 //cerr << "26" << endl;
906 //tgt_speed = prev->speed;
907 //hdg_lock = alt_lock = true;
908 //no_roll = prev->on_ground;
913 //entity.fp = new FGAIFlightPlan(&entity,
915 // trafficRef->getDepartureTime(),
916 // trafficRef->getDepartureAirport(),
917 // trafficRef->getArrivalAirport(),
921 //SetFlightPlan(entity.fp);
925 // Note: This code is copied from David Luff's AILocalTraffic
926 // Warning - ground elev determination is CPU intensive
927 // Either this function or the logic of how often it is called
928 // will almost certainly change.
930 void FGAIAircraft::getGroundElev(double dt) {
933 // Update minimally every three secs, but add some randomness
934 // to prevent all IA objects doing this in synchrony
935 if (dt_elev_count < (3.0) + (rand() % 10))
940 // Only do the proper hitlist stuff if we are within visible range of the viewer.
942 double visibility_meters = fgGetDouble("/environment/visibility-m");
944 FGViewer* vw = globals->get_current_view();
945 double course, distance;
947 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
948 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
949 view.CourseAndDistance(current, &course, &distance);
950 if(distance > visibility_meters) {
951 //aip.getSGLocation()->set_cur_elev_m(aptElev);
955 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
956 double range = 500.0;
957 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
958 // Try to shedule tiles for that position.
959 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
962 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
964 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
965 tgt_altitude_ft = alt * SG_METER_TO_FEET;
967 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
968 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
970 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
971 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
976 void FGAIAircraft::setCallSign(const string& s) {
981 void FGAIAircraft::setTACANChannelID(const string& id) {
982 TACAN_channel_id = id;
986 void FGAIAircraft::doGroundAltitude() {
987 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
988 altitude_ft = (tgt_altitude_ft + groundOffset);
990 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);