]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
This patch only affects aircraft (AI Models) that have no predefined
[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 };
63
64
65 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
66     FGAIBase(otAircraft)
67 {
68     trafficRef = ref;
69     if (trafficRef)
70         groundOffset = trafficRef->getGroundOffset();
71     else
72         groundOffset = 0;
73
74     fp = 0;
75     dt_count = 0;
76     dt_elev_count = 0;
77     use_perf_vs = true;
78     isTanker = false;
79
80     // set heading and altitude locks
81     hdg_lock = false;
82     alt_lock = false;
83     roll = 0;
84     headingChangeRate = 0.0;
85 }
86
87
88 FGAIAircraft::~FGAIAircraft() {
89     //delete fp;
90 }
91
92
93 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
94     if (!scFileNode)
95         return;
96
97     FGAIBase::readFromScenario(scFileNode);
98
99     setPerformance(scFileNode->getStringValue("class", "jet_transport"));
100     setFlightPlan(scFileNode->getStringValue("flightplan"),
101                   scFileNode->getBoolValue("repeat", false));
102     setCallSign(scFileNode->getStringValue("callsign"));
103     setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
104 }
105
106
107 bool FGAIAircraft::init() {
108     //refuel_node = fgGetNode("systems/refuel/contact", true);
109     return FGAIBase::init();
110 }
111
112
113 void FGAIAircraft::bind() {
114     FGAIBase::bind();
115
116     props->tie("controls/gear/gear-down",
117                SGRawValueMethods<FGAIAircraft,bool>(*this,
118                                               &FGAIAircraft::_getGearDown));
119     props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
120     props->setStringValue("callsign", callsign.c_str());
121     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
122     props->setBoolValue("tanker",isTanker);
123 }
124
125
126 void FGAIAircraft::unbind() {
127     FGAIBase::unbind();
128
129     props->untie("controls/gear/gear-down");
130     props->untie("refuel/contact");
131 }
132
133
134 void FGAIAircraft::update(double dt) {
135     FGAIBase::update(dt);
136     Run(dt);
137     Transform();
138 }
139
140
141 void FGAIAircraft::setPerformance(const std::string& acclass) {
142     if (acclass == "light") {
143         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
144     } else if (acclass == "ww2_fighter") {
145         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
146     } else if (acclass == "jet_transport") {
147         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
148     } else if (acclass == "jet_fighter") {
149         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
150     } else if (acclass == "tanker") {
151         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
152         SetTanker(true);
153     } else {
154         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
155     }
156 }
157
158
159 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
160
161    performance = ps;
162 }
163
164
165 void FGAIAircraft::Run(double dt) {
166
167     FGAIAircraft::dt = dt;
168
169     if (fp) {
170         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
171         ProcessFlightPlan(dt, now);
172         if (now < fp->getStartTime()) {
173             // Do execute Ground elev for inactive aircraft, so they
174             // Are repositioned to the correct ground altitude when the user flies within visibility range.
175             if (no_roll) {
176                 Transform();       // make sure aip is initialized.
177                 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
178                 //getGroundElev(dt); // Need to do this twice.
179                 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
180                 doGroundAltitude();
181                 //cerr << " Actual altitude " << altitude << endl;
182                 // Transform();
183                 pos.setElevationFt(altitude);
184             }
185             return;
186         }
187     } else {
188         // no flight plan, update target heading, speed, and altitude
189         // from control properties.  These default to the initial
190         // settings in the config file, but can be changed "on the
191         // fly".
192
193         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
194         if ( lat_mode == "roll" ) {
195             double angle
196                 = props->getDoubleValue("controls/flight/target-roll" );
197             RollTo( angle );
198         } else {
199              double angle
200                 = props->getDoubleValue("controls/flight/target-hdg" );
201             TurnTo( angle );
202         }
203
204         string lon_mode
205             = props->getStringValue("controls/flight/longitude-mode");
206         if ( lon_mode == "alt" ) {
207             double alt = props->getDoubleValue("controls/flight/target-alt" );
208             ClimbTo( alt );
209         } else {
210             double angle
211                 = props->getDoubleValue("controls/flight/target-pitch" );
212             PitchTo( angle );
213         }
214
215         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
216     }
217
218     double turn_radius_ft;
219     double turn_circum_ft;
220     double speed_north_deg_sec;
221     double speed_east_deg_sec;
222     double dist_covered_ft;
223     double alpha;
224
225     // adjust speed
226     double speed_diff; //= tgt_speed - speed;
227     if (!no_roll) {
228         speed_diff = tgt_speed - speed;
229     } else {
230         speed_diff = groundTargetSpeed - speed;
231     }
232     if (fabs(speed_diff) > 0.2) {
233         if (speed_diff > 0.0)
234             speed += performance->accel * dt;
235         if (speed_diff < 0.0) {
236             if (no_roll) { // was (!no_roll) but seems more logical this way (ground brakes).
237                 speed -= performance->decel * dt * 3;
238             } else {
239                 speed -= performance->decel * dt;
240             }
241         }
242     }
243
244     // convert speed to degrees per second
245     speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
246                           * speed * 1.686 / ft_per_deg_lat;
247     speed_east_deg_sec  = sin( hdg / SG_RADIANS_TO_DEGREES )
248                           * speed * 1.686 / ft_per_deg_lon;
249
250     // set new position
251     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
252     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt); 
253     //if (!(finite(pos.lat()) && finite(pos.lon())))
254     //  {
255     //    cerr << "Position is not finite" << endl;
256     //    cerr << "speed = " << speed << endl;
257     //    cerr << "dt" << dt << endl;
258     //    cerr << "heading " << hdg << endl;
259     //    cerr << "speed east " << speed_east_deg_sec << endl;
260     //    cerr << "speed nrth " << speed_north_deg_sec << endl;
261     //    cerr << "deg_lat    " << ft_per_deg_lat << endl;
262     //    cerr << "deg_lon    " << ft_per_deg_lon << endl;
263     //  }
264
265     // adjust heading based on current bank angle
266     if (roll == 0.0)
267         roll = 0.01;
268
269     if (roll != 0.0) {
270         // double turnConstant;
271         //if (no_roll)
272         //  turnConstant = 0.0088362;
273         //else
274         //  turnConstant = 0.088362;
275         // If on ground, calculate heading change directly
276         if (no_roll) {
277             double headingDiff = fabs(hdg-tgt_heading);
278
279             if (headingDiff > 180)
280                 headingDiff = fabs(headingDiff - 360);
281
282             groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
283             if (sign(groundTargetSpeed) != sign(tgt_speed))
284                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
285
286             if (headingDiff > 30.0) {
287                 headingChangeRate += dt * sign(roll); // invert if pushed backward
288                 // Print some debug statements to find out why aircraft may get stuck
289                 // forever turning
290                 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
291                 //    cerr << "Turning : " << trafficRef->getRegistration()
292                 //    cerr <<  " Speed = " << speed << " Heading " << hdg
293                 //         << " Target Heading " << tgt_heading
294                 //         << " Lead Distance " <<  fp->getLeadDistance()
295                 //         << " Distance to go "
296                 //         << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
297                 //         << "waypoint name " << fp->getCurrentWaypoint()->name
298                 //         << endl;
299                 //}
300                 if (headingChangeRate > 30)
301                     headingChangeRate = 30;
302                 else if (headingChangeRate < -30)
303                     headingChangeRate = -30;
304
305             } else {
306                 if (fabs(headingChangeRate) > headingDiff)
307                     headingChangeRate = headingDiff*sign(roll);
308                 else
309                     headingChangeRate += dt * sign(roll);
310             }
311             hdg += headingChangeRate * dt;
312             //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
313             //     << ". Target speed: " << groundTargetSpeed << ". heading change rate"
314             //     << headingChangeRate << endl;
315
316         } else {
317             if (fabs(speed) > 1.0) {
318                 turn_radius_ft = 0.088362 * speed * speed
319                         / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
320             } else {
321                 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
322             }
323             turn_circum_ft = SGD_2PI * turn_radius_ft;
324             dist_covered_ft = speed * 1.686 * dt;
325             alpha = dist_covered_ft / turn_circum_ft * 360.0;
326             hdg += alpha * sign(roll);
327         }
328         while ( hdg > 360.0 ) {
329             hdg -= 360.0;
330             spinCounter++;
331         }
332         while ( hdg < 0.0) {
333             hdg += 360.0;
334             spinCounter--;
335         }
336     }
337
338
339     // adjust target bank angle if heading lock engaged
340     if (hdg_lock) {
341         double bank_sense = 0.0;
342         double diff = fabs(hdg - tgt_heading);
343         if (diff > 180)
344             diff = fabs(diff - 360);
345
346         double sum = hdg + diff;
347         if (sum > 360.0)
348             sum -= 360.0;
349         if (fabs(sum - tgt_heading) < 1.0) {
350             bank_sense = 1.0;   // right turn
351         } else {
352             bank_sense = -1.0;  // left turn
353         }
354         if (diff < 30) {
355             tgt_roll = diff * bank_sense;
356         } else {
357             tgt_roll = 30.0 * bank_sense;
358         }
359         if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
360             tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
361             // The only way to resolve this is to make them slow down.
362             //if (tempReg.empty())
363             //  tempReg = trafficRef->getRegistration();
364             //if (trafficRef->getRegistration() == tempReg) {
365             //    cerr << trafficRef->getRegistration()
366             //         << " appears to be spinning: " << spinCounter << endl
367             //         << " speed          " << speed << endl
368             //         << " heading        " << hdg << endl
369             //         << " lead distance  " << fp->getLeadDistance() << endl
370             //         << " waypoint       " << fp->getCurrentWaypoint()->name
371             //         << " target heading " << tgt_heading << endl
372             //         << " lead in angle  " << fp->getLeadInAngle()<< endl
373             //         << " roll           " << roll << endl
374             //         << " target_roll    " << tgt_roll << endl;
375             //}
376         }
377     }
378
379     // adjust bank angle, use 9 degrees per second
380     double bank_diff = tgt_roll - roll;
381     if (fabs(bank_diff) > 0.2) {
382         if (bank_diff > 0.0)
383             roll += 9.0 * dt;
384
385         if (bank_diff < 0.0)
386             roll -= 9.0 * dt;
387         //while (roll > 180) roll -= 360;
388         //while (roll < 180) roll += 360;
389     }
390
391     // adjust altitude (meters) based on current vertical speed (fpm)
392     altitude += vs / 60.0 * dt;
393     pos.setElevationFt(altitude);  
394     double altitude_ft = altitude;
395
396     // adjust target Altitude, based on ground elevation when on ground
397     if (no_roll) {
398         getGroundElev(dt);
399         doGroundAltitude();
400     } else {
401         // find target vertical speed if altitude lock engaged
402         if (alt_lock && use_perf_vs) {
403             if (altitude_ft < tgt_altitude) {
404                 tgt_vs = tgt_altitude - altitude_ft;
405                 if (tgt_vs > performance->climb_rate)
406                     tgt_vs = performance->climb_rate;
407             } else {
408                 tgt_vs = tgt_altitude - altitude_ft;
409                 if (tgt_vs  < (-performance->descent_rate))
410                     tgt_vs = -performance->descent_rate;
411             }
412         }
413
414         if (alt_lock && !use_perf_vs) {
415             double max_vs = 4*(tgt_altitude - altitude);
416             double min_vs = 100;
417             if (tgt_altitude < altitude)
418                 min_vs = -100.0;
419             if ((fabs(tgt_altitude - altitude) < 1500.0)
420                     && (fabs(max_vs) < fabs(tgt_vs)))
421                 tgt_vs = max_vs;
422
423             if (fabs(tgt_vs) < fabs(min_vs))
424                 tgt_vs = min_vs;
425         }
426     }
427     // adjust vertical speed
428     double vs_diff = tgt_vs - vs;
429     if (fabs(vs_diff) > 10.0) {
430         if (vs_diff > 0.0) {
431             vs += 900.0 * dt;
432
433             if (vs > tgt_vs)
434                 vs = tgt_vs;
435         } else {
436             vs -= 400.0 * dt;
437
438            if (vs < tgt_vs)
439                vs = tgt_vs;
440         }
441     }
442
443     // match pitch angle to vertical speed
444     if (vs > 0) {
445         pitch = vs * 0.005;
446     } else {
447         pitch = vs * 0.002;
448     }
449
450     //###########################//
451     // do calculations for radar //
452     //###########################//
453     double range_ft2 = UpdateRadar(manager);
454
455     //************************************//
456     // Tanker code                        //
457     //************************************//
458
459     if ( isTanker) {
460         if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
461                 && (elevation > 0.0) ) {
462             //refuel_node->setBoolValue(true);
463             contact = true;
464         } else {
465             //refuel_node->setBoolValue(false);
466             contact = false;
467         }
468     } else {
469         contact = false;
470     }
471 }
472
473
474 void FGAIAircraft::AccelTo(double speed) {
475     tgt_speed = speed;
476 }
477
478
479 void FGAIAircraft::PitchTo(double angle) {
480     tgt_pitch = angle;
481     alt_lock = false;
482 }
483
484
485 void FGAIAircraft::RollTo(double angle) {
486     tgt_roll = angle;
487     hdg_lock = false;
488 }
489
490
491 void FGAIAircraft::YawTo(double angle) {
492     tgt_yaw = angle;
493 }
494
495
496 void FGAIAircraft::ClimbTo(double altitude) {
497     tgt_altitude = altitude;
498     alt_lock = true;
499 }
500
501
502 void FGAIAircraft::TurnTo(double heading) {
503     tgt_heading = heading;
504     hdg_lock = true;
505 }
506
507
508 double FGAIAircraft::sign(double x) {
509     if ( x < 0.0 )
510         return -1.0;
511     else
512         return 1.0;
513 }
514
515
516 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
517     if (!flightplan.empty()) {
518         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
519         fp->setRepeat(repeat);
520         SetFlightPlan(fp);
521     }
522 }
523
524
525 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
526     delete fp;
527     fp = f;
528 }
529
530
531 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
532     bool eraseWaypoints;
533     if (trafficRef) {
534 //      FGAirport *arr;
535 //      FGAirport *dep;
536         eraseWaypoints = true;
537 //      cerr << trafficRef->getRegistration();
538 //      cerr << "Departure airport " << endl;
539 //      dep = trafficRef->getDepartureAirport();
540 //      if (dep)
541 //          cerr << dep->getId() << endl;
542 //      cerr << "Arrival   airport " << endl;
543 //      arr = trafficRef->getArrivalAirport();
544 //      if (arr)
545 //          cerr << arr->getId() <<endl << endl;;
546     } else
547         eraseWaypoints = false;
548
549     //cerr << "Processing Flightplan" << endl;
550     FGAIFlightPlan::waypoint* prev = 0; // the one behind you
551     FGAIFlightPlan::waypoint* curr = 0; // the one ahead
552     FGAIFlightPlan::waypoint* next = 0; // the next plus 1
553     prev = fp->getPreviousWaypoint();
554     curr = fp->getCurrentWaypoint();
555     next = fp->getNextWaypoint();
556     dt_count += dt;
557
558     if (!prev) {  //beginning of flightplan, do this initialization once
559         //setBank(0.0);
560         spinCounter = 0;
561         tempReg = "";
562         //prev_dist_to_go = HUGE;
563         //cerr << "Before increment " << curr-> name << endl;
564         fp->IncrementWaypoint(eraseWaypoints);
565         //prev = fp->getPreviousWaypoint(); //first waypoint
566         //curr = fp->getCurrentWaypoint();  //second waypoint
567         //next = fp->getNextWaypoint();     //third waypoint (might not exist!)
568         //cerr << "After increment " << prev-> name << endl;
569         if (!(fp->getNextWaypoint()) && trafficRef)
570             loadNextLeg();
571
572         //cerr << "After load " << prev-> name << endl;
573         prev = fp->getPreviousWaypoint(); //first waypoint
574         curr = fp->getCurrentWaypoint();  //second waypoint
575         next = fp->getNextWaypoint();     //third waypoint (might not exist!)
576         //cerr << "After load " << prev-> name << endl;
577         setLatitude(prev->latitude);
578         setLongitude(prev->longitude);
579         setSpeed(prev->speed);
580         setAltitude(prev->altitude);
581
582         if (prev->speed > 0.0)
583             setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
584         else
585             setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
586
587         // If next doesn't exist, as in incrementally created flightplans for
588         // AI/Trafficmanager created plans,
589         // Make sure lead distance is initialized otherwise
590         if (next)
591             fp->setLeadDistance(speed, hdg, curr, next);
592
593         if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
594             use_perf_vs = false;
595             tgt_vs = (curr->crossat - prev->altitude)
596                     / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
597                     / 6076.0 / prev->speed*60.0);
598             tgt_altitude = curr->crossat;
599         } else {
600             use_perf_vs = true;
601             tgt_altitude = prev->altitude;
602         }
603         alt_lock = hdg_lock = true;
604         no_roll = prev->on_ground;
605         if (no_roll) {
606             Transform();         // make sure aip is initialized.
607             getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
608             //getGroundElev(60.1); // Need to do this twice.
609             //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
610             doGroundAltitude(); //(tgt_altitude);
611         }
612         prevSpeed = 0;
613         //cout << "First waypoint:  " << prev->name << endl;
614         //cout << "  Target speed:    " << tgt_speed << endl;
615         //cout << "  Target altitude: " << tgt_altitude << endl;
616         //cout << "  Target heading:  " << tgt_heading << endl << endl;
617         //cerr << "Done Flightplan init" << endl;
618         return;
619     } // end of initialization
620
621     // let's only process the flight plan every 100 ms.
622     if ((dt_count < 0.1) || (now < fp->getStartTime())) {
623         //cerr  << "done fp dt" << endl;
624         return;
625     } else {
626         dt_count = 0;
627     }
628     // check to see if we've reached the lead point for our next turn
629     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
630
631     //cerr << "2" << endl;
632     double lead_dist = fp->getLeadDistance();
633     //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
634     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
635
636     if (lead_dist < fabs(2*speed)) {
637         lead_dist = fabs(2*speed);  //don't skip over the waypoint
638         //cerr << "Extending lead distance to " << lead_dist << endl;
639     }
640 //  FGAirport * apt = trafficRef->getDepartureAirport();
641 //  if ((dist_to_go > prev_dist_to_go) && trafficRef && apt) {
642 //      if (apt->getId() == string("EHAM"))
643 //          cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name  << endl
644 //               << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
645 //               << "Lead distance : " << lead_dist  << endl
646 //               << "Distance to go: " << dist_to_go << endl;
647 //  }
648
649     prev_dist_to_go = dist_to_go;
650     //cerr << "2" << endl;
651     //if (no_roll)
652     //  lead_dist = 10.0;
653     //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ",  lead_dist: "
654     //     << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading
655     //     << " speed " << speed << " hdg " << hdg << ". Altitude "  << altitude << " TAget alt :"
656     //     << tgt_altitude << endl;
657
658     if ( dist_to_go < lead_dist ) {
659         //prev_dist_to_go = HUGE;
660         // For traffic manager generated aircraft:
661         // check if the aircraft flies of of user range. And adjust the
662         // Current waypoint's elevation according to Terrain Elevation
663         if (curr->finished) {  //end of the flight plan
664             if (fp->getRepeat())
665                 fp->restart();
666             else
667                 setDie(true);
668
669             //cerr << "Done die end of fp" << endl;
670             return;
671         }
672
673         // we've reached the lead-point for the waypoint ahead
674         //cerr << "4" << endl;
675         //cerr << "Situation after lead point" << endl;
676         //cerr << "Prviious: " << prev->name << endl;
677         //cerr << "Current : " << curr->name << endl;
678         //cerr << "Next    : " << next->name << endl;
679         if (next) {
680             tgt_heading = fp->getBearing(curr, next);
681             spinCounter = 0;
682         }
683
684         fp->IncrementWaypoint(eraseWaypoints);
685         if (!(fp->getNextWaypoint()) && trafficRef)
686             loadNextLeg();
687
688         prev = fp->getPreviousWaypoint();
689         curr = fp->getCurrentWaypoint();
690         next = fp->getNextWaypoint();
691
692         // Now that we have incremented the waypoints, excute some traffic manager specific code
693         // based on the name of the waypoint we just passed.
694         if (trafficRef) {
695             double userLatitude  = fgGetDouble("/position/latitude-deg");
696             double userLongitude = fgGetDouble("/position/longitude-deg");
697             double course, distance;
698             SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
699             SGWayPoint user (userLongitude, userLatitude, 0);
700             user.CourseAndDistance(current, &course, &distance);
701             if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
702                 setDie(true);
703                 //cerr << "done fp die out of range" << endl;
704                 return;
705             }
706
707             FGAirport * dep = trafficRef->getDepartureAirport();
708             FGAirport * arr = trafficRef->getArrivalAirport();
709             // At parking the beginning of the airport
710             if (!( dep && arr)) {
711                 setDie(true);
712                 return;
713             }
714
715             //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM")))) {
716             //    cerr << trafficRef->getRegistration()
717             //         << " Enroute from " << dep->getId()
718             //         << " to "           << arr->getId()
719             //         << " just crossed " << prev->name
720             //         << " Assigned rwy     " << fp->getRunwayId()
721             //         << " " << fp->getRunway() << endl;
722             // }
723             //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
724             //    cerr << "Schiphol ground "
725             //         << trafficRef->getCallSign();
726             //    if (trafficRef->getHeavy())
727             //        cerr << "Heavy";
728             //    cerr << ", is type "
729             //         << trafficRef->getAircraft()
730             //         << " ready to go. IFR to "
731             //         << arr->getId() <<endl;
732             // }
733
734             if (prev->name == "park2")
735                 dep->getDynamics()->releaseParking(fp->getGate());
736
737             // Some debug messages, specific to testing the Logical networks.
738             // if ((arr->getId() == string("EHAM")) && (prev->name  == "Center")) {
739             //     cerr << "Schiphol ground "
740             //          << trafficRef->getRegistration() << " "
741             //          << trafficRef->getCallSign();
742             //     if (trafficRef->getHeavy())
743             //         cerr << "Heavy";
744             //     cerr << ", arriving from " << dep->getName() ;
745             //     cerr << " landed runway "
746             //          << fp->getRunway()
747             //          << " request taxi to gate "
748             //          << arr->getDynamics()->getParkingName(fp->getGate())
749             //          << endl;
750             // }
751             if (prev->name == "END")
752                 fp->setTime(trafficRef->getDepartureTime());
753             //cerr << "5" << endl;
754         }
755
756         if (next) {
757             //cerr << "Current waypoint" << curr->name << endl;
758             //cerr << "Next waypoint" << next->name << endl;
759             fp->setLeadDistance(speed, tgt_heading, curr, next);
760         }
761
762         //cerr << "5.1" << endl;
763         if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
764             tgt_altitude = prev->altitude;
765             if (curr->crossat > -1000.0) {
766                 //cerr << "5.1a" << endl;
767                 use_perf_vs = false;
768                 tgt_vs = (curr->crossat - altitude) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
769                         / 6076.0 / speed*60.0);
770                 //cerr << "5.1b" << endl;
771                 tgt_altitude = curr->crossat;
772             } else {
773                 //cerr << "5.1c" << endl;
774                 use_perf_vs = true;
775                 //cerr << "5.1d" << endl;
776                 //cerr << "Setting target altitude : " <<tgt_altitude << endl;
777             }
778         }
779         //cerr << "6" << endl;
780         tgt_speed = prev->speed;
781         hdg_lock = alt_lock = true;
782         no_roll = prev->on_ground;
783         //cout << "Crossing waypoint: " << prev->name << endl;
784         //cout << "  Target speed:    " << tgt_speed << endl;
785         //cout << "  Target altitude: " << tgt_altitude << endl;
786         //cout << "  Target heading:  " << tgt_heading << endl << endl;
787
788     } else {
789         double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
790         //cerr << "Bearing = " << calc_bearing << endl;
791         if (speed < 0) {
792             calc_bearing +=180;
793             if (calc_bearing > 360)
794                 calc_bearing -= 360;
795         }
796
797         if (finite(calc_bearing)) {
798             double hdg_error = calc_bearing - tgt_heading;
799             if (fabs(hdg_error) > 1.0) {
800                 TurnTo( calc_bearing );
801             }
802
803         } else {
804             cerr << "calc_bearing is not a finite number : "
805                  << "Speed " << speed
806                  << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
807                  << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
808             cerr << "waypoint name " << curr->name;
809             exit(1);  // FIXME
810         }
811
812         double speed_diff = speed - prevSpeed;
813         // Update the lead distance calculation if speed has changed sufficiently
814         // to prevent spinning (hopefully);
815         if (fabs(speed_diff) > 10) {
816             prevSpeed = speed;
817             fp->setLeadDistance(speed, tgt_heading, curr, next);
818         }
819
820         //cerr << "Done Processing FlightPlan"<< endl;
821     }
822 }
823
824
825 bool FGAIAircraft::_getGearDown() const {
826     return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
827             && (props->getFloatValue("velocities/airspeed-kt")
828             < performance->land_speed*1.25));
829 }
830
831
832 void FGAIAircraft::loadNextLeg() {
833     //delete fp;
834     //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
835
836     //FGAIModelEntity entity;
837     //entity.m_class = "jet_transport";
838     //entity.path = modelPath.c_str();
839     //entity.flightplan = "none";
840     //entity.latitude = _getLatitude();
841     //entity.longitude = _getLongitude();
842     //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
843     //entity.speed = 450; // HACK ALERT
844     //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
845     int leg;
846     if ((leg = fp->getLeg())  == 10) {
847         trafficRef->next();
848         leg = 1;
849         fp->setLeg(leg);
850         //cerr << "Resetting leg : " << leg << endl;
851     }
852     //leg++;
853     //fp->setLeg(leg);
854     //cerr << "Creating leg number : " << leg << endl;
855     FGAirport *dep = trafficRef->getDepartureAirport();
856     FGAirport *arr = trafficRef->getArrivalAirport();
857     if (!(dep && arr)) {
858         setDie(true);
859         //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
860         //if (dep)
861         //  cerr << "Departure " << dep->getId() << endl;
862         //if (arr)
863         //  cerr << "Arrival   " << arr->getId() << endl;
864
865     } else {
866         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
867         //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
868
869         fp->create (dep,
870                     arr,
871                     leg,
872                     cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
873                     trafficRef->getSpeed(),
874                     _getLatitude(),
875                     _getLongitude(),
876                     false,
877                     trafficRef->getRadius(),
878                     trafficRef->getFlightType(),
879                     acType,
880                     company);
881         //prev = fp->getPreviousWaypoint();
882         //curr = fp->getCurrentWaypoint();
883         //next = fp->getNextWaypoint();
884         //cerr << "25" << endl;
885         //if (next)
886         //        {
887         //  //cerr << "Next waypoint" << next->name << endl;
888         //          fp->setLeadDistance(speed, tgt_heading, curr, next);
889         //        }
890         //cerr << "25.1" << endl;
891         //if (curr->crossat > -1000.0) {
892         //        //cerr << "25.1a" << endl;
893         //        use_perf_vs = false;
894         //
895         //        tgt_vs = (curr->crossat - altitude)/
896         //          (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
897         //        //cerr << "25.1b" << endl;
898         //        tgt_altitude = curr->crossat;
899         //} else {
900         //        //cerr << "25.1c" << endl;
901         //        use_perf_vs = true;
902         //        //cerr << "25.1d" << endl;
903         //        tgt_altitude = prev->altitude;
904         //        //cerr << "Setting target altitude : " <<tgt_altitude << endl;
905         // }
906         //cerr << "26" << endl;
907         //tgt_speed = prev->speed;
908         //hdg_lock = alt_lock = true;
909         //no_roll = prev->on_ground;
910     }
911     //else
912     //{
913     //delete entity.fp;
914     //entity.fp = new FGAIFlightPlan(&entity,
915     //                                 999,  // A hack
916     //                                 trafficRef->getDepartureTime(),
917     //                                 trafficRef->getDepartureAirport(),
918     //                                 trafficRef->getArrivalAirport(),
919     //                                 false,
920     //                                 acType,
921     //                                 company);
922     //SetFlightPlan(entity.fp);
923 }
924
925
926 // Note: This code is copied from David Luff's AILocalTraffic
927 // Warning - ground elev determination is CPU intensive
928 // Either this function or the logic of how often it is called
929 // will almost certainly change.
930
931 void FGAIAircraft::getGroundElev(double dt) {
932     dt_elev_count += dt;
933
934     // Update minimally every three secs, but add some randomness
935     // to prevent all IA objects doing this in synchrony
936     if (dt_elev_count < (3.0) + (rand() % 10))
937         return;
938     else
939        dt_elev_count = 0;
940
941     // Only do the proper hitlist stuff if we are within visible range of the viewer.
942     if (!invisible) {
943         double visibility_meters = fgGetDouble("/environment/visibility-m");
944
945         FGViewer* vw = globals->get_current_view();
946         double course, distance;
947
948         SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
949         SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
950         view.CourseAndDistance(current, &course, &distance);
951         if(distance > visibility_meters) {
952             //aip.getSGLocation()->set_cur_elev_m(aptElev);
953             return;
954         }
955
956         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
957         double range = 500.0;
958         if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
959             // Try to shedule tiles for that position.
960             globals->get_tile_mgr()->update( aip.getSGLocation(), range );
961         }
962
963         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
964         double alt;
965         if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
966             tgt_altitude = alt * SG_METER_TO_FEET;
967
968         //cerr << "Target altitude : " << tgt_altitude << endl;
969         // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
970         //                                            20000.0, alt))
971         //    tgt_altitude = alt * SG_METER_TO_FEET;
972         //cerr << "Target altitude : " << tgt_altitude << endl;
973     }
974 }
975
976
977 void FGAIAircraft::setCallSign(const string& s) {
978     callsign = s;
979 }
980
981
982 void FGAIAircraft::setTACANChannelID(const string& id) {
983     TACAN_channel_id = id;
984 }
985
986
987 void FGAIAircraft::doGroundAltitude() {
988    if (fabs(altitude - (tgt_altitude+groundOffset)) > 1000.0)
989        altitude = (tgt_altitude + groundOffset);
990    else
991       altitude += 0.1 * ((tgt_altitude+groundOffset) - altitude);
992 }
993