]> git.mxchange.org Git - flightgear.git/blob - src/ATC/tower.cxx
Moved the RunwayDetails struct definition out of tower.hxx to ATC.hxx
[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
32 SG_USING_STD(cout);
33
34 // TowerPlaneRec
35
36 TowerPlaneRec::TowerPlaneRec() :
37 clearedToLand(false),
38 clearedToLineUp(false),
39 clearedToTakeOff(false),
40 holdShortReported(false),
41 longFinalReported(false),
42 longFinalAcknowledged(false),
43 finalReported(false),
44 finalAcknowledged(false),
45 leg(TWR_UNKNOWN),
46 isUser(false)
47 {
48         plane.callsign = "UNKNOWN";
49 }
50
51 TowerPlaneRec::TowerPlaneRec(PlaneRec p) :
52 clearedToLand(false),
53 clearedToLineUp(false),
54 clearedToTakeOff(false),
55 holdShortReported(false),
56 longFinalReported(false),
57 longFinalAcknowledged(false),
58 finalReported(false),
59 finalAcknowledged(false),
60 leg(TWR_UNKNOWN),
61 isUser(false)
62 {
63         plane = p;
64 }
65
66 TowerPlaneRec::TowerPlaneRec(Point3D pt) :
67 clearedToLand(false),
68 clearedToLineUp(false),
69 clearedToTakeOff(false),
70 holdShortReported(false),
71 longFinalReported(false),
72 longFinalAcknowledged(false),
73 finalReported(false),
74 finalAcknowledged(false),
75 leg(TWR_UNKNOWN),
76 isUser(false)
77 {
78         plane.callsign = "UNKNOWN";
79         pos = pt;
80 }
81
82 TowerPlaneRec::TowerPlaneRec(PlaneRec p, Point3D pt) :
83 clearedToLand(false),
84 clearedToLineUp(false),
85 clearedToTakeOff(false),
86 holdShortReported(false),
87 longFinalReported(false),
88 longFinalAcknowledged(false),
89 finalReported(false),
90 finalAcknowledged(false),
91 leg(TWR_UNKNOWN),
92 isUser(false)
93 {
94         plane = p;
95         pos = pt;
96 }
97
98
99 // FGTower
100
101 FGTower::FGTower() {
102         ATCmgr = globals->get_ATC_mgr();
103         
104         // Init the property nodes - TODO - need to make sure we're getting surface winds.
105         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
106         wind_speed_knots = fgGetNode("/environment/wind-speed-kts", true);
107         
108         holdListItr = holdList.begin();
109         appListItr = appList.begin();
110         depListItr = depList.begin();
111         rwyListItr = rwyList.begin();
112         circuitListItr = circuitList.begin();
113         trafficListItr = trafficList.begin();
114 }
115
116 FGTower::~FGTower() {
117         if(!separateGround) {
118                 delete ground;
119         }
120 }
121
122 void FGTower::Init() {
123     display = false;
124         
125         // Pointers to user's position
126         user_lon_node = fgGetNode("/position/longitude-deg", true);
127         user_lat_node = fgGetNode("/position/latitude-deg", true);
128         user_elev_node = fgGetNode("/position/altitude-ft", true);
129         
130         // Need some way to initialise rwyOccupied flag correctly if the user is on the runway and to know its the user.
131         // I'll punt the startup issue for now though!!!
132         rwyOccupied = false;
133         
134         // Setup the ground control at this airport
135         AirportATC a;
136         //cout << "Tower ident = " << ident << '\n';
137         if(ATCmgr->GetAirportATCDetails(ident, &a)) {
138                 if(a.ground_freq) {             // Ground control
139                         ground = (FGGround*)ATCmgr->GetATCPointer(ident, GROUND);
140                         separateGround = true;
141                         if(ground == NULL) {
142                                 // Something has gone wrong :-(
143                                 SG_LOG(SG_ATC, SG_WARN, "ERROR - ground has frequency but can't get ground pointer :-(");
144                                 ground = new FGGround(ident);
145                                 separateGround = false;
146                                 ground->Init();
147                                 if(display) {
148                                         ground->SetDisplay();
149                                 } else {
150                                         ground->SetNoDisplay();
151                                 }
152                         }
153                 } else {
154                         // Initialise ground anyway to do the shortest path stuff!
155                         // Note that we're now responsible for updating and deleting this - NOT the ATCMgr.
156                         ground = new FGGround(ident);
157                         separateGround = false;
158                         ground->Init();
159                         if(display) {
160                                 ground->SetDisplay();
161                         } else {
162                                 ground->SetNoDisplay();
163                         }
164                 }
165         } else {
166                 SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details for " << ident << " in FGTower::Init()");
167                 // Initialise ground anyway to avoid segfault later
168                 ground = new FGGround(ident);
169                 separateGround = false;
170                 ground->Init();
171                 if(display) {
172                         ground->SetDisplay();
173                 } else {
174                         ground->SetNoDisplay();
175                 }
176         }
177         
178         // Get the airport elevation
179         aptElev = dclGetAirportElev(ident.c_str()) * SG_FEET_TO_METER;
180         
181         DoRwyDetails();
182         
183         // FIXME - this currently assumes use of the active rwy by the user.
184         rwyOccupied = OnAnyRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
185         if(rwyOccupied) {
186                 // Assume the user is started at the threshold ready to take-off
187                 TowerPlaneRec* t = new TowerPlaneRec;
188                 t->plane.callsign = "Charlie Foxtrot Sierra";   // C-FGFS !!! - fixme - this is a bit hardwired
189                 t->opType = OUTBOUND;   // How do we determine if the user actually wants to do circuits?
190                 t->isUser = true;
191                 t->planePtr = NULL;
192                 t->clearedToTakeOff = true;
193                 rwyList.push_back(t);
194         }
195 }
196
197 void FGTower::Update(double dt) {
198         //cout << "T" << flush;
199     // Each time step, what do we need to do?
200     // We need to go through the list of outstanding requests and acknowedgements
201     // and process at least one of them.
202     // We need to go through the list of planes under our control and check if
203     // any need to be addressed.
204     // We need to check for planes not under our control coming within our 
205     // control area and address if necessary.
206
207         // TODO - a lot of the below probably doesn't need to be called every frame and should be staggered.
208         
209         // Sort the arriving planes
210
211         // Calculate the eta of each plane to the threshold.
212         // For ground traffic this is the fastest they can get there.
213         // For air traffic this is the middle approximation.
214         doThresholdETACalc();
215         
216         // Order the list of traffic as per expected threshold use and flag any conflicts
217         bool conflicts = doThresholdUseOrder();
218         
219         // sortConficts() !!!
220         
221         // Do one plane from the hold list
222         if(holdList.size()) {
223                 //cout << "A" << endl;
224                 //cout << "*holdListItr = " << *holdListItr << endl;
225                 if(holdListItr == holdList.end()) {
226                         holdListItr = holdList.begin();
227                 }
228                 //cout << "*holdListItr = " << *holdListItr << endl;
229                 //Process(*holdListItr);
230                 TowerPlaneRec* t = *holdListItr;
231                 //cout << "t = " << t << endl;
232                 if(t->holdShortReported) {
233                         //cout << "B" << endl;
234                         double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
235                         if(t->clearanceCounter > responseTime) {
236                                 //cout << "C" << endl;
237                                 if(t->nextOnRwy) {
238                                         //cout << "D" << endl;
239                                         if(rwyOccupied) {
240                                                 //cout << "E" << endl;
241                                                 // Do nothing for now - consider acknowloging hold short eventually
242                                         } else {
243                                                 // Lets Roll !!!!
244                                                 string trns = t->plane.callsign;
245                                                 //if(departed plane < some threshold in time away) {
246                                                 if(0) {         // FIXME
247                                                         trns += " line up";
248                                                         t->clearedToLineUp = true;
249                                                         t->planePtr->RegisterTransmission(3);   // cleared to line-up
250                                                 //} else if(arriving plane < some threshold away) {
251                                                 } else if(0) {  // FIXME
252                                                         trns += " cleared immediate take-off";
253                                                         // TODO - add traffic is... ?
254                                                         t->clearedToTakeOff = true;
255                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off - TODO differentiate between immediate and normal take-off
256                                                 } else {
257                                                         trns += " cleared for take-off";
258                                                         // TODO - add traffic is... ?
259                                                         t->clearedToTakeOff = true;
260                                                         t->planePtr->RegisterTransmission(4);   // cleared to take-off
261                                                 }
262                                                 if(display) {
263                                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
264                                                 }
265                                                 t->holdShortReported = false;
266                                                 t->clearanceCounter = 0;
267                                                 rwyList.push_back(t);
268                                                 rwyOccupied = true;
269                                                 holdList.erase(holdListItr);
270                                                 holdListItr = holdList.begin();
271                                         }
272                                 } else {
273                                         // possibly tell him to hold and what position he is?
274                                 }
275                         } else {
276                                 t->clearanceCounter += (dt * holdList.size());
277                         }
278                 }                               
279                 ++holdListItr;
280         }
281         
282         // 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!!
283         if(rwyOccupied) {
284                 if(!rwyList.size()) {
285                         rwyOccupied = false;
286                 } else {
287                         rwyListItr = rwyList.begin();
288                         TowerPlaneRec* t = *rwyListItr;
289                         if(t->isUser) {
290                                 bool on_rwy = OnActiveRunway(Point3D(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0));
291                                 // TODO - how do we find the position when it's not the user?
292                                 if(!on_rwy) {
293                                         rwyList.pop_front();
294                                         delete t;
295                                 }
296                         } // else TODO figure out what to do when it's not the user
297                 }
298         }
299         
300         doCommunication();
301         
302         if(!separateGround) {
303                 // The display stuff might have to get more clever than this when not separate 
304                 // since the tower and ground might try communicating simultaneously even though
305                 // they're mean't to be the same contoller/frequency!!
306                 if(display) {
307                         ground->SetDisplay();
308                 } else {
309                         ground->SetNoDisplay();
310                 }
311                 ground->Update(dt);
312         }
313         //cout << "R " << flush;
314 }
315
316
317 // Figure out which runways are active.
318 // For now we'll just be simple and do one active runway - eventually this will get much more complex
319 // This is a private function - public interface to the results of this is through GetActiveRunway
320 void FGTower::DoRwyDetails() {
321         //cout << "GetRwyDetails called" << endl;
322         
323         // Based on the airport-id and wind get the active runway
324         SGPath path( globals->get_fg_root() );
325         path.append( "Airports" );
326         path.append( "runways.mk4" );
327         FGRunways runways( path.c_str() );
328         
329         //wind
330         double hdg = wind_from_hdg->getDoubleValue();
331         double speed = wind_speed_knots->getDoubleValue();
332         hdg = (speed == 0.0 ? 270.0 : hdg);
333         //cout << "Heading = " << hdg << '\n';
334         
335         FGRunway runway;
336         bool rwyGood = runways.search(ident, int(hdg), &runway);
337         if(rwyGood) {
338                 activeRwy = runway.rwy_no;
339                 rwy.rwyID = runway.rwy_no;
340                 SG_LOG(SG_ATC, SG_INFO, "Active runway for airport " << ident << " is " << activeRwy);
341                 
342                 // Get the threshold position
343                 double other_way = runway.heading - 180.0;
344                 while(other_way <= 0.0) {
345                         other_way += 360.0;
346                 }
347         // move to the +l end/center of the runway
348                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
349         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
350                 Point3D ref = origin;
351         double tshlon, tshlat, tshr;
352                 double tolon, tolat, tor;
353                 rwy.length = runway.length * SG_FEET_TO_METER;
354         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
355                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
356         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
357                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
358                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
359                 // now copy what we need out of runway into rwy
360         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
361                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
362                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
363                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
364                 rwy.hdg = runway.heading;
365                 // Set the projection for the local area based on this active runway
366                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
367                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
368                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
369         } else {
370                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
371                 activeRwy = "NN";
372         }
373 }
374
375
376 // Figure out if a given position lies on the active runway
377 // Might have to change when we consider more than one active rwy.
378 bool FGTower::OnActiveRunway(Point3D pt) {
379         SGPath path( globals->get_fg_root() );
380         path.append( "Airports" );
381         path.append( "runways.mk4" );
382         FGRunways runways( path.c_str() );
383         
384         FGRunway runway;
385         bool rwyGood = runways.search(ident, activeRwy, &runway);
386         if(!rwyGood) {
387                 SG_LOG(SG_ATC, SG_WARN, "Unable to find runway " << activeRwy << " for airport ID " << ident << " in FGTower");
388         }
389         return(OnRunway(pt, &runway) ? true : false);
390 }       
391
392
393 // Figure out if a given position lies on any runway or not
394 bool FGTower::OnAnyRunway(Point3D pt) {
395         ATCData ad;
396         double dist = current_commlist->FindClosest(lon, lat, elev, ad, TOWER, 10.0);
397         if(dist < 0.0) {
398                 return(false);
399         }
400         // Based on the airport-id, go through all the runways and check for a point in them
401         SGPath spath( globals->get_fg_root() );
402         spath.append( "Airports" );
403         spath.append( "runways.mk4" );
404         FGRunways runways( spath.c_str() );
405         
406         // TODO - do we actually need to search for the airport - surely we already know our ident and
407         // can just search runways of our airport???
408         //cout << "Airport ident is " << ad.ident << '\n';
409         FGRunway runway;
410         bool rwyGood = runways.search(ad.ident, &runway);
411         if(!rwyGood) {
412                 SG_LOG(SG_ATC, SG_WARN, "Unable to find any runways for airport ID " << ad.ident << " in FGTower");
413         }
414         bool on = false;
415         while(runway.id == ad.ident) {          
416                 on = OnRunway(pt, &runway);
417                 //cout << "Runway " << runway.rwy_no << ": On = " << (on ? "true\n" : "false\n");
418                 if(on) return(true);
419                 runways.next(&runway);          
420         }
421         return(on);
422 }
423
424
425 // Calculate the eta of each plane to the threshold.
426 // For ground traffic this is the fastest they can get there.
427 // For air traffic this is the middle approximation.
428 void FGTower::doThresholdETACalc() {
429         // For now we'll be very crude and hardwire expected speeds to C172-like values
430         // The speeds below are specified in knots IAS and then converted to m/s
431         double app_ias = 100.0 * 0.514444;                      // Speed during straight-in approach
432         double circuit_ias = 80.0 * 0.514444;           // Speed around circuit
433         double final_ias = 70.0 * 0.514444;             // Speed during final approach
434
435         tower_plane_rec_list_iterator twrItr;
436
437         // Sign convention - dist_out is -ve for approaching planes and +ve for departing planes
438         // dist_across is +ve in the pattern direction - ie a plane correctly on downwind will have a +ve dist_across
439         for(twrItr = trafficList.begin(); twrItr != trafficList.end(); twrItr++) {
440                 TowerPlaneRec* tpr = *twrItr;
441                 Point3D op = ortho.ConvertToLocal(tpr->pos);
442                 double dist_out_m = op.y();
443                 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
444                 //cout << "Doing ETA calc for " << tpr->plane.callsign << '\n';
445                 if(tpr->opType == CIRCUIT) {
446                         // It's complicated - depends on if base leg is delayed or not
447                         if(tpr->leg == TWR_LANDING_ROLL) {
448                                 tpr->eta = 0;
449                         } else if(tpr->leg == TWR_FINAL) {
450                                 tpr->eta = fabs(dist_out_m) / final_ias;
451                         } else if(tpr->leg == TWR_BASE) {
452                                 tpr->eta = (fabs(dist_out_m) / final_ias) + (dist_across_m / circuit_ias);
453                         } else {
454                                 // Need to calculate where base leg is likely to be
455                                 // FIXME - for now I'll hardwire it to 1000m which is what AILocalTraffic uses!!!
456                                 // 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
457                                 double nominal_base_dist_out_m = -1000;
458                                 double current_base_dist_out_m = nominal_base_dist_out_m;
459                                 double nominal_dist_across_m = 1000;    // Hardwired value from AILocalTraffic
460                                 double nominal_cross_dist_out_m = 1000; // Bit of a guess - AI plane turns to crosswind at 600ft agl.
461                                 tpr->eta = fabs(current_base_dist_out_m) / final_ias;   // final
462                                 if(tpr->leg == TWR_DOWNWIND) {
463                                         tpr->eta += dist_across_m / circuit_ias;
464                                         tpr->eta += fabs(current_base_dist_out_m - dist_out_m) / circuit_ias;
465                                 } else if(tpr->leg == TWR_CROSSWIND) {
466                                         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?
467                                         tpr->eta += fabs(current_base_dist_out_m - nominal_cross_dist_out_m) / circuit_ias;
468                                         tpr->eta += (nominal_dist_across_m - dist_across_m) / circuit_ias;
469                                 } else {
470                                         // We've only just started - why not use a generic estimate?
471                                 }
472                         }
473                 } else if((tpr->opType == INBOUND) || (tpr->opType == STRAIGHT_IN)) {
474                         // It's simpler!
475                 } else {
476                         // Must be outbound - ignore it!
477                 }
478                 //cout << "ETA = " << tpr->eta << '\n';
479         }
480 }
481                 
482
483 bool FGTower::doThresholdUseOrder() {
484         return(true);
485 }
486
487 void FGTower::doCommunication() {
488 }
489
490 void FGTower::ContactAtHoldShort(PlaneRec plane, FGAIEntity* requestee, tower_traffic_type operation) {
491         // HACK - assume that anything contacting at hold short is new for now - FIXME LATER
492         TowerPlaneRec* t = new TowerPlaneRec;
493         t->plane = plane;
494         t->planePtr = requestee;
495         t->holdShortReported = true;
496         t->clearanceCounter = 0;
497         t->clearedToLineUp = false;
498         t->clearedToTakeOff = false;
499         t->opType = operation;
500         
501         // HACK ALERT - THIS IS HARDWIRED FOR TESTING - FIXME TODO ETC
502         t->nextOnRwy = true;
503         
504         //cout << "t = " << t << '\n';
505         
506         holdList.push_back(t);
507 }
508
509 void FGTower::RequestLandingClearance(string ID) {
510         //cout << "Request Landing Clearance called...\n";
511 }
512 void FGTower::RequestDepartureClearance(string ID) {
513         //cout << "Request Departure Clearance called...\n";
514 }       
515 //void FGTower::ReportFinal(string ID);
516 //void FGTower::ReportLongFinal(string ID);
517 //void FGTower::ReportOuterMarker(string ID);
518 //void FGTower::ReportMiddleMarker(string ID);
519 //void FGTower::ReportInnerMarker(string ID);
520 //void FGTower::ReportGoingAround(string ID);
521 void FGTower::ReportRunwayVacated(string ID) {
522         //cout << "Report Runway Vacated Called...\n";
523 }