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>
63 #include <Navaids/NavDataCache.hxx>
65 #include "fg_commands.hxx"
69 #include "fg_init.hxx"
71 #include "fg_props.hxx"
72 #include "positioninit.hxx"
74 using namespace flightgear;
79 // The atexit() function handler should know when the graphical subsystem
81 extern int _bootstrap_OSInit;
84 static void fgLoadInitialScenery()
86 static SGPropertyNode_ptr scenery_loaded
87 = fgGetNode("sim/sceneryloaded", true);
88 static SGPropertyNode_ptr scenery_override
89 = fgGetNode("/sim/sceneryloaded-override", true);
91 if (!scenery_loaded->getBoolValue())
93 if (scenery_override->getBoolValue() ||
94 (globals->get_tile_mgr()->isSceneryLoaded()
95 && fgGetBool("sim/fdm-initialized"))) {
96 fgSetBool("sim/sceneryloaded",true);
101 fgSplashProgress("loading scenery");
102 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
103 SGTimeStamp::sleepForMSec(500);
108 // What should we do when we have nothing else to do? Let's get ready
109 // for the next move and update the display?
110 static void fgMainLoop( void )
112 static SGPropertyNode_ptr frame_signal
113 = fgGetNode("/sim/signals/frame", true);
115 frame_signal->fireValueChanged();
117 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
118 SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
120 // compute simulated time (allowing for pause, warp, etc) and
122 double sim_dt, real_dt;
123 static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
124 timeMgr->computeTimeDeltas(sim_dt, real_dt);
126 // update all subsystems
127 globals->get_subsystem_mgr()->update(sim_dt);
129 // END Tile Manager updates
130 fgLoadInitialScenery();
132 simgear::AtomicChangeListener::fireChangeListeners();
134 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
137 // Operation for querying OpenGL parameters. This must be done in a
138 // valid OpenGL context, potentially in another thread.
141 struct GeneralInitOperation : public GraphicsContextOperation
143 GeneralInitOperation()
144 : GraphicsContextOperation(std::string("General init"))
147 void run(osg::GraphicsContext* gc)
149 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
151 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
152 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
154 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
155 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
157 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
158 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
160 simRendering->setStringValue("gl-shading-language-version", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION));
161 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_SHADING_LANGUAGE_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;
186 static int spin_count = 0;
188 static osg::ref_ptr<GeneralInitOperation> genOp;
189 if ( idle_state == 0 ) {
191 // Pick some window on which to do queries.
192 // XXX Perhaps all this graphics initialization code should be
193 // moved to renderer.cxx?
194 genOp = new GeneralInitOperation;
195 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
196 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
197 osg::GraphicsContext* gc = 0;
199 gc = guiCamera->getGraphicsContext();
201 gc->add(genOp.get());
203 wsa->windows[0]->gc->add(genOp.get());
206 } else if ( idle_state == 1 ) {
208 if (!genOp->isFinished())
212 if (!guiFinishInit())
215 fgSplashProgress("loading aircraft list");
217 } else if ( idle_state == 2 ) {
219 fgSplashProgress("loading navigation data");
221 } else if ( idle_state == 3 ) {
225 fgSplashProgress("initializing scenery system");
227 } else if ( idle_state == 4 ) {
229 // based on the requested presets, calculate the true starting
231 flightgear::initPosition();
232 flightgear::initTowerLocationListener();
234 TimeManager* t = new TimeManager;
235 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
236 t->init(); // need to init now, not during initSubsystems
238 // Do some quick general initializations
239 if( !fgInitGeneral()) {
240 SG_LOG( SG_GENERAL, SG_ALERT,
241 "General initialization failed ..." );
245 ////////////////////////////////////////////////////////////////////
246 // Initialize the property-based built-in commands
247 ////////////////////////////////////////////////////////////////////
250 ////////////////////////////////////////////////////////////////////
251 // Initialize the material manager
252 ////////////////////////////////////////////////////////////////////
253 globals->set_matlib( new SGMaterialLib );
254 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
255 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
257 ////////////////////////////////////////////////////////////////////
258 // Initialize the TG scenery subsystem.
259 ////////////////////////////////////////////////////////////////////
260 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
261 globals->add_subsystem("terrasync", terra_sync);
262 globals->set_scenery( new FGScenery );
263 globals->get_scenery()->init();
264 globals->get_scenery()->bind();
265 globals->set_tile_mgr( new FGTileMgr );
267 fgSplashProgress("loading aircraft");
269 } else if ( idle_state == 6 ) {
271 fgSplashProgress("creating subsystems");
273 } else if ( idle_state == 7 ) {
277 fgCreateSubsystems();
278 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
279 fgSplashProgress("binding subsystems");
281 } else if ( idle_state == 8 ) {
285 globals->get_subsystem_mgr()->bind();
286 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
288 fgSplashProgress("initing subsystems");
289 } else if ( idle_state == 9 ) {
290 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
291 if ( status == SGSubsystem::INIT_DONE) {
293 fgSplashProgress("finishing subsystem init");
295 const char* spinChars = "-\\|/";
296 string msg = string("initing subsystems ") + spinChars[spin_count++ % 4];
297 fgSplashProgress(msg.c_str());
300 } else if ( idle_state == 10 ) {
302 fgPostInitSubsystems();
305 // ugly hack for automatic runway selection on startup based on
306 // metar data. Makes startup.nas obsolete and guarantees the same
307 // runway selection as for AI traffic. However, this code belongs to
308 // somewhere(?) else - if I only new where...
309 if( true == fgGetBool( "/environment/metar/valid" ) ) {
310 SG_LOG(SG_ENVIRONMENT, SG_INFO,
311 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
312 // the realwx_ctrl fetches metar in the foreground on init,
313 // If it was able to fetch a metar or one was given on the commandline,
314 // the valid flag is set here, otherwise it is false
315 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
316 string apt = fgGetString( "/sim/startup/options/airport" );
317 string rwy = fgGetString( "/sim/startup/options/runway" );
318 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
319 string parkpos = fgGetString( "/sim/presets/parkpos" );
320 bool onground = fgGetBool( "/sim/presets/onground", false );
321 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
322 // the other logic is taken from former startup.nas
323 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
324 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
325 flightgear::setPosFromAirportIDandHdg( apt, hdg );
328 SG_LOG(SG_ENVIRONMENT, SG_INFO,
329 "No METAR available to pick active runway" );
332 fgSplashProgress("initializing graphics engine");
334 } else if ( idle_state == 900 ) {
337 // setup OpenGL view parameters
338 globals->get_renderer()->setupView();
340 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
341 fgGetInt("/sim/startup/ysize") );
343 int session = fgGetInt("/sim/session",0);
345 fgSetInt("/sim/session",session);
348 if ( idle_state == 1000 ) {
349 // We've finished all our initialization steps, from now on we
350 // run the main loop.
351 fgSetBool("sim/sceneryloaded", false);
352 fgRegisterIdleHandler( fgMainLoop );
356 static void upper_case_property(const char *name)
358 using namespace simgear;
359 SGPropertyNode *p = fgGetNode(name, false);
361 p = fgGetNode(name, true);
362 p->setStringValue("");
364 props::Type t = p->getType();
365 if (t == props::NONE || t == props::UNSPECIFIED)
366 p->setStringValue("");
368 assert(t == props::STRING);
370 p->addChangeListener(new FGMakeUpperCase);
374 // Main top level initialization
375 int fgMainInit( int argc, char **argv ) {
377 // set default log levels
378 sglog().setLogLevels( SG_ALL, SG_ALERT );
381 #ifdef FLIGHTGEAR_VERSION
382 version = FLIGHTGEAR_VERSION;
384 version = "unknown version";
386 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
388 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
390 // Allocate global data structures. This needs to happen before
391 // we parse command line options
393 globals = new FGGlobals;
395 // seed the random number generator
398 FGControls *controls = new FGControls;
399 globals->set_controls( controls );
401 string_list *col = new string_list;
402 globals->set_channel_options_list( col );
404 fgValidatePath("", false); // initialize static variables
405 upper_case_property("/sim/presets/airport-id");
406 upper_case_property("/sim/presets/runway");
407 upper_case_property("/sim/tower/airport-id");
408 upper_case_property("/autopilot/route-manager/input");
410 // Load the configuration parameters. (Command line options
411 // override config file options. Config file options override
413 if ( !fgInitConfig(argc, argv) ) {
414 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
418 // Initialize the Window/Graphics environment.
419 fgOSInit(&argc, argv);
422 fgRegisterIdleHandler( &fgIdleFunction );
424 // Initialize sockets (WinSock needs this)
425 simgear::Socket::initSockets();
427 // Clouds3D requires an alpha channel
428 fgOSOpenWindow(true /* request stencil buffer */);
430 // Initialize the splash screen right away
434 // pass control off to the master event handler
435 int result = fgOSMainLoop();
437 // clean up here; ensure we null globals to avoid
438 // confusing the atexit() handler
442 // delete the NavCache here. This will cause the destruction of many cached
443 // objects (eg, airports, navaids, runways).
444 delete flightgear::NavDataCache::instance();