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