]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
Further progress towards interactive tower control. Very much an initial stab at...
[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 longFinalReported(false),
43 longFinalAcknowledged(false),
44 finalReported(false),
45 finalAcknowledged(false),
46 onRwy(false),
47 nextOnRwy(false),
48 opType(TTT_UNKNOWN),
49 leg(LEG_UNKNOWN),
50 isUser(false)
51 {
52         plane.callsign = "UNKNOWN";
53 }
54
55 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
56 clearedToLand(false),
57 clearedToLineUp(false),
58 clearedToTakeOff(false),
59 holdShortReported(false),
60 longFinalReported(false),
61 longFinalAcknowledged(false),
62 finalReported(false),
63 finalAcknowledged(false),
64 onRwy(false),
65 nextOnRwy(false),
66 opType(TTT_UNKNOWN),
67 leg(LEG_UNKNOWN),
68 isUser(false)
69 {
70         plane = p;
71 }
72
73 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
74 clearedToLand(false),
75 clearedToLineUp(false),
76 clearedToTakeOff(false),
77 holdShortReported(false),
78 longFinalReported(false),
79 longFinalAcknowledged(false),
80 finalReported(false),
81 finalAcknowledged(false),
82 onRwy(false),
83 nextOnRwy(false),
84 opType(TTT_UNKNOWN),
85 leg(LEG_UNKNOWN),
86 isUser(false)
87 {
88         plane.callsign = "UNKNOWN";
89         pos = pt;
90 }
91
92 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
93 clearedToLand(false),
94 clearedToLineUp(false),
95 clearedToTakeOff(false),
96 holdShortReported(false),
97 longFinalReported(false),
98 longFinalAcknowledged(false),
99 finalReported(false),
100 finalAcknowledged(false),
101 onRwy(false),
102 nextOnRwy(false),
103 opType(TTT_UNKNOWN),
104 leg(LEG_UNKNOWN),
105 isUser(false)
106 {
107         plane = p;
108         pos = pt;
109 }
110
111
112 // FGTower
113
114 FGTower::FGTower() {
115         ATCmgr = globals->get_ATC_mgr();
116         
117         // Init the property nodes - TODO - need to make sure we're getting surface winds.
118         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
119         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
120         
121         holdListItr = holdList.begin();
122         appListItr = appList.begin();
123         depListItr = depList.begin();
124         rwyListItr = rwyList.begin();
125         circuitListItr = circuitList.begin();
126         trafficListItr = trafficList.begin();
127         
128         freqClear = true;
129 }
130
131 FGTower::~FGTower() {
132         if(!separateGround) {
133                 delete ground;
134         }
135 }
136
137 void FGTower::Init() {
138     display = false;
139         
140         // Pointers to user's position
141         user_lon_node = fgGetNode("/position/longitude-deg", true);
142         user_lat_node = fgGetNode("/position/latitude-deg", true);
143         user_elev_node = fgGetNode("/position/altitude-ft", true);
144         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
145         
146         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
147         // I'll punt the startup issue for now though!!!
148         rwyOccupied = false;
149         
150         // Setup the ground control at this airport
151         AirportATC a;
152         //cout << "Tower ident = " << ident << '\n';
153         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
154                 if(a.ground_freq) {             // Ground control
155                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
156                         separateGround = true;
157                         if(ground == NULL) {
158                                 // Something has gone wrong :-(
159                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
160                                 ground = new FGGround(ident);
161                                 separateGround = false;
162                                 ground->Init();
163                                 if(display) {
164                                         ground->SetDisplay();
165                                 } else {
166                                         ground->SetNoDisplay();
167                                 }
168                         }
169                 } else {
170                         // Initialise ground anyway to do the shortest path stuff!
171                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
172                         ground = new FGGround(ident);
173                         separateGround = false;
174                         ground->Init();
175                         if(display) {
176                                 ground->SetDisplay();
177                         } else {
178                                 ground->SetNoDisplay();
179                         }
180                 }
181         } else {
182                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
183                 // Initialise ground anyway to avoid segfault later
184                 ground = new FGGround(ident);
185                 separateGround = false;
186                 ground->Init();
187                 if(display) {
188                         ground->SetDisplay();
189                 } else {
190                         ground->SetNoDisplay();
191                 }
192         }
193         
194         // Get the airport elevation
195         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
196         
197         DoRwyDetails();
198         
199         // FIXME - this currently assumes use of the active rwy by the user.
200         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
201         if(rwyOccupied) {
202                 // Assume the user is started at the threshold ready to take-off
203                 TowerPlaneRec* t = new TowerPlaneRec;
204                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
205                 t->plane.type = GA_SINGLE;
206                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
207                 t->leg = TAKEOFF_ROLL;
208                 t->isUser = true;
209                 t->planePtr = NULL;
210                 t->clearedToTakeOff = true;
211                 rwyList.push_back(t);
212         }
213 }
214
215 void FGTower::Update(double dt) {
216         static int ii = 0;      // Counter for spreading the load
217         int ii_max = 15;
218         //cout << "T" << flush;
219         // Each time step, what do we need to do?
220         // We need to go through the list of outstanding requests and acknowedgements
221         // and process at least one of them.
222         // We need to go through the list of planes under our control and check if
223         // any need to be addressed.
224         // We need to check for planes not under our control coming within our 
225         // control area and address if necessary.
226         
227         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
228         
229         // Sort the arriving planes
230         
231         // Calculate the eta of each plane to the threshold.
232         // For ground traffic this is the fastest they can get there.
233         // For air traffic this is the middle approximation.
234         if(ii == 1) {
235                 doThresholdETACalc();
236         }
237         
238         // Order the list of traffic as per expected threshold use and flag any conflicts
239         if(ii == 2) {
240                 bool conflicts = doThresholdUseOrder();
241         }
242         
243         // sortConficts() !!!
244         
245         // Do one plane from the hold list
246         if(ii == 4) {
247                 if(holdList.size()) {
248                         //cout << "*holdListItr = " << *holdListItr << endl;
249                         if(holdListItr == holdList.end()) {
250                                 holdListItr = holdList.begin();
251                         }
252                         //cout << "*holdListItr = " << *holdListItr << endl;
253                         //Process(*holdListItr);
254                         TowerPlaneRec* t = *holdListItr;
255                         //cout << "t = " << t << endl;
256                         if(t->holdShortReported) {
257                                 double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
258                                 if(t->clearanceCounter > responseTime) {
259                                         if(t->nextOnRwy) {
260                                                 if(rwyOccupied) {
261                                                         // Do nothing for now - consider acknowloging hold short eventually
262                                                 } else {
263                                                         // Lets Roll !!!!
264                                                         string trns = t->plane.callsign;
265                                                         //if(departed plane < some threshold in time away) {
266                                                                 if(0) {         // FIXME
267                                                                         trns += " line up";
268                                                                         t->clearedToLineUp = true;
269                                                                         t->planePtr->RegisterTransmission(3);   // cleared to line-up
270                                                                         t->leg = TAKEOFF_ROLL;
271                                                         //} else if(arriving plane < some threshold away) {
272                                                                 } else if(GetTrafficETA(2) < 150.0) {
273                                                                         trns += " cleared immediate take-off";
274                                                                         if(trafficList.size()) {
275                                                                                 tower_plane_rec_list_iterator trfcItr = trafficList.begin();
276                                                                                 trfcItr++;      // At the moment the holding plane should be first in trafficList.
277                                                                                                         // Note though that this will break if holding planes aren't put in trafficList in the future.
278                                                                                 TowerPlaneRec* trfc = *trfcItr;
279                                                                                 trns += "... traffic is";
280                                                                                 switch(trfc->plane.type) {
281                                                                                 case UNKNOWN:
282                                                                                         break;
283                                                                                 case GA_SINGLE:
284                                                                                         trns += " a Cessna";    // TODO - add ability to specify actual plane type somewhere
285                                                                                         break;
286                                                                                 case GA_HP_SINGLE:
287                                                                                         trns += " a Piper";
288                                                                                         break;
289                                                                                 case GA_TWIN:
290                                                                                         trns += " a King-air";
291                                                                                         break;
292                                                                                 case GA_JET:
293                                                                                         trns += " a Learjet";
294                                                                                         break;
295                                                                                 case MEDIUM:
296                                                                                         trns += " a Regional";
297                                                                                         break;
298                                                                                 case HEAVY:
299                                                                                         trns += " a Heavy";
300                                                                                         break;
301                                                                                 case MIL_JET:
302                                                                                         trns += " Military";
303                                                                                         break;
304                                                                                 }
305                                                                                 if(trfc->opType == STRAIGHT_IN || trfc->opType == TTT_UNKNOWN) {
306                                                                                         double miles_out = CalcDistOutMiles(trfc);
307                                                                                         if(miles_out < 2) {
308                                                                                                 trns += " on final";
309                                                                                         } else {
310                                                                                                 trns += " on ";
311                                                                                                 trns += ConvertNumToSpokenDigits((int)miles_out);
312                                                                                                 trns += " mile final";
313                                                                                         }
314                                                                                 } else if(trfc->opType == CIRCUIT) {
315                                                                                         switch(trfc->leg) {
316                                                                                         case FINAL:
317                                                                                                 trns += " on final";
318                                                                                                 break;
319                                                                                         case TURN4:
320                                                                                                 trns += " turning final";
321                                                                                                 break;
322                                                                                         case BASE:
323                                                                                                 trns += " on base";
324                                                                                                 break;
325                                                                                         case TURN3:
326                                                                                                 trns += " turning base";
327                                                                                                 break;
328                                                                                         case DOWNWIND:
329                                                                                                 trns += " in circuit";
330                                                                                                 break;
331                                                                                         // And to eliminate compiler warnings...
332                                                                                         case TAKEOFF_ROLL: break;
333                                                                                         case CLIMBOUT:     break;
334                                                                                         case TURN1:        break;
335                                                                                         case CROSSWIND:    break;
336                                                                                         case TURN2:        break;
337                                                                                         case LANDING_ROLL: break;
338                                                                                         case LEG_UNKNOWN:  break;
339                                                                                         }
340                                                                                 }
341                                                                         } else {
342                                                                                 // By definition there should be some arriving traffic if we're cleared for immediate takeoff
343                                                                                 SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower");
344                                                                         }
345                                                                         t->clearedToTakeOff = true;
346                                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
347                                                                         t->leg = TAKEOFF_ROLL;
348                                                                 } else {
349                                                                         trns += " cleared for take-off";
350                                                                         // TODO - add traffic is... ?
351                                                                         t->clearedToTakeOff = true;
352                                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off
353                                                                         t->leg = TAKEOFF_ROLL;
354                                                                 }
355                                                                 if(display) {
356                                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
357                                                                 }
358                                                                 t->holdShortReported = false;
359                                                                 t->clearanceCounter = 0;
360                                                                 rwyList.push_back(t);
361                                                                 rwyOccupied = true;
362                                                                 holdList.erase(holdListItr);
363                                                                 holdListItr = holdList.begin();
364                                                 }
365                                         } else {
366                                                 // Tell him to hold and what position he is.
367                                                 // Not currently sure under which circumstances we do or don't bother transmitting this.
368                                                 string trns = t->plane.callsign;
369                                                 trns += " hold position";
370                                                 if(display) {
371                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
372                                                 }
373                                                 t->holdShortReported = false;
374                                                 t->clearanceCounter = 0;
375                                                 // TODO - add some idea of what traffic is blocking him.
376                                         }
377                                 } else {
378                                         t->clearanceCounter += (dt * holdList.size() * ii_max);
379                                 }
380                         } else {        // not responding to report, but still need to clear if clear
381                                 if(t->nextOnRwy) {
382                                         if(rwyOccupied) {
383                                                 // Do nothing for now - consider acknowloging hold short eventually
384                                         } else {
385                                                 // Lets Roll !!!!
386                                                 string trns = t->plane.callsign;
387                                                 //if(departed plane < some threshold in time away) {
388                                                         if(0) {         // FIXME
389                                                                 trns += " line up";
390                                                                 t->clearedToLineUp = true;
391                                                                 t->planePtr->RegisterTransmission(3);   // cleared to line-up
392                                                                 t->leg = TAKEOFF_ROLL;
393                                                 //} else if(arriving plane < some threshold away) {
394                                                         } else if(GetTrafficETA(2) < 150.0) {
395                                                                 trns += " cleared immediate take-off";
396                                                                 // TODO - add traffic is... ?
397                                                                 t->clearedToTakeOff = true;
398                                                                 t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
399                                                                 t->leg = TAKEOFF_ROLL;
400                                                         } else {
401                                                                 trns += " cleared for take-off";
402                                                                 // TODO - add traffic is... ?
403                                                                 t->clearedToTakeOff = true;
404                                                                 t->planePtr->RegisterTransmission(4);   // cleared to take-off
405                                                                 t->leg = TAKEOFF_ROLL;
406                                                         }
407                                                         if(display) {
408                                                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
409                                                         }
410                                                         rwyList.push_back(t);
411                                                         rwyOccupied = true;
412                                                         holdList.erase(holdListItr);
413                                                         holdListItr = holdList.begin();
414                                         }
415                                 }
416                                 // TODO - remove the considerable code duplication above!
417                         }
418                         ++holdListItr;
419                 }
420         }
421         
422         // 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!!
423         // FIXME - at the moment it looks like we're only doing the first plane from the rwy list.
424         if(ii == 5) {
425                 if(rwyOccupied) {
426                         if(!rwyList.size()) {
427                                 rwyOccupied = false;
428                         } else {
429                                 rwyListItr = rwyList.begin();
430                                 TowerPlaneRec* t = *rwyListItr;
431                                 if(t->isUser) {
432                                         bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
433                                         // TODO - how do we find the position when it's not the user?
434                                         if(!on_rwy) {
435                                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
436                                                         rwyList.pop_front();
437                                                         delete t;
438                                                         // TODO - tell it to taxi / contact ground / don't delete it etc!
439                                                 } else if(t->opType == OUTBOUND) {
440                                                         depList.push_back(t);
441                                                         rwyList.pop_front();
442                                                 } else if(t->opType == CIRCUIT) {
443                                                         circuitList.push_back(t);
444                                                         //cout << "Oggy oggy oggy\n";
445                                                         AddToTrafficList(t);
446                                                         rwyList.pop_front();
447                                                 } else if(t->opType == TTT_UNKNOWN) {
448                                                         depList.push_back(t);
449                                                         circuitList.push_back(t);
450                                                         //cout << "Aggy aggy aggy\n";
451                                                         AddToTrafficList(t);
452                                                         rwyList.pop_front();
453                                                 } else {
454                                                         // HELP - we shouldn't ever get here!!!
455                                                 }
456                                         }
457                                 } // else TODO figure out what to do when it's not the user
458                         }
459                 }
460         }
461         
462         // do the ciruit list
463         if(ii == 6) {
464                 // Clear the constraints - we recalculate here.
465                 base_leg_pos = 0.0;
466                 downwind_leg_pos = 0.0;
467                 crosswind_leg_pos = 0.0;
468                 if(circuitList.size()) {
469                         circuitListItr = circuitList.begin();   // TODO - at the moment we're constraining plane 2 based on plane 1 - this won't work for 3 planes in the circuit!!
470                         TowerPlaneRec* t = *circuitListItr;
471                         if(t->isUser) {
472                                 t->pos.setlon(user_lon_node->getDoubleValue());
473                                 t->pos.setlat(user_lat_node->getDoubleValue());
474                                 t->pos.setelev(user_elev_node->getDoubleValue());
475                         } else {
476                                 // TODO - set/update the position if it's an AI plane
477                         }
478                         Point3D tortho = ortho.ConvertToLocal(t->pos);
479                         if(t->isUser) {
480                                 // Need to figure out which leg he's on
481                                 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
482                                 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
483                                 //cout << " ho = " << ho << '\n';
484                                 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
485                                 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
486                                 if(abs(ho) < 30) {
487                                         // could be either takeoff, climbout or landing - check orthopos.y
488                                         //cout << "tortho.y = " << tortho.y() << '\n';
489                                         if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
490                                                 t->leg = FINAL;
491                                                 //cout << "Final\n";
492                                         } else {
493                                                 t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
494                                                 //cout << "Climbout\n";
495                                                 // If it's the user we may be unsure of his/her intentions.
496                                                 // (Hopefully the AI planes won't try confusing the sim!!!)
497                                                 if(t->opType == TTT_UNKNOWN) {
498                                                         if(tortho.y() > 5000) {
499                                                                 // 5 km out from threshold - assume it's a departure
500                                                                 t->opType = OUTBOUND;   // TODO - could check if the user has climbed significantly above circuit altitude as well.
501                                                                 // Since we are unknown operation we should be in depList already.
502                                                                 circuitList.erase(circuitListItr);
503                                                                 RemoveFromTrafficList(t->plane.callsign);
504                                                                 circuitListItr = circuitList.begin();
505                                                         }
506                                                 } else if(t->opType == CIRCUIT) {
507                                                         if(tortho.y() > 10000) {
508                                                                 // 10 km out - assume the user has abandoned the circuit!!
509                                                                 t->opType = OUTBOUND;
510                                                                 depList.push_back(t);
511                                                                 circuitList.erase(circuitListItr);
512                                                                 circuitListItr = circuitList.begin();
513                                                         }
514                                                 }
515                                         }
516                                 } else if(abs(ho) < 60) {
517                                         // turn1 or turn 4
518                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
519                                         if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
520                                                 t->leg = TURN1;
521                                                 //cout << "Turn1\n";
522                                         } else {
523                                                 t->leg = TURN4;
524                                                 //cout << "Turn4\n";
525                                         }
526                                 } else if(abs(ho) < 120) {
527                                         // crosswind or base
528                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
529                                         if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
530                                                 t->leg = CROSSWIND;
531                                                 //cout << "Crosswind\n";
532                                         } else {
533                                                 t->leg = BASE;
534                                                 //cout << "Base\n";
535                                         }
536                                 } else if(abs(ho) < 150) {
537                                         // turn2 or turn 3
538                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
539                                         if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
540                                                 t->leg = TURN2;
541                                                 //cout << "Turn2\n";
542                                         } else {
543                                                 t->leg = TURN3;
544                                                 // Probably safe now to assume the user is flying a circuit
545                                                 t->opType = CIRCUIT;
546                                                 //cout << "Turn3\n";
547                                         }
548                                 } else {
549                                         // downwind
550                                         t->leg = DOWNWIND;
551                                         //cout << "Downwind\n";
552                                 }
553                         } else {
554                                 t->leg = t->planePtr->GetLeg();
555                         }
556                         switch(t->leg) {
557                         case FINAL:
558                                 // 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.
559                                 base_leg_pos = tortho.y();
560                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
561                                 break;
562                         case TURN4:
563                                 // Fall through to base
564                         case BASE:
565                                 base_leg_pos = tortho.y();
566                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
567                                 break;
568                         case TURN3:
569                                 // Fall through to downwind
570                         case DOWNWIND:
571                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
572                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
573                                 //cout << "base_leg_pos = " << base_leg_pos;
574                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
575                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
576                                 break;
577                         case TURN2:
578                                 // Fall through to crosswind
579                         case CROSSWIND:
580                                 crosswind_leg_pos = tortho.y();
581                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
582                                 break;
583                         case TURN1:
584                                 // Fall through to climbout
585                         case CLIMBOUT:
586                                 // Only use current by constraint as largest
587                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
588                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
589                                 break;
590                         case TAKEOFF_ROLL:
591                                 break;
592                         case LEG_UNKNOWN:
593                                 break;
594                         case LANDING_ROLL:
595                                 break;
596                         default:
597                                 break;
598                         }
599                 }
600         }
601         
602         // Do one plane from the approach list
603         if(ii == 7) {
604                 if(appList.size()) {
605                         if(appListItr == appList.end()) {
606                                 appListItr = appList.begin();
607                         }
608                         TowerPlaneRec* t = *appListItr;
609                         //cout << "t = " << t << endl;
610                         if(t->isUser) {
611                                 t->pos.setlon(user_lon_node->getDoubleValue());
612                                 t->pos.setlat(user_lat_node->getDoubleValue());
613                                 t->pos.setelev(user_elev_node->getDoubleValue());
614                         } else {
615                                 // TODO - set/update the position if it's an AI plane
616                         }                               
617                         if(t->nextOnRwy && !(t->clearedToLand)) {
618                                 // check distance away and whether runway occupied
619                                 // and schedule transmission if necessary
620                         }                               
621                         ++appListItr;
622                 }
623         }
624         
625         doCommunication();
626         
627         if(!separateGround) {
628                 // The display stuff might have to get more clever than this when not separate 
629                 // since the tower and ground might try communicating simultaneously even though
630                 // they're mean't to be the same contoller/frequency!!
631                 if(display) {
632                         ground->SetDisplay();
633                 } else {
634                         ground->SetNoDisplay();
635                 }
636                 ground->Update(dt);
637         }
638         
639         ++ii;
640         // How big should ii get - ie how long should the update cycle interval stretch?
641         if(ii >= ii_max) {
642                 ii = 0;
643         }
644
645         if(ident == "KEMT") {   
646                 // For AI debugging convienience - may be removed
647                 Point3D user_pos;
648                 user_pos.setlon(user_lon_node->getDoubleValue());
649                 user_pos.setlat(user_lat_node->getDoubleValue());
650                 user_pos.setelev(user_elev_node->getDoubleValue());
651                 Point3D user_ortho_pos = ortho.ConvertToLocal(user_pos);
652                 fgSetDouble("/AI/user/ortho-x", user_ortho_pos.x());
653                 fgSetDouble("/AI/user/ortho-y", user_ortho_pos.y());
654                 fgSetDouble("/AI/user/elev", user_elev_node->getDoubleValue());
655         }
656 }
657
658
659 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
660 // plus the constraint position as a rwy orientated orthopos (meters)
661 bool FGTower::GetCrosswindConstraint(double& cpos) {
662         if(crosswind_leg_pos != 0.0) {
663                 cpos = crosswind_leg_pos;
664                 return(true);
665         } else {
666                 cpos = 0.0;
667                 return(false);
668         }
669 }
670 bool FGTower::GetDownwindConstraint(double& dpos) {
671         if(downwind_leg_pos != 0.0) {
672                 dpos = downwind_leg_pos;
673                 return(true);
674         } else {
675                 dpos = 0.0;
676                 return(false);
677         }
678 }
679 bool FGTower::GetBaseConstraint(double& bpos) {
680         if(base_leg_pos != 0.0) {
681                 bpos = base_leg_pos;
682                 return(true);
683         } else {
684                 bpos = 0.0;
685                 return(false);
686         }
687 }
688
689
690 // Figure out which runways are active.
691 // For now we'll just be simple and do one active runway - eventually this will get much more complex
692 // This is a private function - public interface to the results of this is through GetActiveRunway
693 void FGTower::DoRwyDetails() {
694         //cout << "GetRwyDetails called" << endl;
695         
696         // Based on the airport-id and wind get the active runway
697         
698         //wind
699         double hdg = wind_from_hdg->getDoubleValue();
700         double speed = wind_speed_knots->getDoubleValue();
701         hdg = (speed == 0.0 ? 270.0 : hdg);
702         //cout << "Heading = " << hdg << '\n';
703         
704         FGRunway runway;
705         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
706         if(rwyGood) {
707                 activeRwy = runway.rwy_no;
708                 rwy.rwyID = runway.rwy_no;
709                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
710                 
711                 // Get the threshold position
712                 double other_way = runway.heading - 180.0;
713                 while(other_way <= 0.0) {
714                         other_way += 360.0;
715                 }
716         // move to the +l end/center of the runway
717                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
718         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
719                 Point3D ref = origin;
720         double tshlon, tshlat, tshr;
721                 double tolon, tolat, tor;
722                 rwy.length = runway.length * SG_FEET_TO_METER;
723                 rwy.width = runway.width * SG_FEET_TO_METER;
724         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
725                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
726         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
727                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
728                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
729                 // now copy what we need out of runway into rwy
730         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
731                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
732                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
733                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
734                 rwy.hdg = runway.heading;
735                 // Set the projection for the local area based on this active runway
736                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
737                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
738                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
739         } else {
740                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
741                 activeRwy = "NN";
742         }
743 }
744
745
746 // Figure out if a given position lies on the active runway
747 // Might have to change when we consider more than one active rwy.
748 bool FGTower::OnActiveRunway(Point3D pt) {
749         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
750         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
751         Point3D xyp = ortho.ConvertToLocal(pt);
752         
753         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
754         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
755
756         double rlen = rwy.length/2.0 + 5.0;
757         double rwidth = rwy.width/2.0;
758         double ldiff = fabs(xyp.y() - xyc.y());
759         double wdiff = fabs(xyp.x() - xyc.x());
760
761         return((ldiff < rlen) && (wdiff < rwidth));
762 }       
763
764
765 // Figure out if a given position lies on any runway or not
766 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
767 bool FGTower::OnAnyRunway(Point3D pt) {
768         ATCData ad;
769         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
770         if(dist < 0.0) {
771                 return(false);
772         }
773         // Based on the airport-id, go through all the runways and check for a point in them
774         
775         // TODO - do we actually need to search for the airport - surely we already know our ident and
776         // can just search runways of our airport???
777         //cout << "Airport ident is " << ad.ident << '\n';
778         FGRunway runway;
779         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
780         if(!rwyGood) {
781                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
782         }
783         bool on = false;
784         while(runway.id == ad.ident) {          
785                 on = OnRunway(pt, runway);
786                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
787                 if(on) return(true);
788                 globals->get_runways()->next(&runway);          
789         }
790         return(on);
791 }
792
793
794 // Returns true if successful
795 bool FGTower::RemoveFromTrafficList(string id) {
796         tower_plane_rec_list_iterator twrItr;
797         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
798                 TowerPlaneRec* tpr = *twrItr;
799                 if(tpr->plane.callsign == id) {
800                         trafficList.erase(twrItr);
801                         return(true);
802                 }
803         }       
804         SG_LOG(SG_ATC, SG_WARN, "Warning - unable to remove aircraft " << id << " from trafficList in FGTower");
805         return(false);
806 }
807
808
809 // Add a tower plane rec with ETA to the traffic list in the correct position ETA-wise
810 // and set nextOnRwy if so.
811 // Returns true if this could cause a threshold ETA conflict with other traffic, false otherwise.
812 // For planes holding they are put in the first position with time to go, and the return value is
813 // true if in the first position (nextOnRwy) and false otherwise.
814 bool FGTower::AddToTrafficList(TowerPlaneRec* t, bool holding) {
815         //cout << "AddToTrafficList called, currently size = " << trafficList.size() << ", holding = " << holding << '\n';
816         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.
817         bool conflict = false;
818         double lastETA = 0.0;
819         bool firstTime = true;
820         // FIXME - make this more robust for different plane types eg. light following heavy.
821         tower_plane_rec_list_iterator twrItr;
822         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
823                 TowerPlaneRec* tpr = *twrItr;
824                 if(holding) {
825                         //cout << (tpr->isUser ? "USER!\n" : "NOT user\n");
826                         //cout << "tpr->eta - lastETA = " << tpr->eta - lastETA << '\n';
827                         if(tpr->eta  - lastETA > separation_time) {
828                                 t->nextOnRwy = firstTime;
829                                 trafficList.insert(twrItr, t);
830                                 return(firstTime);
831                         }
832                         firstTime = false;
833                 } else {
834                         if(t->eta < tpr->eta) {
835                                 // Ugg - this one's tricky.
836                                 // It depends on what the two planes are doing and whether there's a conflict what we do.
837                                 if(tpr->eta - t->eta > separation_time) {       // No probs, plane 2 can squeeze in before plane 1 with no apparent conflict
838                                         if(tpr->nextOnRwy) {
839                                                 tpr->nextOnRwy = false;
840                                                 t->nextOnRwy = true;
841                                         }
842                                         trafficList.insert(twrItr, t);
843                                 } else {        // Ooops - this ones tricky - we have a potential conflict!
844                                         conflict = true;
845                                 }
846                                 return(conflict);
847                         }
848                 }
849         }
850         // If we get here we must be at the end of the list, or maybe the list is empty.
851         if(!trafficList.size()) {
852                 t->nextOnRwy = true;
853                 // conflict and firstTime should be false and true respectively in this case anyway.
854         }
855         trafficList.push_back(t);
856         return(holding ? firstTime : conflict);
857 }
858
859
860 // Calculate the eta of a plane to the threshold.
861 // For ground traffic this is the fastest they can get there.
862 // For air traffic this is the middle approximation.
863 void FGTower::CalcETA(TowerPlaneRec* tpr) {
864         // For now we'll be very crude and hardwire expected speeds to C172-like values
865         // The speeds below are specified in knots IAS and then converted to m/s
866         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
867         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
868         double final_ias = 70.0 * 0.514444;             // Speed during final approach
869         
870         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
871         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
872         
873         Point3D op = ortho.ConvertToLocal(tpr->pos);
874         double dist_out_m = op.y();
875         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
876         //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
877         
878         if(tpr->opType == STRAIGHT_IN) {
879                 double dist_to_go_m = sqrt((dist_out_m * dist_out_m) + (dist_across_m * dist_across_m));
880                 if(dist_to_go_m < 1000) {
881                         tpr->eta = dist_to_go_m / final_ias;
882                 } else {
883                         tpr->eta = (1000.0 / final_ias) + ((dist_to_go_m - 1000.0) / app_ias);
884                 }
885         } else if(tpr->opType == CIRCUIT || tpr->opType == TTT_UNKNOWN) {       // Hack alert - UNKNOWN has sort of been added here as a temporary hack.
886                 // It's complicated - depends on if base leg is delayed or not
887                 if(tpr->leg == LANDING_ROLL) {
888                         tpr->eta = 0;
889                 } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
890                         tpr->eta = fabs(dist_out_m) / final_ias;
891                 } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
892                         tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
893                 } else {
894                         // Need to calculate where base leg is likely to be
895                         // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
896                         // 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
897                         double nominal_base_dist_out_m = -1000;
898                         double current_base_dist_out_m;
899                         if(!GetBaseConstraint(current_base_dist_out_m)) {
900                                 current_base_dist_out_m = nominal_base_dist_out_m;
901                         }
902                         double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
903                         double current_dist_across_m;
904                         if(!GetDownwindConstraint(current_dist_across_m)) {
905                                 current_dist_across_m = nominal_dist_across_m;
906                         }
907                         double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
908                         tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
909                         if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
910                                 tpr->eta += dist_across_m / circuit_ias;
911                                 tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
912                         } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
913                                 tpr->eta += nominal_dist_across_m / circuit_ias;        // should we use the dist across of the previous plane if there is previous still on downwind?
914                                 tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
915                                 tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
916                         } else {
917                                 // We've only just started - why not use a generic estimate?
918                         }
919                 }
920                 //cout << "ETA = " << tpr->eta << '\n';
921         } else {
922                 tpr->eta = 99999;
923         }       
924 }
925
926
927 // Calculate the distance of a plane to the threshold in meters
928 // TODO - Modify to calculate flying distance of a plane in the circuit
929 double FGTower::CalcDistOutM(TowerPlaneRec* tpr) {
930         return(dclGetHorizontalSeparation(rwy.threshold_pos, tpr->pos));
931 }
932
933
934 // Calculate the distance of a plane to the threshold in miles
935 // TODO - Modify to calculate flying distance of a plane in the circuit
936 double FGTower::CalcDistOutMiles(TowerPlaneRec* tpr) {
937         return(CalcDistOutM(tpr) / 1600.0);             // FIXME - use a proper constant if possible.
938 }
939
940
941 // Iterate through all the lists and call CalcETA for all the planes.
942 void FGTower::doThresholdETACalc() {
943         tower_plane_rec_list_iterator twrItr;
944         // Do the approach list first
945         for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) {
946                 TowerPlaneRec* tpr = *twrItr;
947                 CalcETA(tpr);
948         }       
949         // Then the circuit list
950         for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) {
951                 TowerPlaneRec* tpr = *twrItr;
952                 CalcETA(tpr);
953         }
954 }
955                 
956
957 // Check that the planes in traffic list are correctly ordered,
958 // that the nearest (timewise) is flagged next on rwy, and return
959 // true if any threshold use conflicts are detected, false otherwise.
960 bool FGTower::doThresholdUseOrder() {
961         bool conflict = false;
962         
963         // TODO - write some code here!
964         
965         return(conflict);
966 }
967
968 void FGTower::doCommunication() {
969 }
970
971 // Return the ETA of plane no. list_pos (1-based) in the traffic list.
972 // i.e. list_pos = 1 implies next to use runway.
973 double FGTower::GetTrafficETA(unsigned int list_pos) {
974         if(trafficList.size() < list_pos) {
975                 return(99999);
976         }
977
978         tower_plane_rec_list_iterator twrItr;
979         twrItr = trafficList.begin();
980         for(unsigned int i = 1; i < list_pos; i++, twrItr++);
981         //cout << "ETA returned = " << (*twrItr)->eta << '\n';
982         return((*twrItr)->eta);
983 }
984         
985
986 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
987         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
988         TowerPlaneRec* t = new TowerPlaneRec;
989         t->plane = plane;
990         t->planePtr = requestee;
991         t->holdShortReported = true;
992         t->clearanceCounter = 0;
993         t->clearedToLineUp = false;
994         t->clearedToTakeOff = false;
995         t->opType = operation;
996         
997         //cout << "Hold Short reported by " << plane.callsign << '\n';
998         
999         bool next = AddToTrafficList(t, true);
1000         
1001         if(next) {
1002                 //cout << "Next to take off - respond with clearance\n";
1003                 double teta = GetTrafficETA(2);
1004                 if(teta < 150.0) {
1005                         t->clearanceCounter = 7.0;      // This reduces the delay before response to 3 secs if an immediate takeoff is reqd
1006                         //cout << "Reducing response time to request due imminent traffic\n";
1007                 }
1008         } else {
1009                 //cout << "Not next to take off - respond with hold\n";
1010         }
1011         
1012         //cout << "t = " << t << '\n';
1013         
1014         holdList.push_back(t);
1015 }
1016
1017 void FGTower::RequestLandingClearance(string ID) {
1018         //cout << "Request Landing Clearance called...\n";
1019         
1020         // Assume this comes from the user - have another function taking a pointer to the AIplane for the AI traffic.
1021         // For now we'll also assume that the user is a light plane and can get him/her to join the circuit if necessary.
1022         
1023         TowerPlaneRec* t = new TowerPlaneRec;
1024         t->isUser = true;
1025         t->clearedToLand = false;
1026         t->pos.setlon(user_lon_node->getDoubleValue());
1027         t->pos.setlat(user_lat_node->getDoubleValue());
1028         t->pos.setelev(user_elev_node->getDoubleValue());
1029         
1030         // TODO
1031         // Calculate where the user is in relation to the active runway and it's circuit
1032         // and set the op-type as appropriate.
1033         
1034         // HACK - to get up and running I'm going to assume that the user contacts tower on a staight-in final for now.
1035         t->opType = STRAIGHT_IN;
1036         
1037         t->plane.type = GA_SINGLE;      // FIXME - Another assumption!
1038         t->plane.callsign = ID;
1039         
1040         appList.push_back(t);   // Not necessarily permanent
1041         AddToTrafficList(t);
1042 }
1043
1044 void FGTower::RequestDepartureClearance(string ID) {
1045         //cout << "Request Departure Clearance called...\n";
1046 }       
1047 //void FGTower::ReportFinal(string ID);
1048 //void FGTower::ReportLongFinal(string ID);
1049 //void FGTower::ReportOuterMarker(string ID);
1050 //void FGTower::ReportMiddleMarker(string ID);
1051 //void FGTower::ReportInnerMarker(string ID);
1052 //void FGTower::ReportGoingAround(string ID);
1053 void FGTower::ReportRunwayVacated(string ID) {
1054         //cout << "Report Runway Vacated Called...\n";
1055 }