]> git.mxchange.org Git - flightgear.git/blob - src/ATC/ground.cxx
3e2e0f68b95268f04942e872575189f7d27bf943
[flightgear.git] / src / ATC / ground.cxx
1 // FGGround - a class to provide ground control at larger 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 <simgear/misc/sg_path.hxx>
22 #include <simgear/math/sg_random.h>
23 #include <simgear/debug/logstream.hxx>
24 #include <simgear/misc/sgstream.hxx>
25 #include <simgear/constants.h>
26 #include <Main/globals.hxx>
27
28 #include <stdlib.h>
29 #include STL_FSTREAM
30
31 #include "ground.hxx"
32 #include "ATCmgr.hxx"
33 #include "ATCutils.hxx"
34 #include "ATCdisplay.hxx"
35 #include "AILocalTraffic.hxx"
36
37 SG_USING_STD(ifstream);
38 SG_USING_STD(cout);
39
40 node::node() {
41 }
42
43 node::~node() {
44         for(unsigned int i=0; i < arcs.size(); ++i) {
45                 delete arcs[i];
46         }
47 }
48
49 // Make sure that a_path.cost += distance is safe from the moment it's created.
50 a_path::a_path() {
51         cost = 0;
52 }
53
54 FGGround::FGGround() {
55         ATCmgr = globals->get_ATC_mgr();
56         _type = GROUND;
57         networkLoadOK = false;
58         ground_traffic.erase(ground_traffic.begin(), ground_traffic.end());
59         ground_traffic_itr = ground_traffic.begin();
60         
61         // Init the property nodes - TODO - need to make sure we're getting surface winds.
62         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
63         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
64         
65         // TODO - get the actual airport elevation
66         aptElev = 0.0;
67 }
68
69 FGGround::FGGround(string id) {
70         ATCmgr = globals->get_ATC_mgr();
71         networkLoadOK = false;
72         ground_traffic.erase(ground_traffic.begin(), ground_traffic.end());
73         ground_traffic_itr = ground_traffic.begin();
74         ident = id;
75         
76         // Init the property nodes - TODO - need to make sure we're getting surface winds.
77         wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true);
78         wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true);
79         
80         // TODO - get the actual airport elevation
81         aptElev = 0.0;
82 }
83
84 FGGround::~FGGround() {
85 }
86
87 void FGGround::ParseRwyExits(node* np, char* es) {
88         char* token;
89         char estr[20];
90         strcpy(estr, es);
91         const char delimiters[] = "-";
92         token = strtok(estr, delimiters);
93         while(token != NULL) {
94                 int i = atoi(token);
95                 //cout << "token = " << token << endl;
96                 //cout << "rwy number = " << i << endl;
97                 //runways[(atoi(token))].exits.push_back(np);
98                 runways[i].exits.push_back(np);
99                 //cout << "token = " << token << '\n';
100                 token = strtok(NULL, delimiters);
101         }
102 }
103         
104
105 // Load the ground logical network of the current instances airport
106 // Return true if successfull.
107 // TODO - currently the file is assumed to reside in the base/ATC directory.
108 // This might change to something more thought out in the future.
109 // NOTE - currently it is assumed that all nodes are loaded before any arcs.
110 // It won't work ATM if this doesn't hold true.
111 bool FGGround::LoadNetwork() {
112         node* np;
113         arc* ap;
114         Gate* gp;
115         
116         int gateCount = 0;      // This is used to allocate gateID's from zero upwards
117         // This may well change in the future - probably to reading in the real-world
118         // gate numbers from file.
119         
120         ifstream fin;
121         SGPath path = globals->get_fg_root();
122         //string taxiPath = "ATC/" + ident + ".taxi";
123         string taxiPath = "ATC/KEMT.taxi";      // FIXME - HARDWIRED FOR TESTING
124         path.append(taxiPath);
125         
126         SG_LOG(SG_ATC, SG_INFO, "Trying to read taxiway data for " << ident << "...");
127         //cout << "Trying to read taxiway data for " << ident << "..." << endl;
128         fin.open(path.c_str(), ios::in);
129         if(!fin) {
130                 SG_LOG(SG_ATC, SG_ALERT, "Unable to open taxiway data input file " << path.c_str());
131                 //cout << "Unable to open taxiway data input file " << path.c_str() << endl;
132                 return(false);
133         }
134         
135         char ch;
136         char buf[30];
137         while(!fin.eof()) {
138                 fin >> buf;
139                 // Node, arc, or [End]?
140                 //cout << "Read in ground network element type = " << buf << endl;
141                 if(!strcmp(buf, "[End]")) {             // TODO - maybe make this more robust to spelling errors by just looking for '['
142                         SG_LOG(SG_ATC, SG_INFO, "Done reading " << path.c_str() << endl);
143                         break;
144                 } else if(!strcmp(buf, "N")) {
145                         // Node
146                         np = new node;
147                         np->struct_type = NODE;
148                         fin >> buf;
149                         np->nodeID = atoi(buf);
150                         fin >> buf;
151                         np->pos.setlon(atof(buf));
152                         fin >> buf;
153                         np->pos.setlat(atof(buf));
154                         fin >> buf;
155                         np->pos.setelev(atof(buf));
156                         fin >> buf;             // node type
157                         if(!strcmp(buf, "J")) {
158                                 np->type = JUNCTION;
159                         } else if(!strcmp(buf, "T")) {
160                                 np->type = TJUNCTION;
161                         } else if(!strcmp(buf, "H")) {
162                                 np->type = HOLD;
163                         } else {
164                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown node type in taxi network...\n");
165                                 delete np;
166                                 return(false);
167                         }
168                         fin >> buf;             // rwy exit information - gets parsed later - FRAGILE - will break if buf is reused.
169                         // Now the name
170                         fin >> ch;      // strip the leading " off
171                         np->name = "";
172                         while(1) {
173                                 fin.unsetf(ios::skipws);
174                                 fin >> ch;
175                                 if((ch == '"') || (ch == 0x0A)) {
176                                         break;
177                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
178                                 np->name += ch;
179                         }
180                         fin.setf(ios::skipws);
181                         network.push_back(np);
182                         // FIXME - fragile - replies on buf not getting modified from exits read to here
183                         // see if we also need to push it onto the runway exit list
184                         //cout << "strlen(buf) = " << strlen(buf) << endl;
185                         if(strlen(buf) > 2) {
186                                 //cout << "Calling ParseRwyExits for " << buf << endl;
187                                 ParseRwyExits(np, buf);
188                         }
189                 } else if(!strcmp(buf, "A")) {
190                         ap = new arc;
191                         ap->struct_type = ARC;
192                         fin >> buf;
193                         ap->n1 = atoi(buf);
194                         fin >> buf;
195                         ap->n2 = atoi(buf);
196                         fin >> buf;
197                         if(!strcmp(buf, "R")) {
198                                 ap->type = RUNWAY;
199                         } else if(!strcmp(buf, "T")) {
200                                 ap->type = TAXIWAY;
201                         } else {
202                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown arc type in taxi network...\n");
203                                 delete ap;
204                                 return(false);
205                         }
206                         // directed?
207                         fin >> buf;
208                         if(!strcmp(buf, "Y")) {
209                                 ap->directed = true;
210                         } else if(!strcmp(buf, "N")) {
211                                 ap->directed = false;
212                         } else {
213                                 SG_LOG(SG_ATC, SG_ALERT, "**** ERROR ***** Unknown arc directed value in taxi network - should be Y/N !!!\n");
214                                 delete ap;
215                                 return(false);
216                         }                       
217                         // Now the name
218                         ap->name = "";
219                         while(1) {
220                                 fin.unsetf(ios::skipws);
221                                 fin >> ch;
222                                 ap->name += ch;
223                                 if((ch == '"') || (ch == 0x0A)) {
224                                         break;
225                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
226                         }
227                         fin.setf(ios::skipws);
228                         ap->distance = (int)dclGetHorizontalSeparation(network[ap->n1]->pos, network[ap->n2]->pos);
229                         //cout << "Distance  = " << ap->distance << '\n';
230                         network[ap->n1]->arcs.push_back(ap);
231                         network[ap->n2]->arcs.push_back(ap);
232                 } else if(!strcmp(buf, "G")) {
233                         gp = new Gate;
234                         gp->struct_type = NODE;
235                         gp->type = GATE;
236                         fin >> buf;
237                         gp->nodeID = atoi(buf);
238                         fin >> buf;
239                         gp->pos.setlon(atof(buf));
240                         fin >> buf;
241                         gp->pos.setlat(atof(buf));
242                         fin >> buf;
243                         gp->pos.setelev(atof(buf));
244                         fin >> buf;             // gate type - ignore this for now
245                         fin >> buf;             // gate heading
246                         gp->heading = atoi(buf);
247                         // Now the name
248                         gp->name = "";
249                         while(1) {
250                                 fin.unsetf(ios::skipws);
251                                 fin >> ch;
252                                 gp->name += ch;
253                                 if((ch == '"') || (ch == 0x0A)) {
254                                         break;
255                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
256                         }
257                         fin.setf(ios::skipws);
258                         gp->id = gateCount;             // Warning - this will likely change in the future.
259                         gp->used = false;
260                         network.push_back(gp);
261                         gates[gateCount] = gp;
262                         gateCount++;
263                 } else {
264                         // Something has gone seriously pear-shaped
265                         SG_LOG(SG_ATC, SG_ALERT, "********* ERROR - unknown ground network element type... aborting read of " << path.c_str() << '\n');
266                         return(false);
267                 }
268                 
269                 fin >> skipeol;         
270         }
271         return(true);
272 }
273
274 void FGGround::Init() {
275         untowered = false;
276         
277         // Figure out which is the active runway - TODO - it would be better to have ground call tower
278         // for runway operation details, but at the moment we can't guarantee that tower control at a given airport
279         // will be initialised before ground so we can't do that.
280         DoRwyDetails();
281         //cout << "In FGGround::Init, active rwy is " << activeRwy << '\n';
282         ortho.Init(rwy.threshold_pos, rwy.hdg);
283
284         networkLoadOK = LoadNetwork();
285 }
286
287 void FGGround::Update(double dt) {
288         // Each time step, what do we need to do?
289         // We need to go through the list of outstanding requests and acknowedgements
290         // and process at least one of them.
291         // We need to go through the list of planes under our control and check if
292         // any need to be addressed.
293         // We need to check for planes not under our control coming within our 
294         // control area and address if necessary.
295         
296         // Lets take the example of a plane which has just contacted ground
297         // following landing - presumably requesting where to go?
298         // First we need to establish the position of the plane within the logical network.
299         // Next we need to decide where its going.
300         
301         if(ground_traffic.size()) {
302                 if(ground_traffic_itr == ground_traffic.end()) {
303                         ground_traffic_itr = ground_traffic.begin();
304                 }
305                 
306                 //Process(*ground_traffic_itr);
307                 GroundRec* g = *ground_traffic_itr;
308                 if(g->taxiRequestOutstanding) {
309                         double responseTime = 10.0;             // seconds - this should get more sophisticated at some point
310                         if(g->clearanceCounter > responseTime) {
311                                 // DO CLEARANCE
312                                 // TODO - move the mechanics of making up the transmission out of the main Update(...) routine.
313                                 string trns = "";
314                                 trns += g->plane.callsign;
315                                 trns += " taxi holding point runway ";  // TODO - add the holding point name
316                                 // eg " taxi holding point G2 runway "
317                                 trns += ConvertRwyNumToSpokenString(activeRwy);
318                                 if(_display) {
319                                         globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
320                                 }
321                                 g->planePtr->RegisterTransmission(1);   // cleared to taxi
322                                 g->clearanceCounter = 0.0;
323                                 g->taxiRequestOutstanding = false;
324                         } else {
325                                 g->clearanceCounter += (dt * ground_traffic.size());
326                         }
327                 } else if(((FGAILocalTraffic*)(g->planePtr))->AtHoldShort()) {          // That's a hack - eventually we should monitor actual position
328                         // HACK ALERT - the automatic cast to AILocalTraffic has to go once we have other sorts working!!!!! FIXME TODO
329                         // NOTE - we don't need to do the contact tower bit unless we have separate tower and ground
330                         string trns = g->plane.callsign;
331                         trns += " contact Tower ";
332                         double f = globals->get_ATC_mgr()->GetFrequency(ident, TOWER) / 100.0;
333                         char buf[10];
334                         sprintf(buf, "%.2f", f);
335                         trns += buf;
336                         if(_display) {
337                                 globals->get_ATC_display()->RegisterSingleMessage(trns, 0);
338                         }
339                         g->planePtr->RegisterTransmission(2);   // contact tower
340                         delete *ground_traffic_itr;
341                         ground_traffic.erase(ground_traffic_itr);
342                         ground_traffic_itr = ground_traffic.begin();
343                 }                               
344                 ++ground_traffic_itr;
345         }
346         
347         // Call the base class update for the response time handling.
348         FGATC::Update(dt);
349 }
350
351 // Figure out which runways are active.
352 // For now we'll just be simple and do one active runway - eventually this will get much more complex
353 // Copied from FGTower - TODO - it would be better to implement this just once, and have ground call tower
354 // for runway operation details, but at the moment we can't guarantee that tower control at a given airport
355 // will be initialised before ground so we can't do that.
356 void FGGround::DoRwyDetails() {
357         //cout << "GetRwyDetails called" << endl;
358         
359         // Based on the airport-id and wind get the active runway
360         
361         //wind
362         double hdg = wind_from_hdg->getDoubleValue();
363         double speed = wind_speed_knots->getDoubleValue();
364         hdg = (speed == 0.0 ? 270.0 : hdg);
365         //cout << "Heading = " << hdg << '\n';
366         
367         FGRunway runway;
368         bool rwyGood = globals->get_runways()->search(ident, int(hdg), &runway);
369         if(rwyGood) {
370                 activeRwy = runway.rwy_no;
371                 rwy.rwyID = runway.rwy_no;
372                 SG_LOG(SG_ATC, SG_INFO, "In FGGround, active runway for airport " << ident << " is " << activeRwy);
373                 
374                 // Get the threshold position
375                 double other_way = runway.heading - 180.0;
376                 while(other_way <= 0.0) {
377                         other_way += 360.0;
378                 }
379         // move to the +l end/center of the runway
380                 //cout << "Runway center is at " << runway.lon << ", " << runway.lat << '\n';
381         Point3D origin = Point3D(runway.lon, runway.lat, aptElev);
382                 Point3D ref = origin;
383         double tshlon, tshlat, tshr;
384                 double tolon, tolat, tor;
385                 rwy.length = runway.length * SG_FEET_TO_METER;
386         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), other_way, 
387                                 rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr );
388         geo_direct_wgs_84 ( aptElev, ref.lat(), ref.lon(), runway.heading, 
389                                 rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor );
390                 // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user.
391                 // now copy what we need out of runway into rwy
392         rwy.threshold_pos = Point3D(tshlon, tshlat, aptElev);
393                 Point3D takeoff_end = Point3D(tolon, tolat, aptElev);
394                 //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n';
395                 //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n';
396                 rwy.hdg = runway.heading;
397                 // Set the projection for the local area based on this active runway
398                 ortho.Init(rwy.threshold_pos, rwy.hdg); 
399                 rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos);        // should come out as zero
400                 rwy.end2ortho = ortho.ConvertToLocal(takeoff_end);
401         } else {
402                 SG_LOG(SG_ATC, SG_ALERT, "Help  - can't get good runway in FGTower!!");
403                 activeRwy = "NN";
404         }
405 }
406
407 // Return a random gate ID of an unused gate.
408 // Two error values may be returned and must be checked for by the calling function:
409 // -2 signifies that no gates exist at this airport.
410 // -1 signifies that all gates are currently full.
411 int FGGround::GetRandomGateID() {
412         // Check that this airport actually has some gates!!
413         if(!gates.size()) {
414                 return(-2);
415         }
416
417         gate_vec_type gateVec;
418         int num = 0;
419         int thenum;
420         int ID;
421         
422         gatesItr = gates.begin();
423         while(gatesItr != gates.end()) {
424                 if((gatesItr->second)->used == false) {
425                         gateVec.push_back(gatesItr->second);
426                         num++;
427                 }
428                 ++gatesItr;
429         }
430
431         // Check that there are some unused gates!
432         if(!gateVec.size()) {
433                 return(-1);
434         }
435         
436         // Randomly select one from the list
437         sg_srandom_time();
438         thenum = (int)(sg_random() * gateVec.size());
439         ID = gateVec[thenum]->id;
440         
441         return(ID);
442 }
443
444 // Return a pointer to an unused gate node
445 Gate* FGGround::GetGateNode() {
446         int id = GetRandomGateID();
447         if(id < 0) {
448                 return(NULL);
449         } else {
450                 return(gates[id]);
451         }
452 }
453
454
455 node* FGGround::GetHoldShortNode(string rwyID) {
456         return(NULL);   // TODO - either implement me or remove me!!!
457 }
458
459
460 // WARNING - This is hardwired to my prototype logical network format
461 // and will almost certainly change when Bernie's stuff comes on-line.
462 // Returns NULL if it can't find a valid node.
463 node* FGGround::GetThresholdNode(string rwyID) {
464         // For now go through all the nodes and parse their names
465         // Maybe in the future we'll map threshold nodes by ID
466         //cout << "Size of network is " << network.size() << '\n';
467         for(unsigned int i=0; i<network.size(); ++i) {
468                 //cout << "Name = " << network[i]->name << '\n';
469                 if(network[i]->name.size()) {
470                         string s = network[i]->name;
471                         // Warning - the next bit is fragile and dependent on my current naming scheme
472                         //cout << "substr = " << s.substr(0,3) << '\n';
473                         //cout << "size of s = " << s.size() << '\n'; 
474                         if(s.substr(0,3) == "rwy") {
475                                 //cout << "subsubstr = " << s.substr(4, s.size() - 4) << '\n';
476                                 if(s.substr(4, s.size() - 4) == rwyID) {
477                                         return network[i];
478                                 }
479                         }
480                 }
481         }
482         return NULL;
483 }
484
485
486 // Get a path from a point on a runway to a gate
487 // TODO !!
488
489 // Get a path from a node to another node
490 // Eventually we will need complex algorithms for this taking other traffic,
491 // shortest path and suitable paths into accout.
492 // For now we'll just call the shortest path algorithm.
493 ground_network_path_type FGGround::GetPath(node* A, node* B) {  
494         return(GetShortestPath(A, B));
495 };
496
497 // Get a path from a node to a runway threshold
498 ground_network_path_type FGGround::GetPath(node* A, string rwyID) {
499         node* b = GetThresholdNode(rwyID);
500         if(b == NULL) {
501                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - unable to find path to runway theshold in ground.cxx for airport " << ident << '\n');
502                 ground_network_path_type emptyPath;
503                 emptyPath.erase(emptyPath.begin(), emptyPath.end());
504                 return(emptyPath);
505         }
506         return GetShortestPath(A, b);
507 }
508
509 // Get a path from a node to a runway hold short point
510 // Bit of a hack this at the moment!
511 ground_network_path_type FGGround::GetPathToHoldShort(node* A, string rwyID) {
512         ground_network_path_type path = GetPath(A, rwyID);
513         path.pop_back();        // That should be the threshold stripped of 
514         path.pop_back();        // and that should be the arc from hold short to threshold
515         // This isn't robust though - TODO - implement properly!
516         return(path);
517 }
518
519 // A shortest path algorithm from memory (ie. I can't find the bl&*dy book again!)
520 // I'm sure there must be enchancements that we can make to this, such as biasing the
521 // order in which the nodes are searched out from in favour of those geographically
522 // closer to the destination.
523 // Note that we are working with the master set of nodes and arcs so we mustn't change
524 // or delete them -  we only delete the paths that we create during the algorithm.
525 ground_network_path_type FGGround::GetShortestPath(node* A, node* B) {
526         a_path* pathPtr;
527         shortest_path_map_type pathMap;
528         node_array_type nodesLeft;
529         
530         // Debugging check
531         int pathsCreated = 0;
532         
533         // Initialise the algorithm
534         nodesLeft.push_back(A);
535         pathPtr = new a_path;
536         pathsCreated++;
537         pathPtr->path.push_back(A);
538         pathPtr->cost = 0;
539         pathMap[A->nodeID] = pathPtr;
540         bool solution_found = false;    // Flag to indicate that at least one candidate path has been found
541         int solution_cost = -1;                 // Cost of current best cost solution.  -1 indicates no solution found yet.
542         a_path solution_path;           
543                                                                                         
544         node* nPtr;     // nPtr is used to point to the node we are currently working with
545         
546         while(nodesLeft.size()) {
547                 //cout << "\n*****nodesLeft*****\n";
548                 //for(unsigned int i=0; i<nodesLeft.size(); ++i) {
549                         //cout << nodesLeft[i]->nodeID << '\n';
550                 //}
551                 //cout << "*******************\n\n";
552                 nPtr = *nodesLeft.begin();              // Thought - definate optimization possibilities here in the choice of which nodes we process first.
553                 nodesLeft.erase(nodesLeft.begin());
554                 //cout << "Walking out from node " << nPtr->nodeID << '\n';
555                 for(unsigned int i=0; i<nPtr->arcs.size(); ++i) {
556                         //cout << "ARC TO " << ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1) << '\n';
557                 }
558                 if((solution_found) && (solution_cost <= pathMap[nPtr->nodeID]->cost)) {
559                         // Do nothing - we've already found a solution and this partial path is already more expensive
560                 } else {
561                         // This path could still be better than the current solution - check it out
562                         for(unsigned int i=0; i<(nPtr->arcs.size()); i++) {
563                                 // Map the new path against the end node, ie. *not* the one we just started with.
564                                 unsigned int end_nodeID = ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1);
565                                 //cout << "end_nodeID = " << end_nodeID << '\n';
566                                 //cout << "pathMap size is " << pathMap.size() << '\n';
567                                 if(end_nodeID == nPtr->nodeID) {
568                                         //cout << "Circular arc!\n";
569                                         // Then its a circular arc - don't bother!!
570                                         //nPtr->arcs.erase(nPtr->arcs.begin() + i);
571                                 } else {
572                                         // see if the end node is already in the map or not
573                                         if(pathMap.find(end_nodeID) == pathMap.end()) {
574                                                 //cout << "Not in the map" << endl;;
575                                                 // Not in the map - easy!
576                                                 pathPtr = new a_path;
577                                                 pathsCreated++;
578                                                 *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
579                                                 pathPtr->path.push_back(nPtr->arcs[i]);
580                                                 pathPtr->path.push_back(network[end_nodeID]);
581                                                 pathPtr->cost += nPtr->arcs[i]->distance;
582                                                 pathMap[end_nodeID] = pathPtr;
583                                                 nodesLeft.push_back(network[end_nodeID]);       // By definition this can't be in the list already, or
584                                                 // it would also have been in the map and hence OR'd with this one.
585                                                 if(end_nodeID == B->nodeID) {
586                                                         //cout << "Solution found!!!" << endl;
587                                                         // Since this node wasn't in the map this is by definition the first solution
588                                                         solution_cost = pathPtr->cost;
589                                                         solution_path = *pathPtr;
590                                                         solution_found = true;
591                                                 }
592                                         } else {
593                                                 //cout << "Already in the map" << endl;
594                                                 // In the map - not so easy - need to get rid of an arc from the higher cost one.
595                                                 //cout << "Current cost of node " << end_nodeID << " is " << pathMap[end_nodeID]->cost << endl;
596                                                 int newCost = pathMap[nPtr->nodeID]->cost + nPtr->arcs[i]->distance;
597                                                 //cout << "New cost is of node " << nPtr->nodeID << " is " << newCost << endl;
598                                                 if(newCost >= pathMap[end_nodeID]->cost) {
599                                                         // No need to do anything.
600                                                         //cout << "Not doing anything!" << endl;
601                                                 } else {
602                                                         delete pathMap[end_nodeID];
603                                                         pathsCreated--;
604                                                         
605                                                         pathPtr = new a_path;
606                                                         pathsCreated++;
607                                                         *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
608                                                         pathPtr->path.push_back(nPtr->arcs[i]);
609                                                         pathPtr->path.push_back(network[end_nodeID]);
610                                                         pathPtr->cost += nPtr->arcs[i]->distance;
611                                                         pathMap[end_nodeID] = pathPtr;
612                                                         
613                                                         // We need to add this node to the list-to-do again to force a recalculation 
614                                                         // onwards from this node with the new lower cost to node cost.
615                                                         nodesLeft.push_back(network[end_nodeID]);
616                                                         
617                                                         if(end_nodeID == B->nodeID) {
618                                                                 //cout << "Solution found!!!" << endl;
619                                                                 // Need to check if there is a previous better solution
620                                                                 if((solution_cost < 0) || (pathPtr->cost < solution_cost)) {
621                                                                         solution_cost = pathPtr->cost;
622                                                                         solution_path = *pathPtr;
623                                                                         solution_found = true;
624                                                                 }
625                                                         }
626                                                 }
627                                         }
628                                 }
629                         }
630                 }
631         }
632         
633         // delete all the paths before returning
634         shortest_path_map_iterator spItr = pathMap.begin();
635         while(spItr != pathMap.end()) {
636                 if(spItr->second != NULL) {
637                         delete spItr->second;
638                         --pathsCreated;
639                 }
640                 ++spItr;
641         }
642         
643         //cout << "pathsCreated = " << pathsCreated << '\n';
644         if(pathsCreated > 0) {
645                 SG_LOG(SG_ATC, SG_ALERT, "WARNING - Possible memory leak in FGGround::GetShortestPath\n\
646                                                                           Please report to flightgear-devel@flightgear.org\n");
647         }
648         
649         //cout << (solution_found ? "Result: solution found\n" : "Result: no solution found\n");
650         return(solution_path.path);             // TODO - we really ought to have a fallback position incase a solution isn't found.
651 }
652                 
653
654
655 // Randomly or otherwise populate some of the gates with parked planes
656 // (might eventually be done by the AIMgr if and when lots of AI traffic is generated)
657
658 // Return a list of exits from a given runway
659 // It is up to the calling function to check for non-zero size of returned array before use
660 node_array_type FGGround::GetExits(string rwyID) {
661         // FIXME - get a 07L or similar in here and we're stuffed!!!
662         return(runways[atoi(rwyID.c_str())].exits);
663 }
664
665 void FGGround::RequestDeparture(PlaneRec plane, FGAIEntity* requestee) {
666         // For now we'll just automatically clear all planes to the runway hold.
667         // This communication needs to be delayed 20 sec or so from receiving the request.
668         // Even if display=false we still need to start the timer in case display=true when communication starts.
669         // We also need to bear in mind we also might have other outstanding communications, although for now we'll punt that issue!
670         // FIXME - sort the above!
671         
672         // HACK - assume that anything requesting departure is new for now - FIXME LATER
673         GroundRec* g = new GroundRec;
674         g->plane = plane;
675         g->planePtr = requestee;
676         g->taxiRequestOutstanding = true;
677         g->clearanceCounter = 0;
678         g->cleared = false;
679         g->incoming = false;
680         // TODO - need to handle the next 3 as well
681     //Point3D current_pos;
682     //node* destination;
683     //node* last_clearance;
684         
685         ground_traffic.push_back(g);
686 }
687
688 #if 0
689 void FGGround::NewArrival(plane_rec plane) {
690         // What are we going to do here?
691         // We need to start a new ground_rec and add the plane_rec to it
692         // We need to decide what gate we are going to clear it to.
693         // Then we need to add clearing it to that gate to the pending transmissions queue? - or simply transmit?
694         // Probably simply transmit for now and think about a transmission queue later if we need one.
695         // We might need one though in order to add a little delay for response time.
696         ground_rec* g = new ground_rec;
697         g->plane_rec = plane;
698         g->current_pos = ConvertWGS84ToXY(plane.pos);
699         g->node = GetNode(g->current_pos);  // TODO - might need to sort out node/arc here
700         AssignGate(g);
701         g->cleared = false;
702         ground_traffic.push_back(g);
703         NextClearance(g);
704 }
705
706 void FGGround::NewContact(plane_rec plane) {
707         // This is a bit of a convienience function at the moment and is likely to change.
708         if(at a gate or apron)
709                 NewDeparture(plane);
710         else
711                 NewArrival(plane);
712 }
713
714 void FGGround::NextClearance(ground_rec &g) {
715         // Need to work out where we can clear g to.
716         // Assume the pilot doesn't need progressive instructions
717         // We *should* already have a gate or holding point assigned by the time we get here
718         // but it wouldn't do any harm to check.
719         
720         // For now though we will hardwire it to clear to the final destination.
721 }
722
723 void FGGround::AssignGate(ground_rec &g) {
724         // We'll cheat for now - since we only have the user's aircraft and a couple of airports implemented
725         // we'll hardwire the gate!
726         // In the long run the logic of which gate or area to send the plane to could be somewhat non-trivial.
727 }
728 #endif //0
729