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