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