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>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/props/AtomicChangeListener.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/timing/sg_time.hxx>
47 #include <simgear/magvar/magvar.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 <Aircraft/controls.hxx>
54 #include <Model/panelnode.hxx>
55 #include <Scenery/scenery.hxx>
56 #include <Scenery/tilemgr.hxx>
57 #include <Sound/soundmanager.hxx>
58 #include <Time/TimeManager.hxx>
60 #include <Viewer/CameraGroup.hxx>
61 #include <Viewer/WindowSystemAdapter.hxx>
62 #include <Viewer/splash.hxx>
63 #include <Viewer/renderer.hxx>
65 #include "fg_commands.hxx"
69 #include "fg_init.hxx"
71 #include "fg_props.hxx"
73 using namespace flightgear;
78 // The atexit() function handler should know when the graphical subsystem
80 extern int _bootstrap_OSInit;
83 static void fgLoadInitialScenery()
85 static SGPropertyNode_ptr scenery_loaded
86 = fgGetNode("sim/sceneryloaded", true);
87 static SGPropertyNode_ptr scenery_override
88 = fgGetNode("/sim/sceneryloaded-override", true);
90 if (!scenery_loaded->getBoolValue())
92 if (scenery_override->getBoolValue() ||
93 (globals->get_tile_mgr()->isSceneryLoaded()
94 && fgGetBool("sim/fdm-initialized"))) {
95 fgSetBool("sim/sceneryloaded",true);
100 fgSplashProgress("loading scenery");
101 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
102 SGTimeStamp::sleepForMSec(500);
107 // What should we do when we have nothing else to do? Let's get ready
108 // for the next move and update the display?
109 static void fgMainLoop( void )
111 static SGPropertyNode_ptr frame_signal
112 = fgGetNode("/sim/signals/frame", true);
114 frame_signal->fireValueChanged();
116 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
117 SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
119 // compute simulated time (allowing for pause, warp, etc) and
121 double sim_dt, real_dt;
122 static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
123 timeMgr->computeTimeDeltas(sim_dt, real_dt);
125 // update magvar model
126 globals->get_mag()->update( globals->get_aircraft_position(),
127 globals->get_time_params()->getJD() );
129 // update all subsystems
130 globals->get_subsystem_mgr()->update(sim_dt);
132 // END Tile Manager updates
133 fgLoadInitialScenery();
135 simgear::AtomicChangeListener::fireChangeListeners();
137 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
140 // Operation for querying OpenGL parameters. This must be done in a
141 // valid OpenGL context, potentially in another thread.
144 struct GeneralInitOperation : public GraphicsContextOperation
146 GeneralInitOperation()
147 : GraphicsContextOperation(std::string("General init"))
150 void run(osg::GraphicsContext* gc)
152 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
154 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
155 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
157 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
158 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
160 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
161 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
164 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
165 simRendering->setIntValue("max-texture-size", tmp);
167 glGetIntegerv( GL_DEPTH_BITS, &tmp );
168 simRendering->setIntValue("depth-buffer-bits", tmp);
174 // This is the top level master main function that is registered as
177 // The first few passes take care of initialization things (a couple
178 // per pass) and once everything has been initialized fgMainLoop from
181 static void fgIdleFunction ( void ) {
182 // Specify our current idle function state. This is used to run all
183 // our initializations out of the idle callback so that we can get a
184 // splash screen up and running right away.
185 static int idle_state = 0;
187 static osg::ref_ptr<GeneralInitOperation> genOp;
188 if ( idle_state == 0 ) {
190 // Pick some window on which to do queries.
191 // XXX Perhaps all this graphics initialization code should be
192 // moved to renderer.cxx?
193 genOp = new GeneralInitOperation;
194 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
195 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
196 osg::GraphicsContext* gc = 0;
198 gc = guiCamera->getGraphicsContext();
200 gc->add(genOp.get());
202 wsa->windows[0]->gc->add(genOp.get());
205 } else if ( idle_state == 1 ) {
207 if (!genOp->isFinished())
211 if (!guiFinishInit())
214 fgSplashProgress("loading aircraft list");
216 } else if ( idle_state == 2 ) {
218 fgSplashProgress("loading navigation data");
220 } else if ( idle_state == 3 ) {
224 fgSplashProgress("initializing scenery system");
226 } else if ( idle_state == 4 ) {
228 // based on the requested presets, calculate the true starting
231 fgInitTowerLocationListener();
233 TimeManager* t = new TimeManager;
234 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
235 t->init(); // need to init now, not during initSubsystems
237 // Do some quick general initializations
238 if( !fgInitGeneral()) {
239 SG_LOG( SG_GENERAL, SG_ALERT,
240 "General initialization failed ..." );
244 ////////////////////////////////////////////////////////////////////
245 // Initialize the property-based built-in commands
246 ////////////////////////////////////////////////////////////////////
249 ////////////////////////////////////////////////////////////////////
250 // Initialize the material manager
251 ////////////////////////////////////////////////////////////////////
252 globals->set_matlib( new SGMaterialLib );
253 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
254 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
256 ////////////////////////////////////////////////////////////////////
257 // Initialize the TG scenery subsystem.
258 ////////////////////////////////////////////////////////////////////
259 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
260 globals->add_subsystem("terrasync", terra_sync);
261 globals->set_scenery( new FGScenery );
262 globals->get_scenery()->init();
263 globals->get_scenery()->bind();
264 globals->set_tile_mgr( new FGTileMgr );
266 fgSplashProgress("loading aircraft");
268 } else if ( idle_state == 6 ) {
271 // Initialize MagVar model
272 SGMagVar *magvar = new SGMagVar();
273 globals->set_mag( magvar );
275 // kludge to initialize mag compass
276 // (should only be done for in-flight startup)
277 // update magvar model
278 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
279 * SGD_DEGREES_TO_RADIANS,
280 fgGetDouble("/position/latitude-deg")
281 * SGD_DEGREES_TO_RADIANS,
282 fgGetDouble("/position/altitude-ft")
284 globals->get_time_params()->getJD() );
286 fgSplashProgress("initializing subsystems");
288 } else if ( idle_state == 7 ) {
290 // Initialize audio support
291 #ifdef ENABLE_AUDIO_SUPPORT
293 // Start the intro music
294 if ( fgGetBool("/sim/startup/intro-music") ) {
295 SGPath mp3file( globals->get_fg_root() );
296 mp3file.append( "Sounds/intro.mp3" );
298 SG_LOG( SG_GENERAL, SG_INFO,
299 "Starting intro music: " << mp3file.str() );
301 # if defined( __CYGWIN__ )
302 string command = "start /m `cygpath -w " + mp3file.str() + "`";
303 # elif defined( _WIN32 )
304 string command = "start /m " + mp3file.str();
306 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
309 if (0 != system ( command.c_str() ))
311 SG_LOG( SG_SOUND, SG_WARN,
312 "Failed to play mp3 file " << mp3file.str() << ". Maybe mp3 player is not installed." );
316 // This is the top level init routine which calls all the
317 // other subsystem initialization routines. If you are adding
318 // a subsystem to flightgear, its initialization call should be
319 // located in this routine.
320 if( !fgInitSubsystems()) {
321 SG_LOG( SG_GENERAL, SG_ALERT,
322 "Subsystem initialization failed ..." );
327 // ugly hack for automatic runway selection on startup based on
328 // metar data. Makes startup.nas obsolete and guarantees the same
329 // runway selection as for AI traffic. However, this code belongs to
330 // somewhere(?) else - if I only new where...
331 if( true == fgGetBool( "/environment/metar/valid" ) ) {
332 SG_LOG(SG_ENVIRONMENT, SG_INFO,
333 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
334 // the realwx_ctrl fetches metar in the foreground on init,
335 // If it was able to fetch a metar or one was given on the commandline,
336 // the valid flag is set here, otherwise it is false
337 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
338 string apt = fgGetString( "/sim/startup/options/airport" );
339 string rwy = fgGetString( "/sim/startup/options/runway" );
340 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
341 string parkpos = fgGetString( "/sim/presets/parkpos" );
342 bool onground = fgGetBool( "/sim/presets/onground", false );
343 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
344 // the other logic is taken from former startup.nas
345 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
346 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
347 fgSetPosFromAirportIDandHdg( apt, hdg );
350 SG_LOG(SG_ENVIRONMENT, SG_INFO,
351 "No METAR available to pick active runway" );
354 fgSplashProgress("initializing graphics engine");
356 } else if ( idle_state == 8 ) {
359 // setup OpenGL view parameters
360 globals->get_renderer()->setupView();
362 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
363 fgGetInt("/sim/startup/ysize") );
365 int session = fgGetInt("/sim/session",0);
367 fgSetInt("/sim/session",session);
370 if ( idle_state == 1000 ) {
371 // We've finished all our initialization steps, from now on we
372 // run the main loop.
373 fgSetBool("sim/sceneryloaded", false);
374 fgRegisterIdleHandler( fgMainLoop );
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 p->addChangeListener(new FGMakeUpperCase);
396 // Main top level initialization
397 int fgMainInit( int argc, char **argv ) {
399 // set default log levels
400 sglog().setLogLevels( SG_ALL, SG_ALERT );
403 #ifdef FLIGHTGEAR_VERSION
404 version = FLIGHTGEAR_VERSION;
406 version = "unknown version";
408 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
410 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
412 // Allocate global data structures. This needs to happen before
413 // we parse command line options
415 globals = new FGGlobals;
417 // seed the random number generator
420 FGControls *controls = new FGControls;
421 globals->set_controls( controls );
423 string_list *col = new string_list;
424 globals->set_channel_options_list( col );
426 fgValidatePath("", false); // initialize static variables
427 upper_case_property("/sim/presets/airport-id");
428 upper_case_property("/sim/presets/runway");
429 upper_case_property("/sim/tower/airport-id");
430 upper_case_property("/autopilot/route-manager/input");
432 // Load the configuration parameters. (Command line options
433 // override config file options. Config file options override
435 if ( !fgInitConfig(argc, argv) ) {
436 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
440 // Initialize the Window/Graphics environment.
441 fgOSInit(&argc, argv);
444 fgRegisterIdleHandler( &fgIdleFunction );
446 // Initialize sockets (WinSock needs this)
447 simgear::Socket::initSockets();
449 // Clouds3D requires an alpha channel
450 fgOSOpenWindow(true /* request stencil buffer */);
452 // Initialize the splash screen right away
456 // pass control off to the master event handler
457 int result = fgOSMainLoop();
459 // clean up here; ensure we null globals to avoid
460 // confusing the atexit() handler