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