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