1 // dynamics.cxx - Code to manage the higher order airport ground activities
2 // Written by Durk Talsma, started December 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.
27 #include <simgear/compiler.h>
29 #include <Environment/environment_mgr.hxx>
30 #include <Environment/environment.hxx>
31 #include <simgear/misc/sg_path.hxx>
32 #include <simgear/props/props.hxx>
33 #include <simgear/structure/subsystem_mgr.hxx>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/route/waypoint.hxx>
36 #include <Main/globals.hxx>
37 #include <Main/fg_props.hxx>
38 #include <Airports/runways.hxx>
39 #include <ATCDCL/ATCutils.hxx>
47 using std::random_shuffle;
50 #include "dynamics.hxx"
52 FGAirportDynamics::FGAirportDynamics(FGAirport * ap):
53 _ap(ap), rwyPrefs(ap), SIDs(ap),
54 atisSequenceIndex(-1),
55 atisSequenceTimeStamp(0.0)
56 startupController(this);
62 FGAirportDynamics::~FGAirportDynamics()
67 // Initialization required after XMLRead
68 void FGAirportDynamics::init()
70 // This may seem a bit weird to first randomly shuffle the parkings
71 // and then sort them again. However, parkings are sorted here by ascending
72 // radius. Since many parkings have similar radii, with each radius class they will
73 // still be allocated relatively systematically. Randomizing prior to sorting will
74 // prevent any initial orderings to be destroyed, leading (hopefully) to a more
75 // naturalistic gate assignment.
76 random_shuffle(parkings.begin(), parkings.end());
77 sort(parkings.begin(), parkings.end());
78 // add the gate positions to the ground network.
79 groundNetwork.setParent(_ap);
80 groundNetwork.addNodes(&parkings);
82 groundNetwork.setTowerController(&towerController);
86 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon,
87 double *heading, int *gateId,
89 const string & flType,
90 const string & acType,
91 const string & airline)
94 bool available = false;
97 FGParkingVecIterator i;
98 if (parkings.begin() == parkings.end()) {
99 //cerr << "Could not find parking spot at " << _ap->getId() << endl;
100 *lat = _ap->getLatitude();
101 *lon = _ap->getLongitude();
105 // First try finding a parking with a designated airline code
106 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
108 // Taken by another aircraft
109 if (!(i->isAvailable())) {
113 // No airline codes, so skip
114 if (i->getCodes().empty()) {
117 } else { // Airline code doesn't match
118 //cerr << "Code = " << airline << ": Codes " << i->getCodes();
119 if (i->getCodes().find(airline, 0) == string::npos) {
121 //cerr << "Unavailable" << endl;
124 //cerr << "Available" << endl;
127 // Type doesn't match
128 if (i->getType() != flType) {
133 if (i->getRadius() < rad) {
139 *lat = i->getLatitude();
140 *lon = i->getLongitude();
141 *heading = i->getHeading();
142 *gateId = i->getIndex();
143 i->setAvailable(false);
147 // then try again for those without codes.
148 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
150 if (!(i->isAvailable())) {
154 if (!(i->getCodes().empty())) {
155 if ((i->getCodes().find(airline, 0) == string::npos)) {
160 if (i->getType() != flType) {
165 if (i->getRadius() < rad) {
171 *lat = i->getLatitude();
172 *lon = i->getLongitude();
173 *heading = i->getHeading();
174 *gateId = i->getIndex();
175 i->setAvailable(false);
179 // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
180 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
182 if (!(i->isAvailable())) {
186 if (i->getType() != flType) {
191 if (i->getRadius() < rad) {
197 *lat = i->getLatitude();
198 *lon = i->getLongitude();
199 *heading = i->getHeading();
200 *gateId = i->getIndex();
201 i->setAvailable(false);
207 //cerr << "Traffic overflow at" << _ap->getId()
208 // << ". flType = " << flType
209 // << ". airline = " << airline
210 // << " Radius = " <<rad
212 *lat = _ap->getLatitude();
213 *lon = _ap->getLongitude();
221 void FGAirportDynamics::getParking(int id, double *lat, double *lon,
225 *lat = _ap->getLatitude();
226 *lon = _ap->getLongitude();
229 FGParkingVecIterator i = parkings.begin();
230 for (i = parkings.begin(); i != parkings.end(); i++) {
231 if (id == i->getIndex()) {
232 *lat = i->getLatitude();
233 *lon = i->getLongitude();
234 *heading = i->getHeading();
240 FGParking *FGAirportDynamics::getParking(int id)
242 FGParkingVecIterator i = parkings.begin();
243 for (i = parkings.begin(); i != parkings.end(); i++) {
244 if (id == i->getIndex()) {
251 string FGAirportDynamics::getParkingName(int id)
253 FGParkingVecIterator i = parkings.begin();
254 for (i = parkings.begin(); i != parkings.end(); i++) {
255 if (id == i->getIndex()) {
260 return string("overflow");
263 void FGAirportDynamics::releaseParking(int id)
267 FGParkingVecIterator i = parkings.begin();
268 for (i = parkings.begin(); i != parkings.end(); i++) {
269 if (id == i->getIndex()) {
270 i->setAvailable(true);
276 void FGAirportDynamics::setRwyUse(const FGRunwayPreference & ref)
279 //cerr << "Exiting due to not implemented yet" << endl;
283 bool FGAirportDynamics::innerGetActiveRunway(const string & trafficType,
284 int action, string & runway,
294 if (!rwyPrefs.available()) {
298 RunwayGroup *currRunwayGroup = 0;
299 int nrActiveRunways = 0;
300 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
301 if ((abs((long) (dayStart - lastUpdate)) > 600)
302 || trafficType != prevTrafficType) {
305 lastUpdate = dayStart;
306 prevTrafficType = trafficType;
310 ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
311 ->getEnvironment(getLatitude(), getLongitude(),
314 windSpeed = fgGetInt("/environment/metar/base-wind-speed-kt"); //stationweather.get_wind_speed_kt();
315 windHeading = fgGetInt("/environment/metar/base-wind-dir-deg");
316 //stationweather.get_wind_from_heading_deg();
318 //cerr << "finding active Runway for : " << _ap->getId() << endl;
319 //cerr << "Wind Heading : " << windHeading << endl;
320 //cerr << "Wind Speed : " << windSpeed << endl;
322 //cerr << "Nr of seconds since day start << " << dayStart << endl;
324 ScheduleTime *currSched;
325 //cerr << "A"<< endl;
326 currSched = rwyPrefs.getSchedule(trafficType.c_str());
329 //cerr << "B"<< endl;
330 scheduleName = currSched->getName(dayStart);
331 maxTail = currSched->getTailWind();
332 maxCross = currSched->getCrossWind();
333 //cerr << "Current Schedule = : " << scheduleName << endl;
334 if (scheduleName.empty())
336 //cerr << "C"<< endl;
337 currRunwayGroup = rwyPrefs.getGroup(scheduleName);
338 //cerr << "D"<< endl;
339 if (!(currRunwayGroup))
341 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
343 // Keep a history of the currently active runways, to ensure
344 // that an already established selection of runways will not
345 // be overridden once a more preferred selection becomes
346 // available as that can lead to random runway swapping.
347 if (trafficType == "com") {
348 currentlyActive = &comActive;
349 } else if (trafficType == "gen") {
350 currentlyActive = &genActive;
351 } else if (trafficType == "mil") {
352 currentlyActive = &milActive;
353 } else if (trafficType == "ul") {
354 currentlyActive = &ulActive;
357 //cerr << "Durrently active selection for " << trafficType << ": ";
358 for (stringVecIterator it = currentlyActive->begin();
359 it != currentlyActive->end(); it++) {
360 //cerr << (*it) << " ";
364 currRunwayGroup->setActive(_ap,
367 maxTail, maxCross, currentlyActive);
369 // Note that I SHOULD keep multiple lists in memory, one for
370 // general aviation, one for commercial and one for military
372 currentlyActive->clear();
373 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
374 //cerr << "Choosing runway for " << trafficType << endl;
375 for (int i = 0; i < nrActiveRunways; i++) {
376 type = "unknown"; // initialize to something other than landing or takeoff
377 currRunwayGroup->getActive(i, name, type);
378 if (type == "landing") {
379 landing.push_back(name);
380 currentlyActive->push_back(name);
381 //cerr << "Landing " << name << endl;
383 if (type == "takeoff") {
384 takeoff.push_back(name);
385 currentlyActive->push_back(name);
386 //cerr << "takeoff " << name << endl;
392 if (action == 1) // takeoff
394 int nr = takeoff.size();
396 // Note that the randomization below, is just a placeholder to choose between
397 // multiple active runways for this action. This should be
398 // under ATC control.
399 runway = chooseRwyByHeading(takeoff, heading);
401 runway = chooseRunwayFallback();
405 if (action == 2) // landing
407 int nr = landing.size();
409 runway = chooseRwyByHeading(landing, heading);
411 runway = chooseRunwayFallback();
418 string FGAirportDynamics::chooseRwyByHeading(stringVec rwys,
421 double bestError = 360.0;
422 double rwyHeading, headingError;
424 for (stringVecIterator i = rwys.begin(); i != rwys.end(); i++) {
425 if (!_ap->hasRunwayWithIdent(*i)) {
426 SG_LOG(SG_ATC, SG_WARN, "chooseRwyByHeading: runway " << *i <<
427 " not found at " << _ap->ident());
431 FGRunway *rwy = _ap->getRunwayByIdent((*i));
432 rwyHeading = rwy->headingDeg();
433 headingError = fabs(heading - rwyHeading);
434 if (headingError > 180)
435 headingError = fabs(headingError - 360);
436 if (headingError < bestError) {
438 bestError = headingError;
441 //cerr << "Using active runway " << runway << " for heading " << heading << endl;
445 void FGAirportDynamics::getActiveRunway(const string & trafficType,
446 int action, string & runway,
449 bool ok = innerGetActiveRunway(trafficType, action, runway, heading);
451 runway = chooseRunwayFallback();
455 string FGAirportDynamics::chooseRunwayFallback()
457 FGRunway *rwy = _ap->getActiveRunwayForUsage();
461 void FGAirportDynamics::addParking(FGParking & park)
463 parkings.push_back(park);
466 double FGAirportDynamics::getLatitude() const
468 return _ap->getLatitude();
471 double FGAirportDynamics::getLongitude() const
473 return _ap->getLongitude();
476 double FGAirportDynamics::getElevation() const
478 return _ap->getElevation();
481 const string & FGAirportDynamics::getId() const
486 // Experimental: Return a different ground frequency depending on the leg of the
487 // Flight. Leg should always have a minimum value of two when this function is called.
488 // Note that in this scheme, the assignment of various frequencies to various ground
489 // operations is completely arbitrary. As such, is a short cut I need to take now,
490 // so that at least I can start working on assigning different frequencies to different
493 int FGAirportDynamics::getGroundFrequency(unsigned leg)
495 //return freqGround.size() ? freqGround[0] : 0; };
498 SG_LOG(SG_ATC, SG_ALERT,
499 "Leg value is smaller than two at " << SG_ORIGIN);
501 if (freqGround.size() == 0) {
504 if ((freqGround.size() > leg - 1) && (leg > 1)) {
505 groundFreq = freqGround[leg - 1];
507 if ((freqGround.size() < leg - 1) && (leg > 1)) {
510 (leg - 1)) ? freqGround[freqGround.size() -
511 1] : freqGround[leg - 2];
513 if ((freqGround.size() >= leg - 1) && (leg > 1)) {
514 groundFreq = freqGround[leg - 2];
519 int FGAirportDynamics::getTowerFrequency(unsigned nr)
523 SG_LOG(SG_ATC, SG_ALERT,
524 "Leg value is smaller than two at " << SG_ORIGIN);
526 if (freqTower.size() == 0) {
529 if ((freqTower.size() > nr - 1) && (nr > 1)) {
530 towerFreq = freqTower[nr - 1];
532 if ((freqTower.size() < nr - 1) && (nr > 1)) {
535 (nr - 1)) ? freqTower[freqTower.size() -
536 1] : freqTower[nr - 2];
538 if ((freqTower.size() >= nr - 1) && (nr > 1)) {
539 towerFreq = freqTower[nr - 2];
545 FGAIFlightPlan *FGAirportDynamics::getSID(string activeRunway,
548 return SIDs.getBest(activeRunway, heading);
551 const std::string FGAirportDynamics::getAtisSequence()
553 if (atisSequenceIndex == -1) {
554 updateAtisSequence(1, false);
557 return GetPhoneticLetter(atisSequenceIndex);
560 int FGAirportDynamics::updateAtisSequence(int interval, bool forceUpdate)
562 double now = globals->get_sim_time_sec();
563 if (atisSequenceIndex == -1) {
565 atisSequenceTimeStamp = now;
566 atisSequenceIndex = rand() % LTRS; // random initial sequence letters
567 return atisSequenceIndex;
570 int steps = static_cast<int>((now - atisSequenceTimeStamp) / interval);
571 atisSequenceTimeStamp += (interval * steps);
572 if (forceUpdate && (steps == 0)) {
573 ++steps; // a "special" ATIS update is required
576 atisSequenceIndex = (atisSequenceIndex + steps) % LTRS;
577 // return a huge value if no update occurred
578 return (atisSequenceIndex + (steps ? 0 : LTRS*1000));