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