]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
Merge commit 'refs/merge-requests/11' of git://gitorious.org/fg/flightgear into next
[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     rwy = apt->getRunwayByIdent(activeRunway);
230     SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
231
232     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
233     if (!gn->exists()) {
234         createDefaultTakeoffTaxi(ac, apt, rwy);
235         return true;
236     }
237
238     intVec ids;
239     int runwayId = gn->findNearestNode(runwayTakeoff);
240
241     // A negative gateId indicates an overflow parking, use a
242     // fallback mechanism for this. 
243     // Starting from gate 0 in this case is a bit of a hack
244     // which requires a more proper solution later on.
245     delete taxiRoute;
246     taxiRoute = new FGTaxiRoute;
247
248     // Determine which node to start from.
249     int node = 0;
250     // Find out which node to start from
251     FGParking *park = apt->getDynamics()->getParking(gateId);
252     if (park) {
253         node = park->getPushBackPoint();
254     }
255
256     if (node == -1) {
257         node = gateId;
258     }
259     // HAndle case where parking doens't have a node
260     if ((node == 0) && park) {
261         if (firstFlight) {
262             node = gateId;
263         } else {
264             node = lastNodeVisited;
265         }
266     }
267
268     *taxiRoute = gn->findShortestRoute(node, runwayId);
269     intVecIterator i;
270
271     if (taxiRoute->empty()) {
272         createDefaultTakeoffTaxi(ac, apt, rwy);
273         return true;
274     }
275
276     taxiRoute->first();
277     //bool isPushBackPoint = false;
278     if (firstFlight) {
279         // If this is called during initialization, randomly
280         // skip a number of waypoints to get a more realistic
281         // taxi situation.
282         int nrWaypointsToSkip = rand() % taxiRoute->size();
283         // but make sure we always keep two active waypoints
284         // to prevent a segmentation fault
285         for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
286             taxiRoute->next(&node);
287         }
288         apt->getDynamics()->releaseParking(gateId);
289     } else {
290         if (taxiRoute->size() > 1) {
291             taxiRoute->next(&node);     // chop off the first waypoint, because that is already the last of the pushback route
292         }
293     }
294
295     // push each node on the taxi route as a waypoint
296     int route;
297     //cerr << "Building taxi route" << endl;
298     while (taxiRoute->next(&node, &route)) {
299         char buffer[10];
300         snprintf(buffer, 10, "%d", node);
301         FGTaxiNode *tn =
302             apt->getDynamics()->getGroundNetwork()->findNode(node);
303         FGAIWaypoint *wpt =
304             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
305                            ac->getPerformance()->vTaxi());
306         wpt->setRouteIndex(route);
307         //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
308         if (taxiRoute->nodesLeft() == 1) {
309             // Note that we actually have hold points in the ground network, but this is just an initial test.
310             //cerr << "Setting departurehold point: " << endl;
311             wpt->setName( wpt->getName() + string("DepartureHold"));
312         }
313         waypoints.push_back(wpt);
314     }
315     // Acceleration point, 105 meters into the runway,
316     SGGeod accelPoint = rwy->pointOnCenterline(105.0);
317     FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
318     waypoints.push_back(wpt);
319
320     //cerr << "[done]" << endl;
321     return true;
322 }
323
324 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
325                                               FGAirport * aAirport)
326 {
327     SGGeod lastWptPos =
328         SGGeod::fromDeg(waypoints.back()->getLongitude(),
329                         waypoints.back()->getLatitude());
330     double airportElev = aAirport->getElevation();
331
332     FGAIWaypoint *wpt;
333     wpt =
334         createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
335                        ac->getPerformance()->vTaxi());
336     waypoints.push_back(wpt);
337     wpt =
338         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
339                        ac->getPerformance()->vTaxi());
340     waypoints.push_back(wpt);
341
342     double heading, lat, lon;
343     aAirport->getDynamics()->getParking(gateId, &lat, &lon, &heading);
344     wpt =
345         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), airportElev,
346                        ac->getPerformance()->vTaxi());
347     waypoints.push_back(wpt);
348 }
349
350 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
351                                        double radius,
352                                        const string & fltType,
353                                        const string & acType,
354                                        const string & airline)
355 {
356     double heading, lat, lon;
357     apt->getDynamics()->getAvailableParking(&lat, &lon, &heading,
358                                             &gateId, radius, fltType,
359                                             acType, airline);
360
361     SGGeod lastWptPos =
362         SGGeod::fromDeg(waypoints.back()->getLongitude(),
363                         waypoints.back()->getLatitude());
364     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
365
366     // Find a route from runway end to parking/gate.
367     if (!gn->exists()) {
368         createDefaultLandingTaxi(ac, apt);
369         return true;
370     }
371
372     intVec ids;
373     int runwayId = gn->findNearestNode(lastWptPos);
374     // A negative gateId indicates an overflow parking, use a
375     // fallback mechanism for this. 
376     // Starting from gate 0 is a bit of a hack...
377     //FGTaxiRoute route;
378     delete taxiRoute;
379     taxiRoute = new FGTaxiRoute;
380     if (gateId >= 0)
381         *taxiRoute = gn->findShortestRoute(runwayId, gateId);
382     else
383         *taxiRoute = gn->findShortestRoute(runwayId, 0);
384     intVecIterator i;
385
386     if (taxiRoute->empty()) {
387         createDefaultLandingTaxi(ac, apt);
388         return true;
389     }
390
391     int node;
392     taxiRoute->first();
393     int size = taxiRoute->size();
394     // Omit the last two waypoints, as 
395     // those are created by createParking()
396     int route;
397     for (int i = 0; i < size - 2; i++) {
398         taxiRoute->next(&node, &route);
399         char buffer[10];
400         snprintf(buffer, 10, "%d", node);
401         FGTaxiNode *tn = gn->findNode(node);
402         FGAIWaypoint *wpt =
403             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
404                            ac->getPerformance()->vTaxi());
405         wpt->setRouteIndex(route);
406         waypoints.push_back(wpt);
407     }
408     return true;
409 }
410
411 /*******************************************************************
412  * CreateTakeOff 
413  * A note on units: 
414  *  - Speed -> knots -> nm/hour
415  *  - distance along runway =-> meters 
416  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
417  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
418  *  given respectively. According to performance data.cxx, a value of kts / second seems
419  *  more likely however. 
420  * 
421  ******************************************************************/
422 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
423                                    FGAirport * apt, double speed,
424                                    const string & fltType)
425 {
426     double accel = ac->getPerformance()->acceleration();
427     double vTaxi = ac->getPerformance()->vTaxi();
428     double vRotate = ac->getPerformance()->vRotate();
429     double vTakeoff = ac->getPerformance()->vTakeoff();
430     //double vClimb = ac->getPerformance()->vClimb();
431
432     double accelMetric = (accel * SG_NM_TO_METER) / 3600;
433     double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600;
434     double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600;
435     double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600;
436     //double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600;
437     // Acceleration = dV / dT
438     // Acceleration X dT = dV
439     // dT = dT / Acceleration
440     //d = (Vf^2 - Vo^2) / (2*a)
441     //double accelTime = (vRotate - vTaxi) / accel;
442     //cerr << "Using " << accelTime << " as total acceleration time" << endl;
443     double accelDistance =
444         (vRotateMetric * vRotateMetric -
445          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
446     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl;
447     FGAIWaypoint *wpt;
448     // Get the current active runway, based on code from David Luff
449     // This should actually be unified and extended to include 
450     // Preferential runway use schema's 
451     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
452     // because the getActive runway function takes care of that.
453     if (firstFlight) {
454         string rwyClass = getRunwayClassFromTrafficType(fltType);
455         double heading = ac->getTrafficRef()->getCourse();
456         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
457                                             heading);
458     }
459     rwy = apt->getRunwayByIdent(activeRunway);
460
461
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         rwy = apt->getRunwayByIdent(activeRunway);
517     }
518     if (sid) {
519         for (wpt_vector_iterator i = sid->getFirstWayPoint();
520              i != sid->getLastWayPoint(); i++) {
521             waypoints.push_back(clone(*(i)));
522             //cerr << " Cloning waypoint " << endl;
523         }
524     } else {
525         SGGeod climb1 = rwy->pointOnCenterline(10 * SG_NM_TO_METER);
526         wpt = createInAir(ac, "10000ft climb", climb1, vClimb, 10000);
527         wpt->setGear_down(true);
528         wpt->setFlaps_down(true);
529         waypoints.push_back(wpt);
530
531         SGGeod climb2 = rwy->pointOnCenterline(20 * SG_NM_TO_METER);
532         wpt = cloneWithPos(ac, wpt, "18000ft climb", climb2);
533         wpt->setAltitude(18000);
534         waypoints.push_back(wpt);
535     }
536     return true;
537 }
538
539
540
541 /*******************************************************************
542  * CreateDescent
543  * Generate a flight path from the last waypoint of the cruise to 
544  * the permission to land point
545  ******************************************************************/
546 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
547                                    double latitude, double longitude,
548                                    double speed, double alt,
549                                    const string & fltType,
550                                    double requiredDistance)
551 {
552     bool reposition = false;
553     FGAIWaypoint *wpt;
554     double vDescent = ac->getPerformance()->vDescent();
555     double vApproach = ac->getPerformance()->vApproach();
556
557
558     //Beginning of Descent 
559     string rwyClass = getRunwayClassFromTrafficType(fltType);
560     double heading = ac->getTrafficRef()->getCourse();
561     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
562                                         heading);
563     rwy = apt->getRunwayByIdent(activeRunway);
564
565
566
567     // Create a slow descent path that ends 250 lateral to the runway.
568     double initialTurnRadius = getTurnRadius(vDescent, true);
569     //double finalTurnRadius = getTurnRadius(vApproach, true);
570
571 // get length of the downwind leg for the intended runway
572     double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance();    //12 * SG_NM_TO_METER;
573     //time_t previousArrivalTime=  apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
574
575
576     SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
577     SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
578     SGGeod refPoint = rwy->pointOnCenterline(0);
579     double distance = SGGeodesy::distanceM(current, initialTarget);
580     double azimuth = SGGeodesy::courseDeg(current, initialTarget);
581     double dummyAz2;
582
583     // To prevent absurdly steep approaches, compute the origin from where the approach should have started
584     SGGeod origin;
585
586     if (ac->getTrafficRef()->getCallSign() ==
587         fgGetString("/ai/track-callsign")) {
588         //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
589         //exit(1);
590     }
591
592     if (distance < requiredDistance * 0.8) {
593         reposition = true;
594         SGGeodesy::direct(initialTarget, azimuth,
595                           -requiredDistance, origin, dummyAz2);
596
597         distance = SGGeodesy::distanceM(current, initialTarget);
598         azimuth = SGGeodesy::courseDeg(current, initialTarget);
599     } else {
600         origin = current;
601     }
602
603
604     double dAlt = alt - (apt->getElevation() + 2000);
605
606     double nPoints = 100;
607
608     char buffer[16];
609
610     // The descent path contains the following phases:
611     // 1) a linear glide path from the initial position to
612     // 2) a semi circle turn to final
613     // 3) approach
614
615     //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
616     // Create an initial destination point on a semicircle
617     //cerr << "lateral offset : " << lateralOffset << endl;
618     //cerr << "Distance       : " << distance      << endl;
619     //cerr << "Azimuth        : " << azimuth       << endl;
620     //cerr << "Initial Lateral point: " << lateralOffset << endl;
621     double lat = refPoint.getLatitudeDeg();
622     double lon = refPoint.getLongitudeDeg();
623     //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
624     lat = initialTarget.getLatitudeDeg();
625     lon = initialTarget.getLongitudeDeg();
626     //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
627
628     double ratio = initialTurnRadius / distance;
629     if (ratio > 1.0)
630         ratio = 1.0;
631     if (ratio < -1.0)
632         ratio = -1.0;
633
634     double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
635     double newDistance =
636         cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
637     //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
638     double side = azimuth - rwy->headingDeg();
639     double lateralOffset = initialTurnRadius;
640     if (side < 0)
641         side += 360;
642     if (side < 180) {
643         lateralOffset *= -1;
644     }
645     // Calculate the ETA at final, based on remaining distance, and approach speed.
646     // distance should really consist of flying time to terniary target, plus circle 
647     // but the distance to secondary target should work as a reasonable approximation
648     // aditionally add the amount of distance covered by making a turn of "side"
649     double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
650     time_t remaining =
651         (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
652     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
653     //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
654     //     cerr << "   Arrival time estimation: turn angle " <<  side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
655     //     //exit(1);
656     //}
657
658     time_t eta = now + remaining;
659     //choose a distance to the runway such that it will take at least 60 seconds more
660     // time to get there than the previous aircraft.
661     // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
662
663     time_t newEta;
664
665     if (reposition == false) {
666         newEta =
667             apt->getDynamics()->getApproachController()->getRunway(rwy->
668                                                                    name
669                                                                    ())->
670             requestTimeSlot(eta);
671     } else {
672         newEta = eta;
673     }
674     //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
675     arrivalTime = newEta;
676     time_t additionalTimeNeeded = newEta - eta;
677     double distanceCovered =
678         ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
679     distanceOut += distanceCovered;
680     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
681     //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
682     //} else {
683     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
684     //}
685     //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
686
687     SGGeod secondaryTarget =
688         rwy->pointOffCenterline(-distanceOut, lateralOffset);
689     initialTarget = rwy->pointOnCenterline(-distanceOut);
690     distance = SGGeodesy::distanceM(origin, secondaryTarget);
691     azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
692
693
694     lat = secondaryTarget.getLatitudeDeg();
695     lon = secondaryTarget.getLongitudeDeg();
696     //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
697     //cerr << "Distance       : " << distance      << endl;
698     //cerr << "Azimuth        : " << azimuth       << endl;
699
700
701     ratio = initialTurnRadius / distance;
702     if (ratio > 1.0)
703         ratio = 1.0;
704     if (ratio < -1.0)
705         ratio = -1.0;
706     newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
707     newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
708     //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
709     if (side < 180) {
710         azimuth += newHeading;
711     } else {
712         azimuth -= newHeading;
713     }
714
715     SGGeod tertiaryTarget;
716     SGGeodesy::direct(origin, azimuth,
717                       newDistance, tertiaryTarget, dummyAz2);
718
719     lat = tertiaryTarget.getLatitudeDeg();
720     lon = tertiaryTarget.getLongitudeDeg();
721     //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
722
723
724     for (int i = 1; i < nPoints; i++) {
725         SGGeod result;
726         double currentDist = i * (newDistance / nPoints);
727         double currentAltitude = alt - (i * (dAlt / nPoints));
728         SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
729         snprintf(buffer, 16, "descent%03d", i);
730         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
731         wpt->setCrossat(currentAltitude);
732         wpt->setTrackLength((newDistance / nPoints));
733         waypoints.push_back(wpt);
734         //cerr << "Track Length : " << wpt->trackLength;
735         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
736     }
737
738     //cerr << "Phase 2: Circle " << endl;
739     double initialAzimuth =
740         SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
741     double finalAzimuth =
742         SGGeodesy::courseDeg(secondaryTarget, initialTarget);
743
744     //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
745     int increment, startval, endval;
746     // circle right around secondary target if orig of position is to the right of the runway
747     // i.e. use negative angles; else circle leftward and use postivi
748     if (side < 180) {
749         increment = -1;
750         startval = floor(initialAzimuth);
751         endval = ceil(finalAzimuth);
752         if (endval > startval) {
753             endval -= 360;
754         }
755     } else {
756         increment = 1;
757         startval = ceil(initialAzimuth);
758         endval = floor(finalAzimuth);
759         if (endval < startval) {
760             endval += 360;
761         }
762
763     }
764
765     //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
766     double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
767     for (int i = startval; i != endval; i += increment) {
768         SGGeod result;
769         double currentAltitude = apt->getElevation() + 2000;
770         SGGeodesy::direct(secondaryTarget, i,
771                           initialTurnRadius, result, dummyAz2);
772         snprintf(buffer, 16, "turn%03d", i);
773         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
774         wpt->setCrossat(currentAltitude);
775         wpt->setTrackLength(trackLength);
776         //cerr << "Track Length : " << wpt->trackLength;
777         waypoints.push_back(wpt);
778         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
779     }
780
781
782     // The approach leg should bring the aircraft to approximately 4-6 out, after which the landing phase should take over. 
783     //cerr << "Phase 3: Approach" << endl;
784     distanceOut -= distanceCovered;
785     for (int i = 1; i < nPoints; i++) {
786         SGGeod result;
787         double currentDist = i * (distanceOut / nPoints);
788         double currentAltitude =
789             apt->getElevation() + 2000 - (i * 2000 / nPoints);
790         snprintf(buffer, 16, "final%03d", i);
791         result = rwy->pointOnCenterline((-distanceOut) + currentDist);
792         wpt = createInAir(ac, buffer, result, currentAltitude, vApproach);
793         wpt->setCrossat(currentAltitude);
794         wpt->setTrackLength((distanceOut / nPoints));
795         // account for the extra distance due to an extended downwind leg
796         if (i == 1) {
797             wpt->setTrackLength(wpt->getTrackLength() + distanceCovered);
798         }
799         //cerr << "Track Length : " << wpt->trackLength;
800         waypoints.push_back(wpt);
801         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
802     }
803
804     //cerr << "Done" << endl;
805
806     // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
807     IncrementWaypoint(true);
808     IncrementWaypoint(true);
809
810     if (reposition) {
811         double tempDistance;
812         //double minDistance = HUGE_VAL;
813         string wptName;
814         tempDistance = SGGeodesy::distanceM(current, initialTarget);
815         time_t eta =
816             tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
817         time_t newEta =
818             apt->getDynamics()->getApproachController()->getRunway(rwy->
819                                                                    name
820                                                                    ())->
821             requestTimeSlot(eta);
822         arrivalTime = newEta;
823         double newDistance =
824             ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
825         //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
826         IncrementWaypoint(true);        // remove waypoint BOD2
827         while (checkTrackLength("final001") > newDistance) {
828             IncrementWaypoint(true);
829         }
830         //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
831         ac->resetPositionFromFlightPlan();
832     }
833     waypoints[1]->setName( (waypoints[1]->getName() + string("legend"))); 
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     FGAIWaypoint *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->setCrossat(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     FGAIWaypoint *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 }