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