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