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},
62 // ufo (extreme accel/decel)
63 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
67 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
72 groundOffset = trafficRef->getGroundOffset();
82 // set heading and altitude locks
86 headingChangeRate = 0.0;
90 FGAIAircraft::~FGAIAircraft() {
95 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
99 FGAIBase::readFromScenario(scFileNode);
101 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
102 setFlightPlan(scFileNode->getStringValue("flightplan"),
103 scFileNode->getBoolValue("repeat", false));
104 setCallSign(scFileNode->getStringValue("callsign"));
105 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
109 bool FGAIAircraft::init() {
110 //refuel_node = fgGetNode("systems/refuel/contact", true);
111 return FGAIBase::init();
115 void FGAIAircraft::bind() {
118 props->tie("controls/gear/gear-down",
119 SGRawValueMethods<FGAIAircraft,bool>(*this,
120 &FGAIAircraft::_getGearDown));
121 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
122 props->setStringValue("callsign", callsign.c_str());
123 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
124 props->setBoolValue("tanker",isTanker);
128 void FGAIAircraft::unbind() {
131 props->untie("controls/gear/gear-down");
132 props->untie("refuel/contact");
136 void FGAIAircraft::update(double dt) {
137 FGAIBase::update(dt);
143 void FGAIAircraft::setPerformance(const std::string& acclass) {
144 if (acclass == "light") {
145 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
146 } else if (acclass == "ww2_fighter") {
147 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
148 } else if (acclass == "jet_transport") {
149 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
150 } else if (acclass == "jet_fighter") {
151 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
152 } else if (acclass == "tanker") {
153 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
155 } else if (acclass == "ufo") {
156 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
158 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
163 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
169 void FGAIAircraft::Run(double dt) {
171 FGAIAircraft::dt = dt;
174 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
175 ProcessFlightPlan(dt, now);
176 if (now < fp->getStartTime()) {
177 // Do execute Ground elev for inactive aircraft, so they
178 // Are repositioned to the correct ground altitude when the user flies within visibility range.
180 Transform(); // make sure aip is initialized.
181 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
182 //getGroundElev(dt); // Need to do this twice.
183 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
185 //cerr << " Actual altitude " << altitude << endl;
187 pos.setElevationFt(altitude_ft);
192 // no flight plan, update target heading, speed, and altitude
193 // from control properties. These default to the initial
194 // settings in the config file, but can be changed "on the
197 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
198 if ( lat_mode == "roll" ) {
200 = props->getDoubleValue("controls/flight/target-roll" );
204 = props->getDoubleValue("controls/flight/target-hdg" );
209 = props->getStringValue("controls/flight/longitude-mode");
210 if ( lon_mode == "alt" ) {
211 double alt = props->getDoubleValue("controls/flight/target-alt" );
215 = props->getDoubleValue("controls/flight/target-pitch" );
219 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
222 double turn_radius_ft;
223 double turn_circum_ft;
224 double speed_north_deg_sec;
225 double speed_east_deg_sec;
226 double dist_covered_ft;
230 double speed_diff; //= tgt_speed - speed;
232 speed_diff = tgt_speed - speed;
234 speed_diff = groundTargetSpeed - speed;
236 if (fabs(speed_diff) > 0.2) {
237 if (speed_diff > 0.0)
238 speed += performance->accel * dt;
239 if (speed_diff < 0.0) {
240 if (no_roll) { // was (!no_roll) but seems more logical this way (ground brakes).
241 speed -= performance->decel * dt * 3;
243 speed -= performance->decel * dt;
248 // convert speed to degrees per second
249 speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
250 * speed * 1.686 / ft_per_deg_lat;
251 speed_east_deg_sec = sin( hdg / SG_RADIANS_TO_DEGREES )
252 * speed * 1.686 / ft_per_deg_lon;
255 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
256 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
257 //if (!(finite(pos.lat()) && finite(pos.lon())))
259 // cerr << "Position is not finite" << endl;
260 // cerr << "speed = " << speed << endl;
261 // cerr << "dt" << dt << endl;
262 // cerr << "heading " << hdg << endl;
263 // cerr << "speed east " << speed_east_deg_sec << endl;
264 // cerr << "speed nrth " << speed_north_deg_sec << endl;
265 // cerr << "deg_lat " << ft_per_deg_lat << endl;
266 // cerr << "deg_lon " << ft_per_deg_lon << endl;
269 // adjust heading based on current bank angle
274 // double turnConstant;
276 // turnConstant = 0.0088362;
278 // turnConstant = 0.088362;
279 // If on ground, calculate heading change directly
281 double headingDiff = fabs(hdg-tgt_heading);
283 if (headingDiff > 180)
284 headingDiff = fabs(headingDiff - 360);
286 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
287 if (sign(groundTargetSpeed) != sign(tgt_speed))
288 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
290 if (headingDiff > 30.0) {
291 headingChangeRate += dt * sign(roll); // invert if pushed backward
292 // Print some debug statements to find out why aircraft may get stuck
294 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
295 // cerr << "Turning : " << trafficRef->getRegistration()
296 // cerr << " Speed = " << speed << " Heading " << hdg
297 // << " Target Heading " << tgt_heading
298 // << " Lead Distance " << fp->getLeadDistance()
299 // << " Distance to go "
300 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
301 // << "waypoint name " << fp->getCurrentWaypoint()->name
304 if (headingChangeRate > 30)
305 headingChangeRate = 30;
306 else if (headingChangeRate < -30)
307 headingChangeRate = -30;
310 if (fabs(headingChangeRate) > headingDiff)
311 headingChangeRate = headingDiff*sign(roll);
313 headingChangeRate += dt * sign(roll);
315 hdg += headingChangeRate * dt;
316 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
317 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
318 // << headingChangeRate << endl;
321 if (fabs(speed) > 1.0) {
322 turn_radius_ft = 0.088362 * speed * speed
323 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
325 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
327 turn_circum_ft = SGD_2PI * turn_radius_ft;
328 dist_covered_ft = speed * 1.686 * dt;
329 alpha = dist_covered_ft / turn_circum_ft * 360.0;
330 hdg += alpha * sign(roll);
332 while ( hdg > 360.0 ) {
343 // adjust target bank angle if heading lock engaged
345 double bank_sense = 0.0;
346 double diff = fabs(hdg - tgt_heading);
348 diff = fabs(diff - 360);
350 double sum = hdg + diff;
353 if (fabs(sum - tgt_heading) < 1.0) {
354 bank_sense = 1.0; // right turn
356 bank_sense = -1.0; // left turn
359 tgt_roll = diff * bank_sense;
361 tgt_roll = 30.0 * bank_sense;
363 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
364 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
365 // The only way to resolve this is to make them slow down.
366 //if (tempReg.empty())
367 // tempReg = trafficRef->getRegistration();
368 //if (trafficRef->getRegistration() == tempReg) {
369 // cerr << trafficRef->getRegistration()
370 // << " appears to be spinning: " << spinCounter << endl
371 // << " speed " << speed << endl
372 // << " heading " << hdg << endl
373 // << " lead distance " << fp->getLeadDistance() << endl
374 // << " waypoint " << fp->getCurrentWaypoint()->name
375 // << " target heading " << tgt_heading << endl
376 // << " lead in angle " << fp->getLeadInAngle()<< endl
377 // << " roll " << roll << endl
378 // << " target_roll " << tgt_roll << endl;
383 // adjust bank angle, use 9 degrees per second
384 double bank_diff = tgt_roll - roll;
385 if (fabs(bank_diff) > 0.2) {
391 //while (roll > 180) roll -= 360;
392 //while (roll < 180) roll += 360;
395 // adjust altitude (meters) based on current vertical speed (fpm)
396 altitude_ft += vs / 60.0 * dt;
397 pos.setElevationFt(altitude_ft);
399 // adjust target Altitude, based on ground elevation when on ground
404 // find target vertical speed if altitude lock engaged
405 if (alt_lock && use_perf_vs) {
406 if (altitude_ft < tgt_altitude_ft) {
407 tgt_vs = tgt_altitude_ft - altitude_ft;
408 if (tgt_vs > performance->climb_rate)
409 tgt_vs = performance->climb_rate;
411 tgt_vs = tgt_altitude_ft - altitude_ft;
412 if (tgt_vs < (-performance->descent_rate))
413 tgt_vs = -performance->descent_rate;
417 if (alt_lock && !use_perf_vs) {
418 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
420 if (tgt_altitude_ft < altitude_ft)
422 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
423 && (fabs(max_vs) < fabs(tgt_vs)))
426 if (fabs(tgt_vs) < fabs(min_vs))
430 // adjust vertical speed
431 double vs_diff = tgt_vs - vs;
432 if (fabs(vs_diff) > 10.0) {
446 // match pitch angle to vertical speed
453 //###########################//
454 // do calculations for radar //
455 //###########################//
456 double range_ft2 = UpdateRadar(manager);
458 //************************************//
460 //************************************//
463 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
464 && (elevation > 0.0) ) {
465 //refuel_node->setBoolValue(true);
468 //refuel_node->setBoolValue(false);
477 void FGAIAircraft::AccelTo(double speed) {
482 void FGAIAircraft::PitchTo(double angle) {
488 void FGAIAircraft::RollTo(double angle) {
494 void FGAIAircraft::YawTo(double angle) {
499 void FGAIAircraft::ClimbTo(double alt_ft ) {
500 tgt_altitude_ft = alt_ft;
505 void FGAIAircraft::TurnTo(double heading) {
506 tgt_heading = heading;
511 double FGAIAircraft::sign(double x) {
519 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
520 if (!flightplan.empty()) {
521 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
522 fp->setRepeat(repeat);
528 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
534 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
539 eraseWaypoints = true;
540 // cerr << trafficRef->getRegistration();
541 // cerr << "Departure airport " << endl;
542 // dep = trafficRef->getDepartureAirport();
544 // cerr << dep->getId() << endl;
545 // cerr << "Arrival airport " << endl;
546 // arr = trafficRef->getArrivalAirport();
548 // cerr << arr->getId() <<endl << endl;;
550 eraseWaypoints = false;
552 //cerr << "Processing Flightplan" << endl;
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
556 prev = fp->getPreviousWaypoint();
557 curr = fp->getCurrentWaypoint();
558 next = fp->getNextWaypoint();
561 if (!prev) { //beginning of flightplan, do this initialization once
565 //prev_dist_to_go = HUGE;
566 //cerr << "Before increment " << curr-> name << endl;
567 fp->IncrementWaypoint(eraseWaypoints);
568 //prev = fp->getPreviousWaypoint(); //first waypoint
569 //curr = fp->getCurrentWaypoint(); //second waypoint
570 //next = fp->getNextWaypoint(); //third waypoint (might not exist!)
571 //cerr << "After increment " << prev-> name << endl;
572 if (!(fp->getNextWaypoint()) && trafficRef)
575 //cerr << "After load " << prev-> name << endl;
576 prev = fp->getPreviousWaypoint(); //first waypoint
577 curr = fp->getCurrentWaypoint(); //second waypoint
578 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
579 //cerr << "After load " << prev-> name << endl;
580 setLatitude(prev->latitude);
581 setLongitude(prev->longitude);
582 setSpeed(prev->speed);
583 setAltitude(prev->altitude);
585 if (prev->speed > 0.0)
586 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
588 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
590 // If next doesn't exist, as in incrementally created flightplans for
591 // AI/Trafficmanager created plans,
592 // Make sure lead distance is initialized otherwise
594 fp->setLeadDistance(speed, hdg, curr, next);
596 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
598 tgt_vs = (curr->crossat - prev->altitude)
599 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
600 / 6076.0 / prev->speed*60.0);
601 tgt_altitude_ft = curr->crossat;
604 tgt_altitude_ft = prev->altitude;
606 alt_lock = hdg_lock = true;
607 no_roll = prev->on_ground;
609 Transform(); // make sure aip is initialized.
610 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
611 //getGroundElev(60.1); // Need to do this twice.
612 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
613 doGroundAltitude(); //(tgt_altitude);
616 //cout << "First waypoint: " << prev->name << endl;
617 //cout << " Target speed: " << tgt_speed << endl;
618 //cout << " Target altitude: " << tgt_altitude << endl;
619 //cout << " Target heading: " << tgt_heading << endl << endl;
620 //cerr << "Done Flightplan init" << endl;
622 } // end of initialization
624 // let's only process the flight plan every 100 ms.
625 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
626 //cerr << "done fp dt" << endl;
631 // check to see if we've reached the lead point for our next turn
632 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
634 //cerr << "2" << endl;
635 double lead_dist = fp->getLeadDistance();
636 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
637 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
639 if (lead_dist < fabs(2*speed)) {
640 lead_dist = fabs(2*speed); //don't skip over the waypoint
641 //cerr << "Extending lead distance to " << lead_dist << endl;
643 // FGAirport * apt = trafficRef->getDepartureAirport();
644 // if ((dist_to_go > prev_dist_to_go) && trafficRef && apt) {
645 // if (apt->getId() == string("EHAM"))
646 // cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name << endl
647 // << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
648 // << "Lead distance : " << lead_dist << endl
649 // << "Distance to go: " << dist_to_go << endl;
652 prev_dist_to_go = dist_to_go;
653 //cerr << "2" << endl;
656 //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ", lead_dist: "
657 // << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading
658 // << " speed " << speed << " hdg " << hdg << ". Altitude " << altitude << " TAget alt :"
659 // << tgt_altitude << endl;
661 if ( dist_to_go < lead_dist ) {
662 //prev_dist_to_go = HUGE;
663 // For traffic manager generated aircraft:
664 // check if the aircraft flies of of user range. And adjust the
665 // Current waypoint's elevation according to Terrain Elevation
666 if (curr->finished) { //end of the flight plan
672 //cerr << "Done die end of fp" << endl;
676 // we've reached the lead-point for the waypoint ahead
677 //cerr << "4" << endl;
678 //cerr << "Situation after lead point" << endl;
679 //cerr << "Prviious: " << prev->name << endl;
680 //cerr << "Current : " << curr->name << endl;
681 //cerr << "Next : " << next->name << endl;
683 tgt_heading = fp->getBearing(curr, next);
687 fp->IncrementWaypoint(eraseWaypoints);
688 if (!(fp->getNextWaypoint()) && trafficRef)
691 prev = fp->getPreviousWaypoint();
692 curr = fp->getCurrentWaypoint();
693 next = fp->getNextWaypoint();
695 // Now that we have incremented the waypoints, excute some traffic manager specific code
696 // based on the name of the waypoint we just passed.
698 double userLatitude = fgGetDouble("/position/latitude-deg");
699 double userLongitude = fgGetDouble("/position/longitude-deg");
700 double course, distance;
701 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
702 SGWayPoint user (userLongitude, userLatitude, 0);
703 user.CourseAndDistance(current, &course, &distance);
704 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
706 //cerr << "done fp die out of range" << endl;
710 FGAirport * dep = trafficRef->getDepartureAirport();
711 FGAirport * arr = trafficRef->getArrivalAirport();
712 // At parking the beginning of the airport
713 if (!( dep && arr)) {
718 //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM")))) {
719 // cerr << trafficRef->getRegistration()
720 // << " Enroute from " << dep->getId()
721 // << " to " << arr->getId()
722 // << " just crossed " << prev->name
723 // << " Assigned rwy " << fp->getRunwayId()
724 // << " " << fp->getRunway() << endl;
726 //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
727 // cerr << "Schiphol ground "
728 // << trafficRef->getCallSign();
729 // if (trafficRef->getHeavy())
731 // cerr << ", is type "
732 // << trafficRef->getAircraft()
733 // << " ready to go. IFR to "
734 // << arr->getId() <<endl;
737 if (prev->name == "park2")
738 dep->getDynamics()->releaseParking(fp->getGate());
740 // Some debug messages, specific to testing the Logical networks.
741 // if ((arr->getId() == string("EHAM")) && (prev->name == "Center")) {
742 // cerr << "Schiphol ground "
743 // << trafficRef->getRegistration() << " "
744 // << trafficRef->getCallSign();
745 // if (trafficRef->getHeavy())
747 // cerr << ", arriving from " << dep->getName() ;
748 // cerr << " landed runway "
749 // << fp->getRunway()
750 // << " request taxi to gate "
751 // << arr->getDynamics()->getParkingName(fp->getGate())
754 if (prev->name == "END")
755 fp->setTime(trafficRef->getDepartureTime());
756 //cerr << "5" << endl;
760 //cerr << "Current waypoint" << curr->name << endl;
761 //cerr << "Next waypoint" << next->name << endl;
762 fp->setLeadDistance(speed, tgt_heading, curr, next);
765 //cerr << "5.1" << endl;
766 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
767 tgt_altitude_ft = prev->altitude;
768 if (curr->crossat > -1000.0) {
769 //cerr << "5.1a" << endl;
771 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
772 / 6076.0 / speed*60.0);
773 //cerr << "5.1b" << endl;
774 tgt_altitude_ft = curr->crossat;
776 //cerr << "5.1c" << endl;
778 //cerr << "5.1d" << endl;
779 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
782 //cerr << "6" << endl;
783 tgt_speed = prev->speed;
784 hdg_lock = alt_lock = true;
785 no_roll = prev->on_ground;
786 //cout << "Crossing waypoint: " << prev->name << endl;
787 //cout << " Target speed: " << tgt_speed << endl;
788 //cout << " Target altitude: " << tgt_altitude_ft << endl;
789 //cout << " Target heading: " << tgt_heading << endl << endl;
792 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
793 //cerr << "Bearing = " << calc_bearing << endl;
796 if (calc_bearing > 360)
800 if (finite(calc_bearing)) {
801 double hdg_error = calc_bearing - tgt_heading;
802 if (fabs(hdg_error) > 1.0) {
803 TurnTo( calc_bearing );
807 cerr << "calc_bearing is not a finite number : "
809 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
810 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
811 cerr << "waypoint name " << curr->name;
815 double speed_diff = speed - prevSpeed;
816 // Update the lead distance calculation if speed has changed sufficiently
817 // to prevent spinning (hopefully);
818 if (fabs(speed_diff) > 10) {
820 fp->setLeadDistance(speed, tgt_heading, curr, next);
823 //cerr << "Done Processing FlightPlan"<< endl;
828 bool FGAIAircraft::_getGearDown() const {
829 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
830 && (props->getFloatValue("velocities/airspeed-kt")
831 < performance->land_speed*1.25));
835 void FGAIAircraft::loadNextLeg() {
837 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
839 //FGAIModelEntity entity;
840 //entity.m_class = "jet_transport";
841 //entity.path = modelPath.c_str();
842 //entity.flightplan = "none";
843 //entity.latitude = _getLatitude();
844 //entity.longitude = _getLongitude();
845 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
846 //entity.speed = 450; // HACK ALERT
847 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
849 if ((leg = fp->getLeg()) == 10) {
853 //cerr << "Resetting leg : " << leg << endl;
857 //cerr << "Creating leg number : " << leg << endl;
858 FGAirport *dep = trafficRef->getDepartureAirport();
859 FGAirport *arr = trafficRef->getArrivalAirport();
862 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
864 // cerr << "Departure " << dep->getId() << endl;
866 // cerr << "Arrival " << arr->getId() << endl;
869 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
870 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
875 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
876 trafficRef->getSpeed(),
880 trafficRef->getRadius(),
881 trafficRef->getFlightType(),
884 //prev = fp->getPreviousWaypoint();
885 //curr = fp->getCurrentWaypoint();
886 //next = fp->getNextWaypoint();
887 //cerr << "25" << endl;
890 // //cerr << "Next waypoint" << next->name << endl;
891 // fp->setLeadDistance(speed, tgt_heading, curr, next);
893 //cerr << "25.1" << endl;
894 //if (curr->crossat > -1000.0) {
895 // //cerr << "25.1a" << endl;
896 // use_perf_vs = false;
898 // tgt_vs = (curr->crossat - altitude_ft)/
899 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
900 // //cerr << "25.1b" << endl;
901 // tgt_altitude_ft = curr->crossat;
903 // //cerr << "25.1c" << endl;
904 // use_perf_vs = true;
905 // //cerr << "25.1d" << endl;
906 // tgt_altitude_ft = prev->altitude;
907 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
909 //cerr << "26" << endl;
910 //tgt_speed = prev->speed;
911 //hdg_lock = alt_lock = true;
912 //no_roll = prev->on_ground;
917 //entity.fp = new FGAIFlightPlan(&entity,
919 // trafficRef->getDepartureTime(),
920 // trafficRef->getDepartureAirport(),
921 // trafficRef->getArrivalAirport(),
925 //SetFlightPlan(entity.fp);
929 // Note: This code is copied from David Luff's AILocalTraffic
930 // Warning - ground elev determination is CPU intensive
931 // Either this function or the logic of how often it is called
932 // will almost certainly change.
934 void FGAIAircraft::getGroundElev(double dt) {
937 // Update minimally every three secs, but add some randomness
938 // to prevent all IA objects doing this in synchrony
939 if (dt_elev_count < (3.0) + (rand() % 10))
944 // Only do the proper hitlist stuff if we are within visible range of the viewer.
946 double visibility_meters = fgGetDouble("/environment/visibility-m");
948 FGViewer* vw = globals->get_current_view();
949 double course, distance;
951 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
952 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
953 view.CourseAndDistance(current, &course, &distance);
954 if(distance > visibility_meters) {
955 //aip.getSGLocation()->set_cur_elev_m(aptElev);
959 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
960 double range = 500.0;
961 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
962 // Try to shedule tiles for that position.
963 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
966 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
968 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
969 tgt_altitude_ft = alt * SG_METER_TO_FEET;
971 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
972 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
974 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
975 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
980 void FGAIAircraft::setCallSign(const string& s) {
985 void FGAIAircraft::setTACANChannelID(const string& id) {
986 TACAN_channel_id = id;
990 void FGAIAircraft::doGroundAltitude() {
991 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
992 altitude_ft = (tgt_altitude_ft + groundOffset);
994 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);