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