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