]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
Redo the runway database scheme to use a flat/ascii file and load the entire
[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 opType(TTT_UNKNOWN),
47 leg(LEG_UNKNOWN),
48 isUser(false)
49 {
50         plane.callsign = "UNKNOWN";
51 }
52
53 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
54 clearedToLand(false),
55 clearedToLineUp(false),
56 clearedToTakeOff(false),
57 holdShortReported(false),
58 longFinalReported(false),
59 longFinalAcknowledged(false),
60 finalReported(false),
61 finalAcknowledged(false),
62 opType(TTT_UNKNOWN),
63 leg(LEG_UNKNOWN),
64 isUser(false)
65 {
66         plane = p;
67 }
68
69 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
70 clearedToLand(false),
71 clearedToLineUp(false),
72 clearedToTakeOff(false),
73 holdShortReported(false),
74 longFinalReported(false),
75 longFinalAcknowledged(false),
76 finalReported(false),
77 finalAcknowledged(false),
78 opType(TTT_UNKNOWN),
79 leg(LEG_UNKNOWN),
80 isUser(false)
81 {
82         plane.callsign = "UNKNOWN";
83         pos = pt;
84 }
85
86 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
87 clearedToLand(false),
88 clearedToLineUp(false),
89 clearedToTakeOff(false),
90 holdShortReported(false),
91 longFinalReported(false),
92 longFinalAcknowledged(false),
93 finalReported(false),
94 finalAcknowledged(false),
95 opType(TTT_UNKNOWN),
96 leg(LEG_UNKNOWN),
97 isUser(false)
98 {
99         plane = p;
100         pos = pt;
101 }
102
103
104 // FGTower
105
106 FGTower::FGTower() {
107         ATCmgr = globals->get_ATC_mgr();
108         
109         // Init the property nodes - TODO - need to make sure we're getting surface winds.
110         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
111         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
112         
113         holdListItr = holdList.begin();
114         appListItr = appList.begin();
115         depListItr = depList.begin();
116         rwyListItr = rwyList.begin();
117         circuitListItr = circuitList.begin();
118         trafficListItr = trafficList.begin();
119 }
120
121 FGTower::~FGTower() {
122         if(!separateGround) {
123                 delete ground;
124         }
125 }
126
127 void FGTower::Init() {
128     display = false;
129         
130         // Pointers to user's position
131         user_lon_node = fgGetNode("/position/longitude-deg", true);
132         user_lat_node = fgGetNode("/position/latitude-deg", true);
133         user_elev_node = fgGetNode("/position/altitude-ft", true);
134         user_hdg_node = fgGetNode("/orientation/heading-deg", true);
135         
136         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
137         // I'll punt the startup issue for now though!!!
138         rwyOccupied = false;
139         
140         // Setup the ground control at this airport
141         AirportATC a;
142         //cout << "Tower ident = " << ident << '\n';
143         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
144                 if(a.ground_freq) {             // Ground control
145                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
146                         separateGround = true;
147                         if(ground == NULL) {
148                                 // Something has gone wrong :-(
149                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
150                                 ground = new FGGround(ident);
151                                 separateGround = false;
152                                 ground->Init();
153                                 if(display) {
154                                         ground->SetDisplay();
155                                 } else {
156                                         ground->SetNoDisplay();
157                                 }
158                         }
159                 } else {
160                         // Initialise ground anyway to do the shortest path stuff!
161                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
162                         ground = new FGGround(ident);
163                         separateGround = false;
164                         ground->Init();
165                         if(display) {
166                                 ground->SetDisplay();
167                         } else {
168                                 ground->SetNoDisplay();
169                         }
170                 }
171         } else {
172                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
173                 // Initialise ground anyway to avoid segfault later
174                 ground = new FGGround(ident);
175                 separateGround = false;
176                 ground->Init();
177                 if(display) {
178                         ground->SetDisplay();
179                 } else {
180                         ground->SetNoDisplay();
181                 }
182         }
183         
184         // Get the airport elevation
185         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
186         
187         DoRwyDetails();
188         
189         // FIXME - this currently assumes use of the active rwy by the user.
190         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
191         if(rwyOccupied) {
192                 // Assume the user is started at the threshold ready to take-off
193                 TowerPlaneRec* t = new TowerPlaneRec;
194                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
195                 t->opType = TTT_UNKNOWN;        // We don't know if the user wants to do circuits or a departure...
196                 t->leg = TAKEOFF_ROLL;
197                 t->isUser = true;
198                 t->planePtr = NULL;
199                 t->clearedToTakeOff = true;
200                 rwyList.push_back(t);
201         }
202 }
203
204 void FGTower::Update(double dt) {
205         static int ii = 0;      // Counter for spreading the load
206         int ii_max = 15;
207         //cout << "T" << flush;
208         // Each time step, what do we need to do?
209         // We need to go through the list of outstanding requests and acknowedgements
210         // and process at least one of them.
211         // We need to go through the list of planes under our control and check if
212         // any need to be addressed.
213         // We need to check for planes not under our control coming within our 
214         // control area and address if necessary.
215         
216         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
217         
218         // Sort the arriving planes
219         
220         // Calculate the eta of each plane to the threshold.
221         // For ground traffic this is the fastest they can get there.
222         // For air traffic this is the middle approximation.
223         if(ii == 1) {
224                 doThresholdETACalc();
225         }
226         
227         // Order the list of traffic as per expected threshold use and flag any conflicts
228         if(ii == 2) {
229                 bool conflicts = doThresholdUseOrder();
230         }
231         
232         // sortConficts() !!!
233         
234         // Do one plane from the hold list
235         if(ii == 4) {
236                 if(holdList.size()) {
237                         //cout << "*holdListItr = " << *holdListItr << endl;
238                         if(holdListItr == holdList.end()) {
239                                 holdListItr = holdList.begin();
240                         }
241                         //cout << "*holdListItr = " << *holdListItr << endl;
242                         //Process(*holdListItr);
243                         TowerPlaneRec* t = *holdListItr;
244                         //cout << "t = " << t << endl;
245                         if(t->holdShortReported) {
246                                 double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
247                                 if(t->clearanceCounter > responseTime) {
248                                         if(t->nextOnRwy) {
249                                                 if(rwyOccupied) {
250                                                         // Do nothing for now - consider acknowloging hold short eventually
251                                                 } else {
252                                                         // Lets Roll !!!!
253                                                         string trns = t->plane.callsign;
254                                                         //if(departed plane < some threshold in time away) {
255                                                                 if(0) {         // FIXME
256                                                                         trns += " line up";
257                                                                         t->clearedToLineUp = true;
258                                                                         t->planePtr->RegisterTransmission(3);   // cleared to line-up
259                                                                         t->leg = TAKEOFF_ROLL;
260                                                         //} else if(arriving plane < some threshold away) {
261                                                                 } else if(0) {  // FIXME
262                                                                         trns += " cleared immediate take-off";
263                                                                         // TODO - add traffic is... ?
264                                                                         t->clearedToTakeOff = true;
265                                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
266                                                                         t->leg = TAKEOFF_ROLL;
267                                                                 } else {
268                                                                         trns += " cleared for take-off";
269                                                                         // TODO - add traffic is... ?
270                                                                         t->clearedToTakeOff = true;
271                                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off
272                                                                         t->leg = TAKEOFF_ROLL;
273                                                                 }
274                                                                 if(display) {
275                                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
276                                                                 }
277                                                                 t->holdShortReported = false;
278                                                                 t->clearanceCounter = 0;
279                                                                 rwyList.push_back(t);
280                                                                 rwyOccupied = true;
281                                                                 holdList.erase(holdListItr);
282                                                                 holdListItr = holdList.begin();
283                                                 }
284                                         } else {
285                                                 // possibly tell him to hold and what position he is?
286                                         }
287                                 } else {
288                                         t->clearanceCounter += (dt * holdList.size() * ii_max);
289                                 }
290                         }                               
291                         ++holdListItr;
292                 }
293         }
294         
295         // 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!!
296         if(ii == 5) {
297                 if(rwyOccupied) {
298                         if(!rwyList.size()) {
299                                 rwyOccupied = false;
300                         } else {
301                                 rwyListItr = rwyList.begin();
302                                 TowerPlaneRec* t = *rwyListItr;
303                                 if(t->isUser) {
304                                         bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
305                                         // TODO - how do we find the position when it's not the user?
306                                         if(!on_rwy) {
307                                                 if((t->opType == INBOUND) || (t->opType == STRAIGHT_IN)) {
308                                                         rwyList.pop_front();
309                                                         delete t;
310                                                         // TODO - tell it to taxi / contact ground / don't delete it etc!
311                                                 } else if(t->opType == OUTBOUND) {
312                                                         depList.push_back(t);
313                                                         rwyList.pop_front();
314                                                 } else if(t->opType == CIRCUIT) {
315                                                         circuitList.push_back(t);
316                                                         rwyList.pop_front();
317                                                 } else if(t->opType == TTT_UNKNOWN) {
318                                                         depList.push_back(t);
319                                                         circuitList.push_back(t);
320                                                         rwyList.pop_front();
321                                                 } else {
322                                                         // HELP - we shouldn't ever get here!!!
323                                                 }
324                                         }
325                                 } // else TODO figure out what to do when it's not the user
326                         }
327                 }
328         }
329         
330         // do the ciruit list
331         if(ii == 6) {
332                 // Clear the constraints - we recalculate here.
333                 base_leg_pos = 0.0;
334                 downwind_leg_pos = 0.0;
335                 crosswind_leg_pos = 0.0;
336                 if(circuitList.size()) {
337                         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!!
338                         TowerPlaneRec* t = *circuitListItr;
339                         if(t->isUser) {
340                                 t->pos.setlon(user_lon_node->getDoubleValue());
341                                 t->pos.setlat(user_lat_node->getDoubleValue());
342                                 t->pos.setelev(user_elev_node->getDoubleValue());
343                         } else {
344                                 // TODO - set/update the position if it's an AI plane
345                         }
346                         Point3D tortho = ortho.ConvertToLocal(t->pos);
347                         if(t->isUser) {
348                                 // Need to figure out which leg he's on
349                                 //cout << "rwy.hdg = " << rwy.hdg << " user hdg = " << user_hdg_node->getDoubleValue();
350                                 double ho = GetAngleDiff_deg(user_hdg_node->getDoubleValue(), rwy.hdg);
351                                 //cout << " ho = " << ho << '\n';
352                                 // TODO FIXME - get the wind and convert this to track, or otherwise use track somehow!!!
353                                 // If it's gusty might need to filter the value, although we are leaving 30 degrees each way leeway!
354                                 if(abs(ho) < 30) {
355                                         // could be either takeoff, climbout or landing - check orthopos.y
356                                         //cout << "tortho.y = " << tortho.y() << '\n';
357                                         if((tortho.y() < 0) || (t->leg == TURN4) || (t->leg == FINAL)) {
358                                                 t->leg = FINAL;
359                                                 //cout << "Final\n";
360                                         } else {
361                                                 t->leg = CLIMBOUT;      // TODO - check elev wrt. apt elev to differentiate takeoff roll and climbout
362                                                 //cout << "Climbout\n";
363                                                 // If it's the user we may be unsure of his/her intentions.
364                                                 // (Hopefully the AI planes won't try confusing the sim!!!)
365                                                 if(t->opType == TTT_UNKNOWN) {
366                                                         if(tortho.y() > 5000) {
367                                                                 // 5 km out from threshold - assume it's a departure
368                                                                 t->opType = OUTBOUND;
369                                                                 // Since we are unknown operation we should be in depList already.
370                                                                 circuitList.erase(circuitListItr);
371                                                                 circuitListItr = circuitList.begin();
372                                                         }
373                                                 } else if(t->opType == CIRCUIT) {
374                                                         if(tortho.y() > 10000) {
375                                                                 // 10 km out - assume the user has abandoned the circuit!!
376                                                                 t->opType = OUTBOUND;
377                                                                 depList.push_back(t);
378                                                                 circuitList.erase(circuitListItr);
379                                                                 circuitListItr = circuitList.begin();
380                                                         }
381                                                 }
382                                         }
383                                 } else if(abs(ho) < 60) {
384                                         // turn1 or turn 4
385                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
386                                         if((t->leg == CLIMBOUT) || (t->leg == TURN1)) {
387                                                 t->leg = TURN1;
388                                                 //cout << "Turn1\n";
389                                         } else {
390                                                 t->leg = TURN4;
391                                                 //cout << "Turn4\n";
392                                         }
393                                 } else if(abs(ho) < 120) {
394                                         // crosswind or base
395                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
396                                         if((t->leg == TURN1) || (t->leg == CROSSWIND)) {
397                                                 t->leg = CROSSWIND;
398                                                 //cout << "Crosswind\n";
399                                         } else {
400                                                 t->leg = BASE;
401                                                 //cout << "Base\n";
402                                         }
403                                 } else if(abs(ho) < 150) {
404                                         // turn2 or turn 3
405                                         // TODO - either fix or doublecheck this hack by looking at heading and pattern direction
406                                         if((t->leg == CROSSWIND) || (t->leg == TURN2)) {
407                                                 t->leg = TURN2;
408                                                 //cout << "Turn2\n";
409                                         } else {
410                                                 t->leg = TURN3;
411                                                 //cout << "Turn3\n";
412                                         }
413                                 } else {
414                                         // downwind
415                                         t->leg = DOWNWIND;
416                                         //cout << "Downwind\n";
417                                 }
418                         } else {
419                                 t->leg = t->planePtr->GetLeg();
420                         }
421                         switch(t->leg) {
422                         case FINAL:
423                                 // 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.
424                                 base_leg_pos = tortho.y();
425                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
426                                 break;
427                         case TURN4:
428                                 // Fall through to base
429                         case BASE:
430                                 base_leg_pos = tortho.y();
431                                 //cout << "base_leg_pos = " << base_leg_pos << '\n';
432                                 break;
433                         case TURN3:
434                                 // Fall through to downwind
435                         case DOWNWIND:
436                                 // Only have the downwind leg pos as turn-to-base constraint if more negative than we already have.
437                                 base_leg_pos = (tortho.y() < base_leg_pos ? tortho.y() : base_leg_pos);
438                                 //cout << "base_leg_pos = " << base_leg_pos;
439                                 downwind_leg_pos = tortho.x();          // Assume that a following plane can simply be constrained by the immediately in front downwind plane
440                                 //cout << " downwind_leg_pos = " << downwind_leg_pos << '\n';
441                                 break;
442                         case TURN2:
443                                 // Fall through to crosswind
444                         case CROSSWIND:
445                                 crosswind_leg_pos = tortho.y();
446                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
447                                 break;
448                         case TURN1:
449                                 // Fall through to climbout
450                         case CLIMBOUT:
451                                 // Only use current by constraint as largest
452                                 crosswind_leg_pos = (tortho.y() > crosswind_leg_pos ? tortho.y() : crosswind_leg_pos);
453                                 //cout << "crosswind_leg_pos = " << crosswind_leg_pos << '\n';
454                                 break;
455                         case TAKEOFF_ROLL:
456                                 break;
457                         case LEG_UNKNOWN:
458                                 break;
459                         case LANDING_ROLL:
460                                 break;
461                         default:
462                                 break;
463                         }
464                 }
465         }
466         
467         doCommunication();
468         
469         if(!separateGround) {
470                 // The display stuff might have to get more clever than this when not separate 
471                 // since the tower and ground might try communicating simultaneously even though
472                 // they're mean't to be the same contoller/frequency!!
473                 if(display) {
474                         ground->SetDisplay();
475                 } else {
476                         ground->SetNoDisplay();
477                 }
478                 ground->Update(dt);
479         }
480         
481         ++ii;
482         // How big should ii get - ie how long should the update cycle interval stretch?
483         if(ii >= ii_max) {
484                 ii = 0;
485         }
486 }
487
488
489 // Returns true if positions of crosswind/downwind/base leg turns should be constrained by previous traffic
490 // plus the constraint position as a rwy orientated orthopos (meters)
491 bool FGTower::GetCrosswindConstraint(double& cpos) {
492         if(crosswind_leg_pos != 0.0) {
493                 cpos = crosswind_leg_pos;
494                 return(true);
495         } else {
496                 cpos = 0.0;
497                 return(false);
498         }
499 }
500 bool FGTower::GetDownwindConstraint(double& dpos) {
501         if(downwind_leg_pos != 0.0) {
502                 dpos = downwind_leg_pos;
503                 return(true);
504         } else {
505                 dpos = 0.0;
506                 return(false);
507         }
508 }
509 bool FGTower::GetBaseConstraint(double& bpos) {
510         if(base_leg_pos != 0.0) {
511                 bpos = base_leg_pos;
512                 return(true);
513         } else {
514                 bpos = 0.0;
515                 return(false);
516         }
517 }
518
519
520 // Figure out which runways are active.
521 // For now we'll just be simple and do one active runway - eventually this will get much more complex
522 // This is a private function - public interface to the results of this is through GetActiveRunway
523 void FGTower::DoRwyDetails() {
524         //cout << "GetRwyDetails called" << endl;
525         
526         // Based on the airport-id and wind get the active runway
527         
528         //wind
529         double hdg = wind_from_hdg->getDoubleValue();
530         double speed = wind_speed_knots->getDoubleValue();
531         hdg = (speed == 0.0 ? 270.0 : hdg);
532         //cout << "Heading = " << hdg << '\n';
533         
534         FGRunway runway;
535         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
536         if(rwyGood) {
537                 activeRwy = runway.rwy_no;
538                 rwy.rwyID = runway.rwy_no;
539                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
540                 
541                 // Get the threshold position
542                 double other_way = runway.heading - 180.0;
543                 while(other_way <= 0.0) {
544                         other_way += 360.0;
545                 }
546         // move to the +l end/center of the runway
547                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
548         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
549                 Point3D ref = origin;
550         double tshlon, tshlat, tshr;
551                 double tolon, tolat, tor;
552                 rwy.length = runway.length * SG_FEET_TO_METER;
553                 rwy.width = runway.width * SG_FEET_TO_METER;
554         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
555                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
556         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
557                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
558                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
559                 // now copy what we need out of runway into rwy
560         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
561                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
562                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
563                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
564                 rwy.hdg = runway.heading;
565                 // Set the projection for the local area based on this active runway
566                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
567                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
568                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
569         } else {
570                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
571                 activeRwy = "NN";
572         }
573 }
574
575
576 // Figure out if a given position lies on the active runway
577 // Might have to change when we consider more than one active rwy.
578 bool FGTower::OnActiveRunway(Point3D pt) {
579         // TODO - check that the centre calculation below isn't confused by displaced thesholds etc.
580         Point3D xyc((rwy.end1ortho.x() + rwy.end2ortho.x())/2.0, (rwy.end1ortho.y() + rwy.end2ortho.y())/2.0, 0.0);
581         Point3D xyp = ortho.ConvertToLocal(pt);
582         
583         //cout << "Length offset = " << fabs(xyp.y() - xyc.y()) << '\n';
584         //cout << "Width offset = " << fabs(xyp.x() - xyc.x()) << '\n';
585
586         double rlen = rwy.length/2.0 + 5.0;
587         double rwidth = rwy.width/2.0;
588         double ldiff = fabs(xyp.y() - xyc.y());
589         double wdiff = fabs(xyp.x() - xyc.x());
590
591         return((ldiff < rlen) && (wdiff < rwidth));
592 }       
593
594
595 // Figure out if a given position lies on any runway or not
596 // Only call this at startup - reading the runways database is expensive and needs to be fixed!
597 bool FGTower::OnAnyRunway(Point3D pt) {
598         ATCData ad;
599         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
600         if(dist < 0.0) {
601                 return(false);
602         }
603         // Based on the airport-id, go through all the runways and check for a point in them
604         
605         // TODO - do we actually need to search for the airport - surely we already know our ident and
606         // can just search runways of our airport???
607         //cout << "Airport ident is " << ad.ident << '\n';
608         FGRunway runway;
609         bool rwyGood = globals->get_runways()->search(ad.ident, &runway);
610         if(!rwyGood) {
611                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
612         }
613         bool on = false;
614         while(runway.id == ad.ident) {          
615                 on = OnRunway(pt, runway);
616                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
617                 if(on) return(true);
618                 globals->get_runways()->next(&runway);          
619         }
620         return(on);
621 }
622
623
624 // Calculate the eta of each plane to the threshold.
625 // For ground traffic this is the fastest they can get there.
626 // For air traffic this is the middle approximation.
627 void FGTower::doThresholdETACalc() {
628         // For now we'll be very crude and hardwire expected speeds to C172-like values
629         // The speeds below are specified in knots IAS and then converted to m/s
630         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
631         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
632         double final_ias = 70.0 * 0.514444;             // Speed during final approach
633
634         tower_plane_rec_list_iterator twrItr;
635
636         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
637         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
638         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
639                 TowerPlaneRec* tpr = *twrItr;
640                 Point3D op = ortho.ConvertToLocal(tpr->pos);
641                 double dist_out_m = op.y();
642                 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
643                 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
644                 if(tpr->opType == CIRCUIT) {
645                         // It's complicated - depends on if base leg is delayed or not
646                         if(tpr->leg == LANDING_ROLL) {
647                                 tpr->eta = 0;
648                         } else if((tpr->leg == FINAL) || (tpr->leg == TURN4)) {
649                                 tpr->eta = fabs(dist_out_m) / final_ias;
650                         } else if((tpr->leg == BASE) || (tpr->leg == TURN3)) {
651                                 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
652                         } else {
653                                 // Need to calculate where base leg is likely to be
654                                 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
655                                 // 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
656                                 double nominal_base_dist_out_m = -1000;
657                                 double current_base_dist_out_m = nominal_base_dist_out_m;
658                                 double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
659                                 double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
660                                 tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
661                                 if((tpr->leg == DOWNWIND) || (tpr->leg == TURN2)) {
662                                         tpr->eta += dist_across_m / circuit_ias;
663                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
664                                 } else if((tpr->leg == CROSSWIND) || (tpr->leg == TURN1)) {
665                                         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?
666                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
667                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
668                                 } else {
669                                         // We've only just started - why not use a generic estimate?
670                                 }
671                         }
672                 } else if((tpr->opType == INBOUND) || (tpr->opType == STRAIGHT_IN)) {
673                         // It's simpler!
674                 } else {
675                         // Must be outbound - ignore it!
676                 }
677                 //cout << "ETA = " << tpr->eta << '\n';
678         }
679 }
680                 
681
682 bool FGTower::doThresholdUseOrder() {
683         return(true);
684 }
685
686 void FGTower::doCommunication() {
687 }
688
689 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIPlane* requestee, tower_traffic_type operation) {
690         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
691         TowerPlaneRec* t = new TowerPlaneRec;
692         t->plane = plane;
693         t->planePtr = requestee;
694         t->holdShortReported = true;
695         t->clearanceCounter = 0;
696         t->clearedToLineUp = false;
697         t->clearedToTakeOff = false;
698         t->opType = operation;
699         
700         // HACK ALERT - THIS IS HARDWIRED FOR TESTING - FIXME TODO ETC
701         t->nextOnRwy = true;
702         
703         //cout << "t = " << t << '\n';
704         
705         holdList.push_back(t);
706 }
707
708 void FGTower::RequestLandingClearance(string ID) {
709         //cout << "Request Landing Clearance called...\n";
710 }
711 void FGTower::RequestDepartureClearance(string ID) {
712         //cout << "Request Departure Clearance called...\n";
713 }       
714 //void FGTower::ReportFinal(string ID);
715 //void FGTower::ReportLongFinal(string ID);
716 //void FGTower::ReportOuterMarker(string ID);
717 //void FGTower::ReportMiddleMarker(string ID);
718 //void FGTower::ReportInnerMarker(string ID);
719 //void FGTower::ReportGoingAround(string ID);
720 void FGTower::ReportRunwayVacated(string ID) {
721         //cout << "Report Runway Vacated Called...\n";
722 }