]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
warnings--
[flightgear.git] / src / AIModel / AIAircraft.cxx
1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
2 //
3 // Written by David Culp, started October 2003.
4 //
5 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.net
6 //
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.
11 //
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.
16 //
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.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
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>
32
33 #include <string>
34 #include <math.h>
35 #include <time.h>
36 #ifdef _MSC_VER
37 #  include <float.h>
38 #  define finite _finite
39 #elif defined(__sun) || defined(sgi)
40 #  include <ieeefp.h>
41 #endif
42
43 SG_USING_STD(string);
44
45 #include "AIAircraft.hxx"
46    static string tempReg;
47 //
48 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
49 // cruise_speed, descent_speed, land_speed
50 //
51 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
52     // light aircraft
53     {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
54     // ww2_fighter
55     {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
56     // jet_transport
57     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
58     // jet_fighter
59     {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
60     // tanker
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}
64 };
65
66
67 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
68     FGAIBase(otAircraft)
69 {
70     trafficRef = ref;
71     if (trafficRef)
72         groundOffset = trafficRef->getGroundOffset();
73     else
74         groundOffset = 0;
75
76     fp = 0;
77     dt_count = 0;
78     dt_elev_count = 0;
79     use_perf_vs = true;
80     isTanker = false;
81
82     // set heading and altitude locks
83     hdg_lock = false;
84     alt_lock = false;
85     roll = 0;
86     headingChangeRate = 0.0;
87 }
88
89
90 FGAIAircraft::~FGAIAircraft() {
91     //delete fp;
92 }
93
94
95 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
96     if (!scFileNode)
97         return;
98
99     FGAIBase::readFromScenario(scFileNode);
100
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"));
106 }
107
108
109 bool FGAIAircraft::init() {
110     //refuel_node = fgGetNode("systems/refuel/contact", true);
111     return FGAIBase::init();
112 }
113
114
115 void FGAIAircraft::bind() {
116     FGAIBase::bind();
117
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);
125 }
126
127
128 void FGAIAircraft::unbind() {
129     FGAIBase::unbind();
130
131     props->untie("controls/gear/gear-down");
132     props->untie("refuel/contact");
133 }
134
135
136 void FGAIAircraft::update(double dt) {
137     FGAIBase::update(dt);
138     Run(dt);
139     Transform();
140 }
141
142
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]);
154         SetTanker(true);
155     } else if (acclass == "ufo") {
156         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
157     } else {
158         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
159     }
160 }
161
162
163 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
164
165    performance = ps;
166 }
167
168
169 void FGAIAircraft::Run(double dt) {
170
171     FGAIAircraft::dt = dt;
172     
173     if (fp) {
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.
179             if (no_roll) {
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;
184                 doGroundAltitude();
185                 //cerr << " Actual altitude " << altitude << endl;
186                 // Transform();
187                 pos.setElevationFt(altitude_ft);
188             }
189             return;
190         }
191     } else {
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
195         // fly".
196         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
197         if ( lat_mode == "roll" ) {
198             double angle
199                 = props->getDoubleValue("controls/flight/target-roll" );
200             RollTo( angle );
201         } else {
202              double angle
203                 = props->getDoubleValue("controls/flight/target-hdg" );
204             TurnTo( angle );
205         }
206
207         string lon_mode
208             = props->getStringValue("controls/flight/longitude-mode");
209         if ( lon_mode == "alt" ) {
210             double alt = props->getDoubleValue("controls/flight/target-alt" );
211             ClimbTo( alt );
212         } else {
213             double angle
214                 = props->getDoubleValue("controls/flight/target-pitch" );
215             PitchTo( angle );
216         }
217
218         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
219     }
220       
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;
226     double alpha;
227
228     // adjust speed
229     double speed_diff; //= tgt_speed - speed;
230     if (!no_roll) {
231         speed_diff = tgt_speed - speed;
232     } else {
233         speed_diff = groundTargetSpeed - speed;
234     }
235
236     if (speed_diff > 0.0) {
237         speed += performance->accel * dt;
238         if (no_roll) { // apply overshoot correction
239           if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
240         }else {
241           if ( speed > tgt_speed ) speed = tgt_speed;
242         }
243     } else if (speed_diff < 0.0) {
244         if (no_roll) {
245             // on ground (aircraft can't roll)
246             // deceleration performance is better due to wheel brakes.
247             speed -= performance->decel * dt * 3;
248         } else {
249             speed -= performance->decel * dt;
250         }
251         if (no_roll) { // apply overshoot correction
252         if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
253         } else { 
254           if ( speed < tgt_speed ) speed = tgt_speed;
255         }
256     }
257     
258     
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;
264
265     // set new position
266     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
267     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt); 
268
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()); */
275
276     //if (!(finite(pos.lat()) && finite(pos.lon())))
277     //  {
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;
286     //  }
287
288     // adjust heading based on current bank angle
289     if (roll == 0.0)
290         roll = 0.01;
291
292     if (roll != 0.0) {
293         // double turnConstant;
294         //if (no_roll)
295         //  turnConstant = 0.0088362;
296         //else
297         //  turnConstant = 0.088362;
298         // If on ground, calculate heading change directly
299         if (no_roll) {
300             double headingDiff = fabs(hdg-tgt_heading);
301
302             if (headingDiff > 180)
303                 headingDiff = fabs(headingDiff - 360);
304
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
308
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
312                 // forever turning
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
321                 //         << endl;
322                 //}
323                 if (headingChangeRate > 30)
324                     headingChangeRate = 30;
325                 else if (headingChangeRate < -30)
326                     headingChangeRate = -30;
327
328             } else {
329                 if (fabs(headingChangeRate) > headingDiff)
330                     headingChangeRate = headingDiff*sign(roll);
331                 else
332                     headingChangeRate += dt * sign(roll);
333             }
334             hdg += headingChangeRate * dt;
335             //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
336             //     << ". Target speed: " << groundTargetSpeed << ". heading change rate"
337             //     << headingChangeRate << endl;
338
339         } else {
340             if (fabs(speed) > 1.0) {
341                 turn_radius_ft = 0.088362 * speed * speed
342                         / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
343             } else {
344                 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
345             }
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);
350         }
351         while ( hdg > 360.0 ) {
352             hdg -= 360.0;
353             spinCounter++;
354         }
355         while ( hdg < 0.0) {
356             hdg += 360.0;
357             spinCounter--;
358         }
359     }
360
361
362     // adjust target bank angle if heading lock engaged
363     if (hdg_lock) {
364         double bank_sense = 0.0;
365         double diff = fabs(hdg - tgt_heading);
366         if (diff > 180)
367             diff = fabs(diff - 360);
368
369         double sum = hdg + diff;
370         if (sum > 360.0)
371             sum -= 360.0;
372         if (fabs(sum - tgt_heading) < 1.0) {
373             bank_sense = 1.0;   // right turn
374         } else {
375             bank_sense = -1.0;  // left turn
376         }
377         if (diff < 30) {
378             tgt_roll = diff * bank_sense;
379         } else {
380             tgt_roll = 30.0 * bank_sense;
381         }
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;
398             //}
399         }
400     }
401
402     // adjust bank angle, use 9 degrees per second
403     double bank_diff = tgt_roll - roll;
404     if (fabs(bank_diff) > 0.2) {
405         if (bank_diff > 0.0)
406             roll += 9.0 * dt;
407
408         if (bank_diff < 0.0)
409             roll -= 9.0 * dt;
410         //while (roll > 180) roll -= 360;
411         //while (roll < 180) roll += 360;
412     }
413
414     // adjust altitude (meters) based on current vertical speed (fpm)
415     altitude_ft += vs / 60.0 * dt;
416     pos.setElevationFt(altitude_ft);  
417
418     // adjust target Altitude, based on ground elevation when on ground
419     if (no_roll) {
420         getGroundElev(dt);
421         doGroundAltitude();
422     } else {
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;
429             } else {
430                 tgt_vs = tgt_altitude_ft - altitude_ft;
431                 if (tgt_vs  < (-performance->descent_rate))
432                     tgt_vs = -performance->descent_rate;
433             }
434         }
435
436         if (alt_lock && !use_perf_vs) {
437             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
438             double min_vs = 100;
439             if (tgt_altitude_ft < altitude_ft)
440                 min_vs = -100.0;
441             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
442                     && (fabs(max_vs) < fabs(tgt_vs)))
443                 tgt_vs = max_vs;
444
445             if (fabs(tgt_vs) < fabs(min_vs))
446                 tgt_vs = min_vs;
447         }
448     }
449     // adjust vertical speed
450     double vs_diff = tgt_vs - vs;
451     if (fabs(vs_diff) > 10.0) {
452         if (vs_diff > 0.0) {
453             vs += 900.0 * dt;
454
455             if (vs > tgt_vs)
456                 vs = tgt_vs;
457         } else {
458             vs -= 400.0 * dt;
459
460            if (vs < tgt_vs)
461                vs = tgt_vs;
462         }
463     }
464
465     // match pitch angle to vertical speed
466     if (vs > 0) {
467         pitch = vs * 0.005;
468     } else {
469         pitch = vs * 0.002;
470     }
471
472     //###########################//
473     // do calculations for radar //
474     //###########################//
475     double range_ft2 = UpdateRadar(manager);
476
477     //************************************//
478     // Tanker code                        //
479     //************************************//
480
481     if ( isTanker) {
482         if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
483                 && (elevation > 0.0) ) {
484             //refuel_node->setBoolValue(true);
485             contact = true;
486         } else {
487             //refuel_node->setBoolValue(false);
488             contact = false;
489         }
490     } else {
491         contact = false;
492     }
493 }
494
495
496 void FGAIAircraft::AccelTo(double speed) {
497     tgt_speed = speed;
498 }
499
500
501 void FGAIAircraft::PitchTo(double angle) {
502     tgt_pitch = angle;
503     alt_lock = false;
504 }
505
506
507 void FGAIAircraft::RollTo(double angle) {
508     tgt_roll = angle;
509     hdg_lock = false;
510 }
511
512
513 void FGAIAircraft::YawTo(double angle) {
514     tgt_yaw = angle;
515 }
516
517
518 void FGAIAircraft::ClimbTo(double alt_ft ) {
519     tgt_altitude_ft = alt_ft;
520     alt_lock = true;
521 }
522
523
524 void FGAIAircraft::TurnTo(double heading) {
525     tgt_heading = heading;
526     hdg_lock = true;
527 }
528
529
530 double FGAIAircraft::sign(double x) {
531     if ( x < 0.0 )
532         return -1.0;
533     else
534         return 1.0;
535 }
536
537
538 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
539     if (!flightplan.empty()) {
540         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
541         fp->setRepeat(repeat);
542         SetFlightPlan(fp);
543     }
544 }
545
546
547 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
548     delete fp;
549     fp = f;
550 }
551
552
553 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
554     bool eraseWaypoints;
555     if (trafficRef) {
556 //      FGAirport *arr;
557 //      FGAirport *dep;
558         eraseWaypoints = true;
559 //      cerr << trafficRef->getRegistration();
560 //      cerr << "Departure airport " << endl;
561 //      dep = trafficRef->getDepartureAirport();
562 //      if (dep)
563 //          cerr << dep->getId() << endl;
564 //      cerr << "Arrival   airport " << endl;
565 //      arr = trafficRef->getArrivalAirport();
566 //      if (arr)
567 //          cerr << arr->getId() <<endl << endl;;
568     } else
569         eraseWaypoints = false;
570
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();
578     dt_count += dt;
579
580     if (!prev) {  //beginning of flightplan, do this initialization once
581         //setBank(0.0);
582         spinCounter = 0;
583         tempReg = "";
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)
592             loadNextLeg();
593
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);
603
604         if (prev->speed > 0.0)
605             setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
606         else
607             setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
608
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
612         if (next)
613             fp->setLeadDistance(speed, hdg, curr, next);
614
615         if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
616             use_perf_vs = false;
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;
621         } else {
622             use_perf_vs = true;
623             tgt_altitude_ft = prev->altitude;
624         }
625         alt_lock = hdg_lock = true;
626         no_roll = prev->on_ground;
627         if (no_roll) {
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);
633         }
634         prevSpeed = 0;
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;
640         return;
641     } // end of initialization
642
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;
646         return;
647     } else {
648         dt_count = 0;
649     }
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);
652
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.
657
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;
661     }
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;
669 //  }
670
671     prev_dist_to_go = dist_to_go;
672     //cerr << "2" << endl;
673     //if (no_roll)
674     //  lead_dist = 10.0;
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;
679
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
686             if (fp->getRepeat())
687                 fp->restart();
688             else
689                 setDie(true);
690
691             //cerr << "Done die end of fp" << endl;
692             return;
693         }
694
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;
701         if (next) {
702             tgt_heading = fp->getBearing(curr, next);
703             spinCounter = 0;
704         }
705
706         fp->IncrementWaypoint(eraseWaypoints);
707         if (!(fp->getNextWaypoint()) && trafficRef)
708             loadNextLeg();
709
710         prev = fp->getPreviousWaypoint();
711         curr = fp->getCurrentWaypoint();
712         next = fp->getNextWaypoint();
713
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.
716         if (trafficRef) {
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) {
724                 setDie(true);
725                 //cerr << "done fp die out of range" << endl;
726                 return;
727             }
728
729             FGAirport * dep = trafficRef->getDepartureAirport();
730             FGAirport * arr = trafficRef->getArrivalAirport();
731             // At parking the beginning of the airport
732             if (!( dep && arr)) {
733                 setDie(true);
734                 return;
735             }
736
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;
744             // }
745             //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
746             //    cerr << "Schiphol ground "
747             //         << trafficRef->getCallSign();
748             //    if (trafficRef->getHeavy())
749             //        cerr << "Heavy";
750             //    cerr << ", is type "
751             //         << trafficRef->getAircraft()
752             //         << " ready to go. IFR to "
753             //         << arr->getId() <<endl;
754             // }
755
756             if (prev->name == "park2")
757                 dep->getDynamics()->releaseParking(fp->getGate());
758
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())
765             //         cerr << "Heavy";
766             //     cerr << ", arriving from " << dep->getName() ;
767             //     cerr << " landed runway "
768             //          << fp->getRunway()
769             //          << " request taxi to gate "
770             //          << arr->getDynamics()->getParkingName(fp->getGate())
771             //          << endl;
772             // }
773             if (prev->name == "END")
774                 fp->setTime(trafficRef->getDepartureTime());
775             //cerr << "5" << endl;
776         }
777
778         if (next) {
779             //cerr << "Current waypoint" << curr->name << endl;
780             //cerr << "Next waypoint" << next->name << endl;
781             fp->setLeadDistance(speed, tgt_heading, curr, next);
782         }
783
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;
789                 use_perf_vs = false;
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;
794             } else {
795                 //cerr << "5.1c" << endl;
796                 use_perf_vs = true;
797                 //cerr << "5.1d" << endl;
798                 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
799             }
800         }
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;
809
810     } else {
811         double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
812         //cerr << "Bearing = " << calc_bearing << endl;
813         if (speed < 0) {
814             calc_bearing +=180;
815             if (calc_bearing > 360)
816                 calc_bearing -= 360;
817         }
818
819         if (finite(calc_bearing)) {
820             double hdg_error = calc_bearing - tgt_heading;
821             if (fabs(hdg_error) > 1.0) {
822                 TurnTo( calc_bearing );
823             }
824
825         } else {
826             cerr << "calc_bearing is not a finite number : "
827                  << "Speed " << speed
828                  << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
829                  << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
830             cerr << "waypoint name " << curr->name;
831             exit(1);  // FIXME
832         }
833
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) {
838             prevSpeed = speed;
839             fp->setLeadDistance(speed, tgt_heading, curr, next);
840         }
841
842         //cerr << "Done Processing FlightPlan"<< endl;
843     }
844 }
845
846
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));
851 }
852
853
854 void FGAIAircraft::loadNextLeg() {
855     //delete fp;
856     //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
857
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);
867     int leg;
868     if ((leg = fp->getLeg())  == 10) {
869         trafficRef->next();
870         leg = 1;
871         fp->setLeg(leg);
872         //cerr << "Resetting leg : " << leg << endl;
873     }
874     //leg++;
875     //fp->setLeg(leg);
876     //cerr << "Creating leg number : " << leg << endl;
877     FGAirport *dep = trafficRef->getDepartureAirport();
878     FGAirport *arr = trafficRef->getArrivalAirport();
879     if (!(dep && arr)) {
880         setDie(true);
881         //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
882         //if (dep)
883         //  cerr << "Departure " << dep->getId() << endl;
884         //if (arr)
885         //  cerr << "Arrival   " << arr->getId() << endl;
886
887     } else {
888         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
889         //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
890
891         fp->create (dep,
892                     arr,
893                     leg,
894                     cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
895                     trafficRef->getSpeed(),
896                     _getLatitude(),
897                     _getLongitude(),
898                     false,
899                     trafficRef->getRadius(),
900                     trafficRef->getFlightType(),
901                     acType,
902                     company);
903         //prev = fp->getPreviousWaypoint();
904         //curr = fp->getCurrentWaypoint();
905         //next = fp->getNextWaypoint();
906         //cerr << "25" << endl;
907         //if (next)
908         //        {
909         //  //cerr << "Next waypoint" << next->name << endl;
910         //          fp->setLeadDistance(speed, tgt_heading, curr, next);
911         //        }
912         //cerr << "25.1" << endl;
913         //if (curr->crossat > -1000.0) {
914         //        //cerr << "25.1a" << endl;
915         //        use_perf_vs = false;
916         //
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;
921         //} else {
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;
927         // }
928         //cerr << "26" << endl;
929         //tgt_speed = prev->speed;
930         //hdg_lock = alt_lock = true;
931         //no_roll = prev->on_ground;
932     }
933     //else
934     //{
935     //delete entity.fp;
936     //entity.fp = new FGAIFlightPlan(&entity,
937     //                                 999,  // A hack
938     //                                 trafficRef->getDepartureTime(),
939     //                                 trafficRef->getDepartureAirport(),
940     //                                 trafficRef->getArrivalAirport(),
941     //                                 false,
942     //                                 acType,
943     //                                 company);
944     //SetFlightPlan(entity.fp);
945 }
946
947
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.
952
953 void FGAIAircraft::getGroundElev(double dt) {
954     dt_elev_count += dt;
955
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))
959         return;
960     else
961        dt_elev_count = 0;
962
963     // Only do the proper hitlist stuff if we are within visible range of the viewer.
964     if (!invisible) {
965         double visibility_meters = fgGetDouble("/environment/visibility-m");
966
967         FGViewer* vw = globals->get_current_view();
968         double course, distance;
969
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);
975             return;
976         }
977
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 );
983         }
984
985         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
986         double alt;
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;
989
990         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
991         // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
992         //                                            20000.0, alt))
993         //    tgt_altitude_ft = alt * SG_METER_TO_FEET;
994         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
995     }
996 }
997
998
999 void FGAIAircraft::setCallSign(const string& s) {
1000     callsign = s;
1001 }
1002
1003
1004 void FGAIAircraft::setTACANChannelID(const string& id) {
1005     TACAN_channel_id = id;
1006 }
1007
1008
1009 void FGAIAircraft::doGroundAltitude() {
1010    if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
1011        altitude_ft = (tgt_altitude_ft + groundOffset);
1012    else
1013       altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
1014 }
1015