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)
41 #include <simgear/canvas/VGInitOperation.hxx>
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/scene/material/Effect.hxx>
45 #include <simgear/props/AtomicChangeListener.hxx>
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/io/raw_socket.hxx>
49 #include <simgear/scene/tsync/terrasync.hxx>
50 #include <simgear/math/SGMath.hxx>
51 #include <simgear/math/sg_random.h>
53 #include <Model/panelnode.hxx>
54 #include <Scenery/scenery.hxx>
55 #include <Scenery/tilemgr.hxx>
56 #include <Sound/soundmanager.hxx>
57 #include <Time/TimeManager.hxx>
59 #include <Viewer/splash.hxx>
60 #include <Viewer/renderer.hxx>
61 #include <Viewer/WindowSystemAdapter.hxx>
62 #include <Navaids/NavDataCache.hxx>
64 #include "fg_commands.hxx"
68 #include "fg_init.hxx"
70 #include "fg_props.hxx"
71 #include "positioninit.hxx"
72 #include "screensaver_control.hxx"
73 #include "subsystemFactory.hxx"
74 #include "options.hxx"
77 using namespace flightgear;
82 // The atexit() function handler should know when the graphical subsystem
84 extern int _bootstrap_OSInit;
86 static SGPropertyNode_ptr frame_signal;
87 static TimeManager* timeMgr;
89 // What should we do when we have nothing else to do? Let's get ready
90 // for the next move and update the display?
91 static void fgMainLoop( void )
93 frame_signal->fireValueChanged();
95 // compute simulated time (allowing for pause, warp, etc) and
97 double sim_dt, real_dt;
98 timeMgr->computeTimeDeltas(sim_dt, real_dt);
100 // update all subsystems
101 globals->get_subsystem_mgr()->update(sim_dt);
103 simgear::AtomicChangeListener::fireChangeListeners();
106 static void initTerrasync()
108 // add the terrasync root as a data path so data can be retrieved from it
109 // (even if we are in read-only mode)
110 std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
111 globals->append_data_path(terraSyncDir);
113 if (fgGetBool("/sim/fghome-readonly", false)) {
117 // start TerraSync up now, so it can be synchronizing shared models
118 // and airports data in parallel with a nav-cache rebuild.
119 SGPath tsyncCache(globals->get_fg_home());
120 tsyncCache.append("terrasync-cache.xml");
122 // wipe the cache file if requested
123 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
124 SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
126 if (tsyncCache.exists()) {
131 fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
133 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
134 terra_sync->setRoot(globals->get_props());
135 globals->add_subsystem("terrasync", terra_sync);
141 static void registerMainLoop()
143 // stash current frame signal property
144 frame_signal = fgGetNode("/sim/signals/frame", true);
145 timeMgr = (TimeManager*) globals->get_subsystem("time");
146 fgRegisterIdleHandler( fgMainLoop );
149 // This is the top level master main function that is registered as
152 // The first few passes take care of initialization things (a couple
153 // per pass) and once everything has been initialized fgMainLoop from
156 static int idle_state = 0;
158 static void fgIdleFunction ( void ) {
159 // Specify our current idle function state. This is used to run all
160 // our initializations out of the idle callback so that we can get a
161 // splash screen up and running right away.
163 if ( idle_state == 0 ) {
167 fgSplashProgress("loading-aircraft-list");
170 } else if ( idle_state == 2 ) {
173 fgSplashProgress("loading-nav-dat");
175 } else if ( idle_state == 3 ) {
177 bool done = fgInitNav();
180 fgSplashProgress("init-scenery");
182 fgSplashProgress("loading-nav-dat");
185 } else if ( idle_state == 4 ) {
188 TimeManager* t = new TimeManager;
189 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
191 // Do some quick general initializations
192 if( !fgInitGeneral()) {
193 throw sg_exception("General initialization failed");
196 ////////////////////////////////////////////////////////////////////
197 // Initialize the property-based built-in commands
198 ////////////////////////////////////////////////////////////////////
201 flightgear::registerSubsystemCommands(globals->get_commands());
203 ////////////////////////////////////////////////////////////////////
204 // Initialize the material manager
205 ////////////////////////////////////////////////////////////////////
206 globals->set_matlib( new SGMaterialLib );
207 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
209 } else if (( idle_state == 5 ) || (idle_state == 2005)) {
211 flightgear::initPosition();
212 flightgear::initTowerLocationListener();
214 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
216 TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
219 ////////////////////////////////////////////////////////////////////
220 // Initialize the TG scenery subsystem.
221 ////////////////////////////////////////////////////////////////////
223 globals->set_scenery( new FGScenery );
224 globals->get_scenery()->init();
225 globals->get_scenery()->bind();
226 globals->set_tile_mgr( new FGTileMgr );
228 fgSplashProgress("creating-subsystems");
229 } else if (( idle_state == 7 ) || (idle_state == 2007)) {
230 bool isReset = (idle_state == 2007);
231 idle_state = 8; // from the next state on, reset & startup are identical
234 fgCreateSubsystems(isReset);
235 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
236 fgSplashProgress("binding-subsystems");
238 } else if ( idle_state == 8 ) {
242 globals->get_subsystem_mgr()->bind();
243 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
245 fgSplashProgress("init-subsystems");
246 } else if ( idle_state == 9 ) {
247 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
248 if ( status == SGSubsystem::INIT_DONE) {
250 fgSplashProgress("finishing-subsystems");
252 fgSplashProgress("init-subsystems");
255 } else if ( idle_state == 10 ) {
257 fgPostInitSubsystems();
258 fgSplashProgress("finalize-position");
259 } else if ( idle_state == 900 ) {
262 // setup OpenGL view parameters
263 globals->get_renderer()->setupView();
265 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
266 fgGetInt("/sim/startup/ysize") );
267 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
268 new simgear::canvas::VGInitOperation()
271 int session = fgGetInt("/sim/session",0);
273 fgSetInt("/sim/session",session);
276 if ( idle_state == 1000 ) {
277 // We've finished all our initialization steps, from now on we
278 // run the main loop.
279 fgSetBool("sim/sceneryloaded", false);
283 if ( idle_state == 2000 ) {
289 void fgResetIdleState()
292 fgRegisterIdleHandler( &fgIdleFunction );
296 static void upper_case_property(const char *name)
298 using namespace simgear;
299 SGPropertyNode *p = fgGetNode(name, false);
301 p = fgGetNode(name, true);
302 p->setStringValue("");
304 props::Type t = p->getType();
305 if (t == props::NONE || t == props::UNSPECIFIED)
306 p->setStringValue("");
308 assert(t == props::STRING);
310 SGPropertyChangeListener* muc = new FGMakeUpperCase;
311 globals->addListenerToCleanup(muc);
312 p->addChangeListener(muc);
315 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
316 // for the details of this.
317 static void ATIScreenSizeHack()
319 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
320 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
321 int prettyMuchAnyInt = 1;
322 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
323 globals->get_renderer()->addCamera(hackCam, false);
326 // Propose NVIDIA Optimus to use high-end GPU
327 #if defined(SG_WINDOWS)
329 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
333 static void logToFile()
335 SGPath logPath = globals->get_fg_home();
336 logPath.append("fgfs.log");
337 if (logPath.exists()) {
338 SGPath prevLogPath = globals->get_fg_home();
339 prevLogPath.append("fgfs_0.log");
340 logPath.rename(prevLogPath);
341 // bit strange, we need to restore the correct value of logPath now
342 logPath = globals->get_fg_home();
343 logPath.append("fgfs.log");
345 sglog().logToFile(logPath, SG_ALL, SG_INFO);
347 #if defined(HAVE_CRASHRPT)
348 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
352 // Main top level initialization
353 int fgMainInit( int argc, char **argv ) {
355 // set default log levels
356 sglog().setLogLevels( SG_ALL, SG_ALERT );
358 globals = new FGGlobals;
363 if (!fgGetBool("/sim/fghome-readonly")) {
364 // now home is initialised, we can log to a file inside it
369 #ifdef FLIGHTGEAR_VERSION
370 version = FLIGHTGEAR_VERSION;
372 version = "unknown version";
374 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
376 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
378 // Allocate global data structures. This needs to happen before
379 // we parse command line options
383 // seed the random number generator
386 string_list *col = new string_list;
387 globals->set_channel_options_list( col );
389 fgValidatePath("", false); // initialize static variables
390 upper_case_property("/sim/presets/airport-id");
391 upper_case_property("/sim/presets/runway");
392 upper_case_property("/sim/tower/airport-id");
393 upper_case_property("/autopilot/route-manager/input");
395 // Load the configuration parameters. (Command line options
396 // override config file options. Config file options override
398 int configResult = fgInitConfig(argc, argv, false);
399 if (configResult == flightgear::FG_OPTIONS_ERROR) {
401 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
405 configResult = fgInitAircraft(false);
406 if (configResult == flightgear::FG_OPTIONS_ERROR) {
408 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
412 configResult = flightgear::Options::sharedInstance()->processOptions();
413 if (configResult == flightgear::FG_OPTIONS_ERROR) {
415 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
419 // Initialize the Window/Graphics environment.
420 fgOSInit(&argc, argv);
423 fgRegisterIdleHandler( &fgIdleFunction );
425 // Initialize sockets (WinSock needs this)
426 simgear::Socket::initSockets();
428 // Clouds3D requires an alpha channel
429 fgOSOpenWindow(true /* request stencil buffer */);
430 fgOSResetProperties();
432 // Initialize the splash screen right away
436 if (fgGetBool("/sim/ati-viewport-hack", true)) {
437 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
443 //try to disable the screensaver
444 fgOSDisableScreensaver();
446 // pass control off to the master event handler
447 int result = fgOSMainLoop();
448 frame_signal.clear();
451 simgear::clearEffectCache();
453 // clean up here; ensure we null globals to avoid
454 // confusing the atexit() handler
458 // delete the NavCache here. This will cause the destruction of many cached
459 // objects (eg, airports, navaids, runways).
460 delete flightgear::NavDataCache::instance();