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