1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 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
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/compiler.h>
29 #include <simgear/props/props_io.hxx>
34 #include <osg/GraphicsContext>
35 #include <osgDB/Registry>
37 #if defined(HAVE_CRASHRPT)
40 // defined in bootstrap.cxx
41 extern bool global_crashRptEnabled;
46 #include <simgear/canvas/VGInitOperation.hxx>
47 #include <simgear/scene/model/modellib.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/scene/material/Effect.hxx>
50 #include <simgear/props/AtomicChangeListener.hxx>
51 #include <simgear/props/props.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/io/raw_socket.hxx>
54 #include <simgear/scene/tsync/terrasync.hxx>
55 #include <simgear/math/SGMath.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/misc/strutils.hxx>
58 #include <simgear/scene/tgdb/GroundLightManager.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Scenery/scenery.hxx>
62 #include <Scenery/tilemgr.hxx>
63 #include <Sound/soundmanager.hxx>
64 #include <Time/TimeManager.hxx>
66 #include <GUI/MessageBox.hxx>
67 #include <Viewer/splash.hxx>
68 #include <Viewer/renderer.hxx>
69 #include <Viewer/WindowSystemAdapter.hxx>
70 #include <Navaids/NavDataCache.hxx>
71 #include <Include/version.h>
73 #include "fg_commands.hxx"
77 #include "fg_init.hxx"
79 #include "fg_props.hxx"
80 #include "positioninit.hxx"
81 #include "screensaver_control.hxx"
82 #include "subsystemFactory.hxx"
83 #include "options.hxx"
86 #include <GUI/QtLauncher.hxx>
89 using namespace flightgear;
94 // The atexit() function handler should know when the graphical subsystem
96 extern int _bootstrap_OSInit;
98 static SGPropertyNode_ptr frame_signal;
99 static TimeManager* timeMgr;
101 // What should we do when we have nothing else to do? Let's get ready
102 // for the next move and update the display?
103 static void fgMainLoop( void )
105 frame_signal->fireValueChanged();
107 // compute simulated time (allowing for pause, warp, etc) and
109 double sim_dt, real_dt;
110 timeMgr->computeTimeDeltas(sim_dt, real_dt);
112 // update all subsystems
113 globals->get_subsystem_mgr()->update(sim_dt);
115 simgear::AtomicChangeListener::fireChangeListeners();
118 static void initTerrasync()
120 // add the terrasync root as a data path so data can be retrieved from it
121 // (even if we are in read-only mode)
122 std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
123 globals->append_data_path(terraSyncDir);
125 if (fgGetBool("/sim/fghome-readonly", false)) {
129 // start TerraSync up now, so it can be synchronizing shared models
130 // and airports data in parallel with a nav-cache rebuild.
131 SGPath tsyncCache(terraSyncDir);
132 tsyncCache.append("terrasync-cache.xml");
134 // wipe the cache file if requested
135 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
136 SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
138 if (tsyncCache.exists()) {
143 fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
145 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
146 terra_sync->setRoot(globals->get_props());
147 globals->add_subsystem("terrasync", terra_sync);
153 static void fgSetVideoOptions()
155 std::string vendor = fgGetString("/sim/rendering/gl-vendor");
156 SGPath path(globals->get_fg_root());
157 path.append("Video");
161 std::string renderer = fgGetString("/sim/rendering/gl-renderer");
162 size_t pos = renderer.find("x86/");
163 if (pos == std::string::npos) {
164 pos = renderer.find('/');
166 if (pos == std::string::npos) {
167 pos = renderer.find(" (");
169 if (pos != std::string::npos) {
170 renderer = renderer.substr(0, pos);
172 path.append(renderer+".xml");
174 SG_LOG(SG_INPUT, SG_INFO, "Reading video settings from " << path.str());
176 SGPropertyNode *r_prop = fgGetNode("/sim/rendering");
177 readProperties(path.str(), r_prop);
178 } catch (sg_exception& e) {
179 SG_LOG(SG_INPUT, SG_WARN, "failed to read video settings:" << e.getMessage()
180 << "(from " << e.getOrigin() << ")");
183 flightgear::Options* options = flightgear::Options::sharedInstance();
184 if (!options->isOptionSet("ignore-autosave"))
186 SGPath dataPath = globals->get_fg_home();
187 globals->loadUserSettings(dataPath);
193 static void checkOpenGLVersion()
196 // Mac users can't upgrade their drivers, so complaining about
197 // versions doesn't help them much
201 // format of these strings is not standardised, so be careful about
203 std::string versionString(fgGetString("/sim/rendering/gl-version"));
204 string_list parts = simgear::strutils::split(versionString);
205 if (parts.size() == 3) {
206 if (parts[1].find("NVIDIA") != std::string::npos) {
207 // driver version number, dot-seperared
208 string_list driverVersion = simgear::strutils::split(parts[2], ".");
209 if (!driverVersion.empty()) {
210 int majorDriverVersion = simgear::strutils::to_int(driverVersion[0]);
211 if (majorDriverVersion < 300) {
212 std::ostringstream ss;
213 ss << "Please upgrade to at least version 300 of the nVidia drivers (installed version is " << parts[2] << ")";
215 flightgear::modalMessageBox("Outdated graphics drivers",
216 "FlightGear has detected outdated drivers for your graphics card.",
220 } // of NVIDIA-style version string
224 static void registerMainLoop()
226 // stash current frame signal property
227 frame_signal = fgGetNode("/sim/signals/frame", true);
228 timeMgr = (TimeManager*) globals->get_subsystem("time");
229 fgRegisterIdleHandler( fgMainLoop );
232 // This is the top level master main function that is registered as
235 // The first few passes take care of initialization things (a couple
236 // per pass) and once everything has been initialized fgMainLoop from
239 static int idle_state = 0;
241 static void fgIdleFunction ( void ) {
242 // Specify our current idle function state. This is used to run all
243 // our initializations out of the idle callback so that we can get a
244 // splash screen up and running right away.
246 if ( idle_state == 0 ) {
249 checkOpenGLVersion();
252 fgSplashProgress("loading-aircraft-list");
255 } else if ( idle_state == 2 ) {
258 fgSplashProgress("loading-nav-dat");
260 } else if ( idle_state == 3 ) {
262 bool done = fgInitNav();
265 fgSplashProgress("init-scenery");
267 } else if ( idle_state == 4 ) {
270 TimeManager* t = new TimeManager;
271 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
273 // Do some quick general initializations
274 if( !fgInitGeneral()) {
275 throw sg_exception("General initialization failed");
278 ////////////////////////////////////////////////////////////////////
279 // Initialize the property-based built-in commands
280 ////////////////////////////////////////////////////////////////////
283 flightgear::registerSubsystemCommands(globals->get_commands());
285 ////////////////////////////////////////////////////////////////////
286 // Initialize the material manager
287 ////////////////////////////////////////////////////////////////////
288 globals->set_matlib( new SGMaterialLib );
289 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
291 } else if (( idle_state == 5 ) || (idle_state == 2005)) {
293 flightgear::initPosition();
294 flightgear::initTowerLocationListener();
296 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
298 TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
301 ////////////////////////////////////////////////////////////////////
302 // Initialize the TG scenery subsystem.
303 ////////////////////////////////////////////////////////////////////
305 globals->add_new_subsystem<FGScenery>(SGSubsystemMgr::DISPLAY);
306 globals->get_scenery()->init();
307 globals->get_scenery()->bind();
308 globals->add_new_subsystem<FGTileMgr>(SGSubsystemMgr::DISPLAY);
310 fgSplashProgress("creating-subsystems");
311 } else if (( idle_state == 7 ) || (idle_state == 2007)) {
312 bool isReset = (idle_state == 2007);
313 idle_state = 8; // from the next state on, reset & startup are identical
316 fgCreateSubsystems(isReset);
317 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
318 fgSplashProgress("binding-subsystems");
320 } else if ( idle_state == 8 ) {
324 globals->get_subsystem_mgr()->bind();
325 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
327 fgSplashProgress("init-subsystems");
328 } else if ( idle_state == 9 ) {
329 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
330 if ( status == SGSubsystem::INIT_DONE) {
332 fgSplashProgress("finishing-subsystems");
334 fgSplashProgress("init-subsystems");
337 } else if ( idle_state == 10 ) {
339 fgPostInitSubsystems();
340 fgSplashProgress("finalize-position");
341 } else if ( idle_state == 900 ) {
344 // setup OpenGL view parameters
345 globals->get_renderer()->setupView();
347 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
348 fgGetInt("/sim/startup/ysize") );
349 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
350 new simgear::canvas::VGInitOperation()
353 int session = fgGetInt("/sim/session",0);
355 fgSetInt("/sim/session",session);
358 if ( idle_state == 1000 ) {
359 // We've finished all our initialization steps, from now on we
360 // run the main loop.
361 fgSetBool("sim/sceneryloaded", false);
365 if ( idle_state == 2000 ) {
371 void fgResetIdleState()
374 fgRegisterIdleHandler( &fgIdleFunction );
378 static void upper_case_property(const char *name)
380 using namespace simgear;
381 SGPropertyNode *p = fgGetNode(name, false);
383 p = fgGetNode(name, true);
384 p->setStringValue("");
386 props::Type t = p->getType();
387 if (t == props::NONE || t == props::UNSPECIFIED)
388 p->setStringValue("");
390 assert(t == props::STRING);
392 SGPropertyChangeListener* muc = new FGMakeUpperCase;
393 globals->addListenerToCleanup(muc);
394 p->addChangeListener(muc);
397 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
398 // for the details of this.
399 static void ATIScreenSizeHack()
401 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
402 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
403 int prettyMuchAnyInt = 1;
404 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
405 globals->get_renderer()->addCamera(hackCam, false);
408 // Propose NVIDIA Optimus to use high-end GPU
409 #if defined(SG_WINDOWS)
411 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
415 static void logToFile()
417 SGPath logPath = globals->get_fg_home();
418 logPath.append("fgfs.log");
419 if (logPath.exists()) {
420 SGPath prevLogPath = globals->get_fg_home();
421 prevLogPath.append("fgfs_0.log");
422 logPath.rename(prevLogPath);
423 // bit strange, we need to restore the correct value of logPath now
424 logPath = globals->get_fg_home();
425 logPath.append("fgfs.log");
427 sglog().logToFile(logPath, SG_ALL, SG_INFO);
429 #if defined(HAVE_CRASHRPT)
430 if (global_crashRptEnabled) {
431 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
432 SG_LOG( SG_GENERAL, SG_INFO, "CrashRpt enabled");
434 SG_LOG(SG_GENERAL, SG_WARN, "CrashRpt enabled at compile time but failed to install");
439 // Main top level initialization
440 int fgMainInit( int argc, char **argv )
442 // set default log levels
443 sglog().setLogLevels( SG_ALL, SG_ALERT );
445 globals = new FGGlobals;
450 if (!fgGetBool("/sim/fghome-readonly")) {
451 // now home is initialised, we can log to a file inside it
455 std::string version(FLIGHTGEAR_VERSION);
456 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
458 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR);
459 SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << HUDSON_BUILD_NUMBER << ":"
462 // seed the random number generator
465 string_list *col = new string_list;
466 globals->set_channel_options_list( col );
468 fgValidatePath(globals->get_fg_home(), false); // initialize static variables
469 upper_case_property("/sim/presets/airport-id");
470 upper_case_property("/sim/presets/runway");
471 upper_case_property("/sim/tower/airport-id");
472 upper_case_property("/autopilot/route-manager/input");
474 // Load the configuration parameters. (Command line options
475 // override config file options. Config file options override
477 int configResult = fgInitConfig(argc, argv, false);
478 if (configResult == flightgear::FG_OPTIONS_ERROR) {
480 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
485 bool showLauncher = flightgear::Options::checkForArg(argc, argv, "launcher");
486 // an Info.plist bundle can't define command line arguments, but it can set
487 // environment variables. This avoids needed a wrapper shell-script on OS-X.
488 showLauncher |= (::getenv("FG_LAUNCHER") != 0);
491 flightgear::initApp(argc, argv);
492 if (!flightgear::runLauncherDialog()) {
497 fgInitAircraftPaths(false);
499 configResult = fgInitAircraft(false);
500 if (configResult == flightgear::FG_OPTIONS_ERROR) {
502 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
506 configResult = flightgear::Options::sharedInstance()->processOptions();
507 if (configResult == flightgear::FG_OPTIONS_ERROR) {
509 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
513 // Initialize the Window/Graphics environment.
514 fgOSInit(&argc, argv);
517 fgRegisterIdleHandler( &fgIdleFunction );
519 // Initialize sockets (WinSock needs this)
520 simgear::Socket::initSockets();
522 // Clouds3D requires an alpha channel
523 fgOSOpenWindow(true /* request stencil buffer */);
524 fgOSResetProperties();
526 // Initialize the splash screen right away
530 if (fgGetBool("/sim/ati-viewport-hack", true)) {
531 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
537 //try to disable the screensaver
538 fgOSDisableScreensaver();
540 // pass control off to the master event handler
541 int result = fgOSMainLoop();
542 frame_signal.clear();
545 simgear::clearEffectCache();
547 // clean up here; ensure we null globals to avoid
548 // confusing the atexit() handler
552 // delete the NavCache here. This will cause the destruction of many cached
553 // objects (eg, airports, navaids, runways).
554 delete flightgear::NavDataCache::instance();
555 simgear::GroundLightManager::instance()->getRunwayLightStateSet()->clear();
556 simgear::GroundLightManager::instance()->getTaxiLightStateSet()->clear();
557 simgear::GroundLightManager::instance()->getGroundLightStateSet()->clear();