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.
26 # include <strings.h> // bcopy()
28 # include <string.h> // MSVC doesn't have strings.h
31 #include <Main/globals.hxx>
32 #include <Airports/runways.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/debug/logstream.hxx>
37 #include "ATCdisplay.hxx"
39 #include "ATCutils.hxx"
40 #include "ATCDialog.hxx"
41 #include "commlist.hxx"
42 #include "AILocalTraffic.hxx"
48 TowerPlaneRec::TowerPlaneRec() :
51 clearedToLineUp(false),
52 clearedToTakeOff(false),
53 holdShortReported(false),
54 downwindReported(false),
55 longFinalReported(false),
56 longFinalAcknowledged(false),
58 finalAcknowledged(false),
59 rwyVacatedReported(false),
60 rwyVacatedAcknowledged(false),
61 goAroundReported(false),
62 instructedToGoAround(false),
65 vfrArrivalReported(false),
66 vfrArrivalAcknowledged(false),
69 landingType(AIP_LT_UNKNOWN),
72 plane.callsign = "UNKNOWN";
75 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
78 clearedToLineUp(false),
79 clearedToTakeOff(false),
80 holdShortReported(false),
81 downwindReported(false),
82 longFinalReported(false),
83 longFinalAcknowledged(false),
85 finalAcknowledged(false),
86 rwyVacatedReported(false),
87 rwyVacatedAcknowledged(false),
88 goAroundReported(false),
89 instructedToGoAround(false),
92 vfrArrivalReported(false),
93 vfrArrivalAcknowledged(false),
96 landingType(AIP_LT_UNKNOWN),
102 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
104 clearedToLand(false),
105 clearedToLineUp(false),
106 clearedToTakeOff(false),
107 holdShortReported(false),
108 downwindReported(false),
109 longFinalReported(false),
110 longFinalAcknowledged(false),
111 finalReported(false),
112 finalAcknowledged(false),
113 rwyVacatedReported(false),
114 rwyVacatedAcknowledged(false),
115 goAroundReported(false),
116 instructedToGoAround(false),
119 vfrArrivalReported(false),
120 vfrArrivalAcknowledged(false),
123 landingType(AIP_LT_UNKNOWN),
126 plane.callsign = "UNKNOWN";
130 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
132 clearedToLand(false),
133 clearedToLineUp(false),
134 clearedToTakeOff(false),
135 holdShortReported(false),
136 downwindReported(false),
137 longFinalReported(false),
138 longFinalAcknowledged(false),
139 finalReported(false),
140 finalAcknowledged(false),
141 rwyVacatedReported(false),
142 rwyVacatedAcknowledged(false),
143 goAroundReported(false),
144 instructedToGoAround(false),
147 vfrArrivalReported(false),
148 vfrArrivalAcknowledged(false),
151 landingType(AIP_LT_UNKNOWN),
161 /*******************************************
164 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in. (MAJOR)
166 Use track instead of heading to determine what leg of the circuit the user is flying. (MINOR)
168 Use altitude as well as position to try to determine if the user has left the circuit. (MEDIUM - other issues as well).
170 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and
171 will break when planes start queueing. (CRITICAL)
173 Report-Runway-Vacated is left as only user ATC option following a go-around. (MAJOR)
175 Report-Downwind is not added as ATC option when user takes off to fly a circuit. (MAJOR)
177 eta of USER can be calculated very wrongly in circuit if flying straight out and turn4 etc are with +ve ortho y.
178 This can then screw up circuit ordering for other planes (MEDIUM)
180 USER leaving circuit needs to be more robustly considered when intentions unknown
181 Currently only considered during climbout and breaks when user turns (MEDIUM).
183 GetPos() of the AI planes is called erratically - either too much or not enough. (MINOR)
185 GO-AROUND is instructed very late at < 12s to landing - possibly make more dependent on chance of rwy clearing before landing (FEATURE)
187 Need to make clear when TowerPlaneRecs do or don't get deleted in RemoveFromCircuitList etc. (MINOR until I misuse it - then CRITICAL!)
189 FGTower::RemoveAllUserDialogOptions() really ought to be replaced by an ATCDialog::clear_entries() function. (MINOR - efficiency).
190 *******************************************/
193 ATCmgr = globals->get_ATC_mgr();
197 // Init the property nodes - TODO - need to make sure we're getting surface winds.
198 wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
199 wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
202 update_count_max = 15;
204 holdListItr = holdList.begin();
206 appListItr = appList.begin();
207 depListItr = depList.begin();
208 rwyListItr = rwyList.begin();
209 circuitListItr = circuitList.begin();
210 trafficListItr = trafficList.begin();
212 vacatedListItr = vacatedList.begin();
216 timeSinceLastDeparture = 9999;
219 nominal_downwind_leg_pos = 1000.0;
220 nominal_base_leg_pos = -1000.0;
221 // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
223 _departureControlled = false;
226 FGTower::~FGTower() {
227 if(!separateGround) {
232 void FGTower::Init() {
233 //cout << "Initialising tower " << ident << '\n';
235 // Pointers to user's position
236 user_lon_node = fgGetNode("/position/longitude-deg", true);
237 user_lat_node = fgGetNode("/position/latitude-deg", true);
238 user_elev_node = fgGetNode("/position/altitude-ft", true);
239 user_hdg_node = fgGetNode("/orientation/heading-deg", true);
241 // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
242 // I'll punt the startup issue for now though!!!
245 // Setup the ground control at this airport
247 //cout << "Tower ident = " << ident << '\n';
248 if(ATCmgr->GetAirportATCDetails(ident, &a)) {
249 if(a.ground_freq) { // Ground control
250 ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
251 separateGround = true;
253 // Something has gone wrong :-(
254 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
255 ground = new FGGround(ident);
256 separateGround = false;
259 ground->SetDisplay();
261 ground->SetNoDisplay();
265 // Initialise ground anyway to do the shortest path stuff!
266 // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
267 ground = new FGGround(ident);
268 separateGround = false;
271 ground->SetDisplay();
273 ground->SetNoDisplay();
277 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
278 // Initialise ground anyway to avoid segfault later
279 ground = new FGGround(ident);
280 separateGround = false;
283 ground->SetDisplay();
285 ground->SetNoDisplay();
289 // TODO - attempt to get a departure control pointer to see if we need to hand off departing traffic to departure.
291 // Get the airport elevation
292 aptElev = dclGetAirportElev(ident.c_str());
294 // TODO - this function only assumes one active rwy.
297 // TODO - this currently assumes only one active runway.
298 rwyOccupied = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
300 //cout << "User found on active runway\n";
301 // Assume the user is started at the threshold ready to take-off
302 TowerPlaneRec* t = new TowerPlaneRec;
303 t->plane.callsign = fgGetString("/sim/user/callsign");
304 t->plane.type = GA_SINGLE; // FIXME - hardwired!!
305 t->opType = TTT_UNKNOWN; // We don't know if the user wants to do circuits or a departure...
306 t->landingType = AIP_LT_UNKNOWN;
307 t->leg = TAKEOFF_ROLL;
310 t->clearedToTakeOff = true;
311 rwyList.push_back(t);
314 //cout << "User not on active runway\n";
315 // For now assume that this means the user is not at the airport and is in the air.
316 // TODO FIXME - this will break when user starts on apron, at hold short, etc.
317 if(!OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0))) {
318 //cout << ident << " ADD 0\n";
319 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with the ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
324 void FGTower::Update(double dt) {
325 //cout << "T" << endl;
326 // Each time step, what do we need to do?
327 // We need to go through the list of outstanding requests and acknowedgements
328 // and process at least one of them.
329 // We need to go through the list of planes under our control and check if
330 // any need to be addressed.
331 // We need to check for planes not under our control coming within our
332 // control area and address if necessary.
334 // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
336 // Sort the arriving planes
339 if(ident == "KEMT") {
340 cout << update_count << "\ttL: " << trafficList.size() << " cL: " << circuitList.size() << " hL: " << holdList.size() << " aL: " << appList.size() << '\n';
343 //if(ident == "EGNX") cout << display << '\n';
345 if(departed != false) {
346 timeSinceLastDeparture += dt;
347 //if(ident == "KEMT")
348 // cout << " dt = " << dt << " timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
351 //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n';
353 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
356 responseReqd = false;
359 // Calculate the eta of each plane to the threshold.
360 // For ground traffic this is the fastest they can get there.
361 // For air traffic this is the middle approximation.
362 if(update_count == 1) {
363 doThresholdETACalc();
366 // Order the list of traffic as per expected threshold use and flag any conflicts
367 if(update_count == 2) {
368 //bool conflicts = doThresholdUseOrder();
369 doThresholdUseOrder();
372 // sortConficts() !!!
374 if(update_count == 4) {
378 // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
385 if(update_count == 5 && rwyOccupied) {
389 if(update_count == 6) {
390 CheckCircuitList(dt);
393 if(update_count == 7) {
394 CheckApproachList(dt);
397 if(update_count == 8) {
398 CheckDepartureList(dt);
401 // TODO - do one plane from the departure list and set departed = false when out of consideration
405 if(!separateGround) {
406 // The display stuff might have to get more clever than this when not separate
407 // since the tower and ground might try communicating simultaneously even though
408 // they're mean't to be the same contoller/frequency!!
409 // We could also get rid of this by overloading FGATC's Set(No)Display() functions.
411 ground->SetDisplay();
413 ground->SetNoDisplay();
419 // How big should ii get - ie how long should the update cycle interval stretch?
420 if(update_count >= update_count_max) {
424 // Call the base class update for the response time handling.
428 if(ident == "KEMT") {
429 // For AI debugging convienience - may be removed
431 user_pos.setlon(user_lon_node->getDoubleValue());
432 user_pos.setlat(user_lat_node->getDoubleValue());
433 user_pos.setelev(user_elev_node->getDoubleValue());
434 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
435 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
436 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
437 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
441 //cout << "Done T" << endl;
444 void FGTower::ReceiveUserCallback(int code) {
445 if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
446 //cout << "User requested departure\n";
447 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
448 VFRArrivalContact("USER");
449 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
450 VFRArrivalContact("USER", FULL_STOP);
451 } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
452 VFRArrivalContact("USER", TOUCH_AND_GO);
453 } else if(code == (int)USER_REPORT_DOWNWIND) {
454 ReportDownwind("USER");
455 } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
456 // For now we'll just call report final instead of report long final to avoid having to alter the response code
458 } else if(code == (int)USER_REPORT_RWY_VACATED) {
459 ReportRunwayVacated("USER");
460 } else if(code == (int)USER_REPORT_GOING_AROUND) {
461 ReportGoingAround("USER");
465 // **************** RESPONSE FUNCTIONS ****************
467 void FGTower::Respond() {
468 //cout << "\nEntering Respond, responseID = " << responseID << endl;
469 TowerPlaneRec* t = FindPlane(responseID);
472 if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
473 //cout << "Tower " << ident << " is responding to VFR arrival reported...\n";
474 // Testing - hardwire straight in for now
475 string trns = t->plane.callsign;
479 // Should we clear staight in or for downwind entry?
480 // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
481 // Later on we might check the actual heading and direct some of those to enter on downwind or base.
482 Point3D op = ortho.ConvertToLocal(t->pos);
484 trns += " Report three mile straight-in runway ";
485 t->opType = STRAIGHT_IN;
487 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
489 t->planePtr->RegisterTransmission(14);
492 // For now we'll just request reporting downwind.
493 // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
494 // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
496 //cout << "Responding, rwy.patterDirection is " << rwy.patternDirection << '\n';
497 trns += ((rwy.patternDirection == 1) ? "right " : "left ");
498 trns += "downwind runway ";
500 // leave it in the app list until it gets into pattern though.
502 current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
504 t->planePtr->RegisterTransmission(15);
507 trns += ConvertRwyNumToSpokenString(activeRwy);
509 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
511 //cout << "Not displaying, trns was " << trns << '\n';
513 t->vfrArrivalAcknowledged = true;
514 } else if(t->downwindReported) {
515 //cout << "Tower " << ident << " is responding to downwind reported...\n";
516 ProcessDownwindReport(t);
517 t->downwindReported = false;
518 } else if(t->holdShortReported) {
519 //cout << "Tower " << ident << " is reponding to holdShortReported...\n";
521 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!!)
522 // Do nothing for now - consider acknowloging hold short eventually
524 ClearHoldingPlane(t);
525 t->leg = TAKEOFF_ROLL;
526 rwyList.push_back(t);
528 // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
529 // FIXME TODO - FIX THIS!!!
530 if(holdList.size()) {
531 if(holdListItr == holdList.end()) {
532 holdListItr = holdList.begin();
534 holdList.erase(holdListItr);
535 holdListItr = holdList.begin();
539 // Tell him to hold and what position he is.
540 // Not currently sure under which circumstances we do or don't bother transmitting this.
541 string trns = t->plane.callsign;
542 trns += " hold position";
544 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
546 // TODO - add some idea of what traffic is blocking him.
548 t->holdShortReported = false;
549 } else if(t->finalReported && !(t->finalAcknowledged)) {
550 //cout << "Tower " << ident << " is responding to finalReported...\n";
552 string trns = t->plane.callsign;
553 //cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
554 //cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
555 if(t->nextOnRwy && !rwyOccupied && !(t->instructedToGoAround)) {
556 if(t->landingType == FULL_STOP) {
557 trns += " cleared to land ";
559 trns += " cleared for the option ";
562 t->clearedToLand = true;
563 // Maybe remove report downwind from menu here as well incase user didn't bother to?
565 //cout << "ADD VACATED B\n";
566 // Put going around at the top (and hence default) since that'll be more desperate,
567 // or put rwy vacated at the top since that'll be more common?
568 current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
569 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
571 t->planePtr->RegisterTransmission(7);
573 } else if(t->eta < 20) {
574 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
575 // runway doesn't clear so no point in calling "continue approach".
578 trns += " continue approach";
579 t->clearedToLand = false;
581 if(_display && disp) {
582 globals->get_ATC_display()->RegisterSingleMessage(trns);
584 t->finalAcknowledged = true;
585 } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
586 ProcessRunwayVacatedReport(t);
587 t->rwyVacatedAcknowledged = true;
590 //freqClear = true; // FIXME - set this to come true after enough time to render the message
591 _releaseCounter = 0.0;
593 _runReleaseCounter = true;
594 //cout << "Done Respond\n" << endl;
597 void FGTower::ProcessDownwindReport(TowerPlaneRec* t) {
599 int a = 0; // Count of preceding planes on approach
600 bool cf = false; // conflicting traffic on final
601 bool cc = false; // preceding traffic in circuit
603 for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
604 if((*twrItr)->plane.callsign == responseID) break;
608 if(i > 1) { cc = true; }
609 doThresholdETACalc();
611 for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
612 if((*twrItr)->eta < (t->eta + 45)) {
616 // This should set the flagged plane to be the last conflicting one, and hence the one to follow.
617 // It ignores the fact that we might have problems slotting into the approach traffic behind it -
618 // eventually we'll need some fancy algorithms for that!
621 string trns = t->plane.callsign;
623 trns += ConvertNumToSpokenDigits(i + a);
624 // This assumes that the number spoken is landing position, not circuit position, since some of the traffic might be on straight-in final.
627 if((i == 1) && (!rwyList.size()) && (t->nextOnRwy) && (!cf)) { // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below.
628 trns += "Cleared to land"; // TODO - clear for the option if appropriate
629 t->clearedToLand = true;
630 if(!t->isUser) t->planePtr->RegisterTransmission(7);
631 } else if((i+a) > 1) {
632 //First set tt to point to the correct preceding plane - final or circuit
634 tt = (tf->eta < tc->eta ? tf : tc);
640 // We should never get here!
641 SG_LOG(SG_ATC, SG_ALERT, "ALERT - Logic error in FGTower::ProcessDownwindReport");
643 trns += "Follow the ";
644 string s = tt->plane.callsign;
648 if((tt->opType) == CIRCUIT) {
649 if(tt->planePtr->GetLeg() == FINAL) {
651 } else if(tt->planePtr->GetLeg() == TURN4) {
652 trns += " turning final";
653 } else if(tt->planePtr->GetLeg() == BASE) {
655 } else if(tt->planePtr->GetLeg() == TURN3) {
656 trns += " turning base";
659 double miles_out = CalcDistOutMiles(tt);
661 trns += " on short final";
664 trns += ConvertNumToSpokenDigits((int)miles_out);
665 trns += " mile final";
670 globals->get_ATC_display()->RegisterSingleMessage(trns);
673 if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
674 //cout << "ADD VACATED A\n";
675 // Put going around at the top (and hence default) since that'll be more desperate,
676 // or put rwy vacated at the top since that'll be more common?
677 //cout << "ident = " << ident << ", adding go-around option\n";
678 current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
679 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
683 void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) {
684 //cout << "Processing rwy vacated...\n";
685 current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
686 string trns = t->plane.callsign;
688 trns += " Contact ground on ";
689 double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0;
691 sprintf(buf, "%.2f", f);
694 if(!t->isUser) t->planePtr->RegisterTransmission(5);
697 trns += " cleared for taxi to the GA parking";
698 if(!t->isUser) t->planePtr->RegisterTransmission(6); // TODO - this is a mega-hack!!
700 //cout << "trns = " << trns << '\n';
702 globals->get_ATC_display()->RegisterSingleMessage(trns);
704 // Maybe we should check that the plane really *has* vacated the runway!
707 // *********** END RESPONSE FUNCTIONS *****************
709 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land -
710 // this should be done prior to calling this function.
711 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
712 //cout << "Entering ClearHoldingPlane..." << endl;
714 string trns = t->plane.callsign;
715 //if(departed plane < some threshold in time away) {
717 //if(timeSinceLastDeparture <= 60.0 && departed == true) {
719 t->clearedToLineUp = true;
720 t->planePtr->RegisterTransmission(3); // cleared to line-up
721 //} else if(arriving plane < some threshold away) {
722 } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time
723 trns += " cleared immediate take-off";
724 if(trafficList.size()) {
725 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
726 trfcItr++; // At the moment the holding plane should be first in trafficList.
727 // Note though that this will break if holding planes aren't put in trafficList in the future.
728 TowerPlaneRec* trfc = *trfcItr;
729 trns += "... traffic is";
730 switch(trfc->plane.type) {
734 trns += " a Cessna"; // TODO - add ability to specify actual plane type somewhere
740 trns += " a King-air";
743 trns += " a Learjet";
746 trns += " a Regional";
755 //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
756 if(trfc->opType == STRAIGHT_IN) {
757 double miles_out = CalcDistOutMiles(trfc);
762 trns += ConvertNumToSpokenDigits((int)miles_out);
763 trns += " mile final";
765 } else if(trfc->opType == CIRCUIT) {
766 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
772 trns += " turning final";
778 trns += " turning base";
781 trns += " in circuit"; // At the moment the user plane is generally flagged as unknown opType when downwind incase its a downwind departure which means we won't get here.
783 // And to eliminate compiler warnings...
784 case TAKEOFF_ROLL: break;
785 case CLIMBOUT: break;
787 case CROSSWIND: break;
789 case LANDING_ROLL: break;
790 case LEG_UNKNOWN: break;
794 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
795 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
797 t->clearedToTakeOff = true;
798 t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off
800 timeSinceLastDeparture = 0.0;
802 //} else if(timeSinceLastDeparture > 60.0 || departed == false) { // Hack - test for timeSinceLastDeparture should be in lineup block eventually
803 trns += " cleared for take-off";
804 // TODO - add traffic is... ?
805 t->clearedToTakeOff = true;
806 t->planePtr->RegisterTransmission(4); // cleared to take-off
808 timeSinceLastDeparture = 0.0;
811 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
813 //cout << "Done ClearHoldingPlane " << endl;
817 // ***************************************************************************************
818 // ********** Functions to periodically check what the various traffic is doing **********
820 // Do one plane from the hold list
821 void FGTower::CheckHoldList(double dt) {
822 //cout << "Entering CheckHoldList..." << endl;
823 if(holdList.size()) {
824 //cout << "*holdListItr = " << *holdListItr << endl;
825 if(holdListItr == holdList.end()) {
826 holdListItr = holdList.begin();
828 //cout << "*holdListItr = " << *holdListItr << endl;
829 //Process(*holdListItr);
830 TowerPlaneRec* t = *holdListItr;
831 //cout << "t = " << t << endl;
832 if(t->holdShortReported) {
833 // NO-OP - leave it to the response handler.
834 } else { // not responding to report, but still need to clear if clear
836 //cout << "departed = " << departed << '\n';
837 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
840 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
841 // Do nothing - this is a bit of a hack - should maybe do line up be ready here
843 ClearHoldingPlane(t);
844 t->leg = TAKEOFF_ROLL;
845 rwyList.push_back(t);
847 holdList.erase(holdListItr);
848 holdListItr = holdList.begin();
851 // TODO - rationalise the considerable code duplication above!
855 //cout << "Done CheckHoldList" << endl;
858 // do the ciruit list
859 void FGTower::CheckCircuitList(double dt) {
860 //cout << "Entering CheckCircuitList..." << endl;
861 // Clear the constraints - we recalculate here.
863 downwind_leg_pos = 0.0;
864 crosswind_leg_pos = 0.0;
866 if(circuitList.size()) { // Do one plane from the circuit
867 if(circuitListItr == circuitList.end()) {
868 circuitListItr = circuitList.begin();
870 TowerPlaneRec* t = *circuitListItr;
871 //cout << ident << ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
873 t->pos.setlon(user_lon_node->getDoubleValue());
874 t->pos.setlat(user_lat_node->getDoubleValue());
875 t->pos.setelev(user_elev_node->getDoubleValue());
876 //cout << ident << ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
878 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.
879 t->landingType = t->planePtr->GetLandingOption();
880 //cout << "AI plane landing option is " << t->landingType << '\n';
882 Point3D tortho = ortho.ConvertToLocal(t->pos);
884 // Need to figure out which leg he's on
885 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
886 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
887 //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
888 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
889 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
891 // could be either takeoff, climbout or landing - check orthopos.y
892 //cout << "tortho.y = " << tortho.y() << '\n';
893 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
897 t->leg = CLIMBOUT; // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
898 //cout << "Climbout\n";
899 // If it's the user we may be unsure of his/her intentions.
900 // (Hopefully the AI planes won't try confusing the sim!!!)
901 //cout << "tortho.y = " << tortho.y() << '\n';
902 if(t->opType == TTT_UNKNOWN) {
903 if(tortho.y() > 5000) {
904 // 5 km out from threshold - assume it's a departure
905 t->opType = OUTBOUND; // TODO - could check if the user has climbed significantly above circuit altitude as well.
906 // Since we are unknown operation we should be in depList already.
907 //cout << ident << " Removing user from circuitList (TTT_UNKNOWN)\n";
908 circuitList.erase(circuitListItr);
909 RemoveFromTrafficList(t->plane.callsign);
910 circuitListItr = circuitList.begin();
912 } else if(t->opType == CIRCUIT) {
913 if(tortho.y() > 10000) {
914 // 10 km out - assume the user has abandoned the circuit!!
915 t->opType = OUTBOUND;
916 depList.push_back(t);
917 //cout << ident << " removing user from circuitList (CIRCUIT)\n";
918 circuitList.erase(circuitListItr);
919 circuitListItr = circuitList.begin();
923 } else if(abs(ho) < 60) {
925 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
926 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
933 } else if(abs(ho) < 120) {
935 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
936 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
938 //cout << "Crosswind\n";
943 } else if(abs(ho) < 150) {
945 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
946 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
951 // Probably safe now to assume the user is flying a circuit
958 //cout << "Downwind\n";
960 if(t->leg == FINAL) {
961 if(OnActiveRunway(t->pos)) {
962 t->leg = LANDING_ROLL;
966 t->leg = t->planePtr->GetLeg();
969 // Set the constraints IF this is the first plane in the circuit
970 // 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!!
971 if(circuitListItr == circuitList.begin()) {
974 // 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.
975 base_leg_pos = tortho.y();
976 //cout << "base_leg_pos = " << base_leg_pos << '\n';
979 // Fall through to base
981 base_leg_pos = tortho.y();
982 //cout << "base_leg_pos = " << base_leg_pos << '\n';
985 // Fall through to downwind
987 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
988 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
989 //cout << "base_leg_pos = " << base_leg_pos;
990 downwind_leg_pos = tortho.x(); // Assume that a following plane can simply be constrained by the immediately in front downwind plane
991 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
994 // Fall through to crosswind
996 crosswind_leg_pos = tortho.y();
997 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
998 t->instructedToGoAround = false;
1001 // Fall through to climbout
1003 // Only use current by constraint as largest
1004 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
1005 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1018 if(t->leg == FINAL && !(t->instructedToGoAround)) {
1019 doThresholdETACalc();
1020 doThresholdUseOrder();
1023 cout << "Checking USER on final... ";
1024 cout << "eta " << t->eta;
1025 if(t->clearedToLand) cout << " cleared to land\n";
1028 //cout << "YES FINAL, t->eta = " << t->eta << ", rwyList.size() = " << rwyList.size() << '\n';
1029 if(t->landingType == FULL_STOP) {
1030 t->opType = INBOUND;
1031 //cout << "\n******** SWITCHING TO INBOUND AT POINT AAA *********\n\n";
1033 if(t->eta < 12 && rwyList.size()) {
1034 // TODO - need to make this more sophisticated
1035 // eg. is the plane accelerating down the runway taking off [OK],
1036 // or stationary near the start [V. BAD!!].
1037 // For now this should stop the AI plane landing on top of the user.
1038 string trns = t->plane.callsign;
1039 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1040 pending_transmission = trns;
1041 ImmediateTransmit();
1042 t->instructedToGoAround = true;
1043 t->clearedToLand = false;
1044 // Assume it complies!!!
1045 t->opType = CIRCUIT;
1048 //cout << "Registering Go-around transmission with AI plane\n";
1049 t->planePtr->RegisterTransmission(13);
1051 } else if(!t->clearedToLand) {
1053 if(!rwyList.size()) {
1054 string trns = t->plane.callsign;
1055 trns += " Cleared to land";
1056 pending_transmission = trns;
1058 //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1059 t->clearedToLand = true;
1061 t->planePtr->RegisterTransmission(7);
1065 //if(t->isUser) cout << "Not next\n";
1068 } else if(t->leg == LANDING_ROLL) {
1069 //cout << t->plane.callsign << " has landed - adding to rwyList\n";
1070 rwyList.push_front(t);
1071 // TODO - if(!clearedToLand) shout something!!
1072 t->clearedToLand = false;
1073 RemoveFromTrafficList(t->plane.callsign);
1075 t->opType = TTT_UNKNOWN;
1076 } // TODO - allow the user to specify opType via ATC menu
1077 //cout << ident << " Removing " << t->plane.callsign << " from circuitList..." << endl;
1078 circuitListItr = circuitList.erase(circuitListItr);
1079 if(circuitListItr == circuitList.end() ) {
1080 circuitListItr = circuitList.begin();
1085 //cout << "Done CheckCircuitList" << endl;
1088 // 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!!
1089 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
1090 // (However, at the moment there should only be one airplane on the rwy at once, until we
1091 // start allowing planes to line up whilst previous arrival clears the rwy.)
1092 void FGTower::CheckRunwayList(double dt) {
1093 //cout << "Entering CheckRunwayList..." << endl;
1095 if(!rwyList.size()) {
1096 rwyOccupied = false;
1098 rwyListItr = rwyList.begin();
1099 TowerPlaneRec* t = *rwyListItr;
1101 t->pos.setlon(user_lon_node->getDoubleValue());
1102 t->pos.setlat(user_lat_node->getDoubleValue());
1103 t->pos.setelev(user_elev_node->getDoubleValue());
1105 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.
1107 bool on_rwy = OnActiveRunway(t->pos);
1109 // TODO - for all of these we need to check what the user is *actually* doing!
1110 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
1111 //cout << "Tower " << ident << " is removing plane " << t->plane.callsign << " from rwy list (vacated)\n";
1112 //cout << "Size of rwylist was " << rwyList.size() << '\n';
1113 //cout << "Size of vacatedList was " << vacatedList.size() << '\n';
1114 RemoveFromRwyList(t->plane.callsign);
1115 vacatedList.push_back(t);
1116 //cout << "Size of rwylist is " << rwyList.size() << '\n';
1117 //cout << "Size of vacatedList is " << vacatedList.size() << '\n';
1118 // At the moment we wait until Runway Vacated is reported by the plane before telling to contact ground etc.
1119 // It's possible we could be a bit more proactive about this.
1120 } else if(t->opType == OUTBOUND) {
1121 depList.push_back(t);
1122 rwyList.pop_front();
1124 timeSinceLastDeparture = 0.0;
1125 } else if(t->opType == CIRCUIT) {
1126 //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1127 circuitList.push_back(t);
1128 AddToTrafficList(t);
1129 rwyList.pop_front();
1131 timeSinceLastDeparture = 0.0;
1132 } else if(t->opType == TTT_UNKNOWN) {
1133 depList.push_back(t);
1134 //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1135 circuitList.push_back(t);
1136 AddToTrafficList(t);
1137 rwyList.pop_front();
1139 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.
1141 // HELP - we shouldn't ever get here!!!
1146 //cout << "Done CheckRunwayList" << endl;
1149 // Do one plane from the approach list
1150 void FGTower::CheckApproachList(double dt) {
1151 //cout << "CheckApproachList called for " << ident << endl;
1152 //cout << "AppList.size is " << appList.size() << endl;
1153 if(appList.size()) {
1154 if(appListItr == appList.end()) {
1155 appListItr = appList.begin();
1157 TowerPlaneRec* t = *appListItr;
1158 //cout << "t = " << t << endl;
1159 //cout << "Checking " << t->plane.callsign << endl;
1161 t->pos.setlon(user_lon_node->getDoubleValue());
1162 t->pos.setlat(user_lat_node->getDoubleValue());
1163 t->pos.setelev(user_elev_node->getDoubleValue());
1165 // TODO - set/update the position if it's an AI plane
1167 //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n';
1168 if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
1169 // TODO - need to make this more sophisticated
1170 // eg. is the plane accelerating down the runway taking off [OK],
1171 // or stationary near the start [V. BAD!!].
1172 // For now this should stop the AI plane landing on top of the user.
1173 string trns = t->plane.callsign;
1174 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1175 pending_transmission = trns;
1176 ImmediateTransmit();
1177 t->instructedToGoAround = true;
1178 t->clearedToLand = false;
1179 t->nextOnRwy = false; // But note this is recalculated so don't rely on it
1180 // Assume it complies!!!
1181 t->opType = CIRCUIT;
1185 //cout << "Registering Go-around transmission with AI plane\n";
1186 t->planePtr->RegisterTransmission(13);
1189 // TODO - add Go-around ack to comm options,
1190 // remove report rwy vacated. (possibly).
1193 if(t->nextOnRwy && !(t->clearedToLand) && !(t->instructedToGoAround)) {
1194 // check distance away and whether runway occupied
1195 // and schedule transmission if necessary
1198 // Check for landing...
1199 bool landed = false;
1202 if(t->planePtr->GetLeg() == LANDING_ROLL) {
1206 SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!");
1209 if(OnActiveRunway(t->pos)) {
1215 // Duplicated in CheckCircuitList - must be able to rationalise this somehow!
1216 //cout << "A " << t->plane.callsign << " has landed, adding to rwyList...\n";
1217 rwyList.push_front(t);
1218 // TODO - if(!clearedToLand) shout something!!
1219 t->clearedToLand = false;
1220 RemoveFromTrafficList(t->plane.callsign);
1222 // t->opType = TTT_UNKNOWN;
1223 //} // TODO - allow the user to specify opType via ATC menu
1224 appListItr = appList.erase(appListItr);
1225 if(appListItr == appList.end() ) {
1226 appListItr = appList.begin();
1232 //cout << "Done" << endl;
1235 // Do one plane from the departure list
1236 void FGTower::CheckDepartureList(double dt) {
1237 if(depList.size()) {
1238 if(depListItr == depList.end()) {
1239 depListItr = depList.begin();
1241 TowerPlaneRec* t = *depListItr;
1242 //cout << "Dep list, checking " << t->plane.callsign;
1244 double distout; // meters
1245 if(t->isUser) distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
1246 else distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), t->planePtr->GetPos());
1247 //cout << " distout = " << distout << '\n';
1248 if(distout > 10000) {
1249 string trns = t->plane.callsign;
1250 trns += " You are now clear of my airspace, good day";
1251 pending_transmission = trns;
1254 // Change the communication options
1255 RemoveAllUserDialogOptions();
1256 //cout << "ADD A\n";
1257 current_atcdialog->add_entry(ident, "@AP Tower @CS @MI miles @CD of the airport for full stop with the ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
1259 // Send a clear-of-airspace signal
1260 // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals).
1262 RemovePlane(t->plane.callsign);
1269 // ********** End periodic check functions ***********************************************
1270 // ***************************************************************************************
1273 // Remove all dialog options for this tower.
1274 void FGTower::RemoveAllUserDialogOptions() {
1275 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_DEPARTURE, TOWER);
1276 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1277 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1278 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1279 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1280 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
1281 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
1282 current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
1285 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
1286 // plus the constraint position as a rwy orientated orthopos (meters)
1287 bool FGTower::GetCrosswindConstraint(double& cpos) {
1288 if(crosswind_leg_pos != 0.0) {
1289 cpos = crosswind_leg_pos;
1296 bool FGTower::GetDownwindConstraint(double& dpos) {
1297 if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
1298 dpos = downwind_leg_pos;
1305 bool FGTower::GetBaseConstraint(double& bpos) {
1306 if(base_leg_pos < nominal_base_leg_pos) {
1307 bpos = base_leg_pos;
1310 bpos = nominal_base_leg_pos;
1316 // Figure out which runways are active.
1317 // For now we'll just be simple and do one active runway - eventually this will get much more complex
1318 // This is a private function - public interface to the results of this is through GetActiveRunway
1319 void FGTower::DoRwyDetails() {
1320 //cout << "GetRwyDetails called" << endl;
1322 // Based on the airport-id and wind get the active runway
1325 double hdg = wind_from_hdg->getDoubleValue();
1326 double speed = wind_speed_knots->getDoubleValue();
1327 hdg = (speed == 0.0 ? 270.0 : hdg);
1328 //cout << "Heading = " << hdg << '\n';
1331 bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
1333 //cout << "RUNWAY GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD\n";
1334 activeRwy = runway.rwy_no;
1335 rwy.rwyID = runway.rwy_no;
1336 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
1338 // Get the threshold position
1339 double other_way = runway.heading - 180.0;
1340 while(other_way <= 0.0) {
1343 // move to the +l end/center of the runway
1344 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
1345 Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
1346 Point3D ref = origin;
1347 double tshlon, tshlat, tshr;
1348 double tolon, tolat, tor;
1349 rwy.length = runway.length * SG_FEET_TO_METER;
1350 rwy.width = runway.width * SG_FEET_TO_METER;
1351 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way,
1352 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
1353 geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading,
1354 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
1355 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
1356 // now copy what we need out of runway into rwy
1357 rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
1358 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
1359 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
1360 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
1361 rwy.hdg = runway.heading;
1362 // Set the projection for the local area based on this active runway
1363 ortho.Init(rwy.threshold_pos, rwy.hdg);
1364 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero
1365 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
1367 // Set the pattern direction
1368 // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
1369 // for certain circumstances (RH parallel rwy).
1370 rwy.patternDirection = -1; // Left
1371 if(rwy.rwyID.size() == 3) {
1372 rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
1374 //cout << "Doing details, rwy.patterDirection is " << rwy.patternDirection << '\n';
1376 SG_LOG(SG_ATC, SG_ALERT, "Help - can't get good runway in FGTower!!");
1382 // Figure out if a given position lies on the active runway
1383 // Might have to change when we consider more than one active rwy.
1384 bool FGTower::OnActiveRunway(Point3D pt) {
1385 // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
1386 Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
1387 Point3D xyp = ortho.ConvertToLocal(pt);
1389 //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
1390 //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
1392 double rlen = rwy.length/2.0 + 5.0;
1393 double rwidth = rwy.width/2.0;
1394 double ldiff = fabs(xyp.y() - xyc.y());
1395 double wdiff = fabs(xyp.x() - xyc.x());
1397 return((ldiff < rlen) && (wdiff < rwidth));
1401 // Figure out if a given position lies on any runway or not
1402 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
1403 bool FGTower::OnAnyRunway(Point3D pt) {
1405 double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
1409 // Based on the airport-id, go through all the runways and check for a point in them
1411 // TODO - do we actually need to search for the airport - surely we already know our ident and
1412 // can just search runways of our airport???
1413 //cout << "Airport ident is " << ad.ident << '\n';
1415 bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
1417 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
1420 while(runway.id == ad.ident) {
1421 on = OnRunway(pt, runway);
1422 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
1423 if(on) return(true);
1424 globals->get_runways()->next(&runway);
1430 // Returns true if successful
1431 bool FGTower::RemoveFromTrafficList(string id) {
1432 tower_plane_rec_list_iterator twrItr;
1433 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1434 TowerPlaneRec* tpr = *twrItr;
1435 if(tpr->plane.callsign == id) {
1436 trafficList.erase(twrItr);
1437 trafficListItr = trafficList.begin();
1441 SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1446 // Returns true if successful
1447 bool FGTower::RemoveFromAppList(string id) {
1448 tower_plane_rec_list_iterator twrItr;
1449 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1450 TowerPlaneRec* tpr = *twrItr;
1451 if(tpr->plane.callsign == id) {
1452 appList.erase(twrItr);
1453 appListItr = appList.begin();
1457 //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from appList in FGTower");
1461 // Returns true if successful
1462 bool FGTower::RemoveFromRwyList(string id) {
1463 tower_plane_rec_list_iterator twrItr;
1464 for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
1465 TowerPlaneRec* tpr = *twrItr;
1466 if(tpr->plane.callsign == id) {
1467 rwyList.erase(twrItr);
1468 rwyListItr = rwyList.begin();
1472 //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from rwyList in FGTower");
1477 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1478 // and set nextOnRwy if so.
1479 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1480 // For planes holding they are put in the first position with time to go, and the return value is
1481 // true if in the first position (nextOnRwy) and false otherwise.
1482 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1483 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1484 //cout << "ADD: " << trafficList.size();
1485 //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1486 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.
1487 double departure_sep_time = 60.0; // Separation time behind departing airplanes. Comments above also apply.
1488 bool conflict = false;
1489 double lastETA = 0.0;
1490 bool firstTime = true;
1491 // FIXME - make this more robust for different plane types eg. light following heavy.
1492 tower_plane_rec_list_iterator twrItr;
1493 //twrItr = trafficList.begin();
1495 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1496 //if(twrItr == trafficList.end()) {
1498 // trafficList.push_back(t);
1499 // return(holding ? firstTime : conflict);
1501 TowerPlaneRec* tpr = *twrItr;
1503 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1504 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1505 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0);
1506 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1507 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1508 // and if not needs time to clear the rwy anyway.
1509 if(tpr->eta - lastETA > slot_time) {
1510 t->nextOnRwy = firstTime;
1511 trafficList.insert(twrItr, t);
1512 //cout << "\tH\t" << trafficList.size() << '\n';
1517 if(t->eta < tpr->eta) {
1518 // Ugg - this one's tricky.
1519 // It depends on what the two planes are doing and whether there's a conflict what we do.
1520 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1521 if(tpr->nextOnRwy) {
1522 tpr->nextOnRwy = false;
1523 t->nextOnRwy = true;
1525 trafficList.insert(twrItr, t);
1526 } else { // Ooops - this ones tricky - we have a potential conflict!
1528 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1529 if(tpr->nextOnRwy) {
1530 tpr->nextOnRwy = false;
1531 t->nextOnRwy = true;
1533 trafficList.insert(twrItr, t);
1535 //cout << "\tC\t" << trafficList.size() << '\n';
1542 // If we get here we must be at the end of the list, or maybe the list is empty.
1543 if(!trafficList.size()) {
1544 t->nextOnRwy = true;
1545 // conflict and firstTime should be false and true respectively in this case anyway.
1547 t->nextOnRwy = false;
1549 trafficList.push_back(t);
1550 //cout << "\tE\t" << trafficList.size() << endl;
1551 return(holding ? firstTime : conflict);
1554 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1555 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1556 // Safe to add a plane that is already in - planes with the same callsign are not added.
1557 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1559 //cout << "**********************************************\n";
1560 //cout << "AddToCircuitList called with NULL pointer!!!!!\n";
1561 //cout << "**********************************************\n";
1564 //cout << "ADD: " << circuitList.size();
1565 //cout << ident << " AddToCircuitList called for " << t->plane.callsign << ", currently size = " << circuitList.size() << endl;
1566 double separation_time = 60.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.
1567 bool conflict = false;
1568 tower_plane_rec_list_iterator twrItr;
1569 // First check if the plane is already in the list
1570 //cout << "A" << endl;
1571 //cout << "Checking whether " << t->plane.callsign << " is already in circuit list..." << endl;
1572 //cout << "B" << endl;
1573 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1574 if((*twrItr)->plane.callsign == t->plane.callsign) {
1575 //cout << "In list - returning...\n";
1579 //cout << "Not in list - adding..." << endl;
1581 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1582 TowerPlaneRec* tpr = *twrItr;
1583 //cout << tpr->plane.callsign << " eta is " << tpr->eta << '\n';
1584 //cout << "New eta is " << t->eta << '\n';
1585 if(t->eta < tpr->eta) {
1586 // Ugg - this one's tricky.
1587 // It depends on what the two planes are doing and whether there's a conflict what we do.
1588 if(tpr->eta - t->eta > separation_time) { // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1589 circuitList.insert(twrItr, t);
1590 } else { // Ooops - this ones tricky - we have a potential conflict!
1592 // HACK - just add anyway for now and flag conflict.
1593 circuitList.insert(twrItr, t);
1595 //cout << "\tC\t" << circuitList.size() << '\n';
1599 // If we get here we must be at the end of the list, or maybe the list is empty.
1600 //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1601 circuitList.push_back(t); // TODO - check the separation with the preceding plane for the conflict flag.
1602 //cout << "\tE\t" << circuitList.size() << endl;
1607 // Calculate the eta of a plane to the threshold.
1608 // For ground traffic this is the fastest they can get there.
1609 // For air traffic this is the middle approximation.
1610 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1611 // For now we'll be very crude and hardwire expected speeds to C172-like values
1612 // The speeds below are specified in knots IAS and then converted to m/s
1613 double app_ias = 100.0 * 0.514444; // Speed during straight-in approach
1614 double circuit_ias = 80.0 * 0.514444; // Speed around circuit
1615 double final_ias = 70.0 * 0.514444; // Speed during final approach
1618 //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1619 //cout << (tpr->isUser ? "USER\n" : "AI\n");
1623 // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1624 // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1626 Point3D op = ortho.ConvertToLocal(tpr->pos);
1628 //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
1629 //cout << "opType is " << tpr->opType << '\n';
1631 double dist_out_m = op.y();
1632 double dist_across_m = fabs(op.x()); // The fabs is a hack to cope with the fact that we don't know the circuit direction yet
1633 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1635 if(tpr->opType == STRAIGHT_IN || tpr->opType == INBOUND) {
1636 //cout << "CASE 1\n";
1637 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1638 if(dist_to_go_m < 1000) {
1639 tpr->eta = dist_to_go_m / final_ias;
1641 tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1643 } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) { // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1644 //cout << "CASE 2\n";
1645 // It's complicated - depends on if base leg is delayed or not
1647 //cout << "Leg = " << tpr->leg << '\n';
1649 if(tpr->leg == LANDING_ROLL) {
1651 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1652 //cout << "dist_out_m = " << dist_out_m << '\n';
1653 tpr->eta = fabs(dist_out_m) / final_ias;
1654 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1655 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1657 // Need to calculate where base leg is likely to be
1658 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1659 // 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
1660 double nominal_base_dist_out_m = -1000;
1661 double current_base_dist_out_m;
1662 if(!GetBaseConstraint(current_base_dist_out_m)) {
1663 current_base_dist_out_m = nominal_base_dist_out_m;
1665 //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
1666 double nominal_dist_across_m = 1000; // Hardwired value from AILocalTraffic
1667 double current_dist_across_m;
1668 if(!GetDownwindConstraint(current_dist_across_m)) {
1669 current_dist_across_m = nominal_dist_across_m;
1671 double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 700ft agl.
1672 tpr->eta = fabs(current_base_dist_out_m) / final_ias; // final
1673 //cout << "a = " << tpr->eta << '\n';
1674 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1675 tpr->eta += dist_across_m / circuit_ias;
1676 //cout << "b = " << tpr->eta << '\n';
1677 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1678 //cout << "c = " << tpr->eta << '\n';
1679 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1680 //cout << "CROSSWIND calc: ";
1681 //cout << tpr->eta << ' ';
1682 if(dist_across_m > nominal_dist_across_m) {
1683 tpr->eta += dist_across_m / circuit_ias;
1686 tpr->eta += nominal_dist_across_m / circuit_ias;
1689 //cout << tpr->eta << ' ';
1690 // should we use the dist across of the previous plane if there is previous still on downwind?
1691 //if(printout) cout << "bb = " << tpr->eta << '\n';
1692 if(dist_out_m > nominal_cross_dist_out_m) {
1693 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1696 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1699 //cout << tpr->eta << ' ';
1700 //if(printout) cout << "cc = " << tpr->eta << '\n';
1701 if(nominal_dist_across_m > dist_across_m) {
1702 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1708 //cout << tpr->eta << '\n';
1709 //if(printout) cout << "dd = " << tpr->eta << '\n';
1711 // We've only just started - why not use a generic estimate?
1716 // cout << "ETA = " << tpr->eta << '\n';
1718 //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
1725 // Calculate the distance of a plane to the threshold in meters
1726 // TODO - Modify to calculate flying distance of a plane in the circuit
1727 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1728 return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1732 // Calculate the distance of a plane to the threshold in miles
1733 // TODO - Modify to calculate flying distance of a plane in the circuit
1734 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1735 return(CalcDistOutM(tpr) / 1600.0); // FIXME - use a proper constant if possible.
1739 // Iterate through all the lists, update the position of, and call CalcETA for all the planes.
1740 void FGTower::doThresholdETACalc() {
1741 //cout << "Entering doThresholdETACalc..." << endl;
1742 tower_plane_rec_list_iterator twrItr;
1743 // Do the approach list first
1744 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1745 TowerPlaneRec* tpr = *twrItr;
1746 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1750 // Then the circuit list
1751 //cout << "Circuit list size is " << circuitList.size() << '\n';
1752 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1753 TowerPlaneRec* tpr = *twrItr;
1754 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1758 //cout << "Done doThresholdETCCalc" << endl;
1762 // Check that the planes in traffic list are correctly ordered,
1763 // that the nearest (timewise) is flagged next on rwy, and return
1764 // true if any threshold use conflicts are detected, false otherwise.
1765 bool FGTower::doThresholdUseOrder() {
1766 //cout << "Entering doThresholdUseOrder..." << endl;
1767 bool conflict = false;
1769 // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1770 // Here's the rather simplistic assumptions we're using:
1771 // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1772 // In order of priority for runway use:
1773 // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1774 // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1775 // and holding planes until a space.
1776 // When calculating if a holding plane can use the runway, time clearance from last departure
1777 // as well as time clearance to next arrival must be considered.
1779 trafficList.clear();
1781 tower_plane_rec_list_iterator twrItr;
1782 // Do the approach list first
1783 //if(ident == "KRHV") cout << "A" << flush;
1784 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1785 TowerPlaneRec* tpr = *twrItr;
1786 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1787 conflict = AddToTrafficList(tpr);
1789 // Then the circuit list
1790 //if(ident == "KRHV") cout << "C" << flush;
1791 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1792 TowerPlaneRec* tpr = *twrItr;
1793 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1794 conflict = AddToTrafficList(tpr);
1796 // And finally the hold list
1797 //cout << "H" << endl;
1798 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1799 TowerPlaneRec* tpr = *twrItr;
1800 AddToTrafficList(tpr, true);
1805 //if(ident == "KRHV") {
1807 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1808 TowerPlaneRec* tpr = *twrItr;
1809 cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1814 //cout << "Done doThresholdUseOrder" << endl;
1819 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1820 // i.e. list_pos = 1 implies next to use runway.
1821 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1822 if(trafficList.size() < list_pos) {
1826 tower_plane_rec_list_iterator twrItr;
1827 twrItr = trafficList.begin();
1828 for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1829 TowerPlaneRec* tpr = *twrItr;
1830 CalcETA(tpr, printout);
1831 //cout << "ETA returned = " << tpr->eta << '\n';
1836 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1837 // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1838 TowerPlaneRec* t = new TowerPlaneRec;
1840 t->planePtr = requestee;
1841 t->holdShortReported = true;
1842 t->clearedToLineUp = false;
1843 t->clearedToTakeOff = false;
1844 t->opType = operation;
1845 t->pos = requestee->GetPos();
1847 //cout << "Hold Short reported by " << plane.callsign << '\n';
1848 SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1851 bool next = AddToTrafficList(t, true);
1853 double teta = GetTrafficETA(2);
1855 t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1856 //cout << "Reducing response time to request due imminent traffic\n";
1861 // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1863 holdList.push_back(t);
1865 responseReqd = true;
1868 // Register the presence of an AI plane at a point where contact would already have been made in real life
1869 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1870 void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type op, PatternLeg lg) {
1871 // At the moment this is only going to be tested with inserting an AI plane on downwind
1872 TowerPlaneRec* t = new TowerPlaneRec;
1877 t->pos = ai->GetPos();
1881 if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1882 AddToCircuitList(t);
1887 doThresholdUseOrder();
1890 void FGTower::DeregisterAIPlane(string id) {
1894 // Contact tower for VFR approach
1895 // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
1896 // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
1897 // opt defaults to AIP_LT_UNKNOWN
1898 void FGTower::VFRArrivalContact(string ID, LandingType opt) {
1899 //cout << "USER Request Landing Clearance called for ID " << ID << '\n';
1901 // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
1904 string usercall = fgGetString("/sim/user/callsign");
1905 if(ID == "USER" || ID == usercall) {
1906 t = FindPlane(usercall);
1908 //cout << "NOT t\n";
1909 t = new TowerPlaneRec;
1911 t->pos.setlon(user_lon_node->getDoubleValue());
1912 t->pos.setlat(user_lat_node->getDoubleValue());
1913 t->pos.setelev(user_elev_node->getDoubleValue());
1916 // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
1917 // quite getting out of tower airspace - just ignore for now and treat as new arrival.
1918 // TODO - Maybe should remove from departure and circuit list if in there though!!
1921 // Oops - something has gone wrong - put out a warning
1922 cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
1928 // Calculate where the plane is in relation to the active runway and it's circuit
1929 // and set the op-type as appropriate.
1931 // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1932 t->opType = STRAIGHT_IN;
1934 t->plane.type = GA_SINGLE; // FIXME - Another assumption!
1935 t->plane.callsign = usercall;
1937 t->vfrArrivalReported = true;
1938 responseReqd = true;
1940 appList.push_back(t); // Not necessarily permanent
1941 AddToTrafficList(t);
1943 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1944 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1945 current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1948 // landingType defaults to AIP_LT_UNKNOWN
1949 void FGTower::VFRArrivalContact(PlaneRec plane, FGAIPlane* requestee, LandingType lt) {
1950 //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n';
1951 // Possible hack - assume this plane is new for now - TODO - should check really
1952 TowerPlaneRec* t = new TowerPlaneRec;
1954 t->planePtr = requestee;
1955 t->landingType = lt;
1956 t->pos = requestee->GetPos();
1958 //cout << "Hold Short reported by " << plane.callsign << '\n';
1959 SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign);
1960 //cout << "VFR arrival contact made by " << plane.callsign << '\n';
1962 // HACK - to get up and running I'm going to assume a staight-in final for now.
1963 t->opType = STRAIGHT_IN;
1965 t->vfrArrivalReported = true;
1966 responseReqd = true;
1968 //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n';
1969 appList.push_back(t); // Not necessarily permanent
1970 //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n';
1971 AddToTrafficList(t);
1974 void FGTower::RequestDepartureClearance(string ID) {
1975 //cout << "Request Departure Clearance called...\n";
1978 void FGTower::ReportFinal(string ID) {
1979 //cout << "Report Final Called at tower " << ident << " by plane " << ID << '\n';
1981 ID = fgGetString("/sim/user/callsign");
1982 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1984 TowerPlaneRec* t = FindPlane(ID);
1986 t->finalReported = true;
1987 t->finalAcknowledged = false;
1988 if(!(t->clearedToLand)) {
1989 responseReqd = true;
1991 // possibly respond with wind even if already cleared to land?
1992 t->finalReported = false;
1993 t->finalAcknowledged = true;
1994 // HACK!! - prevents next reporting being misinterpreted as this one.
1997 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
2001 void FGTower::ReportLongFinal(string ID) {
2003 ID = fgGetString("/sim/user/callsign");
2004 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2006 TowerPlaneRec* t = FindPlane(ID);
2008 t->longFinalReported = true;
2009 t->longFinalAcknowledged = false;
2010 if(!(t->clearedToLand)) {
2011 responseReqd = true;
2012 } // possibly respond with wind even if already cleared to land?
2014 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
2018 //void FGTower::ReportOuterMarker(string ID);
2019 //void FGTower::ReportMiddleMarker(string ID);
2020 //void FGTower::ReportInnerMarker(string ID);
2022 void FGTower::ReportRunwayVacated(string ID) {
2023 //cout << "Report Runway Vacated Called at tower " << ident << " by plane " << ID << '\n';
2025 ID = fgGetString("/sim/user/callsign");
2026 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
2028 TowerPlaneRec* t = FindPlane(ID);
2030 //cout << "Found it...\n";
2031 t->rwyVacatedReported = true;
2032 responseReqd = true;
2034 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2035 SG_LOG(SG_ATC, SG_ALERT, "A WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2036 //cout << "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)\n";
2040 TowerPlaneRec* FGTower::FindPlane(string ID) {
2041 //cout << "FindPlane called for " << ID << "...\n";
2042 tower_plane_rec_list_iterator twrItr;
2043 // Do the approach list first
2044 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2045 //cout << "appList callsign is " << (*twrItr)->plane.callsign << '\n';
2046 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2048 // Then the circuit list
2049 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2050 //cout << "circuitList callsign is " << (*twrItr)->plane.callsign << '\n';
2051 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2053 // Then the runway list
2054 //cout << "rwyList.size() is " << rwyList.size() << '\n';
2055 for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2056 //cout << "rwyList callsign is " << (*twrItr)->plane.callsign << '\n';
2057 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2060 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2061 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2063 // And finally the vacated list
2064 for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2065 //cout << "vacatedList callsign is " << (*twrItr)->plane.callsign << '\n';
2066 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2068 SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
2073 void FGTower::RemovePlane(string ID) {
2074 //cout << ident << " RemovePlane called for " << ID << '\n';
2075 // We have to be careful here - we want to erase the plane from all lists it is in,
2076 // but we can only delete it once, AT THE END.
2077 TowerPlaneRec* t = NULL;
2078 tower_plane_rec_list_iterator twrItr;
2079 for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2080 if((*twrItr)->plane.callsign == ID) {
2082 twrItr = appList.erase(twrItr);
2083 appListItr = appList.begin();
2086 for(twrItr = depList.begin(); twrItr != depList.end(); twrItr++) {
2087 if((*twrItr)->plane.callsign == ID) {
2089 twrItr = depList.erase(twrItr);
2090 depListItr = depList.begin();
2093 for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2094 if((*twrItr)->plane.callsign == ID) {
2096 twrItr = circuitList.erase(twrItr);
2097 circuitListItr = circuitList.begin();
2100 for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2101 if((*twrItr)->plane.callsign == ID) {
2103 twrItr = holdList.erase(twrItr);
2104 holdListItr = holdList.begin();
2107 for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2108 if((*twrItr)->plane.callsign == ID) {
2110 twrItr = rwyList.erase(twrItr);
2111 rwyListItr = rwyList.begin();
2114 for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2115 if((*twrItr)->plane.callsign == ID) {
2117 twrItr = vacatedList.erase(twrItr);
2118 vacatedListItr = vacatedList.begin();
2121 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
2122 if((*twrItr)->plane.callsign == ID) {
2124 twrItr = trafficList.erase(twrItr);
2125 trafficListItr = trafficList.begin();
2128 // And finally, delete the record if we found it.
2132 void FGTower::ReportDownwind(string ID) {
2133 //cout << "ReportDownwind(...) called\n";
2135 ID = fgGetString("/sim/user/callsign");
2136 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
2138 TowerPlaneRec* t = FindPlane(ID);
2140 t->downwindReported = true;
2141 responseReqd = true;
2142 // If the plane is in the app list, remove it and put it in the circuit list instead.
2143 // Ideally we might want to do this at the 2 mile report prior to 45 deg entry, but at
2144 // the moment that would b&gg?r up the constraint position calculations.
2145 RemoveFromAppList(ID);
2148 t->pos.setlon(user_lon_node->getDoubleValue());
2149 t->pos.setlat(user_lat_node->getDoubleValue());
2150 t->pos.setelev(user_elev_node->getDoubleValue());
2152 // ASSERT(t->planePtr != NULL);
2153 t->pos = t->planePtr->GetPos();
2156 AddToCircuitList(t);
2158 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2162 void FGTower::ReportGoingAround(string ID) {
2164 ID = fgGetString("/sim/user/callsign");
2165 RemoveAllUserDialogOptions(); // TODO - it would be much more efficient if ATCDialog simply had a clear() function!!!
2166 current_atcdialog->add_entry(ident, "@AP Tower @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
2168 TowerPlaneRec* t = FindPlane(ID);
2170 //t->goAroundReported = true; // No need to set this until we start responding to it.
2171 responseReqd = false; // might change in the future but for now we'll not distract them during the go-around.
2172 // If the plane is in the app list, remove it and put it in the circuit list instead.
2173 RemoveFromAppList(ID);
2176 t->pos.setlon(user_lon_node->getDoubleValue());
2177 t->pos.setlat(user_lat_node->getDoubleValue());
2178 t->pos.setelev(user_elev_node->getDoubleValue());
2180 // ASSERT(t->planePtr != NULL);
2181 t->pos = t->planePtr->GetPos();
2184 AddToCircuitList(t);
2186 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2190 string FGTower::GenText(const string& m, int c) {
2191 const int cmax = 300;
2201 string usercall = fgGetString("/sim/user/callsign");
2203 //transmission_list_type tmissions = transmissionlist_station[station];
2204 //transmission_list_iterator current = tmissions.begin();
2205 //transmission_list_iterator last = tmissions.end();
2207 //for ( ; current != last ; ++current ) {
2208 // if ( current->get_code().c1 == code.c1 &&
2209 // current->get_code().c2 == code.c2 &&
2210 // current->get_code().c3 == code.c3 ) {
2212 //if ( ttext ) message = current->get_transtext();
2213 //else message = current->get_menutext();
2214 strcpy( &mes[0], m.c_str() );
2216 // Replace all the '@' parameters with the actual text.
2217 int check = 0; // If mes gets overflowed the while loop can go infinite
2218 while ( strchr(&mes[0], crej) != NULL ) { // ie. loop until no more occurances of crej ('@') found
2219 pos = strchr( &mes[0], crej );
2220 bcopy(pos, &tag[0], 3);
2224 for ( i=0; i<cmax; i++ ) {
2225 if ( mes[i] == crej ) {
2230 strncpy( &dum[0], &mes[0], len );
2233 if ( strcmp ( tag, "@ST" ) == 0 )
2234 //strcat( &dum[0], tpars.station.c_str() );
2235 strcat(&dum[0], ident.c_str());
2236 else if ( strcmp ( tag, "@AP" ) == 0 )
2237 //strcat( &dum[0], tpars.airport.c_str() );
2238 strcat(&dum[0], name.c_str());
2239 else if ( strcmp ( tag, "@CS" ) == 0 )
2240 //strcat( &dum[0], tpars.callsign.c_str() );
2241 strcat(&dum[0], usercall.c_str());
2242 else if ( strcmp ( tag, "@TD" ) == 0 ) {
2244 if ( tpars.tdir == 1 ) {
2245 char buf[] = "left";
2246 strcat( &dum[0], &buf[0] );
2249 char buf[] = "right";
2250 strcat( &dum[0], &buf[0] );
2254 else if ( strcmp ( tag, "@HE" ) == 0 ) {
2257 sprintf( buf, "%i", (int)(tpars.heading) );
2258 strcat( &dum[0], &buf[0] );
2261 else if ( strcmp ( tag, "@VD" ) == 0 ) {
2263 if ( tpars.VDir == 1 ) {
2264 char buf[] = "Descend and maintain";
2265 strcat( &dum[0], &buf[0] );
2267 else if ( tpars.VDir == 2 ) {
2268 char buf[] = "Maintain";
2269 strcat( &dum[0], &buf[0] );
2271 else if ( tpars.VDir == 3 ) {
2272 char buf[] = "Climb and maintain";
2273 strcat( &dum[0], &buf[0] );
2277 else if ( strcmp ( tag, "@AL" ) == 0 ) {
2280 sprintf( buf, "%i", (int)(tpars.alt) );
2281 strcat( &dum[0], &buf[0] );
2284 else if ( strcmp ( tag, "@MI" ) == 0 ) {
2286 //sprintf( buf, "%3.1f", tpars.miles );
2287 int dist_miles = (int)dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
2288 sprintf(buf, "%i", dist_miles);
2289 strcat( &dum[0], &buf[0] );
2291 else if ( strcmp ( tag, "@FR" ) == 0 ) {
2294 sprintf( buf, "%6.2f", tpars.freq );
2295 strcat( &dum[0], &buf[0] );
2298 else if ( strcmp ( tag, "@RW" ) == 0 ) {
2299 strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
2300 } else if(strcmp(tag, "@CD") == 0) { // @CD = compass direction
2301 double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
2302 while(h < 0.0) h += 360.0;
2303 while(h > 360.0) h -= 360.0;
2304 if(h < 22.5 || h > 337.5) {
2305 strcat(&dum[0], "North");
2306 } else if(h < 67.5) {
2307 strcat(&dum[0], "North-East");
2308 } else if(h < 112.5) {
2309 strcat(&dum[0], "East");
2310 } else if(h < 157.5) {
2311 strcat(&dum[0], "South-East");
2312 } else if(h < 202.5) {
2313 strcat(&dum[0], "South");
2314 } else if(h < 247.5) {
2315 strcat(&dum[0], "South-West");
2316 } else if(h < 292.5) {
2317 strcat(&dum[0], "West");
2319 strcat(&dum[0], "North-West");
2322 cout << "Tag " << tag << " not found" << endl;
2325 strcat( &dum[0], &mes[len+3] );
2326 strcpy( &mes[0], &dum[0] );
2330 SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)");
2335 //cout << mes << endl;
2339 if ( mes != "" ) return mes;
2340 else return "No transmission found";
2343 ostream& operator << (ostream& os, tower_traffic_type ttt) {
2345 case(CIRCUIT): return(os << "CIRCUIT");
2346 case(INBOUND): return(os << "INBOUND");
2347 case(OUTBOUND): return(os << "OUTBOUND");
2348 case(TTT_UNKNOWN): return(os << "UNKNOWN");
2349 case(STRAIGHT_IN): return(os << "STRAIGHT_IN");
2351 return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");