]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Use a helper thread to rebuild the navcache.
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>             // strcmp()
31
32 #ifdef _WIN32
33 #  include <io.h>               // isatty()
34 #  define isatty _isatty
35 #endif
36
37 #include <simgear/compiler.h>
38
39 #include <string>
40 #include <boost/algorithm/string/compare.hpp>
41 #include <boost/algorithm/string/predicate.hpp>
42
43 #include <simgear/constants.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/structure/exception.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/structure/SGPerfMon.hxx>
48 #include <simgear/misc/sg_path.hxx>
49 #include <simgear/misc/sg_dir.hxx>
50 #include <simgear/misc/sgstream.hxx>
51 #include <simgear/misc/strutils.hxx>
52 #include <simgear/props/props_io.hxx>
53
54 #include <simgear/misc/interpolator.hxx>
55 #include <simgear/scene/material/matlib.hxx>
56 #include <simgear/scene/model/particles.hxx>
57
58 #include <Aircraft/controls.hxx>
59 #include <Aircraft/replay.hxx>
60 #include <Airports/runways.hxx>
61 #include <Airports/simple.hxx>
62 #include <Airports/dynamics.hxx>
63
64 #include <AIModel/AIManager.hxx>
65
66 #include <ATCDCL/ATISmgr.hxx>
67 #include <ATC/atc_mgr.hxx>
68
69 #include <Autopilot/route_mgr.hxx>
70 #include <Autopilot/autopilotgroup.hxx>
71
72 #include <Cockpit/panel.hxx>
73 #include <Cockpit/panel_io.hxx>
74
75 #include <Canvas/canvas_mgr.hxx>
76 #include <Canvas/gui_mgr.hxx>
77 #include <GUI/new_gui.hxx>
78 #include <Input/input.hxx>
79 #include <Instrumentation/instrument_mgr.hxx>
80 #include <Model/acmodel.hxx>
81 #include <Model/modelmgr.hxx>
82 #include <AIModel/submodel.hxx>
83 #include <AIModel/AIManager.hxx>
84 #include <Navaids/navdb.hxx>
85 #include <Navaids/navlist.hxx>
86 #include <Scenery/scenery.hxx>
87 #include <Scenery/tilemgr.hxx>
88 #include <Scripting/NasalSys.hxx>
89 #include <Sound/voice.hxx>
90 #include <Sound/soundmanager.hxx>
91 #include <Systems/system_mgr.hxx>
92 #include <Time/light.hxx>
93 #include <Traffic/TrafficMgr.hxx>
94 #include <MultiPlayer/multiplaymgr.hxx>
95 #include <FDM/fdm_shell.hxx>
96 #include <Environment/ephemeris.hxx>
97 #include <Environment/environment_mgr.hxx>
98 #include <Viewer/renderer.hxx>
99 #include <Viewer/viewmgr.hxx>
100 #include <Navaids/NavDataCache.hxx>
101
102 #include "fg_init.hxx"
103 #include "fg_io.hxx"
104 #include "fg_commands.hxx"
105 #include "fg_props.hxx"
106 #include "options.hxx"
107 #include "globals.hxx"
108 #include "logger.hxx"
109 #include "main.hxx"
110 #include "positioninit.hxx"
111
112 using std::string;
113 using namespace boost::algorithm;
114
115
116 // Return the current base package version
117 string fgBasePackageVersion() {
118     SGPath base_path( globals->get_fg_root() );
119     base_path.append("version");
120
121     sg_gzifstream in( base_path.str() );
122     if ( !in.is_open() ) {
123         SGPath old_path( globals->get_fg_root() );
124         old_path.append( "Thanks" );
125         sg_gzifstream old( old_path.str() );
126         if ( !old.is_open() ) {
127             return "[none]";
128         } else {
129             return "[old version]";
130         }
131     }
132
133     string version;
134     in >> version;
135
136     return version;
137 }
138
139
140 template <class T>
141 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
142 {
143   if (!dirPath.exists()) {
144     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
145     return false;
146   }
147     
148   bool recurse = true;
149   simgear::Dir dir(dirPath);
150   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
151   simgear::PathList::iterator p;
152   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
153     // check file name ends with -set.xml
154     
155     // if we found a -set.xml at this level, don't recurse any deeper
156     recurse = false;
157     
158     bool done = (obj->*pred)(*p);
159     if (done) {
160       return true;
161     }
162   } // of -set.xml iteration
163   
164   if (!recurse) {
165     return false;
166   }
167   
168   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
169   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
170     if (p->file() == "CVS") {
171       continue;
172     }
173     
174     if (fgFindAircraftInDir(*p, obj, pred)) {
175       return true;
176     }
177   } // of subdirs iteration
178   
179   return false;
180 }
181
182 template <class T>
183 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
184 {
185   const string_list& paths(globals->get_aircraft_paths());
186   string_list::const_iterator it = paths.begin();
187   for (; it != paths.end(); ++it) {
188     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
189     if (done) {
190       return;
191     }
192   } // of aircraft paths iteration
193   
194   // if we reach this point, search the default location (always last)
195   SGPath rootAircraft(globals->get_fg_root());
196   rootAircraft.append("Aircraft");
197   fgFindAircraftInDir(rootAircraft, obj, pred);
198 }
199
200 class FindAndCacheAircraft
201 {
202 public:
203   FindAndCacheAircraft(SGPropertyNode* autoSave)
204   {
205     _cache = autoSave->getNode("sim/startup/path-cache", true);
206   }
207   
208   bool loadAircraft()
209   {
210     std::string aircraft = fgGetString( "/sim/aircraft", "");
211     if (aircraft.empty()) {
212       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
213       return false;
214     }
215     
216     _searchAircraft = aircraft + "-set.xml";
217     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
218     if (!aircraftDir.empty()) {
219       // aircraft-dir was set, skip any searching at all, if it's valid
220       simgear::Dir acPath(aircraftDir);
221       SGPath setFile = acPath.file(_searchAircraft);
222       if (setFile.exists()) {
223         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
224         
225         try {
226           readProperties(setFile.str(), globals->get_props());
227         } catch ( const sg_exception &e ) {
228           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
229           return false;
230         }
231         
232         return true;
233       } else {
234         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
235                "' not found in specified dir:" << aircraftDir);
236         return false;
237       }
238     }
239     
240     if (!checkCache()) {
241       // prepare cache for re-scan
242       SGPropertyNode *n = _cache->getNode("fg-root", true);
243       n->setStringValue(globals->get_fg_root().c_str());
244       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
245       n = _cache->getNode("fg-aircraft", true);
246       n->setStringValue(getAircraftPaths().c_str());
247       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
248       _cache->removeChildren("aircraft");
249   
250       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
251     }
252     
253     if (_foundPath.str().empty()) {
254       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
255       return false;
256     }
257     
258     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
259     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
260     if (!_foundPath.exists()) {
261       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
262       return false;
263     }
264     
265     try {
266       readProperties(_foundPath.str(), globals->get_props());
267     } catch ( const sg_exception &e ) {
268       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
269       return false;
270     }
271     
272     return true;
273   }
274   
275 private:
276   SGPath getAircraftPaths() {
277     string_list pathList = globals->get_aircraft_paths();
278     SGPath aircraftPaths;
279     string_list::const_iterator it = pathList.begin();
280     if (it != pathList.end()) {
281         aircraftPaths.set(*it);
282         it++;
283     }
284     for (; it != pathList.end(); ++it) {
285         aircraftPaths.add(*it);
286     }
287     return aircraftPaths;
288   }
289   
290   bool checkCache()
291   {
292     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
293       return false; // cache mismatch
294     }
295
296     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
297       return false; // cache mismatch
298     }
299     
300     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
301     for (unsigned int i = 0; i < cache.size(); i++) {
302       const char *name = cache[i]->getStringValue("file", "");
303       if (!boost::equals(_searchAircraft, name, is_iequal())) {
304         continue;
305       }
306       
307       SGPath xml(cache[i]->getStringValue("path", ""));
308       xml.append(name);
309       if (xml.exists()) {
310         _foundPath = xml;
311         return true;
312       } 
313       
314       return false;
315     } // of aircraft in cache iteration
316     
317     return false;
318   }
319   
320   bool checkAircraft(const SGPath& p)
321   {
322     // create cache node
323     int i = 0;
324     while (1) {
325         if (!_cache->getChild("aircraft", i++, false))
326             break;
327     }
328     
329     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
330
331     std::string fileName(p.file());
332     n = entry->getNode("file", true);
333     n->setStringValue(fileName);
334     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
335
336     n = entry->getNode("path", true);
337     n->setStringValue(p.dir());
338     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
339
340     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
341         _foundPath = p;
342         return true;
343     }
344
345     return false;
346   }
347   
348   std::string _searchAircraft;
349   SGPath _foundPath;
350   SGPropertyNode* _cache;
351 };
352
353 #ifdef _WIN32
354 static SGPath platformDefaultDataPath()
355 {
356   char *envp = ::getenv( "APPDATA" );
357   SGPath config( envp );
358   config.append( "flightgear.org" );
359   return config;
360 }
361 #elif __APPLE__
362
363 #include <CoreServices/CoreServices.h>
364
365 static SGPath platformDefaultDataPath()
366 {
367   FSRef ref;
368   OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
369   if (err) {
370     return SGPath();
371   }
372   
373   unsigned char path[1024];
374   if (FSRefMakePath(&ref, path, 1024) != noErr) {
375     return SGPath();
376   }
377   
378   SGPath appData;
379   appData.set((const char*) path);
380   appData.append("FlightGear");
381   return appData;
382 }
383 #else
384 static SGPath platformDefaultDataPath()
385 {
386   SGPath config( homedir );
387   config.append( ".fgfs" );
388   return config;
389 }
390 #endif
391
392 // Read in configuration (file and command line)
393 bool fgInitConfig ( int argc, char **argv )
394 {
395     SGPath dataPath = platformDefaultDataPath();
396     
397     const char *fg_home = getenv("FG_HOME");
398     if (fg_home)
399       dataPath = fg_home;
400       
401     globals->set_fg_home(dataPath.c_str());
402     
403     simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
404     if (!exportDir.exists()) {
405       exportDir.create(0777);
406     }
407     
408     // Set /sim/fg-home and don't allow malign code to override it until
409     // Nasal security is set up.  Use FG_HOME if necessary.
410     SGPropertyNode *home = fgGetNode("/sim", true);
411     home->removeChild("fg-home", 0, false);
412     home = home->getChild("fg-home", 0, true);
413     home->setStringValue(dataPath.c_str());
414     home->setAttribute(SGPropertyNode::WRITE, false);
415   
416     flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
417   
418     // Read global preferences from $FG_ROOT/preferences.xml
419     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
420     fgLoadProps("preferences.xml", globals->get_props());
421     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
422
423     // do not load user settings when reset to default is requested
424     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
425     {
426         SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
427     }
428     else
429     {
430         globals->loadUserSettings(dataPath);
431     }
432
433     // Scan user config files and command line for a specified aircraft.
434     flightgear::Options::sharedInstance()->initAircraft();
435
436     FindAndCacheAircraft f(globals->get_props());
437     if (!f.loadAircraft()) {
438       return false;
439     }
440
441     // parse options after loading aircraft to ensure any user
442     // overrides of defaults are honored.
443     flightgear::Options::sharedInstance()->processOptions();
444       
445     return true;
446 }
447
448
449
450 /**
451  * Initialize vor/ndb/ils/fix list management and query systems (as
452  * well as simple airport db list)
453  * This is called multiple times in the case of a cache rebuild,
454  * to allow length caching to take place in the background, without
455  * blocking the main/UI thread.
456  */
457 bool
458 fgInitNav ()
459 {
460   flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
461   static bool doingRebuild = false;
462   if (doingRebuild || cache->isRebuildRequired()) {
463     doingRebuild = true;
464     bool finished = cache->rebuild();
465     if (!finished) {
466       // sleep to give the rebuild thread more time
467       SGTimeStamp::sleepForMSec(50);
468       return false;
469     }
470   }
471   
472   FGTACANList *channellist = new FGTACANList;
473   globals->set_channellist( channellist );
474   
475   SGPath path(globals->get_fg_root());
476   path.append( "Navaids/TACAN_freq.dat" );
477   flightgear::loadTacan(path, channellist);
478   
479   return true;
480 }
481
482 // General house keeping initializations
483 bool fgInitGeneral() {
484     string root;
485
486     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
487     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
488
489     root = globals->get_fg_root();
490     if ( ! root.length() ) {
491         // No root path set? Then bail ...
492         SG_LOG( SG_GENERAL, SG_ALERT,
493                 "Cannot continue without a path to the base package "
494                 << "being defined." );
495         exit(-1);
496     }
497     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
498
499     // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
500     globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
501     fgSetString("/sim/startup/browser-app", globals->get_browser());
502
503     simgear::Dir cwd(simgear::Dir::current());
504     SGPropertyNode *curr = fgGetNode("/sim", true);
505     curr->removeChild("fg-current", 0, false);
506     curr = curr->getChild("fg-current", 0, true);
507     curr->setStringValue(cwd.path().str());
508     curr->setAttribute(SGPropertyNode::WRITE, false);
509
510     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
511     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
512     return true;
513 }
514
515 // This is the top level init routine which calls all the other
516 // initialization routines.  If you are adding a subsystem to flight
517 // gear, its initialization call should located in this routine.
518 // Returns non-zero if a problem encountered.
519 void fgCreateSubsystems() {
520
521     SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
522     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
523
524     ////////////////////////////////////////////////////////////////////
525     // Initialize the sound subsystem.
526     ////////////////////////////////////////////////////////////////////
527     // Sound manager uses an own subsystem group "SOUND" which is the last
528     // to be updated in every loop.
529     // Sound manager is updated last so it can use the CPU while the GPU
530     // is processing the scenery (doubled the frame-rate for me) -EMH-
531     globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
532
533     ////////////////////////////////////////////////////////////////////
534     // Initialize the event manager subsystem.
535     ////////////////////////////////////////////////////////////////////
536
537     globals->get_event_mgr()->init();
538     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
539
540     ////////////////////////////////////////////////////////////////////
541     // Initialize the property interpolator subsystem. Put into the INIT
542     // group because the "nasal" subsystem may need it at GENERAL take-down.
543     ////////////////////////////////////////////////////////////////////
544     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
545
546
547     ////////////////////////////////////////////////////////////////////
548     // Add the FlightGear property utilities.
549     ////////////////////////////////////////////////////////////////////
550     globals->add_subsystem("properties", new FGProperties);
551
552
553     ////////////////////////////////////////////////////////////////////
554     // Add the performance monitoring system.
555     ////////////////////////////////////////////////////////////////////
556     globals->add_subsystem("performance-mon",
557             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
558                                      fgGetNode("/sim/performance-monitor", true)));
559
560     ////////////////////////////////////////////////////////////////////
561     // Initialize the material property subsystem.
562     ////////////////////////////////////////////////////////////////////
563
564     SGPath mpath( globals->get_fg_root() );
565     mpath.append( fgGetString("/sim/rendering/materials-file") );
566     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
567             globals->get_props()) ) {
568         SG_LOG( SG_GENERAL, SG_ALERT,
569                 "Error loading materials file " << mpath.str() );
570         exit(-1);
571     }
572
573
574     ////////////////////////////////////////////////////////////////////
575     // Initialize the scenery management subsystem.
576     ////////////////////////////////////////////////////////////////////
577
578     globals->get_scenery()->get_scene_graph()
579         ->addChild(simgear::Particles::getCommonRoot());
580     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
581
582     ////////////////////////////////////////////////////////////////////
583     // Initialize the flight model subsystem.
584     ////////////////////////////////////////////////////////////////////
585
586     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
587
588     ////////////////////////////////////////////////////////////////////
589     // Initialize the weather subsystem.
590     ////////////////////////////////////////////////////////////////////
591
592     // Initialize the weather modeling subsystem
593     globals->add_subsystem("environment", new FGEnvironmentMgr);
594     globals->add_subsystem("ephemeris", new Ephemeris);
595     
596     ////////////////////////////////////////////////////////////////////
597     // Initialize the aircraft systems and instrumentation (before the
598     // autopilot.)
599     ////////////////////////////////////////////////////////////////////
600
601     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
602     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
603
604     ////////////////////////////////////////////////////////////////////
605     // Initialize the XML Autopilot subsystem.
606     ////////////////////////////////////////////////////////////////////
607
608     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
609     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
610     globals->add_subsystem( "route-manager", new FGRouteMgr );
611
612     ////////////////////////////////////////////////////////////////////
613     // Initialize the Input-Output subsystem
614     ////////////////////////////////////////////////////////////////////
615     globals->add_subsystem( "io", new FGIO );
616
617     ////////////////////////////////////////////////////////////////////
618     // Create and register the logger.
619     ////////////////////////////////////////////////////////////////////
620     
621     globals->add_subsystem("logger", new FGLogger);
622
623     ////////////////////////////////////////////////////////////////////
624     // Create and register the XML GUI.
625     ////////////////////////////////////////////////////////////////////
626
627     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
628
629     //////////////////////////////////////////////////////////////////////
630     // Initialize the 2D cloud subsystem.
631     ////////////////////////////////////////////////////////////////////
632     fgGetBool("/sim/rendering/bump-mapping", false);
633
634     ////////////////////////////////////////////////////////////////////
635     // Initialize the canvas 2d drawing subsystem.
636     ////////////////////////////////////////////////////////////////////
637     globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
638     globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
639
640     ////////////////////////////////////////////////////////////////////
641     // Initialise the ATIS Manager
642     // Note that this is old stuff, but is necessary for the
643     // current ATIS implementation. Therefore, leave it in here
644     // until the ATIS system is ported over to make use of the ATIS 
645     // sub system infrastructure.
646     ////////////////////////////////////////////////////////////////////
647
648     globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
649
650     ////////////////////////////////////////////////////////////////////
651    // Initialize the ATC subsystem
652     ////////////////////////////////////////////////////////////////////
653     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
654
655     ////////////////////////////////////////////////////////////////////
656     // Initialize multiplayer subsystem
657     ////////////////////////////////////////////////////////////////////
658
659     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
660
661     ////////////////////////////////////////////////////////////////////
662     // Initialise the AI Model Manager
663     ////////////////////////////////////////////////////////////////////
664     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
665     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
666     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
667
668
669     // It's probably a good idea to initialize the top level traffic manager
670     // After the AI and ATC systems have been initialized properly.
671     // AI Traffic manager
672     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
673
674     ////////////////////////////////////////////////////////////////////
675     // Add a new 2D panel.
676     ////////////////////////////////////////////////////////////////////
677
678     fgSetArchivable("/sim/panel/visibility");
679     fgSetArchivable("/sim/panel/x-offset");
680     fgSetArchivable("/sim/panel/y-offset");
681     fgSetArchivable("/sim/panel/jitter");
682   
683     ////////////////////////////////////////////////////////////////////
684     // Initialize the controls subsystem.
685     ////////////////////////////////////////////////////////////////////
686     
687     globals->add_subsystem("controls", new FGControls);
688
689     ////////////////////////////////////////////////////////////////////
690     // Initialize the input subsystem.
691     ////////////////////////////////////////////////////////////////////
692
693     globals->add_subsystem("input", new FGInput);
694
695
696     ////////////////////////////////////////////////////////////////////
697     // Initialize the replay subsystem
698     ////////////////////////////////////////////////////////////////////
699     globals->add_subsystem("replay", new FGReplay);
700
701 #ifdef ENABLE_AUDIO_SUPPORT
702     ////////////////////////////////////////////////////////////////////
703     // Initialize the sound-effects subsystem.
704     ////////////////////////////////////////////////////////////////////
705     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
706 #endif
707
708     ////////////////////////////////////////////////////////////////////
709     // Initialize the lighting subsystem.
710     ////////////////////////////////////////////////////////////////////
711
712     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
713     
714     // ordering here is important : Nasal (via events), then models, then views
715     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
716
717     globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
718     globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
719
720     FGViewMgr *viewmgr = new FGViewMgr;
721     globals->set_viewmgr( viewmgr );
722     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
723
724     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
725       SGSubsystemMgr::DISPLAY);
726 }
727
728 void fgPostInitSubsystems()
729 {
730     SGTimeStamp st;
731     st.stamp();
732   
733     ////////////////////////////////////////////////////////////////////////
734     // Initialize the Nasal interpreter.
735     // Do this last, so that the loaded scripts see initialized state
736     ////////////////////////////////////////////////////////////////////////
737     FGNasalSys* nasal = new FGNasalSys();
738     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
739     nasal->init();
740     SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
741   
742     // initialize methods that depend on other subsystems.
743     st.stamp();
744     globals->get_subsystem_mgr()->postinit();
745     SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
746   
747     ////////////////////////////////////////////////////////////////////
748     // TODO FIXME! UGLY KLUDGE!
749     ////////////////////////////////////////////////////////////////////
750     {
751         /* Scenarios require Nasal, so FGAIManager loads the scenarios,
752          * including its models such as a/c carriers, in its 'postinit',
753          * which is the very last thing we do.
754          * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
755          * one of the first things we do, long before scenarios/carriers are
756          * loaded. => When requested "initial preset position" relates to a
757          * carrier, recalculate the 'initial' position here (how have things
758          * ever worked before this hack - this init sequence has always been
759          * this way...?)*/
760         std::string carrier = fgGetString("/sim/presets/carrier","");
761         if (carrier != "")
762         {
763             // clear preset location and re-trigger position setup
764             fgSetDouble("/sim/presets/longitude-deg", 9999);
765             fgSetDouble("/sim/presets/latitude-deg", 9999);
766             flightgear::initPosition();
767         }
768     }
769
770     ////////////////////////////////////////////////////////////////////////
771     // End of subsystem initialization.
772     ////////////////////////////////////////////////////////////////////
773
774     fgSetBool("/sim/crashed", false);
775     fgSetBool("/sim/initialized", true);
776
777     SG_LOG( SG_GENERAL, SG_INFO, endl);
778
779                                 // Save the initial state for future
780                                 // reference.
781     globals->saveInitialState();
782 }
783
784 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
785 void fgReInitSubsystems()
786 {
787     static const SGPropertyNode *master_freeze
788         = fgGetNode("/sim/freeze/master");
789
790     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
791
792 // setup state to begin re-init
793     bool freeze = master_freeze->getBoolValue();
794     if ( !freeze ) {
795         fgSetBool("/sim/freeze/master", true);
796     }
797     
798     fgSetBool("/sim/signals/reinit", true);
799     fgSetBool("/sim/crashed", false);
800
801 // do actual re-init steps
802     globals->get_subsystem("flight")->unbind();
803     
804   // reset control state, before restoring initial state; -set or config files
805   // may specify values for flaps, trim tabs, magnetos, etc
806     globals->get_controls()->reset_all();
807         
808     globals->restoreInitialState();
809
810     // update our position based on current presets
811     flightgear::initPosition();
812     
813     // Force reupdating the positions of the ai 3d models. They are used for
814     // initializing ground level for the FDM.
815     globals->get_subsystem("ai-model")->reinit();
816
817     // Initialize the FDM
818     globals->get_subsystem("flight")->reinit();
819
820     // reset replay buffers
821     globals->get_subsystem("replay")->reinit();
822     
823     // reload offsets from config defaults
824     globals->get_viewmgr()->reinit();
825
826     globals->get_subsystem("time")->reinit();
827
828     // need to bind FDMshell again, since we manually unbound it above...
829     globals->get_subsystem("flight")->bind();
830
831     // need to reset aircraft (systems/instruments) so they can adapt to current environment
832     globals->get_subsystem("systems")->reinit();
833     globals->get_subsystem("instrumentation")->reinit();
834
835 // setup state to end re-init
836     fgSetBool("/sim/signals/reinit", false);
837     if ( !freeze ) {
838         fgSetBool("/sim/freeze/master", false);
839     }
840     fgSetBool("/sim/sceneryloaded",false);
841 }
842
843
844 ///////////////////////////////////////////////////////////////////////////////
845 // helper object to implement the --show-aircraft command.
846 // resides here so we can share the fgFindAircraftInDir template above,
847 // and hence ensure this command lists exectly the same aircraft as the normal
848 // loading path.
849 class ShowAircraft 
850 {
851 public:
852   ShowAircraft()
853   {
854     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
855   }
856   
857   
858   void show(const SGPath& path)
859   {
860     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
861   
862     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
863     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
864     cout << "Available aircraft:" << endl;
865     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
866         cout << _aircraft[i] << endl;
867     }
868   }
869   
870 private:
871   bool processAircraft(const SGPath& path)
872   {
873     SGPropertyNode root;
874     try {
875        readProperties(path.str(), &root);
876     } catch (sg_exception& ) {
877        return false;
878     }
879   
880     int maturity = 0;
881     string descStr("   ");
882     descStr += path.file();
883   // trim common suffix from file names
884     int nPos = descStr.rfind("-set.xml");
885     if (nPos == (int)(descStr.size() - 8)) {
886       descStr.resize(nPos);
887     }
888     
889     SGPropertyNode *node = root.getNode("sim");
890     if (node) {
891       SGPropertyNode* desc = node->getNode("description");
892       // if a status tag is found, read it in
893       if (node->hasValue("status")) {
894         maturity = getNumMaturity(node->getStringValue("status"));
895       }
896       
897       if (desc) {
898         if (descStr.size() <= 27+3) {
899           descStr.append(29+3-descStr.size(), ' ');
900         } else {
901           descStr += '\n';
902           descStr.append( 32, ' ');
903         }
904         descStr += desc->getStringValue();
905       }
906     } // of have 'sim' node
907     
908     if (maturity < _minStatus) {
909       return false;
910     }
911
912     _aircraft.push_back(descStr);
913     return false;
914   }
915
916
917   int getNumMaturity(const char * str) 
918   {
919     // changes should also be reflected in $FG_ROOT/data/options.xml & 
920     // $FG_ROOT/data/Translations/string-default.xml
921     const char* levels[] = {"alpha","beta","early-production","production"}; 
922
923     if (!strcmp(str, "all")) {
924       return 0;
925     }
926
927     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
928       if (strcmp(str,levels[i])==0)
929         return i;
930
931     return 0;
932   }
933
934   // recommended in Meyers, Effective STL when internationalization and embedded
935   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
936   struct ciLessLibC : public std::binary_function<string, string, bool>
937   {
938     bool operator()(const std::string &lhs, const std::string &rhs) const
939     {
940       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
941     }
942   };
943
944   int _minStatus;
945   string_list _aircraft;
946 };
947
948 void fgShowAircraft(const SGPath &path)
949 {
950     ShowAircraft s;
951     s.show(path);
952         
953 #ifdef _MSC_VER
954     cout << "Hit a key to continue..." << endl;
955     cin.get();
956 #endif
957 }
958
959