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