]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
AI plane should go around instead of landing on user if user dawdles on runway now
[flightgear.git] / src / ATC / tower.cxx
1 // FGTower - a class to provide tower control at towered airports.
2 //
3 // Written by David Luff, started March 2002.
4 //
5 // Copyright (C) 2002  David C. Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #include <Main/globals.hxx>
22 #include <Airports/runways.hxx>
23 #include <simgear/math/sg_geodesy.hxx>
24 #include <simgear/debug/logstream.hxx>
25
26 #include "tower.hxx"
27 #include "ATCdisplay.hxx"
28 #include "ATCmgr.hxx"
29 #include "ATCutils.hxx"
30 #include "commlist.hxx"
31 #include "AILocalTraffic.hxx"
32
33 SG_USING_STD(cout);
34
35 // TowerPlaneRec
36
37 TowerPlaneRec::TowerPlaneRec() :
38 clearedToLand(false),
39 clearedToLineUp(false),
40 clearedToTakeOff(false),
41 holdShortReported(false),
42 downwindReported(false),
43 longFinalReported(false),
44 longFinalAcknowledged(false),
45 finalReported(false),
46 finalAcknowledged(false),
47 instructedToGoAround(false),
48 onRwy(false),
49 nextOnRwy(false),
50 opType(TTT_UNKNOWN),
51 leg(LEG_UNKNOWN),
52 landingType(AIP_LT_UNKNOWN),
53 isUser(false)
54 {
55         plane.callsign = "UNKNOWN";
56 }
57
58 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
59 clearedToLand(false),
60 clearedToLineUp(false),
61 clearedToTakeOff(false),
62 holdShortReported(false),
63 downwindReported(false),
64 longFinalReported(false),
65 longFinalAcknowledged(false),
66 finalReported(false),
67 finalAcknowledged(false),
68 instructedToGoAround(false),
69 onRwy(false),
70 nextOnRwy(false),
71 opType(TTT_UNKNOWN),
72 leg(LEG_UNKNOWN),
73 landingType(AIP_LT_UNKNOWN),
74 isUser(false)
75 {
76         plane = p;
77 }
78
79 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
80 clearedToLand(false),
81 clearedToLineUp(false),
82 clearedToTakeOff(false),
83 holdShortReported(false),
84 downwindReported(false),
85 longFinalReported(false),
86 longFinalAcknowledged(false),
87 finalReported(false),
88 finalAcknowledged(false),
89 instructedToGoAround(false),
90 onRwy(false),
91 nextOnRwy(false),
92 opType(TTT_UNKNOWN),
93 leg(LEG_UNKNOWN),
94 landingType(AIP_LT_UNKNOWN),
95 isUser(false)
96 {
97         plane.callsign = "UNKNOWN";
98         pos = pt;
99 }
100
101 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
102 clearedToLand(false),
103 clearedToLineUp(false),
104 clearedToTakeOff(false),
105 holdShortReported(false),
106 downwindReported(false),
107 longFinalReported(false),
108 longFinalAcknowledged(false),
109 finalReported(false),
110 finalAcknowledged(false),
111 instructedToGoAround(false),
112 onRwy(false),
113 nextOnRwy(false),
114 opType(TTT_UNKNOWN),
115 leg(LEG_UNKNOWN),
116 landingType(AIP_LT_UNKNOWN),
117 isUser(false)
118 {
119         plane = p;
120         pos = pt;
121 }
122
123
124 // FGTower
125
126 /*******************************************
127                TODO List
128                            
129 Currently user is assumed to have taken off again when leaving the runway - check speed/elev for taxiing-in.
130
131 AI plane lands even when user on rwy - make it go-around instead.
132
133 Tell AI plane to contact ground when taxiing in.
134
135 Use track instead of heading to determine what leg of the circuit the user is flying.
136
137 Use altitude as well as position to try to determine if the user has left the circuit.
138
139 Currently HoldShortReported code assumes there will be only one plane holding for the runway at once and 
140 will break when planes start queueing.
141
142 Implement ReportRunwayVacated
143 *******************************************/
144
145 FGTower::FGTower() {
146         ATCmgr = globals->get_ATC_mgr();
147         
148         // Init the property nodes - TODO - need to make sure we're getting surface winds.
149         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
150         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
151         
152         update_count = 0;
153         update_count_max = 15;
154         
155         holdListItr = holdList.begin();
156         appListItr = appList.begin();
157         depListItr = depList.begin();
158         rwyListItr = rwyList.begin();
159         circuitListItr = circuitList.begin();
160         trafficListItr = trafficList.begin();
161         
162         freqClear = true;
163         
164         timeSinceLastDeparture = 9999;
165         departed = false;
166 }
167
168 FGTower::~FGTower() {
169         if(!separateGround) {
170                 delete ground;
171         }
172 }
173
174 void FGTower::Init() {
175     display = false;
176         
177         // Pointers to user's position
178         user_lon_node = fgGetNode("/position/longitude-deg", true);
179         user_lat_node = fgGetNode("/position/latitude-deg", true);
180         user_elev_node = fgGetNode("/position/altitude-ft", true);
181         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
182         
183         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
184         // I'll punt the startup issue for now though!!!
185         rwyOccupied = false;
186         
187         // Setup the ground control at this airport
188         AirportATC a;
189         //cout << "Tower ident = " << ident << '\n';
190         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
191                 if(a.ground_freq) {             // Ground control
192                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
193                         separateGround = true;
194                         if(ground == NULL) {
195                                 // Something has gone wrong :-(
196                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
197                                 ground = new FGGround(ident);
198                                 separateGround = false;
199                                 ground->Init();
200                                 if(display) {
201                                         ground->SetDisplay();
202                                 } else {
203                                         ground->SetNoDisplay();
204                                 }
205                         }
206                 } else {
207                         // Initialise ground anyway to do the shortest path stuff!
208                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
209                         ground = new FGGround(ident);
210                         separateGround = false;
211                         ground->Init();
212                         if(display) {
213                                 ground->SetDisplay();
214                         } else {
215                                 ground->SetNoDisplay();
216                         }
217                 }
218         } else {
219                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
220                 // Initialise ground anyway to avoid segfault later
221                 ground = new FGGround(ident);
222                 separateGround = false;
223                 ground->Init();
224                 if(display) {
225                         ground->SetDisplay();
226                 } else {
227                         ground->SetNoDisplay();
228                 }
229         }
230         
231         // Get the airport elevation
232         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
233         
234         DoRwyDetails();
235         
236         // FIXME - this currently assumes use of the active rwy by the user.
237         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
238         if(rwyOccupied) {
239                 // Assume the user is started at the threshold ready to take-off
240                 TowerPlaneRec* t = new TowerPlaneRec;
241                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
242                 t->plane.type = GA_SINGLE;
243                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
244                 t->landingType = AIP_LT_UNKNOWN;
245                 t->leg = TAKEOFF_ROLL;
246                 t->isUser = true;
247                 t->planePtr = NULL;
248                 t->clearedToTakeOff = true;
249                 rwyList.push_back(t);
250                 departed = false;
251         }
252 }
253
254 void FGTower::Update(double dt) {
255         //cout << "T" << endl;
256         // Each time step, what do we need to do?
257         // We need to go through the list of outstanding requests and acknowedgements
258         // and process at least one of them.
259         // We need to go through the list of planes under our control and check if
260         // any need to be addressed.
261         // We need to check for planes not under our control coming within our 
262         // control area and address if necessary.
263         
264         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
265         
266         // Sort the arriving planes
267         
268         /*
269         if(ident == "KEMT") {
270                 cout << update_count << "\ttL: " << trafficList.size() << "  cL: " << circuitList.size() << "  hL: " << holdList.size() << "  aL: " << appList.size() << '\n';
271         }
272         */
273         
274         if(departed != false) {
275                 timeSinceLastDeparture += dt;
276                 //if(ident == "KEMT") 
277                 //      cout << "  dt = " << dt << "  timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
278         }
279         
280         //cout << ident << " respond = " << respond << " responseReqd = " << responseReqd << '\n'; 
281         if(respond) {
282                 if(!responseReqd) SG_LOG(SG_ATC, SG_ALERT, "ERROR - respond is true and responseReqd is false in FGTower::Update(...)");
283                 Respond();
284                 respond = false;
285                 responseReqd = false;
286         }
287         
288         // Calculate the eta of each plane to the threshold.
289         // For ground traffic this is the fastest they can get there.
290         // For air traffic this is the middle approximation.
291         if(update_count == 1) {
292                 doThresholdETACalc();
293         }
294         
295         // Order the list of traffic as per expected threshold use and flag any conflicts
296         if(update_count == 2) {
297                 //bool conflicts = doThresholdUseOrder();
298                 doThresholdUseOrder();
299         }
300         
301         // sortConficts() !!!
302         
303         if(update_count == 4) {
304                 CheckHoldList(dt);
305         }
306         
307         // Uggh - HACK - why have we got rwyOccupied - wouldn't simply testing rwyList.size() do?
308         if(rwyList.size()) {
309                 rwyOccupied = true;
310         } else {
311                 rwyOccupied = false;
312         }
313         
314         if(update_count == 5 && rwyOccupied) {
315                 CheckRunwayList(dt);
316         }
317                 
318         if(update_count == 6) {
319                 CheckCircuitList(dt);
320         }
321         
322         if(update_count == 7) {
323                 CheckApproachList(dt);
324         }
325         
326         // TODO - do one plane from the departure list and set departed = false when out of consideration
327         
328         //doCommunication();
329         
330         if(!separateGround) {
331                 // The display stuff might have to get more clever than this when not separate 
332                 // since the tower and ground might try communicating simultaneously even though
333                 // they're mean't to be the same contoller/frequency!!
334                 if(display) {
335                         ground->SetDisplay();
336                 } else {
337                         ground->SetNoDisplay();
338                 }
339                 ground->Update(dt);
340         }
341         
342         ++update_count;
343         // How big should ii get - ie how long should the update cycle interval stretch?
344         if(update_count >= update_count_max) {
345                 update_count = 0;
346         }
347         
348         // Call the base class update for the response time handling.
349         FGATC::Update(dt);
350
351         if(ident == "KEMT") {   
352                 // For AI debugging convienience - may be removed
353                 Point3D user_pos;
354                 user_pos.setlon(user_lon_node->getDoubleValue());
355                 user_pos.setlat(user_lat_node->getDoubleValue());
356                 user_pos.setelev(user_elev_node->getDoubleValue());
357                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
358                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
359                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
360                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
361         }
362         
363         //cout << "Done T" << endl;
364 }
365
366 void FGTower::Respond() {
367         //cout << "Entering Respond..." << endl;
368         TowerPlaneRec* t = FindPlane(responseID);
369         if(t) {
370                 // This will grow!!!
371                 if(t->downwindReported) {
372                         t->downwindReported = false;
373                         int i = 1;
374                         for(tower_plane_rec_list_iterator twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
375                                 if((*twrItr)->plane.callsign == responseID) break;
376                                 ++i;
377                         }                       
378                         string trns = "Number ";
379                         trns += ConvertNumToSpokenDigits(i);
380                         trns += " ";
381                         trns += t->plane.callsign;
382                         if(display) {
383                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
384                         }
385                         if(t->isUser && t->opType == TTT_UNKNOWN) {
386                                 t->opType = CIRCUIT;
387                         }
388                 } else if(t->holdShortReported) {
389                         if(t->nextOnRwy) {
390                                 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!!)
391                                         // Do nothing for now - consider acknowloging hold short eventually
392                                 } else {
393                                         ClearHoldingPlane(t);
394                                         t->leg = TAKEOFF_ROLL;
395                                         rwyList.push_back(t);
396                                         rwyOccupied = true;
397                                         // WARNING - WE ARE ASSUMING ONLY ONE PLANE REPORTING HOLD AT A TIME BELOW
398                                         // FIXME TODO - FIX THIS!!!
399                                         if(holdList.size()) {
400                                                 if(holdListItr == holdList.end()) {
401                                                         holdListItr = holdList.begin();
402                                                 }
403                                                 holdList.erase(holdListItr);
404                                                 holdListItr = holdList.begin();
405                                         }
406                                 }
407                         } else {
408                                 // Tell him to hold and what position he is.
409                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
410                                 string trns = t->plane.callsign;
411                                 trns += " hold position";
412                                 if(display) {
413                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
414                                 }
415                                 // TODO - add some idea of what traffic is blocking him.
416                         }
417                         t->holdShortReported = false;
418                 } else if(t->finalReported && !(t->finalAcknowledged)) {
419                         bool disp = true;
420                         string trns = t->plane.callsign;
421                         if(t->nextOnRwy && !rwyOccupied) {
422                                 if(t->landingType == FULL_STOP) {
423                                         trns += " cleared to land ";
424                                 } else {
425                                         trns += " cleared for the option ";
426                                 }
427                                 // TODO - add winds
428                                 t->clearedToLand = true;
429                         } else if(t->eta < 20) {
430                                 // Do nothing - we'll be telling it to go around in less than 10 seconds if the
431                                 // runway doesn't clear so no point in calling "continue approach".
432                                 disp = false;
433                         } else {
434                                 trns += " continue approach";
435                                 t->clearedToLand = false;
436                         }
437                         if(display && disp) {
438                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
439                         }
440                         t->finalAcknowledged = true;
441                 }
442         }
443         freqClear = true;       // FIXME - set this to come true after enough time to render the message
444         //cout << "Done Respond" << endl;
445 }
446
447 // Currently this assumes we *are* next on the runway and doesn't check for planes about to land - 
448 // this should be done prior to calling this function.
449 void FGTower::ClearHoldingPlane(TowerPlaneRec* t) {
450         //cout << "Entering ClearHoldingPlane..." << endl;
451         // Lets Roll !!!!
452         string trns = t->plane.callsign;
453         //if(departed plane < some threshold in time away) {
454         if(0) {         // FIXME
455         //if(timeSinceLastDeparture <= 60.0 && departed == true) {
456                 trns += " line up";
457                 t->clearedToLineUp = true;
458                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
459         //} else if(arriving plane < some threshold away) {
460         } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) {   // Hack - hardwired time
461                 trns += " cleared immediate take-off";
462                 if(trafficList.size()) {
463                         tower_plane_rec_list_iterator trfcItr = trafficList.begin();
464                         trfcItr++;      // At the moment the holding plane should be first in trafficList.
465                         // Note though that this will break if holding planes aren't put in trafficList in the future.
466                         TowerPlaneRec* trfc = *trfcItr;
467                         trns += "... traffic is";
468                         switch(trfc->plane.type) {
469                         case UNKNOWN:
470                                 break;
471                         case GA_SINGLE:
472                                 trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
473                                 break;
474                         case GA_HP_SINGLE:
475                                 trns += " a Piper";
476                                 break;
477                         case GA_TWIN:
478                                 trns += " a King-air";
479                                 break;
480                         case GA_JET:
481                                 trns += " a Learjet";
482                                 break;
483                         case MEDIUM:
484                                 trns += " a Regional";
485                                 break;
486                         case HEAVY:
487                                 trns += " a Heavy";
488                                 break;
489                         case MIL_JET:
490                                 trns += " Military";
491                                 break;
492                         }
493                         //if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
494                         if(trfc->opType == STRAIGHT_IN) {
495                                 double miles_out = CalcDistOutMiles(trfc);
496                                 if(miles_out < 2) {
497                                         trns += " on final";
498                                 } else {
499                                         trns += " on ";
500                                         trns += ConvertNumToSpokenDigits((int)miles_out);
501                                         trns += " mile final";
502                                 }
503                         } else if(trfc->opType == CIRCUIT) {
504                                 //cout << "Getting leg of " << trfc->plane.callsign << '\n';
505                                 switch(trfc->leg) {
506                                 case FINAL:
507                                         trns += " on final";
508                                         break;
509                                 case TURN4:
510                                         trns += " turning final";
511                                         break;
512                                 case BASE:
513                                         trns += " on base";
514                                         break;
515                                 case TURN3:
516                                         trns += " turning base";
517                                         break;
518                                 case DOWNWIND:
519                                         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.
520                                         break;
521                                 // And to eliminate compiler warnings...
522                                 case TAKEOFF_ROLL: break;
523                                 case CLIMBOUT:     break;
524                                 case TURN1:        break;
525                                 case CROSSWIND:    break;
526                                 case TURN2:        break;
527                                 case LANDING_ROLL: break;
528                                 case LEG_UNKNOWN:  break;
529                                 }
530                         }
531                 } else {
532                         // By definition there should be some arriving traffic if we're cleared for immediate takeoff
533                         SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
534                 }
535                 t->clearedToTakeOff = true;
536                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
537                 departed = false;
538                 timeSinceLastDeparture = 0.0;
539         } else {
540         //} else if(timeSinceLastDeparture > 60.0 || departed == false) {       // Hack - test for timeSinceLastDeparture should be in lineup block eventually
541                 trns += " cleared for take-off";
542                 // TODO - add traffic is... ?
543                 t->clearedToTakeOff = true;
544                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
545                 departed = false;
546                 timeSinceLastDeparture = 0.0;
547         }
548         if(display) {
549                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
550         }
551         //cout << "Done ClearHoldingPlane " << endl;
552 }
553
554 // Do one plane from the hold list
555 void FGTower::CheckHoldList(double dt) {
556         //cout << "Entering CheckHoldList..." << endl;
557         if(holdList.size()) {
558                 //cout << "*holdListItr = " << *holdListItr << endl;
559                 if(holdListItr == holdList.end()) {
560                         holdListItr = holdList.begin();
561                 }
562                 //cout << "*holdListItr = " << *holdListItr << endl;
563                 //Process(*holdListItr);
564                 TowerPlaneRec* t = *holdListItr;
565                 //cout << "t = " << t << endl;
566                 if(t->holdShortReported) {
567                         // NO-OP - leave it to the response handler.
568                 } else {        // not responding to report, but still need to clear if clear
569                         if(t->nextOnRwy) {
570                                 //cout << "departed = " << departed << '\n';
571                                 //cout << "timeSinceLastDeparture = " << timeSinceLastDeparture << '\n';
572                                 if(rwyOccupied) {
573                                         // Do nothing
574                                 } else if(timeSinceLastDeparture <= 60.0 && departed == true) {
575                                         // Do nothing - this is a bit of a hack - should maybe do line up be ready here
576                                 } else {
577                                         ClearHoldingPlane(t);
578                                         t->leg = TAKEOFF_ROLL;
579                                         rwyList.push_back(t);
580                                         rwyOccupied = true;
581                                         holdList.erase(holdListItr);
582                                         holdListItr = holdList.begin();
583                                 }
584                         }
585                         // TODO - rationalise the considerable code duplication above!
586                 }
587                 ++holdListItr;
588         }
589         //cout << "Done CheckHoldList" << endl;
590 }
591
592 // do the ciruit list
593 void FGTower::CheckCircuitList(double dt) {
594         //cout << "Entering CheckCircuitList..." << endl;
595         // Clear the constraints - we recalculate here.
596         base_leg_pos = 0.0;
597         downwind_leg_pos = 0.0;
598         crosswind_leg_pos = 0.0;
599         
600         if(circuitList.size()) {        // Do one plane from the circuit
601                 if(circuitListItr == circuitList.end()) {
602                         circuitListItr = circuitList.begin();
603                 }
604                 TowerPlaneRec* t = *circuitListItr;
605                 if(t->isUser) {
606                         t->pos.setlon(user_lon_node->getDoubleValue());
607                         t->pos.setlat(user_lat_node->getDoubleValue());
608                         t->pos.setelev(user_elev_node->getDoubleValue());
609                 } else {
610                         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.
611                         t->landingType = t->planePtr->GetLandingOption();
612                         //cout << "AI plane landing option is " << t->landingType << '\n';
613                 }
614                 Point3D tortho = ortho.ConvertToLocal(t->pos);
615                 if(t->isUser) {
616                         // Need to figure out which leg he's on
617                         //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
618                         double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
619                         //cout << " ho = " << ho << " abs(ho = " << abs(ho) << '\n';
620                         // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
621                         // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
622                         if(abs(ho) < 30) {
623                                 // could be either takeoff, climbout or landing - check orthopos.y
624                                 //cout << "tortho.y = " << tortho.y() << '\n';
625                                 if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
626                                         t->leg = FINAL;
627                                         //cout << "Final\n";
628                                 } else {
629                                         t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
630                                         //cout << "Climbout\n";
631                                         // If it's the user we may be unsure of his/her intentions.
632                                         // (Hopefully the AI planes won't try confusing the sim!!!)
633                                         if(t->opType == TTT_UNKNOWN) {
634                                                 if(tortho.y() > 5000) {
635                                                         // 5 km out from threshold - assume it's a departure
636                                                         t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
637                                                         // Since we are unknown operation we should be in depList already.
638                                                         circuitList.erase(circuitListItr);
639                                                         RemoveFromTrafficList(t->plane.callsign);
640                                                         circuitListItr = circuitList.begin();
641                                                 }
642                                         } else if(t->opType == CIRCUIT) {
643                                                 if(tortho.y() > 10000) {
644                                                         // 10 km out - assume the user has abandoned the circuit!!
645                                                         t->opType = OUTBOUND;
646                                                         depList.push_back(t);
647                                                         circuitList.erase(circuitListItr);
648                                                         circuitListItr = circuitList.begin();
649                                                 }
650                                         }
651                                 }
652                         } else if(abs(ho) < 60) {
653                                 // turn1 or turn 4
654                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
655                                 if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
656                                         t->leg = TURN1;
657                                         //cout << "Turn1\n";
658                                 } else {
659                                         t->leg = TURN4;
660                                         //cout << "Turn4\n";
661                                 }
662                         } else if(abs(ho) < 120) {
663                                 // crosswind or base
664                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
665                                 if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
666                                         t->leg = CROSSWIND;
667                                         //cout << "Crosswind\n";
668                                 } else {
669                                         t->leg = BASE;
670                                         //cout << "Base\n";
671                                 }
672                         } else if(abs(ho) < 150) {
673                                 // turn2 or turn 3
674                                 // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
675                                 if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
676                                         t->leg = TURN2;
677                                         //cout << "Turn2\n";
678                                 } else {
679                                         t->leg = TURN3;
680                                         // Probably safe now to assume the user is flying a circuit
681                                         t->opType = CIRCUIT;
682                                         //cout << "Turn3\n";
683                                 }
684                         } else {
685                                 // downwind
686                                 t->leg = DOWNWIND;
687                                 //cout << "Downwind\n";
688                         }
689                         if(t->leg == FINAL) {
690                                 if(OnActiveRunway(t->pos)) {
691                                         t->leg = LANDING_ROLL;
692                                 }
693                         }
694                 } else {
695                         t->leg = t->planePtr->GetLeg();
696                 }
697                 
698                 // Set the constraints IF this is the first plane in the circuit
699                 // 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!!
700                 if(circuitListItr == circuitList.begin()) {
701                         switch(t->leg) {
702                         case FINAL:
703                                 // 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.
704                                 base_leg_pos = tortho.y();
705                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
706                                 break;
707                         case TURN4:
708                                 // Fall through to base
709                         case BASE:
710                                 base_leg_pos = tortho.y();
711                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
712                                 break;
713                         case TURN3:
714                                 // Fall through to downwind
715                         case DOWNWIND:
716                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
717                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
718                                 //cout << "base_leg_pos = " << base_leg_pos;
719                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
720                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
721                                 break;
722                         case TURN2:
723                                 // Fall through to crosswind
724                         case CROSSWIND:
725                                 crosswind_leg_pos = tortho.y();
726                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
727                                 t->instructedToGoAround = false;
728                                 break;
729                         case TURN1:
730                                 // Fall through to climbout
731                         case CLIMBOUT:
732                                 // Only use current by constraint as largest
733                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
734                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
735                                 break;
736                         case TAKEOFF_ROLL:
737                                 break;
738                         case LEG_UNKNOWN:
739                                 break;
740                         case LANDING_ROLL:
741                                 break;
742                         default:
743                                 break;
744                         }
745                 }
746                 
747                 if(t->leg == FINAL) {
748                         if(t->landingType == FULL_STOP) t->opType = INBOUND;
749                         if(t->eta < 12 && rwyList.size() && !(t->instructedToGoAround)) {
750                                 // TODO - need to make this more sophisticated 
751                                 // eg. is the plane accelerating down the runway taking off [OK],
752                                 // or stationary near the start [V. BAD!!].
753                                 // For now this should stop the AI plane landing on top of the user.
754                                 string trns = t->plane.callsign;
755                                 trns += " GO AROUND TRAFFIC ON RUNWAY I REPEAT GO AROUND";
756                                 if(display) {
757                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
758                                 }
759                                 t->instructedToGoAround = true;
760                                 if(t->planePtr) {
761                                         cout << "Registering Go-around transmission with AI plane\n";
762                                         t->planePtr->RegisterTransmission(13);
763                                 }
764                         }
765                 } else if(t->leg == LANDING_ROLL) {
766                         rwyList.push_front(t);
767                         // TODO - if(!clearedToLand) shout something!!
768                         t->clearedToLand = false;
769                         RemoveFromTrafficList(t->plane.callsign);
770                         if(t->isUser) {
771                                 t->opType = TTT_UNKNOWN;
772                         }       // TODO - allow the user to specify opType via ATC menu
773                         circuitListItr = circuitList.erase(circuitListItr);
774                         if(circuitListItr == circuitList.end() ) {
775                                 circuitListItr = circuitList.begin();
776                         }
777                 }
778                 ++circuitListItr;
779         }
780         //cout << "Done CheckCircuitList" << endl;
781 }
782
783 // 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!!
784 // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
785 // (However, at the moment there should only be one airplane on the rwy at once, until we
786 // start allowing planes to line up whilst previous arrival clears the rwy.)
787 void FGTower::CheckRunwayList(double dt) {
788         //cout << "Entering CheckRunwayList..." << endl;
789         if(rwyOccupied) {
790                 if(!rwyList.size()) {
791                         rwyOccupied = false;
792                 } else {
793                         rwyListItr = rwyList.begin();
794                         TowerPlaneRec* t = *rwyListItr;
795                         if(t->isUser) {
796                                 t->pos.setlon(user_lon_node->getDoubleValue());
797                                 t->pos.setlat(user_lat_node->getDoubleValue());
798                                 t->pos.setelev(user_elev_node->getDoubleValue());
799                         } else {
800                                 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.
801                         }
802                         bool on_rwy = OnActiveRunway(t->pos);
803                         if(!on_rwy) {
804                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
805                                         rwyList.pop_front();
806                                         delete t;
807                                         // TODO - tell it to taxi / contact ground / don't delete it etc!
808                                 } else if(t->opType == OUTBOUND) {
809                                         depList.push_back(t);
810                                         rwyList.pop_front();
811                                         departed = true;
812                                         timeSinceLastDeparture = 0.0;
813                                 } else if(t->opType == CIRCUIT) {
814                                         circuitList.push_back(t);
815                                         AddToTrafficList(t);
816                                         rwyList.pop_front();
817                                         departed = true;
818                                         timeSinceLastDeparture = 0.0;
819                                 } else if(t->opType == TTT_UNKNOWN) {
820                                         depList.push_back(t);
821                                         circuitList.push_back(t);
822                                         AddToTrafficList(t);
823                                         rwyList.pop_front();
824                                         departed = true;
825                                         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.
826                                 } else {
827                                         // HELP - we shouldn't ever get here!!!
828                                 }
829                         }
830                 }
831         }
832         //cout << "Done CheckRunwayList" << endl;
833 }
834
835 // Do one plane from the approach list
836 void FGTower::CheckApproachList(double dt) {
837         if(appList.size()) {
838                 if(appListItr == appList.end()) {
839                         appListItr = appList.begin();
840                 }
841                 TowerPlaneRec* t = *appListItr;
842                 //cout << "t = " << t << endl;
843                 if(t->isUser) {
844                         t->pos.setlon(user_lon_node->getDoubleValue());
845                         t->pos.setlat(user_lat_node->getDoubleValue());
846                         t->pos.setelev(user_elev_node->getDoubleValue());
847                 } else {
848                         // TODO - set/update the position if it's an AI plane
849                 }                               
850                 if(t->nextOnRwy && !(t->clearedToLand)) {
851                         // check distance away and whether runway occupied
852                         // and schedule transmission if necessary
853                 }                               
854                 ++appListItr;
855         }
856 }
857
858 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
859 // plus the constraint position as a rwy orientated orthopos (meters)
860 bool FGTower::GetCrosswindConstraint(double& cpos) {
861         if(crosswind_leg_pos != 0.0) {
862                 cpos = crosswind_leg_pos;
863                 return(true);
864         } else {
865                 cpos = 0.0;
866                 return(false);
867         }
868 }
869 bool FGTower::GetDownwindConstraint(double& dpos) {
870         if(downwind_leg_pos != 0.0) {
871                 dpos = downwind_leg_pos;
872                 return(true);
873         } else {
874                 dpos = 0.0;
875                 return(false);
876         }
877 }
878 bool FGTower::GetBaseConstraint(double& bpos) {
879         if(base_leg_pos != 0.0) {
880                 bpos = base_leg_pos;
881                 return(true);
882         } else {
883                 bpos = 0.0;
884                 return(false);
885         }
886 }
887
888
889 // Figure out which runways are active.
890 // For now we'll just be simple and do one active runway - eventually this will get much more complex
891 // This is a private function - public interface to the results of this is through GetActiveRunway
892 void FGTower::DoRwyDetails() {
893         //cout << "GetRwyDetails called" << endl;
894         
895         // Based on the airport-id and wind get the active runway
896         
897         //wind
898         double hdg = wind_from_hdg->getDoubleValue();
899         double speed = wind_speed_knots->getDoubleValue();
900         hdg = (speed == 0.0 ? 270.0 : hdg);
901         //cout << "Heading = " << hdg << '\n';
902         
903         FGRunway runway;
904         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
905         if(rwyGood) {
906                 activeRwy = runway.rwy_no;
907                 rwy.rwyID = runway.rwy_no;
908                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
909                 
910                 // Get the threshold position
911                 double other_way = runway.heading - 180.0;
912                 while(other_way <= 0.0) {
913                         other_way += 360.0;
914                 }
915         // move to the +l end/center of the runway
916                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
917         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
918                 Point3D ref = origin;
919         double tshlon, tshlat, tshr;
920                 double tolon, tolat, tor;
921                 rwy.length = runway.length * SG_FEET_TO_METER;
922                 rwy.width = runway.width * SG_FEET_TO_METER;
923         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
924                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
925         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
926                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
927                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
928                 // now copy what we need out of runway into rwy
929         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
930                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
931                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
932                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
933                 rwy.hdg = runway.heading;
934                 // Set the projection for the local area based on this active runway
935                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
936                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
937                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
938         } else {
939                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
940                 activeRwy = "NN";
941         }
942 }
943
944
945 // Figure out if a given position lies on the active runway
946 // Might have to change when we consider more than one active rwy.
947 bool FGTower::OnActiveRunway(Point3D pt) {
948         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
949         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
950         Point3D xyp = ortho.ConvertToLocal(pt);
951         
952         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
953         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
954
955         double rlen = rwy.length/2.0 + 5.0;
956         double rwidth = rwy.width/2.0;
957         double ldiff = fabs(xyp.y() - xyc.y());
958         double wdiff = fabs(xyp.x() - xyc.x());
959
960         return((ldiff < rlen) && (wdiff < rwidth));
961 }       
962
963
964 // Figure out if a given position lies on any runway or not
965 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
966 bool FGTower::OnAnyRunway(Point3D pt) {
967         ATCData ad;
968         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
969         if(dist < 0.0) {
970                 return(false);
971         }
972         // Based on the airport-id, go through all the runways and check for a point in them
973         
974         // TODO - do we actually need to search for the airport - surely we already know our ident and
975         // can just search runways of our airport???
976         //cout << "Airport ident is " << ad.ident << '\n';
977         FGRunway runway;
978         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
979         if(!rwyGood) {
980                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
981         }
982         bool on = false;
983         while(runway.id == ad.ident) {          
984                 on = OnRunway(pt, runway);
985                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
986                 if(on) return(true);
987                 globals->get_runways()->next(&runway);          
988         }
989         return(on);
990 }
991
992
993 // Returns true if successful
994 bool FGTower::RemoveFromTrafficList(string id) {
995         tower_plane_rec_list_iterator twrItr;
996         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
997                 TowerPlaneRec* tpr = *twrItr;
998                 if(tpr->plane.callsign == id) {
999                         trafficList.erase(twrItr);
1000                         return(true);
1001                 }
1002         }       
1003         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
1004         return(false);
1005 }
1006
1007
1008 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
1009 // and set nextOnRwy if so.
1010 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
1011 // For planes holding they are put in the first position with time to go, and the return value is
1012 // true if in the first position (nextOnRwy) and false otherwise.
1013 // See the comments in FGTower::doThresholdUseOrder for notes on the ordering
1014 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
1015         //cout << "ADD: " << trafficList.size();
1016         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << endl;
1017         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.
1018         double departure_sep_time = 60.0;       // Separation time behind departing airplanes.  Comments above also apply.
1019         bool conflict = false;
1020         double lastETA = 0.0;
1021         bool firstTime = true;
1022         // FIXME - make this more robust for different plane types eg. light following heavy.
1023         tower_plane_rec_list_iterator twrItr;
1024         //twrItr = trafficList.begin();
1025         //while(1) {
1026         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1027                 //if(twrItr == trafficList.end()) {
1028                 //      cout << "  END  ";
1029                 //      trafficList.push_back(t);
1030                 //      return(holding ? firstTime : conflict);
1031                 //} else {
1032                         TowerPlaneRec* tpr = *twrItr;
1033                         if(holding) {
1034                                 //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
1035                                 //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
1036                                 double dep_allowance = (timeSinceLastDeparture < departure_sep_time ? departure_sep_time - timeSinceLastDeparture : 0.0); 
1037                                 double slot_time = (firstTime ? separation_time + dep_allowance : separation_time + departure_sep_time);
1038                                 // separation_time + departure_sep_time in the above accounts for the fact that the arrival could be touch and go,
1039                                 // and if not needs time to clear the rwy anyway.
1040                                 if(tpr->eta  - lastETA > slot_time) {
1041                                         t->nextOnRwy = firstTime;
1042                                         trafficList.insert(twrItr, t);
1043                                         //cout << "\tH\t" << trafficList.size() << '\n';
1044                                         return(firstTime);
1045                                 }
1046                                 firstTime = false;
1047                         } else {
1048                                 if(t->eta < tpr->eta) {
1049                                         // Ugg - this one's tricky.
1050                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1051                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1052                                                 if(tpr->nextOnRwy) {
1053                                                         tpr->nextOnRwy = false;
1054                                                         t->nextOnRwy = true;
1055                                                 }
1056                                                 trafficList.insert(twrItr, t);
1057                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1058                                                 conflict = true;
1059                                                 // HACK - just add anyway for now and flag conflict - TODO - FIX THIS using CIRCUIT/STRAIGHT_IN and VFR/IFR precedence rules.
1060                                                 if(tpr->nextOnRwy) {
1061                                                         tpr->nextOnRwy = false;
1062                                                         t->nextOnRwy = true;
1063                                                 }
1064                                                 trafficList.insert(twrItr, t);
1065                                         }
1066                                         //cout << "\tC\t" << trafficList.size() << '\n';
1067                                         return(conflict);
1068                                 }
1069                         }
1070                 //}
1071                 //++twrItr;
1072         }
1073         // If we get here we must be at the end of the list, or maybe the list is empty.
1074         if(!trafficList.size()) {
1075                 t->nextOnRwy = true;
1076                 // conflict and firstTime should be false and true respectively in this case anyway.
1077         }
1078         trafficList.push_back(t);
1079         //cout << "\tE\t" << trafficList.size() << endl;
1080         return(holding ? firstTime : conflict);
1081 }
1082
1083 // Add a tower plane rec with ETA to the circuit list in the correct position ETA-wise
1084 // Returns true if this might cause a separation conflict (based on ETA) with other traffic, false otherwise.
1085 bool FGTower::AddToCircuitList(TowerPlaneRec* t) {
1086         //cout << "ADD: " << circuitList.size();
1087         //cout << "AddToCircuitList called, currently size = " << circuitList.size() << endl;
1088         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.
1089         bool conflict = false;
1090         tower_plane_rec_list_iterator twrItr;
1091         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1092                         TowerPlaneRec* tpr = *twrItr;
1093                                 
1094                                 if(t->eta < tpr->eta) {
1095                                         // Ugg - this one's tricky.
1096                                         // It depends on what the two planes are doing and whether there's a conflict what we do.
1097                                         if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
1098                                                 circuitList.insert(twrItr, t);
1099                                         } else {        // Ooops - this ones tricky - we have a potential conflict!
1100                                                 conflict = true;
1101                                                 // HACK - just add anyway for now and flag conflict.
1102                                                 circuitList.insert(twrItr, t);
1103                                         }
1104                                         //cout << "\tC\t" << circuitList.size() << '\n';
1105                                         return(conflict);
1106                                 }
1107         }
1108         // If we get here we must be at the end of the list, or maybe the list is empty.
1109         circuitList.push_back(t);       // TODO - check the separation with the preceding plane for the conflict flag.
1110         //cout << "\tE\t" << circuitList.size() << endl;
1111         return(conflict);
1112 }
1113
1114
1115 // Calculate the eta of a plane to the threshold.
1116 // For ground traffic this is the fastest they can get there.
1117 // For air traffic this is the middle approximation.
1118 void FGTower::CalcETA(TowerPlaneRec* tpr, bool printout) {
1119         // For now we'll be very crude and hardwire expected speeds to C172-like values
1120         // The speeds below are specified in knots IAS and then converted to m/s
1121         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
1122         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
1123         double final_ias = 70.0 * 0.514444;             // Speed during final approach
1124         
1125         //if(printout) {
1126         //cout << "In CalcETA, airplane ident = " << tpr->plane.callsign << '\n';
1127         //cout << (tpr->isUser ? "USER\n" : "AI\n");
1128         //cout << flush;
1129         //}
1130         
1131         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
1132         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
1133         
1134         Point3D op = ortho.ConvertToLocal(tpr->pos);
1135         //if(printout) {
1136         //      cout << "Orthopos is " << op.x() << ", " << op.y() << '\n';
1137         //      cout << "opType is " << tpr->opType << '\n';
1138         //}
1139         double dist_out_m = op.y();
1140         double dist_across_m = fabs(op.x());    // FIXME = the fabs is a hack to cope with the fact that we don't know the circuit direction yet
1141         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
1142         
1143         if(tpr->opType == STRAIGHT_IN) {
1144                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
1145                 if(dist_to_go_m < 1000) {
1146                         tpr->eta = dist_to_go_m / final_ias;
1147                 } else {
1148                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
1149                 }
1150         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
1151                 // It's complicated - depends on if base leg is delayed or not
1152                 //if(printout) {
1153                 //      cout << "Leg = " << tpr->leg << '\n';
1154                 //}
1155                 if(tpr->leg == LANDING_ROLL) {
1156                         tpr->eta = 0;
1157                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
1158                         tpr->eta = fabs(dist_out_m) / final_ias;
1159                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
1160                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
1161                 } else {
1162                         // Need to calculate where base leg is likely to be
1163                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
1164                         // 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
1165                         double nominal_base_dist_out_m = -1000;
1166                         double current_base_dist_out_m;
1167                         if(!GetBaseConstraint(current_base_dist_out_m)) {
1168                                 current_base_dist_out_m = nominal_base_dist_out_m;
1169                         }
1170                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
1171                         double current_dist_across_m;
1172                         if(!GetDownwindConstraint(current_dist_across_m)) {
1173                                 current_dist_across_m = nominal_dist_across_m;
1174                         }
1175                         double nominal_cross_dist_out_m = 2000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
1176                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
1177                         //if(printout) cout << "a = " << tpr->eta << '\n';
1178                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
1179                                 tpr->eta += dist_across_m / circuit_ias;
1180                                 //if(printout) cout << "b = " << tpr->eta << '\n';
1181                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1182                                 //if(printout) cout << "c = " << tpr->eta << '\n';
1183                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
1184                                 if(dist_across_m > nominal_dist_across_m) {
1185                                         tpr->eta += dist_across_m / circuit_ias;
1186                                 } else {
1187                                         tpr->eta += nominal_dist_across_m / circuit_ias;
1188                                 }
1189                                 // should we use the dist across of the previous plane if there is previous still on downwind?
1190                                 //if(printout) cout << "bb = " << tpr->eta << '\n';
1191                                 if(dist_out_m > nominal_cross_dist_out_m) {
1192                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
1193                                 } else {
1194                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
1195                                 }
1196                                 //if(printout) cout << "cc = " << tpr->eta << '\n';
1197                                 if(nominal_dist_across_m > dist_across_m) {
1198                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
1199                                 } else {
1200                                         // Nothing to add
1201                                 }
1202                                 //if(printout) cout << "dd = " << tpr->eta << '\n';
1203                         } else {
1204                                 // We've only just started - why not use a generic estimate?
1205                                 tpr->eta = 240.0;
1206                         }
1207                 }
1208                 //if(printout) {
1209                 //      cout << "ETA = " << tpr->eta << '\n';
1210                 //}
1211         } else {
1212                 tpr->eta = 99999;
1213         }       
1214 }
1215
1216
1217 // Calculate the distance of a plane to the threshold in meters
1218 // TODO - Modify to calculate flying distance of a plane in the circuit
1219 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
1220         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
1221 }
1222
1223
1224 // Calculate the distance of a plane to the threshold in miles
1225 // TODO - Modify to calculate flying distance of a plane in the circuit
1226 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
1227         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
1228 }
1229
1230
1231 // Iterate through all the lists and call CalcETA for all the planes.
1232 void FGTower::doThresholdETACalc() {
1233         //cout << "Entering doThresholdETACalc..." << endl;
1234         tower_plane_rec_list_iterator twrItr;
1235         // Do the approach list first
1236         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1237                 TowerPlaneRec* tpr = *twrItr;
1238                 CalcETA(tpr);
1239         }       
1240         // Then the circuit list
1241         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1242                 TowerPlaneRec* tpr = *twrItr;
1243                 CalcETA(tpr);
1244         }
1245         //cout << "Done doThresholdETCCalc" << endl;
1246 }
1247                 
1248
1249 // Check that the planes in traffic list are correctly ordered,
1250 // that the nearest (timewise) is flagged next on rwy, and return
1251 // true if any threshold use conflicts are detected, false otherwise.
1252 bool FGTower::doThresholdUseOrder() {
1253         //cout << "Entering doThresholdUseOrder..." << endl;
1254         bool conflict = false;
1255         
1256         // Wipe out traffic list, go through circuit, app and hold list, and reorder them in traffic list.
1257         // Here's the rather simplistic assumptions we're using:
1258         // Currently all planes are assumed to be GA light singles with corresponding speeds and separation times.
1259         // In order of priority for runway use:
1260         // STRAIGHT_IN > CIRCUIT > HOLDING_FOR_DEPARTURE
1261         // No modification of planes speeds occurs - conflicts are resolved by delaying turn for base,
1262         // and holding planes until a space.
1263         // When calculating if a holding plane can use the runway, time clearance from last departure
1264         // as well as time clearance to next arrival must be considered.
1265         
1266         trafficList.clear();
1267         
1268         tower_plane_rec_list_iterator twrItr;
1269         // Do the approach list first
1270         //cout << "A" << flush;
1271         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1272                 TowerPlaneRec* tpr = *twrItr;
1273                 conflict = AddToTrafficList(tpr);
1274         }       
1275         // Then the circuit list
1276         //cout << "C" << flush;
1277         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1278                 TowerPlaneRec* tpr = *twrItr;
1279                 conflict = AddToTrafficList(tpr);
1280         }
1281         // And finally the hold list
1282         //cout << "H" << endl;
1283         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1284                 TowerPlaneRec* tpr = *twrItr;
1285                 AddToTrafficList(tpr, true);
1286         }
1287         
1288         if(0) {
1289         //if(ident == "KEMT") {
1290                 for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
1291                         TowerPlaneRec* tpr = *twrItr;
1292                         cout << tpr->plane.callsign << '\t' << tpr->eta << '\t';
1293                 }
1294                 cout << endl;
1295         }
1296         
1297         //cout << "Done doThresholdUseOrder" << endl;
1298         return(conflict);
1299 }
1300
1301
1302 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
1303 // i.e. list_pos = 1 implies next to use runway.
1304 double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) {
1305         if(trafficList.size() < list_pos) {
1306                 return(99999);
1307         }
1308
1309         tower_plane_rec_list_iterator twrItr;
1310         twrItr = trafficList.begin();
1311         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
1312         TowerPlaneRec* tpr = *twrItr;
1313         CalcETA(tpr, printout);
1314         //cout << "ETA returned = " << tpr->eta << '\n';
1315         return(tpr->eta);
1316 }
1317         
1318
1319 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
1320         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
1321         TowerPlaneRec* t = new TowerPlaneRec;
1322         t->plane = plane;
1323         t->planePtr = requestee;
1324         t->holdShortReported = true;
1325         t->clearedToLineUp = false;
1326         t->clearedToTakeOff = false;
1327         t->opType = operation;
1328         t->pos = requestee->GetPos();
1329         
1330         //cout << "Hold Short reported by " << plane.callsign << '\n';
1331         SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign);
1332
1333 /*      
1334         bool next = AddToTrafficList(t, true);
1335         if(next) {
1336                 double teta = GetTrafficETA(2);
1337                 if(teta < 150.0) {
1338                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1339                         //cout << "Reducing response time to request due imminent traffic\n";
1340                 }
1341         } else {
1342         }
1343 */
1344         // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme
1345
1346         holdList.push_back(t);
1347         
1348         responseReqd = true;
1349 }
1350
1351 // Register the presence of an AI plane at a point where contact would already have been made in real life
1352 // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns.
1353 void FGTower::RegisterAIPlane(PlaneRec plane, FGAIPlane* ai, tower_traffic_type op, PatternLeg lg) {
1354         // At the moment this is only going to be tested with inserting an AI plane on downwind
1355         TowerPlaneRec* t = new TowerPlaneRec;
1356         t->plane = plane;
1357         t->planePtr = ai;
1358         t->opType = op;
1359         t->leg = lg;
1360         t->pos = ai->GetPos();
1361         
1362         CalcETA(t);
1363         
1364         if(op == CIRCUIT && lg != LEG_UNKNOWN) {
1365                 AddToCircuitList(t);
1366         } else {
1367                 // FLAG A WARNING
1368         }
1369         
1370         doThresholdUseOrder();
1371 }
1372
1373 void FGTower::RequestLandingClearance(string ID) {
1374         //cout << "Request Landing Clearance called...\n";
1375         
1376         // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1377         // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1378         
1379         TowerPlaneRec* t = new TowerPlaneRec;
1380         t->isUser = true;
1381         t->clearedToLand = false;
1382         t->pos.setlon(user_lon_node->getDoubleValue());
1383         t->pos.setlat(user_lat_node->getDoubleValue());
1384         t->pos.setelev(user_elev_node->getDoubleValue());
1385         
1386         // TODO
1387         // Calculate where the user is in relation to the active runway and it's circuit
1388         // and set the op-type as appropriate.
1389         
1390         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1391         t->opType = STRAIGHT_IN;
1392         
1393         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
1394         t->plane.callsign = ID;
1395         
1396         appList.push_back(t);   // Not necessarily permanent
1397         AddToTrafficList(t);
1398 }
1399
1400 void FGTower::RequestDepartureClearance(string ID) {
1401         //cout << "Request Departure Clearance called...\n";
1402 }
1403         
1404 void FGTower::ReportFinal(string ID) {
1405         TowerPlaneRec* t = FindPlane(ID);
1406         if(t) {
1407                 t->finalReported = true;
1408                 t->finalAcknowledged = false;
1409                 if(!(t->clearedToLand)) {
1410                         responseReqd = true;
1411                 } // possibly respond with wind even if already cleared to land?
1412         } else {
1413                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportFinal(...)");
1414         }
1415 }
1416
1417 //void FGTower::ReportLongFinal(string ID);
1418 //void FGTower::ReportOuterMarker(string ID);
1419 //void FGTower::ReportMiddleMarker(string ID);
1420 //void FGTower::ReportInnerMarker(string ID);
1421 //void FGTower::ReportGoingAround(string ID);
1422
1423 void FGTower::ReportRunwayVacated(string ID) {
1424         //cout << "Report Runway Vacated Called...\n";
1425 }
1426
1427 TowerPlaneRec* FGTower::FindPlane(string ID) {
1428         tower_plane_rec_list_iterator twrItr;
1429         // Do the approach list first
1430         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
1431                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1432         }       
1433         // Then the circuit list
1434         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
1435                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1436         }
1437         // And finally the hold list
1438         for(twrItr = holdList.begin(); twrItr != holdList.end(); twrItr++) {
1439                 if((*twrItr)->plane.callsign == ID) return(*twrItr);
1440         }
1441         SG_LOG(SG_ATC, SG_WARN, "Unable to find " << ID << " in FGTower::FindPlane(...)");
1442         return(NULL);
1443 }
1444
1445 void FGTower::ReportDownwind(string ID) {
1446         //cout << "ReportDownwind(...) called\n";
1447         // Tell the plane reporting what number she is in the circuit
1448         TowerPlaneRec* t = FindPlane(ID);
1449         if(t) {
1450                 t->downwindReported = true;
1451                 responseReqd = true;
1452         } else {
1453                 SG_LOG(SG_ATC, SG_WARN, "WARNING: Unable to find plane " << ID << " in FGTower::ReportDownwind(...)");
1454         }
1455 }
1456
1457 ostream& operator << (ostream& os, tower_traffic_type ttt) {
1458         switch(ttt) {
1459         case(CIRCUIT):      return(os << "CIRCUIT");
1460         case(INBOUND):      return(os << "INBOUND");
1461         case(OUTBOUND):     return(os << "OUTBOUND");
1462         case(TTT_UNKNOWN):  return(os << "UNKNOWN");
1463         case(STRAIGHT_IN):  return(os << "STRAIGHT_IN");
1464         }
1465         return(os << "ERROR - Unknown switch in tower_traffic_type operator << ");
1466 }
1467