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