1 // FGTower - a class to provide tower control at towered airports.
3 // Written by David Luff, started March 2002.
5 // Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #include <Main/globals.hxx>
22 #include <Airports/runways.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/debug/logstream.hxx>
27 #include "ATCdisplay.hxx"
29 #include "ATCutils.hxx"
30 #include "commlist.hxx"
31 #include "AILocalTraffic.hxx"
37 TowerPlaneRec::TowerPlaneRec() :
39 clearedToLineUp(false),
40 clearedToTakeOff(false),
41 holdShortReported(false),
42 longFinalReported(false),
43 longFinalAcknowledged(false),
45 finalAcknowledged(false),
50 landingType(AIP_LT_UNKNOWN),
53 plane.callsign = "UNKNOWN";
56 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
58 clearedToLineUp(false),
59 clearedToTakeOff(false),
60 holdShortReported(false),
61 longFinalReported(false),
62 longFinalAcknowledged(false),
64 finalAcknowledged(false),
69 landingType(AIP_LT_UNKNOWN),
75 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
77 clearedToLineUp(false),
78 clearedToTakeOff(false),
79 holdShortReported(false),
80 longFinalReported(false),
81 longFinalAcknowledged(false),
83 finalAcknowledged(false),
88 landingType(AIP_LT_UNKNOWN),
91 plane.callsign = "UNKNOWN";
95 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
97 clearedToLineUp(false),
98 clearedToTakeOff(false),
99 holdShortReported(false),
100 longFinalReported(false),
101 longFinalAcknowledged(false),
102 finalReported(false),
103 finalAcknowledged(false),
108 landingType(AIP_LT_UNKNOWN),
119 ATCmgr = globals->get_ATC_mgr();
121 // Init the property nodes - TODO - need to make sure we're getting surface winds.
122 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
123 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
126 update_count_max = 15;
128 holdListItr = holdList.begin();
129 appListItr = appList.begin();
130 depListItr = depList.begin();
131 rwyListItr = rwyList.begin();
132 circuitListItr = circuitList.begin();
133 trafficListItr = trafficList.begin();
137 timeSinceLastDeparture = 9999;
141 FGTower::~FGTower() {
142 if(!separateGround) {
147 void FGTower::Init() {
150 // Pointers to user's position
151 user_lon_node = fgGetNode("/position/longitude-deg", true);
152 user_lat_node = fgGetNode("/position/latitude-deg", true);
153 user_elev_node = fgGetNode("/position/altitude-ft", true);
154 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
156 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
157 // I'll punt the startup issue for now though!!!
160 // Setup the ground control at this airport
162 //cout << "Tower ident = " << ident << '\n';
163 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
164 if(a.ground_freq) { // Ground control
165 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
166 separateGround = true;
168 // Something has gone wrong :-(
169 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
170 ground = new FGGround(ident);
171 separateGround = false;
174 ground->SetDisplay();
176 ground->SetNoDisplay();
180 // Initialise ground anyway to do the shortest path stuff!
181 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
182 ground = new FGGround(ident);
183 separateGround = false;
186 ground->SetDisplay();
188 ground->SetNoDisplay();
192 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
193 // Initialise ground anyway to avoid segfault later
194 ground = new FGGround(ident);
195 separateGround = false;
198 ground->SetDisplay();
200 ground->SetNoDisplay();
204 // Get the airport elevation
205 aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
209 // FIXME - this currently assumes use of the active rwy by the user.
210 rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
212 // Assume the user is started at the threshold ready to take-off
213 TowerPlaneRec* t = new TowerPlaneRec;
214 t->plane.callsign = "Charlie Foxtrot Sierra"; // C-FGFS !!! - fixme - this is a bit hardwired
215 t->plane.type = GA_SINGLE;
216 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
217 t->landingType = AIP_LT_UNKNOWN;
218 t->leg = TAKEOFF_ROLL;
221 t->clearedToTakeOff = true;
222 rwyList.push_back(t);
227 void FGTower::Update(double dt) {
228 //cout << "T" << flush;
229 // Each time step, what do we need to do?
230 // We need to go through the list of outstanding requests and acknowedgements
231 // and process at least one of them.
232 // We need to go through the list of planes under our control and check if
233 // any need to be addressed.
234 // We need to check for planes not under our control coming within our
235 // control area and address if necessary.
237 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
239 // Sort the arriving planes
242 if(ident == "KEMT") {
243 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
247 if(departed != false) {
248 timeSinceLastDeparture += dt;
249 //if(ident == "KEMT")
250 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
253 // Calculate the eta of each plane to the threshold.
254 // For ground traffic this is the fastest they can get there.
255 // For air traffic this is the middle approximation.
256 if(update_count == 1) {
257 doThresholdETACalc();
260 // Order the list of traffic as per expected threshold use and flag any conflicts
261 if(update_count == 2) {
262 //bool conflicts = doThresholdUseOrder();
263 doThresholdUseOrder();
266 // sortConficts() !!!
268 if(update_count == 4) {
272 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
279 if(update_count == 5 && rwyOccupied) {
283 if(update_count == 6) {
284 CheckCircuitList(dt);
287 if(update_count == 7) {
288 CheckApproachList(dt);
291 // TODO - do one plane from the departure list and set departed = false when out of consideration
295 if(!separateGround) {
296 // The display stuff might have to get more clever than this when not separate
297 // since the tower and ground might try communicating simultaneously even though
298 // they're mean't to be the same contoller/frequency!!
300 ground->SetDisplay();
302 ground->SetNoDisplay();
308 // How big should ii get - ie how long should the update cycle interval stretch?
309 if(update_count >= update_count_max) {
313 // Call the base class update for the response time handling.
316 if(ident == "KEMT") {
317 // For AI debugging convienience - may be removed
319 user_pos.setlon(user_lon_node->getDoubleValue());
320 user_pos.setlat(user_lat_node->getDoubleValue());
321 user_pos.setelev(user_elev_node->getDoubleValue());
322 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
323 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
324 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
325 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
329 // Do one plane from the hold list
330 void FGTower::CheckHoldList(double dt) {
332 if(holdList.size()) {
333 //cout << "*holdListItr = " << *holdListItr << endl;
334 if(holdListItr == holdList.end()) {
335 holdListItr = holdList.begin();
337 //cout << "*holdListItr = " << *holdListItr << endl;
338 //Process(*holdListItr);
339 TowerPlaneRec* t = *holdListItr;
340 //cout << "t = " << t << endl;
341 if(t->holdShortReported) {
343 double responseTime = 10.0; // seconds - this should get more sophisticated at some point
344 if(t->clearanceCounter > responseTime) {
346 if(rwyOccupied) { // TODO - ought to add a sanity check that it isn't this plane only on the runway (even though it shouldn't be!!)
347 // Do nothing for now - consider acknowloging hold short eventually
350 string trns = t->plane.callsign;
351 //if(departed plane < some threshold in time away) {
354 t->clearedToLineUp = true;
355 t->planePtr->RegisterTransmission(3); // cleared to line-up
356 t->leg = TAKEOFF_ROLL;
357 //} else if(arriving plane < some threshold away) {
358 } else if(GetTrafficETA(2) < 150.0) {
359 trns += " cleared immediate take-off";
360 if(trafficList.size()) {
361 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
362 trfcItr++; // At the moment the holding plane should be first in trafficList.
363 // Note though that this will break if holding planes aren't put in trafficList in the future.
364 TowerPlaneRec* trfc = *trfcItr;
365 trns += "... traffic is";
366 switch(trfc->plane.type) {
370 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
376 trns += " a King-air";
379 trns += " a Learjet";
382 trns += " a Regional";
391 if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
392 double miles_out = CalcDistOutMiles(trfc);
397 trns += ConvertNumToSpokenDigits((int)miles_out);
398 trns += " mile final";
400 } else if(trfc->opType == CIRCUIT) {
406 trns += " turning final";
412 trns += " turning base";
415 trns += " in circuit";
417 // And to eliminate compiler warnings...
418 case TAKEOFF_ROLL: break;
419 case CLIMBOUT: break;
421 case CROSSWIND: break;
423 case LANDING_ROLL: break;
424 case LEG_UNKNOWN: break;
428 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
429 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
431 t->clearedToTakeOff = true;
432 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
433 t->leg = TAKEOFF_ROLL;
435 timeSinceLastDeparture = 0.0;
437 trns += " cleared for take-off";
438 // TODO - add traffic is... ?
439 t->clearedToTakeOff = true;
440 t->planePtr->RegisterTransmission(4); // cleared to take-off
441 t->leg = TAKEOFF_ROLL;
443 timeSinceLastDeparture = 0.0;
446 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
448 t->holdShortReported = false;
449 t->clearanceCounter = 0;
450 rwyList.push_back(t);
452 holdList.erase(holdListItr);
453 holdListItr = holdList.begin();
456 // Tell him to hold and what position he is.
457 // Not currently sure under which circumstances we do or don't bother transmitting this.
458 string trns = t->plane.callsign;
459 trns += " hold position";
461 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
463 t->holdShortReported = false;
464 t->clearanceCounter = 0;
465 // TODO - add some idea of what traffic is blocking him.
468 t->clearanceCounter += (dt * holdList.size() * update_count_max);
470 } else { // not responding to report, but still need to clear if clear
473 //cout << "departed = " << departed << '\n';
474 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
476 // Do nothing for now - consider acknowloging hold short eventually
477 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
478 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
481 string trns = t->plane.callsign;
482 //cout << "******************* squaggle\n";
483 //cout << "departed = " << departed << '\n';
484 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
485 //if(departed plane < some threshold in time away) {
489 t->clearedToLineUp = true;
490 t->planePtr->RegisterTransmission(3); // cleared to line-up
491 t->leg = TAKEOFF_ROLL;
492 //} else if(arriving plane < some threshold away) {
493 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
495 trns += " cleared immediate take-off";
496 // TODO - add traffic is... ?
497 t->clearedToTakeOff = true;
498 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
499 t->leg = TAKEOFF_ROLL;
501 timeSinceLastDeparture = 0.0;
502 } else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
504 trns += " cleared for take-off";
505 // TODO - add traffic is... ?
506 t->clearedToTakeOff = true;
507 t->planePtr->RegisterTransmission(4); // cleared to take-off
508 t->leg = TAKEOFF_ROLL;
510 timeSinceLastDeparture = 0.0;
515 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
517 rwyList.push_back(t);
519 holdList.erase(holdListItr);
520 holdListItr = holdList.begin();
523 // TODO - rationalise the considerable code duplication above!
529 // do the ciruit list
530 void FGTower::CheckCircuitList(double dt) {
531 // Clear the constraints - we recalculate here.
533 downwind_leg_pos = 0.0;
534 crosswind_leg_pos = 0.0;
536 if(circuitList.size()) { // Do one plane from the circuit
537 if(circuitListItr == circuitList.end()) {
538 circuitListItr = circuitList.begin();
540 TowerPlaneRec* t = *circuitListItr;
542 t->pos.setlon(user_lon_node->getDoubleValue());
543 t->pos.setlat(user_lat_node->getDoubleValue());
544 t->pos.setelev(user_elev_node->getDoubleValue());
546 t->pos = t->planePtr->GetPos(); // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this.
547 t->landingType = t->planePtr->GetLandingOption();
548 //cout << "AI plane landing option is " << t->landingType << '\n';
550 Point3D tortho = ortho.ConvertToLocal(t->pos);
552 // Need to figure out which leg he's on
553 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
554 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
555 //cout << " ho = " << ho << '\n';
556 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
557 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
559 // could be either takeoff, climbout or landing - check orthopos.y
560 //cout << "tortho.y = " << tortho.y() << '\n';
561 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
565 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
566 //cout << "Climbout\n";
567 // If it's the user we may be unsure of his/her intentions.
568 // (Hopefully the AI planes won't try confusing the sim!!!)
569 if(t->opType == TTT_UNKNOWN) {
570 if(tortho.y() > 5000) {
571 // 5 km out from threshold - assume it's a departure
572 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
573 // Since we are unknown operation we should be in depList already.
574 circuitList.erase(circuitListItr);
575 RemoveFromTrafficList(t->plane.callsign);
576 circuitListItr = circuitList.begin();
578 } else if(t->opType == CIRCUIT) {
579 if(tortho.y() > 10000) {
580 // 10 km out - assume the user has abandoned the circuit!!
581 t->opType = OUTBOUND;
582 depList.push_back(t);
583 circuitList.erase(circuitListItr);
584 circuitListItr = circuitList.begin();
588 } else if(abs(ho) < 60) {
590 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
591 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
598 } else if(abs(ho) < 120) {
600 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
601 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
603 //cout << "Crosswind\n";
608 } else if(abs(ho) < 150) {
610 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
611 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
616 // Probably safe now to assume the user is flying a circuit
623 //cout << "Downwind\n";
625 if(t->leg == FINAL) {
626 if(OnActiveRunway(t->pos)) {
627 t->leg = LANDING_ROLL;
631 t->leg = t->planePtr->GetLeg();
634 // Set the constraints IF this is the first plane in the circuit
635 // TODO - at the moment we're constraining plane 2 based on plane 1 - this won't (or might not) work for 3 planes in the circuit!!
636 if(circuitListItr == circuitList.begin()) {
639 // Base leg must be at least as far out as the plane is - actually possibly not necessary for separation, but we'll use that for now.
640 base_leg_pos = tortho.y();
641 //cout << "base_leg_pos = " << base_leg_pos << '\n';
644 // Fall through to base
646 base_leg_pos = tortho.y();
647 //cout << "base_leg_pos = " << base_leg_pos << '\n';
650 // Fall through to downwind
652 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
653 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
654 //cout << "base_leg_pos = " << base_leg_pos;
655 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
656 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
659 // Fall through to crosswind
661 crosswind_leg_pos = tortho.y();
662 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
665 // Fall through to climbout
667 // Only use current by constraint as largest
668 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
669 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
682 if(t->leg == FINAL) {
683 if(t->landingType == FULL_STOP) t->opType = INBOUND;
684 } else if(t->leg == LANDING_ROLL) {
685 rwyList.push_front(t);
686 RemoveFromTrafficList(t->plane.callsign);
688 t->opType = TTT_UNKNOWN;
689 } // TODO - allow the user to specify opType via ATC menu
690 circuitListItr = circuitList.erase(circuitListItr);
691 if(circuitListItr == circuitList.end() ) {
692 circuitListItr = circuitList.begin();
699 // Do the runway list - we'll do the whole runway list since it's important and there'll never be many planes on the rwy at once!!
700 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
701 // (However, at the moment there should only be one airplane on the rwy at once, until we
702 // start allowing planes to line up whilst previous arrival clears the rwy.)
703 void FGTower::CheckRunwayList(double dt) {
705 if(!rwyList.size()) {
708 rwyListItr = rwyList.begin();
709 TowerPlaneRec* t = *rwyListItr;
711 t->pos.setlon(user_lon_node->getDoubleValue());
712 t->pos.setlat(user_lat_node->getDoubleValue());
713 t->pos.setelev(user_elev_node->getDoubleValue());
715 t->pos = t->planePtr->GetPos(); // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this.
717 bool on_rwy = OnActiveRunway(t->pos);
719 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
722 // TODO - tell it to taxi / contact ground / don't delete it etc!
723 } else if(t->opType == OUTBOUND) {
724 depList.push_back(t);
727 timeSinceLastDeparture = 0.0;
728 } else if(t->opType == CIRCUIT) {
729 circuitList.push_back(t);
733 timeSinceLastDeparture = 0.0;
734 } else if(t->opType == TTT_UNKNOWN) {
735 depList.push_back(t);
736 circuitList.push_back(t);
740 timeSinceLastDeparture = 0.0; // TODO - we need to take into account that the user might taxi-in when flagged opType UNKNOWN - check speed/altitude etc to make decision as to what user is up to.
742 // HELP - we shouldn't ever get here!!!
749 // Do one plane from the approach list
750 void FGTower::CheckApproachList(double dt) {
752 if(appListItr == appList.end()) {
753 appListItr = appList.begin();
755 TowerPlaneRec* t = *appListItr;
756 //cout << "t = " << t << endl;
758 t->pos.setlon(user_lon_node->getDoubleValue());
759 t->pos.setlat(user_lat_node->getDoubleValue());
760 t->pos.setelev(user_elev_node->getDoubleValue());
762 // TODO - set/update the position if it's an AI plane
764 if(t->nextOnRwy && !(t->clearedToLand)) {
765 // check distance away and whether runway occupied
766 // and schedule transmission if necessary
772 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
773 // plus the constraint position as a rwy orientated orthopos (meters)
774 bool FGTower::GetCrosswindConstraint(double& cpos) {
775 if(crosswind_leg_pos != 0.0) {
776 cpos = crosswind_leg_pos;
783 bool FGTower::GetDownwindConstraint(double& dpos) {
784 if(downwind_leg_pos != 0.0) {
785 dpos = downwind_leg_pos;
792 bool FGTower::GetBaseConstraint(double& bpos) {
793 if(base_leg_pos != 0.0) {
803 // Figure out which runways are active.
804 // For now we'll just be simple and do one active runway - eventually this will get much more complex
805 // This is a private function - public interface to the results of this is through GetActiveRunway
806 void FGTower::DoRwyDetails() {
807 //cout << "GetRwyDetails called" << endl;
809 // Based on the airport-id and wind get the active runway
812 double hdg = wind_from_hdg->getDoubleValue();
813 double speed = wind_speed_knots->getDoubleValue();
814 hdg = (speed == 0.0 ? 270.0 : hdg);
815 //cout << "Heading = " << hdg << '\n';
818 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
820 activeRwy = runway.rwy_no;
821 rwy.rwyID = runway.rwy_no;
822 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
824 // Get the threshold position
825 double other_way = runway.heading - 180.0;
826 while(other_way <= 0.0) {
829 // move to the +l end/center of the runway
830 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
831 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
832 Point3D ref = origin;
833 double tshlon, tshlat, tshr;
834 double tolon, tolat, tor;
835 rwy.length = runway.length * SG_FEET_TO_METER;
836 rwy.width = runway.width * SG_FEET_TO_METER;
837 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
838 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
839 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
840 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
841 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
842 // now copy what we need out of runway into rwy
843 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
844 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
845 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
846 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
847 rwy.hdg = runway.heading;
848 // Set the projection for the local area based on this active runway
849 ortho.Init(rwy.threshold_pos, rwy.hdg);
850 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
851 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
853 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
859 // Figure out if a given position lies on the active runway
860 // Might have to change when we consider more than one active rwy.
861 bool FGTower::OnActiveRunway(Point3D pt) {
862 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
863 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
864 Point3D xyp = ortho.ConvertToLocal(pt);
866 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
867 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
869 double rlen = rwy.length/2.0 + 5.0;
870 double rwidth = rwy.width/2.0;
871 double ldiff = fabs(xyp.y() - xyc.y());
872 double wdiff = fabs(xyp.x() - xyc.x());
874 return((ldiff < rlen) && (wdiff < rwidth));
878 // Figure out if a given position lies on any runway or not
879 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
880 bool FGTower::OnAnyRunway(Point3D pt) {
882 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
886 // Based on the airport-id, go through all the runways and check for a point in them
888 // TODO - do we actually need to search for the airport - surely we already know our ident and
889 // can just search runways of our airport???
890 //cout << "Airport ident is " << ad.ident << '\n';
892 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
894 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
897 while(runway.id == ad.ident) {
898 on = OnRunway(pt, runway);
899 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
901 globals->get_runways()->next(&runway);
907 // Returns true if successful
908 bool FGTower::RemoveFromTrafficList(string id) {
909 tower_plane_rec_list_iterator twrItr;
910 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
911 TowerPlaneRec* tpr = *twrItr;
912 if(tpr->plane.callsign == id) {
913 trafficList.erase(twrItr);
917 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
922 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
923 // and set nextOnRwy if so.
924 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
925 // For planes holding they are put in the first position with time to go, and the return value is
926 // true if in the first position (nextOnRwy) and false otherwise.
927 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
928 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
929 //cout << "ADD: " << trafficList.size();
930 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
931 double separation_time = 90.0; // seconds - this is currently a guess for light plane separation, and includes a few seconds for a holding plane to taxi onto the rwy.
932 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
933 bool conflict = false;
934 double lastETA = 0.0;
935 bool firstTime = true;
936 // FIXME - make this more robust for different plane types eg. light following heavy.
937 tower_plane_rec_list_iterator twrItr;
938 //twrItr = trafficList.begin();
940 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
941 //if(twrItr == trafficList.end()) {
943 // trafficList.push_back(t);
944 // return(holding ? firstTime : conflict);
946 TowerPlaneRec* tpr = *twrItr;
948 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
949 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
950 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
951 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
952 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
953 // and if not needs time to clear the rwy anyway.
954 if(tpr->eta - lastETA > slot_time) {
955 t->nextOnRwy = firstTime;
956 trafficList.insert(twrItr, t);
957 //cout << "\tH\t" << trafficList.size() << '\n';
962 if(t->eta < tpr->eta) {
963 // Ugg - this one's tricky.
964 // It depends on what the two planes are doing and whether there's a conflict what we do.
965 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
967 tpr->nextOnRwy = false;
970 trafficList.insert(twrItr, t);
971 } else { // Ooops - this ones tricky - we have a potential conflict!
973 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
975 tpr->nextOnRwy = false;
978 trafficList.insert(twrItr, t);
980 //cout << "\tC\t" << trafficList.size() << '\n';
987 // If we get here we must be at the end of the list, or maybe the list is empty.
988 if(!trafficList.size()) {
990 // conflict and firstTime should be false and true respectively in this case anyway.
992 trafficList.push_back(t);
993 //cout << "\tE\t" << trafficList.size() << '\n';
994 return(holding ? firstTime : conflict);
998 // Calculate the eta of a plane to the threshold.
999 // For ground traffic this is the fastest they can get there.
1000 // For air traffic this is the middle approximation.
1001 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1002 // For now we'll be very crude and hardwire expected speeds to C172-like values
1003 // The speeds below are specified in knots IAS and then converted to m/s
1004 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1005 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1006 double final_ias = 70.0 * 0.514444; // Speed during final approach
1009 // cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1010 // cout << (tpr->isUser ? "USER\n" : "AI\n");
1013 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1014 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1016 Point3D op = ortho.ConvertToLocal(tpr->pos);
1018 // cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1019 // cout << "opType is " << tpr->opType << '\n';
1021 double dist_out_m = op.y();
1022 double dist_across_m = fabs(op.x()); // FIXME = the fabs is a hack to cope with the fact that we don't know the circuit direction yet
1023 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1025 if(tpr->opType == STRAIGHT_IN) {
1026 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1027 if(dist_to_go_m < 1000) {
1028 tpr->eta = dist_to_go_m / final_ias;
1030 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1032 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1033 // It's complicated - depends on if base leg is delayed or not
1035 // cout << "Leg = " << tpr->leg << '\n';
1037 if(tpr->leg == LANDING_ROLL) {
1039 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1040 tpr->eta = fabs(dist_out_m) / final_ias;
1041 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1042 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1044 // Need to calculate where base leg is likely to be
1045 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1046 // TODO - as a matter of design - AILocalTraffic should get the nominal no-traffic base turn distance from Tower, since in real life the published pattern might differ from airport to airport
1047 double nominal_base_dist_out_m = -1000;
1048 double current_base_dist_out_m;
1049 if(!GetBaseConstraint(current_base_dist_out_m)) {
1050 current_base_dist_out_m = nominal_base_dist_out_m;
1052 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1053 double current_dist_across_m;
1054 if(!GetDownwindConstraint(current_dist_across_m)) {
1055 current_dist_across_m = nominal_dist_across_m;
1057 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1058 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1059 //if(printout) cout << "a = " << tpr->eta << '\n';
1060 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1061 tpr->eta += dist_across_m / circuit_ias;
1062 //if(printout) cout << "b = " << tpr->eta << '\n';
1063 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1064 //if(printout) cout << "c = " << tpr->eta << '\n';
1065 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1066 if(dist_across_m > nominal_dist_across_m) {
1067 tpr->eta += dist_across_m / circuit_ias;
1069 tpr->eta += nominal_dist_across_m / circuit_ias;
1071 // should we use the dist across of the previous plane if there is previous still on downwind?
1072 //if(printout) cout << "bb = " << tpr->eta << '\n';
1073 if(dist_out_m > nominal_cross_dist_out_m) {
1074 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1076 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1078 //if(printout) cout << "cc = " << tpr->eta << '\n';
1079 if(nominal_dist_across_m > dist_across_m) {
1080 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1084 //if(printout) cout << "dd = " << tpr->eta << '\n';
1086 // We've only just started - why not use a generic estimate?
1091 // cout << "ETA = " << tpr->eta << '\n';
1099 // Calculate the distance of a plane to the threshold in meters
1100 // TODO - Modify to calculate flying distance of a plane in the circuit
1101 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1102 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1106 // Calculate the distance of a plane to the threshold in miles
1107 // TODO - Modify to calculate flying distance of a plane in the circuit
1108 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1109 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1113 // Iterate through all the lists and call CalcETA for all the planes.
1114 void FGTower::doThresholdETACalc() {
1115 tower_plane_rec_list_iterator twrItr;
1116 // Do the approach list first
1117 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1118 TowerPlaneRec* tpr = *twrItr;
1121 // Then the circuit list
1122 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1123 TowerPlaneRec* tpr = *twrItr;
1129 // Check that the planes in traffic list are correctly ordered,
1130 // that the nearest (timewise) is flagged next on rwy, and return
1131 // true if any threshold use conflicts are detected, false otherwise.
1132 bool FGTower::doThresholdUseOrder() {
1133 bool conflict = false;
1135 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1136 // Here's the rather simplistic assumptions we're using:
1137 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1138 // In order of priority for runway use:
1139 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1140 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1141 // and holding planes until a space.
1142 // When calculating if a holding plane can use the runway, time clearance from last departure
1143 // as well as time clearance to next arrival must be considered.
1145 trafficList.clear();
1147 tower_plane_rec_list_iterator twrItr;
1148 // Do the approach list first
1149 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1150 TowerPlaneRec* tpr = *twrItr;
1151 conflict = AddToTrafficList(tpr);
1153 // Then the circuit list
1154 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1155 TowerPlaneRec* tpr = *twrItr;
1156 conflict = AddToTrafficList(tpr);
1158 // And finally the hold list
1159 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1160 TowerPlaneRec* tpr = *twrItr;
1161 AddToTrafficList(tpr, true);
1165 //if(ident == "KEMT") {
1166 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1167 TowerPlaneRec* tpr = *twrItr;
1168 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1177 void FGTower::doCommunication() {
1181 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1182 // i.e. list_pos = 1 implies next to use runway.
1183 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1184 if(trafficList.size() < list_pos) {
1188 tower_plane_rec_list_iterator twrItr;
1189 twrItr = trafficList.begin();
1190 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1191 TowerPlaneRec* tpr = *twrItr;
1192 CalcETA(tpr, printout);
1193 //cout << "ETA returned = " << tpr->eta << '\n';
1198 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1199 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1200 TowerPlaneRec* t = new TowerPlaneRec;
1202 t->planePtr = requestee;
1203 t->holdShortReported = true;
1204 t->clearanceCounter = 0;
1205 t->clearedToLineUp = false;
1206 t->clearedToTakeOff = false;
1207 t->opType = operation;
1209 //cout << "Hold Short reported by " << plane.callsign << '\n';
1211 bool next = AddToTrafficList(t, true);
1214 //cout << "Next to take off - respond with clearance\n";
1215 double teta = GetTrafficETA(2);
1217 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1218 //cout << "Reducing response time to request due imminent traffic\n";
1221 //cout << "Not next to take off - respond with hold\n";
1224 //cout << "t = " << t << '\n';
1226 holdList.push_back(t);
1229 void FGTower::RequestLandingClearance(string ID) {
1230 //cout << "Request Landing Clearance called...\n";
1232 // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1233 // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1235 TowerPlaneRec* t = new TowerPlaneRec;
1237 t->clearedToLand = false;
1238 t->pos.setlon(user_lon_node->getDoubleValue());
1239 t->pos.setlat(user_lat_node->getDoubleValue());
1240 t->pos.setelev(user_elev_node->getDoubleValue());
1243 // Calculate where the user is in relation to the active runway and it's circuit
1244 // and set the op-type as appropriate.
1246 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1247 t->opType = STRAIGHT_IN;
1249 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1250 t->plane.callsign = ID;
1252 appList.push_back(t); // Not necessarily permanent
1253 AddToTrafficList(t);
1256 void FGTower::RequestDepartureClearance(string ID) {
1257 //cout << "Request Departure Clearance called...\n";
1259 //void FGTower::ReportFinal(string ID);
1260 //void FGTower::ReportLongFinal(string ID);
1261 //void FGTower::ReportOuterMarker(string ID);
1262 //void FGTower::ReportMiddleMarker(string ID);
1263 //void FGTower::ReportInnerMarker(string ID);
1264 //void FGTower::ReportGoingAround(string ID);
1265 void FGTower::ReportRunwayVacated(string ID) {
1266 //cout << "Report Runway Vacated Called...\n";
1269 void FGTower::ReportDownwind(string ID) {
1270 // Tell the plane reporting what number she is in the circuit
1273 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1275 case(CIRCUIT): return(os << "CIRCUIT");
1276 case(INBOUND): return(os << "INBOUND");
1277 case(OUTBOUND): return(os << "OUTBOUND");
1278 case(TTT_UNKNOWN): return(os << "UNKNOWN");
1279 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
1281 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");