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