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