]> git.mxchange.org Git - flightgear.git/blob - src/Main/globals.cxx
Make FGControls behave like a standard subsystem.
[flightgear.git] / src / Main / globals.cxx
1 // globals.cxx -- Global state that needs to be shared among the sim modules
2 //
3 // Written by Curtis Olson, started July 2000.
4 //
5 // Copyright (C) 2000  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 Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <boost/foreach.hpp>
28 #include <algorithm>
29
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>
42
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>
48 #include <GUI/gui.h>
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>
55
56 #include "globals.hxx"
57 #include "locale.hxx"
58
59 #include "fg_props.hxx"
60 #include "fg_io.hxx"
61
62 class AircraftResourceProvider : public simgear::ResourceProvider
63 {
64 public:
65   AircraftResourceProvider() :
66     simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
67   {
68   }
69   
70   virtual SGPath resolve(const std::string& aResource, SGPath&) const
71   {
72     string_list pieces(sgPathBranchSplit(aResource));
73     if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
74       return SGPath(); // not an Aircraft path
75     }
76     
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) {
84           r.append(pieces[i]);
85         }
86         
87         if (r.exists()) {
88           SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " via /sim/aircraft-dir: " << r.str());
89           return r;
90         }
91     }
92   
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) {
98       SGPath p(*it, res);
99       if (p.exists()) {
100         SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " in aircraft dir: " << *it);
101         return p;
102       }
103     } // of aircraft path iteration
104     
105     return SGPath(); // not found
106   }
107 };
108
109 ////////////////////////////////////////////////////////////////////////
110 // Implementation of FGGlobals.
111 ////////////////////////////////////////////////////////////////////////
112
113 // global global :-)
114 FGGlobals *globals;
115
116
117 // Constructor
118 FGGlobals::FGGlobals() :
119     props( new SGPropertyNode ),
120     initial_state( NULL ),
121     locale( new FGLocale(props) ),
122     renderer( new FGRenderer ),
123     subsystem_mgr( new SGSubsystemMgr ),
124     event_mgr( new SGEventMgr ),
125     sim_time_sec( 0.0 ),
126     fg_root( "" ),
127     fg_home( "" ),
128     time_params( NULL ),
129     ephem( NULL ),
130     matlib( NULL ),
131     route_mgr( NULL ),
132     ATIS_mgr( NULL ),
133     controls( NULL ),
134     viewmgr( NULL ),
135     commands( SGCommandMgr::instance() ),
136     channel_options_list( NULL ),
137     initial_waypoints( NULL ),
138     scenery( NULL ),
139     tile_mgr( NULL ),
140     fontcache ( new FGFontCache ),
141     channellist( NULL ),
142     haveUserSettings(false)
143 {
144   simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider());
145   simgear::PropertyObjectBase::setDefaultRoot(props);
146   
147   positionLon = props->getNode("position/longitude-deg", true);
148   positionLat = props->getNode("position/latitude-deg", true);
149   positionAlt = props->getNode("position/altitude-ft", true);
150   
151   orientPitch = props->getNode("orientation/pitch-deg", true);
152   orientHeading = props->getNode("orientation/heading-deg", true);
153   orientRoll = props->getNode("orientation/roll-deg", true);
154 }
155
156 // Destructor
157 FGGlobals::~FGGlobals() 
158 {
159     // save user settings (unless already saved)
160     saveUserSettings();
161
162     // The AIModels manager performs a number of actions upon
163     // Shutdown that implicitly assume that other subsystems
164     // are still operational (Due to the dynamic allocation and
165     // deallocation of AIModel objects. To ensure we can safely
166     // shut down all subsystems, make sure we take down the 
167     // AIModels system first.
168     SGSubsystem* ai = subsystem_mgr->remove("ai-model");
169     if (ai) {
170         ai->unbind();
171         delete ai;
172     }
173     SGSubsystem* sound = subsystem_mgr->remove("sound");
174
175     subsystem_mgr->shutdown();
176     subsystem_mgr->unbind();
177     delete subsystem_mgr;
178     
179     delete renderer;
180     renderer = NULL;
181     
182     delete time_params;
183     delete matlib;
184     delete route_mgr;
185
186     delete ATIS_mgr;
187
188     delete channel_options_list;
189     delete initial_waypoints;
190     delete scenery;
191     delete fontcache;
192
193     delete channellist;
194     delete sound;
195
196     delete locale;
197     locale = NULL;
198 }
199
200 // set the fg_root path
201 void FGGlobals::set_fg_root (const string &root) {
202     SGPath tmp(root);
203     fg_root = tmp.realpath();
204
205     // append /data to root if it exists
206     tmp.append( "data" );
207     tmp.append( "version" );
208     if ( tmp.exists() ) {
209         fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
210         fg_root += "/data";
211         fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
212         SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
213                 << fg_root << "'\n***\n***");
214     }
215
216     // remove /sim/fg-root before writing to prevent hijacking
217     SGPropertyNode *n = fgGetNode("/sim", true);
218     n->removeChild("fg-root", 0, false);
219     n = n->getChild("fg-root", 0, true);
220     n->setStringValue(fg_root.c_str());
221     n->setAttribute(SGPropertyNode::WRITE, false);
222     
223     simgear::ResourceManager::instance()->addBasePath(fg_root, 
224       simgear::ResourceManager::PRIORITY_DEFAULT);
225 }
226
227 // set the fg_home path
228 void FGGlobals::set_fg_home (const string &home) {
229     SGPath tmp(home);
230     fg_home = tmp.realpath();
231 }
232
233 void FGGlobals::append_fg_scenery (const string &paths)
234 {
235 //    fg_scenery.clear();
236     SGPropertyNode* sim = fgGetNode("/sim", true);
237
238   // find first unused fg-scenery property in /sim
239     int propIndex = 0;
240     while (sim->getChild("fg-scenery", propIndex) != NULL) {
241       ++propIndex; 
242     }
243   
244     BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
245         SGPath abspath(path.realpath());
246         if (!abspath.exists()) {
247           SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
248           continue;
249         }
250
251       // check for duplicates
252       string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
253       if (ex != fg_scenery.end()) {
254         SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
255         continue;
256       }
257       
258         simgear::Dir dir(abspath);
259         SGPath terrainDir(dir.file("Terrain"));
260         SGPath objectsDir(dir.file("Objects"));
261         
262       // this code used to add *either* the base dir, OR add the 
263       // Terrain and Objects subdirs, but the conditional logic was commented
264       // out, such that all three dirs are added. Unfortunately there's
265       // no information as to why the change was made.
266         fg_scenery.push_back(abspath.str());
267         
268         if (terrainDir.exists()) {
269           fg_scenery.push_back(terrainDir.str());
270         }
271         
272         if (objectsDir.exists()) {
273           fg_scenery.push_back(objectsDir.str());
274         }
275         
276         // insert a marker for FGTileEntry::load(), so that
277         // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
278         // "B/Terrain", "B/Objects", ""]
279         fg_scenery.push_back("");
280         
281       // make scenery dirs available to Nasal
282         SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
283         n->setStringValue(abspath.str());
284         n->setAttribute(SGPropertyNode::WRITE, false);
285     } // of path list iteration
286 }
287
288 void FGGlobals::append_aircraft_path(const std::string& path)
289 {
290   SGPath dirPath(path);
291   if (!dirPath.exists()) {
292     SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
293     return;
294   }
295   std::string abspath = dirPath.realpath();
296   
297   unsigned int index = fg_aircraft_dirs.size();  
298   fg_aircraft_dirs.push_back(abspath);
299   
300 // make aircraft dirs available to Nasal
301   SGPropertyNode* sim = fgGetNode("/sim", true);
302   sim->removeChild("fg-aircraft", index, false);
303   SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
304   n->setStringValue(abspath);
305   n->setAttribute(SGPropertyNode::WRITE, false);
306 }
307
308 void FGGlobals::append_aircraft_paths(const std::string& path)
309 {
310   string_list paths = sgPathSplit(path);
311   for (unsigned int p = 0; p<paths.size(); ++p) {
312     append_aircraft_path(paths[p]);
313   }
314 }
315
316 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
317 {
318   return simgear::ResourceManager::instance()->findPath(branch);
319 }
320
321 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
322 {
323   return simgear::ResourceManager::instance()->findPath(branch);
324 }
325
326 SGPath FGGlobals::resolve_ressource_path(const std::string& branch) const
327 {
328   return simgear::ResourceManager::instance()
329     ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
330 }
331
332 FGRenderer *
333 FGGlobals::get_renderer () const
334 {
335    return renderer;
336 }
337
338 SGSubsystemMgr *
339 FGGlobals::get_subsystem_mgr () const
340 {
341     return subsystem_mgr;
342 }
343
344 SGSubsystem *
345 FGGlobals::get_subsystem (const char * name)
346 {
347     return subsystem_mgr->get_subsystem(name);
348 }
349
350 void
351 FGGlobals::add_subsystem (const char * name,
352                           SGSubsystem * subsystem,
353                           SGSubsystemMgr::GroupType type,
354                           double min_time_sec)
355 {
356     subsystem_mgr->add(name, subsystem, type, min_time_sec);
357 }
358
359 SGSoundMgr *
360 FGGlobals::get_soundmgr () const
361 {
362     if (subsystem_mgr)
363         return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
364
365     return NULL;
366 }
367
368 SGEventMgr *
369 FGGlobals::get_event_mgr () const
370 {
371     return event_mgr;
372 }
373
374 SGGeod
375 FGGlobals::get_aircraft_position() const
376 {
377   return SGGeod::fromDegFt(positionLon->getDoubleValue(),
378                            positionLat->getDoubleValue(),
379                            positionAlt->getDoubleValue());
380 }
381
382 SGVec3d
383 FGGlobals::get_aircraft_positon_cart() const
384 {
385     return SGVec3d::fromGeod(get_aircraft_position());
386 }
387
388 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
389 {
390   heading = orientHeading->getDoubleValue();
391   pitch = orientPitch->getDoubleValue();
392   roll = orientRoll->getDoubleValue();
393 }
394
395
396 // Save the current state as the initial state.
397 void
398 FGGlobals::saveInitialState ()
399 {
400   initial_state = new SGPropertyNode();
401
402   // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
403   int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
404                  SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
405   int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
406   if (!copyProperties(props, initial_state, expected, checked))
407     SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
408     
409   // delete various properties from the initial state, since we want to
410   // preserve their values even if doing a restore
411   // => Properties should now use the PRESERVE flag to protect their values
412   // on sim-reset. Remove some specific properties for backward compatibility.
413   SGPropertyNode* sim = initial_state->getChild("sim");
414   SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
415   if (cameraGroupNode) {
416     cameraGroupNode->removeChild("camera");
417     cameraGroupNode->removeChild("gui");
418   }
419 }
420
421
422 // Restore the saved initial state, if any
423 void
424 FGGlobals::restoreInitialState ()
425 {
426     if ( initial_state == 0 ) {
427         SG_LOG(SG_GENERAL, SG_ALERT,
428                "No initial state available to restore!!!");
429         return;
430     }
431     // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
432     int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
433                    SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
434     int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
435     if ( copyProperties(initial_state, props, expected, checked)) {
436         SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
437     } else {
438         SG_LOG( SG_GENERAL, SG_INFO,
439                 "Some errors restoring initial state (read-only props?)" );
440     }
441
442 }
443
444 // Load user settings from autosave.xml
445 void
446 FGGlobals::loadUserSettings(const SGPath& dataPath)
447 {
448     // remember that we have (tried) to load any existing autsave.xml
449     haveUserSettings = true;
450
451     SGPath autosaveFile = simgear::Dir(dataPath).file("autosave.xml");
452     SGPropertyNode autosave;
453     if (autosaveFile.exists()) {
454       SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
455       try {
456           readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
457       } catch (sg_exception& e) {
458           SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
459             << "(from " << e.getOrigin() << ")");
460       }
461     }
462     copyProperties(&autosave, globals->get_props());
463 }
464
465 // Save user settings in autosave.xml
466 void
467 FGGlobals::saveUserSettings()
468 {
469     // only save settings when we have (tried) to load the previous
470     // settings (otherwise user data was lost)
471     if (!haveUserSettings)
472         return;
473
474     if (fgGetBool("/sim/startup/save-on-exit")) {
475       // don't save settings more than once on shutdown
476       haveUserSettings = false;
477
478       SGPath autosaveFile(globals->get_fg_home());
479       autosaveFile.append( "autosave.xml" );
480       autosaveFile.create_dir( 0700 );
481       SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
482       try {
483         writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
484       } catch (const sg_exception &e) {
485         guiErrorMessage("Error writing autosave.xml: ", e);
486       }
487       SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
488     }
489 }
490
491 FGViewer *
492 FGGlobals::get_current_view () const
493 {
494   return viewmgr->get_current_view();
495 }
496
497 long int FGGlobals::get_warp() const
498 {
499   return fgGetInt("/sim/time/warp");
500 }
501
502 void FGGlobals::set_warp( long int w )
503 {
504   fgSetInt("/sim/time/warp", w);
505 }
506
507 long int FGGlobals::get_warp_delta() const
508 {
509   return fgGetInt("/sim/time/warp-delta");
510 }
511
512 void FGGlobals::set_warp_delta( long int d )
513 {
514   fgSetInt("/sim/time/warp-delta", d);
515 }
516
517 // end of globals.cxx