]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Create FGSoundManager as a wrapper for SGSoundMgr_OpenAl
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <osg/Camera>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
40
41 // Class references
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>
52
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>
59 #include <GUI/gui.h>
60 #include <Viewer/CameraGroup.hxx>
61 #include <Viewer/WindowSystemAdapter.hxx>
62 #include <Viewer/splash.hxx>
63 #include <Viewer/renderer.hxx>
64
65 #include "fg_commands.hxx"
66 #include "fg_io.hxx"
67 #include "main.hxx"
68 #include "util.hxx"
69 #include "fg_init.hxx"
70 #include "fg_os.hxx"
71 #include "fg_props.hxx"
72
73 using namespace flightgear;
74
75 using std::cerr;
76 using std::vector;
77
78 // Specify our current idle function state.  This is used to run all
79 // our initializations out of the idle callback so that we can get a
80 // splash screen up and running right away.
81 int idle_state = 0;
82
83 // The atexit() function handler should know when the graphical subsystem
84 // is initialized.
85 extern int _bootstrap_OSInit;
86
87
88 static void fgLoadInitialScenery()
89 {
90     static SGPropertyNode_ptr scenery_loaded
91         = fgGetNode("sim/sceneryloaded", true);
92
93     if (!scenery_loaded->getBoolValue())
94     {
95         if (globals->get_tile_mgr()->isSceneryLoaded()
96              && fgGetBool("sim/fdm-initialized")) {
97             fgSetBool("sim/sceneryloaded",true);
98             fgSplashProgress("");
99         }
100         else
101         {
102             fgSplashProgress("loading scenery");
103             // be nice to loader threads while waiting for initial scenery, reduce to 2fps
104             SGTimeStamp::sleepForMSec(500);
105         }
106     }
107 }
108
109 // What should we do when we have nothing else to do?  Let's get ready
110 // for the next move and update the display?
111 static void fgMainLoop( void )
112 {
113     static SGPropertyNode_ptr frame_signal
114         = fgGetNode("/sim/signals/frame", true);
115
116     frame_signal->fireValueChanged();
117
118     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
119     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
120
121     // compute simulated time (allowing for pause, warp, etc) and
122     // real elapsed time
123     double sim_dt, real_dt;
124     TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
125     timeMgr->computeTimeDeltas(sim_dt, real_dt);
126
127     // update magvar model
128     globals->get_mag()->update( globals->get_aircraft_position(),
129                                 globals->get_time_params()->getJD() );
130
131     // update all subsystems
132     globals->get_subsystem_mgr()->update(sim_dt);
133
134     // END Tile Manager updates
135     fgLoadInitialScenery();
136
137     simgear::AtomicChangeListener::fireChangeListeners();
138
139     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
140 }
141
142 // Operation for querying OpenGL parameters. This must be done in a
143 // valid OpenGL context, potentially in another thread.
144 namespace
145 {
146 struct GeneralInitOperation : public GraphicsContextOperation
147 {
148     GeneralInitOperation()
149         : GraphicsContextOperation(std::string("General init"))
150     {
151     }
152     void run(osg::GraphicsContext* gc)
153     {
154         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
155         
156         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
157         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
158         
159         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
160         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
161         
162         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
163         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
164
165         GLint tmp;
166         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
167         simRendering->setIntValue("max-texture-size", tmp);
168
169         glGetIntegerv( GL_DEPTH_BITS, &tmp );
170         simRendering->setIntValue("depth-buffer-bits", tmp);
171     }
172 };
173
174 }
175
176 // This is the top level master main function that is registered as
177 // our idle function
178
179 // The first few passes take care of initialization things (a couple
180 // per pass) and once everything has been initialized fgMainLoop from
181 // then on.
182
183 static void fgIdleFunction ( void ) {
184     static osg::ref_ptr<GeneralInitOperation> genOp;
185     if ( idle_state == 0 ) {
186         idle_state++;
187         // Pick some window on which to do queries.
188         // XXX Perhaps all this graphics initialization code should be
189         // moved to renderer.cxx?
190         genOp = new GeneralInitOperation;
191         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
192         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
193         osg::GraphicsContext* gc = 0;
194         if (guiCamera)
195             gc = guiCamera->getGraphicsContext();
196         if (gc) {
197             gc->add(genOp.get());
198         } else {
199             wsa->windows[0]->gc->add(genOp.get());
200         }
201         guiStartInit(gc);
202     } else if ( idle_state == 1 ) {
203         if (genOp.valid()) {
204             if (!genOp->isFinished())
205                 return;
206             genOp = 0;
207         }
208         if (!guiFinishInit())
209             return;
210         idle_state++;
211         fgSplashProgress("loading aircraft list");
212
213     } else if ( idle_state == 2 ) {
214         idle_state++;
215         fgSplashProgress("loading navigation data");
216
217     } else if ( idle_state == 3 ) {
218         idle_state++;
219         fgInitNav();
220
221         fgSplashProgress("initializing scenery system");
222
223     } else if ( idle_state == 4 ) {
224         idle_state++;
225         // based on the requested presets, calculate the true starting
226         // lon, lat
227         fgInitPosition();
228         fgInitTowerLocationListener();
229
230         TimeManager* t = new TimeManager;
231         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
232         t->init(); // need to init now, not during initSubsystems
233         
234         // Do some quick general initializations
235         if( !fgInitGeneral()) {
236             SG_LOG( SG_GENERAL, SG_ALERT,
237                 "General initialization failed ..." );
238             exit(-1);
239         }
240
241         ////////////////////////////////////////////////////////////////////
242         // Initialize the property-based built-in commands
243         ////////////////////////////////////////////////////////////////////
244         fgInitCommands();
245
246         ////////////////////////////////////////////////////////////////////
247         // Initialize the material manager
248         ////////////////////////////////////////////////////////////////////
249         globals->set_matlib( new SGMaterialLib );
250         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
251         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
252
253         ////////////////////////////////////////////////////////////////////
254         // Initialize the TG scenery subsystem.
255         ////////////////////////////////////////////////////////////////////
256         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
257         globals->add_subsystem("terrasync", terra_sync);
258         globals->set_scenery( new FGScenery );
259         globals->get_scenery()->init();
260         globals->get_scenery()->bind();
261         globals->set_tile_mgr( new FGTileMgr );
262
263         fgSplashProgress("loading aircraft");
264
265     } else if ( idle_state == 5 ) {
266         idle_state++;
267
268         fgSplashProgress("initializing sky elements");
269
270     } else if ( idle_state == 6 ) {
271         idle_state++;
272         
273         // Initialize MagVar model
274         SGMagVar *magvar = new SGMagVar();
275         globals->set_mag( magvar );
276         
277         
278         // kludge to initialize mag compass
279         // (should only be done for in-flight
280         // startup)
281         // update magvar model
282         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
283                                    * SGD_DEGREES_TO_RADIANS,
284                                    fgGetDouble("/position/latitude-deg")
285                                    * SGD_DEGREES_TO_RADIANS,
286                                    fgGetDouble("/position/altitude-ft")
287                                    * SG_FEET_TO_METER,
288                                    globals->get_time_params()->getJD() );
289
290         fgSplashProgress("initializing subsystems");
291
292     } else if ( idle_state == 7 ) {
293         idle_state++;
294         // Initialize audio support
295 #ifdef ENABLE_AUDIO_SUPPORT
296
297         // Start the intro music
298         if ( fgGetBool("/sim/startup/intro-music") ) {
299             SGPath mp3file( globals->get_fg_root() );
300             mp3file.append( "Sounds/intro.mp3" );
301
302             SG_LOG( SG_GENERAL, SG_INFO,
303                 "Starting intro music: " << mp3file.str() );
304
305 # if defined( __CYGWIN__ )
306             string command = "start /m `cygpath -w " + mp3file.str() + "`";
307 # elif defined( _WIN32 )
308             string command = "start /m " + mp3file.str();
309 # else
310             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
311 # endif
312
313             if (0 != system ( command.c_str() ))
314             {
315                 SG_LOG( SG_SOUND, SG_WARN,
316                     "Failed to play mp3 file " << mp3file.str() << ". Maybe mp3 player is not installed." );
317             }
318         }
319 #endif
320         // This is the top level init routine which calls all the
321         // other subsystem initialization routines.  If you are adding
322         // a subsystem to flightgear, its initialization call should be
323         // located in this routine.
324         if( !fgInitSubsystems()) {
325             SG_LOG( SG_GENERAL, SG_ALERT,
326                 "Subsystem initialization failed ..." );
327             exit(-1);
328         }
329
330         // Torsten Dreyer:
331         // ugly hack for automatic runway selection on startup based on
332         // metar data. Makes startup.nas obsolete and guarantees the same
333         // runway selection as for AI traffic. However, this code belongs to
334         // somewhere(?) else - if I only new where...
335         if( true == fgGetBool( "/environment/metar/valid" ) ) {
336             SG_LOG(SG_ENVIRONMENT, SG_INFO,
337                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
338             // the realwx_ctrl fetches metar in the foreground on init,
339             // If it was able to fetch a metar or one was given on the commandline,
340             // the valid flag is set here, otherwise it is false
341             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
342             string apt = fgGetString( "/sim/startup/options/airport" );
343             string rwy = fgGetString( "/sim/startup/options/runway" );
344             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
345             string parkpos = fgGetString( "/sim/presets/parkpos" );
346             bool onground = fgGetBool( "/sim/presets/onground", false );
347             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
348             // the other logic is taken from former startup.nas
349             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
350                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
351                 fgSetPosFromAirportIDandHdg( apt, hdg );
352             }
353         } else {
354             SG_LOG(SG_ENVIRONMENT, SG_INFO,
355                 "No METAR available to pick active runway" );
356         }
357
358         fgSplashProgress("initializing graphics engine");
359
360     } else if ( idle_state == 8 ) {
361         idle_state = 1000;
362         
363         // setup OpenGL view parameters
364         globals->get_renderer()->setupView();
365
366         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
367                                          fgGetInt("/sim/startup/ysize") );
368
369         int session = fgGetInt("/sim/session",0);
370         session++;
371         fgSetInt("/sim/session",session);
372     }
373
374     if ( idle_state == 1000 ) {
375         // We've finished all our initialization steps, from now on we
376         // run the main loop.
377         fgSetBool("sim/sceneryloaded", false);
378         fgRegisterIdleHandler( fgMainLoop );
379     }
380 }
381
382 static void upper_case_property(const char *name)
383 {
384     using namespace simgear;
385     SGPropertyNode *p = fgGetNode(name, false);
386     if (!p) {
387         p = fgGetNode(name, true);
388         p->setStringValue("");
389     } else {
390         props::Type t = p->getType();
391         if (t == props::NONE || t == props::UNSPECIFIED)
392             p->setStringValue("");
393         else
394             assert(t == props::STRING);
395     }
396     p->addChangeListener(new FGMakeUpperCase);
397 }
398
399
400 // Main top level initialization
401 int fgMainInit( int argc, char **argv ) {
402
403     // set default log levels
404     sglog().setLogLevels( SG_ALL, SG_ALERT );
405
406     string version;
407 #ifdef FLIGHTGEAR_VERSION
408     version = FLIGHTGEAR_VERSION;
409 #else
410     version = "unknown version";
411 #endif
412     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
413             << version );
414     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
415
416     // Allocate global data structures.  This needs to happen before
417     // we parse command line options
418
419     globals = new FGGlobals;
420
421     // seed the random number generator
422     sg_srandom_time();
423
424     FGControls *controls = new FGControls;
425     globals->set_controls( controls );
426
427     string_list *col = new string_list;
428     globals->set_channel_options_list( col );
429
430     fgValidatePath("", false);  // initialize static variables
431     upper_case_property("/sim/presets/airport-id");
432     upper_case_property("/sim/presets/runway");
433     upper_case_property("/sim/tower/airport-id");
434     upper_case_property("/autopilot/route-manager/input");
435
436     // Load the configuration parameters.  (Command line options
437     // override config file options.  Config file options override
438     // defaults.)
439     if ( !fgInitConfig(argc, argv) ) {
440       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
441       exit(-1);
442     }
443
444     // Initialize the Window/Graphics environment.
445     fgOSInit(&argc, argv);
446     _bootstrap_OSInit++;
447
448     fgRegisterIdleHandler( &fgIdleFunction );
449
450     // Initialize sockets (WinSock needs this)
451     simgear::Socket::initSockets();
452
453     // Clouds3D requires an alpha channel
454     fgOSOpenWindow(true /* request stencil buffer */);
455
456     // Initialize the splash screen right away
457     fntInit();
458     fgSplashInit();
459
460     // pass control off to the master event handler
461     int result = fgOSMainLoop();
462     
463     // clean up here; ensure we null globals to avoid
464     // confusing the atexit() handler
465     delete globals;
466     globals = NULL;
467     
468     return result;
469 }