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.
29 #include <boost/foreach.hpp>
31 #include <simgear/compiler.h>
33 #include <Environment/environment_mgr.hxx>
34 #include <Environment/environment.hxx>
35 #include <simgear/misc/sg_path.hxx>
36 #include <simgear/props/props.hxx>
37 #include <simgear/structure/subsystem_mgr.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/locale.hxx>
42 #include <Airports/runways.hxx>
43 #include <Navaids/NavDataCache.hxx>
45 #include "airport.hxx"
46 #include "dynamics.hxx"
51 using std::random_shuffle;
53 class ParkingAssignment::ParkingAssignmentPrivate
56 ParkingAssignmentPrivate(FGParking* pk, FGAirportDynamics* dyn) :
63 retain(); // initial count of 1
66 ~ParkingAssignmentPrivate()
68 dynamics->releaseParking(parking);
73 if ((--refCount) == 0) {
83 unsigned int refCount;
85 FGAirportDynamicsRef dynamics;
88 ParkingAssignment::ParkingAssignment() :
93 ParkingAssignment::~ParkingAssignment()
96 _sharedData->release();
100 ParkingAssignment::ParkingAssignment(FGParking* pk, FGAirportDynamics* dyn) :
104 _sharedData = new ParkingAssignmentPrivate(pk, dyn);
108 ParkingAssignment::ParkingAssignment(const ParkingAssignment& aOther) :
109 _sharedData(aOther._sharedData)
112 _sharedData->retain();
116 void ParkingAssignment::operator=(const ParkingAssignment& aOther)
118 if (_sharedData == aOther._sharedData) {
119 return; // self-assignment, special case
123 _sharedData->release();
126 _sharedData = aOther._sharedData;
128 _sharedData->retain();
132 void ParkingAssignment::release()
135 _sharedData->release();
140 bool ParkingAssignment::isValid() const
142 return (_sharedData != NULL);
145 FGParking* ParkingAssignment::parking() const
147 return _sharedData ? _sharedData->parking.ptr() : NULL;
150 ////////////////////////////////////////////////////////////////////////////////
152 FGAirportDynamics::FGAirportDynamics(FGAirport * ap):
153 _ap(ap), rwyPrefs(ap),
154 startupController (this),
155 towerController (this),
156 approachController (this),
157 atisSequenceIndex(-1),
158 atisSequenceTimeStamp(0.0)
165 FGAirportDynamics::~FGAirportDynamics()
167 SG_LOG(SG_AI, SG_INFO, "destroyed dynamics for:" << _ap->ident());
171 // Initialization required after XMLRead
172 void FGAirportDynamics::init()
174 groundNetwork.init(this);
175 groundNetwork.setTowerController(&towerController);
179 FGParking* FGAirportDynamics::innerGetAvailableParking(double radius, const string & flType,
180 const string & airline,
181 bool skipEmptyAirlineCode)
183 const FGParkingList& parkings(groundNetwork.allParkings());
184 FGParkingList::const_iterator it;
185 for (it = parkings.begin(); it != parkings.end(); ++it) {
186 FGParkingRef parking = *it;
187 if (!isParkingAvailable(parking)) {
191 if (skipEmptyAirlineCode && parking->getCodes().empty()) {
195 if (!airline.empty() && !parking->getCodes().empty()) {
196 if (parking->getCodes().find(airline, 0) == string::npos) {
201 setParkingAvailable(parking, false);
208 ParkingAssignment FGAirportDynamics::getAvailableParking(double radius, const string & flType,
209 const string & acType,
210 const string & airline)
212 SG_UNUSED(acType); // sadly not used at the moment
214 // most exact seach - airline codes must be present and match
215 FGParking* result = innerGetAvailableParking(radius, flType, airline, true);
217 return ParkingAssignment(result, this);
220 // more tolerant - gates with empty airline codes are permitted
221 result = innerGetAvailableParking(radius, flType, airline, false);
223 return ParkingAssignment(result, this);
226 // fallback - ignore the airline code entirely
227 result = innerGetAvailableParking(radius, flType, string(), false);
228 return result ? ParkingAssignment(result, this) : ParkingAssignment();
231 ParkingAssignment FGAirportDynamics::getParkingByName(const std::string& name) const
233 const FGParkingList& parkings(groundNetwork.allParkings());
234 FGParkingList::const_iterator it;
235 for (it = parkings.begin(); it != parkings.end(); ++it) {
236 if ((*it)->name() == name) {
237 return ParkingAssignment(*it, const_cast<FGAirportDynamics*>(this));
241 return ParkingAssignment();
244 void FGAirportDynamics::setParkingAvailable(FGParking* park, bool available)
247 releaseParking(park);
249 occupiedParkings.insert(park);
253 bool FGAirportDynamics::isParkingAvailable(FGParking* parking) const
255 return (occupiedParkings.find(parking) == occupiedParkings.end());
258 void FGAirportDynamics::releaseParking(FGParking* id)
260 ParkingSet::iterator it = occupiedParkings.find(id);
261 if (it == occupiedParkings.end()) {
265 occupiedParkings.erase(it);
268 class GetParkingsPredicate
270 bool mustBeAvailable;
272 const FGAirportDynamics* dynamics;
274 GetParkingsPredicate(bool b, const std::string& ty, const FGAirportDynamics* dyn) :
280 bool operator()(const FGParkingRef& park) const
282 if (!type.empty() && (park->getType() != type))
285 if (mustBeAvailable && !dynamics->isParkingAvailable(park)) {
293 FGParkingList FGAirportDynamics::getParkings(bool onlyAvailable, const std::string &type) const
295 FGParkingList result(groundNetwork.allParkings());
297 GetParkingsPredicate pred(onlyAvailable, type, this);
298 FGParkingList::iterator it = std::remove_if(result.begin(), result.end(), pred);
299 result.erase(it, result.end());
303 void FGAirportDynamics::setRwyUse(const FGRunwayPreference & ref)
308 bool FGAirportDynamics::innerGetActiveRunway(const string & trafficType,
309 int action, string & runway,
319 if (!rwyPrefs.available()) {
323 RunwayGroup *currRunwayGroup = 0;
324 int nrActiveRunways = 0;
325 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
326 if ((std::abs((long) (dayStart - lastUpdate)) > 600)
327 || trafficType != prevTrafficType) {
330 lastUpdate = dayStart;
331 prevTrafficType = trafficType;
335 ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
336 ->getEnvironment(getLatitude(), getLongitude(),
339 windSpeed = fgGetInt("/environment/metar/base-wind-speed-kt"); //stationweather.get_wind_speed_kt();
340 windHeading = fgGetInt("/environment/metar/base-wind-dir-deg");
341 //stationweather.get_wind_from_heading_deg();
343 //cerr << "finding active Runway for : " << _ap->getId() << endl;
344 //cerr << "Wind Heading : " << windHeading << endl;
345 //cerr << "Wind Speed : " << windSpeed << endl;
347 //cerr << "Nr of seconds since day start << " << dayStart << endl;
349 ScheduleTime *currSched;
350 //cerr << "A"<< endl;
351 currSched = rwyPrefs.getSchedule(trafficType.c_str());
354 //cerr << "B"<< endl;
355 scheduleName = currSched->getName(dayStart);
356 maxTail = currSched->getTailWind();
357 maxCross = currSched->getCrossWind();
358 //cerr << "Current Schedule = : " << scheduleName << endl;
359 if (scheduleName.empty())
361 //cerr << "C"<< endl;
362 currRunwayGroup = rwyPrefs.getGroup(scheduleName);
363 //cerr << "D"<< endl;
364 if (!(currRunwayGroup))
366 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
368 // Keep a history of the currently active runways, to ensure
369 // that an already established selection of runways will not
370 // be overridden once a more preferred selection becomes
371 // available as that can lead to random runway swapping.
372 if (trafficType == "com") {
373 currentlyActive = &comActive;
374 } else if (trafficType == "gen") {
375 currentlyActive = &genActive;
376 } else if (trafficType == "mil") {
377 currentlyActive = &milActive;
378 } else if (trafficType == "ul") {
379 currentlyActive = &ulActive;
382 //cerr << "Durrently active selection for " << trafficType << ": ";
383 for (stringVecIterator it = currentlyActive->begin();
384 it != currentlyActive->end(); it++) {
385 //cerr << (*it) << " ";
389 currRunwayGroup->setActive(_ap,
392 maxTail, maxCross, currentlyActive);
394 // Note that I SHOULD keep multiple lists in memory, one for
395 // general aviation, one for commercial and one for military
397 currentlyActive->clear();
398 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
399 //cerr << "Choosing runway for " << trafficType << endl;
400 for (int i = 0; i < nrActiveRunways; i++) {
401 type = "unknown"; // initialize to something other than landing or takeoff
402 currRunwayGroup->getActive(i, name, type);
403 if (type == "landing") {
404 landing.push_back(name);
405 currentlyActive->push_back(name);
406 //cerr << "Landing " << name << endl;
408 if (type == "takeoff") {
409 takeoff.push_back(name);
410 currentlyActive->push_back(name);
411 //cerr << "takeoff " << name << endl;
417 if (action == 1) // takeoff
419 int nr = takeoff.size();
421 // Note that the randomization below, is just a placeholder to choose between
422 // multiple active runways for this action. This should be
423 // under ATC control.
424 runway = chooseRwyByHeading(takeoff, heading);
426 runway = chooseRunwayFallback();
430 if (action == 2) // landing
432 int nr = landing.size();
434 runway = chooseRwyByHeading(landing, heading);
436 runway = chooseRunwayFallback();
443 string FGAirportDynamics::chooseRwyByHeading(stringVec rwys,
446 double bestError = 360.0;
447 double rwyHeading, headingError;
449 for (stringVecIterator i = rwys.begin(); i != rwys.end(); i++) {
450 if (!_ap->hasRunwayWithIdent(*i)) {
451 SG_LOG(SG_ATC, SG_WARN, "chooseRwyByHeading: runway " << *i <<
452 " not found at " << _ap->ident());
456 FGRunway *rwy = _ap->getRunwayByIdent((*i));
457 rwyHeading = rwy->headingDeg();
458 headingError = fabs(heading - rwyHeading);
459 if (headingError > 180)
460 headingError = fabs(headingError - 360);
461 if (headingError < bestError) {
463 bestError = headingError;
466 //cerr << "Using active runway " << runway << " for heading " << heading << endl;
470 void FGAirportDynamics::getActiveRunway(const string & trafficType,
471 int action, string & runway,
474 bool ok = innerGetActiveRunway(trafficType, action, runway, heading);
476 runway = chooseRunwayFallback();
480 string FGAirportDynamics::chooseRunwayFallback()
482 FGRunway *rwy = _ap->getActiveRunwayForUsage();
486 double FGAirportDynamics::getElevation() const
488 return _ap->getElevation();
491 const string FGAirportDynamics::getId() const
496 // Experimental: Return a different ground frequency depending on the leg of the
497 // Flight. Leg should always have a minimum value of two when this function is called.
498 // Note that in this scheme, the assignment of various frequencies to various ground
499 // operations is completely arbitrary. As such, is a short cut I need to take now,
500 // so that at least I can start working on assigning different frequencies to different
503 int FGAirportDynamics::getGroundFrequency(unsigned leg)
505 //return freqGround.size() ? freqGround[0] : 0; };
506 //cerr << "Getting frequency for : " << leg << endl;
509 SG_LOG(SG_ATC, SG_ALERT,
510 "Leg value is smaller than one at " << SG_ORIGIN);
512 if (freqGround.size() == 0) {
516 if ((freqGround.size() < leg) && (leg > 0)) {
518 (freqGround.size() <=
519 (leg - 1)) ? freqGround[freqGround.size() -
520 1] : freqGround[leg - 1];
522 if ((freqGround.size() >= leg) && (leg > 0)) {
523 groundFreq = freqGround[leg - 1];
528 int FGAirportDynamics::getTowerFrequency(unsigned nr)
532 SG_LOG(SG_ATC, SG_ALERT,
533 "Leg value is smaller than two at " << SG_ORIGIN);
535 if (freqTower.size() == 0) {
538 if ((freqTower.size() > nr - 1) && (nr > 1)) {
539 towerFreq = freqTower[nr - 1];
541 if ((freqTower.size() < nr - 1) && (nr > 1)) {
544 (nr - 1)) ? freqTower[freqTower.size() -
545 1] : freqTower[nr - 2];
547 if ((freqTower.size() >= nr - 1) && (nr > 1)) {
548 towerFreq = freqTower[nr - 2];
553 const std::string FGAirportDynamics::getAtisSequence()
555 if (atisSequenceIndex == -1) {
556 updateAtisSequence(1, false);
559 char atisSequenceString[2];
560 atisSequenceString[0] = 'a' + atisSequenceIndex;
561 atisSequenceString[1] = 0;
563 return globals->get_locale()->getLocalizedString(atisSequenceString, "atc", "unknown");
566 int FGAirportDynamics::updateAtisSequence(int interval, bool forceUpdate)
568 double now = globals->get_sim_time_sec();
569 if (atisSequenceIndex == -1) {
571 atisSequenceTimeStamp = now;
572 atisSequenceIndex = rand() % 26; // random initial sequence letters
573 return atisSequenceIndex;
576 int steps = static_cast<int>((now - atisSequenceTimeStamp) / interval);
577 atisSequenceTimeStamp += (interval * steps);
578 if (forceUpdate && (steps == 0)) {
579 ++steps; // a "special" ATIS update is required
582 atisSequenceIndex = (atisSequenceIndex + steps) % 26;
583 // return a huge value if no update occurred
584 return (atisSequenceIndex + (steps ? 0 : 26*1000));