]> git.mxchange.org Git - flightgear.git/blob - src/ATC/ground.cxx
Removed a lot of the remaining hardwired KEMT stuff, made the initialisation more...
[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 "ATCutils.hxx"
33
34 SG_USING_STD(ifstream);
35 SG_USING_STD(cout);
36
37 node::node() {
38 }
39
40 node::~node() {
41         for(unsigned int i=0; i < arcs.size(); ++i) {
42                 delete arcs[i];
43         }
44 }
45
46 // Make sure that a_path.cost += distance is safe from the moment it's created.
47 a_path::a_path() {
48         cost = 0;
49 }
50
51 FGGround::FGGround() {
52         display = false;
53         networkLoadOK = false;
54 }
55
56 FGGround::~FGGround() {
57 }
58
59 void FGGround::ParseRwyExits(node* np, char* es) {
60         char* token;
61         char estr[20];
62         strcpy(estr, es);
63         const char delimiters[] = "-";
64         token = strtok(estr, delimiters);
65         while(token != NULL) {
66                 int i = atoi(token);
67                 //cout << "token = " << token << endl;
68                 //cout << "rwy number = " << i << endl;
69                 //runways[(atoi(token))].exits.push_back(np);
70                 runways[i].exits.push_back(np);
71                 //cout << "token = " << token << '\n';
72                 token = strtok(NULL, delimiters);
73         }
74 }
75         
76
77 // Load the ground logical network of the current instances airport
78 // Return true if successfull.
79 // TODO - currently the file is assumed to reside in the base/ATC directory.
80 // This might change to something more thought out in the future.
81 // NOTE - currently it is assumed that all nodes are loaded before any arcs.
82 // It won't work ATM if this doesn't hold true.
83 bool FGGround::LoadNetwork() {
84         node* np;
85         arc* ap;
86         Gate* gp;
87         
88         int gateCount = 0;      // This is used to allocate gateID's from zero upwards
89         // This may well change in the future - probably to reading in the real-world
90         // gate numbers from file.
91         
92         ifstream fin;
93         SGPath path = globals->get_fg_root();
94         //string taxiPath = "ATC/" + ident + ".taxi";
95         string taxiPath = "ATC/KEMT.taxi";      // FIXME - HARDWIRED FOR TESTING
96         path.append(taxiPath);
97         
98         SG_LOG(SG_GENERAL, SG_INFO, "Trying to read taxiway data for " << ident << "...");
99         //cout << "Trying to read taxiway data for " << ident << "..." << endl;
100         fin.open(path.c_str(), ios::in);
101         if(!fin) {
102                 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to open taxiway data input file " << path.c_str());
103                 //cout << "Unable to open taxiway data input file " << path.c_str() << endl;
104                 return(false);
105         }
106         
107         char ch;
108         char buf[30];
109         while(!fin.eof()) {
110                 fin >> buf;
111                 // Node, arc, or [End]?
112                 //cout << "Read in ground network element type = " << buf << endl;
113                 if(!strcmp(buf, "[End]")) {             // TODO - maybe make this more robust to spelling errors by just looking for '['
114                         SG_LOG(SG_GENERAL, SG_INFO, "Done reading " << path.c_str() << endl);
115                         break;
116                 } else if(!strcmp(buf, "N")) {
117                         // Node
118                         np = new node;
119                         np->struct_type = NODE;
120                         fin >> buf;
121                         np->nodeID = atoi(buf);
122                         fin >> buf;
123                         np->pos.setlon(atof(buf));
124                         fin >> buf;
125                         np->pos.setlat(atof(buf));
126                         fin >> buf;
127                         np->pos.setelev(atof(buf));
128                         fin >> buf;             // node type
129                         if(!strcmp(buf, "J")) {
130                                 np->type = JUNCTION;
131                         } else if(!strcmp(buf, "T")) {
132                                 np->type = TJUNCTION;
133                         } else if(!strcmp(buf, "H")) {
134                                 np->type = HOLD;
135                         } else {
136                                 SG_LOG(SG_GENERAL, SG_ALERT, "**** ERROR ***** Unknown node type in taxi network...\n");
137                                 delete np;
138                                 return(false);
139                         }
140                         fin >> buf;             // rwy exit information - gets parsed later - FRAGILE - will break if buf is reused.
141                         // Now the name
142                         fin >> ch;      // strip the leading " off
143                         np->name = "";
144                         while(1) {
145                                 fin.unsetf(ios::skipws);
146                                 fin >> ch;
147                                 if((ch == '"') || (ch == 0x0A)) {
148                                         break;
149                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
150                                 np->name += ch;
151                         }
152                         fin.setf(ios::skipws);
153                         network.push_back(np);
154                         // FIXME - fragile - replies on buf not getting modified from exits read to here
155                         // see if we also need to push it onto the runway exit list
156                         //cout << "strlen(buf) = " << strlen(buf) << endl;
157                         if(strlen(buf) > 2) {
158                                 //cout << "Calling ParseRwyExits for " << buf << endl;
159                                 ParseRwyExits(np, buf);
160                         }
161                 } else if(!strcmp(buf, "A")) {
162                         ap = new arc;
163                         ap->struct_type = ARC;
164                         fin >> buf;
165                         ap->n1 = atoi(buf);
166                         fin >> buf;
167                         ap->n2 = atoi(buf);
168                         fin >> buf;
169                         if(!strcmp(buf, "R")) {
170                                 ap->type = RUNWAY;
171                         } else if(!strcmp(buf, "T")) {
172                                 ap->type = TAXIWAY;
173                         } else {
174                                 SG_LOG(SG_GENERAL, SG_ALERT, "**** ERROR ***** Unknown arc type in taxi network...\n");
175                                 delete ap;
176                                 return(false);
177                         }
178                         // directed?
179                         fin >> buf;
180                         if(!strcmp(buf, "Y")) {
181                                 ap->directed = true;
182                         } else if(!strcmp(buf, "N")) {
183                                 ap->directed = false;
184                         } else {
185                                 SG_LOG(SG_GENERAL, SG_ALERT, "**** ERROR ***** Unknown arc directed value in taxi network - should be Y/N !!!\n");
186                                 delete ap;
187                                 return(false);
188                         }                       
189                         // Now the name
190                         ap->name = "";
191                         while(1) {
192                                 fin.unsetf(ios::skipws);
193                                 fin >> ch;
194                                 ap->name += ch;
195                                 if((ch == '"') || (ch == 0x0A)) {
196                                         break;
197                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
198                         }
199                         fin.setf(ios::skipws);
200                         ap->distance = (int)dclGetHorizontalSeparation(network[ap->n1]->pos, network[ap->n2]->pos);
201                         //cout << "Distance  = " << ap->distance << '\n';
202                         network[ap->n1]->arcs.push_back(ap);
203                         network[ap->n2]->arcs.push_back(ap);
204                 } else if(!strcmp(buf, "G")) {
205                         gp = new Gate;
206                         gp->struct_type = NODE;
207                         gp->type = GATE;
208                         fin >> buf;
209                         gp->nodeID = atoi(buf);
210                         fin >> buf;
211                         gp->pos.setlon(atof(buf));
212                         fin >> buf;
213                         gp->pos.setlat(atof(buf));
214                         fin >> buf;
215                         gp->pos.setelev(atof(buf));
216                         fin >> buf;             // gate type - ignore this for now
217                         fin >> buf;             // gate heading
218                         gp->heading = atoi(buf);
219                         // Now the name
220                         gp->name = "";
221                         while(1) {
222                                 fin.unsetf(ios::skipws);
223                                 fin >> ch;
224                                 gp->name += ch;
225                                 if((ch == '"') || (ch == 0x0A)) {
226                                         break;
227                                 }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
228                         }
229                         fin.setf(ios::skipws);
230                         gp->id = gateCount;             // Warning - this will likely change in the future.
231                         gp->used = false;
232                         network.push_back(gp);
233                         gates[gateCount] = gp;
234                         gateCount++;
235                 } else {
236                         // Something has gone seriously pear-shaped
237                         SG_LOG(SG_GENERAL, SG_ALERT, "********* ERROR - unknown ground network element type... aborting read of " << path.c_str() << '\n');
238                         return(false);
239                 }
240                 
241                 fin >> skipeol;         
242         }
243         return(true);
244 }
245
246 void FGGround::Init() {
247         display = false;
248         
249         // For now we'll hardwire the threshold end
250         Point3D P010(-118.037483, 34.081358, 296 * SG_FEET_TO_METER);
251         double hdg = 25.32;
252         ortho.Init(P010, hdg);
253         
254         networkLoadOK = LoadNetwork();
255 }
256
257 void FGGround::Update() {
258         // Each time step, what do we need to do?
259         // We need to go through the list of outstanding requests and acknowedgements
260         // and process at least one of them.
261         // We need to go through the list of planes under our control and check if
262         // any need to be addressed.
263         // We need to check for planes not under our control coming within our 
264         // control area and address if necessary.
265         
266         // Lets take the example of a plane which has just contacted ground
267         // following landing - presumably requesting where to go?
268         // First we need to establish the position of the plane within the logical network.
269         // Next we need to decide where its going. 
270 }
271
272 // Return a random gate ID of an unused gate.
273 // Two error values may be returned and must be checked for by the calling function:
274 // -2 signifies that no gates exist at this airport.
275 // -1 signifies that all gates are currently full.
276 int FGGround::GetRandomGateID() {
277         // Check that this airport actually has some gates!!
278         if(!gates.size()) {
279                 return(-2);
280         }
281
282         gate_vec_type gateVec;
283         int num = 0;
284         int thenum;
285         int ID;
286         
287         gatesItr = gates.begin();
288         while(gatesItr != gates.end()) {
289                 if((gatesItr->second)->used == false) {
290                         gateVec.push_back(gatesItr->second);
291                         num++;
292                 }
293                 ++gatesItr;
294         }
295
296         // Check that there are some unused gates!
297         if(!gateVec.size()) {
298                 return(-1);
299         }
300         
301         // Randomly select one from the list
302         sg_srandom_time();
303         thenum = (int)(sg_random() * gateVec.size());
304         ID = gateVec[thenum]->id;
305         
306         return(ID);
307 }
308
309 // Return a pointer to an unused gate node
310 Gate* FGGround::GetGateNode() {
311         int id = GetRandomGateID();
312         if(id < 0) {
313                 return(NULL);
314         } else {
315                 return(gates[id]);
316         }
317 }
318
319
320 // WARNING - This is hardwired to my prototype logical network format
321 // and will almost certainly change when Bernie's stuff comes on-line.
322 node* FGGround::GetThresholdNode(string rwyID) {
323         // For now go through all the nodes and parse their names
324         // Maybe in the future we'll map threshold nodes by ID
325         //cout << "Size of network is " << network.size() << '\n';
326         for(unsigned int i=0; i<network.size(); ++i) {
327                 //cout << "Name = " << network[i]->name << '\n';
328                 if(network[i]->name.size()) {
329                         string s = network[i]->name;
330                         // Warning - the next bit is fragile and dependent on my current naming scheme
331                         //cout << "substr = " << s.substr(0,3) << '\n';
332                         //cout << "size of s = " << s.size() << '\n'; 
333                         if(s.substr(0,3) == "rwy") {
334                                 //cout << "subsubstr = " << s.substr(4, s.size() - 4) << '\n';
335                                 if(s.substr(4, s.size() - 4) == rwyID) {
336                                         return network[i];
337                                 }
338                         }
339                 }
340         }
341         return NULL;
342 }
343
344 // Get a path from a point on a runway to a gate
345 // TODO !!
346
347 // Get a path from a node to another node
348 // Eventually we will need complex algorithms for this taking other traffic,
349 // shortest path and suitable paths into accout.
350 // For now we'll just call the shortest path algorithm.
351 ground_network_path_type FGGround::GetPath(node* A, node* B) {  
352         return(GetShortestPath(A, B));
353 };
354
355 // Get a path from a node to a runway threshold
356 ground_network_path_type FGGround::GetPath(node* A, string rwyID) {
357         node* b = GetThresholdNode(rwyID);
358         if(b == NULL) {
359                 SG_LOG(SG_GENERAL, SG_ALERT, "ERROR - unable to find path to runway theshold in ground.cxx\n");
360                 ground_network_path_type emptyPath;
361                 emptyPath.erase(emptyPath.begin(), emptyPath.end());
362                 return(emptyPath);
363         }
364         return GetShortestPath(A, b);
365 }
366
367 // A shortest path algorithm from memory (ie. I can't find the bl&*dy book again!)
368 // I'm sure there must be enchancements that we can make to this, such as biasing the
369 // order in which the nodes are searched out from in favour of those geographically
370 // closer to the destination.
371 // Note that we are working with the master set of nodes and arcs so we mustn't change
372 // or delete them -  we only delete the paths that we create during the algorithm.
373 ground_network_path_type FGGround::GetShortestPath(node* A, node* B) {
374         a_path* pathPtr;
375         shortest_path_map_type pathMap;
376         node_array_type nodesLeft;
377         
378         // Debugging check
379         int pathsCreated = 0;
380         
381         // Initialise the algorithm
382         nodesLeft.push_back(A);
383         pathPtr = new a_path;
384         pathsCreated++;
385         pathPtr->path.push_back(A);
386         pathPtr->cost = 0;
387         pathMap[A->nodeID] = pathPtr;
388         bool solution_found = false;    // Flag to indicate that at least one candidate path has been found
389         int solution_cost = -1;                 // Cost of current best cost solution.  -1 indicates no solution found yet.
390         a_path solution_path;           
391                                                                                         
392         node* nPtr;     // nPtr is used to point to the node we are currently working with
393         
394         while(nodesLeft.size()) {
395                 //cout << "\n*****nodesLeft*****\n";
396                 //for(unsigned int i=0; i<nodesLeft.size(); ++i) {
397                         //cout << nodesLeft[i]->nodeID << '\n';
398                 //}
399                 //cout << "*******************\n\n";
400                 nPtr = *nodesLeft.begin();              // Thought - definate optimization possibilities here in the choice of which nodes we process first.
401                 nodesLeft.erase(nodesLeft.begin());
402                 //cout << "Walking out from node " << nPtr->nodeID << '\n';
403                 for(unsigned int i=0; i<nPtr->arcs.size(); ++i) {
404                         //cout << "ARC TO " << ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1) << '\n';
405                 }
406                 if((solution_found) && (solution_cost <= pathMap[nPtr->nodeID]->cost)) {
407                         // Do nothing - we've already found a solution and this partial path is already more expensive
408                 } else {
409                         // This path could still be better than the current solution - check it out
410                         for(unsigned int i=0; i<(nPtr->arcs.size()); i++) {
411                                 // Map the new path against the end node, ie. *not* the one we just started with.
412                                 unsigned int end_nodeID = ((nPtr->arcs[i]->n1 == nPtr->nodeID) ? nPtr->arcs[i]->n2 : nPtr->arcs[i]->n1);
413                                 //cout << "end_nodeID = " << end_nodeID << '\n';
414                                 //cout << "pathMap size is " << pathMap.size() << '\n';
415                                 if(end_nodeID == nPtr->nodeID) {
416                                         //cout << "Circular arc!\n";
417                                         // Then its a circular arc - don't bother!!
418                                         //nPtr->arcs.erase(nPtr->arcs.begin() + i);
419                                 } else {
420                                         // see if the end node is already in the map or not
421                                         if(pathMap.find(end_nodeID) == pathMap.end()) {
422                                                 //cout << "Not in the map" << endl;;
423                                                 // Not in the map - easy!
424                                                 pathPtr = new a_path;
425                                                 pathsCreated++;
426                                                 *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
427                                                 pathPtr->path.push_back(nPtr->arcs[i]);
428                                                 pathPtr->path.push_back(network[end_nodeID]);
429                                                 pathPtr->cost += nPtr->arcs[i]->distance;
430                                                 pathMap[end_nodeID] = pathPtr;
431                                                 nodesLeft.push_back(network[end_nodeID]);       // By definition this can't be in the list already, or
432                                                 // it would also have been in the map and hence OR'd with this one.
433                                                 if(end_nodeID == B->nodeID) {
434                                                         //cout << "Solution found!!!" << endl;
435                                                         // Since this node wasn't in the map this is by definition the first solution
436                                                         solution_cost = pathPtr->cost;
437                                                         solution_path = *pathPtr;
438                                                         solution_found = true;
439                                                 }
440                                         } else {
441                                                 //cout << "Already in the map" << endl;
442                                                 // In the map - not so easy - need to get rid of an arc from the higher cost one.
443                                                 //cout << "Current cost of node " << end_nodeID << " is " << pathMap[end_nodeID]->cost << endl;
444                                                 int newCost = pathMap[nPtr->nodeID]->cost + nPtr->arcs[i]->distance;
445                                                 //cout << "New cost is of node " << nPtr->nodeID << " is " << newCost << endl;
446                                                 if(newCost >= pathMap[end_nodeID]->cost) {
447                                                         // No need to do anything.
448                                                         //cout << "Not doing anything!" << endl;
449                                                 } else {
450                                                         delete pathMap[end_nodeID];
451                                                         pathsCreated--;
452                                                         
453                                                         pathPtr = new a_path;
454                                                         pathsCreated++;
455                                                         *pathPtr = *pathMap[nPtr->nodeID];      // *copy* the path
456                                                         pathPtr->path.push_back(nPtr->arcs[i]);
457                                                         pathPtr->path.push_back(network[end_nodeID]);
458                                                         pathPtr->cost += nPtr->arcs[i]->distance;
459                                                         pathMap[end_nodeID] = pathPtr;
460                                                         
461                                                         // We need to add this node to the list-to-do again to force a recalculation 
462                                                         // onwards from this node with the new lower cost to node cost.
463                                                         nodesLeft.push_back(network[end_nodeID]);
464                                                         
465                                                         if(end_nodeID == B->nodeID) {
466                                                                 //cout << "Solution found!!!" << endl;
467                                                                 // Need to check if there is a previous better solution
468                                                                 if((solution_cost < 0) || (pathPtr->cost < solution_cost)) {
469                                                                         solution_cost = pathPtr->cost;
470                                                                         solution_path = *pathPtr;
471                                                                         solution_found = true;
472                                                                 }
473                                                         }
474                                                 }
475                                         }
476                                 }
477                         }
478                 }
479         }
480         
481         // delete all the paths before returning
482         shortest_path_map_iterator spItr = pathMap.begin();
483         while(spItr != pathMap.end()) {
484                 if(spItr->second != NULL) {
485                         delete spItr->second;
486                         --pathsCreated;
487                 }
488                 ++spItr;
489         }
490         
491         //cout << "pathsCreated = " << pathsCreated << '\n';
492         if(pathsCreated > 0) {
493                 SG_LOG(SG_GENERAL, SG_ALERT, "WARNING - Possible memory leak in FGGround::GetShortestPath\n\
494                                                                           Please report to flightgear-devel@flightgear.org\n");
495         }
496         
497         //cout << (solution_found ? "Result: solution found\n" : "Result: no solution found\n");
498         return(solution_path.path);             // TODO - we really ought to have a fallback position incase a solution isn't found.
499 }
500                 
501
502
503 // Randomly or otherwise populate some of the gates with parked planes
504 // (might eventually be done by the AIMgr if and when lots of AI traffic is generated)
505
506 // Return a list of exits from a given runway
507 // It is up to the calling function to check for non-zero size of returned array before use
508 node_array_type FGGround::GetExits(int rwyID) {
509         return(runways[rwyID].exits);
510 }
511
512 #if 0
513 void FGGround::NewArrival(plane_rec plane) {
514         // What are we going to do here?
515         // We need to start a new ground_rec and add the plane_rec to it
516         // We need to decide what gate we are going to clear it to.
517         // Then we need to add clearing it to that gate to the pending transmissions queue? - or simply transmit?
518         // Probably simply transmit for now and think about a transmission queue later if we need one.
519         // We might need one though in order to add a little delay for response time.
520         ground_rec* g = new ground_rec;
521         g->plane_rec = plane;
522         g->current_pos = ConvertWGS84ToXY(plane.pos);
523         g->node = GetNode(g->current_pos);  // TODO - might need to sort out node/arc here
524         AssignGate(g);
525         g->cleared = false;
526         ground_traffic.push_back(g);
527         NextClearance(g);
528 }
529
530 void FGGround::NewContact(plane_rec plane) {
531         // This is a bit of a convienience function at the moment and is likely to change.
532         if(at a gate or apron)
533                 NewDeparture(plane);
534         else
535                 NewArrival(plane);
536 }
537
538 void FGGround::NextClearance(ground_rec &g) {
539         // Need to work out where we can clear g to.
540         // Assume the pilot doesn't need progressive instructions
541         // We *should* already have a gate or holding point assigned by the time we get here
542         // but it wouldn't do any harm to check.
543         
544         // For now though we will hardwire it to clear to the final destination.
545 }
546
547 void FGGround::AssignGate(ground_rec &g) {
548         // We'll cheat for now - since we only have the user's aircraft and a couple of airports implemented
549         // we'll hardwire the gate!
550         // In the long run the logic of which gate or area to send the plane to could be somewhat non-trivial.
551 }
552 #endif //0
553