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