]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
Patch by Torsten Dryer: Remove the Ugly global dialog variable and remove rwy as...
[flightgear.git] / src / AIModel / AIFlightPlanCreate.cxx
1 /******************************************************************************
2  * AIFlightPlanCreate.cxx
3  * Written by Durk Talsma, started May, 2004.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  **************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25
26 #include "AIFlightPlan.hxx"
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/props/props.hxx>
29 #include <simgear/props/props_io.hxx>
30
31 #include <Airports/simple.hxx>
32 #include <Airports/runways.hxx>
33 #include <Airports/dynamics.hxx>
34 #include "AIAircraft.hxx"
35 #include "performancedata.hxx"
36
37 #include <Environment/environment_mgr.hxx>
38 #include <Environment/environment.hxx>
39
40
41 /* FGAIFlightPlan::create()
42  * dynamically create a flight plan for AI traffic, based on data provided by the
43  * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10) 
44  *
45  * This is the top-level function, and the only one that is publicly available.
46  *
47  */
48
49
50 // Check lat/lon values during initialization;
51 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
52                             FGAirport * arr, int legNr, double alt,
53                             double speed, double latitude,
54                             double longitude, bool firstFlight,
55                             double radius, const string & fltType,
56                             const string & aircraftType,
57                             const string & airline, double distance)
58 {
59     bool retVal = true;
60     int currWpt = wpt_iterator - waypoints.begin();
61     switch (legNr) {
62     case 1:
63         retVal = createPushBack(ac, firstFlight, dep, latitude, longitude,
64                                 radius, fltType, aircraftType, airline);
65         break;
66     case 2:
67         retVal =  createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
68                           aircraftType, airline);
69         break;
70     case 3:
71         retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
72         break;
73     case 4:
74         retVal = createClimb(ac, firstFlight, dep, speed, alt, fltType);
75         break;
76     case 5:
77         retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
78                      alt, fltType);
79         break;
80     case 6:
81         retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
82                       distance);
83         break;
84     case 7:
85         retVal = createLanding(ac, arr, fltType);
86         break;
87     case 8:
88         retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
89         break;
90     case 9:
91         retVal = createParking(ac, arr, radius);
92         break;
93     default:
94         //exit(1);
95         SG_LOG(SG_INPUT, SG_ALERT,
96                "AIFlightPlan::create() attempting to create unknown leg"
97                " this is probably an internal program error");
98     }
99     wpt_iterator = waypoints.begin() + currWpt;
100     //don't  increment leg right away, but only once we pass the actual last waypoint that was created.
101     // to do so, mark the last waypoint with a special status flag
102    if (retVal) {
103         waypoints.back()->setName( waypoints.back()->getName() + string("legend")); 
104         // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
105    }
106
107
108     //leg++;
109     return retVal;
110 }
111
112 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
113                                    const std::string & aName,
114                                    const SGGeod & aPos, double aElev,
115                                    double aSpeed)
116 {
117     FGAIWaypoint *wpt  = new FGAIWaypoint;
118     wpt->setName       (aName                  );
119     wpt->setLongitude  (aPos.getLongitudeDeg() );
120     wpt->setLatitude   (aPos.getLatitudeDeg()  );
121     wpt->setAltitude   (aElev                  );
122     wpt->setSpeed      (aSpeed                 );
123     wpt->setCrossat    (-10000.1               );
124     wpt->setGear_down  (true                   );
125     wpt->setFlaps_down (true                   );
126     wpt->setFinished   (false                  );
127     wpt->setOn_ground  (true                   );
128     wpt->setRouteIndex (0                      );
129     return wpt;
130 }
131
132 FGAIWaypoint *    FGAIFlightPlan::createInAir(FGAIAircraft * ac,
133                                 const std::string & aName,
134                                 const SGGeod & aPos, double aElev,
135                                 double aSpeed)
136 {
137     FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
138     wpt->setGear_down  (false                   );
139     wpt->setFlaps_down (false                   );
140     wpt->setOn_ground  (false                   );
141     return wpt;
142 }
143
144 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
145 {
146     FGAIWaypoint *wpt = new FGAIWaypoint;
147     wpt->setName       ( aWpt->getName ()      );
148     wpt->setLongitude  ( aWpt->getLongitude()  );
149     wpt->setLatitude   ( aWpt->getLatitude()   );
150     wpt->setAltitude   ( aWpt->getAltitude()   );
151     wpt->setSpeed      ( aWpt->getSpeed()      );
152     wpt->setCrossat    ( aWpt->getCrossat()    );
153     wpt->setGear_down  ( aWpt->getGear_down()  );
154     wpt->setFlaps_down ( aWpt->getFlaps_down() );
155     wpt->setFinished   ( aWpt->isFinished()    );
156     wpt->setOn_ground  ( aWpt->getOn_ground()  );
157     wpt->setRouteIndex ( 0                     );
158
159     return wpt;
160 }
161
162
163 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
164                                  const std::string & aName,
165                                  const SGGeod & aPos)
166 {
167     FGAIWaypoint *wpt = clone(aWpt);
168     wpt->setName       ( aName                   );
169     wpt->setLongitude  ( aPos.getLongitudeDeg () );
170     wpt->setLatitude   ( aPos.getLatitudeDeg  () );
171
172     return wpt;
173 }
174
175
176
177 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
178                                               FGAirport * aAirport,
179                                               FGRunway * aRunway)
180 {
181     SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
182     double airportElev = aAirport->getElevation();
183
184     FGAIWaypoint *wpt;
185     wpt =
186         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
187                        ac->getPerformance()->vTaxi());
188     waypoints.push_back(wpt);
189     wpt =
190         createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
191                        ac->getPerformance()->vTaxi());
192     waypoints.push_back(wpt);
193 }
194
195 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
196                                        FGAirport * apt,
197                                        double radius,
198                                        const string & fltType,
199                                        const string & acType,
200                                        const string & airline)
201 {
202     double heading, lat, lon;
203
204     // If this function is called during initialization,
205     // make sure we obtain a valid gate ID first
206     // and place the model at the location of the gate.
207     if (firstFlight) {
208         if (!(apt->getDynamics()->getAvailableParking(&lat, &lon,
209                                                       &heading, &gateId,
210                                                       radius, fltType,
211                                                       acType, airline))) {
212             SG_LOG(SG_INPUT, SG_WARN, "Could not find parking for a " <<
213                    acType <<
214                    " of flight type " << fltType <<
215                    " of airline     " << airline <<
216                    " at airport     " << apt->getId());
217         }
218     }
219
220     string rwyClass = getRunwayClassFromTrafficType(fltType);
221
222     // Only set this if it hasn't been set by ATC already.
223     if (activeRunway.empty()) {
224         //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
225         double depHeading = ac->getTrafficRef()->getCourse();
226         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
227                                             depHeading);
228     }
229     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
230     assert( rwy != NULL );
231     SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
232
233     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
234     if (!gn->exists()) {
235         createDefaultTakeoffTaxi(ac, apt, rwy);
236         return true;
237     }
238
239     intVec ids;
240     int runwayId = gn->findNearestNode(runwayTakeoff);
241
242     // A negative gateId indicates an overflow parking, use a
243     // fallback mechanism for this. 
244     // Starting from gate 0 in this case is a bit of a hack
245     // which requires a more proper solution later on.
246     delete taxiRoute;
247     taxiRoute = new FGTaxiRoute;
248
249     // Determine which node to start from.
250     int node = 0;
251     // Find out which node to start from
252     FGParking *park = apt->getDynamics()->getParking(gateId);
253     if (park) {
254         node = park->getPushBackPoint();
255     }
256
257     if (node == -1) {
258         node = gateId;
259     }
260     // HAndle case where parking doens't have a node
261     if ((node == 0) && park) {
262         if (firstFlight) {
263             node = gateId;
264         } else {
265             node = lastNodeVisited;
266         }
267     }
268
269     *taxiRoute = gn->findShortestRoute(node, runwayId);
270     intVecIterator i;
271
272     if (taxiRoute->empty()) {
273         createDefaultTakeoffTaxi(ac, apt, rwy);
274         return true;
275     }
276
277     taxiRoute->first();
278     //bool isPushBackPoint = false;
279     if (firstFlight) {
280         // If this is called during initialization, randomly
281         // skip a number of waypoints to get a more realistic
282         // taxi situation.
283         int nrWaypointsToSkip = rand() % taxiRoute->size();
284         // but make sure we always keep two active waypoints
285         // to prevent a segmentation fault
286         for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
287             taxiRoute->next(&node);
288         }
289         apt->getDynamics()->releaseParking(gateId);
290     } else {
291         if (taxiRoute->size() > 1) {
292             taxiRoute->next(&node);     // chop off the first waypoint, because that is already the last of the pushback route
293         }
294     }
295
296     // push each node on the taxi route as a waypoint
297     int route;
298     //cerr << "Building taxi route" << endl;
299     while (taxiRoute->next(&node, &route)) {
300         char buffer[10];
301         snprintf(buffer, 10, "%d", node);
302         FGTaxiNode *tn =
303             apt->getDynamics()->getGroundNetwork()->findNode(node);
304         FGAIWaypoint *wpt =
305             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
306                            ac->getPerformance()->vTaxi());
307         wpt->setRouteIndex(route);
308         //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
309         if (taxiRoute->nodesLeft() == 1) {
310             // Note that we actually have hold points in the ground network, but this is just an initial test.
311             //cerr << "Setting departurehold point: " << endl;
312             wpt->setName( wpt->getName() + string("DepartureHold"));
313         }
314         waypoints.push_back(wpt);
315     }
316     // Acceleration point, 105 meters into the runway,
317     SGGeod accelPoint = rwy->pointOnCenterline(105.0);
318     FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
319     waypoints.push_back(wpt);
320
321     //cerr << "[done]" << endl;
322     return true;
323 }
324
325 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
326                                               FGAirport * aAirport)
327 {
328     SGGeod lastWptPos =
329         SGGeod::fromDeg(waypoints.back()->getLongitude(),
330                         waypoints.back()->getLatitude());
331     double airportElev = aAirport->getElevation();
332
333     FGAIWaypoint *wpt;
334     wpt =
335         createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
336                        ac->getPerformance()->vTaxi());
337     waypoints.push_back(wpt);
338     wpt =
339         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
340                        ac->getPerformance()->vTaxi());
341     waypoints.push_back(wpt);
342
343     double heading, lat, lon;
344     aAirport->getDynamics()->getParking(gateId, &lat, &lon, &heading);
345     wpt =
346         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), airportElev,
347                        ac->getPerformance()->vTaxi());
348     waypoints.push_back(wpt);
349 }
350
351 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
352                                        double radius,
353                                        const string & fltType,
354                                        const string & acType,
355                                        const string & airline)
356 {
357     double heading, lat, lon;
358     apt->getDynamics()->getAvailableParking(&lat, &lon, &heading,
359                                             &gateId, radius, fltType,
360                                             acType, airline);
361
362     SGGeod lastWptPos =
363         SGGeod::fromDeg(waypoints.back()->getLongitude(),
364                         waypoints.back()->getLatitude());
365     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
366
367     // Find a route from runway end to parking/gate.
368     if (!gn->exists()) {
369         createDefaultLandingTaxi(ac, apt);
370         return true;
371     }
372
373     intVec ids;
374     int runwayId = gn->findNearestNode(lastWptPos);
375     // A negative gateId indicates an overflow parking, use a
376     // fallback mechanism for this. 
377     // Starting from gate 0 is a bit of a hack...
378     //FGTaxiRoute route;
379     delete taxiRoute;
380     taxiRoute = new FGTaxiRoute;
381     if (gateId >= 0)
382         *taxiRoute = gn->findShortestRoute(runwayId, gateId);
383     else
384         *taxiRoute = gn->findShortestRoute(runwayId, 0);
385     intVecIterator i;
386
387     if (taxiRoute->empty()) {
388         createDefaultLandingTaxi(ac, apt);
389         return true;
390     }
391
392     int node;
393     taxiRoute->first();
394     int size = taxiRoute->size();
395     // Omit the last two waypoints, as 
396     // those are created by createParking()
397     int route;
398     for (int i = 0; i < size - 2; i++) {
399         taxiRoute->next(&node, &route);
400         char buffer[10];
401         snprintf(buffer, 10, "%d", node);
402         FGTaxiNode *tn = gn->findNode(node);
403         FGAIWaypoint *wpt =
404             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
405                            ac->getPerformance()->vTaxi());
406         wpt->setRouteIndex(route);
407         waypoints.push_back(wpt);
408     }
409     return true;
410 }
411
412 /*******************************************************************
413  * CreateTakeOff 
414  * A note on units: 
415  *  - Speed -> knots -> nm/hour
416  *  - distance along runway =-> meters 
417  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
418  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
419  *  given respectively. According to performance data.cxx, a value of kts / second seems
420  *  more likely however. 
421  * 
422  ******************************************************************/
423 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
424                                    FGAirport * apt, double speed,
425                                    const string & fltType)
426 {
427     double accel = ac->getPerformance()->acceleration();
428     double vTaxi = ac->getPerformance()->vTaxi();
429     double vRotate = ac->getPerformance()->vRotate();
430     double vTakeoff = ac->getPerformance()->vTakeoff();
431     //double vClimb = ac->getPerformance()->vClimb();
432
433     double accelMetric = (accel * SG_NM_TO_METER) / 3600;
434     double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600;
435     double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600;
436     double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600;
437     //double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600;
438     // Acceleration = dV / dT
439     // Acceleration X dT = dV
440     // dT = dT / Acceleration
441     //d = (Vf^2 - Vo^2) / (2*a)
442     //double accelTime = (vRotate - vTaxi) / accel;
443     //cerr << "Using " << accelTime << " as total acceleration time" << endl;
444     double accelDistance =
445         (vRotateMetric * vRotateMetric -
446          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
447     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl;
448     FGAIWaypoint *wpt;
449     // Get the current active runway, based on code from David Luff
450     // This should actually be unified and extended to include 
451     // Preferential runway use schema's 
452     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
453     // because the getActive runway function takes care of that.
454     if (firstFlight) {
455         string rwyClass = getRunwayClassFromTrafficType(fltType);
456         double heading = ac->getTrafficRef()->getCourse();
457         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
458                                             heading);
459     }
460     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
461     assert( rwy != NULL );
462
463     double airportElev = apt->getElevation();
464     
465
466     accelDistance =
467         (vTakeoffMetric * vTakeoffMetric -
468          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
469     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
470     SGGeod accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
471     wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
472     waypoints.push_back(wpt);
473
474     accelDistance =
475         ((vTakeoffMetric * 1.1) * (vTakeoffMetric * 1.1) -
476          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
477     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
478     accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
479     wpt =
480         createOnGround(ac, "rotate", accelPoint, airportElev + 1000,
481                        vTakeoff * 1.1);
482     wpt->setOn_ground(false);
483     waypoints.push_back(wpt);
484
485     wpt = cloneWithPos(ac, wpt, "3000 ft", rwy->end());
486     wpt->setAltitude(airportElev + 3000);
487     waypoints.push_back(wpt);
488
489     // Finally, add two more waypoints, so that aircraft will remain under
490     // Tower control until they have reached the 3000 ft climb point
491     SGGeod pt = rwy->pointOnCenterline(5000 + rwy->lengthM() * 0.5);
492     wpt = cloneWithPos(ac, wpt, "5000 ft", pt);
493     wpt->setAltitude(airportElev + 5000);
494     waypoints.push_back(wpt);
495     return true;
496 }
497
498 /*******************************************************************
499  * CreateClimb
500  * initialize the Aircraft at the parking location
501  ******************************************************************/
502 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
503                                  FGAirport * apt, double speed, double alt,
504                                  const string & fltType)
505 {
506     FGAIWaypoint *wpt;
507 //  bool planLoaded = false;
508     string fPLName;
509     double vClimb = ac->getPerformance()->vClimb();
510
511     if (firstFlight) {
512         string rwyClass = getRunwayClassFromTrafficType(fltType);
513         double heading = ac->getTrafficRef()->getCourse();
514         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
515                                             heading);
516     }
517     if (sid) {
518         for (wpt_vector_iterator i = sid->getFirstWayPoint();
519              i != sid->getLastWayPoint(); i++) {
520             waypoints.push_back(clone(*(i)));
521             //cerr << " Cloning waypoint " << endl;
522         }
523     } else {
524         FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
525         assert( rwy != NULL );
526
527         SGGeod climb1 = rwy->pointOnCenterline(10 * SG_NM_TO_METER);
528         wpt = createInAir(ac, "10000ft climb", climb1, vClimb, 10000);
529         wpt->setGear_down(true);
530         wpt->setFlaps_down(true);
531         waypoints.push_back(wpt);
532
533         SGGeod climb2 = rwy->pointOnCenterline(20 * SG_NM_TO_METER);
534         wpt = cloneWithPos(ac, wpt, "18000ft climb", climb2);
535         wpt->setAltitude(18000);
536         waypoints.push_back(wpt);
537     }
538     return true;
539 }
540
541
542
543 /*******************************************************************
544  * CreateDescent
545  * Generate a flight path from the last waypoint of the cruise to 
546  * the permission to land point
547  ******************************************************************/
548 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
549                                    double latitude, double longitude,
550                                    double speed, double alt,
551                                    const string & fltType,
552                                    double requiredDistance)
553 {
554     bool reposition = false;
555     FGAIWaypoint *wpt;
556     double vDescent = ac->getPerformance()->vDescent();
557     double vApproach = ac->getPerformance()->vApproach();
558
559
560     //Beginning of Descent 
561     string rwyClass = getRunwayClassFromTrafficType(fltType);
562     double heading = ac->getTrafficRef()->getCourse();
563     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
564                                         heading);
565     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
566     assert( rwy != NULL );
567
568     // Create a slow descent path that ends 250 lateral to the runway.
569     double initialTurnRadius = getTurnRadius(vDescent, true);
570     //double finalTurnRadius = getTurnRadius(vApproach, true);
571
572 // get length of the downwind leg for the intended runway
573     double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance();    //12 * SG_NM_TO_METER;
574     //time_t previousArrivalTime=  apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
575
576
577     SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
578     SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
579     SGGeod refPoint = rwy->pointOnCenterline(0);
580     double distance = SGGeodesy::distanceM(current, initialTarget);
581     double azimuth = SGGeodesy::courseDeg(current, initialTarget);
582     double dummyAz2;
583
584     // To prevent absurdly steep approaches, compute the origin from where the approach should have started
585     SGGeod origin;
586
587     if (ac->getTrafficRef()->getCallSign() ==
588         fgGetString("/ai/track-callsign")) {
589         //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
590         //exit(1);
591     }
592
593     if (distance < requiredDistance * 0.8) {
594         reposition = true;
595         SGGeodesy::direct(initialTarget, azimuth,
596                           -requiredDistance, origin, dummyAz2);
597
598         distance = SGGeodesy::distanceM(current, initialTarget);
599         azimuth = SGGeodesy::courseDeg(current, initialTarget);
600     } else {
601         origin = current;
602     }
603
604
605     double dAlt = alt - (apt->getElevation() + 2000);
606
607     double nPoints = 100;
608
609     char buffer[16];
610
611     // The descent path contains the following phases:
612     // 1) a linear glide path from the initial position to
613     // 2) a semi circle turn to final
614     // 3) approach
615
616     //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
617     // Create an initial destination point on a semicircle
618     //cerr << "lateral offset : " << lateralOffset << endl;
619     //cerr << "Distance       : " << distance      << endl;
620     //cerr << "Azimuth        : " << azimuth       << endl;
621     //cerr << "Initial Lateral point: " << lateralOffset << endl;
622     double lat = refPoint.getLatitudeDeg();
623     double lon = refPoint.getLongitudeDeg();
624     //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
625     lat = initialTarget.getLatitudeDeg();
626     lon = initialTarget.getLongitudeDeg();
627     //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
628
629     double ratio = initialTurnRadius / distance;
630     if (ratio > 1.0)
631         ratio = 1.0;
632     if (ratio < -1.0)
633         ratio = -1.0;
634
635     double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
636     double newDistance =
637         cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
638     //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
639     double side = azimuth - rwy->headingDeg();
640     double lateralOffset = initialTurnRadius;
641     if (side < 0)
642         side += 360;
643     if (side < 180) {
644         lateralOffset *= -1;
645     }
646     // Calculate the ETA at final, based on remaining distance, and approach speed.
647     // distance should really consist of flying time to terniary target, plus circle 
648     // but the distance to secondary target should work as a reasonable approximation
649     // aditionally add the amount of distance covered by making a turn of "side"
650     double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
651     time_t remaining =
652         (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
653     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
654     //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
655     //     cerr << "   Arrival time estimation: turn angle " <<  side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
656     //     //exit(1);
657     //}
658
659     time_t eta = now + remaining;
660     //choose a distance to the runway such that it will take at least 60 seconds more
661     // time to get there than the previous aircraft.
662     // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
663
664     time_t newEta;
665
666     if (reposition == false) {
667         newEta =
668             apt->getDynamics()->getApproachController()->getRunway(rwy->
669                                                                    name
670                                                                    ())->
671             requestTimeSlot(eta);
672     } else {
673         newEta = eta;
674     }
675     //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
676     arrivalTime = newEta;
677     time_t additionalTimeNeeded = newEta - eta;
678     double distanceCovered =
679         ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
680     distanceOut += distanceCovered;
681     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
682     //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
683     //} else {
684     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
685     //}
686     //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
687
688     SGGeod secondaryTarget =
689         rwy->pointOffCenterline(-distanceOut, lateralOffset);
690     initialTarget = rwy->pointOnCenterline(-distanceOut);
691     distance = SGGeodesy::distanceM(origin, secondaryTarget);
692     azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
693
694
695     lat = secondaryTarget.getLatitudeDeg();
696     lon = secondaryTarget.getLongitudeDeg();
697     //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
698     //cerr << "Distance       : " << distance      << endl;
699     //cerr << "Azimuth        : " << azimuth       << endl;
700
701
702     ratio = initialTurnRadius / distance;
703     if (ratio > 1.0)
704         ratio = 1.0;
705     if (ratio < -1.0)
706         ratio = -1.0;
707     newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
708     newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
709     //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
710     if (side < 180) {
711         azimuth += newHeading;
712     } else {
713         azimuth -= newHeading;
714     }
715
716     SGGeod tertiaryTarget;
717     SGGeodesy::direct(origin, azimuth,
718                       newDistance, tertiaryTarget, dummyAz2);
719
720     lat = tertiaryTarget.getLatitudeDeg();
721     lon = tertiaryTarget.getLongitudeDeg();
722     //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
723
724
725     for (int i = 1; i < nPoints; i++) {
726         SGGeod result;
727         double currentDist = i * (newDistance / nPoints);
728         double currentAltitude = alt - (i * (dAlt / nPoints));
729         SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
730         snprintf(buffer, 16, "descent%03d", i);
731         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
732         wpt->setCrossat(currentAltitude);
733         wpt->setTrackLength((newDistance / nPoints));
734         waypoints.push_back(wpt);
735         //cerr << "Track Length : " << wpt->trackLength;
736         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
737     }
738
739     //cerr << "Phase 2: Circle " << endl;
740     double initialAzimuth =
741         SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
742     double finalAzimuth =
743         SGGeodesy::courseDeg(secondaryTarget, initialTarget);
744
745     //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
746     int increment, startval, endval;
747     // circle right around secondary target if orig of position is to the right of the runway
748     // i.e. use negative angles; else circle leftward and use postivi
749     if (side < 180) {
750         increment = -1;
751         startval = floor(initialAzimuth);
752         endval = ceil(finalAzimuth);
753         if (endval > startval) {
754             endval -= 360;
755         }
756     } else {
757         increment = 1;
758         startval = ceil(initialAzimuth);
759         endval = floor(finalAzimuth);
760         if (endval < startval) {
761             endval += 360;
762         }
763
764     }
765
766     //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
767     double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
768     for (int i = startval; i != endval; i += increment) {
769         SGGeod result;
770         double currentAltitude = apt->getElevation() + 2000;
771         SGGeodesy::direct(secondaryTarget, i,
772                           initialTurnRadius, result, dummyAz2);
773         snprintf(buffer, 16, "turn%03d", i);
774         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
775         wpt->setCrossat(currentAltitude);
776         wpt->setTrackLength(trackLength);
777         //cerr << "Track Length : " << wpt->trackLength;
778         waypoints.push_back(wpt);
779         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
780     }
781
782
783     // The approach leg should bring the aircraft to approximately 4-6 out, after which the landing phase should take over. 
784     //cerr << "Phase 3: Approach" << endl;
785     distanceOut -= distanceCovered;
786     for (int i = 1; i < nPoints; i++) {
787         SGGeod result;
788         double currentDist = i * (distanceOut / nPoints);
789         double currentAltitude =
790             apt->getElevation() + 2000 - (i * 2000 / nPoints);
791         snprintf(buffer, 16, "final%03d", i);
792         result = rwy->pointOnCenterline((-distanceOut) + currentDist);
793         wpt = createInAir(ac, buffer, result, currentAltitude, vApproach);
794         wpt->setCrossat(currentAltitude);
795         wpt->setTrackLength((distanceOut / nPoints));
796         // account for the extra distance due to an extended downwind leg
797         if (i == 1) {
798             wpt->setTrackLength(wpt->getTrackLength() + distanceCovered);
799         }
800         //cerr << "Track Length : " << wpt->trackLength;
801         waypoints.push_back(wpt);
802         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
803     }
804
805     //cerr << "Done" << endl;
806
807     // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
808     IncrementWaypoint(true);
809     IncrementWaypoint(true);
810
811     if (reposition) {
812         double tempDistance;
813         //double minDistance = HUGE_VAL;
814         string wptName;
815         tempDistance = SGGeodesy::distanceM(current, initialTarget);
816         time_t eta =
817             tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
818         time_t newEta =
819             apt->getDynamics()->getApproachController()->getRunway(rwy->
820                                                                    name
821                                                                    ())->
822             requestTimeSlot(eta);
823         arrivalTime = newEta;
824         double newDistance =
825             ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
826         //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
827         IncrementWaypoint(true);        // remove waypoint BOD2
828         while (checkTrackLength("final001") > newDistance) {
829             IncrementWaypoint(true);
830         }
831         //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
832         ac->resetPositionFromFlightPlan();
833     }
834     waypoints[1]->setName( (waypoints[1]->getName() + string("legend"))); 
835     return true;
836 }
837
838 /*******************************************************************
839  * CreateLanding
840  * Create a flight path from the "permision to land" point (currently
841    hardcoded at 5000 meters from the threshold) to the threshold, at
842    a standard glide slope angle of 3 degrees. 
843  ******************************************************************/
844 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
845                                    const string & fltType)
846 {
847     double vTouchdown = ac->getPerformance()->vTouchdown();
848     //double vTaxi = ac->getPerformance()->vTaxi();
849
850     //string rwyClass = getRunwayClassFromTrafficType(fltType);
851     //double heading = ac->getTrafficRef()->getCourse();
852     //apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway, heading);
853     //rwy = apt->getRunwayByIdent(activeRunway);
854
855
856     FGAIWaypoint *wpt;
857     double aptElev = apt->getElevation();
858
859     SGGeod coord;
860     char buffer[12];
861     for (int i = 1; i < 10; i++) {
862         snprintf(buffer, 12, "wpt%d", i);
863         FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
864         assert( rwy != NULL );
865
866         coord = rwy->pointOnCenterline(rwy->lengthM() * (i / 10.0));
867         wpt = createOnGround(ac, buffer, coord, aptElev, (vTouchdown / i));
868         wpt->setCrossat(apt->getElevation());
869         waypoints.push_back(wpt);
870     }
871
872     /*
873        //Runway Threshold
874        wpt = createOnGround(ac, "Threshold", rwy->threshold(), aptElev, vTouchdown);
875        wpt->crossat = apt->getElevation();
876        waypoints.push_back(wpt); 
877
878        // Roll-out
879        wpt = createOnGround(ac, "Center", rwy->geod(), aptElev, vTaxi*2);
880        waypoints.push_back(wpt);
881
882        SGGeod rollOut = rwy->pointOnCenterline(rwy->lengthM() * 0.9);
883        wpt = createOnGround(ac, "Roll Out", rollOut, aptElev, vTaxi);
884        wpt->crossat   = apt->getElevation();
885        waypoints.push_back(wpt); 
886      */
887     return true;
888 }
889
890 /*******************************************************************
891  * CreateParking
892  * initialize the Aircraft at the parking location
893  ******************************************************************/
894 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
895                                    double radius)
896 {
897     FGAIWaypoint *wpt;
898     double aptElev = apt->getElevation();
899     double lat = 0.0, lat2 = 0.0;
900     double lon = 0.0, lon2 = 0.0;
901     double az2 = 0.0;
902     double heading = 0.0;
903
904     double vTaxi = ac->getPerformance()->vTaxi();
905     double vTaxiReduced = vTaxi * (2.0 / 3.0);
906     apt->getDynamics()->getParking(gateId, &lat, &lon, &heading);
907     heading += 180.0;
908     if (heading > 360)
909         heading -= 360;
910     geo_direct_wgs_84(0, lat, lon, heading,
911                       2.2 * radius, &lat2, &lon2, &az2);
912     wpt =
913         createOnGround(ac, "taxiStart", SGGeod::fromDeg(lon2, lat2),
914                        aptElev, vTaxiReduced);
915     waypoints.push_back(wpt);
916
917     geo_direct_wgs_84(0, lat, lon, heading,
918                       0.1 * radius, &lat2, &lon2, &az2);
919
920     wpt =
921         createOnGround(ac, "taxiStart2", SGGeod::fromDeg(lon2, lat2),
922                        aptElev, vTaxiReduced);
923     waypoints.push_back(wpt);
924
925     wpt =
926         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), aptElev,
927                        vTaxiReduced);
928     waypoints.push_back(wpt);
929     return true;
930 }
931
932 /**
933  *
934  * @param fltType a string describing the type of
935  * traffic, normally used for gate assignments
936  * @return a converted string that gives the runway
937  * preference schedule to be used at aircraft having
938  * a preferential runway schedule implemented (i.e.
939  * having a rwyprefs.xml file
940  * 
941  * Currently valid traffic types for gate assignment:
942  * - gate (commercial gate)
943  * - cargo (commercial gargo),
944  * - ga (general aviation) ,
945  * - ul (ultralight),
946  * - mil-fighter (military - fighter),
947  * - mil-transport (military - transport)
948  *
949  * Valid runway classes:
950  * - com (commercial traffic: jetliners, passenger and cargo)
951  * - gen (general aviation)
952  * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
953  * - mil (all military traffic)
954  */
955 string FGAIFlightPlan::getRunwayClassFromTrafficType(string fltType)
956 {
957     if ((fltType == "gate") || (fltType == "cargo")) {
958         return string("com");
959     }
960     if (fltType == "ga") {
961         return string("gen");
962     }
963     if (fltType == "ul") {
964         return string("ul");
965     }
966     if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
967         return string("mil");
968     }
969     return string("com");
970 }
971
972
973 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
974 {
975     double turn_radius;
976     if (inAir == false) {
977         turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
978     } else {
979         turn_radius = 0.1911 * speed * speed;   // an estimate for 25 degrees bank
980     }
981     return turn_radius;
982 }