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) {
88 SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " via /sim/aircraft-dir: " << r.str());
93 // try each aircraft dir in turn
94 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
95 const string_list& dirs(globals->get_aircraft_paths());
96 string_list::const_iterator it = dirs.begin();
97 for (; it != dirs.end(); ++it) {
100 SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " in aircraft dir: " << *it);
103 } // of aircraft path iteration
105 return SGPath(); // not found
109 class CurrentAircraftDirProvider : public simgear::ResourceProvider
112 CurrentAircraftDirProvider() :
113 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
117 virtual SGPath resolve(const std::string& aResource, SGPath&) const
119 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
120 SGPath p(aircraftDir);
122 return p.exists() ? p : SGPath();
126 ////////////////////////////////////////////////////////////////////////
127 // Implementation of FGGlobals.
128 ////////////////////////////////////////////////////////////////////////
135 FGGlobals::FGGlobals() :
136 props( new SGPropertyNode ),
137 initial_state( NULL ),
138 locale( new FGLocale(props) ),
139 renderer( new FGRenderer ),
140 subsystem_mgr( new SGSubsystemMgr ),
141 event_mgr( new SGEventMgr ),
152 commands( SGCommandMgr::instance() ),
153 channel_options_list( NULL ),
154 initial_waypoints( NULL ),
157 fontcache ( new FGFontCache ),
159 haveUserSettings(false)
161 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
162 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
163 simgear::PropertyObjectBase::setDefaultRoot(props);
165 positionLon = props->getNode("position/longitude-deg", true);
166 positionLat = props->getNode("position/latitude-deg", true);
167 positionAlt = props->getNode("position/altitude-ft", true);
169 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
170 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
171 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
173 orientPitch = props->getNode("orientation/pitch-deg", true);
174 orientHeading = props->getNode("orientation/heading-deg", true);
175 orientRoll = props->getNode("orientation/roll-deg", true);
179 FGGlobals::~FGGlobals()
181 // save user settings (unless already saved)
184 // The AIModels manager performs a number of actions upon
185 // Shutdown that implicitly assume that other subsystems
186 // are still operational (Due to the dynamic allocation and
187 // deallocation of AIModel objects. To ensure we can safely
188 // shut down all subsystems, make sure we take down the
189 // AIModels system first.
190 SGSubsystem* ai = subsystem_mgr->remove("ai-model");
195 SGSubsystem* sound = subsystem_mgr->remove("sound");
197 subsystem_mgr->shutdown();
198 subsystem_mgr->unbind();
199 delete subsystem_mgr;
210 delete channel_options_list;
211 delete initial_waypoints;
222 // set the fg_root path
223 void FGGlobals::set_fg_root (const string &root) {
225 fg_root = tmp.realpath();
227 // append /data to root if it exists
228 tmp.append( "data" );
229 tmp.append( "version" );
230 if ( tmp.exists() ) {
231 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
233 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
234 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
235 << fg_root << "'\n***\n***");
238 // remove /sim/fg-root before writing to prevent hijacking
239 SGPropertyNode *n = fgGetNode("/sim", true);
240 n->removeChild("fg-root", 0, false);
241 n = n->getChild("fg-root", 0, true);
242 n->setStringValue(fg_root.c_str());
243 n->setAttribute(SGPropertyNode::WRITE, false);
245 simgear::ResourceManager::instance()->addBasePath(fg_root,
246 simgear::ResourceManager::PRIORITY_DEFAULT);
249 // set the fg_home path
250 void FGGlobals::set_fg_home (const string &home) {
252 fg_home = tmp.realpath();
255 void FGGlobals::append_fg_scenery (const string &paths)
257 // fg_scenery.clear();
258 SGPropertyNode* sim = fgGetNode("/sim", true);
260 // find first unused fg-scenery property in /sim
262 while (sim->getChild("fg-scenery", propIndex) != NULL) {
266 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
267 SGPath abspath(path.realpath());
268 if (!abspath.exists()) {
269 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
273 // check for duplicates
274 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
275 if (ex != fg_scenery.end()) {
276 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
280 simgear::Dir dir(abspath);
281 SGPath terrainDir(dir.file("Terrain"));
282 SGPath objectsDir(dir.file("Objects"));
284 // this code used to add *either* the base dir, OR add the
285 // Terrain and Objects subdirs, but the conditional logic was commented
286 // out, such that all three dirs are added. Unfortunately there's
287 // no information as to why the change was made.
288 fg_scenery.push_back(abspath.str());
290 if (terrainDir.exists()) {
291 fg_scenery.push_back(terrainDir.str());
294 if (objectsDir.exists()) {
295 fg_scenery.push_back(objectsDir.str());
298 // insert a marker for FGTileEntry::load(), so that
299 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
300 // "B/Terrain", "B/Objects", ""]
301 fg_scenery.push_back("");
303 // make scenery dirs available to Nasal
304 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
305 n->setStringValue(abspath.str());
306 n->setAttribute(SGPropertyNode::WRITE, false);
307 } // of path list iteration
310 void FGGlobals::append_aircraft_path(const std::string& path)
312 SGPath dirPath(path);
313 if (!dirPath.exists()) {
314 SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
317 std::string abspath = dirPath.realpath();
319 unsigned int index = fg_aircraft_dirs.size();
320 fg_aircraft_dirs.push_back(abspath);
322 // make aircraft dirs available to Nasal
323 SGPropertyNode* sim = fgGetNode("/sim", true);
324 sim->removeChild("fg-aircraft", index, false);
325 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
326 n->setStringValue(abspath);
327 n->setAttribute(SGPropertyNode::WRITE, false);
330 void FGGlobals::append_aircraft_paths(const std::string& path)
332 string_list paths = sgPathSplit(path);
333 for (unsigned int p = 0; p<paths.size(); ++p) {
334 append_aircraft_path(paths[p]);
338 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
340 return simgear::ResourceManager::instance()->findPath(branch);
343 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
345 return simgear::ResourceManager::instance()->findPath(branch);
348 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
350 return simgear::ResourceManager::instance()
351 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
355 FGGlobals::get_renderer () const
361 FGGlobals::get_subsystem_mgr () const
363 return subsystem_mgr;
367 FGGlobals::get_subsystem (const char * name)
369 return subsystem_mgr->get_subsystem(name);
373 FGGlobals::add_subsystem (const char * name,
374 SGSubsystem * subsystem,
375 SGSubsystemMgr::GroupType type,
378 subsystem_mgr->add(name, subsystem, type, min_time_sec);
382 FGGlobals::get_soundmgr () const
385 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
391 FGGlobals::get_event_mgr () const
397 FGGlobals::get_aircraft_position() const
399 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
400 positionLat->getDoubleValue(),
401 positionAlt->getDoubleValue());
405 FGGlobals::get_aircraft_position_cart() const
407 return SGVec3d::fromGeod(get_aircraft_position());
410 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
412 heading = orientHeading->getDoubleValue();
413 pitch = orientPitch->getDoubleValue();
414 roll = orientRoll->getDoubleValue();
418 FGGlobals::get_view_position() const
420 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
421 viewLat->getDoubleValue(),
422 viewAlt->getDoubleValue());
426 FGGlobals::get_view_position_cart() const
428 return SGVec3d::fromGeod(get_view_position());
431 // Save the current state as the initial state.
433 FGGlobals::saveInitialState ()
435 initial_state = new SGPropertyNode();
437 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
438 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
439 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
440 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
441 if (!copyProperties(props, initial_state, expected, checked))
442 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
444 // delete various properties from the initial state, since we want to
445 // preserve their values even if doing a restore
446 // => Properties should now use the PRESERVE flag to protect their values
447 // on sim-reset. Remove some specific properties for backward compatibility.
448 SGPropertyNode* sim = initial_state->getChild("sim");
449 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
450 if (cameraGroupNode) {
451 cameraGroupNode->removeChild("camera");
452 cameraGroupNode->removeChild("gui");
456 static std::string autosaveName()
458 std::ostringstream os;
459 string_list versionParts = simgear::strutils::split(VERSION, ".");
460 if (versionParts.size() < 2) {
461 return "autosave.xml";
464 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
468 // Restore the saved initial state, if any
470 FGGlobals::restoreInitialState ()
472 if ( initial_state == 0 ) {
473 SG_LOG(SG_GENERAL, SG_ALERT,
474 "No initial state available to restore!!!");
477 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
478 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
479 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
480 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
481 if ( copyProperties(initial_state, props, expected, checked)) {
482 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
484 SG_LOG( SG_GENERAL, SG_INFO,
485 "Some errors restoring initial state (read-only props?)" );
490 // Load user settings from autosave.xml
492 FGGlobals::loadUserSettings(const SGPath& dataPath)
494 // remember that we have (tried) to load any existing autsave.xml
495 haveUserSettings = true;
497 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
498 SGPropertyNode autosave;
499 if (autosaveFile.exists()) {
500 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
502 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
503 } catch (sg_exception& e) {
504 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
505 << "(from " << e.getOrigin() << ")");
508 copyProperties(&autosave, globals->get_props());
511 // Save user settings in autosave.xml
513 FGGlobals::saveUserSettings()
515 // only save settings when we have (tried) to load the previous
516 // settings (otherwise user data was lost)
517 if (!haveUserSettings)
520 if (fgGetBool("/sim/startup/save-on-exit")) {
521 // don't save settings more than once on shutdown
522 haveUserSettings = false;
524 SGPath autosaveFile(globals->get_fg_home());
525 autosaveFile.append(autosaveName());
526 autosaveFile.create_dir( 0700 );
527 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
529 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
530 } catch (const sg_exception &e) {
531 guiErrorMessage("Error writing autosave:", e);
533 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
538 FGGlobals::get_current_view () const
540 return viewmgr->get_current_view();
543 long int FGGlobals::get_warp() const
545 return fgGetInt("/sim/time/warp");
548 void FGGlobals::set_warp( long int w )
550 fgSetInt("/sim/time/warp", w);
553 long int FGGlobals::get_warp_delta() const
555 return fgGetInt("/sim/time/warp-delta");
558 void FGGlobals::set_warp_delta( long int d )
560 fgSetInt("/sim/time/warp-delta", d);
563 // end of globals.cxx