]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
try to fix yet another crash bug (don't worry, there's one for anybody!)
[flightgear.git] / src / ATC / tower.cxx
1 // FGTower - a class to provide tower control at towered airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
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.
11 //
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.
16 //
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #ifdef HAVE_STRINGS_H
26 #  include <strings.h>   // bcopy()
27 #else
28 #  include <string.h>    // MSVC doesn't have strings.h
29 #endif
30
31 #include <Main/globals.hxx>
32 #include <Airports/runways.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/debug/logstream.hxx>
35
36 #include "tower.hxx"
37 #include "ATCmgr.hxx"
38 #include "ATCutils.hxx"
39 #include "ATCDialog.hxx"
40 #include "commlist.hxx"
41 #include "AILocalTraffic.hxx"
42
43 SG_USING_STD(cout);
44
45 // TowerPlaneRec
46
47 TowerPlaneRec::TowerPlaneRec() :
48         planePtr(NULL),
49         clearedToLand(false),
50         clearedToLineUp(false),
51         clearedToTakeOff(false),
52         holdShortReported(false),
53         downwindReported(false),
54         longFinalReported(false),
55         longFinalAcknowledged(false),
56         finalReported(false),
57         finalAcknowledged(false),
58         rwyVacatedReported(false),
59         rwyVacatedAcknowledged(false),
60         goAroundReported(false),
61         instructedToGoAround(false),
62         onRwy(false),
63         nextOnRwy(false),
64         vfrArrivalReported(false),
65         vfrArrivalAcknowledged(false),
66         opType(TTT_UNKNOWN),
67         leg(LEG_UNKNOWN),
68         landingType(AIP_LT_UNKNOWN),
69         isUser(false)
70 {
71         plane.callsign = "UNKNOWN";
72 }
73
74 TowerPlaneRec::TowerPlaneRec(const PlaneRec& p) :
75         planePtr(NULL),
76         clearedToLand(false),
77         clearedToLineUp(false),
78         clearedToTakeOff(false),
79         holdShortReported(false),
80         downwindReported(false),
81         longFinalReported(false),
82         longFinalAcknowledged(false),
83         finalReported(false),
84         finalAcknowledged(false),
85         rwyVacatedReported(false),
86         rwyVacatedAcknowledged(false),
87         goAroundReported(false),
88         instructedToGoAround(false),
89         onRwy(false),
90         nextOnRwy(false),
91         vfrArrivalReported(false),
92         vfrArrivalAcknowledged(false),
93         opType(TTT_UNKNOWN),
94         leg(LEG_UNKNOWN),
95         landingType(AIP_LT_UNKNOWN),
96         isUser(false)
97 {
98         plane = p;
99 }
100
101 TowerPlaneRec::TowerPlaneRec(const Point3D& pt) :
102         planePtr(NULL),
103         clearedToLand(false),
104         clearedToLineUp(false),
105         clearedToTakeOff(false),
106         holdShortReported(false),
107         downwindReported(false),
108         longFinalReported(false),
109         longFinalAcknowledged(false),
110         finalReported(false),
111         finalAcknowledged(false),
112         rwyVacatedReported(false),
113         rwyVacatedAcknowledged(false),
114         goAroundReported(false),
115         instructedToGoAround(false),
116         onRwy(false),
117         nextOnRwy(false),
118         vfrArrivalReported(false),
119         vfrArrivalAcknowledged(false),
120         opType(TTT_UNKNOWN),
121         leg(LEG_UNKNOWN),
122         landingType(AIP_LT_UNKNOWN),
123         isUser(false)
124 {
125         plane.callsign = "UNKNOWN";
126         pos = pt;
127 }
128
129 TowerPlaneRec::TowerPlaneRec(const PlaneRec& p, const Point3D& pt) :
130         planePtr(NULL),
131         clearedToLand(false),
132         clearedToLineUp(false),
133         clearedToTakeOff(false),
134         holdShortReported(false),
135         downwindReported(false),
136         longFinalReported(false),
137         longFinalAcknowledged(false),
138         finalReported(false),
139         finalAcknowledged(false),
140         rwyVacatedReported(false),
141         rwyVacatedAcknowledged(false),
142         goAroundReported(false),
143         instructedToGoAround(false),
144         onRwy(false),
145         nextOnRwy(false),
146         vfrArrivalReported(false),
147         vfrArrivalAcknowledged(false),
148         opType(TTT_UNKNOWN),
149         leg(LEG_UNKNOWN),
150         landingType(AIP_LT_UNKNOWN),
151         isUser(false)
152 {
153         plane = p;
154         pos = pt;
155 }
156
157
158 // FGTower
159
160 /*******************************************
161                TODO List
162                            
163 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in. (MAJOR)
164
165 Use track instead of heading to determine what leg of the circuit the user is flying. (MINOR)
166
167 Use altitude as well as position to try to determine if the user has left the circuit. (MEDIUM - other issues as well).
168
169 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
170 will break when planes start queueing. (CRITICAL)
171
172 Report-Runway-Vacated is left as only user ATC option following a go-around. (MAJOR)
173
174 Report-Downwind is not added as ATC option when user takes off to fly a circuit. (MAJOR)
175
176 eta of USER can be calculated very wrongly in circuit if flying straight out and turn4 etc are with +ve ortho y. 
177 This can then screw up circuit ordering for other planes (MEDIUM)
178
179 USER leaving circuit needs to be more robustly considered when intentions unknown
180 Currently only considered during climbout and breaks when user turns (MEDIUM).
181
182 GetPos() of the AI planes is called erratically - either too much or not enough. (MINOR)
183
184 GO-AROUND is instructed very late at < 12s to landing - possibly make more dependent on chance of rwy clearing before landing (FEATURE)
185
186 Need to make clear when TowerPlaneRecs do or don't get deleted in RemoveFromCircuitList etc. (MINOR until I misuse it - then CRITICAL!)
187
188 FGTower::RemoveAllUserDialogOptions() really ought to be replaced by an ATCDialog::clear_entries() function. (MINOR - efficiency).
189
190 At the moment planes in the lists are not guaranteed to always have a sensible ETA - it should be set as part of AddList functions, and lists should only be accessed this way. (FAIRLY MAJOR). 
191 *******************************************/
192
193 FGTower::FGTower() :
194         separateGround(true),
195         ground(0)
196 {
197         ATCmgr = globals->get_ATC_mgr();
198         
199         _type = TOWER;
200         
201         // Init the property nodes - TODO - need to make sure we're getting surface winds.
202         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
203         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
204         
205         update_count = 0;
206         update_count_max = 15;
207         
208         holdListItr = holdList.begin();
209         appListItr = appList.begin();
210         depListItr = depList.begin();
211         rwyListItr = rwyList.begin();
212         circuitListItr = circuitList.begin();
213         trafficListItr = trafficList.begin();
214         vacatedListItr = vacatedList.begin();
215         
216         freqClear = true;
217         
218         timeSinceLastDeparture = 9999;
219         departed = false;
220         
221         nominal_downwind_leg_pos = 1000.0;
222         nominal_base_leg_pos = -1000.0;
223         // TODO - set nominal crosswind leg pos based on minimum distance from takeoff end of rwy.
224         
225         _departureControlled = false;
226 }
227
228 FGTower::~FGTower() {
229         if(!separateGround) {
230                 delete ground;
231         }
232 }
233
234 void FGTower::Init() {
235         //cout << "Initialising tower " << ident << '\n';
236         
237         // Pointers to user's position
238         user_lon_node = fgGetNode("/position/longitude-deg", true);
239         user_lat_node = fgGetNode("/position/latitude-deg", true);
240         user_elev_node = fgGetNode("/position/altitude-ft", true);
241         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
242         
243         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
244         // I'll punt the startup issue for now though!!!
245         rwyOccupied = false;
246         
247         // Setup the ground control at this airport
248         AirportATC a;
249         //cout << "Tower ident = " << ident << '\n';
250         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
251                 if(a.ground_freq) {             // Ground control
252                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
253                         separateGround = true;
254                         if(ground == NULL) {
255                                 // Something has gone wrong :-(
256                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
257                                 ground = new FGGround(ident);
258                                 separateGround = false;
259                                 ground->Init();
260                                 if(_display) {
261                                         ground->SetDisplay();
262                                 } else {
263                                         ground->SetNoDisplay();
264                                 }
265                         }
266                 } else {
267                         // Initialise ground anyway to do the shortest path stuff!
268                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
269                         ground = new FGGround(ident);
270                         separateGround = false;
271                         ground->Init();
272                         if(_display) {
273                                 ground->SetDisplay();
274                         } else {
275                                 ground->SetNoDisplay();
276                         }
277                 }
278         } else {
279                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
280                 // Initialise ground anyway to avoid segfault later
281                 ground = new FGGround(ident);
282                 separateGround = false;
283                 ground->Init();
284                 if(_display) {
285                         ground->SetDisplay();
286                 } else {
287                         ground->SetNoDisplay();
288                 }
289         }
290         
291         // TODO - attempt to get a departure control pointer to see if we need to hand off departing traffic to departure.
292         
293         // Get the airport elevation
294         aptElev = fgGetAirportElev(ident.c_str());
295         
296         // TODO - this function only assumes one active rwy.
297         DoRwyDetails();
298         
299         // TODO - this currently assumes only one active runway.
300         rwyOccupied = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
301         if(rwyOccupied) {
302                 //cout << "User found on active runway\n";
303                 // Assume the user is started at the threshold ready to take-off
304                 TowerPlaneRec* t = new TowerPlaneRec;
305                 t->plane.callsign = fgGetString("/sim/user/callsign");
306                 t->plane.type = GA_SINGLE;      // FIXME - hardwired!!
307                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
308                 t->landingType = AIP_LT_UNKNOWN;
309                 t->leg = TAKEOFF_ROLL;
310                 t->isUser = true;
311                 t->planePtr = NULL;
312                 t->clearedToTakeOff = true;
313                 rwyList.push_back(t);
314                 rwyListItr = rwyList.begin();
315                 departed = false;
316         } else {
317                 //cout << "User not on active runway\n";
318                 // For now assume that this means the user is not at the airport and is in the air.
319                 // TODO FIXME - this will break when user starts on apron, at hold short, etc.
320                 if(!OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0))) {
321                         //cout << ident << "  ADD 0\n";
322                         current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
323                 }
324         }
325 }
326
327 void FGTower::Update(double dt) {
328         //cout << "T" << endl;
329         // Each time step, what do we need to do?
330         // We need to go through the list of outstanding requests and acknowedgements
331         // and process at least one of them.
332         // We need to go through the list of planes under our control and check if
333         // any need to be addressed.
334         // We need to check for planes not under our control coming within our 
335         // control area and address if necessary.
336         
337         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
338         
339         // Sort the arriving planes
340         
341         /*
342         if(ident == "KEMT") {
343                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
344         }
345         */
346         //if(ident == "EGNX") cout << display << '\n';
347         
348         if(departed != false) {
349                 timeSinceLastDeparture += dt;
350                 //if(ident == "KEMT") 
351                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
352         }
353         
354         //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n'; 
355         if(respond) {
356                 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
357                 Respond();
358                 respond = false;
359                 responseReqd = false;
360         }
361         
362         // Calculate the eta of each plane to the threshold.
363         // For ground traffic this is the fastest they can get there.
364         // For air traffic this is the middle approximation.
365         if(update_count == 1) {
366                 doThresholdETACalc();
367         }
368         
369         // Order the list of traffic as per expected threshold use and flag any conflicts
370         if(update_count == 2) {
371                 //bool conflicts = doThresholdUseOrder();
372                 doThresholdUseOrder();
373         }
374         
375         // sortConficts() !!!
376         
377         if(update_count == 4) {
378                 CheckHoldList(dt);
379         }
380         
381         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
382         if(rwyList.size()) {
383                 rwyOccupied = true;
384         } else {
385                 rwyOccupied = false;
386         }
387         
388         if(update_count == 5 && rwyOccupied) {
389                 CheckRunwayList(dt);
390         }
391                 
392         if(update_count == 6) {
393                 CheckCircuitList(dt);
394         }
395         
396         if(update_count == 7) {
397                 CheckApproachList(dt);
398         }
399         
400         if(update_count == 8) {
401                 CheckDepartureList(dt);
402         }
403         
404         // TODO - do one plane from the departure list and set departed = false when out of consideration
405         
406         //doCommunication();
407         
408         if(!separateGround) {
409                 // The display stuff might have to get more clever than this when not separate 
410                 // since the tower and ground might try communicating simultaneously even though
411                 // they're mean't to be the same contoller/frequency!!
412                 // We could also get rid of this by overloading FGATC's Set(No)Display() functions.
413                 if(_display) {
414                         ground->SetDisplay();
415                 } else {
416                         ground->SetNoDisplay();
417                 }
418                 ground->Update(dt);
419         }
420         
421         ++update_count;
422         // How big should ii get - ie how long should the update cycle interval stretch?
423         if(update_count >= update_count_max) {
424                 update_count = 0;
425         }
426         
427         // Call the base class update for the response time handling.
428         FGATC::Update(dt);
429
430         /*
431         if(ident == "KEMT") {   
432                 // For AI debugging convienience - may be removed
433                 Point3D user_pos;
434                 user_pos.setlon(user_lon_node->getDoubleValue());
435                 user_pos.setlat(user_lat_node->getDoubleValue());
436                 user_pos.setelev(user_elev_node->getDoubleValue());
437                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
438                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
439                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
440                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
441         }
442         */
443         
444         //cout << "Done T" << endl;
445 }
446
447 void FGTower::ReceiveUserCallback(int code) {
448         if(code == (int)USER_REQUEST_VFR_DEPARTURE) {
449                 //cout << "User requested departure\n";
450         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL) {
451                 VFRArrivalContact("USER");
452         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP) {
453                 VFRArrivalContact("USER", FULL_STOP);
454         } else if(code == (int)USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO) {
455                 VFRArrivalContact("USER", TOUCH_AND_GO);
456         } else if(code == (int)USER_REPORT_DOWNWIND) {
457                 ReportDownwind("USER");
458         } else if(code == (int)USER_REPORT_3_MILE_FINAL) {
459                 // For now we'll just call report final instead of report long final to avoid having to alter the response code
460                 ReportFinal("USER");
461         } else if(code == (int)USER_REPORT_RWY_VACATED) {
462                 ReportRunwayVacated("USER");
463         } else if(code == (int)USER_REPORT_GOING_AROUND) {
464                 ReportGoingAround("USER");
465         }
466 }
467
468 // **************** RESPONSE FUNCTIONS ****************
469
470 void FGTower::Respond() {
471         //cout << "\nEntering Respond, responseID = " << responseID << endl;
472         TowerPlaneRec* t = FindPlane(responseID);
473         if(t) {
474                 // This will grow!!!
475                 if(t->vfrArrivalReported && !t->vfrArrivalAcknowledged) {
476                         //cout << "Tower " << ident << " is responding to VFR arrival reported...\n";
477                         // Testing - hardwire straight in for now
478                         string trns = t->plane.callsign;
479                         trns += " ";
480                         trns += name;
481                         trns += " Tower,";
482                         // Should we clear staight in or for downwind entry?
483                         // For now we'll clear straight in if greater than 1km from a line drawn through the threshold perpendicular to the rwy.
484                         // Later on we might check the actual heading and direct some of those to enter on downwind or base.
485                         Point3D op = ortho.ConvertToLocal(t->pos);
486                         if(op.y() < -1000) {
487                                 trns += " Report three mile straight-in runway ";
488                                 t->opType = STRAIGHT_IN;
489                                 if(t->isUser) {
490                                         current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI mile final Runway @RW", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL);
491                                 } else {
492                                         t->planePtr->RegisterTransmission(14);
493                                 }
494                         } else {
495                                 // For now we'll just request reporting downwind.
496                                 // TODO - In real life something like 'report 2 miles southwest right downwind rwy 19R' might be used
497                                 // but I'm not sure how to handle all permutations of which direction to tell to report from yet.
498                                 trns += " Report ";
499                                 //cout << "Responding, rwy.patterDirection is " << rwy.patternDirection << '\n';
500                                 trns += ((rwy.patternDirection == 1) ? "right " : "left ");
501                                 trns += "downwind runway ";
502                                 t->opType = CIRCUIT;
503                                 // leave it in the app list until it gets into pattern though.
504                                 if(t->isUser) {
505                                         current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
506                                 } else {
507                                         t->planePtr->RegisterTransmission(15);
508                                 }
509                         }
510                         trns += ConvertRwyNumToSpokenString(activeRwy);
511                         if(_display) {
512                                 pending_transmission = trns;
513                                 Transmit();
514                         } else {
515                                 //cout << "Not displaying, trns was " << trns << '\n';
516                         }
517                         t->vfrArrivalAcknowledged = true;
518                 } else if(t->downwindReported) {
519                         //cout << "Tower " << ident << " is responding to downwind reported...\n";
520                         ProcessDownwindReport(t);
521                         t->downwindReported = false;
522                 } else if(t->holdShortReported) {
523                         //cout << "Tower " << ident << " is reponding to holdShortReported...\n";
524                         if(t->nextOnRwy) {
525                                 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!!)
526                                         // Do nothing for now - consider acknowloging hold short eventually
527                                 } else {
528                                         ClearHoldingPlane(t);
529                                         t->leg = TAKEOFF_ROLL;
530                                         rwyList.push_back(t);
531                                         rwyListItr = rwyList.begin();
532                                         rwyOccupied = true;
533                                         // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
534                                         // FIXME TODO - FIX THIS!!!
535                                         if(!holdList.empty()) {
536                                                 if(holdListItr == holdList.end()) {
537                                                         holdListItr = holdList.begin();
538                                                 }
539                                                 holdList.erase(holdListItr);
540                                                 holdListItr = holdList.begin();
541                                         }
542                                 }
543                         } else {
544                                 // Tell him to hold and what position he is.
545                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
546                                 string trns = t->plane.callsign;
547                                 trns += " hold position";
548                                 if(_display) {
549                                         pending_transmission = trns;
550                                         Transmit();
551                                 }
552                                 // TODO - add some idea of what traffic is blocking him.
553                         }
554                         t->holdShortReported = false;
555                 } else if(t->finalReported && !(t->finalAcknowledged)) {
556                         //cout << "Tower " << ident << " is responding to finalReported...\n";
557                         bool disp = true;
558                         string trns = t->plane.callsign;
559                         //cout << (t->nextOnRwy ? "Next on rwy " : "Not next!! ");
560                         //cout << (rwyOccupied ? "RWY OCCUPIED!!\n" : "Rwy not occupied\n");
561                         if(t->nextOnRwy && !rwyOccupied && !(t->instructedToGoAround)) {
562                                 if(t->landingType == FULL_STOP) {
563                                         trns += " cleared to land ";
564                                 } else {
565                                         trns += " cleared for the option ";
566                                 }
567                                 // TODO - add winds
568                                 t->clearedToLand = true;
569                                 // Maybe remove report downwind from menu here as well incase user didn't bother to?
570                                 if(t->isUser) {
571                                         //cout << "ADD VACATED B\n";
572                                         // Put going around at the top (and hence default) since that'll be more desperate,
573                                         // or put rwy vacated at the top since that'll be more common?
574                                         current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
575                                         current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
576                                 } else {
577                                         t->planePtr->RegisterTransmission(7);
578                                 }
579                         } else if(t->eta < 20) {
580                                 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
581                                 // runway doesn't clear so no point in calling "continue approach".
582                                 disp = false;
583                         } else {
584                                 trns += " continue approach";
585                                 t->clearedToLand = false;
586                         }
587                         if(_display && disp) {
588                                 pending_transmission = trns;
589                                 Transmit();
590                         }
591                         t->finalAcknowledged = true;
592                 } else if(t->rwyVacatedReported && !(t->rwyVacatedAcknowledged)) {
593                         ProcessRunwayVacatedReport(t);
594                         t->rwyVacatedAcknowledged = true;
595                 }
596         }
597         //freqClear = true;     // FIXME - set this to come true after enough time to render the message
598         _releaseCounter = 0.0;
599         _releaseTime = 5.5;
600         _runReleaseCounter = true;
601         //cout << "Done Respond\n" << endl;
602 }
603
604 void FGTower::ProcessDownwindReport(TowerPlaneRec* t) {
605         int i = 1;
606         int a = 0;      // Count of preceding planes on approach
607         bool cf = false;        // conflicting traffic on final
608         bool cc = false;        // preceding traffic in circuit
609         TowerPlaneRec* tc = NULL;
610         for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
611                 if((*twrItr)->plane.callsign == responseID) break;
612                 tc = *twrItr;
613                 ++i;
614         }
615         if(i > 1) { cc = true; }
616         doThresholdETACalc();
617         TowerPlaneRec* tf = NULL;
618         for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
619                 if((*twrItr)->eta < (t->eta + 45)) {
620                         a++;
621                         tf = *twrItr;
622                         cf = true;
623                         // This should set the flagged plane to be the last conflicting one, and hence the one to follow.
624                         // It ignores the fact that we might have problems slotting into the approach traffic behind it - 
625                         // eventually we'll need some fancy algorithms for that!
626                 }
627         }
628         string trns = t->plane.callsign;
629         trns += " Number ";
630         trns += ConvertNumToSpokenDigits(i + a);
631         // This assumes that the number spoken is landing position, not circuit position, since some of the traffic might be on straight-in final.
632         trns += " ";
633         TowerPlaneRec* tt = NULL;
634         if((i == 1) && rwyList.empty() && (t->nextOnRwy) && (!cf)) {    // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below.
635                 trns += "Cleared to land";      // TODO - clear for the option if appropriate
636                 t->clearedToLand = true;
637                 if(!t->isUser) t->planePtr->RegisterTransmission(7);
638         } else if((i+a) > 1) {
639                 //First set tt to point to the correct preceding plane - final or circuit
640                 if(tc && tf) {
641                         tt = (tf->eta < tc->eta ? tf : tc);
642                 } else if(tc) {
643                         tt = tc;
644                 } else if(tf) {
645                         tt = tf;
646                 } else {
647                         // We should never get here!
648                         SG_LOG(SG_ATC, SG_ALERT, "ALERT - Logic error in FGTower::ProcessDownwindReport");
649                         return;
650                 }
651                 trns += "Follow the ";
652                 string s = tt->plane.callsign;
653                 int p = s.find('-');
654                 s = s.substr(0,p);
655                 trns += s;
656                 if((tt->opType) == CIRCUIT) {
657                         PatternLeg leg;
658                         if(tt->isUser) {
659                                 leg = tt->leg;
660                         } else {
661                                 leg = tt->planePtr->GetLeg();
662                         }
663                         if(leg == FINAL) {
664                                 trns += " on final";
665                         } else if(leg == TURN4) {
666                                 trns += " turning final";
667                         } else if(leg == BASE) {
668                                 trns += " on base";
669                         } else if(leg == TURN3) {
670                                 trns += " turning base";
671                         }
672                 } else {
673                         double miles_out = CalcDistOutMiles(tt);
674                         if(miles_out < 2) {
675                                 trns += " on short final";
676                         } else {
677                                 trns += " on ";
678                                 trns += ConvertNumToSpokenDigits((int)miles_out);
679                                 trns += " mile final";
680                         }
681                 }
682         }
683         if(_display) {
684                 pending_transmission = trns;
685                 Transmit();
686         }
687         if(t->isUser) {
688                 if(t->opType == TTT_UNKNOWN) t->opType = CIRCUIT;
689                 //cout << "ADD VACATED A\n";
690                 // Put going around at the top (and hence default) since that'll be more desperate,
691                 // or put rwy vacated at the top since that'll be more common?
692                 //cout << "ident = " << ident << ", adding go-around option\n";
693                 current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND);
694                 current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED);
695         }
696 }
697
698 void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) {
699         //cout << "Processing rwy vacated...\n";
700         if(t->isUser) current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);
701         string trns = t->plane.callsign;
702         if(separateGround) {
703                 trns += " Contact ground on ";
704                 double f = globals->get_ATC_mgr()->GetFrequency(ident, GROUND) / 100.0; 
705                 char buf[10];
706                 sprintf(buf, "%.2f", f);
707                 trns += buf;
708                 trns += " Good Day";
709                 if(!t->isUser) t->planePtr->RegisterTransmission(5);
710         } else {
711                 // Cop-out!!
712                 trns += " cleared for taxi to general aviation parking";
713                 if(!t->isUser) t->planePtr->RegisterTransmission(6);    // TODO - this is a mega-hack!!
714         }
715         //cout << "trns = " << trns << '\n';
716         if(_display) {
717                 pending_transmission = trns;
718                 Transmit();
719         }
720         RemoveFromRwyList(t->plane.callsign);
721         AddToVacatedList(t);
722         // Maybe we should check that the plane really *has* vacated the runway!
723 }
724
725 // *********** END RESPONSE FUNCTIONS *****************
726
727 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
728 // this should be done prior to calling this function.
729 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
730         //cout << "Entering ClearHoldingPlane..." << endl;
731         // Lets Roll !!!!
732         string trns = t->plane.callsign;
733         //if(departed plane < some threshold in time away) {
734         if(0) {         // FIXME
735         //if(timeSinceLastDeparture <= 60.0 && departed == true) {
736                 trns += " line up";
737                 t->clearedToLineUp = true;
738                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
739         //} else if(arriving plane < some threshold away) {
740         } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
741                 trns += " cleared immediate take-off";
742                 if(trafficList.size()) {
743                         tower_plane_rec_list_iterator trfcItr = trafficList.begin();
744                         trfcItr++;      // At the moment the holding plane should be first in trafficList.
745                         // Note though that this will break if holding planes aren't put in trafficList in the future.
746                         TowerPlaneRec* trfc = *trfcItr;
747                         trns += "... traffic is";
748                         switch(trfc->plane.type) {
749                         case UNKNOWN:
750                                 break;
751                         case GA_SINGLE:
752                                 trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
753                                 break;
754                         case GA_HP_SINGLE:
755                                 trns += " a Piper";
756                                 break;
757                         case GA_TWIN:
758                                 trns += " a King-air";
759                                 break;
760                         case GA_JET:
761                                 trns += " a Learjet";
762                                 break;
763                         case MEDIUM:
764                                 trns += " a Regional";
765                                 break;
766                         case HEAVY:
767                                 trns += " a Heavy";
768                                 break;
769                         case MIL_JET:
770                                 trns += " Military";
771                                 break;
772                         }
773                         //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
774                         if(trfc->opType == STRAIGHT_IN) {
775                                 double miles_out = CalcDistOutMiles(trfc);
776                                 if(miles_out < 2) {
777                                         trns += " on final";
778                                 } else {
779                                         trns += " on ";
780                                         trns += ConvertNumToSpokenDigits((int)miles_out);
781                                         trns += " mile final";
782                                 }
783                         } else if(trfc->opType == CIRCUIT) {
784                                 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
785                                 switch(trfc->leg) {
786                                 case FINAL:
787                                         trns += " on final";
788                                         break;
789                                 case TURN4:
790                                         trns += " turning final";
791                                         break;
792                                 case BASE:
793                                         trns += " on base";
794                                         break;
795                                 case TURN3:
796                                         trns += " turning base";
797                                         break;
798                                 case DOWNWIND:
799                                         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.
800                                         break;
801                                 // And to eliminate compiler warnings...
802                                 case TAKEOFF_ROLL: break;
803                                 case CLIMBOUT:     break;
804                                 case TURN1:        break;
805                                 case CROSSWIND:    break;
806                                 case TURN2:        break;
807                                 case LANDING_ROLL: break;
808                                 case LEG_UNKNOWN:  break;
809                                 }
810                         }
811                 } else {
812                         // By definition there should be some arriving traffic if we're cleared for immediate takeoff
813                         SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
814                 }
815                 t->clearedToTakeOff = true;
816                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
817                 departed = false;
818                 timeSinceLastDeparture = 0.0;
819         } else {
820         //} else if(timeSinceLastDeparture > 60.0 || departed == false) {       // Hack - test for timeSinceLastDeparture should be in lineup block eventually
821                 trns += " cleared for take-off";
822                 // TODO - add traffic is... ?
823                 t->clearedToTakeOff = true;
824                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
825                 departed = false;
826                 timeSinceLastDeparture = 0.0;
827         }
828         if(_display) {
829                 pending_transmission = trns;
830                 Transmit();
831         }
832         //cout << "Done ClearHoldingPlane " << endl;
833 }
834
835
836 // ***************************************************************************************
837 // ********** Functions to periodically check what the various traffic is doing **********
838
839 // Do one plane from the hold list
840 void FGTower::CheckHoldList(double dt) {
841         //cout << "Entering CheckHoldList..." << endl;
842         if(!holdList.empty()) {
843                 //cout << "*holdListItr = " << *holdListItr << endl;
844                 if(holdListItr == holdList.end()) {
845                         holdListItr = holdList.begin();
846                 }
847                 //cout << "*holdListItr = " << *holdListItr << endl;
848                 //Process(*holdListItr);
849                 TowerPlaneRec* t = *holdListItr;
850                 //cout << "t = " << t << endl;
851                 if(t->holdShortReported) {
852                         // NO-OP - leave it to the response handler.
853                 } else {        // not responding to report, but still need to clear if clear
854                         if(t->nextOnRwy) {
855                                 //cout << "departed = " << departed << '\n';
856                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
857                                 if(rwyOccupied) {
858                                         // Do nothing
859                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
860                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
861                                 } else {
862                                         ClearHoldingPlane(t);
863                                         t->leg = TAKEOFF_ROLL;
864                                         rwyList.push_back(t);
865                                         rwyListItr = rwyList.begin();
866                                         rwyOccupied = true;
867                                         holdList.erase(holdListItr);
868                                         holdListItr = holdList.begin();
869                                         if (holdList.empty())
870                                           return;
871                                 }
872                         }
873                         // TODO - rationalise the considerable code duplication above!
874                 }
875                 ++holdListItr;
876         }
877         //cout << "Done CheckHoldList" << endl;
878 }
879
880 // do the ciruit list
881 void FGTower::CheckCircuitList(double dt) {
882         //cout << "Entering CheckCircuitList..." << endl;
883         // Clear the constraints - we recalculate here.
884         base_leg_pos = 0.0;
885         downwind_leg_pos = 0.0;
886         crosswind_leg_pos = 0.0;
887         
888         if(!circuitList.empty()) {      // Do one plane from the circuit
889                 if(circuitListItr == circuitList.end()) {
890                         circuitListItr = circuitList.begin();
891                 }
892                 TowerPlaneRec* t = *circuitListItr;
893                 //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
894                 if(t->isUser) {
895                         t->pos.setlon(user_lon_node->getDoubleValue());
896                         t->pos.setlat(user_lat_node->getDoubleValue());
897                         t->pos.setelev(user_elev_node->getDoubleValue());
898                         //cout << ident <<  ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n';
899                 } else {
900                         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.
901                         t->landingType = t->planePtr->GetLandingOption();
902                         //cout << "AI plane landing option is " << t->landingType << '\n';
903                 }
904                 Point3D tortho = ortho.ConvertToLocal(t->pos);
905                 if(t->isUser) {
906                         // Need to figure out which leg he's on
907                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
908                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
909                         //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
910                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
911                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
912                         if(fabs(ho) < 30) {
913                                 // could be either takeoff, climbout or landing - check orthopos.y
914                                 //cout << "tortho.y = " << tortho.y() << '\n';
915                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
916                                         t->leg = FINAL;
917                                         //cout << "Final\n";
918                                 } else {
919                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
920                                         //cout << "Climbout\n";
921                                         // If it's the user we may be unsure of his/her intentions.
922                                         // (Hopefully the AI planes won't try confusing the sim!!!)
923                                         //cout << "tortho.y = " << tortho.y() << '\n';
924                                         if(t->opType == TTT_UNKNOWN) {
925                                                 if(tortho.y() > 5000) {
926                                                         // 5 km out from threshold - assume it's a departure
927                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
928                                                         // Since we are unknown operation we should be in depList already.
929                                                         //cout << ident << " Removing user from circuitList (TTT_UNKNOWN)\n";
930                                                         circuitListItr = circuitList.erase(circuitListItr);
931                                                         RemoveFromTrafficList(t->plane.callsign);
932                                                         if (circuitList.empty())
933                                                             return;
934                                                 }
935                                         } else if(t->opType == CIRCUIT) {
936                                                 if(tortho.y() > 10000) {
937                                                         // 10 km out - assume the user has abandoned the circuit!!
938                                                         t->opType = OUTBOUND;
939                                                         depList.push_back(t);
940                                                         depListItr = depList.begin();
941                                                         //cout << ident << " removing user from circuitList (CIRCUIT)\n";
942                                                         circuitListItr = circuitList.erase(circuitListItr);
943                                                         if (circuitList.empty())
944                                                           return;
945                                                 }
946                                         }
947                                 }
948                         } else if(fabs(ho) < 60) {
949                                 // turn1 or turn 4
950                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
951                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
952                                         t->leg = TURN1;
953                                         //cout << "Turn1\n";
954                                 } else {
955                                         t->leg = TURN4;
956                                         //cout << "Turn4\n";
957                                 }
958                         } else if(fabs(ho) < 120) {
959                                 // crosswind or base
960                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
961                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
962                                         t->leg = CROSSWIND;
963                                         //cout << "Crosswind\n";
964                                 } else {
965                                         t->leg = BASE;
966                                         //cout << "Base\n";
967                                 }
968                         } else if(fabs(ho) < 150) {
969                                 // turn2 or turn 3
970                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
971                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
972                                         t->leg = TURN2;
973                                         //cout << "Turn2\n";
974                                 } else {
975                                         t->leg = TURN3;
976                                         // Probably safe now to assume the user is flying a circuit
977                                         t->opType = CIRCUIT;
978                                         //cout << "Turn3\n";
979                                 }
980                         } else {
981                                 // downwind
982                                 t->leg = DOWNWIND;
983                                 //cout << "Downwind\n";
984                         }
985                         if(t->leg == FINAL) {
986                                 if(OnActiveRunway(t->pos)) {
987                                         t->leg = LANDING_ROLL;
988                                 }
989                         }
990                 } else {
991                         t->leg = t->planePtr->GetLeg();
992                 }
993                 
994                 // Set the constraints IF this is the first plane in the circuit
995                 // 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!!
996                 if(circuitListItr == circuitList.begin()) {
997                         switch(t->leg) {
998                                 case FINAL:
999                                 // 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.
1000                                 base_leg_pos = tortho.y();
1001                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
1002                                 break;
1003                                 case TURN4:
1004                                 // Fall through to base
1005                                 case BASE:
1006                                 base_leg_pos = tortho.y();
1007                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
1008                                 break;
1009                                 case TURN3:
1010                                 // Fall through to downwind
1011                                 case DOWNWIND:
1012                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
1013                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
1014                                 //cout << "base_leg_pos = " << base_leg_pos;
1015                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
1016                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
1017                                 break;
1018                                 case TURN2:
1019                                 // Fall through to crosswind
1020                                 case CROSSWIND:
1021                                 crosswind_leg_pos = tortho.y();
1022                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1023                                 t->instructedToGoAround = false;
1024                                 break;
1025                                 case TURN1:
1026                                 // Fall through to climbout
1027                                 case CLIMBOUT:
1028                                 // Only use current by constraint as largest
1029                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
1030                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
1031                                 break;
1032                                 case TAKEOFF_ROLL:
1033                                 break;
1034                                 case LEG_UNKNOWN:
1035                                 break;
1036                                 case LANDING_ROLL:
1037                                 break;
1038                                 default:
1039                                 break;
1040                         }
1041                 }
1042                 
1043                 if(t->leg == FINAL && !(t->instructedToGoAround)) {
1044                         doThresholdETACalc();
1045                         doThresholdUseOrder();
1046                         /*
1047                         if(t->isUser) {
1048                                 cout << "Checking USER on final... ";
1049                                 cout << "eta " << t->eta;
1050                                 if(t->clearedToLand) cout << " cleared to land\n";
1051                         }
1052                         */
1053                         //cout << "YES FINAL, t->eta = " << t->eta << ", rwyList.size() = " << rwyList.size() << '\n';
1054                         if(t->landingType == FULL_STOP) {
1055                                 t->opType = INBOUND;
1056                                 //cout << "\n******** SWITCHING TO INBOUND AT POINT AAA *********\n\n";
1057                         }
1058                         if(t->eta < 12 && rwyList.size()) {
1059                                 // TODO - need to make this more sophisticated 
1060                                 // eg. is the plane accelerating down the runway taking off [OK],
1061                                 // or stationary near the start [V. BAD!!].
1062                                 // For now this should stop the AI plane landing on top of the user.
1063                                 string trns = t->plane.callsign;
1064                                 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1065                                 pending_transmission = trns;
1066                                 ImmediateTransmit();
1067                                 t->instructedToGoAround = true;
1068                                 t->clearedToLand = false;
1069                                 // Assume it complies!!!
1070                                 t->opType = CIRCUIT;
1071                                 t->leg = CLIMBOUT;
1072                                 if(t->planePtr) {
1073                                         //cout << "Registering Go-around transmission with AI plane\n";
1074                                         t->planePtr->RegisterTransmission(13);
1075                                 }
1076                         } else if(!t->clearedToLand) {
1077                                 // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
1078                                 // TODO - fix this!
1079                                 bool cf = false;
1080                                 for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1081                                         if((*twrItr)->eta < t->eta) {
1082                                                 cf = true;
1083                                         }
1084                                 }
1085                                 if(t->nextOnRwy && !cf) {
1086                                         if(!rwyList.size()) {
1087                                                 string trns = t->plane.callsign;
1088                                                 trns += " Cleared to land";
1089                                                 pending_transmission = trns;
1090                                                 Transmit();
1091                                                 //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1092                                                 t->clearedToLand = true;
1093                                                 if(!t->isUser) {
1094                                                         t->planePtr->RegisterTransmission(7);
1095                                                 }
1096                                         }
1097                                 } else {
1098                                         //if(t->isUser) cout << "Not next\n";
1099                                 }
1100                         }
1101                 } else if(t->leg == LANDING_ROLL) {
1102                         //cout << t->plane.callsign << " has landed - adding to rwyList\n";
1103                         rwyList.push_front(t);
1104                         // TODO - if(!clearedToLand) shout something!!
1105                         t->clearedToLand = false;
1106                         RemoveFromTrafficList(t->plane.callsign);
1107                         if(t->isUser) {
1108                                 t->opType = TTT_UNKNOWN;
1109                         }       // TODO - allow the user to specify opType via ATC menu
1110                         //cout << ident << " Removing " << t->plane.callsign << " from circuitList..." << endl;
1111                         circuitListItr = circuitList.erase(circuitListItr);
1112                         if(circuitListItr == circuitList.end() ) {
1113                                 circuitListItr = circuitList.begin();
1114                                 // avoid increment of circuitListItr (would increment to second element, or crash if no element left)
1115                                 return;
1116                         }
1117                 }
1118                 ++circuitListItr;
1119         }
1120         //cout << "Done CheckCircuitList" << endl;
1121 }
1122
1123 // 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!!
1124 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
1125 // (However, at the moment there should only be one airplane on the rwy at once, until we
1126 // start allowing planes to line up whilst previous arrival clears the rwy.)
1127 void FGTower::CheckRunwayList(double dt) {
1128         //cout << "Entering CheckRunwayList..." << endl;
1129         if(rwyOccupied) {
1130                 if(!rwyList.size()) {
1131                         rwyOccupied = false;
1132                 } else {
1133                         rwyListItr = rwyList.begin();
1134                         TowerPlaneRec* t = *rwyListItr;
1135                         if(t->isUser) {
1136                                 t->pos.setlon(user_lon_node->getDoubleValue());
1137                                 t->pos.setlat(user_lat_node->getDoubleValue());
1138                                 t->pos.setelev(user_elev_node->getDoubleValue());
1139                         } else {
1140                                 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.
1141                         }
1142                         bool on_rwy = OnActiveRunway(t->pos);
1143                         if(!on_rwy) {
1144                                 // TODO - for all of these we need to check what the user is *actually* doing!
1145                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
1146                                         //cout << "Tower " << ident << " is removing plane " << t->plane.callsign << " from rwy list (vacated)\n";
1147                                         //cout << "Size of rwylist was " << rwyList.size() << '\n';
1148                                         //cout << "Size of vacatedList was " << vacatedList.size() << '\n';
1149                                         RemoveFromRwyList(t->plane.callsign);
1150                                         AddToVacatedList(t);
1151                                         //cout << "Size of rwylist is " << rwyList.size() << '\n';
1152                                         //cout << "Size of vacatedList is " << vacatedList.size() << '\n';
1153                                         // At the moment we wait until Runway Vacated is reported by the plane before telling to contact ground etc.
1154                                         // It's possible we could be a bit more proactive about this.
1155                                 } else if(t->opType == OUTBOUND) {
1156                                         depList.push_back(t);
1157                                         depListItr = depList.begin();
1158                                         rwyList.pop_front();
1159                                         departed = true;
1160                                         timeSinceLastDeparture = 0.0;
1161                                 } else if(t->opType == CIRCUIT) {
1162                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1163                                         circuitList.push_back(t);
1164                                         circuitListItr = circuitList.begin();
1165                                         AddToTrafficList(t);
1166                                         rwyList.pop_front();
1167                                         departed = true;
1168                                         timeSinceLastDeparture = 0.0;
1169                                 } else if(t->opType == TTT_UNKNOWN) {
1170                                         depList.push_back(t);
1171                                         depListItr = depList.begin();
1172                                         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1173                                         circuitList.push_back(t);
1174                                         circuitListItr = circuitList.begin();
1175                                         AddToTrafficList(t);
1176                                         rwyList.pop_front();
1177                                         departed = true;
1178                                         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.
1179                                 } else {
1180                                         // HELP - we shouldn't ever get here!!!
1181                                 }
1182                         }
1183                 }
1184         }
1185         //cout << "Done CheckRunwayList" << endl;
1186 }
1187
1188 // Do one plane from the approach list
1189 void FGTower::CheckApproachList(double dt) {
1190         //cout << "CheckApproachList called for " << ident << endl;
1191         //cout << "AppList.size is " << appList.size() << endl;
1192         if(!appList.empty()) {
1193                 if(appListItr == appList.end()) {
1194                         appListItr = appList.begin();
1195                 }
1196                 TowerPlaneRec* t = *appListItr;
1197                 //cout << "t = " << t << endl;
1198                 //cout << "Checking " << t->plane.callsign << endl;
1199                 if(t->isUser) {
1200                         t->pos.setlon(user_lon_node->getDoubleValue());
1201                         t->pos.setlat(user_lat_node->getDoubleValue());
1202                         t->pos.setelev(user_elev_node->getDoubleValue());
1203                 } else {
1204                         // TODO - set/update the position if it's an AI plane
1205                 }
1206                 doThresholdETACalc();   // We need this here because planes in the lists are not guaranteed to *always* have the correct ETA
1207                 //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n';
1208                 if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
1209                         // TODO - need to make this more sophisticated 
1210                         // eg. is the plane accelerating down the runway taking off [OK],
1211                         // or stationary near the start [V. BAD!!].
1212                         // For now this should stop the AI plane landing on top of the user.
1213                         string trns = t->plane.callsign;
1214                         trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
1215                         pending_transmission = trns;
1216                         ImmediateTransmit();
1217                         t->instructedToGoAround = true;
1218                         t->clearedToLand = false;
1219                         t->nextOnRwy = false;   // But note this is recalculated so don't rely on it
1220                         // Assume it complies!!!
1221                         t->opType = CIRCUIT;
1222                         t->leg = CLIMBOUT;
1223                         if(!t->isUser) {
1224                                 if(t->planePtr) {
1225                                         //cout << "Registering Go-around transmission with AI plane\n";
1226                                         t->planePtr->RegisterTransmission(13);
1227                                 }
1228                         } else {
1229                                 // TODO - add Go-around ack to comm options,
1230                                 // remove report rwy vacated. (possibly).
1231                         }
1232                 } else if(t->eta < 90 && !t->clearedToLand) {
1233                         //doThresholdETACalc();
1234                         doThresholdUseOrder();
1235                         // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work
1236                         // TODO - fix this!
1237                         bool cf = false;
1238                         for(tower_plane_rec_list_iterator twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1239                                 if((*twrItr)->eta < t->eta) {
1240                                         cf = true;
1241                                 }
1242                         }
1243                         if(t->nextOnRwy && !cf) {
1244                                 if(!rwyList.size()) {
1245                                         string trns = t->plane.callsign;
1246                                         trns += " Cleared to land";
1247                                         pending_transmission = trns;
1248                                         Transmit();
1249                                         //if(t->isUser) cout << "Transmitting cleared to Land!!!\n";
1250                                         t->clearedToLand = true;
1251                                         if(!t->isUser) {
1252                                                 t->planePtr->RegisterTransmission(7);
1253                                         }
1254                                 }
1255                         } else {
1256                                 //if(t->isUser) cout << "Not next\n";
1257                         }
1258                 }
1259                 
1260                 // Check for landing...
1261                 bool landed = false;
1262                 if(!t->isUser) {
1263                         if(t->planePtr) {
1264                                 if(t->planePtr->GetLeg() == LANDING_ROLL) {
1265                                         landed = true;
1266                                 }
1267                         } else {
1268                                 SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!");
1269                         }
1270                 } else {        // user
1271                         if(OnActiveRunway(t->pos)) {
1272                                 landed = true;
1273                         }
1274                 }
1275                 
1276                 if(landed) {
1277                         // Duplicated in CheckCircuitList - must be able to rationalise this somehow!
1278                         //cout << "A " << t->plane.callsign << " has landed, adding to rwyList...\n";
1279                         rwyList.push_front(t);
1280                         // TODO - if(!clearedToLand) shout something!!
1281                         t->clearedToLand = false;
1282                         RemoveFromTrafficList(t->plane.callsign);
1283                         //if(t->isUser) {
1284                                 //      t->opType = TTT_UNKNOWN;
1285                         //}     // TODO - allow the user to specify opType via ATC menu
1286                         appListItr = appList.erase(appListItr);
1287                         if(appListItr == appList.end() ) {
1288                                 appListItr = appList.begin();
1289                         }
1290                         if (appList.empty())
1291                           return;
1292
1293                 }
1294                 
1295                 ++appListItr;
1296         }
1297         //cout << "Done" << endl;
1298 }
1299
1300 // Do one plane from the departure list
1301 void FGTower::CheckDepartureList(double dt) {
1302         if(!depList.empty()) {
1303                 if(depListItr == depList.end()) {
1304                         depListItr = depList.begin();
1305                 }
1306                 TowerPlaneRec* t = *depListItr;
1307                 //cout << "Dep list, checking " << t->plane.callsign;
1308                 
1309                 double distout; // meters
1310                 if(t->isUser) distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
1311                 else distout = dclGetHorizontalSeparation(Point3D(lon, lat, elev), t->planePtr->GetPos());
1312                 //cout << " distout = " << distout << '\n';
1313                 if(distout > 10000) {
1314                         string trns = t->plane.callsign;
1315                         trns += " You are now clear of my airspace, good day";
1316                         pending_transmission = trns;
1317                         Transmit();
1318                         if(t->isUser) {
1319                                 // Change the communication options
1320                                 RemoveAllUserDialogOptions();
1321                                 //cout << "ADD A\n";
1322                                 current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI miles @CD of the airport for full stop with ATIS", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP);
1323                         } else {
1324                                 // Send a clear-of-airspace signal
1325                                 // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals).
1326                         }
1327                         RemovePlane(t->plane.callsign);
1328                 } else {
1329                         ++depListItr;
1330                 }
1331         }
1332 }
1333
1334 // ********** End periodic check functions ***********************************************
1335 // ***************************************************************************************
1336
1337
1338 // Remove all dialog options for this tower.
1339 void FGTower::RemoveAllUserDialogOptions() {
1340         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_DEPARTURE, TOWER);
1341         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
1342         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
1343         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
1344         current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
1345         current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
1346         current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
1347         current_atcdialog->remove_entry(ident, USER_REPORT_GOING_AROUND, TOWER);        
1348 }
1349
1350 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
1351 // plus the constraint position as a rwy orientated orthopos (meters)
1352 bool FGTower::GetCrosswindConstraint(double& cpos) {
1353         if(crosswind_leg_pos != 0.0) {
1354                 cpos = crosswind_leg_pos;
1355                 return(true);
1356         } else {
1357                 cpos = 0.0;
1358                 return(false);
1359         }
1360 }
1361 bool FGTower::GetDownwindConstraint(double& dpos) {
1362         if(fabs(downwind_leg_pos) > nominal_downwind_leg_pos) {
1363                 dpos = downwind_leg_pos;
1364                 return(true);
1365         } else {
1366                 dpos = 0.0;
1367                 return(false);
1368         }
1369 }
1370 bool FGTower::GetBaseConstraint(double& bpos) {
1371         if(base_leg_pos < nominal_base_leg_pos) {
1372                 bpos = base_leg_pos;
1373                 return(true);
1374         } else {
1375                 bpos = nominal_base_leg_pos;
1376                 return(false);
1377         }
1378 }
1379
1380
1381 // Figure out which runways are active.
1382 // For now we'll just be simple and do one active runway - eventually this will get much more complex
1383 // This is a private function - public interface to the results of this is through GetActiveRunway
1384 void FGTower::DoRwyDetails() {
1385         //cout << "GetRwyDetails called" << endl;
1386         
1387         // Based on the airport-id and wind get the active runway
1388         
1389         //wind
1390         double hdg = wind_from_hdg->getDoubleValue();
1391         double speed = wind_speed_knots->getDoubleValue();
1392         hdg = (speed == 0.0 ? 270.0 : hdg);
1393         //cout << "Heading = " << hdg << '\n';
1394         
1395         FGRunway runway;
1396         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
1397         if(rwyGood) {
1398                 //cout << "RUNWAY GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOD\n";
1399                 activeRwy = runway._rwy_no;
1400                 rwy.rwyID = runway._rwy_no;
1401                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
1402                 
1403                 // Get the threshold position
1404                 double other_way = runway._heading - 180.0;
1405                 while(other_way <= 0.0) {
1406                         other_way += 360.0;
1407                 }
1408         // move to the +l end/center of the runway
1409                 //cout << "Runway center is at " << runway._lon << ", " << runway._lat << '\n';
1410         Point3D origin = Point3D(runway._lon, runway._lat, aptElev);
1411                 Point3D ref = origin;
1412         double tshlon, tshlat, tshr;
1413                 double tolon, tolat, tor;
1414                 rwy.length = runway._length * SG_FEET_TO_METER;
1415                 rwy.width = runway._width * SG_FEET_TO_METER;
1416         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
1417                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
1418         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway._heading, 
1419                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
1420                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
1421                 // now copy what we need out of runway into rwy
1422         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
1423                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
1424                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
1425                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
1426                 rwy.hdg = runway._heading;
1427                 // Set the projection for the local area based on this active runway
1428                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
1429                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
1430                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
1431                 
1432                 // Set the pattern direction
1433                 // TODO - we'll check for a facilities file with this in eventually - for now assume left traffic except
1434                 // for certain circumstances (RH parallel rwy).
1435                 rwy.patternDirection = -1;              // Left
1436                 if(rwy.rwyID.size() == 3) {
1437                         rwy.patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1);
1438                 }
1439                 //cout << "Doing details, rwy.patterDirection is " << rwy.patternDirection << '\n';
1440         } else {
1441                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
1442                 activeRwy = "NN";
1443         }
1444 }
1445
1446
1447 // Figure out if a given position lies on the active runway
1448 // Might have to change when we consider more than one active rwy.
1449 bool FGTower::OnActiveRunway(const Point3D& pt) {
1450         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
1451         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
1452         Point3D xyp = ortho.ConvertToLocal(pt);
1453         
1454         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
1455         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
1456
1457         double rlen = rwy.length/2.0 + 5.0;
1458         double rwidth = rwy.width/2.0;
1459         double ldiff = fabs(xyp.y() - xyc.y());
1460         double wdiff = fabs(xyp.x() - xyc.x());
1461
1462         return((ldiff < rlen) && (wdiff < rwidth));
1463 }       
1464
1465
1466 // Figure out if a given position lies on any runway or not
1467 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
1468 bool FGTower::OnAnyRunway(const Point3D& pt) {
1469         ATCData ad;
1470         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
1471         if(dist < 0.0) {
1472                 return(false);
1473         }
1474         // Based on the airport-id, go through all the runways and check for a point in them
1475         
1476         // TODO - do we actually need to search for the airport - surely we already know our ident and
1477         // can just search runways of our airport???
1478         //cout << "Airport ident is " << ad.ident << '\n';
1479         FGRunway runway;
1480         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
1481         if(!rwyGood) {
1482                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
1483         }
1484         bool on = false;
1485         while(runway._id == ad.ident) {         
1486                 on = OnRunway(pt, runway);
1487                 //cout << "Runway " << runway._rwy_no << ": On = " << (on ? "true\n" : "false\n");
1488                 if(on) return(true);
1489                 globals->get_runways()->next(&runway);          
1490         }
1491         return(on);
1492 }
1493
1494
1495 // Returns true if successful
1496 bool FGTower::RemoveFromTrafficList(const string& id) {
1497         tower_plane_rec_list_iterator twrItr;
1498         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1499                 TowerPlaneRec* tpr = *twrItr;
1500                 if(tpr->plane.callsign == id) {
1501                         trafficList.erase(twrItr);
1502                         trafficListItr = trafficList.begin();
1503                         return(true);
1504                 }
1505         }       
1506         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1507         return(false);
1508 }
1509
1510
1511 // Returns true if successful
1512 bool FGTower::RemoveFromAppList(const string& id) {
1513         tower_plane_rec_list_iterator twrItr;
1514         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1515                 TowerPlaneRec* tpr = *twrItr;
1516                 if(tpr->plane.callsign == id) {
1517                         appList.erase(twrItr);
1518                         appListItr = appList.begin();
1519                         return(true);
1520                 }
1521         }       
1522         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from appList in FGTower");
1523         return(false);
1524 }
1525
1526 // Returns true if successful
1527 bool FGTower::RemoveFromRwyList(const string& id) {
1528         tower_plane_rec_list_iterator twrItr;
1529         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
1530                 TowerPlaneRec* tpr = *twrItr;
1531                 if(tpr->plane.callsign == id) {
1532                         rwyList.erase(twrItr);
1533                         rwyListItr = rwyList.begin();
1534                         return(true);
1535                 }
1536         }       
1537         //SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from rwyList in FGTower");
1538         return(false);
1539 }
1540
1541
1542 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1543 // and set nextOnRwy if so.
1544 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1545 // For planes holding they are put in the first position with time to go, and the return value is
1546 // true if in the first position (nextOnRwy) and false otherwise.
1547 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1548 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1549         //cout << "ADD: " << trafficList.size();
1550         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1551         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.
1552         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
1553         bool conflict = false;
1554         double lastETA = 0.0;
1555         bool firstTime = true;
1556         // FIXME - make this more robust for different plane types eg. light following heavy.
1557         tower_plane_rec_list_iterator twrItr;
1558         //twrItr = trafficList.begin();
1559         //while(1) {
1560         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1561                 //if(twrItr == trafficList.end()) {
1562                 //      cout << "  END  ";
1563                 //      trafficList.push_back(t);
1564                 //      return(holding ? firstTime : conflict);
1565                 //} else {
1566                         TowerPlaneRec* tpr = *twrItr;
1567                         if(holding) {
1568                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1569                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1570                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
1571                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1572                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1573                                 // and if not needs time to clear the rwy anyway.
1574                                 if(tpr->eta  - lastETA > slot_time) {
1575                                         t->nextOnRwy = firstTime;
1576                                         trafficList.insert(twrItr, t);
1577                                         //cout << "\tH\t" << trafficList.size() << '\n';
1578                                         return(firstTime);
1579                                 }
1580                                 firstTime = false;
1581                         } else {
1582                                 if(t->eta < tpr->eta) {
1583                                         // Ugg - this one's tricky.
1584                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1585                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1586                                                 if(tpr->nextOnRwy) {
1587                                                         tpr->nextOnRwy = false;
1588                                                         t->nextOnRwy = true;
1589                                                 }
1590                                                 trafficList.insert(twrItr, t);
1591                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1592                                                 conflict = true;
1593                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1594                                                 if(tpr->nextOnRwy) {
1595                                                         tpr->nextOnRwy = false;
1596                                                         t->nextOnRwy = true;
1597                                                 }
1598                                                 trafficList.insert(twrItr, t);
1599                                         }
1600                                         //cout << "\tC\t" << trafficList.size() << '\n';
1601                                         return(conflict);
1602                                 }
1603                         }
1604                 //}
1605                 //++twrItr;
1606         }
1607         // If we get here we must be at the end of the list, or maybe the list is empty.
1608         if(!trafficList.size()) {
1609                 t->nextOnRwy = true;
1610                 // conflict and firstTime should be false and true respectively in this case anyway.
1611         } else {
1612                 t->nextOnRwy = false;
1613         }
1614         trafficList.push_back(t);
1615         //cout << "\tE\t" << trafficList.size() << endl;
1616         return(holding ? firstTime : conflict);
1617 }
1618
1619 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1620 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1621 // Safe to add a plane that is already in - planes with the same callsign are not added.
1622 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1623         if(!t) {
1624                 //cout << "**********************************************\n";
1625                 //cout << "AddToCircuitList called with NULL pointer!!!!!\n";
1626                 //cout << "**********************************************\n";
1627                 return false;
1628         }
1629         //cout << "ADD: " << circuitList.size();
1630         //cout << ident << " AddToCircuitList called for " << t->plane.callsign << ", currently size = " << circuitList.size() << endl;
1631         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.
1632         bool conflict = false;
1633         tower_plane_rec_list_iterator twrItr;
1634         // First check if the plane is already in the list
1635         //cout << "A" << endl;
1636         //cout << "Checking whether " << t->plane.callsign << " is already in circuit list..." << endl;
1637         //cout << "B" << endl;
1638         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1639                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1640                         //cout << "In list - returning...\n";
1641                         return false;
1642                 }
1643         }
1644         //cout << "Not in list - adding..." << endl;
1645         
1646         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1647                 TowerPlaneRec* tpr = *twrItr;
1648                 //cout << tpr->plane.callsign << " eta is " << tpr->eta << '\n';
1649                 //cout << "New eta is " << t->eta << '\n';              
1650                 if(t->eta < tpr->eta) {
1651                         // Ugg - this one's tricky.
1652                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1653                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1654                                 circuitList.insert(twrItr, t);
1655                                 circuitListItr = circuitList.begin();
1656                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1657                                 conflict = true;
1658                                 // HACK - just add anyway for now and flag conflict.
1659                                 circuitList.insert(twrItr, t);
1660                                 circuitListItr = circuitList.begin();
1661                         }
1662                         //cout << "\tC\t" << circuitList.size() << '\n';
1663                         return(conflict);
1664                 }
1665         }
1666         // If we get here we must be at the end of the list, or maybe the list is empty.
1667         //cout << ident << " adding " << t->plane.callsign << " to circuitList" << endl;
1668         circuitList.push_back(t);       // TODO - check the separation with the preceding plane for the conflict flag.
1669         circuitListItr = circuitList.begin();
1670         //cout << "\tE\t" << circuitList.size() << endl;
1671         return(conflict);
1672 }
1673
1674 // Add to vacated list only if not already present
1675 void FGTower::AddToVacatedList(TowerPlaneRec* t) {
1676         tower_plane_rec_list_iterator twrItr;
1677         bool found = false;
1678         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
1679                 if((*twrItr)->plane.callsign == t->plane.callsign) {
1680                         found = true;
1681                 }
1682         }
1683         if(found) return;
1684         vacatedList.push_back(t);
1685 }
1686
1687
1688 // Calculate the eta of a plane to the threshold.
1689 // For ground traffic this is the fastest they can get there.
1690 // For air traffic this is the middle approximation.
1691 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1692         // For now we'll be very crude and hardwire expected speeds to C172-like values
1693         // The speeds below are specified in knots IAS and then converted to m/s
1694         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1695         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1696         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1697         
1698         //if(printout) {
1699         //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1700         //cout << (tpr->isUser ? "USER\n" : "AI\n");
1701         //cout << flush;
1702         //}
1703         
1704         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1705         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1706         
1707         Point3D op = ortho.ConvertToLocal(tpr->pos);
1708         //if(printout) {
1709         //if(!tpr->isUser) cout << "Orthopos is " << op.x() << ", " << op.y() << ' ';
1710         //cout << "opType is " << tpr->opType << '\n';
1711         //}
1712         double dist_out_m = op.y();
1713         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
1714         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1715         
1716         if(tpr->opType == STRAIGHT_IN || tpr->opType == INBOUND) {
1717                 //cout << "CASE 1\n";
1718                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1719                 if(dist_to_go_m < 1000) {
1720                         tpr->eta = dist_to_go_m / final_ias;
1721                 } else {
1722                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1723                 }
1724         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1725                 //cout << "CASE 2\n";
1726                 // It's complicated - depends on if base leg is delayed or not
1727                 //if(printout) {
1728                 //cout << "Leg = " << tpr->leg << '\n';
1729                 //}
1730                 if(tpr->leg == LANDING_ROLL) {
1731                         tpr->eta = 0;
1732                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1733                         //cout << "dist_out_m = " << dist_out_m << '\n';
1734                         tpr->eta = fabs(dist_out_m) / final_ias;
1735                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1736                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1737                 } else {
1738                         // Need to calculate where base leg is likely to be
1739                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1740                         // 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
1741                         double nominal_base_dist_out_m = -1000;
1742                         double current_base_dist_out_m;
1743                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1744                                 current_base_dist_out_m = nominal_base_dist_out_m;
1745                         }
1746                         //cout << "current_base_dist_out_m = " << current_base_dist_out_m << '\n';
1747                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1748                         double current_dist_across_m;
1749                         if(!GetDownwindConstraint(current_dist_across_m)) {
1750                                 current_dist_across_m = nominal_dist_across_m;
1751                         }
1752                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 700ft agl.
1753                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1754                         //cout << "a = " << tpr->eta << '\n';
1755                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1756                                 tpr->eta += dist_across_m / circuit_ias;
1757                                 //cout << "b = " << tpr->eta << '\n';
1758                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1759                                 //cout << "c = " << tpr->eta << '\n';
1760                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1761                                 //cout << "CROSSWIND calc: ";
1762                                 //cout << tpr->eta << ' ';
1763                                 if(dist_across_m > nominal_dist_across_m) {
1764                                         tpr->eta += dist_across_m / circuit_ias;
1765                                         //cout << "a ";
1766                                 } else {
1767                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1768                                         //cout << "b ";
1769                                 }
1770                                 //cout << tpr->eta << ' ';
1771                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1772                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1773                                 if(dist_out_m > nominal_cross_dist_out_m) {
1774                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1775                                         //cout << "c ";
1776                                 } else {
1777                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1778                                         //cout << "d ";
1779                                 }
1780                                 //cout << tpr->eta << ' ';
1781                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1782                                 if(nominal_dist_across_m > dist_across_m) {
1783                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1784                                         //cout << "e ";
1785                                 } else {
1786                                         // Nothing to add
1787                                         //cout << "f ";
1788                                 }
1789                                 //cout << tpr->eta << '\n';
1790                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1791                         } else {
1792                                 // We've only just started - why not use a generic estimate?
1793                                 tpr->eta = 240.0;
1794                         }
1795                 }
1796                 //if(printout) {
1797                 //      cout << "ETA = " << tpr->eta << '\n';
1798                 //}
1799                 //if(!tpr->isUser) cout << tpr->plane.callsign << '\t' << tpr->eta << '\n';
1800         } else {
1801                 tpr->eta = 99999;
1802         }       
1803 }
1804
1805
1806 // Calculate the distance of a plane to the threshold in meters
1807 // TODO - Modify to calculate flying distance of a plane in the circuit
1808 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1809         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1810 }
1811
1812
1813 // Calculate the distance of a plane to the threshold in miles
1814 // TODO - Modify to calculate flying distance of a plane in the circuit
1815 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1816         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1817 }
1818
1819
1820 // Iterate through all the lists, update the position of, and call CalcETA for all the planes.
1821 void FGTower::doThresholdETACalc() {
1822         //cout << "Entering doThresholdETACalc..." << endl;
1823         tower_plane_rec_list_iterator twrItr;
1824         // Do the approach list first
1825         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1826                 TowerPlaneRec* tpr = *twrItr;
1827                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1828                 //cout << "APP: ";
1829                 CalcETA(tpr);
1830         }       
1831         // Then the circuit list
1832         //cout << "Circuit list size is " << circuitList.size() << '\n';
1833         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1834                 TowerPlaneRec* tpr = *twrItr;
1835                 if(!(tpr->isUser)) tpr->pos = tpr->planePtr->GetPos();
1836                 //cout << "CIRC: ";
1837                 CalcETA(tpr);
1838         }
1839         //cout << "Done doThresholdETCCalc" << endl;
1840 }
1841                 
1842
1843 // Check that the planes in traffic list are correctly ordered,
1844 // that the nearest (timewise) is flagged next on rwy, and return
1845 // true if any threshold use conflicts are detected, false otherwise.
1846 bool FGTower::doThresholdUseOrder() {
1847         //cout << "Entering doThresholdUseOrder..." << endl;
1848         bool conflict = false;
1849         
1850         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1851         // Here's the rather simplistic assumptions we're using:
1852         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1853         // In order of priority for runway use:
1854         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1855         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1856         // and holding planes until a space.
1857         // When calculating if a holding plane can use the runway, time clearance from last departure
1858         // as well as time clearance to next arrival must be considered.
1859         
1860         trafficList.clear();
1861         
1862         tower_plane_rec_list_iterator twrItr;
1863         // Do the approach list first
1864         //if(ident == "KRHV") cout << "A" << flush;
1865         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1866                 TowerPlaneRec* tpr = *twrItr;
1867                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1868                 conflict = AddToTrafficList(tpr);
1869         }       
1870         // Then the circuit list
1871         //if(ident == "KRHV") cout << "C" << flush;
1872         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1873                 TowerPlaneRec* tpr = *twrItr;
1874                 //if(ident == "KRHV") cout << tpr->plane.callsign << '\n';
1875                 conflict = AddToTrafficList(tpr);
1876         }
1877         // And finally the hold list
1878         //cout << "H" << endl;
1879         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1880                 TowerPlaneRec* tpr = *twrItr;
1881                 AddToTrafficList(tpr, true);
1882         }
1883         
1884         
1885         if(0) {
1886         //if(ident == "KRHV") {
1887                 cout << "T\n";
1888                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1889                         TowerPlaneRec* tpr = *twrItr;
1890                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1891                 }
1892                 cout << endl;
1893         }
1894         
1895         //cout << "Done doThresholdUseOrder" << endl;
1896         return(conflict);
1897 }
1898
1899
1900 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1901 // i.e. list_pos = 1 implies next to use runway.
1902 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1903         if(trafficList.size() < list_pos) {
1904                 return(99999);
1905         }
1906
1907         tower_plane_rec_list_iterator twrItr;
1908         twrItr = trafficList.begin();
1909         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1910         TowerPlaneRec* tpr = *twrItr;
1911         CalcETA(tpr, printout);
1912         //cout << "ETA returned = " << tpr->eta << '\n';
1913         return(tpr->eta);
1914 }
1915         
1916
1917 void FGTower::ContactAtHoldShort(const PlaneRec& plane, FGAIPlane* requestee, tower_traffic_type operation) {
1918         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1919         TowerPlaneRec* t = new TowerPlaneRec;
1920         t->plane = plane;
1921         t->planePtr = requestee;
1922         t->holdShortReported = true;
1923         t->clearedToLineUp = false;
1924         t->clearedToTakeOff = false;
1925         t->opType = operation;
1926         t->pos = requestee->GetPos();
1927         
1928         //cout << "Hold Short reported by " << plane.callsign << '\n';
1929         SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1930
1931 /*      
1932         bool next = AddToTrafficList(t, true);
1933         if(next) {
1934                 double teta = GetTrafficETA(2);
1935                 if(teta < 150.0) {
1936                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1937                         //cout << "Reducing response time to request due imminent traffic\n";
1938                 }
1939         } else {
1940         }
1941 */
1942         // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1943
1944         holdList.push_back(t);
1945         
1946         responseReqd = true;
1947 }
1948
1949 // Register the presence of an AI plane at a point where contact would already have been made in real life
1950 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1951 void FGTower::RegisterAIPlane(const PlaneRec& plane, FGAIPlane* ai, const tower_traffic_type& op, const PatternLeg& lg) {
1952         // At the moment this is only going to be tested with inserting an AI plane on downwind
1953         TowerPlaneRec* t = new TowerPlaneRec;
1954         t->plane = plane;
1955         t->planePtr = ai;
1956         t->opType = op;
1957         t->leg = lg;
1958         t->pos = ai->GetPos();
1959         
1960         CalcETA(t);
1961         
1962         if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1963                 AddToCircuitList(t);
1964         } else {
1965                 // FLAG A WARNING
1966         }
1967         
1968         doThresholdUseOrder();
1969 }
1970
1971 void FGTower::DeregisterAIPlane(const string& id) {
1972         RemovePlane(id);
1973 }
1974
1975 // Contact tower for VFR approach
1976 // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo"
1977 // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec.
1978 // opt defaults to AIP_LT_UNKNOWN
1979 void FGTower::VFRArrivalContact(const string& ID, const LandingType& opt) {
1980         //cout << "USER Request Landing Clearance called for ID " << ID << '\n';
1981         
1982         // For now we'll assume that the user is a light plane and can get him/her to join the circuit if necessary.
1983
1984         TowerPlaneRec* t;       
1985         string usercall = fgGetString("/sim/user/callsign");
1986         if(ID == "USER" || ID == usercall) {
1987                 t = FindPlane(usercall);
1988                 if(!t) {
1989                         //cout << "NOT t\n";
1990                         t = new TowerPlaneRec;
1991                         t->isUser = true;
1992                         t->pos.setlon(user_lon_node->getDoubleValue());
1993                         t->pos.setlat(user_lat_node->getDoubleValue());
1994                         t->pos.setelev(user_elev_node->getDoubleValue());
1995                 } else {
1996                         //cout << "IS t\n";
1997                         // Oops - the plane is already registered with this tower - maybe we took off and flew a giant circuit without
1998                         // quite getting out of tower airspace - just ignore for now and treat as new arrival.
1999                         // TODO - Maybe should remove from departure and circuit list if in there though!!
2000                 }
2001         } else {
2002                 // Oops - something has gone wrong - put out a warning
2003                 cout << "WARNING - FGTower::VFRContact(string ID, LandingType lt) called with ID " << ID << " which does not appear to be the user.\n";
2004                 return;
2005         }
2006                 
2007         
2008         // TODO
2009         // Calculate where the plane is in relation to the active runway and it's circuit
2010         // and set the op-type as appropriate.
2011         
2012         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
2013         t->opType = STRAIGHT_IN;
2014         
2015         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
2016         t->plane.callsign = usercall;
2017         
2018         t->vfrArrivalReported = true;
2019         responseReqd = true;
2020         
2021         appList.push_back(t);   // Not necessarily permanent
2022         appListItr = appList.begin();
2023         AddToTrafficList(t);
2024         
2025         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL, TOWER);
2026         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_FULL_STOP, TOWER);
2027         current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER);
2028 }
2029
2030 // landingType defaults to AIP_LT_UNKNOWN
2031 void FGTower::VFRArrivalContact(const PlaneRec& plane, FGAIPlane* requestee, const LandingType& lt) {
2032         //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n';
2033         // Possible hack - assume this plane is new for now - TODO - should check really
2034         TowerPlaneRec* t = new TowerPlaneRec;
2035         t->plane = plane;
2036         t->planePtr = requestee;
2037         t->landingType = lt;
2038         t->pos = requestee->GetPos();
2039         
2040         //cout << "Hold Short reported by " << plane.callsign << '\n';
2041         SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign);
2042         //cout << "VFR arrival contact made by " << plane.callsign << '\n';
2043
2044         // HACK - to get up and running I'm going to assume a staight-in final for now.
2045         t->opType = STRAIGHT_IN;
2046         
2047         t->vfrArrivalReported = true;
2048         responseReqd = true;
2049         
2050         //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n';
2051         appList.push_back(t);   // Not necessarily permanent
2052         appListItr = appList.begin();
2053         //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n';
2054         AddToTrafficList(t);
2055 }
2056
2057 void FGTower::RequestDepartureClearance(const string& ID) {
2058         //cout << "Request Departure Clearance called...\n";
2059 }
2060         
2061 void FGTower::ReportFinal(const string& ID) {
2062         //cout << "Report Final Called at tower " << ident << " by plane " << ID << '\n';
2063         string uid=ID;
2064         if(ID == "USER") {
2065                 uid = fgGetString("/sim/user/callsign");
2066                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2067         }
2068         TowerPlaneRec* t = FindPlane(uid);
2069         if(t) {
2070                 t->finalReported = true;
2071                 t->finalAcknowledged = false;
2072                 if(!(t->clearedToLand)) {
2073                         responseReqd = true;
2074                 } else {
2075                         // possibly respond with wind even if already cleared to land?
2076                         t->finalReported = false;
2077                         t->finalAcknowledged = true;
2078                         // HACK!! - prevents next reporting being misinterpreted as this one.
2079                 }
2080         } else {
2081                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
2082         }
2083 }
2084
2085 void FGTower::ReportLongFinal(const string& ID) {
2086         string uid=ID;
2087         if(ID == "USER") {
2088                 uid = fgGetString("/sim/user/callsign");
2089                 current_atcdialog->remove_entry(ident, USER_REPORT_3_MILE_FINAL, TOWER);
2090         }
2091         TowerPlaneRec* t = FindPlane(uid);
2092         if(t) {
2093                 t->longFinalReported = true;
2094                 t->longFinalAcknowledged = false;
2095                 if(!(t->clearedToLand)) {
2096                         responseReqd = true;
2097                 } // possibly respond with wind even if already cleared to land?
2098         } else {
2099                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportLongFinal(...)");
2100         }
2101 }
2102
2103 //void FGTower::ReportOuterMarker(string ID);
2104 //void FGTower::ReportMiddleMarker(string ID);
2105 //void FGTower::ReportInnerMarker(string ID);
2106
2107 void FGTower::ReportRunwayVacated(const string& ID) {
2108         //cout << "Report Runway Vacated Called at tower " << ident << " by plane " << ID << '\n';
2109         string uid=ID;
2110         if(ID == "USER") {
2111                 uid = fgGetString("/sim/user/callsign");
2112                 current_atcdialog->remove_entry(ident, USER_REPORT_RWY_VACATED, TOWER);
2113         }
2114         TowerPlaneRec* t = FindPlane(uid);
2115         if(t) {
2116                 //cout << "Found it...\n";
2117                 t->rwyVacatedReported = true;
2118                 responseReqd = true;
2119         } else {
2120                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2121                 SG_LOG(SG_ATC, SG_ALERT, "A WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)");
2122                 //cout << "WARNING: Unable to find plane " << ID << " in FGTower::ReportRunwayVacated(...)\n";
2123         }
2124 }
2125
2126 TowerPlaneRec* FGTower::FindPlane(const string& ID) {
2127         //cout << "FindPlane called for " << ID << "...\n";
2128         tower_plane_rec_list_iterator twrItr;
2129         // Do the approach list first
2130         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
2131                 //cout << "appList callsign is " << (*twrItr)->plane.callsign << '\n';
2132                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2133         }       
2134         // Then the circuit list
2135         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
2136                 //cout << "circuitList callsign is " << (*twrItr)->plane.callsign << '\n';
2137                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2138         }
2139         // Then the runway list
2140         //cout << "rwyList.size() is " << rwyList.size() << '\n';
2141         for(twrItr = rwyList.begin(); twrItr != rwyList.end(); twrItr++) {
2142                 //cout << "rwyList callsign is " << (*twrItr)->plane.callsign << '\n';
2143                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2144         }
2145         // The hold list
2146         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
2147                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2148         }
2149         // And finally the vacated list
2150         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end(); twrItr++) {
2151                 //cout << "vacatedList callsign is " << (*twrItr)->plane.callsign << '\n';
2152                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
2153         }
2154         SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
2155         //exit(-1);
2156         return(NULL);
2157 }
2158
2159 void FGTower::RemovePlane(const string& ID) {
2160         //cout << ident << " RemovePlane called for " << ID << '\n';
2161         // We have to be careful here - we want to erase the plane from all lists it is in,
2162         // but we can only delete it once, AT THE END.
2163         TowerPlaneRec* t = NULL;
2164         tower_plane_rec_list_iterator twrItr;
2165         for(twrItr = appList.begin(); twrItr != appList.end();) {
2166                 if((*twrItr)->plane.callsign == ID) {
2167                         t = *twrItr;
2168                         twrItr = appList.erase(twrItr);
2169                         appListItr = appList.begin();
2170                         // HACK: aircraft are sometimes more than once in a list, so we need to
2171                         // remove them all before we can delete the TowerPlaneRec class
2172                         //break;
2173                 } else
2174                         ++twrItr;
2175         }
2176         for(twrItr = depList.begin(); twrItr != depList.end();) {
2177                 if((*twrItr)->plane.callsign == ID) {
2178                         t = *twrItr;
2179                         twrItr = depList.erase(twrItr);
2180                         depListItr = depList.begin();
2181                 } else
2182                         ++twrItr;
2183         }
2184         for(twrItr = circuitList.begin(); twrItr != circuitList.end();) {
2185                 if((*twrItr)->plane.callsign == ID) {
2186                         t = *twrItr;
2187                         twrItr = circuitList.erase(twrItr);
2188                         circuitListItr = circuitList.begin();
2189                 } else
2190                         ++twrItr;
2191         }
2192         for(twrItr = holdList.begin(); twrItr != holdList.end();) {
2193                 if((*twrItr)->plane.callsign == ID) {
2194                         t = *twrItr;
2195                         twrItr = holdList.erase(twrItr);
2196                         holdListItr = holdList.begin();
2197                 } else
2198                         ++twrItr;
2199         }
2200         for(twrItr = rwyList.begin(); twrItr != rwyList.end();) {
2201                 if((*twrItr)->plane.callsign == ID) {
2202                         t = *twrItr;
2203                         twrItr = rwyList.erase(twrItr);
2204                         rwyListItr = rwyList.begin();
2205                 } else
2206                         ++twrItr;
2207         }
2208         for(twrItr = vacatedList.begin(); twrItr != vacatedList.end();) {
2209                 if((*twrItr)->plane.callsign == ID) {
2210                         t = *twrItr;
2211                         twrItr = vacatedList.erase(twrItr);
2212                         vacatedListItr = vacatedList.begin();
2213                 } else
2214                         ++twrItr;
2215         }
2216         for(twrItr = trafficList.begin(); twrItr != trafficList.end();) {
2217                 if((*twrItr)->plane.callsign == ID) {
2218                         t = *twrItr;
2219                         twrItr = trafficList.erase(twrItr);
2220                         trafficListItr = trafficList.begin();
2221                 } else
2222                         ++twrItr;
2223         }
2224         // And finally, delete the record.
2225         delete t;
2226 }
2227
2228 void FGTower::ReportDownwind(const string& ID) {
2229         //cout << "ReportDownwind(...) called\n";
2230         string uid=ID;
2231         if(ID == "USER") {
2232                 uid = fgGetString("/sim/user/callsign");
2233                 current_atcdialog->remove_entry(ident, USER_REPORT_DOWNWIND, TOWER);
2234         }
2235         TowerPlaneRec* t = FindPlane(uid);
2236         if(t) {
2237                 t->downwindReported = true;
2238                 responseReqd = true;
2239                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2240                 // Ideally we might want to do this at the 2 mile report prior to 45 deg entry, but at
2241                 // the moment that would b&gg?r up the constraint position calculations.
2242                 RemoveFromAppList(ID);
2243                 t->leg = DOWNWIND;
2244                 if(t->isUser) {
2245                         t->pos.setlon(user_lon_node->getDoubleValue());
2246                         t->pos.setlat(user_lat_node->getDoubleValue());
2247                         t->pos.setelev(user_elev_node->getDoubleValue());
2248                 } else {
2249                         // ASSERT(t->planePtr != NULL);
2250                         t->pos = t->planePtr->GetPos();
2251                 }
2252                 CalcETA(t);
2253                 AddToCircuitList(t);
2254         } else {
2255                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2256         }
2257 }
2258
2259 void FGTower::ReportGoingAround(const string& ID) {
2260         string uid=ID;
2261         if(ID == "USER") {
2262                 uid = fgGetString("/sim/user/callsign");
2263                 RemoveAllUserDialogOptions();   // TODO - it would be much more efficient if ATCDialog simply had a clear() function!!!
2264                 current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND);
2265         }
2266         TowerPlaneRec* t = FindPlane(uid);
2267         if(t) {
2268                 //t->goAroundReported = true;  // No need to set this until we start responding to it.
2269                 responseReqd = false;   // might change in the future but for now we'll not distract them during the go-around.
2270                 // If the plane is in the app list, remove it and put it in the circuit list instead.
2271                 RemoveFromAppList(ID);
2272                 t->leg = CLIMBOUT;
2273                 if(t->isUser) {
2274                         t->pos.setlon(user_lon_node->getDoubleValue());
2275                         t->pos.setlat(user_lat_node->getDoubleValue());
2276                         t->pos.setelev(user_elev_node->getDoubleValue());
2277                 } else {
2278                         // ASSERT(t->planePtr != NULL);
2279                         t->pos = t->planePtr->GetPos();
2280                 }
2281                 CalcETA(t);
2282                 AddToCircuitList(t);
2283         } else {
2284                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
2285         }
2286 }
2287
2288 string FGTower::GenText(const string& m, int c) {
2289         const int cmax = 300;
2290         //string message;
2291         char tag[4];
2292         char crej = '@';
2293         char mes[cmax];
2294         char dum[cmax];
2295         //char buf[10];
2296         char *pos;
2297         int len;
2298         //FGTransmission t;
2299         string usercall = fgGetString("/sim/user/callsign");
2300         
2301         //transmission_list_type     tmissions = transmissionlist_station[station];
2302         //transmission_list_iterator current   = tmissions.begin();
2303         //transmission_list_iterator last      = tmissions.end();
2304         
2305         //for ( ; current != last ; ++current ) {
2306         //      if ( current->get_code().c1 == code.c1 &&  
2307         //              current->get_code().c2 == code.c2 &&
2308         //          current->get_code().c3 == code.c3 ) {
2309                         
2310                         //if ( ttext ) message = current->get_transtext();
2311                         //else message = current->get_menutext();
2312                         strcpy( &mes[0], m.c_str() ); 
2313                         
2314                         // Replace all the '@' parameters with the actual text.
2315                         int check = 0;  // If mes gets overflowed the while loop can go infinite
2316                         while ( strchr(&mes[0], crej) != NULL  ) {      // ie. loop until no more occurances of crej ('@') found
2317                                 pos = strchr( &mes[0], crej );
2318                                 memmove(&tag[0], pos, 3);
2319                                 tag[3] = '\0';
2320                                 int i;
2321                                 len = 0;
2322                                 for ( i=0; i<cmax; i++ ) {
2323                                         if ( mes[i] == crej ) {
2324                                                 len = i; 
2325                                                 break;
2326                                         }
2327                                 }
2328                                 strncpy( &dum[0], &mes[0], len );
2329                                 dum[len] = '\0';
2330                                 
2331                                 if ( strcmp ( tag, "@ST" ) == 0 )
2332                                         //strcat( &dum[0], tpars.station.c_str() );
2333                                         strcat(&dum[0], ident.c_str());
2334                                 else if ( strcmp ( tag, "@AP" ) == 0 )
2335                                         //strcat( &dum[0], tpars.airport.c_str() );
2336                                         strcat(&dum[0], name.c_str());
2337                                 else if ( strcmp ( tag, "@CS" ) == 0 ) 
2338                                         //strcat( &dum[0], tpars.callsign.c_str() );
2339                                         strcat(&dum[0], usercall.c_str());
2340                                 else if ( strcmp ( tag, "@TD" ) == 0 ) {
2341                                         /*
2342                                         if ( tpars.tdir == 1 ) {
2343                                                 char buf[] = "left";
2344                                                 strcat( &dum[0], &buf[0] );
2345                                         }
2346                                         else {
2347                                                 char buf[] = "right";
2348                                                 strcat( &dum[0], &buf[0] );
2349                                         }
2350                                         */
2351                                 }
2352                                 else if ( strcmp ( tag, "@HE" ) == 0 ) {
2353                                         /*
2354                                         char buf[10];
2355                                         sprintf( buf, "%i", (int)(tpars.heading) );
2356                                         strcat( &dum[0], &buf[0] );
2357                                         */
2358                                 }
2359                                 else if ( strcmp ( tag, "@VD" ) == 0 ) {
2360                                         /*
2361                                         if ( tpars.VDir == 1 ) {
2362                                                 char buf[] = "Descend and maintain";
2363                                                 strcat( &dum[0], &buf[0] );
2364                                         }
2365                                         else if ( tpars.VDir == 2 ) {
2366                                                 char buf[] = "Maintain";
2367                                                 strcat( &dum[0], &buf[0] );
2368                                         }
2369                                         else if ( tpars.VDir == 3 ) {
2370                                                 char buf[] = "Climb and maintain";
2371                                                 strcat( &dum[0], &buf[0] );
2372                                         } 
2373                                         */
2374                                 }
2375                                 else if ( strcmp ( tag, "@AL" ) == 0 ) {
2376                                         /*
2377                                         char buf[10];
2378                                         sprintf( buf, "%i", (int)(tpars.alt) );
2379                                         strcat( &dum[0], &buf[0] );
2380                                         */
2381                                 }
2382                                 else if ( strcmp ( tag, "@MI" ) == 0 ) {
2383                                         char buf[10];
2384                                         //sprintf( buf, "%3.1f", tpars.miles );
2385                                         int dist_miles = (int)dclGetHorizontalSeparation(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())) / 1600;
2386                                         sprintf(buf, "%i", dist_miles);
2387                                         strcat( &dum[0], &buf[0] );
2388                                 }
2389                                 else if ( strcmp ( tag, "@FR" ) == 0 ) {
2390                                         /*
2391                                         char buf[10];
2392                                         sprintf( buf, "%6.2f", tpars.freq );
2393                                         strcat( &dum[0], &buf[0] );
2394                                         */
2395                                 }
2396                                 else if ( strcmp ( tag, "@RW" ) == 0 ) {
2397                                         strcat(&dum[0], ConvertRwyNumToSpokenString(activeRwy).c_str());
2398                                 } else if(strcmp(tag, "@CD") == 0) {    // @CD = compass direction
2399                                         double h = GetHeadingFromTo(Point3D(lon, lat, elev), Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue()));
2400                                         while(h < 0.0) h += 360.0;
2401                                         while(h > 360.0) h -= 360.0;
2402                                         if(h < 22.5 || h > 337.5) {
2403                                                 strcat(&dum[0], "North");
2404                                         } else if(h < 67.5) {
2405                                                 strcat(&dum[0], "North-East");
2406                                         } else if(h < 112.5) {
2407                                                 strcat(&dum[0], "East");
2408                                         } else if(h < 157.5) {
2409                                                 strcat(&dum[0], "South-East");
2410                                         } else if(h < 202.5) {
2411                                                 strcat(&dum[0], "South");
2412                                         } else if(h < 247.5) {
2413                                                 strcat(&dum[0], "South-West");
2414                                         } else if(h < 292.5) {
2415                                                 strcat(&dum[0], "West");
2416                                         } else {
2417                                                 strcat(&dum[0], "North-West");
2418                                         }
2419                                 } else {
2420                                         cout << "Tag " << tag << " not found" << endl;
2421                                         break;
2422                                 }
2423                                 strcat( &dum[0], &mes[len+3] );
2424                                 strcpy( &mes[0], &dum[0] );
2425                                 
2426                                 ++check;
2427                                 if(check > 10) {
2428                                         SG_LOG(SG_ATC, SG_WARN, "WARNING: Possibly endless loop terminated in FGTransmissionlist::gen_text(...)"); 
2429                                         break;
2430                                 }
2431                         }
2432                         
2433                         //cout << mes  << endl;  
2434                         //break;
2435                 //}
2436         //}
2437         if ( mes[0] ) return mes;
2438         else return "No transmission found";
2439 }
2440
2441 ostream& operator << (ostream& os, tower_traffic_type ttt) {
2442         switch(ttt) {
2443         case(CIRCUIT):      return(os << "CIRCUIT");
2444         case(INBOUND):      return(os << "INBOUND");
2445         case(OUTBOUND):     return(os << "OUTBOUND");
2446         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
2447         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
2448         }
2449         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
2450 }
2451