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>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
36 #if defined(HAVE_CRASHRPT)
39 // defined in bootstrap.cxx
40 extern bool global_crashRptEnabled;
45 #include <simgear/canvas/VGInitOperation.hxx>
46 #include <simgear/scene/model/modellib.hxx>
47 #include <simgear/scene/material/matlib.hxx>
48 #include <simgear/scene/material/Effect.hxx>
49 #include <simgear/props/AtomicChangeListener.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/io/raw_socket.hxx>
53 #include <simgear/scene/tsync/terrasync.hxx>
54 #include <simgear/math/SGMath.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/misc/strutils.hxx>
58 #include <Model/panelnode.hxx>
59 #include <Scenery/scenery.hxx>
60 #include <Scenery/tilemgr.hxx>
61 #include <Sound/soundmanager.hxx>
62 #include <Time/TimeManager.hxx>
64 #include <GUI/MessageBox.hxx>
65 #include <Viewer/splash.hxx>
66 #include <Viewer/renderer.hxx>
67 #include <Viewer/WindowSystemAdapter.hxx>
68 #include <Navaids/NavDataCache.hxx>
69 #include <Include/version.h>
70 #include <Viewer/WindowBuilder.hxx>
72 #include "fg_commands.hxx"
76 #include "fg_init.hxx"
78 #include "fg_props.hxx"
79 #include "positioninit.hxx"
80 #include "screensaver_control.hxx"
81 #include "subsystemFactory.hxx"
82 #include "options.hxx"
85 #include <QApplication>
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(globals->get_fg_home());
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 checkOpenGLVersion()
156 // Mac users can't upgrade their drivers, so complaining about
157 // versions doesn't help them much
161 // format of these strings is not standardised, so be careful about
163 std::string versionString(fgGetString("/sim/rendering/gl-version"));
164 string_list parts = simgear::strutils::split(versionString);
165 if (parts.size() == 3) {
166 if (parts[1].find("NVIDIA") != std::string::npos) {
167 // driver version number, dot-seperared
168 string_list driverVersion = simgear::strutils::split(parts[2], ".");
169 if (!driverVersion.empty()) {
170 int majorDriverVersion = simgear::strutils::to_int(driverVersion[0]);
171 if (majorDriverVersion < 300) {
172 std::ostringstream ss;
173 ss << "Please upgrade to at least version 300 of the nVidia drivers (installed version is " << parts[2] << ")";
175 flightgear::modalMessageBox("Outdated graphics drivers",
176 "FlightGear has detected outdated drivers for your graphics card.",
180 } // of NVIDIA-style version string
184 static void registerMainLoop()
186 // stash current frame signal property
187 frame_signal = fgGetNode("/sim/signals/frame", true);
188 timeMgr = (TimeManager*) globals->get_subsystem("time");
189 fgRegisterIdleHandler( fgMainLoop );
192 // This is the top level master main function that is registered as
195 // The first few passes take care of initialization things (a couple
196 // per pass) and once everything has been initialized fgMainLoop from
199 static int idle_state = 0;
201 static void fgIdleFunction ( void ) {
202 // Specify our current idle function state. This is used to run all
203 // our initializations out of the idle callback so that we can get a
204 // splash screen up and running right away.
206 if ( idle_state == 0 ) {
209 checkOpenGLVersion();
211 fgSplashProgress("loading-aircraft-list");
214 } else if ( idle_state == 2 ) {
217 fgSplashProgress("loading-nav-dat");
219 } else if ( idle_state == 3 ) {
221 bool done = fgInitNav();
224 fgSplashProgress("init-scenery");
226 fgSplashProgress("loading-nav-dat");
229 } else if ( idle_state == 4 ) {
232 TimeManager* t = new TimeManager;
233 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
235 // Do some quick general initializations
236 if( !fgInitGeneral()) {
237 throw sg_exception("General initialization failed");
240 ////////////////////////////////////////////////////////////////////
241 // Initialize the property-based built-in commands
242 ////////////////////////////////////////////////////////////////////
245 flightgear::registerSubsystemCommands(globals->get_commands());
247 ////////////////////////////////////////////////////////////////////
248 // Initialize the material manager
249 ////////////////////////////////////////////////////////////////////
250 globals->set_matlib( new SGMaterialLib );
251 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
253 } else if (( idle_state == 5 ) || (idle_state == 2005)) {
255 flightgear::initPosition();
256 flightgear::initTowerLocationListener();
258 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
260 TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
263 ////////////////////////////////////////////////////////////////////
264 // Initialize the TG scenery subsystem.
265 ////////////////////////////////////////////////////////////////////
267 globals->set_scenery( new FGScenery );
268 globals->get_scenery()->init();
269 globals->get_scenery()->bind();
270 globals->set_tile_mgr( new FGTileMgr );
272 fgSplashProgress("creating-subsystems");
273 } else if (( idle_state == 7 ) || (idle_state == 2007)) {
274 bool isReset = (idle_state == 2007);
275 idle_state = 8; // from the next state on, reset & startup are identical
278 fgCreateSubsystems(isReset);
279 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
280 fgSplashProgress("binding-subsystems");
282 } else if ( idle_state == 8 ) {
286 globals->get_subsystem_mgr()->bind();
287 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
289 fgSplashProgress("init-subsystems");
290 } else if ( idle_state == 9 ) {
291 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
292 if ( status == SGSubsystem::INIT_DONE) {
294 fgSplashProgress("finishing-subsystems");
296 fgSplashProgress("init-subsystems");
299 } else if ( idle_state == 10 ) {
301 fgPostInitSubsystems();
302 fgSplashProgress("finalize-position");
303 } else if ( idle_state == 900 ) {
306 // setup OpenGL view parameters
307 globals->get_renderer()->setupView();
309 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
310 fgGetInt("/sim/startup/ysize") );
311 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
312 new simgear::canvas::VGInitOperation()
315 int session = fgGetInt("/sim/session",0);
317 fgSetInt("/sim/session",session);
320 if ( idle_state == 1000 ) {
321 // We've finished all our initialization steps, from now on we
322 // run the main loop.
323 fgSetBool("sim/sceneryloaded", false);
327 if ( idle_state == 2000 ) {
333 void fgResetIdleState()
336 fgRegisterIdleHandler( &fgIdleFunction );
340 static void upper_case_property(const char *name)
342 using namespace simgear;
343 SGPropertyNode *p = fgGetNode(name, false);
345 p = fgGetNode(name, true);
346 p->setStringValue("");
348 props::Type t = p->getType();
349 if (t == props::NONE || t == props::UNSPECIFIED)
350 p->setStringValue("");
352 assert(t == props::STRING);
354 SGPropertyChangeListener* muc = new FGMakeUpperCase;
355 globals->addListenerToCleanup(muc);
356 p->addChangeListener(muc);
359 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
360 // for the details of this.
361 static void ATIScreenSizeHack()
363 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
364 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
365 int prettyMuchAnyInt = 1;
366 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
367 globals->get_renderer()->addCamera(hackCam, false);
370 // Propose NVIDIA Optimus to use high-end GPU
371 #if defined(SG_WINDOWS)
373 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
377 static void logToFile()
379 SGPath logPath = globals->get_fg_home();
380 logPath.append("fgfs.log");
381 if (logPath.exists()) {
382 SGPath prevLogPath = globals->get_fg_home();
383 prevLogPath.append("fgfs_0.log");
384 logPath.rename(prevLogPath);
385 // bit strange, we need to restore the correct value of logPath now
386 logPath = globals->get_fg_home();
387 logPath.append("fgfs.log");
389 sglog().logToFile(logPath, SG_ALL, SG_INFO);
391 #if defined(HAVE_CRASHRPT)
392 if (global_crashRptEnabled) {
393 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
394 SG_LOG( SG_GENERAL, SG_INFO, "CrashRpt enabled");
396 SG_LOG(SG_GENERAL, SG_WARN, "CrashRpt enabled at compile time but failed to install");
401 // Main top level initialization
402 int fgMainInit( int argc, char **argv )
405 QApplication app(argc, argv);
406 app.setOrganizationName("FlightGear");
407 app.setApplicationName("FlightGear");
408 app.setOrganizationDomain("flightgear.org");
411 // set default log levels
412 sglog().setLogLevels( SG_ALL, SG_ALERT );
414 globals = new FGGlobals;
419 if (!fgGetBool("/sim/fghome-readonly")) {
420 // now home is initialised, we can log to a file inside it
425 #ifdef FLIGHTGEAR_VERSION
426 version = FLIGHTGEAR_VERSION;
428 version = "unknown version";
430 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
432 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR);
433 SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << HUDSON_BUILD_NUMBER << ":"
436 // seed the random number generator
439 string_list *col = new string_list;
440 globals->set_channel_options_list( col );
442 fgValidatePath("", false); // initialize static variables
443 upper_case_property("/sim/presets/airport-id");
444 upper_case_property("/sim/presets/runway");
445 upper_case_property("/sim/tower/airport-id");
446 upper_case_property("/autopilot/route-manager/input");
448 // Load the configuration parameters. (Command line options
449 // override config file options. Config file options override
451 int configResult = fgInitConfig(argc, argv, false);
452 if (configResult == flightgear::FG_OPTIONS_ERROR) {
454 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
458 // launcher needs to know the aircraft paths in use
459 fgInitAircraftPaths(false);
462 bool showLauncher = flightgear::Options::checkForArg(argc, argv, "launcher");
463 // an Info.plist bundle can't define command line arguments, but it can set
464 // environment variables. This avoids needed a wrapper shell-script on OS-X.
465 showLauncher |= (::getenv("FG_LAUNCHER") != 0);
468 // avoid double Apple menu and other weirdness if both Qt and OSG
469 // try to initialise various Cocoa structures.
470 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
472 if (!QtLauncher::runLauncherDialog()) {
478 configResult = fgInitAircraft(false);
479 if (configResult == flightgear::FG_OPTIONS_ERROR) {
481 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
485 configResult = flightgear::Options::sharedInstance()->processOptions();
486 if (configResult == flightgear::FG_OPTIONS_ERROR) {
488 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
492 // Initialize the Window/Graphics environment.
493 fgOSInit(&argc, argv);
496 fgRegisterIdleHandler( &fgIdleFunction );
498 // Initialize sockets (WinSock needs this)
499 simgear::Socket::initSockets();
501 // Clouds3D requires an alpha channel
502 fgOSOpenWindow(true /* request stencil buffer */);
503 fgOSResetProperties();
505 // Initialize the splash screen right away
509 if (fgGetBool("/sim/ati-viewport-hack", true)) {
510 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
516 //try to disable the screensaver
517 fgOSDisableScreensaver();
519 // pass control off to the master event handler
520 int result = fgOSMainLoop();
521 frame_signal.clear();
524 simgear::clearEffectCache();
526 // clean up here; ensure we null globals to avoid
527 // confusing the atexit() handler
531 // delete the NavCache here. This will cause the destruction of many cached
532 // objects (eg, airports, navaids, runways).
533 delete flightgear::NavDataCache::instance();