]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
ef12ac4890733067583948e731c694daafa9c73a
[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 #include "AIFlightPlan.hxx"
26 #include <simgear/math/sg_geodesy.hxx>
27 #include <simgear/props/props.hxx>
28 #include <simgear/props/props_io.hxx>
29
30 #include <Airports/simple.hxx>
31 #include <Airports/runways.hxx>
32 #include <Airports/dynamics.hxx>
33 #include "AIAircraft.hxx"
34 #include "performancedata.hxx"
35
36 #include <Environment/environment_mgr.hxx>
37 #include <Environment/environment.hxx>
38
39
40 /* FGAIFlightPlan::create()
41  * dynamically create a flight plan for AI traffic, based on data provided by the
42  * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10) 
43  *
44  * This is the top-level function, and the only one that is publicly available.
45  *
46  */
47
48
49 // Check lat/lon values during initialization;
50 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
51                             FGAirport * arr, int legNr, double alt,
52                             double speed, double latitude,
53                             double longitude, bool firstFlight,
54                             double radius, const string & fltType,
55                             const string & aircraftType,
56                             const string & airline, double distance)
57 {
58     bool retVal = true;
59     int currWpt = wpt_iterator - waypoints.begin();
60     switch (legNr) {
61     case 1:
62         retVal = createPushBack(ac, firstFlight, dep, latitude, longitude,
63                                 radius, fltType, aircraftType, airline);
64         break;
65     case 2:
66         retVal =  createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
67                           aircraftType, airline);
68         break;
69     case 3:
70         retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
71         break;
72     case 4:
73         retVal = createClimb(ac, firstFlight, dep, speed, alt, fltType);
74         break;
75     case 5:
76         retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
77                      alt, fltType);
78         break;
79     case 6:
80         retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
81                       distance);
82         break;
83     case 7:
84         retVal = createLanding(ac, arr, fltType);
85         break;
86     case 8:
87         retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
88         break;
89     case 9:
90         retVal = createParking(ac, arr, radius);
91         break;
92     default:
93         //exit(1);
94         SG_LOG(SG_INPUT, SG_ALERT,
95                "AIFlightPlan::create() attempting to create unknown leg"
96                " this is probably an internal program error");
97     }
98     wpt_iterator = waypoints.begin() + currWpt;
99     leg++;
100     return retVal;
101 }
102
103 FGAIFlightPlan::waypoint *
104     FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
105                                    const std::string & aName,
106                                    const SGGeod & aPos, double aElev,
107                                    double aSpeed)
108 {
109     waypoint *wpt = new waypoint;
110     wpt->name = aName;
111     wpt->longitude = aPos.getLongitudeDeg();
112     wpt->latitude = aPos.getLatitudeDeg();
113     wpt->altitude = aElev;
114     wpt->speed = aSpeed;
115     wpt->crossat = -10000.1;
116     wpt->gear_down = true;
117     wpt->flaps_down = true;
118     wpt->finished = false;
119     wpt->on_ground = true;
120     wpt->routeIndex = 0;
121     return wpt;
122 }
123
124 FGAIFlightPlan::waypoint *
125     FGAIFlightPlan::createInAir(FGAIAircraft * ac,
126                                 const std::string & aName,
127                                 const SGGeod & aPos, double aElev,
128                                 double aSpeed)
129 {
130     waypoint *wpt = new waypoint;
131     wpt->name = aName;
132     wpt->longitude = aPos.getLongitudeDeg();
133     wpt->latitude = aPos.getLatitudeDeg();
134     wpt->altitude = aElev;
135     wpt->speed = aSpeed;
136     wpt->crossat = -10000.1;
137     wpt->gear_down = false;
138     wpt->flaps_down = false;
139     wpt->finished = false;
140     wpt->on_ground = false;
141     wpt->routeIndex = 0;
142     return wpt;
143 }
144
145 FGAIFlightPlan::waypoint *
146     FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, waypoint * aWpt,
147                                  const std::string & aName,
148                                  const SGGeod & aPos)
149 {
150     waypoint *wpt = new waypoint;
151     wpt->name = aName;
152     wpt->longitude = aPos.getLongitudeDeg();
153     wpt->latitude = aPos.getLatitudeDeg();
154
155     wpt->altitude = aWpt->altitude;
156     wpt->speed = aWpt->speed;
157     wpt->crossat = aWpt->crossat;
158     wpt->gear_down = aWpt->gear_down;
159     wpt->flaps_down = aWpt->flaps_down;
160     wpt->finished = aWpt->finished;
161     wpt->on_ground = aWpt->on_ground;
162     wpt->routeIndex = 0;
163
164     return wpt;
165 }
166
167 FGAIFlightPlan::waypoint * FGAIFlightPlan::clone(waypoint * aWpt)
168 {
169     waypoint *wpt = new waypoint;
170     wpt->name = aWpt->name;
171     wpt->longitude = aWpt->longitude;
172     wpt->latitude = aWpt->latitude;
173
174     wpt->altitude = aWpt->altitude;
175     wpt->speed = aWpt->speed;
176     wpt->crossat = aWpt->crossat;
177     wpt->gear_down = aWpt->gear_down;
178     wpt->flaps_down = aWpt->flaps_down;
179     wpt->finished = aWpt->finished;
180     wpt->on_ground = aWpt->on_ground;
181     wpt->routeIndex = 0;
182
183     return wpt;
184 }
185
186
187 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
188                                               FGAirport * aAirport,
189                                               FGRunway * aRunway)
190 {
191     SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
192     double airportElev = aAirport->getElevation();
193
194     waypoint *wpt;
195     wpt =
196         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
197                        ac->getPerformance()->vTaxi());
198     waypoints.push_back(wpt);
199     wpt =
200         createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
201                        ac->getPerformance()->vTaxi());
202     waypoints.push_back(wpt);
203 }
204
205 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
206                                        FGAirport * apt,
207                                        double radius,
208                                        const string & fltType,
209                                        const string & acType,
210                                        const string & airline)
211 {
212     double heading, lat, lon;
213
214     // If this function is called during initialization,
215     // make sure we obtain a valid gate ID first
216     // and place the model at the location of the gate.
217     if (firstFlight) {
218         if (!(apt->getDynamics()->getAvailableParking(&lat, &lon,
219                                                       &heading, &gateId,
220                                                       radius, fltType,
221                                                       acType, airline))) {
222             SG_LOG(SG_INPUT, SG_WARN, "Could not find parking for a " <<
223                    acType <<
224                    " of flight type " << fltType <<
225                    " of airline     " << airline <<
226                    " at airport     " << apt->getId());
227         }
228     }
229
230     string rwyClass = getRunwayClassFromTrafficType(fltType);
231
232     // Only set this if it hasn't been set by ATC already.
233     if (activeRunway.empty()) {
234         //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
235         double depHeading = ac->getTrafficRef()->getCourse();
236         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
237                                             depHeading);
238     }
239     rwy = apt->getRunwayByIdent(activeRunway);
240     SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
241
242     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
243     if (!gn->exists()) {
244         createDefaultTakeoffTaxi(ac, apt, rwy);
245         return true;
246     }
247
248     intVec ids;
249     int runwayId = gn->findNearestNode(runwayTakeoff);
250
251     // A negative gateId indicates an overflow parking, use a
252     // fallback mechanism for this. 
253     // Starting from gate 0 in this case is a bit of a hack
254     // which requires a more proper solution later on.
255     delete taxiRoute;
256     taxiRoute = new FGTaxiRoute;
257
258     // Determine which node to start from.
259     int node = 0;
260     // Find out which node to start from
261     FGParking *park = apt->getDynamics()->getParking(gateId);
262     if (park) {
263         node = park->getPushBackPoint();
264     }
265
266     if (node == -1) {
267         node = gateId;
268     }
269     // HAndle case where parking doens't have a node
270     if ((node == 0) && park) {
271         if (firstFlight) {
272             node = gateId;
273         } else {
274             node = lastNodeVisited;
275         }
276     }
277
278     *taxiRoute = gn->findShortestRoute(node, runwayId);
279     intVecIterator i;
280
281     if (taxiRoute->empty()) {
282         createDefaultTakeoffTaxi(ac, apt, rwy);
283         return true;
284     }
285
286     taxiRoute->first();
287     //bool isPushBackPoint = false;
288     if (firstFlight) {
289         // If this is called during initialization, randomly
290         // skip a number of waypoints to get a more realistic
291         // taxi situation.
292         int nrWaypointsToSkip = rand() % taxiRoute->size();
293         // but make sure we always keep two active waypoints
294         // to prevent a segmentation fault
295         for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
296             taxiRoute->next(&node);
297         }
298         apt->getDynamics()->releaseParking(gateId);
299     } else {
300         if (taxiRoute->size() > 1) {
301             taxiRoute->next(&node);     // chop off the first waypoint, because that is already the last of the pushback route
302         }
303     }
304
305     // push each node on the taxi route as a waypoint
306     int route;
307     while (taxiRoute->next(&node, &route)) {
308         char buffer[10];
309         snprintf(buffer, 10, "%d", node);
310         FGTaxiNode *tn =
311             apt->getDynamics()->getGroundNetwork()->findNode(node);
312         waypoint *wpt =
313             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
314                            ac->getPerformance()->vTaxi());
315         wpt->routeIndex = route;
316         waypoints.push_back(wpt);
317     }
318     return true;
319 }
320
321 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
322                                               FGAirport * aAirport)
323 {
324     SGGeod lastWptPos =
325         SGGeod::fromDeg(waypoints.back()->longitude,
326                         waypoints.back()->latitude);
327     double airportElev = aAirport->getElevation();
328
329     waypoint *wpt;
330     wpt =
331         createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
332                        ac->getPerformance()->vTaxi());
333     waypoints.push_back(wpt);
334     wpt =
335         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
336                        ac->getPerformance()->vTaxi());
337     waypoints.push_back(wpt);
338
339     double heading, lat, lon;
340     aAirport->getDynamics()->getParking(gateId, &lat, &lon, &heading);
341     wpt =
342         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), airportElev,
343                        ac->getPerformance()->vTaxi());
344     waypoints.push_back(wpt);
345 }
346
347 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
348                                        double radius,
349                                        const string & fltType,
350                                        const string & acType,
351                                        const string & airline)
352 {
353     double heading, lat, lon;
354     apt->getDynamics()->getAvailableParking(&lat, &lon, &heading,
355                                             &gateId, radius, fltType,
356                                             acType, airline);
357
358     SGGeod lastWptPos =
359         SGGeod::fromDeg(waypoints.back()->longitude,
360                         waypoints.back()->latitude);
361     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
362
363     // Find a route from runway end to parking/gate.
364     if (!gn->exists()) {
365         createDefaultLandingTaxi(ac, apt);
366         return true;
367     }
368
369     intVec ids;
370     int runwayId = gn->findNearestNode(lastWptPos);
371     // A negative gateId indicates an overflow parking, use a
372     // fallback mechanism for this. 
373     // Starting from gate 0 is a bit of a hack...
374     //FGTaxiRoute route;
375     delete taxiRoute;
376     taxiRoute = new FGTaxiRoute;
377     if (gateId >= 0)
378         *taxiRoute = gn->findShortestRoute(runwayId, gateId);
379     else
380         *taxiRoute = gn->findShortestRoute(runwayId, 0);
381     intVecIterator i;
382
383     if (taxiRoute->empty()) {
384         createDefaultLandingTaxi(ac, apt);
385         return true;
386     }
387
388     int node;
389     taxiRoute->first();
390     int size = taxiRoute->size();
391     // Omit the last two waypoints, as 
392     // those are created by createParking()
393     int route;
394     for (int i = 0; i < size - 2; i++) {
395         taxiRoute->next(&node, &route);
396         char buffer[10];
397         snprintf(buffer, 10, "%d", node);
398         FGTaxiNode *tn = gn->findNode(node);
399         waypoint *wpt =
400             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
401                            ac->getPerformance()->vTaxi());
402         wpt->routeIndex = route;
403         waypoints.push_back(wpt);
404     }
405     return true;
406 }
407
408 /*******************************************************************
409  * CreateTakeOff 
410  * A note on units: 
411  *  - Speed -> knots -> nm/hour
412  *  - distance along runway =-> meters 
413  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
414  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
415  *  given respectively. According to performance data.cxx, a value of kts / second seems
416  *  more likely however. 
417  * 
418  ******************************************************************/
419 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
420                                    FGAirport * apt, double speed,
421                                    const string & fltType)
422 {
423     double accel = ac->getPerformance()->acceleration();
424     double vTaxi = ac->getPerformance()->vTaxi();
425     double vRotate = ac->getPerformance()->vRotate();
426     double vTakeoff = ac->getPerformance()->vTakeoff();
427     //double vClimb = ac->getPerformance()->vClimb();
428
429     double accelMetric = (accel * SG_NM_TO_METER) / 3600;
430     double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600;
431     double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600;
432     double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600;
433     //double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600;
434     // Acceleration = dV / dT
435     // Acceleration X dT = dV
436     // dT = dT / Acceleration
437     //d = (Vf^2 - Vo^2) / (2*a)
438     //double accelTime = (vRotate - vTaxi) / accel;
439     //cerr << "Using " << accelTime << " as total acceleration time" << endl;
440     double accelDistance =
441         (vRotateMetric * vRotateMetric -
442          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
443     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl;
444     waypoint *wpt;
445     // Get the current active runway, based on code from David Luff
446     // This should actually be unified and extended to include 
447     // Preferential runway use schema's 
448     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
449     // because the getActive runway function takes care of that.
450     if (firstFlight) {
451         string rwyClass = getRunwayClassFromTrafficType(fltType);
452         double heading = ac->getTrafficRef()->getCourse();
453         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
454                                             heading);
455     }
456     rwy = apt->getRunwayByIdent(activeRunway);
457
458
459
460     double airportElev = apt->getElevation();
461     // Acceleration point, 105 meters into the runway,
462     SGGeod accelPoint = rwy->pointOnCenterline(105.0);
463     wpt = createOnGround(ac, "accel", accelPoint, airportElev, vRotate);
464     waypoints.push_back(wpt);
465
466
467     accelDistance =
468         (vTakeoffMetric * vTakeoffMetric -
469          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
470     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
471     accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
472     wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
473     waypoints.push_back(wpt);
474
475     accelDistance =
476         ((vTakeoffMetric * 1.1) * (vTakeoffMetric * 1.1) -
477          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
478     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
479     accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
480     wpt =
481         createOnGround(ac, "rotate", accelPoint, airportElev + 1000,
482                        vTakeoff * 1.1);
483     wpt->on_ground = false;
484     waypoints.push_back(wpt);
485
486     wpt = cloneWithPos(ac, wpt, "3000 ft", rwy->end());
487     wpt->altitude = airportElev + 3000;
488     waypoints.push_back(wpt);
489
490     // Finally, add two more waypoints, so that aircraft will remain under
491     // Tower control until they have reached the 3000 ft climb point
492     SGGeod pt = rwy->pointOnCenterline(5000 + rwy->lengthM() * 0.5);
493     wpt = cloneWithPos(ac, wpt, "5000 ft", pt);
494     wpt->altitude = airportElev + 5000;
495     waypoints.push_back(wpt);
496     return true;
497 }
498
499 /*******************************************************************
500  * CreateClimb
501  * initialize the Aircraft at the parking location
502  ******************************************************************/
503 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
504                                  FGAirport * apt, double speed, double alt,
505                                  const string & fltType)
506 {
507     waypoint *wpt;
508 //  bool planLoaded = false;
509     string fPLName;
510     double vClimb = ac->getPerformance()->vClimb();
511
512     if (firstFlight) {
513         string rwyClass = getRunwayClassFromTrafficType(fltType);
514         double heading = ac->getTrafficRef()->getCourse();
515         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
516                                             heading);
517         rwy = apt->getRunwayByIdent(activeRunway);
518     }
519     if (sid) {
520         for (wpt_vector_iterator i = sid->getFirstWayPoint();
521              i != sid->getLastWayPoint(); i++) {
522             waypoints.push_back(clone(*(i)));
523             //cerr << " Cloning waypoint " << endl;
524         }
525     } else {
526         SGGeod climb1 = rwy->pointOnCenterline(10 * SG_NM_TO_METER);
527         wpt = createInAir(ac, "10000ft climb", climb1, vClimb, 10000);
528         wpt->gear_down = true;
529         wpt->flaps_down = true;
530         waypoints.push_back(wpt);
531
532         SGGeod climb2 = rwy->pointOnCenterline(20 * SG_NM_TO_METER);
533         wpt = cloneWithPos(ac, wpt, "18000ft climb", climb2);
534         wpt->altitude = 18000;
535         waypoints.push_back(wpt);
536     }
537     return true;
538 }
539
540
541
542 /*******************************************************************
543  * CreateDescent
544  * Generate a flight path from the last waypoint of the cruise to 
545  * the permission to land point
546  ******************************************************************/
547 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
548                                    double latitude, double longitude,
549                                    double speed, double alt,
550                                    const string & fltType,
551                                    double requiredDistance)
552 {
553     bool reposition = false;
554     waypoint *wpt;
555     double vDescent = ac->getPerformance()->vDescent();
556     double vApproach = ac->getPerformance()->vApproach();
557
558
559     //Beginning of Descent 
560     string rwyClass = getRunwayClassFromTrafficType(fltType);
561     double heading = ac->getTrafficRef()->getCourse();
562     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
563                                         heading);
564     rwy = apt->getRunwayByIdent(activeRunway);
565
566
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->crossat = currentAltitude;
733         wpt->trackLength = (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->crossat = currentAltitude;
776         wpt->trackLength = 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->crossat = currentAltitude;
795         wpt->trackLength = (distanceOut / nPoints);
796         // account for the extra distance due to an extended downwind leg
797         if (i == 1) {
798             wpt->trackLength += 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     return true;
835 }
836
837 /*******************************************************************
838  * CreateLanding
839  * Create a flight path from the "permision to land" point (currently
840    hardcoded at 5000 meters from the threshold) to the threshold, at
841    a standard glide slope angle of 3 degrees. 
842  ******************************************************************/
843 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
844                                    const string & fltType)
845 {
846     double vTouchdown = ac->getPerformance()->vTouchdown();
847     //double vTaxi = ac->getPerformance()->vTaxi();
848
849     //string rwyClass = getRunwayClassFromTrafficType(fltType);
850     //double heading = ac->getTrafficRef()->getCourse();
851     //apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway, heading);
852     //rwy = apt->getRunwayByIdent(activeRunway);
853
854
855     waypoint *wpt;
856     double aptElev = apt->getElevation();
857
858     SGGeod coord;
859     char buffer[12];
860     for (int i = 1; i < 10; i++) {
861         snprintf(buffer, 12, "wpt%d", i);
862         coord = rwy->pointOnCenterline(rwy->lengthM() * (i / 10.0));
863         wpt = createOnGround(ac, buffer, coord, aptElev, (vTouchdown / i));
864         wpt->crossat = apt->getElevation();
865         waypoints.push_back(wpt);
866     }
867
868     /*
869        //Runway Threshold
870        wpt = createOnGround(ac, "Threshold", rwy->threshold(), aptElev, vTouchdown);
871        wpt->crossat = apt->getElevation();
872        waypoints.push_back(wpt); 
873
874        // Roll-out
875        wpt = createOnGround(ac, "Center", rwy->geod(), aptElev, vTaxi*2);
876        waypoints.push_back(wpt);
877
878        SGGeod rollOut = rwy->pointOnCenterline(rwy->lengthM() * 0.9);
879        wpt = createOnGround(ac, "Roll Out", rollOut, aptElev, vTaxi);
880        wpt->crossat   = apt->getElevation();
881        waypoints.push_back(wpt); 
882      */
883     return true;
884 }
885
886 /*******************************************************************
887  * CreateParking
888  * initialize the Aircraft at the parking location
889  ******************************************************************/
890 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
891                                    double radius)
892 {
893     waypoint *wpt;
894     double aptElev = apt->getElevation();
895     double lat = 0.0, lat2 = 0.0;
896     double lon = 0.0, lon2 = 0.0;
897     double az2 = 0.0;
898     double heading = 0.0;
899
900     double vTaxi = ac->getPerformance()->vTaxi();
901     double vTaxiReduced = vTaxi * (2.0 / 3.0);
902     apt->getDynamics()->getParking(gateId, &lat, &lon, &heading);
903     heading += 180.0;
904     if (heading > 360)
905         heading -= 360;
906     geo_direct_wgs_84(0, lat, lon, heading,
907                       2.2 * radius, &lat2, &lon2, &az2);
908     wpt =
909         createOnGround(ac, "taxiStart", SGGeod::fromDeg(lon2, lat2),
910                        aptElev, vTaxiReduced);
911     waypoints.push_back(wpt);
912
913     geo_direct_wgs_84(0, lat, lon, heading,
914                       0.1 * radius, &lat2, &lon2, &az2);
915
916     wpt =
917         createOnGround(ac, "taxiStart2", SGGeod::fromDeg(lon2, lat2),
918                        aptElev, vTaxiReduced);
919     waypoints.push_back(wpt);
920
921     wpt =
922         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), aptElev,
923                        vTaxiReduced);
924     waypoints.push_back(wpt);
925     return true;
926 }
927
928 /**
929  *
930  * @param fltType a string describing the type of
931  * traffic, normally used for gate assignments
932  * @return a converted string that gives the runway
933  * preference schedule to be used at aircraft having
934  * a preferential runway schedule implemented (i.e.
935  * having a rwyprefs.xml file
936  * 
937  * Currently valid traffic types for gate assignment:
938  * - gate (commercial gate)
939  * - cargo (commercial gargo),
940  * - ga (general aviation) ,
941  * - ul (ultralight),
942  * - mil-fighter (military - fighter),
943  * - mil-transport (military - transport)
944  *
945  * Valid runway classes:
946  * - com (commercial traffic: jetliners, passenger and cargo)
947  * - gen (general aviation)
948  * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
949  * - mil (all military traffic)
950  */
951 string FGAIFlightPlan::getRunwayClassFromTrafficType(string fltType)
952 {
953     if ((fltType == "gate") || (fltType == "cargo")) {
954         return string("com");
955     }
956     if (fltType == "ga") {
957         return string("gen");
958     }
959     if (fltType == "ul") {
960         return string("ul");
961     }
962     if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
963         return string("mil");
964     }
965     return string("com");
966 }
967
968
969 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
970 {
971     double turn_radius;
972     if (inAir == false) {
973         turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
974     } else {
975         turn_radius = 0.1911 * speed * speed;   // an estimate for 25 degrees bank
976     }
977     return turn_radius;
978 }