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