1 /******************************************************************************
2 * AIFlightPlanCreate.cxx
3 * Written by Durk Talsma, started May, 2004.
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.
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.
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.
19 **************************************************************************/
28 #include "AIFlightPlan.hxx"
29 #include <simgear/math/sg_geodesy.hxx>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
33 #include <Airports/airport.hxx>
34 #include <Airports/runways.hxx>
35 #include <Airports/dynamics.hxx>
36 #include <Airports/groundnetwork.hxx>
38 #include "AIAircraft.hxx"
39 #include "performancedata.hxx"
41 #include <Main/fg_props.hxx>
42 #include <Environment/environment_mgr.hxx>
43 #include <Environment/environment.hxx>
44 #include <FDM/LaRCsim/basic_aero.h>
45 #include <Navaids/navrecord.hxx>
46 #include <Traffic/Schedule.hxx>
50 /* FGAIFlightPlan::create()
51 * dynamically create a flight plan for AI traffic, based on data provided by the
52 * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10)
54 * This is the top-level function, and the only one that is publicly available.
59 // Check lat/lon values during initialization;
60 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
61 FGAirport * arr, int legNr, double alt,
62 double speed, double latitude,
63 double longitude, bool firstFlight,
64 double radius, const string & fltType,
65 const string & aircraftType,
66 const string & airline, double distance)
69 int currWpt = wpt_iterator - waypoints.begin();
72 retVal = createPushBack(ac, firstFlight, dep,
73 radius, fltType, aircraftType, airline);
74 // Pregenerate the taxi leg.
76 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
77 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
81 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
82 aircraftType, airline);
85 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
88 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
91 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
95 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
99 retVal = createLanding(ac, arr, fltType);
102 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
105 retVal = createParking(ac, arr, radius);
109 SG_LOG(SG_AI, SG_ALERT,
110 "AIFlightPlan::create() attempting to create unknown leg"
111 " this is probably an internal program error");
114 wpt_iterator = waypoints.begin() + currWpt;
115 //don't increment leg right away, but only once we pass the actual last waypoint that was created.
116 // to do so, mark the last waypoint with a special status flag
118 waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
119 // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
127 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
128 const std::string & aName,
129 const SGGeod & aPos, double aElev,
132 FGAIWaypoint *wpt = new FGAIWaypoint;
133 wpt->setName (aName );
134 wpt->setLongitude (aPos.getLongitudeDeg() );
135 wpt->setLatitude (aPos.getLatitudeDeg() );
136 wpt->setAltitude (aElev );
137 wpt->setSpeed (aSpeed );
138 wpt->setCrossat (-10000.1 );
139 wpt->setGear_down (true );
140 wpt->setFlaps_down (true );
141 wpt->setFinished (false );
142 wpt->setOn_ground (true );
143 wpt->setRouteIndex (0 );
147 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
148 const std::string & aName,
149 const SGGeod & aPos, double aElev,
152 FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
153 wpt->setGear_down (false );
154 wpt->setFlaps_down (false );
155 wpt->setOn_ground (false );
156 wpt->setCrossat (aElev );
160 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
162 FGAIWaypoint *wpt = new FGAIWaypoint;
163 wpt->setName ( aWpt->getName () );
164 wpt->setLongitude ( aWpt->getLongitude() );
165 wpt->setLatitude ( aWpt->getLatitude() );
166 wpt->setAltitude ( aWpt->getAltitude() );
167 wpt->setSpeed ( aWpt->getSpeed() );
168 wpt->setCrossat ( aWpt->getCrossat() );
169 wpt->setGear_down ( aWpt->getGear_down() );
170 wpt->setFlaps_down ( aWpt->getFlaps_down() );
171 wpt->setFinished ( aWpt->isFinished() );
172 wpt->setOn_ground ( aWpt->getOn_ground() );
173 wpt->setRouteIndex ( 0 );
179 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
180 const std::string & aName,
183 FGAIWaypoint *wpt = clone(aWpt);
184 wpt->setName ( aName );
185 wpt->setLongitude ( aPos.getLongitudeDeg () );
186 wpt->setLatitude ( aPos.getLatitudeDeg () );
193 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
194 FGAirport * aAirport,
197 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
198 double airportElev = aAirport->getElevation();
202 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
203 ac->getPerformance()->vTaxi());
204 pushBackWaypoint(wpt);
206 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
207 ac->getPerformance()->vTaxi());
208 pushBackWaypoint(wpt);
211 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
214 const string & fltType,
215 const string & acType,
216 const string & airline)
219 // If this function is called during initialization,
220 // make sure we obtain a valid gate ID first
221 // and place the model at the location of the gate.
224 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
226 if (!gate.isValid()) {
227 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
229 " of flight type " << fltType <<
230 " of airline " << airline <<
231 " at airport " << apt->getId());
235 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
237 // Only set this if it hasn't been set by ATC already.
238 if (activeRunway.empty()) {
239 //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
240 double depHeading = ac->getTrafficRef()->getCourse();
241 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
244 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
245 assert( rwy != NULL );
246 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
248 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
250 createDefaultTakeoffTaxi(ac, apt, rwy);
254 FGTaxiNodeRef runwayNode;
255 if (gn->getVersion() > 0) {
256 FGTaxiNodeRef runwayNode = gn->findNearestNodeOnRunway(runwayTakeoff);
258 FGTaxiNodeRef runwayNode = gn->findNearestNode(runwayTakeoff);
261 // A negative gateId indicates an overflow parking, use a
262 // fallback mechanism for this.
263 // Starting from gate 0 in this case is a bit of a hack
264 // which requires a more proper solution later on.
266 // taxiRoute = new FGTaxiRoute;
268 // Determine which node to start from.
270 // Find out which node to start from
271 FGParking *park = gate.parking();
273 node = park->getPushBackPoint();
275 // Handle case where parking doesn't have a node
279 node = lastNodeVisited;
284 FGTaxiRoute taxiRoute;
286 taxiRoute = gn->findShortestRoute(node, runwayNode);
288 if (taxiRoute.empty()) {
289 createDefaultTakeoffTaxi(ac, apt, rwy);
294 FGTaxiNodeRef skipNode;
296 //bool isPushBackPoint = false;
298 // If this is called during initialization, randomly
299 // skip a number of waypoints to get a more realistic
301 int nrWaypointsToSkip = rand() % taxiRoute.size();
302 // but make sure we always keep two active waypoints
303 // to prevent a segmentation fault
304 for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
305 taxiRoute.next(skipNode, &route);
308 gate.release(); // free up our gate as required
310 if (taxiRoute.size() > 1) {
311 taxiRoute.next(skipNode, &route); // chop off the first waypoint, because that is already the last of the pushback route
315 // push each node on the taxi route as a waypoint
317 //cerr << "Building taxi route" << endl;
319 // Note that the line wpt->setRouteIndex was commented out by revision [afcdbd] 2012-01-01,
320 // which breaks the rendering functions.
321 // These can probably be generated on the fly however.
322 while (taxiRoute.next(node, &route)) {
324 snprintf(buffer, 10, "%d", node->getIndex());
326 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
327 ac->getPerformance()->vTaxi());
328 wpt->setRouteIndex(route);
329 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
330 if (taxiRoute.nodesLeft() == 1) {
331 // Note that we actually have hold points in the ground network, but this is just an initial test.
332 //cerr << "Setting departurehold point: " << endl;
333 wpt->setName( wpt->getName() + string("DepartureHold"));
335 if (taxiRoute.nodesLeft() == 0) {
336 wpt->setName(wpt->getName() + string("Accel"));
338 pushBackWaypoint(wpt);
340 // Acceleration point, 105 meters into the runway,
341 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
342 FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
343 pushBackWaypoint(wpt);
345 //cerr << "[done]" << endl;
349 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
350 FGAirport * aAirport)
353 SGGeod::fromDeg(waypoints.back()->getLongitude(),
354 waypoints.back()->getLatitude());
355 double airportElev = aAirport->getElevation();
359 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
360 ac->getPerformance()->vTaxi());
361 pushBackWaypoint(wpt);
363 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
364 ac->getPerformance()->vTaxi());
365 pushBackWaypoint(wpt);
367 if (gate.isValid()) {
368 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
369 ac->getPerformance()->vTaxi());
370 pushBackWaypoint(wpt);
374 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
376 const string & fltType,
377 const string & acType,
378 const string & airline)
381 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
384 SGGeod lastWptPos = waypoints.back()->getPos();
385 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
387 // Find a route from runway end to parking/gate.
389 createDefaultLandingTaxi(ac, apt);
393 FGTaxiNodeRef runwayNode;
394 if (gn->getVersion() == 1) {
395 runwayNode = gn->findNearestNodeOnRunway(lastWptPos);
397 runwayNode = gn->findNearestNode(lastWptPos);
399 //cerr << "Using network node " << runwayId << endl;
400 // A negative gateId indicates an overflow parking, use a
401 // fallback mechanism for this.
402 // Starting from gate 0 doesn't work, so don't try it
403 FGTaxiRoute taxiRoute;
405 taxiRoute = gn->findShortestRoute(runwayNode, gate.parking());
407 if (taxiRoute.empty()) {
408 createDefaultLandingTaxi(ac, apt);
414 int size = taxiRoute.size();
415 // Omit the last two waypoints, as
416 // those are created by createParking()
418 for (int i = 0; i < size - 2; i++) {
419 taxiRoute.next(node, &route);
421 snprintf(buffer, 10, "%d", node->getIndex());
423 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
424 ac->getPerformance()->vTaxi());
426 wpt->setRouteIndex(route);
427 pushBackWaypoint(wpt);
432 static double accelDistance(double v0, double v1, double accel)
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);
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)
445 return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
448 /*******************************************************************
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.
458 ******************************************************************/
459 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
460 FGAirport * apt, double speed,
461 const string & fltType)
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;
468 double accel = ac->getPerformance()->acceleration();
469 double vTaxi = ac->getPerformance()->vTaxi();
470 double vRotate = ac->getPerformance()->vRotate();
471 double vTakeoff = ac->getPerformance()->vTakeoff();
473 double accelMetric = accel * SG_KT_TO_MPS;
474 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
475 double vRotateMetric = vRotate * SG_KT_TO_MPS;
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.
484 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
485 double heading = ac->getTrafficRef()->getCourse();
486 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
490 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
491 assert( rwy != NULL );
492 double airportElev = apt->getElevation();
494 double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
496 SGGeod accelPoint = rwy->pointOnCenterline(d);
497 wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
498 pushBackWaypoint(wpt);
500 double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
502 double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
503 accelPoint = rwy->pointOnCenterline(gearUpDist);
505 wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
507 wpt->setCrossat(airportElev + 400);
508 wpt->setOn_ground(false);
509 wpt->setGear_down(false);
510 pushBackWaypoint(wpt);
512 // limit climbout speed to 240kts below 10000'
513 double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
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);
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);
531 /*******************************************************************
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)
542 double vClimb = ac->getPerformance()->vClimb();
545 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
546 double heading = ac->getTrafficRef()->getCourse();
547 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
551 for (wpt_vector_iterator i = sid->getFirstWayPoint();
552 i != sid->getLastWayPoint(); i++) {
553 pushBackWaypoint(clone(*(i)));
554 //cerr << " Cloning waypoint " << endl;
557 FGRunway* runway = apt->getRunwayByIdent(activeRunway);
558 SGGeod cur = runway->end();
559 if (!waypoints.empty()) {
560 cur = waypoints.back()->getPos();
563 // compute course towards destination
564 double course = SGGeodesy::courseDeg(cur, arrival->geod());
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);
572 SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
573 wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
574 pushBackWaypoint(wpt);
581 /*******************************************************************
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)
592 bool reposition = false;
594 double vDescent = ac->getPerformance()->vDescent();
595 double vApproach = ac->getPerformance()->vApproach();
597 //Beginning of Descent
598 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
599 double heading = ac->getTrafficRef()->getCourse();
600 apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
602 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
603 assert( rwy != NULL );
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);
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();
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);
621 // To prevent absurdly steep approaches, compute the origin from where the approach should have started
624 if (ac->getTrafficRef()->getCallSign() ==
625 fgGetString("/ai/track-callsign")) {
626 //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
630 if (distance < requiredDistance * 0.8) {
632 SGGeodesy::direct(initialTarget, azimuth,
633 -requiredDistance, origin, dummyAz2);
635 distance = SGGeodesy::distanceM(current, initialTarget);
636 azimuth = SGGeodesy::courseDeg(current, initialTarget);
641 double dAlt = 0; // = alt - (apt->getElevation() + 2000);
643 if (apt->getDynamics()->getGroundNetwork()) {
644 tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
648 dAlt = alt - ((tn->getElevationFt()) + 2000);
650 dAlt = alt - (apt->getElevation() + 2000);
653 double nPoints = 100;
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
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;
674 double ratio = initialTurnRadius / distance;
680 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
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;
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);
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;
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...
711 if (reposition == false) {
713 apt->getDynamics()->getApproachController()->getRunway(rwy->
716 requestTimeSlot(eta);
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;
729 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
731 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
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);
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;
747 ratio = initialTurnRadius / distance;
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;
756 azimuth += newHeading;
758 azimuth -= newHeading;
761 SGGeod tertiaryTarget;
762 SGGeodesy::direct(origin, azimuth,
763 newDistance, tertiaryTarget, dummyAz2);
765 // lat = tertiaryTarget.getLatitudeDeg();
766 // lon = tertiaryTarget.getLongitudeDeg();
767 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
770 for (int i = 1; i < nPoints; i++) {
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;
784 //cerr << "Phase 2: Circle " << endl;
785 double initialAzimuth =
786 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
787 double finalAzimuth =
788 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
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
796 startval = floor(initialAzimuth);
797 endval = ceil(finalAzimuth);
798 if (endval > startval) {
803 startval = ceil(initialAzimuth);
804 endval = floor(finalAzimuth);
805 if (endval < startval) {
811 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
812 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
813 double currentAltitude = 0;
815 currentAltitude = (tn->getElevationFt()) + 2000;
817 currentAltitude = apt->getElevation() + 2000;
820 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
821 for (int i = startval; i != endval; i += increment) {
823 //double currentAltitude = apt->getElevation() + 2000;
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;
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;
840 //cerr << "Done" << endl;
842 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
843 IncrementWaypoint(true);
844 IncrementWaypoint(true);
848 //double minDistance = HUGE_VAL;
850 tempDistance = SGGeodesy::distanceM(current, initialTarget);
852 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
854 apt->getDynamics()->getApproachController()->getRunway(rwy->
857 requestTimeSlot(eta);
858 arrivalTime = newEta;
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);
866 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
867 ac->resetPositionFromFlightPlan();
869 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
874 * compute the distance along the centerline, to the ILS glideslope
875 * transmitter. Return -1 if there's no GS for the runway
877 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
879 FGNavRecord* gs = rwy->glideslope();
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;
889 // project the gsTransmitterVec along the runwayDirctionVec to get out
890 // final value (in metres)
891 double dist = dot(runwayDirectionVec, gsTransmitterVec);
895 /*******************************************************************
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)
905 double vTouchdown = ac->getPerformance()->vTouchdown();
906 double vTaxi = ac->getPerformance()->vTaxi();
907 double decel = ac->getPerformance()->decelerationOnGround();
908 double vApproach = ac->getPerformance()->vApproach();
910 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
911 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
912 double decelMetric = decel * SG_KT_TO_MPS;
915 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
916 assert( rwy != NULL );
917 SGGeod threshold = rwy->threshold();
918 double currElev = threshold.getElevationFt();
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);
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);
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);
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);
948 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
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);
961 wpt->setSpeed(vTaxi);
962 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
964 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
969 coord = rwy->pointOnCenterline(mindist);
971 if (gn->getVersion() > 0) {
972 tn = gn->findNearestNodeOnRunway(coord, rwy);
974 tn = gn->findNearestNode(coord);
978 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
979 pushBackWaypoint(wpt);
985 /*******************************************************************
987 * initialize the Aircraft at the parking location
988 ******************************************************************/
989 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
993 double aptElev = apt->getElevation();
994 double vTaxi = ac->getPerformance()->vTaxi();
995 double vTaxiReduced = vTaxi * (2.0 / 3.0);
996 if (!gate.isValid()) {
997 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
999 pushBackWaypoint(wpt);
1003 FGParking* parking = gate.parking();
1004 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1005 double az; // unused
1008 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1011 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1012 pushBackWaypoint(wpt);
1014 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1016 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1017 pushBackWaypoint(wpt);
1019 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1021 pushBackWaypoint(wpt);
1027 * @param fltType a string describing the type of
1028 * traffic, normally used for gate assignments
1029 * @return a converted string that gives the runway
1030 * preference schedule to be used at aircraft having
1031 * a preferential runway schedule implemented (i.e.
1032 * having a rwyprefs.xml file
1034 * Currently valid traffic types for gate assignment:
1035 * - gate (commercial gate)
1036 * - cargo (commercial gargo),
1037 * - ga (general aviation) ,
1038 * - ul (ultralight),
1039 * - mil-fighter (military - fighter),
1040 * - mil-transport (military - transport)
1042 * Valid runway classes:
1043 * - com (commercial traffic: jetliners, passenger and cargo)
1044 * - gen (general aviation)
1045 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1046 * - mil (all military traffic)
1048 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1050 if ((fltType == "gate") || (fltType == "cargo")) {
1053 if (fltType == "ga") {
1056 if (fltType == "ul") {
1059 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1066 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1069 if (inAir == false) {
1070 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1072 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank