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>
57 #include <Model/panelnode.hxx>
58 #include <Scenery/scenery.hxx>
59 #include <Scenery/tilemgr.hxx>
60 #include <Sound/soundmanager.hxx>
61 #include <Time/TimeManager.hxx>
63 #include <Viewer/splash.hxx>
64 #include <Viewer/renderer.hxx>
65 #include <Viewer/WindowSystemAdapter.hxx>
66 #include <Navaids/NavDataCache.hxx>
67 #include <Include/version.h>
69 #include "fg_commands.hxx"
73 #include "fg_init.hxx"
75 #include "fg_props.hxx"
76 #include "positioninit.hxx"
77 #include "screensaver_control.hxx"
78 #include "subsystemFactory.hxx"
79 #include "options.hxx"
82 using namespace flightgear;
87 // The atexit() function handler should know when the graphical subsystem
89 extern int _bootstrap_OSInit;
91 static SGPropertyNode_ptr frame_signal;
92 static TimeManager* timeMgr;
94 // What should we do when we have nothing else to do? Let's get ready
95 // for the next move and update the display?
96 static void fgMainLoop( void )
98 frame_signal->fireValueChanged();
100 // compute simulated time (allowing for pause, warp, etc) and
102 double sim_dt, real_dt;
103 timeMgr->computeTimeDeltas(sim_dt, real_dt);
105 // update all subsystems
106 globals->get_subsystem_mgr()->update(sim_dt);
108 simgear::AtomicChangeListener::fireChangeListeners();
111 static void initTerrasync()
113 // add the terrasync root as a data path so data can be retrieved from it
114 // (even if we are in read-only mode)
115 std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
116 globals->append_data_path(terraSyncDir);
118 if (fgGetBool("/sim/fghome-readonly", false)) {
122 // start TerraSync up now, so it can be synchronizing shared models
123 // and airports data in parallel with a nav-cache rebuild.
124 SGPath tsyncCache(globals->get_fg_home());
125 tsyncCache.append("terrasync-cache.xml");
127 // wipe the cache file if requested
128 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
129 SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
131 if (tsyncCache.exists()) {
136 fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
138 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
139 terra_sync->setRoot(globals->get_props());
140 globals->add_subsystem("terrasync", terra_sync);
146 static void registerMainLoop()
148 // stash current frame signal property
149 frame_signal = fgGetNode("/sim/signals/frame", true);
150 timeMgr = (TimeManager*) globals->get_subsystem("time");
151 fgRegisterIdleHandler( fgMainLoop );
154 // This is the top level master main function that is registered as
157 // The first few passes take care of initialization things (a couple
158 // per pass) and once everything has been initialized fgMainLoop from
161 static int idle_state = 0;
163 static void fgIdleFunction ( void ) {
164 // Specify our current idle function state. This is used to run all
165 // our initializations out of the idle callback so that we can get a
166 // splash screen up and running right away.
168 if ( idle_state == 0 ) {
172 fgSplashProgress("loading-aircraft-list");
175 } else if ( idle_state == 2 ) {
178 fgSplashProgress("loading-nav-dat");
180 } else if ( idle_state == 3 ) {
182 bool done = fgInitNav();
185 fgSplashProgress("init-scenery");
187 fgSplashProgress("loading-nav-dat");
190 } else if ( idle_state == 4 ) {
193 TimeManager* t = new TimeManager;
194 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
196 // Do some quick general initializations
197 if( !fgInitGeneral()) {
198 throw sg_exception("General initialization failed");
201 ////////////////////////////////////////////////////////////////////
202 // Initialize the property-based built-in commands
203 ////////////////////////////////////////////////////////////////////
206 flightgear::registerSubsystemCommands(globals->get_commands());
208 ////////////////////////////////////////////////////////////////////
209 // Initialize the material manager
210 ////////////////////////////////////////////////////////////////////
211 globals->set_matlib( new SGMaterialLib );
212 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
214 } else if (( idle_state == 5 ) || (idle_state == 2005)) {
216 flightgear::initPosition();
217 flightgear::initTowerLocationListener();
219 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
221 TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
224 ////////////////////////////////////////////////////////////////////
225 // Initialize the TG scenery subsystem.
226 ////////////////////////////////////////////////////////////////////
228 globals->set_scenery( new FGScenery );
229 globals->get_scenery()->init();
230 globals->get_scenery()->bind();
231 globals->set_tile_mgr( new FGTileMgr );
233 fgSplashProgress("creating-subsystems");
234 } else if (( idle_state == 7 ) || (idle_state == 2007)) {
235 bool isReset = (idle_state == 2007);
236 idle_state = 8; // from the next state on, reset & startup are identical
239 fgCreateSubsystems(isReset);
240 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
241 fgSplashProgress("binding-subsystems");
243 } else if ( idle_state == 8 ) {
247 globals->get_subsystem_mgr()->bind();
248 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
250 fgSplashProgress("init-subsystems");
251 } else if ( idle_state == 9 ) {
252 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
253 if ( status == SGSubsystem::INIT_DONE) {
255 fgSplashProgress("finishing-subsystems");
257 fgSplashProgress("init-subsystems");
260 } else if ( idle_state == 10 ) {
262 fgPostInitSubsystems();
263 fgSplashProgress("finalize-position");
264 } else if ( idle_state == 900 ) {
267 // setup OpenGL view parameters
268 globals->get_renderer()->setupView();
270 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
271 fgGetInt("/sim/startup/ysize") );
272 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
273 new simgear::canvas::VGInitOperation()
276 int session = fgGetInt("/sim/session",0);
278 fgSetInt("/sim/session",session);
281 if ( idle_state == 1000 ) {
282 // We've finished all our initialization steps, from now on we
283 // run the main loop.
284 fgSetBool("sim/sceneryloaded", false);
288 if ( idle_state == 2000 ) {
294 void fgResetIdleState()
297 fgRegisterIdleHandler( &fgIdleFunction );
301 static void upper_case_property(const char *name)
303 using namespace simgear;
304 SGPropertyNode *p = fgGetNode(name, false);
306 p = fgGetNode(name, true);
307 p->setStringValue("");
309 props::Type t = p->getType();
310 if (t == props::NONE || t == props::UNSPECIFIED)
311 p->setStringValue("");
313 assert(t == props::STRING);
315 SGPropertyChangeListener* muc = new FGMakeUpperCase;
316 globals->addListenerToCleanup(muc);
317 p->addChangeListener(muc);
320 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
321 // for the details of this.
322 static void ATIScreenSizeHack()
324 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
325 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
326 int prettyMuchAnyInt = 1;
327 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
328 globals->get_renderer()->addCamera(hackCam, false);
331 // Propose NVIDIA Optimus to use high-end GPU
332 #if defined(SG_WINDOWS)
334 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
338 static void logToFile()
340 SGPath logPath = globals->get_fg_home();
341 logPath.append("fgfs.log");
342 if (logPath.exists()) {
343 SGPath prevLogPath = globals->get_fg_home();
344 prevLogPath.append("fgfs_0.log");
345 logPath.rename(prevLogPath);
346 // bit strange, we need to restore the correct value of logPath now
347 logPath = globals->get_fg_home();
348 logPath.append("fgfs.log");
350 sglog().logToFile(logPath, SG_ALL, SG_INFO);
352 #if defined(HAVE_CRASHRPT)
353 if (global_crashRptEnabled) {
354 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
355 SG_LOG( SG_GENERAL, SG_INFO, "CrashRpt enabled");
357 SG_LOG(SG_GENERAL, SG_WARN, "CrashRpt enabled at compile time but failed to install");
362 // Main top level initialization
363 int fgMainInit( int argc, char **argv ) {
365 // set default log levels
366 sglog().setLogLevels( SG_ALL, SG_ALERT );
368 globals = new FGGlobals;
373 if (!fgGetBool("/sim/fghome-readonly")) {
374 // now home is initialised, we can log to a file inside it
379 #ifdef FLIGHTGEAR_VERSION
380 version = FLIGHTGEAR_VERSION;
382 version = "unknown version";
384 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
386 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR);
387 SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << HUDSON_BUILD_NUMBER << ":"
390 // Allocate global data structures. This needs to happen before
391 // we parse command line options
395 // seed the random number generator
398 string_list *col = new string_list;
399 globals->set_channel_options_list( col );
401 fgValidatePath("", false); // initialize static variables
402 upper_case_property("/sim/presets/airport-id");
403 upper_case_property("/sim/presets/runway");
404 upper_case_property("/sim/tower/airport-id");
405 upper_case_property("/autopilot/route-manager/input");
407 // Load the configuration parameters. (Command line options
408 // override config file options. Config file options override
410 int configResult = fgInitConfig(argc, argv, false);
411 if (configResult == flightgear::FG_OPTIONS_ERROR) {
413 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
417 configResult = fgInitAircraft(false);
418 if (configResult == flightgear::FG_OPTIONS_ERROR) {
420 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
424 configResult = flightgear::Options::sharedInstance()->processOptions();
425 if (configResult == flightgear::FG_OPTIONS_ERROR) {
427 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
431 // Initialize the Window/Graphics environment.
432 fgOSInit(&argc, argv);
435 fgRegisterIdleHandler( &fgIdleFunction );
437 // Initialize sockets (WinSock needs this)
438 simgear::Socket::initSockets();
440 // Clouds3D requires an alpha channel
441 fgOSOpenWindow(true /* request stencil buffer */);
442 fgOSResetProperties();
444 // Initialize the splash screen right away
448 if (fgGetBool("/sim/ati-viewport-hack", true)) {
449 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
455 //try to disable the screensaver
456 fgOSDisableScreensaver();
458 // pass control off to the master event handler
459 int result = fgOSMainLoop();
460 frame_signal.clear();
463 simgear::clearEffectCache();
465 // clean up here; ensure we null globals to avoid
466 // confusing the atexit() handler
470 // delete the NavCache here. This will cause the destruction of many cached
471 // objects (eg, airports, navaids, runways).
472 delete flightgear::NavDataCache::instance();