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