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