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