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 <Environment/environment_mgr.hxx>
42 #include <Environment/environment.hxx>
43 #include <FDM/LaRCsim/basic_aero.h>
44 #include <Navaids/navrecord.hxx>
48 /* FGAIFlightPlan::create()
49 * dynamically create a flight plan for AI traffic, based on data provided by the
50 * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10)
52 * This is the top-level function, and the only one that is publicly available.
57 // Check lat/lon values during initialization;
58 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
59 FGAirport * arr, int legNr, double alt,
60 double speed, double latitude,
61 double longitude, bool firstFlight,
62 double radius, const string & fltType,
63 const string & aircraftType,
64 const string & airline, double distance)
67 int currWpt = wpt_iterator - waypoints.begin();
70 retVal = createPushBack(ac, firstFlight, dep,
71 radius, fltType, aircraftType, airline);
72 // Pregenerate the taxi leg.
74 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
75 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
79 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
80 aircraftType, airline);
83 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
86 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
89 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
93 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
97 retVal = createLanding(ac, arr, fltType);
100 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
103 retVal = createParking(ac, arr, radius);
107 SG_LOG(SG_AI, SG_ALERT,
108 "AIFlightPlan::create() attempting to create unknown leg"
109 " this is probably an internal program error");
112 wpt_iterator = waypoints.begin() + currWpt;
113 //don't increment leg right away, but only once we pass the actual last waypoint that was created.
114 // to do so, mark the last waypoint with a special status flag
116 waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
117 // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
125 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
126 const std::string & aName,
127 const SGGeod & aPos, double aElev,
130 FGAIWaypoint *wpt = new FGAIWaypoint;
131 wpt->setName (aName );
132 wpt->setLongitude (aPos.getLongitudeDeg() );
133 wpt->setLatitude (aPos.getLatitudeDeg() );
134 wpt->setAltitude (aElev );
135 wpt->setSpeed (aSpeed );
136 wpt->setCrossat (-10000.1 );
137 wpt->setGear_down (true );
138 wpt->setFlaps_down (true );
139 wpt->setFinished (false );
140 wpt->setOn_ground (true );
141 wpt->setRouteIndex (0 );
145 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
146 const std::string & aName,
147 const SGGeod & aPos, double aElev,
150 FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
151 wpt->setGear_down (false );
152 wpt->setFlaps_down (false );
153 wpt->setOn_ground (false );
154 wpt->setCrossat (aElev );
158 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
160 FGAIWaypoint *wpt = new FGAIWaypoint;
161 wpt->setName ( aWpt->getName () );
162 wpt->setLongitude ( aWpt->getLongitude() );
163 wpt->setLatitude ( aWpt->getLatitude() );
164 wpt->setAltitude ( aWpt->getAltitude() );
165 wpt->setSpeed ( aWpt->getSpeed() );
166 wpt->setCrossat ( aWpt->getCrossat() );
167 wpt->setGear_down ( aWpt->getGear_down() );
168 wpt->setFlaps_down ( aWpt->getFlaps_down() );
169 wpt->setFinished ( aWpt->isFinished() );
170 wpt->setOn_ground ( aWpt->getOn_ground() );
171 wpt->setRouteIndex ( 0 );
177 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
178 const std::string & aName,
181 FGAIWaypoint *wpt = clone(aWpt);
182 wpt->setName ( aName );
183 wpt->setLongitude ( aPos.getLongitudeDeg () );
184 wpt->setLatitude ( aPos.getLatitudeDeg () );
191 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
192 FGAirport * aAirport,
195 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
196 double airportElev = aAirport->getElevation();
200 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
201 ac->getPerformance()->vTaxi());
202 pushBackWaypoint(wpt);
204 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
205 ac->getPerformance()->vTaxi());
206 pushBackWaypoint(wpt);
209 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
212 const string & fltType,
213 const string & acType,
214 const string & airline)
217 // If this function is called during initialization,
218 // make sure we obtain a valid gate ID first
219 // and place the model at the location of the gate.
222 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
224 if (!gate.isValid()) {
225 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
227 " of flight type " << fltType <<
228 " of airline " << airline <<
229 " at airport " << apt->getId());
233 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
235 // Only set this if it hasn't been set by ATC already.
236 if (activeRunway.empty()) {
237 //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
238 double depHeading = ac->getTrafficRef()->getCourse();
239 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
242 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
243 assert( rwy != NULL );
244 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
246 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
248 createDefaultTakeoffTaxi(ac, apt, rwy);
252 FGTaxiNodeRef runwayNode;
253 if (gn->getVersion() > 0) {
254 FGTaxiNodeRef runwayNode = gn->findNearestNodeOnRunway(runwayTakeoff);
256 FGTaxiNodeRef runwayNode = gn->findNearestNode(runwayTakeoff);
259 // A negative gateId indicates an overflow parking, use a
260 // fallback mechanism for this.
261 // Starting from gate 0 in this case is a bit of a hack
262 // which requires a more proper solution later on.
264 // taxiRoute = new FGTaxiRoute;
266 // Determine which node to start from.
268 // Find out which node to start from
269 FGParking *park = gate.parking();
271 node = park->getPushBackPoint();
273 // Handle case where parking doesn't have a node
277 node = lastNodeVisited;
282 FGTaxiRoute taxiRoute;
284 taxiRoute = gn->findShortestRoute(node, runwayNode);
286 if (taxiRoute.empty()) {
287 createDefaultTakeoffTaxi(ac, apt, rwy);
292 FGTaxiNodeRef skipNode;
294 //bool isPushBackPoint = false;
296 // If this is called during initialization, randomly
297 // skip a number of waypoints to get a more realistic
299 int nrWaypointsToSkip = rand() % taxiRoute.size();
300 // but make sure we always keep two active waypoints
301 // to prevent a segmentation fault
302 for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
303 taxiRoute.next(skipNode, &route);
306 gate.release(); // free up our gate as required
308 if (taxiRoute.size() > 1) {
309 taxiRoute.next(skipNode, &route); // chop off the first waypoint, because that is already the last of the pushback route
313 // push each node on the taxi route as a waypoint
315 //cerr << "Building taxi route" << endl;
317 // Note that the line wpt->setRouteIndex was commented out by revision [afcdbd] 2012-01-01,
318 // which breaks the rendering functions.
319 // These can probably be generated on the fly however.
320 while (taxiRoute.next(node, &route)) {
322 snprintf(buffer, 10, "%d", node->getIndex());
324 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
325 ac->getPerformance()->vTaxi());
326 wpt->setRouteIndex(route);
327 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
328 if (taxiRoute.nodesLeft() == 1) {
329 // Note that we actually have hold points in the ground network, but this is just an initial test.
330 //cerr << "Setting departurehold point: " << endl;
331 wpt->setName( wpt->getName() + string("DepartureHold"));
333 if (taxiRoute.nodesLeft() == 0) {
334 wpt->setName(wpt->getName() + string("Accel"));
336 pushBackWaypoint(wpt);
338 // Acceleration point, 105 meters into the runway,
339 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
340 FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
341 pushBackWaypoint(wpt);
343 //cerr << "[done]" << endl;
347 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
348 FGAirport * aAirport)
351 SGGeod::fromDeg(waypoints.back()->getLongitude(),
352 waypoints.back()->getLatitude());
353 double airportElev = aAirport->getElevation();
357 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
358 ac->getPerformance()->vTaxi());
359 pushBackWaypoint(wpt);
361 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
362 ac->getPerformance()->vTaxi());
363 pushBackWaypoint(wpt);
365 if (gate.isValid()) {
366 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
367 ac->getPerformance()->vTaxi());
368 pushBackWaypoint(wpt);
372 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
374 const string & fltType,
375 const string & acType,
376 const string & airline)
379 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
382 SGGeod lastWptPos = waypoints.back()->getPos();
383 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
385 // Find a route from runway end to parking/gate.
387 createDefaultLandingTaxi(ac, apt);
391 FGTaxiNodeRef runwayNode;
392 if (gn->getVersion() == 1) {
393 runwayNode = gn->findNearestNodeOnRunway(lastWptPos);
395 runwayNode = gn->findNearestNode(lastWptPos);
397 //cerr << "Using network node " << runwayId << endl;
398 // A negative gateId indicates an overflow parking, use a
399 // fallback mechanism for this.
400 // Starting from gate 0 doesn't work, so don't try it
401 FGTaxiRoute taxiRoute;
403 taxiRoute = gn->findShortestRoute(runwayNode, gate.parking());
405 if (taxiRoute.empty()) {
406 createDefaultLandingTaxi(ac, apt);
412 int size = taxiRoute.size();
413 // Omit the last two waypoints, as
414 // those are created by createParking()
416 for (int i = 0; i < size - 2; i++) {
417 taxiRoute.next(node, &route);
419 snprintf(buffer, 10, "%d", node->getIndex());
421 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
422 ac->getPerformance()->vTaxi());
424 wpt->setRouteIndex(route);
425 pushBackWaypoint(wpt);
430 static double accelDistance(double v0, double v1, double accel)
432 double t = fabs(v1 - v0) / accel; // time in seconds to change velocity
433 // area under the v/t graph: (t * v0) + (dV / 2t) where (dV = v1 - v0)
434 return t * 0.5 * (v1 + v0);
437 // find the horizontal distance to gain the specific altiude, holding
438 // a constant pitch angle. Used to compute distance based on standard FD/AP
439 // PITCH mode prior to VS or CLIMB engaging. Visually, we want to avoid
440 // a dip in the nose angle after rotation, during initial climb-out.
441 static double pitchDistance(double pitchAngleDeg, double altGainM)
443 return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
446 /*******************************************************************
449 * - Speed -> knots -> nm/hour
450 * - distance along runway =-> meters
451 * - accel / decel -> is given as knots/hour, but this is highly questionable:
452 * for a jet_transport performance class, a accel / decel rate of 5 / 2 is
453 * given respectively. According to performance data.cxx, a value of kts / second seems
454 * more likely however.
456 ******************************************************************/
457 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
458 FGAirport * apt, double speed,
459 const string & fltType)
461 const double ACCEL_POINT = 105.0;
462 // climb-out angle in degrees. could move this to the perf-db but this
463 // value is pretty sane
464 const double INITIAL_PITCH_ANGLE = 10.0;
466 double accel = ac->getPerformance()->acceleration();
467 double vTaxi = ac->getPerformance()->vTaxi();
468 double vRotate = ac->getPerformance()->vRotate();
469 double vTakeoff = ac->getPerformance()->vTakeoff();
471 double accelMetric = accel * SG_KT_TO_MPS;
472 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
473 double vRotateMetric = vRotate * SG_KT_TO_MPS;
476 // Get the current active runway, based on code from David Luff
477 // This should actually be unified and extended to include
478 // Preferential runway use schema's
479 // NOTE: DT (2009-01-18: IIRC, this is currently already the case,
480 // because the getActive runway function takes care of that.
482 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
483 double heading = ac->getTrafficRef()->getCourse();
484 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
488 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
489 assert( rwy != NULL );
490 double airportElev = apt->getElevation();
492 double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
494 SGGeod accelPoint = rwy->pointOnCenterline(d);
495 wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
496 pushBackWaypoint(wpt);
498 double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
500 double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
501 accelPoint = rwy->pointOnCenterline(gearUpDist);
503 wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
505 wpt->setCrossat(airportElev + 400);
506 wpt->setOn_ground(false);
507 wpt->setGear_down(false);
508 pushBackWaypoint(wpt);
510 // limit climbout speed to 240kts below 10000'
511 double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
513 // create two climb-out points. This is important becuase the first climb point will
514 // be a (sometimes large) turn towards the destination, and we don't want to
515 // commence that turn below 2000'
516 double climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2000 * SG_FEET_TO_METER);
517 accelPoint = rwy->pointOnCenterline(climbOut);
518 wpt = createInAir(ac, "2000'", accelPoint, airportElev + 2000, vClimbBelow10000);
519 pushBackWaypoint(wpt);
521 climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2500 * SG_FEET_TO_METER);
522 accelPoint = rwy->pointOnCenterline(climbOut);
523 wpt = createInAir(ac, "2500'", accelPoint, airportElev + 2500, vClimbBelow10000);
524 pushBackWaypoint(wpt);
529 /*******************************************************************
531 * initialize the Aircraft at the parking location
532 ******************************************************************/
533 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
534 FGAirport * apt, FGAirport* arrival,
535 double speed, double alt,
536 const string & fltType)
540 double vClimb = ac->getPerformance()->vClimb();
543 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
544 double heading = ac->getTrafficRef()->getCourse();
545 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
549 for (wpt_vector_iterator i = sid->getFirstWayPoint();
550 i != sid->getLastWayPoint(); i++) {
551 pushBackWaypoint(clone(*(i)));
552 //cerr << " Cloning waypoint " << endl;
555 FGRunway* runway = apt->getRunwayByIdent(activeRunway);
556 SGGeod cur = runway->end();
557 if (!waypoints.empty()) {
558 cur = waypoints.back()->getPos();
561 // compute course towards destination
562 double course = SGGeodesy::courseDeg(cur, arrival->geod());
564 SGGeod climb1 = SGGeodesy::direct(cur, course, 10 * SG_NM_TO_METER);
565 wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
566 wpt->setGear_down(true);
567 wpt->setFlaps_down(true);
568 pushBackWaypoint(wpt);
570 SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
571 wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
572 pushBackWaypoint(wpt);
579 /*******************************************************************
581 * Generate a flight path from the last waypoint of the cruise to
582 * the permission to land point
583 ******************************************************************/
584 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
585 double latitude, double longitude,
586 double speed, double alt,
587 const string & fltType,
588 double requiredDistance)
590 bool reposition = false;
592 double vDescent = ac->getPerformance()->vDescent();
593 double vApproach = ac->getPerformance()->vApproach();
595 //Beginning of Descent
596 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
597 double heading = ac->getTrafficRef()->getCourse();
598 apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
600 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
601 assert( rwy != NULL );
603 // Create a slow descent path that ends 250 lateral to the runway.
604 double initialTurnRadius = getTurnRadius(vDescent, true);
605 //double finalTurnRadius = getTurnRadius(vApproach, true);
607 // get length of the downwind leg for the intended runway
608 double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance(); //12 * SG_NM_TO_METER;
609 //time_t previousArrivalTime= apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
612 SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
613 SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
614 SGGeod refPoint = rwy->pointOnCenterline(0);
615 double distance = SGGeodesy::distanceM(current, initialTarget);
616 double azimuth = SGGeodesy::courseDeg(current, initialTarget);
619 // To prevent absurdly steep approaches, compute the origin from where the approach should have started
622 if (ac->getTrafficRef()->getCallSign() ==
623 fgGetString("/ai/track-callsign")) {
624 //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
628 if (distance < requiredDistance * 0.8) {
630 SGGeodesy::direct(initialTarget, azimuth,
631 -requiredDistance, origin, dummyAz2);
633 distance = SGGeodesy::distanceM(current, initialTarget);
634 azimuth = SGGeodesy::courseDeg(current, initialTarget);
639 double dAlt = 0; // = alt - (apt->getElevation() + 2000);
641 if (apt->getDynamics()->getGroundNetwork()) {
642 tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
646 dAlt = alt - ((tn->getElevationFt()) + 2000);
648 dAlt = alt - (apt->getElevation() + 2000);
651 double nPoints = 100;
654 // The descent path contains the following phases:
655 // 1) a linear glide path from the initial position to
656 // 2) a semi circle turn to final
659 //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
660 // Create an initial destination point on a semicircle
661 //cerr << "lateral offset : " << lateralOffset << endl;
662 //cerr << "Distance : " << distance << endl;
663 //cerr << "Azimuth : " << azimuth << endl;
664 //cerr << "Initial Lateral point: " << lateralOffset << endl;
665 // double lat = refPoint.getLatitudeDeg();
666 // double lon = refPoint.getLongitudeDeg();
667 //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
668 // lat = initialTarget.getLatitudeDeg();
669 // lon = initialTarget.getLongitudeDeg();
670 //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
672 double ratio = initialTurnRadius / distance;
678 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
680 cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
681 //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
682 double side = azimuth - rwy->headingDeg();
683 double lateralOffset = initialTurnRadius;
689 // Calculate the ETA at final, based on remaining distance, and approach speed.
690 // distance should really consist of flying time to terniary target, plus circle
691 // but the distance to secondary target should work as a reasonable approximation
692 // aditionally add the amount of distance covered by making a turn of "side"
693 double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
695 (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
696 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
697 //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
698 // cerr << " Arrival time estimation: turn angle " << side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
702 time_t eta = now + remaining;
703 //choose a distance to the runway such that it will take at least 60 seconds more
704 // time to get there than the previous aircraft.
705 // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
709 if (reposition == false) {
711 apt->getDynamics()->getApproachController()->getRunway(rwy->
714 requestTimeSlot(eta);
718 //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
719 arrivalTime = newEta;
720 time_t additionalTimeNeeded = newEta - eta;
721 double distanceCovered =
722 ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
723 distanceOut += distanceCovered;
724 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
725 //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
727 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
729 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
731 SGGeod secondaryTarget =
732 rwy->pointOffCenterline(-distanceOut, lateralOffset);
733 initialTarget = rwy->pointOnCenterline(-distanceOut);
734 distance = SGGeodesy::distanceM(origin, secondaryTarget);
735 azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
738 // lat = secondaryTarget.getLatitudeDeg();
739 // lon = secondaryTarget.getLongitudeDeg();
740 //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
741 //cerr << "Distance : " << distance << endl;
742 //cerr << "Azimuth : " << azimuth << endl;
745 ratio = initialTurnRadius / distance;
750 newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
751 newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
752 //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
754 azimuth += newHeading;
756 azimuth -= newHeading;
759 SGGeod tertiaryTarget;
760 SGGeodesy::direct(origin, azimuth,
761 newDistance, tertiaryTarget, dummyAz2);
763 // lat = tertiaryTarget.getLatitudeDeg();
764 // lon = tertiaryTarget.getLongitudeDeg();
765 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
768 for (int i = 1; i < nPoints; i++) {
770 double currentDist = i * (newDistance / nPoints);
771 double currentAltitude = alt - (i * (dAlt / nPoints));
772 SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
773 snprintf(buffer, 16, "descent%03d", i);
774 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
775 wpt->setCrossat(currentAltitude);
776 wpt->setTrackLength((newDistance / nPoints));
777 pushBackWaypoint(wpt);
778 //cerr << "Track Length : " << wpt->trackLength;
779 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
782 //cerr << "Phase 2: Circle " << endl;
783 double initialAzimuth =
784 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
785 double finalAzimuth =
786 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
788 //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
789 int increment, startval, endval;
790 // circle right around secondary target if orig of position is to the right of the runway
791 // i.e. use negative angles; else circle leftward and use postivi
794 startval = floor(initialAzimuth);
795 endval = ceil(finalAzimuth);
796 if (endval > startval) {
801 startval = ceil(initialAzimuth);
802 endval = floor(finalAzimuth);
803 if (endval < startval) {
809 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
810 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
811 double currentAltitude = 0;
813 currentAltitude = (tn->getElevationFt()) + 2000;
815 currentAltitude = apt->getElevation() + 2000;
818 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
819 for (int i = startval; i != endval; i += increment) {
821 //double currentAltitude = apt->getElevation() + 2000;
823 SGGeodesy::direct(secondaryTarget, i,
824 initialTurnRadius, result, dummyAz2);
825 snprintf(buffer, 16, "turn%03d", i);
826 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
827 wpt->setCrossat(currentAltitude);
828 wpt->setTrackLength(trackLength);
829 //cerr << "Track Length : " << wpt->trackLength;
830 pushBackWaypoint(wpt);
831 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
835 // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over.
836 //cerr << "Phase 3: Approach" << endl;
838 //cerr << "Done" << endl;
840 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
841 IncrementWaypoint(true);
842 IncrementWaypoint(true);
846 //double minDistance = HUGE_VAL;
848 tempDistance = SGGeodesy::distanceM(current, initialTarget);
850 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
852 apt->getDynamics()->getApproachController()->getRunway(rwy->
855 requestTimeSlot(eta);
856 arrivalTime = newEta;
858 ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
859 //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
860 IncrementWaypoint(true); // remove waypoint BOD2
861 while (checkTrackLength("final001") > newDistance) {
862 IncrementWaypoint(true);
864 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
865 ac->resetPositionFromFlightPlan();
867 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
872 * compute the distance along the centerline, to the ILS glideslope
873 * transmitter. Return -1 if there's no GS for the runway
875 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
877 FGNavRecord* gs = rwy->glideslope();
882 SGVec3d runwayPosCart = SGVec3d::fromGeod(rwy->pointOnCenterline(0.0));
883 // compute a unit vector in ECF cartesian space, from the runway beginning to the end
884 SGVec3d runwayDirectionVec = normalize(SGVec3d::fromGeod(rwy->end()) - runwayPosCart);
885 SGVec3d gsTransmitterVec = gs->cart() - runwayPosCart;
887 // project the gsTransmitterVec along the runwayDirctionVec to get out
888 // final value (in metres)
889 double dist = dot(runwayDirectionVec, gsTransmitterVec);
893 /*******************************************************************
895 * Create a flight path from the "permision to land" point (currently
896 hardcoded at 5000 meters from the threshold) to the threshold, at
897 a standard glide slope angle of 3 degrees.
898 Position : 50.0354 8.52592 384 364 11112
899 ******************************************************************/
900 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
901 const string & fltType)
903 double vTouchdown = ac->getPerformance()->vTouchdown();
904 double vTaxi = ac->getPerformance()->vTaxi();
905 double decel = ac->getPerformance()->decelerationOnGround();
906 double vApproach = ac->getPerformance()->vApproach();
908 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
909 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
910 double decelMetric = decel * SG_KT_TO_MPS;
913 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
914 assert( rwy != NULL );
915 SGGeod threshold = rwy->threshold();
916 double currElev = threshold.getElevationFt();
918 double touchdownDistance = runwayGlideslopeTouchdownDistance(rwy);
919 if (touchdownDistance < 0.0) {
920 double landingLength = rwy->lengthM() - (rwy->displacedThresholdM());
921 // touchdown 25% of the way along the landing area
922 touchdownDistance = rwy->displacedThresholdM() + (landingLength * 0.25);
926 // find glideslope entry point, 2000' above touchdown elevation
927 double glideslopeEntry = -((2000 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
928 FGAIWaypoint *wpt = createInAir(ac, "Glideslope begin", rwy->pointOnCenterline(glideslopeEntry),
929 currElev + 2000, vApproach);
930 pushBackWaypoint(wpt);
932 // deceleration point, 500' above touchdown elevation - slow from approach speed
933 // to touchdown speed
934 double decelPoint = -((500 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
935 wpt = createInAir(ac, "500' decel", rwy->pointOnCenterline(decelPoint),
936 currElev + 2000, vTouchdown);
937 pushBackWaypoint(wpt);
939 // compute elevation above the runway start, based on a 3-degree glideslope
940 double heightAboveRunwayStart = touchdownDistance *
941 tan(3.0 * SG_DEGREES_TO_RADIANS) * SG_METER_TO_FEET;
942 wpt = createInAir(ac, "CrossThreshold", rwy->begin(),
943 heightAboveRunwayStart + currElev, vTouchdown);
944 pushBackWaypoint(wpt);
946 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
949 for (int i = 1; i < nPoints; i++) {
950 snprintf(buffer, 12, "landing03%d", i);
951 double t = ((double) i) / nPoints;
952 coord = rwy->pointOnCenterline(touchdownDistance + (rolloutDistance * t));
953 double vel = (vTouchdownMetric * (1.0 - t)) + (vTaxiMetric * t);
954 wpt = createOnGround(ac, buffer, coord, currElev, vel);
955 wpt->setCrossat(currElev);
956 pushBackWaypoint(wpt);
959 wpt->setSpeed(vTaxi);
960 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
962 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
967 coord = rwy->pointOnCenterline(mindist);
969 if (gn->getVersion() > 0) {
970 tn = gn->findNearestNodeOnRunway(coord, rwy);
972 tn = gn->findNearestNode(coord);
976 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
977 pushBackWaypoint(wpt);
983 /*******************************************************************
985 * initialize the Aircraft at the parking location
986 ******************************************************************/
987 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
991 double aptElev = apt->getElevation();
992 double vTaxi = ac->getPerformance()->vTaxi();
993 double vTaxiReduced = vTaxi * (2.0 / 3.0);
994 if (!gate.isValid()) {
995 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
997 pushBackWaypoint(wpt);
1001 FGParking* parking = gate.parking();
1002 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1003 double az; // unused
1006 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1009 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1010 pushBackWaypoint(wpt);
1012 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1014 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1015 pushBackWaypoint(wpt);
1017 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1019 pushBackWaypoint(wpt);
1025 * @param fltType a string describing the type of
1026 * traffic, normally used for gate assignments
1027 * @return a converted string that gives the runway
1028 * preference schedule to be used at aircraft having
1029 * a preferential runway schedule implemented (i.e.
1030 * having a rwyprefs.xml file
1032 * Currently valid traffic types for gate assignment:
1033 * - gate (commercial gate)
1034 * - cargo (commercial gargo),
1035 * - ga (general aviation) ,
1036 * - ul (ultralight),
1037 * - mil-fighter (military - fighter),
1038 * - mil-transport (military - transport)
1040 * Valid runway classes:
1041 * - com (commercial traffic: jetliners, passenger and cargo)
1042 * - gen (general aviation)
1043 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1044 * - mil (all military traffic)
1046 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1048 if ((fltType == "gate") || (fltType == "cargo")) {
1051 if (fltType == "ga") {
1054 if (fltType == "ul") {
1057 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1064 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1067 if (inAir == false) {
1068 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1070 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank