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