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/scene/model/animation.hxx>
45 #include <simgear/scene/sky/sky.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/props/AtomicChangeListener.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/timing/sg_time.hxx>
50 #include <simgear/math/sg_random.h>
52 #include <Time/light.hxx>
53 #include <Aircraft/replay.hxx>
54 #include <Cockpit/cockpit.hxx>
55 #include <Cockpit/hud.hxx>
56 #include <Model/panelnode.hxx>
57 #include <Model/modelmgr.hxx>
58 #include <Model/acmodel.hxx>
59 #include <Scenery/scenery.hxx>
60 #include <Scenery/tilemgr.hxx>
61 #include <Sound/fg_fx.hxx>
62 #include <Sound/beacon.hxx>
63 #include <Sound/morse.hxx>
64 #include <Sound/fg_fx.hxx>
65 #include <ATCDCL/ATCmgr.hxx>
66 #include <Time/TimeManager.hxx>
67 #include <Environment/environment_mgr.hxx>
68 #include <Environment/ephemeris.hxx>
69 #include <GUI/new_gui.hxx>
70 #include <MultiPlayer/multiplaymgr.hxx>
72 #include "CameraGroup.hxx"
73 #include "fg_commands.hxx"
75 #include "renderer.hxx"
79 #include "fg_init.hxx"
81 #include "WindowSystemAdapter.hxx"
82 #include <Main/viewer.hxx>
85 using namespace flightgear;
89 // Specify our current idle function state. This is used to run all
90 // our initializations out of the idle callback so that we can get a
91 // splash screen up and running right away.
95 void fgInitSoundManager();
96 void fgSetNewSoundDevice(const char *);
98 // The atexit() function handler should know when the graphical subsystem
100 extern int _bootstrap_OSInit;
102 // What should we do when we have nothing else to do? Let's get ready
103 // for the next move and update the display?
104 static void fgMainLoop( void ) {
106 static SGConstPropertyNode_ptr longitude
107 = fgGetNode("/position/longitude-deg");
108 static SGConstPropertyNode_ptr latitude
109 = fgGetNode("/position/latitude-deg");
110 static SGConstPropertyNode_ptr altitude
111 = fgGetNode("/position/altitude-ft");
112 static SGConstPropertyNode_ptr vn_fps
113 = fgGetNode("/velocities/speed-north-fps");
114 static SGConstPropertyNode_ptr ve_fps
115 = fgGetNode("/velocities/speed-east-fps");
116 static SGConstPropertyNode_ptr vd_fps
117 = fgGetNode("/velocities/speed-down-fps");
119 static SGPropertyNode_ptr frame_signal
120 = fgGetNode("/sim/signals/frame", true);
122 frame_signal->fireValueChanged();
123 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
125 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
126 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
130 double sim_dt, real_dt;
131 TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
132 // compute simulated time (allowing for pause, warp, etc) and
134 timeMgr->computeTimeDeltas(sim_dt, real_dt);
136 if (globals->get_warp_delta() != 0) {
137 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
141 // update magvar model
142 globals->get_mag()->update( longitude->getDoubleValue()
143 * SGD_DEGREES_TO_RADIANS,
144 latitude->getDoubleValue()
145 * SGD_DEGREES_TO_RADIANS,
146 altitude->getDoubleValue() * SG_FEET_TO_METER,
147 globals->get_time_params()->getJD() );
150 // Update any multiplayer's network queues, the AIMultiplayer
151 // implementation is an AI model and depends on that
152 globals->get_multiplayer_mgr()->Update();
156 if (fgGetBool("/sim/atc/enabled"))
157 globals->get_ATC_mgr()->update(sim_dt);
160 globals->get_subsystem_mgr()->update(sim_dt);
161 globals->get_aircraft_model()->update(sim_dt);
164 // Tile Manager updates - see if we need to load any new scenery tiles.
165 // this code ties together the fdm, viewer and scenery classes...
166 // we may want to move this to its own class at some point
168 double visibility_meters = fgGetDouble("/environment/visibility-m");
169 globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
171 // update tile manager for view...
172 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
173 SGGeod geodViewPos = SGGeod::fromCart(viewPos);
174 globals->get_tile_mgr()->update(geodViewPos, visibility_meters);
176 // run Nasal's settimer() loops right before the view manager
177 globals->get_event_mgr()->update(sim_dt);
179 // pick up model coordidnates that Nasal code may have set relative to the
181 globals->get_model_mgr()->update(sim_dt);
183 // update the view angle as late as possible, but before sound calculations
184 globals->get_viewmgr()->update(real_dt);
186 // Update the sound manager last so it can use the CPU while the GPU
187 // is processing the scenery (doubled the frame-rate for me) -EMH-
188 #ifdef ENABLE_AUDIO_SUPPORT
189 static bool smgr_init = true;
190 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
191 if (smgr_init == true) {
192 if (sound_working->getBoolValue() == true) {
193 fgInitSoundManager();
197 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
198 static SGSoundMgr *smgr = globals->get_soundmgr();
199 static bool smgr_enabled = true;
201 if (sound_working->getBoolValue() == false) { // request to reinit
204 sound_working->setBoolValue(true);
207 if (smgr_enabled != sound_enabled->getBoolValue()) {
208 if (smgr_enabled == true) { // request to suspend
210 smgr_enabled = false;
217 if (smgr_enabled == true) {
218 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
219 smgr->set_volume(volume->getFloatValue());
220 smgr->update(sim_dt);
225 // END Tile Manager udpates
226 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
227 if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
228 && fgGetBool("sim/fdm-initialized")) {
229 fgSetBool("sim/sceneryloaded",true);
230 if (fgGetBool("/sim/sound/working")) {
231 globals->get_soundmgr()->activate();
233 globals->get_props()->tie("/sim/sound/devices/name",
234 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
236 simgear::AtomicChangeListener::fireChangeListeners();
238 SG_LOG( SG_ALL, SG_DEBUG, "" );
241 void fgInitSoundManager()
243 SGSoundMgr *smgr = globals->get_soundmgr();
246 smgr->init(fgGetString("/sim/sound/device-name", NULL));
248 vector <const char*>devices = smgr->get_available_devices();
249 for (unsigned int i=0; i<devices.size(); i++) {
250 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
251 p->setStringValue(devices[i]);
256 void fgSetNewSoundDevice(const char *device)
258 globals->get_soundmgr()->suspend();
259 globals->get_soundmgr()->stop();
260 globals->get_soundmgr()->init(device);
261 globals->get_soundmgr()->resume();
264 // Operation for querying OpenGL parameters. This must be done in a
265 // valid OpenGL context, potentially in another thread.
268 struct GeneralInitOperation : public GraphicsContextOperation
270 GeneralInitOperation()
271 : GraphicsContextOperation(std::string("General init"))
274 void run(osg::GraphicsContext* gc)
276 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
278 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
279 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
281 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
282 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
284 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
285 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
288 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
289 simRendering->setIntValue("max-texture-size", tmp);
291 glGetIntegerv( GL_DEPTH_BITS, &tmp );
292 simRendering->setIntValue("depth-buffer-bits", tmp);
297 osg::Node* load_panel(SGPropertyNode *n)
299 osg::Geode* geode = new osg::Geode;
300 geode->addDrawable(new FGPanelNode(n));
304 SGPath resolve_path(const std::string& s)
306 return globals->resolve_maybe_aircraft_path(s);
311 // This is the top level master main function that is registered as
314 // The first few passes take care of initialization things (a couple
315 // per pass) and once everything has been initialized fgMainLoop from
318 static void fgIdleFunction ( void ) {
319 static osg::ref_ptr<GeneralInitOperation> genOp;
320 if ( idle_state == 0 ) {
322 // Pick some window on which to do queries.
323 // XXX Perhaps all this graphics initialization code should be
324 // moved to renderer.cxx?
325 genOp = new GeneralInitOperation;
326 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
327 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
328 osg::GraphicsContext* gc = 0;
330 gc = guiCamera->getGraphicsContext();
332 gc->add(genOp.get());
334 wsa->windows[0]->gc->add(genOp.get());
337 } else if ( idle_state == 1 ) {
339 if (!genOp->isFinished())
343 if (!guiFinishInit())
346 fgSplashProgress("reading aircraft list");
349 } else if ( idle_state == 2 ) {
352 fgSplashProgress("reading airport & navigation data");
355 } else if ( idle_state == 3 ) {
358 fgSplashProgress("setting up scenery");
361 } else if ( idle_state == 4 ) {
363 // based on the requested presets, calculate the true starting
366 fgInitTowerLocationListener();
368 TimeManager* t = new TimeManager;
369 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
370 t->init(); // need to init now, not during initSubsystems
372 // Do some quick general initializations
373 if( !fgInitGeneral()) {
374 SG_LOG( SG_GENERAL, SG_ALERT,
375 "General initialization failed ..." );
379 ////////////////////////////////////////////////////////////////////
380 // Initialize the property-based built-in commands
381 ////////////////////////////////////////////////////////////////////
385 ////////////////////////////////////////////////////////////////////
386 // Initialize the material manager
387 ////////////////////////////////////////////////////////////////////
388 globals->set_matlib( new SGMaterialLib );
389 simgear::SGModelLib::init(globals->get_fg_root());
390 simgear::SGModelLib::setPropRoot(globals->get_props());
391 simgear::SGModelLib::setPanelFunc(load_panel);
393 ////////////////////////////////////////////////////////////////////
394 // Initialize the TG scenery subsystem.
395 ////////////////////////////////////////////////////////////////////
396 globals->set_scenery( new FGScenery );
397 globals->get_scenery()->init();
398 globals->get_scenery()->bind();
399 globals->set_tile_mgr( new FGTileMgr );
402 ////////////////////////////////////////////////////////////////////
403 // Initialize the general model subsystem.
404 ////////////////////////////////////////////////////////////////////
405 globals->set_model_mgr(new FGModelMgr);
406 globals->get_model_mgr()->init();
407 globals->get_model_mgr()->bind();
408 fgSplashProgress("loading aircraft");
411 } else if ( idle_state == 5 ) {
414 ////////////////////////////////////////////////////////////////////
415 // Initialize the 3D aircraft model subsystem (has a dependency on
416 // the scenery subsystem.)
417 ////////////////////////////////////////////////////////////////////
418 FGAircraftModel* acm = new FGAircraftModel;
419 globals->set_aircraft_model(acm);
420 //globals->add_subsystem("aircraft-model", acm);
424 ////////////////////////////////////////////////////////////////////
425 // Initialize the view manager subsystem.
426 ////////////////////////////////////////////////////////////////////
427 FGViewMgr *viewmgr = new FGViewMgr;
428 globals->set_viewmgr( viewmgr );
431 fgSplashProgress("generating sky elements");
434 } else if ( idle_state == 6 ) {
436 // Initialize the sky
438 Ephemeris* eph = new Ephemeris;
439 globals->add_subsystem("ephemeris", eph);
440 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
443 // TODO: move to environment mgr
445 SGPath texture_path(globals->get_fg_root());
446 texture_path.append("Textures");
447 texture_path.append("Sky");
448 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
449 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
450 thesky->add_cloud_layer(layer);
453 SGPath sky_tex_path( globals->get_fg_root() );
454 sky_tex_path.append( "Textures" );
455 sky_tex_path.append( "Sky" );
456 thesky->texture_path( sky_tex_path.str() );
458 // The sun and moon diameters are scaled down numbers of the
459 // actual diameters. This was needed to fit both the sun and the
460 // moon within the distance to the far clip plane.
461 // Moon diameter: 3,476 kilometers
462 // Sun diameter: 1,390,000 kilometers
463 thesky->build( 80000.0, 80000.0,
465 *globals->get_ephem(),
466 fgGetNode("/environment", true));
468 // Initialize MagVar model
469 SGMagVar *magvar = new SGMagVar();
470 globals->set_mag( magvar );
473 // kludge to initialize mag compass
474 // (should only be done for in-flight
476 // update magvar model
477 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
478 * SGD_DEGREES_TO_RADIANS,
479 fgGetDouble("/position/latitude-deg")
480 * SGD_DEGREES_TO_RADIANS,
481 fgGetDouble("/position/altitude-ft")
483 globals->get_time_params()->getJD() );
484 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
485 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
486 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
489 // airport = new ssgBranch;
490 // airport->setName( "Airport Lighting" );
491 // lighting->addKid( airport );
493 // build our custom render states
494 fgSplashProgress("initializing subsystems");
497 } else if ( idle_state == 7 ) {
499 // Initialize audio support
500 #ifdef ENABLE_AUDIO_SUPPORT
502 // Start the intro music
503 if ( fgGetBool("/sim/startup/intro-music") ) {
504 SGPath mp3file( globals->get_fg_root() );
505 mp3file.append( "Sounds/intro.mp3" );
507 SG_LOG( SG_GENERAL, SG_INFO,
508 "Starting intro music: " << mp3file.str() );
510 # if defined( __CYGWIN__ )
511 string command = "start /m `cygpath -w " + mp3file.str() + "`";
512 # elif defined( _WIN32 )
513 string command = "start /m " + mp3file.str();
515 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
518 system ( command.c_str() );
521 // This is the top level init routine which calls all the
522 // other subsystem initialization routines. If you are adding
523 // a subsystem to flightgear, its initialization call should be
524 // located in this routine.
525 if( !fgInitSubsystems()) {
526 SG_LOG( SG_GENERAL, SG_ALERT,
527 "Subsystem initialization failed ..." );
530 fgSplashProgress("setting up time & renderer");
533 } else if ( idle_state == 8 ) {
536 // setup OpenGL view parameters
537 globals->get_renderer()->init();
539 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
540 fgGetInt("/sim/startup/ysize") );
542 fgSplashProgress("loading scenery objects");
543 int session = fgGetInt("/sim/session",0);
545 fgSetInt("/sim/session",session);
548 if ( idle_state == 1000 ) {
549 // We've finished all our initialization steps, from now on we
550 // run the main loop.
551 fgSetBool("sim/sceneryloaded", false);
552 fgRegisterIdleHandler( fgMainLoop );
557 static void upper_case_property(const char *name)
559 using namespace simgear;
560 SGPropertyNode *p = fgGetNode(name, false);
562 p = fgGetNode(name, true);
563 p->setStringValue("");
565 props::Type t = p->getType();
566 if (t == props::NONE || t == props::UNSPECIFIED)
567 p->setStringValue("");
569 assert(t == props::STRING);
571 p->addChangeListener(new FGMakeUpperCase);
575 // Main top level initialization
576 int fgMainInit( int argc, char **argv ) {
578 // set default log levels
579 sglog().setLogLevels( SG_ALL, SG_ALERT );
582 #ifdef FLIGHTGEAR_VERSION
583 version = FLIGHTGEAR_VERSION;
585 version = "unknown version";
587 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
589 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
591 // Allocate global data structures. This needs to happen before
592 // we parse command line options
594 globals = new FGGlobals;
596 // seed the random number generator
599 FGControls *controls = new FGControls;
600 globals->set_controls( controls );
602 string_list *col = new string_list;
603 globals->set_channel_options_list( col );
605 fgValidatePath("", false); // initialize static variables
606 upper_case_property("/sim/presets/airport-id");
607 upper_case_property("/sim/presets/runway");
608 upper_case_property("/sim/tower/airport-id");
609 upper_case_property("/autopilot/route-manager/input");
611 // Scan the config file(s) and command line options to see if
612 // fg_root was specified (ignore all other options for now)
613 fgInitFGRoot(argc, argv);
615 // Check for the correct base package version
616 static char required_version[] = "2.0.0";
617 string base_version = fgBasePackageVersion();
618 if ( !(base_version == required_version) ) {
619 // tell the operator how to use this application
621 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
622 cerr << endl << "Base package check failed ... " \
623 << "Found version " << base_version << " at: " \
624 << globals->get_fg_root() << endl;
625 cerr << "Please upgrade to version: " << required_version << endl;
627 cerr << "Hit a key to continue..." << endl;
633 // Load the configuration parameters. (Command line options
634 // override config file options. Config file options override
636 if ( !fgInitConfig(argc, argv) ) {
637 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
641 // Initialize the Window/Graphics environment.
642 fgOSInit(&argc, argv);
645 fgRegisterWindowResizeHandler( &FGRenderer::resize );
646 fgRegisterIdleHandler( &fgIdleFunction );
647 fgRegisterDrawHandler( &FGRenderer::update );
649 // Initialize plib net interface
650 netInit( &argc, argv );
652 // Clouds3D requires an alpha channel
653 fgOSOpenWindow(true /* request stencil buffer */);
655 // Initialize the splash screen right away
659 // pass control off to the master event handler
660 int result = fgOSMainLoop();
662 // clean up here; ensure we null globals to avoid
663 // confusing the atexit() handler