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/io/raw_socket.hxx>
48 #include <simgear/scene/tsync/terrasync.hxx>
49 #include <simgear/math/SGMath.hxx>
50 #include <simgear/math/sg_random.h>
52 #include <Aircraft/controls.hxx>
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/CameraGroup.hxx>
60 #include <Viewer/WindowSystemAdapter.hxx>
61 #include <Viewer/splash.hxx>
62 #include <Viewer/renderer.hxx>
64 #include "fg_commands.hxx"
68 #include "fg_init.hxx"
70 #include "fg_props.hxx"
72 using namespace flightgear;
77 // The atexit() function handler should know when the graphical subsystem
79 extern int _bootstrap_OSInit;
82 static void fgLoadInitialScenery()
84 static SGPropertyNode_ptr scenery_loaded
85 = fgGetNode("sim/sceneryloaded", true);
86 static SGPropertyNode_ptr scenery_override
87 = fgGetNode("/sim/sceneryloaded-override", true);
89 if (!scenery_loaded->getBoolValue())
91 if (scenery_override->getBoolValue() ||
92 (globals->get_tile_mgr()->isSceneryLoaded()
93 && fgGetBool("sim/fdm-initialized"))) {
94 fgSetBool("sim/sceneryloaded",true);
99 fgSplashProgress("loading scenery");
100 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
101 SGTimeStamp::sleepForMSec(500);
106 // What should we do when we have nothing else to do? Let's get ready
107 // for the next move and update the display?
108 static void fgMainLoop( void )
110 static SGPropertyNode_ptr frame_signal
111 = fgGetNode("/sim/signals/frame", true);
113 frame_signal->fireValueChanged();
115 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
116 SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
118 // compute simulated time (allowing for pause, warp, etc) and
120 double sim_dt, real_dt;
121 static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
122 timeMgr->computeTimeDeltas(sim_dt, real_dt);
124 // update all subsystems
125 globals->get_subsystem_mgr()->update(sim_dt);
127 // END Tile Manager updates
128 fgLoadInitialScenery();
130 simgear::AtomicChangeListener::fireChangeListeners();
132 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
135 // Operation for querying OpenGL parameters. This must be done in a
136 // valid OpenGL context, potentially in another thread.
139 struct GeneralInitOperation : public GraphicsContextOperation
141 GeneralInitOperation()
142 : GraphicsContextOperation(std::string("General init"))
145 void run(osg::GraphicsContext* gc)
147 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
149 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
150 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
152 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
153 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
155 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
156 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
158 simRendering->setStringValue("gl-shading-language-version", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION));
159 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_SHADING_LANGUAGE_VERSION));
162 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
163 simRendering->setIntValue("max-texture-size", tmp);
165 glGetIntegerv( GL_DEPTH_BITS, &tmp );
166 simRendering->setIntValue("depth-buffer-bits", tmp);
172 // This is the top level master main function that is registered as
175 // The first few passes take care of initialization things (a couple
176 // per pass) and once everything has been initialized fgMainLoop from
179 static void fgIdleFunction ( void ) {
180 // Specify our current idle function state. This is used to run all
181 // our initializations out of the idle callback so that we can get a
182 // splash screen up and running right away.
183 static int idle_state = 0;
185 static osg::ref_ptr<GeneralInitOperation> genOp;
186 if ( idle_state == 0 ) {
188 // Pick some window on which to do queries.
189 // XXX Perhaps all this graphics initialization code should be
190 // moved to renderer.cxx?
191 genOp = new GeneralInitOperation;
192 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
193 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
194 osg::GraphicsContext* gc = 0;
196 gc = guiCamera->getGraphicsContext();
198 gc->add(genOp.get());
200 wsa->windows[0]->gc->add(genOp.get());
203 } else if ( idle_state == 1 ) {
205 if (!genOp->isFinished())
209 if (!guiFinishInit())
212 fgSplashProgress("loading aircraft list");
214 } else if ( idle_state == 2 ) {
216 fgSplashProgress("loading navigation data");
218 } else if ( idle_state == 3 ) {
222 fgSplashProgress("initializing scenery system");
224 } else if ( idle_state == 4 ) {
226 // based on the requested presets, calculate the true starting
229 fgInitTowerLocationListener();
231 TimeManager* t = new TimeManager;
232 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
233 t->init(); // need to init now, not during initSubsystems
235 // Do some quick general initializations
236 if( !fgInitGeneral()) {
237 SG_LOG( SG_GENERAL, SG_ALERT,
238 "General initialization failed ..." );
242 ////////////////////////////////////////////////////////////////////
243 // Initialize the property-based built-in commands
244 ////////////////////////////////////////////////////////////////////
247 ////////////////////////////////////////////////////////////////////
248 // Initialize the material manager
249 ////////////////////////////////////////////////////////////////////
250 globals->set_matlib( new SGMaterialLib );
251 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
252 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
254 ////////////////////////////////////////////////////////////////////
255 // Initialize the TG scenery subsystem.
256 ////////////////////////////////////////////////////////////////////
257 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
258 globals->add_subsystem("terrasync", terra_sync);
259 globals->set_scenery( new FGScenery );
260 globals->get_scenery()->init();
261 globals->get_scenery()->bind();
262 globals->set_tile_mgr( new FGTileMgr );
264 fgSplashProgress("loading aircraft");
266 } else if ( idle_state == 6 ) {
268 fgSplashProgress("initializing subsystems");
270 } else if ( idle_state == 7 ) {
272 // Initialize audio support
273 #ifdef ENABLE_AUDIO_SUPPORT
275 // Start the intro music
276 if ( fgGetBool("/sim/startup/intro-music") ) {
277 SGPath mp3file( globals->get_fg_root() );
278 mp3file.append( "Sounds/intro.mp3" );
280 SG_LOG( SG_GENERAL, SG_INFO,
281 "Starting intro music: " << mp3file.str() );
283 # if defined( __CYGWIN__ )
284 string command = "start /m `cygpath -w " + mp3file.str() + "`";
285 # elif defined( _WIN32 )
286 string command = "start /m " + mp3file.str();
288 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
291 if (0 != system ( command.c_str() ))
293 SG_LOG( SG_SOUND, SG_WARN,
294 "Failed to play mp3 file " << mp3file.str() << ". Maybe mp3 player is not installed." );
298 // This is the top level init routine which calls all the
299 // other subsystem initialization routines. If you are adding
300 // a subsystem to flightgear, its initialization call should be
301 // located in this routine.
302 if( !fgInitSubsystems()) {
303 SG_LOG( SG_GENERAL, SG_ALERT,
304 "Subsystem initialization failed ..." );
309 // ugly hack for automatic runway selection on startup based on
310 // metar data. Makes startup.nas obsolete and guarantees the same
311 // runway selection as for AI traffic. However, this code belongs to
312 // somewhere(?) else - if I only new where...
313 if( true == fgGetBool( "/environment/metar/valid" ) ) {
314 SG_LOG(SG_ENVIRONMENT, SG_INFO,
315 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
316 // the realwx_ctrl fetches metar in the foreground on init,
317 // If it was able to fetch a metar or one was given on the commandline,
318 // the valid flag is set here, otherwise it is false
319 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
320 string apt = fgGetString( "/sim/startup/options/airport" );
321 string rwy = fgGetString( "/sim/startup/options/runway" );
322 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
323 string parkpos = fgGetString( "/sim/presets/parkpos" );
324 bool onground = fgGetBool( "/sim/presets/onground", false );
325 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
326 // the other logic is taken from former startup.nas
327 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
328 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
329 fgSetPosFromAirportIDandHdg( apt, hdg );
332 SG_LOG(SG_ENVIRONMENT, SG_INFO,
333 "No METAR available to pick active runway" );
336 fgSplashProgress("initializing graphics engine");
338 } else if ( idle_state == 8 ) {
341 // setup OpenGL view parameters
342 globals->get_renderer()->setupView();
344 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
345 fgGetInt("/sim/startup/ysize") );
347 int session = fgGetInt("/sim/session",0);
349 fgSetInt("/sim/session",session);
352 if ( idle_state == 1000 ) {
353 // We've finished all our initialization steps, from now on we
354 // run the main loop.
355 fgSetBool("sim/sceneryloaded", false);
356 fgRegisterIdleHandler( fgMainLoop );
360 static void upper_case_property(const char *name)
362 using namespace simgear;
363 SGPropertyNode *p = fgGetNode(name, false);
365 p = fgGetNode(name, true);
366 p->setStringValue("");
368 props::Type t = p->getType();
369 if (t == props::NONE || t == props::UNSPECIFIED)
370 p->setStringValue("");
372 assert(t == props::STRING);
374 p->addChangeListener(new FGMakeUpperCase);
378 // Main top level initialization
379 int fgMainInit( int argc, char **argv ) {
381 // set default log levels
382 sglog().setLogLevels( SG_ALL, SG_ALERT );
385 #ifdef FLIGHTGEAR_VERSION
386 version = FLIGHTGEAR_VERSION;
388 version = "unknown version";
390 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
392 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
394 // Allocate global data structures. This needs to happen before
395 // we parse command line options
397 globals = new FGGlobals;
399 // seed the random number generator
402 FGControls *controls = new FGControls;
403 globals->set_controls( controls );
405 string_list *col = new string_list;
406 globals->set_channel_options_list( col );
408 fgValidatePath("", false); // initialize static variables
409 upper_case_property("/sim/presets/airport-id");
410 upper_case_property("/sim/presets/runway");
411 upper_case_property("/sim/tower/airport-id");
412 upper_case_property("/autopilot/route-manager/input");
414 // Load the configuration parameters. (Command line options
415 // override config file options. Config file options override
417 if ( !fgInitConfig(argc, argv) ) {
418 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
422 // Initialize the Window/Graphics environment.
423 fgOSInit(&argc, argv);
426 fgRegisterIdleHandler( &fgIdleFunction );
428 // Initialize sockets (WinSock needs this)
429 simgear::Socket::initSockets();
431 // Clouds3D requires an alpha channel
432 fgOSOpenWindow(true /* request stencil buffer */);
434 // Initialize the splash screen right away
438 // pass control off to the master event handler
439 int result = fgOSMainLoop();
441 // clean up here; ensure we null globals to avoid
442 // confusing the atexit() handler