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
196 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
197 if ( lat_mode == "roll" ) {
199 = props->getDoubleValue("controls/flight/target-roll" );
203 = props->getDoubleValue("controls/flight/target-hdg" );
208 = props->getStringValue("controls/flight/longitude-mode");
209 if ( lon_mode == "alt" ) {
210 double alt = props->getDoubleValue("controls/flight/target-alt" );
214 = props->getDoubleValue("controls/flight/target-pitch" );
218 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
221 double turn_radius_ft;
222 double turn_circum_ft;
223 double speed_north_deg_sec;
224 double speed_east_deg_sec;
225 double dist_covered_ft;
229 double speed_diff; //= tgt_speed - speed;
231 speed_diff = tgt_speed - speed;
233 speed_diff = groundTargetSpeed - speed;
236 if (speed_diff > 0.0) {
237 speed += performance->accel * dt;
238 if (no_roll) { // apply overshoot correction
239 if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
241 if ( speed > tgt_speed ) speed = tgt_speed;
243 } else if (speed_diff < 0.0) {
245 // on ground (aircraft can't roll)
246 // deceleration performance is better due to wheel brakes.
247 speed -= performance->decel * dt * 3;
249 speed -= performance->decel * dt;
251 if (no_roll) { // apply overshoot correction
252 if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
254 if ( speed < tgt_speed ) speed = tgt_speed;
259 // convert speed to degrees per second
260 speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
261 * speed * 1.686 / ft_per_deg_lat;
262 speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
263 * speed * 1.686 / ft_per_deg_lon;
266 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
267 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
269 /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
270 dt, hdg, speed, ft_per_deg_lat,
271 cos( hdg * SGD_DEGREES_TO_RADIANS ),
272 speed * 1.686 / ft_per_deg_lat,
273 speed_north_deg_sec, speed_east_deg_sec,
274 pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
276 //if (!(finite(pos.lat()) && finite(pos.lon())))
278 // cerr << "Position is not finite" << endl;
279 // cerr << "speed = " << speed << endl;
280 // cerr << "dt" << dt << endl;
281 // cerr << "heading " << hdg << endl;
282 // cerr << "speed east " << speed_east_deg_sec << endl;
283 // cerr << "speed nrth " << speed_north_deg_sec << endl;
284 // cerr << "deg_lat " << ft_per_deg_lat << endl;
285 // cerr << "deg_lon " << ft_per_deg_lon << endl;
288 // adjust heading based on current bank angle
293 // double turnConstant;
295 // turnConstant = 0.0088362;
297 // turnConstant = 0.088362;
298 // If on ground, calculate heading change directly
300 double headingDiff = fabs(hdg-tgt_heading);
302 if (headingDiff > 180)
303 headingDiff = fabs(headingDiff - 360);
305 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
306 if (sign(groundTargetSpeed) != sign(tgt_speed))
307 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
309 if (headingDiff > 30.0) {
310 headingChangeRate += dt * sign(roll); // invert if pushed backward
311 // Print some debug statements to find out why aircraft may get stuck
313 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
314 // cerr << "Turning : " << trafficRef->getRegistration()
315 // cerr << " Speed = " << speed << " Heading " << hdg
316 // << " Target Heading " << tgt_heading
317 // << " Lead Distance " << fp->getLeadDistance()
318 // << " Distance to go "
319 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
320 // << "waypoint name " << fp->getCurrentWaypoint()->name
323 if (headingChangeRate > 30)
324 headingChangeRate = 30;
325 else if (headingChangeRate < -30)
326 headingChangeRate = -30;
329 if (fabs(headingChangeRate) > headingDiff)
330 headingChangeRate = headingDiff*sign(roll);
332 headingChangeRate += dt * sign(roll);
334 hdg += headingChangeRate * dt;
335 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
336 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
337 // << headingChangeRate << endl;
340 if (fabs(speed) > 1.0) {
341 turn_radius_ft = 0.088362 * speed * speed
342 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
344 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
346 turn_circum_ft = SGD_2PI * turn_radius_ft;
347 dist_covered_ft = speed * 1.686 * dt;
348 alpha = dist_covered_ft / turn_circum_ft * 360.0;
349 hdg += alpha * sign(roll);
351 while ( hdg > 360.0 ) {
362 // adjust target bank angle if heading lock engaged
364 double bank_sense = 0.0;
365 double diff = fabs(hdg - tgt_heading);
367 diff = fabs(diff - 360);
369 double sum = hdg + diff;
372 if (fabs(sum - tgt_heading) < 1.0) {
373 bank_sense = 1.0; // right turn
375 bank_sense = -1.0; // left turn
378 tgt_roll = diff * bank_sense;
380 tgt_roll = 30.0 * bank_sense;
382 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
383 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
384 // The only way to resolve this is to make them slow down.
385 //if (tempReg.empty())
386 // tempReg = trafficRef->getRegistration();
387 //if (trafficRef->getRegistration() == tempReg) {
388 // cerr << trafficRef->getRegistration()
389 // << " appears to be spinning: " << spinCounter << endl
390 // << " speed " << speed << endl
391 // << " heading " << hdg << endl
392 // << " lead distance " << fp->getLeadDistance() << endl
393 // << " waypoint " << fp->getCurrentWaypoint()->name
394 // << " target heading " << tgt_heading << endl
395 // << " lead in angle " << fp->getLeadInAngle()<< endl
396 // << " roll " << roll << endl
397 // << " target_roll " << tgt_roll << endl;
402 // adjust bank angle, use 9 degrees per second
403 double bank_diff = tgt_roll - roll;
404 if (fabs(bank_diff) > 0.2) {
410 //while (roll > 180) roll -= 360;
411 //while (roll < 180) roll += 360;
414 // adjust altitude (meters) based on current vertical speed (fpm)
415 altitude_ft += vs / 60.0 * dt;
416 pos.setElevationFt(altitude_ft);
418 // adjust target Altitude, based on ground elevation when on ground
423 // find target vertical speed if altitude lock engaged
424 if (alt_lock && use_perf_vs) {
425 if (altitude_ft < tgt_altitude_ft) {
426 tgt_vs = tgt_altitude_ft - altitude_ft;
427 if (tgt_vs > performance->climb_rate)
428 tgt_vs = performance->climb_rate;
430 tgt_vs = tgt_altitude_ft - altitude_ft;
431 if (tgt_vs < (-performance->descent_rate))
432 tgt_vs = -performance->descent_rate;
436 if (alt_lock && !use_perf_vs) {
437 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
439 if (tgt_altitude_ft < altitude_ft)
441 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
442 && (fabs(max_vs) < fabs(tgt_vs)))
445 if (fabs(tgt_vs) < fabs(min_vs))
449 // adjust vertical speed
450 double vs_diff = tgt_vs - vs;
451 if (fabs(vs_diff) > 10.0) {
465 // match pitch angle to vertical speed
472 //###########################//
473 // do calculations for radar //
474 //###########################//
475 double range_ft2 = UpdateRadar(manager);
477 //************************************//
479 //************************************//
482 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
483 && (elevation > 0.0) ) {
484 //refuel_node->setBoolValue(true);
487 //refuel_node->setBoolValue(false);
496 void FGAIAircraft::AccelTo(double speed) {
501 void FGAIAircraft::PitchTo(double angle) {
507 void FGAIAircraft::RollTo(double angle) {
513 void FGAIAircraft::YawTo(double angle) {
518 void FGAIAircraft::ClimbTo(double alt_ft ) {
519 tgt_altitude_ft = alt_ft;
524 void FGAIAircraft::TurnTo(double heading) {
525 tgt_heading = heading;
530 double FGAIAircraft::sign(double x) {
538 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
539 if (!flightplan.empty()) {
540 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
541 fp->setRepeat(repeat);
547 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
553 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
558 eraseWaypoints = true;
559 // cerr << trafficRef->getRegistration();
560 // cerr << "Departure airport " << endl;
561 // dep = trafficRef->getDepartureAirport();
563 // cerr << dep->getId() << endl;
564 // cerr << "Arrival airport " << endl;
565 // arr = trafficRef->getArrivalAirport();
567 // cerr << arr->getId() <<endl << endl;;
569 eraseWaypoints = false;
571 //cerr << "Processing Flightplan" << endl;
572 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
573 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
574 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
575 prev = fp->getPreviousWaypoint();
576 curr = fp->getCurrentWaypoint();
577 next = fp->getNextWaypoint();
580 if (!prev) { //beginning of flightplan, do this initialization once
584 //prev_dist_to_go = HUGE;
585 //cerr << "Before increment " << curr-> name << endl;
586 fp->IncrementWaypoint(eraseWaypoints);
587 //prev = fp->getPreviousWaypoint(); //first waypoint
588 //curr = fp->getCurrentWaypoint(); //second waypoint
589 //next = fp->getNextWaypoint(); //third waypoint (might not exist!)
590 //cerr << "After increment " << prev-> name << endl;
591 if (!(fp->getNextWaypoint()) && trafficRef)
594 //cerr << "After load " << prev-> name << endl;
595 prev = fp->getPreviousWaypoint(); //first waypoint
596 curr = fp->getCurrentWaypoint(); //second waypoint
597 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
598 //cerr << "After load " << prev-> name << endl;
599 setLatitude(prev->latitude);
600 setLongitude(prev->longitude);
601 setSpeed(prev->speed);
602 setAltitude(prev->altitude);
604 if (prev->speed > 0.0)
605 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
607 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
609 // If next doesn't exist, as in incrementally created flightplans for
610 // AI/Trafficmanager created plans,
611 // Make sure lead distance is initialized otherwise
613 fp->setLeadDistance(speed, hdg, curr, next);
615 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
617 tgt_vs = (curr->crossat - prev->altitude)
618 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
619 / 6076.0 / prev->speed*60.0);
620 tgt_altitude_ft = curr->crossat;
623 tgt_altitude_ft = prev->altitude;
625 alt_lock = hdg_lock = true;
626 no_roll = prev->on_ground;
628 Transform(); // make sure aip is initialized.
629 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
630 //getGroundElev(60.1); // Need to do this twice.
631 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
632 doGroundAltitude(); //(tgt_altitude);
635 //cout << "First waypoint: " << prev->name << endl;
636 //cout << " Target speed: " << tgt_speed << endl;
637 //cout << " Target altitude: " << tgt_altitude << endl;
638 //cout << " Target heading: " << tgt_heading << endl << endl;
639 //cerr << "Done Flightplan init" << endl;
641 } // end of initialization
643 // let's only process the flight plan every 100 ms.
644 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
645 //cerr << "done fp dt" << endl;
650 // check to see if we've reached the lead point for our next turn
651 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
653 //cerr << "2" << endl;
654 double lead_dist = fp->getLeadDistance();
655 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
656 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
658 if (lead_dist < fabs(2*speed)) {
659 lead_dist = fabs(2*speed); //don't skip over the waypoint
660 //cerr << "Extending lead distance to " << lead_dist << endl;
662 // FGAirport * apt = trafficRef->getDepartureAirport();
663 // if ((dist_to_go > prev_dist_to_go) && trafficRef && apt) {
664 // if (apt->getId() == string("EHAM"))
665 // cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name << endl
666 // << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
667 // << "Lead distance : " << lead_dist << endl
668 // << "Distance to go: " << dist_to_go << endl;
671 prev_dist_to_go = dist_to_go;
672 //cerr << "2" << endl;
675 //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ", lead_dist: "
676 // << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading
677 // << " speed " << speed << " hdg " << hdg << ". Altitude " << altitude << " TAget alt :"
678 // << tgt_altitude << endl;
680 if ( dist_to_go < lead_dist ) {
681 //prev_dist_to_go = HUGE;
682 // For traffic manager generated aircraft:
683 // check if the aircraft flies of of user range. And adjust the
684 // Current waypoint's elevation according to Terrain Elevation
685 if (curr->finished) { //end of the flight plan
691 //cerr << "Done die end of fp" << endl;
695 // we've reached the lead-point for the waypoint ahead
696 //cerr << "4" << endl;
697 //cerr << "Situation after lead point" << endl;
698 //cerr << "Prviious: " << prev->name << endl;
699 //cerr << "Current : " << curr->name << endl;
700 //cerr << "Next : " << next->name << endl;
702 tgt_heading = fp->getBearing(curr, next);
706 fp->IncrementWaypoint(eraseWaypoints);
707 if (!(fp->getNextWaypoint()) && trafficRef)
710 prev = fp->getPreviousWaypoint();
711 curr = fp->getCurrentWaypoint();
712 next = fp->getNextWaypoint();
714 // Now that we have incremented the waypoints, excute some traffic manager specific code
715 // based on the name of the waypoint we just passed.
717 double userLatitude = fgGetDouble("/position/latitude-deg");
718 double userLongitude = fgGetDouble("/position/longitude-deg");
719 double course, distance;
720 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
721 SGWayPoint user (userLongitude, userLatitude, 0);
722 user.CourseAndDistance(current, &course, &distance);
723 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
725 //cerr << "done fp die out of range" << endl;
729 FGAirport * dep = trafficRef->getDepartureAirport();
730 FGAirport * arr = trafficRef->getArrivalAirport();
731 // At parking the beginning of the airport
732 if (!( dep && arr)) {
737 //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM")))) {
738 // cerr << trafficRef->getRegistration()
739 // << " Enroute from " << dep->getId()
740 // << " to " << arr->getId()
741 // << " just crossed " << prev->name
742 // << " Assigned rwy " << fp->getRunwayId()
743 // << " " << fp->getRunway() << endl;
745 //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
746 // cerr << "Schiphol ground "
747 // << trafficRef->getCallSign();
748 // if (trafficRef->getHeavy())
750 // cerr << ", is type "
751 // << trafficRef->getAircraft()
752 // << " ready to go. IFR to "
753 // << arr->getId() <<endl;
756 if (prev->name == "park2")
757 dep->getDynamics()->releaseParking(fp->getGate());
759 // Some debug messages, specific to testing the Logical networks.
760 // if ((arr->getId() == string("EHAM")) && (prev->name == "Center")) {
761 // cerr << "Schiphol ground "
762 // << trafficRef->getRegistration() << " "
763 // << trafficRef->getCallSign();
764 // if (trafficRef->getHeavy())
766 // cerr << ", arriving from " << dep->getName() ;
767 // cerr << " landed runway "
768 // << fp->getRunway()
769 // << " request taxi to gate "
770 // << arr->getDynamics()->getParkingName(fp->getGate())
773 if (prev->name == "END")
774 fp->setTime(trafficRef->getDepartureTime());
775 //cerr << "5" << endl;
779 //cerr << "Current waypoint" << curr->name << endl;
780 //cerr << "Next waypoint" << next->name << endl;
781 fp->setLeadDistance(speed, tgt_heading, curr, next);
784 //cerr << "5.1" << endl;
785 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
786 tgt_altitude_ft = prev->altitude;
787 if (curr->crossat > -1000.0) {
788 //cerr << "5.1a" << endl;
790 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
791 / 6076.0 / speed*60.0);
792 //cerr << "5.1b" << endl;
793 tgt_altitude_ft = curr->crossat;
795 //cerr << "5.1c" << endl;
797 //cerr << "5.1d" << endl;
798 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
801 //cerr << "6" << endl;
802 tgt_speed = prev->speed;
803 hdg_lock = alt_lock = true;
804 no_roll = prev->on_ground;
805 //cout << "Crossing waypoint: " << prev->name << endl;
806 //cout << " Target speed: " << tgt_speed << endl;
807 //cout << " Target altitude: " << tgt_altitude_ft << endl;
808 //cout << " Target heading: " << tgt_heading << endl << endl;
811 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
812 //cerr << "Bearing = " << calc_bearing << endl;
815 if (calc_bearing > 360)
819 if (finite(calc_bearing)) {
820 double hdg_error = calc_bearing - tgt_heading;
821 if (fabs(hdg_error) > 1.0) {
822 TurnTo( calc_bearing );
826 cerr << "calc_bearing is not a finite number : "
828 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
829 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
830 cerr << "waypoint name " << curr->name;
834 double speed_diff = speed - prevSpeed;
835 // Update the lead distance calculation if speed has changed sufficiently
836 // to prevent spinning (hopefully);
837 if (fabs(speed_diff) > 10) {
839 fp->setLeadDistance(speed, tgt_heading, curr, next);
842 //cerr << "Done Processing FlightPlan"<< endl;
847 bool FGAIAircraft::_getGearDown() const {
848 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
849 && (props->getFloatValue("velocities/airspeed-kt")
850 < performance->land_speed*1.25));
854 void FGAIAircraft::loadNextLeg() {
856 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
858 //FGAIModelEntity entity;
859 //entity.m_class = "jet_transport";
860 //entity.path = modelPath.c_str();
861 //entity.flightplan = "none";
862 //entity.latitude = _getLatitude();
863 //entity.longitude = _getLongitude();
864 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
865 //entity.speed = 450; // HACK ALERT
866 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
868 if ((leg = fp->getLeg()) == 10) {
872 //cerr << "Resetting leg : " << leg << endl;
876 //cerr << "Creating leg number : " << leg << endl;
877 FGAirport *dep = trafficRef->getDepartureAirport();
878 FGAirport *arr = trafficRef->getArrivalAirport();
881 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
883 // cerr << "Departure " << dep->getId() << endl;
885 // cerr << "Arrival " << arr->getId() << endl;
888 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
889 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
894 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
895 trafficRef->getSpeed(),
899 trafficRef->getRadius(),
900 trafficRef->getFlightType(),
903 //prev = fp->getPreviousWaypoint();
904 //curr = fp->getCurrentWaypoint();
905 //next = fp->getNextWaypoint();
906 //cerr << "25" << endl;
909 // //cerr << "Next waypoint" << next->name << endl;
910 // fp->setLeadDistance(speed, tgt_heading, curr, next);
912 //cerr << "25.1" << endl;
913 //if (curr->crossat > -1000.0) {
914 // //cerr << "25.1a" << endl;
915 // use_perf_vs = false;
917 // tgt_vs = (curr->crossat - altitude_ft)/
918 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
919 // //cerr << "25.1b" << endl;
920 // tgt_altitude_ft = curr->crossat;
922 // //cerr << "25.1c" << endl;
923 // use_perf_vs = true;
924 // //cerr << "25.1d" << endl;
925 // tgt_altitude_ft = prev->altitude;
926 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
928 //cerr << "26" << endl;
929 //tgt_speed = prev->speed;
930 //hdg_lock = alt_lock = true;
931 //no_roll = prev->on_ground;
936 //entity.fp = new FGAIFlightPlan(&entity,
938 // trafficRef->getDepartureTime(),
939 // trafficRef->getDepartureAirport(),
940 // trafficRef->getArrivalAirport(),
944 //SetFlightPlan(entity.fp);
948 // Note: This code is copied from David Luff's AILocalTraffic
949 // Warning - ground elev determination is CPU intensive
950 // Either this function or the logic of how often it is called
951 // will almost certainly change.
953 void FGAIAircraft::getGroundElev(double dt) {
956 // Update minimally every three secs, but add some randomness
957 // to prevent all IA objects doing this in synchrony
958 if (dt_elev_count < (3.0) + (rand() % 10))
963 // Only do the proper hitlist stuff if we are within visible range of the viewer.
965 double visibility_meters = fgGetDouble("/environment/visibility-m");
967 FGViewer* vw = globals->get_current_view();
968 double course, distance;
970 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
971 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
972 view.CourseAndDistance(current, &course, &distance);
973 if(distance > visibility_meters) {
974 //aip.getSGLocation()->set_cur_elev_m(aptElev);
978 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
979 double range = 500.0;
980 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
981 // Try to shedule tiles for that position.
982 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
985 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
987 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
988 tgt_altitude_ft = alt * SG_METER_TO_FEET;
990 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
991 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
993 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
994 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
999 void FGAIAircraft::setCallSign(const string& s) {
1004 void FGAIAircraft::setTACANChannelID(const string& id) {
1005 TACAN_channel_id = id;
1009 void FGAIAircraft::doGroundAltitude() {
1010 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
1011 altitude_ft = (tgt_altitude_ft + groundOffset);
1013 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);