1 // globals.cxx -- Global state that needs to be shared among the sim modules
3 // Written by Curtis Olson, started July 2000.
5 // Copyright (C) 2000 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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 Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <boost/foreach.hpp>
30 #include <simgear/structure/commands.hxx>
31 #include <simgear/misc/sg_path.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/ephemeris/ephemeris.hxx>
35 #include <simgear/scene/material/matlib.hxx>
36 #include <simgear/structure/subsystem_mgr.hxx>
37 #include <simgear/structure/event_mgr.hxx>
38 #include <simgear/sound/soundmgr_openal.hxx>
39 #include <simgear/misc/ResourceManager.hxx>
40 #include <simgear/props/propertyObject.hxx>
41 #include <simgear/props/props_io.hxx>
43 #include <Aircraft/controls.hxx>
44 #include <Airports/runways.hxx>
45 #include <ATCDCL/ATISmgr.hxx>
46 #include <Autopilot/route_mgr.hxx>
47 #include <GUI/FGFontCache.hxx>
49 #include <MultiPlayer/multiplaymgr.hxx>
50 #include <Scenery/scenery.hxx>
51 #include <Scenery/tilemgr.hxx>
52 #include <Navaids/navlist.hxx>
53 #include <Viewer/renderer.hxx>
54 #include <Viewer/viewmgr.hxx>
56 #include "globals.hxx"
59 #include "fg_props.hxx"
62 class AircraftResourceProvider : public simgear::ResourceProvider
65 AircraftResourceProvider() :
66 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
70 virtual SGPath resolve(const std::string& aResource, SGPath&) const
72 string_list pieces(sgPathBranchSplit(aResource));
73 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
74 return SGPath(); // not an Aircraft path
77 // test against the aircraft-dir property
78 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
79 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
80 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
81 // current aircraft-dir matches resource aircraft
82 SGPath r(aircraftDir);
83 for (unsigned int i=2; i<pieces.size(); ++i) {
92 // try each aircraft dir in turn
93 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
94 const string_list& dirs(globals->get_aircraft_paths());
95 string_list::const_iterator it = dirs.begin();
96 for (; it != dirs.end(); ++it) {
101 } // of aircraft path iteration
103 return SGPath(); // not found
107 class CurrentAircraftDirProvider : public simgear::ResourceProvider
110 CurrentAircraftDirProvider() :
111 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
115 virtual SGPath resolve(const std::string& aResource, SGPath&) const
117 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
118 SGPath p(aircraftDir);
120 return p.exists() ? p : SGPath();
124 ////////////////////////////////////////////////////////////////////////
125 // Implementation of FGGlobals.
126 ////////////////////////////////////////////////////////////////////////
133 FGGlobals::FGGlobals() :
134 props( new SGPropertyNode ),
135 initial_state( NULL ),
136 locale( new FGLocale(props) ),
137 renderer( new FGRenderer ),
138 subsystem_mgr( new SGSubsystemMgr ),
139 event_mgr( new SGEventMgr ),
150 commands( SGCommandMgr::instance() ),
151 channel_options_list( NULL ),
152 initial_waypoints( NULL ),
155 fontcache ( new FGFontCache ),
157 haveUserSettings(false)
159 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
160 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
161 simgear::PropertyObjectBase::setDefaultRoot(props);
163 positionLon = props->getNode("position/longitude-deg", true);
164 positionLat = props->getNode("position/latitude-deg", true);
165 positionAlt = props->getNode("position/altitude-ft", true);
167 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
168 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
169 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
171 orientPitch = props->getNode("orientation/pitch-deg", true);
172 orientHeading = props->getNode("orientation/heading-deg", true);
173 orientRoll = props->getNode("orientation/roll-deg", true);
177 FGGlobals::~FGGlobals()
179 // save user settings (unless already saved)
182 // The AIModels manager performs a number of actions upon
183 // Shutdown that implicitly assume that other subsystems
184 // are still operational (Due to the dynamic allocation and
185 // deallocation of AIModel objects. To ensure we can safely
186 // shut down all subsystems, make sure we take down the
187 // AIModels system first.
188 SGSubsystem* ai = subsystem_mgr->remove("ai-model");
193 SGSubsystem* sound = subsystem_mgr->remove("sound");
195 subsystem_mgr->shutdown();
196 subsystem_mgr->unbind();
197 delete subsystem_mgr;
208 delete channel_options_list;
209 delete initial_waypoints;
220 // set the fg_root path
221 void FGGlobals::set_fg_root (const std::string &root) {
223 fg_root = tmp.realpath();
225 // append /data to root if it exists
226 tmp.append( "data" );
227 tmp.append( "version" );
228 if ( tmp.exists() ) {
229 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
231 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
232 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
233 << fg_root << "'\n***\n***");
236 // remove /sim/fg-root before writing to prevent hijacking
237 SGPropertyNode *n = fgGetNode("/sim", true);
238 n->removeChild("fg-root", 0, false);
239 n = n->getChild("fg-root", 0, true);
240 n->setStringValue(fg_root.c_str());
241 n->setAttribute(SGPropertyNode::WRITE, false);
243 simgear::ResourceManager::instance()->addBasePath(fg_root,
244 simgear::ResourceManager::PRIORITY_DEFAULT);
247 // set the fg_home path
248 void FGGlobals::set_fg_home (const std::string &home) {
250 fg_home = tmp.realpath();
253 PathList FGGlobals::get_data_paths() const
255 PathList r(additional_data_paths);
256 r.push_back(SGPath(fg_root));
260 PathList FGGlobals::get_data_paths(const std::string& suffix) const
263 BOOST_FOREACH(SGPath p, get_data_paths()) {
273 void FGGlobals::append_data_path(const SGPath& path)
275 if (!path.exists()) {
276 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
279 additional_data_paths.push_back(path);
282 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
284 BOOST_FOREACH(SGPath p, additional_data_paths) {
285 p.append(pathSuffix);
291 SGPath rootPath(fg_root);
292 rootPath.append(pathSuffix);
293 if (rootPath.exists()) {
297 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
301 void FGGlobals::append_fg_scenery (const std::string &paths)
303 // fg_scenery.clear();
304 SGPropertyNode* sim = fgGetNode("/sim", true);
306 // find first unused fg-scenery property in /sim
308 while (sim->getChild("fg-scenery", propIndex) != NULL) {
312 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
313 SGPath abspath(path.realpath());
314 if (!abspath.exists()) {
315 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
319 // check for duplicates
320 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
321 if (ex != fg_scenery.end()) {
322 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
326 simgear::Dir dir(abspath);
327 SGPath terrainDir(dir.file("Terrain"));
328 SGPath objectsDir(dir.file("Objects"));
330 // this code used to add *either* the base dir, OR add the
331 // Terrain and Objects subdirs, but the conditional logic was commented
332 // out, such that all three dirs are added. Unfortunately there's
333 // no information as to why the change was made.
334 fg_scenery.push_back(abspath.str());
336 if (terrainDir.exists()) {
337 fg_scenery.push_back(terrainDir.str());
340 if (objectsDir.exists()) {
341 fg_scenery.push_back(objectsDir.str());
344 // insert a marker for FGTileEntry::load(), so that
345 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
346 // "B/Terrain", "B/Objects", ""]
347 fg_scenery.push_back("");
349 // make scenery dirs available to Nasal
350 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
351 n->setStringValue(abspath.str());
352 n->setAttribute(SGPropertyNode::WRITE, false);
353 } // of path list iteration
356 void FGGlobals::append_aircraft_path(const std::string& path)
358 SGPath dirPath(path);
359 if (!dirPath.exists()) {
360 SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
363 std::string abspath = dirPath.realpath();
365 unsigned int index = fg_aircraft_dirs.size();
366 fg_aircraft_dirs.push_back(abspath);
368 // make aircraft dirs available to Nasal
369 SGPropertyNode* sim = fgGetNode("/sim", true);
370 sim->removeChild("fg-aircraft", index, false);
371 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
372 n->setStringValue(abspath);
373 n->setAttribute(SGPropertyNode::WRITE, false);
376 void FGGlobals::append_aircraft_paths(const std::string& path)
378 string_list paths = sgPathSplit(path);
379 for (unsigned int p = 0; p<paths.size(); ++p) {
380 append_aircraft_path(paths[p]);
384 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
386 return simgear::ResourceManager::instance()->findPath(branch);
389 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
391 return simgear::ResourceManager::instance()->findPath(branch);
394 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
396 return simgear::ResourceManager::instance()
397 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
401 FGGlobals::get_renderer () const
407 FGGlobals::get_subsystem_mgr () const
409 return subsystem_mgr;
413 FGGlobals::get_subsystem (const char * name)
415 return subsystem_mgr->get_subsystem(name);
419 FGGlobals::add_subsystem (const char * name,
420 SGSubsystem * subsystem,
421 SGSubsystemMgr::GroupType type,
424 subsystem_mgr->add(name, subsystem, type, min_time_sec);
428 FGGlobals::get_soundmgr () const
431 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
437 FGGlobals::get_event_mgr () const
443 FGGlobals::get_aircraft_position() const
445 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
446 positionLat->getDoubleValue(),
447 positionAlt->getDoubleValue());
451 FGGlobals::get_aircraft_position_cart() const
453 return SGVec3d::fromGeod(get_aircraft_position());
456 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
458 heading = orientHeading->getDoubleValue();
459 pitch = orientPitch->getDoubleValue();
460 roll = orientRoll->getDoubleValue();
464 FGGlobals::get_view_position() const
466 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
467 viewLat->getDoubleValue(),
468 viewAlt->getDoubleValue());
472 FGGlobals::get_view_position_cart() const
474 return SGVec3d::fromGeod(get_view_position());
477 // Save the current state as the initial state.
479 FGGlobals::saveInitialState ()
481 initial_state = new SGPropertyNode();
483 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
484 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
485 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
486 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
487 if (!copyProperties(props, initial_state, expected, checked))
488 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
490 // delete various properties from the initial state, since we want to
491 // preserve their values even if doing a restore
492 // => Properties should now use the PRESERVE flag to protect their values
493 // on sim-reset. Remove some specific properties for backward compatibility.
494 SGPropertyNode* sim = initial_state->getChild("sim");
495 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
496 if (cameraGroupNode) {
497 cameraGroupNode->removeChild("camera");
498 cameraGroupNode->removeChild("gui");
502 static std::string autosaveName()
504 std::ostringstream os;
505 string_list versionParts = simgear::strutils::split(VERSION, ".");
506 if (versionParts.size() < 2) {
507 return "autosave.xml";
510 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
514 // Restore the saved initial state, if any
516 FGGlobals::restoreInitialState ()
518 if ( initial_state == 0 ) {
519 SG_LOG(SG_GENERAL, SG_ALERT,
520 "No initial state available to restore!!!");
523 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
524 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
525 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
526 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
527 if ( copyProperties(initial_state, props, expected, checked)) {
528 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
530 SG_LOG( SG_GENERAL, SG_INFO,
531 "Some errors restoring initial state (read-only props?)" );
536 // Load user settings from autosave.xml
538 FGGlobals::loadUserSettings(const SGPath& dataPath)
540 // remember that we have (tried) to load any existing autsave.xml
541 haveUserSettings = true;
543 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
544 SGPropertyNode autosave;
545 if (autosaveFile.exists()) {
546 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
548 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
549 } catch (sg_exception& e) {
550 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
551 << "(from " << e.getOrigin() << ")");
554 copyProperties(&autosave, globals->get_props());
557 // Save user settings in autosave.xml
559 FGGlobals::saveUserSettings()
561 // only save settings when we have (tried) to load the previous
562 // settings (otherwise user data was lost)
563 if (!haveUserSettings)
566 if (fgGetBool("/sim/startup/save-on-exit")) {
567 // don't save settings more than once on shutdown
568 haveUserSettings = false;
570 SGPath autosaveFile(globals->get_fg_home());
571 autosaveFile.append(autosaveName());
572 autosaveFile.create_dir( 0700 );
573 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
575 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
576 } catch (const sg_exception &e) {
577 guiErrorMessage("Error writing autosave:", e);
579 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
584 FGGlobals::get_current_view () const
586 return viewmgr->get_current_view();
589 long int FGGlobals::get_warp() const
591 return fgGetInt("/sim/time/warp");
594 void FGGlobals::set_warp( long int w )
596 fgSetInt("/sim/time/warp", w);
599 long int FGGlobals::get_warp_delta() const
601 return fgGetInt("/sim/time/warp-delta");
604 void FGGlobals::set_warp_delta( long int d )
606 fgSetInt("/sim/time/warp-delta", d);
609 // end of globals.cxx