]> git.mxchange.org Git - flightgear.git/blob - src/Main/globals.cxx
Support for multiple data dirs.
[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 class CurrentAircraftDirProvider : public simgear::ResourceProvider
110 {
111 public:
112   CurrentAircraftDirProvider() :
113     simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
114   {
115   }
116   
117   virtual SGPath resolve(const std::string& aResource, SGPath&) const
118   {
119     const char* aircraftDir = fgGetString("/sim/aircraft-dir");
120     SGPath p(aircraftDir);
121     p.append(aResource);
122     return p.exists() ? p : SGPath();
123   }
124 };
125
126 ////////////////////////////////////////////////////////////////////////
127 // Implementation of FGGlobals.
128 ////////////////////////////////////////////////////////////////////////
129
130 // global global :-)
131 FGGlobals *globals;
132
133
134 // Constructor
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 ),
142     sim_time_sec( 0.0 ),
143     fg_root( "" ),
144     fg_home( "" ),
145     time_params( NULL ),
146     ephem( NULL ),
147     matlib( NULL ),
148     route_mgr( NULL ),
149     ATIS_mgr( NULL ),
150     controls( NULL ),
151     viewmgr( NULL ),
152     commands( SGCommandMgr::instance() ),
153     channel_options_list( NULL ),
154     initial_waypoints( NULL ),
155     scenery( NULL ),
156     tile_mgr( NULL ),
157     fontcache ( new FGFontCache ),
158     channellist( NULL ),
159     haveUserSettings(false)
160 {
161   simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
162   simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
163   simgear::PropertyObjectBase::setDefaultRoot(props);
164   
165   positionLon = props->getNode("position/longitude-deg", true);
166   positionLat = props->getNode("position/latitude-deg", true);
167   positionAlt = props->getNode("position/altitude-ft", true);
168   
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);
172   
173   orientPitch = props->getNode("orientation/pitch-deg", true);
174   orientHeading = props->getNode("orientation/heading-deg", true);
175   orientRoll = props->getNode("orientation/roll-deg", true);
176 }
177
178 // Destructor
179 FGGlobals::~FGGlobals() 
180 {
181     // save user settings (unless already saved)
182     saveUserSettings();
183
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");
191     if (ai) {
192         ai->unbind();
193         delete ai;
194     }
195     SGSubsystem* sound = subsystem_mgr->remove("sound");
196
197     subsystem_mgr->shutdown();
198     subsystem_mgr->unbind();
199     delete subsystem_mgr;
200     
201     delete renderer;
202     renderer = NULL;
203     
204     delete time_params;
205     delete matlib;
206     delete route_mgr;
207
208     delete ATIS_mgr;
209
210     delete channel_options_list;
211     delete initial_waypoints;
212     delete scenery;
213     delete fontcache;
214
215     delete channellist;
216     delete sound;
217
218     delete locale;
219     locale = NULL;
220 }
221
222 // set the fg_root path
223 void FGGlobals::set_fg_root (const std::string &root) {
224     SGPath tmp(root);
225     fg_root = tmp.realpath();
226
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);
232         fg_root += "/data";
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***");
236     }
237
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);
244     
245     simgear::ResourceManager::instance()->addBasePath(fg_root, 
246       simgear::ResourceManager::PRIORITY_DEFAULT);
247 }
248
249 // set the fg_home path
250 void FGGlobals::set_fg_home (const std::string &home) {
251     SGPath tmp(home);
252     fg_home = tmp.realpath();
253 }
254
255 PathList FGGlobals::get_data_paths() const
256 {
257     PathList r(additional_data_paths);
258     r.push_back(SGPath(fg_root));
259     return r;
260 }
261
262 PathList FGGlobals::get_data_paths(const std::string& suffix) const
263 {
264     PathList r;
265     BOOST_FOREACH(SGPath p, get_data_paths()) {
266         p.append(suffix);
267         if (p.exists()) {
268             r.push_back(p);
269         }
270     }
271
272     return r;
273 }
274
275 void FGGlobals::append_data_path(const SGPath& path)
276 {
277     if (!path.exists()) {
278         SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
279     }
280     
281     additional_data_paths.push_back(path);
282 }
283
284 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
285 {
286     BOOST_FOREACH(SGPath p, additional_data_paths) {
287         p.append(pathSuffix);
288         if (p.exists()) {
289             return p;
290         }
291     }
292     
293     SGPath rootPath(fg_root);
294     rootPath.append(pathSuffix);
295     if (rootPath.exists()) {
296         return rootPath;
297     }
298     
299     SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
300     return SGPath();
301 }
302
303 void FGGlobals::append_fg_scenery (const std::string &paths)
304 {
305 //    fg_scenery.clear();
306     SGPropertyNode* sim = fgGetNode("/sim", true);
307
308   // find first unused fg-scenery property in /sim
309     int propIndex = 0;
310     while (sim->getChild("fg-scenery", propIndex) != NULL) {
311       ++propIndex; 
312     }
313   
314     BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
315         SGPath abspath(path.realpath());
316         if (!abspath.exists()) {
317           SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
318           continue;
319         }
320
321       // check for duplicates
322       string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
323       if (ex != fg_scenery.end()) {
324         SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
325         continue;
326       }
327       
328         simgear::Dir dir(abspath);
329         SGPath terrainDir(dir.file("Terrain"));
330         SGPath objectsDir(dir.file("Objects"));
331         
332       // this code used to add *either* the base dir, OR add the 
333       // Terrain and Objects subdirs, but the conditional logic was commented
334       // out, such that all three dirs are added. Unfortunately there's
335       // no information as to why the change was made.
336         fg_scenery.push_back(abspath.str());
337         
338         if (terrainDir.exists()) {
339           fg_scenery.push_back(terrainDir.str());
340         }
341         
342         if (objectsDir.exists()) {
343           fg_scenery.push_back(objectsDir.str());
344         }
345         
346         // insert a marker for FGTileEntry::load(), so that
347         // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
348         // "B/Terrain", "B/Objects", ""]
349         fg_scenery.push_back("");
350         
351       // make scenery dirs available to Nasal
352         SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
353         n->setStringValue(abspath.str());
354         n->setAttribute(SGPropertyNode::WRITE, false);
355     } // of path list iteration
356 }
357
358 void FGGlobals::append_aircraft_path(const std::string& path)
359 {
360   SGPath dirPath(path);
361   if (!dirPath.exists()) {
362     SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
363     return;
364   }
365   std::string abspath = dirPath.realpath();
366   
367   unsigned int index = fg_aircraft_dirs.size();  
368   fg_aircraft_dirs.push_back(abspath);
369   
370 // make aircraft dirs available to Nasal
371   SGPropertyNode* sim = fgGetNode("/sim", true);
372   sim->removeChild("fg-aircraft", index, false);
373   SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
374   n->setStringValue(abspath);
375   n->setAttribute(SGPropertyNode::WRITE, false);
376 }
377
378 void FGGlobals::append_aircraft_paths(const std::string& path)
379 {
380   string_list paths = sgPathSplit(path);
381   for (unsigned int p = 0; p<paths.size(); ++p) {
382     append_aircraft_path(paths[p]);
383   }
384 }
385
386 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
387 {
388   return simgear::ResourceManager::instance()->findPath(branch);
389 }
390
391 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
392 {
393   return simgear::ResourceManager::instance()->findPath(branch);
394 }
395
396 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
397 {
398   return simgear::ResourceManager::instance()
399     ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
400 }
401
402 FGRenderer *
403 FGGlobals::get_renderer () const
404 {
405    return renderer;
406 }
407
408 SGSubsystemMgr *
409 FGGlobals::get_subsystem_mgr () const
410 {
411     return subsystem_mgr;
412 }
413
414 SGSubsystem *
415 FGGlobals::get_subsystem (const char * name)
416 {
417     return subsystem_mgr->get_subsystem(name);
418 }
419
420 void
421 FGGlobals::add_subsystem (const char * name,
422                           SGSubsystem * subsystem,
423                           SGSubsystemMgr::GroupType type,
424                           double min_time_sec)
425 {
426     subsystem_mgr->add(name, subsystem, type, min_time_sec);
427 }
428
429 SGSoundMgr *
430 FGGlobals::get_soundmgr () const
431 {
432     if (subsystem_mgr)
433         return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
434
435     return NULL;
436 }
437
438 SGEventMgr *
439 FGGlobals::get_event_mgr () const
440 {
441     return event_mgr;
442 }
443
444 SGGeod
445 FGGlobals::get_aircraft_position() const
446 {
447   return SGGeod::fromDegFt(positionLon->getDoubleValue(),
448                            positionLat->getDoubleValue(),
449                            positionAlt->getDoubleValue());
450 }
451
452 SGVec3d
453 FGGlobals::get_aircraft_position_cart() const
454 {
455     return SGVec3d::fromGeod(get_aircraft_position());
456 }
457
458 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
459 {
460   heading = orientHeading->getDoubleValue();
461   pitch = orientPitch->getDoubleValue();
462   roll = orientRoll->getDoubleValue();
463 }
464
465 SGGeod
466 FGGlobals::get_view_position() const
467 {
468   return SGGeod::fromDegFt(viewLon->getDoubleValue(),
469                            viewLat->getDoubleValue(),
470                            viewAlt->getDoubleValue());
471 }
472
473 SGVec3d
474 FGGlobals::get_view_position_cart() const
475 {
476   return SGVec3d::fromGeod(get_view_position());
477 }
478
479 // Save the current state as the initial state.
480 void
481 FGGlobals::saveInitialState ()
482 {
483   initial_state = new SGPropertyNode();
484
485   // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
486   int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
487                  SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
488   int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
489   if (!copyProperties(props, initial_state, expected, checked))
490     SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
491     
492   // delete various properties from the initial state, since we want to
493   // preserve their values even if doing a restore
494   // => Properties should now use the PRESERVE flag to protect their values
495   // on sim-reset. Remove some specific properties for backward compatibility.
496   SGPropertyNode* sim = initial_state->getChild("sim");
497   SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
498   if (cameraGroupNode) {
499     cameraGroupNode->removeChild("camera");
500     cameraGroupNode->removeChild("gui");
501   }
502 }
503
504 static std::string autosaveName()
505 {
506     std::ostringstream os;
507     string_list versionParts = simgear::strutils::split(VERSION, ".");
508     if (versionParts.size() < 2) {
509         return "autosave.xml";
510     }
511     
512     os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
513     return os.str();
514 }
515
516 // Restore the saved initial state, if any
517 void
518 FGGlobals::restoreInitialState ()
519 {
520     if ( initial_state == 0 ) {
521         SG_LOG(SG_GENERAL, SG_ALERT,
522                "No initial state available to restore!!!");
523         return;
524     }
525     // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
526     int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
527                    SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
528     int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
529     if ( copyProperties(initial_state, props, expected, checked)) {
530         SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
531     } else {
532         SG_LOG( SG_GENERAL, SG_INFO,
533                 "Some errors restoring initial state (read-only props?)" );
534     }
535
536 }
537
538 // Load user settings from autosave.xml
539 void
540 FGGlobals::loadUserSettings(const SGPath& dataPath)
541 {
542     // remember that we have (tried) to load any existing autsave.xml
543     haveUserSettings = true;
544
545     SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
546     SGPropertyNode autosave;
547     if (autosaveFile.exists()) {
548       SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
549       try {
550           readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
551       } catch (sg_exception& e) {
552           SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
553             << "(from " << e.getOrigin() << ")");
554       }
555     }
556     copyProperties(&autosave, globals->get_props());
557 }
558
559 // Save user settings in autosave.xml
560 void
561 FGGlobals::saveUserSettings()
562 {
563     // only save settings when we have (tried) to load the previous
564     // settings (otherwise user data was lost)
565     if (!haveUserSettings)
566         return;
567
568     if (fgGetBool("/sim/startup/save-on-exit")) {
569       // don't save settings more than once on shutdown
570       haveUserSettings = false;
571
572       SGPath autosaveFile(globals->get_fg_home());
573       autosaveFile.append(autosaveName());
574       autosaveFile.create_dir( 0700 );
575       SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
576       try {
577         writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
578       } catch (const sg_exception &e) {
579         guiErrorMessage("Error writing autosave:", e);
580       }
581       SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
582     }
583 }
584
585 FGViewer *
586 FGGlobals::get_current_view () const
587 {
588   return viewmgr->get_current_view();
589 }
590
591 long int FGGlobals::get_warp() const
592 {
593   return fgGetInt("/sim/time/warp");
594 }
595
596 void FGGlobals::set_warp( long int w )
597 {
598   fgSetInt("/sim/time/warp", w);
599 }
600
601 long int FGGlobals::get_warp_delta() const
602 {
603   return fgGetInt("/sim/time/warp-delta");
604 }
605
606 void FGGlobals::set_warp_delta( long int d )
607 {
608   fgSetInt("/sim/time/warp-delta", d);
609 }
610
611 // end of globals.cxx