]> git.mxchange.org Git - flightgear.git/blob - src/ATC/AIMgr.cxx
If it's a struct, it's not a class
[flightgear.git] / src / ATC / AIMgr.cxx
1 // AIMgr.cxx - implementation of FGAIMgr 
2 // - a global management class for FlightGear generated AI traffic
3 //
4 // Written by David Luff, started March 2002.
5 //
6 // Copyright (C) 2002  David C Luff - david.luff@nottingham.ac.uk
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <simgear/misc/sg_path.hxx>
29 #include <simgear/math/sg_random.h>
30 #include <list>
31
32 #ifdef _MSC_VER
33 #  include <io.h>
34 #else
35 #  include <sys/types.h>        // for directory reading
36 #  include <dirent.h>           // for directory reading
37 #endif
38
39 #include <Environment/environment_mgr.hxx>
40 #include <Environment/environment.hxx>
41
42 #include "AIMgr.hxx"
43 #include "AILocalTraffic.hxx"
44 #include "AIGAVFRTraffic.hxx"
45 #include "ATCutils.hxx"
46 #include "commlist.hxx"
47
48 SG_USING_STD(list);
49 SG_USING_STD(cout);
50
51 FGAIMgr::FGAIMgr() {
52         ATC = globals->get_ATC_mgr();
53         initDone = false;
54         ai_callsigns_used["GFS"] = 1;   // so we don't inadvertently use this
55         // TODO - use the proper user callsign when it becomes user settable.
56         removalList.clear();
57         activated.clear();
58         _havePiperModel = true;
59 }
60
61 FGAIMgr::~FGAIMgr() {
62 }
63
64 void FGAIMgr::init() {
65         //cout << "AIMgr::init called..." << endl;
66         
67         // Pointers to user's position
68         lon_node = fgGetNode("/position/longitude-deg", true);
69         lat_node = fgGetNode("/position/latitude-deg", true);
70         elev_node = fgGetNode("/position/altitude-ft", true);
71
72         lon = lon_node->getDoubleValue();
73         lat = lat_node->getDoubleValue();
74         elev = elev_node->getDoubleValue();
75         
76         // Load up models at the start to avoid pausing later
77         // Hack alert - Hardwired paths!!
78         string planepath = "Aircraft/c172p/Models/c172p.xml";
79         bool _loadedDefaultOK = true;
80         try {
81                 _defaultModel = sgLoad3DModel( globals->get_fg_root(),
82                                            planepath.c_str(),
83                                                                            globals->get_props(),
84                                                                            globals->get_sim_time_sec() );
85         } catch(sg_exception&) {
86                 _loadedDefaultOK = false;
87         }
88         
89         if(!_loadedDefaultOK ) {
90                 // Just load the same 3D model as the default user plane - that's *bound* to exist!
91                 // TODO - implement robust determination of availability of GA AI aircraft models
92                 planepath = "Aircraft/c172p/Models/c172p.ac";
93                 _defaultModel = sgLoad3DModel( globals->get_fg_root(),
94                                            planepath.c_str(),
95                                                                            globals->get_props(),
96                                                                            globals->get_sim_time_sec() );
97         }
98
99         planepath = "Aircraft/pa28-161/Models/pa28-161.ac";
100         try {
101                 _piperModel = sgLoad3DModel( globals->get_fg_root(),
102                                          planepath.c_str(),
103                                                                          globals->get_props(),
104                                                                          globals->get_sim_time_sec() );
105         } catch(sg_exception&) {
106                 _havePiperModel = false;
107         }
108
109         // go through the $FG_ROOT/ATC directory and find all *.taxi files
110         SGPath path(globals->get_fg_root());
111         path.append("ATC/");
112         string dir = path.dir();
113         string ext;
114         string file, f_ident;
115         int pos;
116         
117         ulDir *d;
118         struct ulDirEnt *de;
119         
120         if ( (d = ulOpenDir( dir.c_str() )) == NULL ) {
121                 SG_LOG(SG_ATC, SG_WARN, "cannot open directory " << dir);
122         } else {
123                 // load all .taxi files
124                 while ( (de = ulReadDir(d)) != NULL ) {
125                         file = de->d_name;
126                         pos = file.find(".");
127                         ext = file.substr(pos + 1);
128                         if(ext == "taxi") {
129                                 f_ident = file.substr(0, pos);
130                                 const FGAirport *a = fgFindAirportID( f_ident);
131                                 if(a){
132                                         SGBucket sgb(a->getLongitude(), a->getLatitude());
133                                         int idx = sgb.gen_index();
134                                         if(facilities.find(idx) != facilities.end()) {
135                                                 facilities[idx]->push_back(f_ident);
136                                         } else {
137                                                 ID_list_type* apts = new ID_list_type;
138                                                 apts->push_back(f_ident);
139                                                 facilities[idx] = apts;
140                                         }
141                                         SG_LOG(SG_ATC, SG_BULK, "Mapping " << f_ident << " to bucket " << idx);
142                                 }
143                         }
144                 }               
145                 ulCloseDir(d);
146         }
147
148         // See if are in range at startup and activate if necessary
149         SearchByPos(15.0);
150         
151         initDone = true;
152         
153         //cout << "AIMgr::init done..." << endl;
154         
155         /*
156         // TESTING
157         FGATCAlignedProjection ortho;
158         ortho.Init(fgGetAirportPos("KEMT"), 205.0);     // Guess of rwy19 heading
159         //Point3D ip = ortho.ConvertFromLocal(Point3D(6000, 1000, 1000));       // 90 deg entry
160         //Point3D ip = ortho.ConvertFromLocal(Point3D(-7000, 3000, 1000));      // 45 deg entry
161         Point3D ip = ortho.ConvertFromLocal(Point3D(1000, -7000, 1000));        // straight-in
162         ATC->AIRegisterAirport("KEMT");
163         FGAIGAVFRTraffic* p = new FGAIGAVFRTraffic();
164         p->SetModel(_defaultModel);
165         p->Init(ip, "KEMT", GenerateShortForm(GenerateUniqueCallsign()));
166         ai_list.push_back(p);
167         traffic[ident].push_back(p);
168         activated["KEMT"] = 1;
169         */      
170 }
171
172 void FGAIMgr::bind() {
173 }
174
175 void FGAIMgr::unbind() {
176 }
177
178 void FGAIMgr::update(double dt) {
179         if(!initDone) {
180                 init();
181                 SG_LOG(SG_ATC, SG_WARN, "Warning - AIMgr::update(...) called before AIMgr::init()");
182         }
183         
184         //cout << activated.size() << '\n';
185         
186         Point3D userPos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
187         
188         // TODO - make these class variables!!
189         static int i = 0;
190         static int j = 0;
191
192         // Don't update any planes for first 50 runs through - this avoids some possible initialisation anomalies
193         // Might not need it now we have fade-in though?
194         if(i < 50) {
195                 ++i;
196                 return;
197         }
198         
199         if(j == 215) {
200                 SearchByPos(25.0);
201                 j = 0;
202         } else if(j == 200) {
203                 // Go through the list of activated airports and remove those out of range
204                 //cout << "The following airports have been activated by the AI system:\n";
205                 ai_activated_map_iterator apt_itr = activated.begin();
206                 while(apt_itr != activated.end()) {
207                         //cout << "FIRST IS " << (*apt_itr).first << '\n';
208                         if(dclGetHorizontalSeparation(userPos, fgGetAirportPos((*apt_itr).first)) > (35.0 * 1600.0)) {
209                                 // Then get rid of it and make sure the iterator is left pointing to the next one!
210                                 string s = (*apt_itr).first;
211                                 if(traffic.find(s) != traffic.end()) {
212                                         //cout << "s = " << s << ", traffic[s].size() = " << traffic[s].size() << '\n';
213                                         if(!traffic[s].empty()) {
214                                                 apt_itr++;
215                                         } else {
216                                                 //cout << "Erasing " << (*apt_itr).first << " and traffic" << '\n';
217                                                 activated.erase(apt_itr);
218                                                 apt_itr = activated.upper_bound(s);
219                                                 traffic.erase(s);
220                                         }
221                                 } else {
222                                                 //cout << "Erasing " << (*apt_itr).first << ' ' << (*apt_itr).second << '\n';
223                                                 activated.erase(apt_itr);
224                                                 apt_itr = activated.upper_bound(s);
225                                 }
226                         } else {
227                                 apt_itr++;
228                         }
229                 }
230         } else if(j == 180) {
231                 // Go through the list of activated airports and do the random airplane generation
232                 ai_traffic_map_iterator it = traffic.begin();
233                 while(it != traffic.end()) {
234                         string s = (*it).first;
235                         //cout << "s = " << s << " size = " << (*it).second.size() << '\n';
236                         // Only generate extra traffic if within a certain distance of the user,
237                         // TODO - maybe take users's tuned freq into account as well.
238                         double d = dclGetHorizontalSeparation(userPos, fgGetAirportPos(s)); 
239                         if(d < (15.0 * 1600.0)) {
240                                 double cd = 0.0;
241                                 bool gen = false;
242                                 //cout << "Size of list is " << (*it).second.size() << " at " << s << '\n';
243                                 if((*it).second.size()) {
244                                         FGAIEntity* e = *((*it).second.rbegin());       // Get the last airplane currently scheduled to arrive at this airport.
245                                         cd = dclGetHorizontalSeparation(e->GetPos(), fgGetAirportPos(s));
246                                         if(cd < (d < 5000 ? 10000 : d + 5000)) {
247                                                 gen = true;
248                                         }
249                                 } else {
250                                         gen = true;
251                                         cd = 0.0;
252                                 }
253                                 if(gen) {
254                                         //cout << "Generating extra traffic at airport " << s << ", at least " << cd << " meters out\n";
255                                         //GenerateSimpleAirportTraffic(s, cd);
256                                         GenerateSimpleAirportTraffic(s, cd + 3000.0);   // The random seems a bit wierd - traffic could get far too bunched without the +3000.
257                                         // TODO - make the anti-random constant variable depending on the ai-traffic level.
258                                 }
259                         }
260                         ++it;
261                 }
262         }
263         
264         ++j;
265         
266         //cout << "Size of AI list is " << ai_list.size() << '\n';
267         
268         // TODO - need to add a check of if any activated airports have gone out of range
269         
270         string rs;      // plane to be removed, if one.
271         if(removalList.size()) {
272                 rs = *(removalList.begin());
273                 removalList.pop_front();
274         } else {
275                 rs = "";
276         }
277         
278         // Traverse the list of active planes and run all their update methods
279         // TODO - spread the load - not all planes should need updating every frame.
280         // Note that this will require dt to be calculated for each plane though
281         // since they rely on it to calculate distance travelled.
282         ai_list_itr = ai_list.begin();
283         while(ai_list_itr != ai_list.end()) {
284                 FGAIEntity *e = *ai_list_itr;
285                 if(rs.size() && e->GetCallsign() == rs) {
286                         //cout << "Removing " << rs << " from ai_list\n";
287                         ai_list_itr = ai_list.erase(ai_list_itr);
288                         delete e;
289                         // This is a hack - we should deref this plane from the airport count!
290                 } else {
291                         e->Update(dt);
292                         ++ai_list_itr;
293                 }
294         }
295
296         //cout << "Size of AI list is " << ai_list.size() << '\n';
297 }
298
299 void FGAIMgr::ScheduleRemoval(const string& s) {
300         //cout << "Scheduling removal of plane " << s << " from AIMgr\n";
301         removalList.push_back(s);
302 }
303
304 // Activate AI traffic at an airport
305 void FGAIMgr::ActivateAirport(const string& ident) {
306         ATC->AIRegisterAirport(ident);
307         // TODO - need to start the traffic more randomly
308         FGAILocalTraffic* local_traffic = new FGAILocalTraffic;
309         local_traffic->SetModel(_defaultModel); // currently hardwired to cessna.
310         //local_traffic->Init(ident, IN_PATTERN, TAKEOFF_ROLL);
311         local_traffic->Init(GenerateShortForm(GenerateUniqueCallsign()), ident);
312         local_traffic->FlyCircuits(1, true);    // Fly 2 circuits with touch & go in between
313         ai_list.push_back(local_traffic);
314         traffic[ident].push_back(local_traffic);
315         //cout << "******** ACTIVATING AIRPORT, ident = " << ident << '\n';
316         activated[ident] = 1;
317 }
318
319 // Hack - Generate AI traffic at an airport with no facilities file
320 void FGAIMgr::GenerateSimpleAirportTraffic(const string& ident, double min_dist) {
321         // Ugly hack - don't let VFR Cessnas operate at a hardwired list of major airports
322         // This will go eventually once airport .xml files specify the traffic profile
323         if(ident == "KSFO" || ident == "KDFW" || ident == "EGLL" || ident == "KORD" || ident == "KJFK" 
324                            || ident == "KMSP" || ident == "KLAX" || ident == "KBOS" || ident == "KEDW"
325                                            || ident == "KSEA" || ident == "EHAM") {
326                 return;
327         }
328         
329         /*
330         // TODO - check for military airports - this should be in the current data.
331         // UGGH - there's no point at the moment - everything is labelled civil in basic.dat!
332         FGAirport a = fgFindAirportID(ident, &a);
333         if(a) {
334                 cout << "CODE IS " << a.code << '\n';
335         } else {
336                 // UG - can't find the airport!
337                 return;
338         }
339         */
340         
341         Point3D aptpos = fgGetAirportPos(ident);        // TODO - check for elev of -9999
342         //cout << "ident = " << ident << ", elev = " << aptpos.elev() << '\n';
343         
344         // Operate from airports at 3000ft and below only to avoid the default cloud layers and since we don't degrade AI performance with altitude.
345         if(aptpos.elev() > 3000) {
346                 //cout << "High alt airports not yet supported - returning\n";
347                 return;
348         }
349         
350         // Rough hack for plane type - make 70% of the planes cessnas, the rest pipers.
351         bool cessna = true;
352         
353         // Get the time and only operate VFR in the (approximate) daytime.
354         struct tm *t = globals->get_time_params()->getGmt();
355         int loc_time = t->tm_hour + int(aptpos.lon() / (360.0 / 24.0));
356         while (loc_time < 0)
357                 loc_time += 24;
358         while (loc_time >= 24)
359                 loc_time -= 24;
360
361         //cout << "loc_time = " << loc_time << '\n';
362         if(loc_time < 7 || loc_time > 19) return;
363         
364         // Check that the visibility is OK for IFR operation.
365         double visibility;
366         FGEnvironment stationweather =
367             ((FGEnvironmentMgr *)globals->get_subsystem("environment"))
368               ->getEnvironment(aptpos.lat(), aptpos.lon(), aptpos.elev());      // TODO - check whether this should take ft or m for elev.
369         visibility = stationweather.get_visibility_m();
370         // Technically we can do VFR down to 1 mile (1600m) but that's pretty murky!
371         //cout << "vis = " << visibility << '\n';
372         if(visibility < 3000) return;
373         
374         ATC->AIRegisterAirport(ident);
375         
376         // Next - get the distance from user to the airport.
377         Point3D userpos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
378         double d = dclGetHorizontalSeparation(userpos, aptpos); // in meters
379         
380         int lev = fgGetInt("/sim/ai-traffic/level");
381         if(lev < 1)
382                 return;
383         if (lev > 3)
384                 lev = 3;
385         if(visibility < 6000) lev = 1;
386         //cout << "level = " << lev << '\n';
387         
388         // Next - generate any local / circuit traffic
389
390         /*
391         // --------------------------- THIS BLOCK IS JUST FOR TESTING - COMMENT OUT BEFORE RELEASE ---------------
392         // Finally - generate VFR approaching traffic
393         //if(d > 2000) {
394         if(ident == "KPOC") {
395                 double ad = 2000.0;
396                 double avd = 3000.0;    // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
397                 //while(ad < (d < 10000 ? 12000 : d + 2000)) {
398                 for(int i=0; i<8; ++i) {
399                         double dd = sg_random() * avd;
400                         // put a minimum spacing in for now since I don't think tower will cope otherwise!
401                         if(dd < 1500) dd = 1500; 
402                         //ad += dd;
403                         ad += dd;
404                         double dir = int(sg_random() * 36);
405                         if(dir == 36) dir--;
406                         dir *= 10;
407                         //dir = 180;
408                         if(sg_random() < 0.3) cessna = false;
409                         else cessna = true;
410                         string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
411                         FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
412                         t->SetModel(cessna ? _defaultModel : _piperModel);
413                         //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
414                         Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
415                         if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0);
416                         t->Init(tpos, ident, s);
417                         ai_list.push_back(t);
418                 }
419         }
420         activated[ident] = 1;
421         return;
422         //---------------------------------------------------------------------------------------------------
423         */
424         
425         double ad;   // Minimum distance out of first arriving plane in meters.
426         double mind; // Minimum spacing of traffic in meters
427         double avd;  // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
428         // Finally - generate VFR approaching traffic
429         //if(d > 2000) {
430         if(1) {
431                 if(lev == 3) {
432                         ad = 5000.0;
433                         mind = 2000.0;
434                         avd = 6000.0;
435                 } else if(lev == 2) {
436                         ad = 8000.0;
437                         mind = 4000.0;
438                         avd = 10000.0;
439                 } else {
440                         ad = 9000.0;    // Start the first aircraft at least 9K out for now.
441                         mind = 6000.0;
442                         avd = 15000.0;
443                 }
444                 /*
445                 // Check if there is already arriving traffic at this airport
446                 cout << "BING A " << ident << '\n';
447                 if(traffic.find(ident) != traffic.end()) {
448                         cout << "BING B " << ident << '\n';
449                         ai_list_type lst = traffic[ident];
450                         cout << "BING C " << ident << '\n';
451                         if(lst.size()) {
452                                 cout << "BING D " << ident << '\n';
453                                 double cd = dclGetHorizontalSeparation(aptpos, (*lst.rbegin())->GetPos());
454                                 cout << "ident = " << ident << ", cd = " << cd << '\n';
455                                 if(cd > ad) ad = cd;
456                         }
457                 }
458                 */
459                 if(min_dist != 0) ad = min_dist;
460                 //cout << "ident = " << ident << ", ad = " << ad << '\n';
461                 while(ad < (d < 5000 ? 15000 : d + 10000)) {
462                         double dd = mind + (sg_random() * (avd - mind));
463                         ad += dd;
464                         double dir = int(sg_random() * 36);
465                         if(dir == 36) dir--;
466                         dir *= 10;
467                         
468                         if(sg_random() < 0.3) cessna = false;
469                         else cessna = true;
470                         string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
471                         FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
472                         t->SetModel(cessna ? _defaultModel : (_havePiperModel ? _piperModel : _defaultModel));
473                         //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
474                         Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
475                         if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0);        // FEET yuk :-(
476                         t->Init(tpos, ident, s);
477                         ai_list.push_back(t);
478                         traffic[ident].push_back(t);
479                 }
480         }       
481 }
482
483 /*
484 // Generate a VFR arrival at airport apt, at least distance d (meters) out.
485 void FGAIMgr::GenerateVFRArrival(const string& apt, double d) {
486 }
487 */
488
489 // Search for valid airports in the vicinity of the user and activate them if necessary
490 void FGAIMgr::SearchByPos(double range) {
491         //cout << "In SearchByPos(...)" << endl;
492         
493         // get bucket number for plane position
494         lon = lon_node->getDoubleValue();
495         lat = lat_node->getDoubleValue();
496         elev = elev_node->getDoubleValue() * SG_FEET_TO_METER;
497         SGBucket buck(lon, lat);
498
499         // get neigboring buckets
500         int bx = (int)( range*SG_NM_TO_METER / buck.get_width_m() / 2);
501         //cout << "bx = " << bx << endl;
502         int by = (int)( range*SG_NM_TO_METER / buck.get_height_m() / 2 );
503         //cout << "by = " << by << endl;
504         
505         // Search for airports with facitities files --------------------------
506         // loop over bucket range 
507         for ( int i=-bx; i<=bx; i++) {
508                 //cout << "i loop\n";
509                 for ( int j=-by; j<=by; j++) {
510                         //cout << "j loop\n";
511                         buck = sgBucketOffset(lon, lat, i, j);
512                         long int bucket = buck.gen_index();
513                         //cout << "bucket is " << bucket << endl;
514                         if(facilities.find(bucket) != facilities.end()) {
515                                 ID_list_type* apts = facilities[bucket];
516                                 ID_list_iterator current = apts->begin();
517                                 ID_list_iterator last = apts->end();
518                                 
519                                 //cout << "Size of apts is " << apts->size() << endl;
520                                 
521                                 //double rlon = lon * SGD_DEGREES_TO_RADIANS;
522                                 //double rlat = lat * SGD_DEGREES_TO_RADIANS;
523                                 //Point3D aircraft = sgGeodToCart( Point3D(rlon, rlat, elev) );
524                                 //Point3D airport;
525                                 for(; current != last; ++current) {
526                                         //cout << "Found " << *current << endl;;
527                                         if(activated.find(*current) == activated.end()) {
528                                                 //cout << "Activating " << *current << endl;
529                                                 //FGAirport a;
530                                                 //if(dclFindAirportID(*current, &a)) {
531                                                         //      // We can do something here based on distance from the user if we wish.
532                                                 //}
533                                                 //string s = *current;
534                                                 //cout << "s = " << s << '\n';
535                                                 ActivateAirport(*current);
536                                                 //ActivateSimpleAirport(*current);      // TODO - put this back to ActivateAirport when that code is done.
537                                                 //cout << "Activation done" << endl;
538                                         } else {
539                                                 //cout << *current << " already activated" << endl;
540                                         }
541                                 }
542                         }
543                 }
544         }
545         //-------------------------------------------------------------
546         
547         // Search for any towered airports in the vicinity ------------
548         comm_list_type towered;
549         comm_list_iterator twd_itr;
550         
551         int num_twd = current_commlist->FindByPos(lon, lat, elev, range, &towered, TOWER);
552         if (num_twd != 0) {
553                 double closest = 1000000;
554                 string s = "";
555                 for(twd_itr = towered.begin(); twd_itr != towered.end(); twd_itr++) {
556                         // Only activate the closest airport not already activated each time.
557                         if(activated.find(twd_itr->ident) == activated.end()) {
558                                 double sep = dclGetHorizontalSeparation(Point3D(lon, lat, elev), fgGetAirportPos(twd_itr->ident));
559                                 if(sep < closest) {
560                                         closest = sep;
561                                         s = twd_itr->ident;
562                                 }
563                                 
564                         }
565                 }
566                 if(s.size()) {
567                         // TODO - find out why empty strings come through here when all in-range airports done.
568                         GenerateSimpleAirportTraffic(s);
569                         //cout << "**************ACTIVATING SIMPLE AIRPORT, ident = " << s << '\n';
570                         activated[s] = 1;
571                 }
572         }
573 }
574
575 string FGAIMgr::GenerateCallsign() {
576         // For now we'll just generate US callsigns until we can regionally identify airports.
577         string s = "N";
578         // Add 3 to 5 numbers and make up to 5 with letters.
579         //sg_srandom_time();
580         double d = sg_random();
581         int n = int(d * 3);
582         if(n == 3) --n;
583         //cout << "First n, n = " << n << '\n';
584         int j = 3 + n;
585         //cout << "j = " << j << '\n';
586         for(int i=0; i<j; ++i) { 
587                 int n = int(sg_random() * 10);
588                 if(n == 10) --n;
589                 s += (char)('0' + n);
590         }
591         for(int i=j; i<5; ++i) {
592                 int n = int(sg_random() * 26);
593                 if(n == 26) --n;
594                 //cout << "Alpha, n = " << n << '\n';
595                 s += (char)('A' + n);
596         }
597         //cout << "s = " << s << '\n';
598         return(s);
599 }
600
601 string FGAIMgr::GenerateUniqueCallsign() {
602         while(1) {
603                 string s = GenerateCallsign();
604                 if(!ai_callsigns_used[s]) {
605                         ai_callsigns_used[s] = 1;
606                         return(s);
607                 }
608         }
609 }
610
611 // This will be moved somewhere else eventually!!!!
612 string FGAIMgr::GenerateShortForm(const string& callsign, const string& plane_str, bool local) {
613         //cout << callsign << '\n';
614         string s;
615         if(local) s = "Trainer-";
616         else s = plane_str;
617         for(int i=3; i>0; --i) {
618                 char c = callsign[callsign.size() - i];
619                 //cout << c << '\n';
620                 string tmp = "";
621                 tmp += c;
622                 if(isalpha(c)) s += GetPhoneticIdent(c);
623                 else s += ConvertNumToSpokenDigits(tmp);
624                 if(i > 1) s += '-';
625         }
626         return(s);
627 }