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