]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
8bbb456484a55e425a53f01d23e0f6cc77abd3f3
[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 #include <iostream>
31
32 #include <osg/Camera>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
35
36 // Class references
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/material/matlib.hxx>
39 #include <simgear/props/AtomicChangeListener.hxx>
40 #include <simgear/props/props.hxx>
41 #include <simgear/timing/sg_time.hxx>
42 #include <simgear/io/raw_socket.hxx>
43 #include <simgear/scene/tsync/terrasync.hxx>
44 #include <simgear/math/SGMath.hxx>
45 #include <simgear/math/sg_random.h>
46
47 #include <Model/panelnode.hxx>
48 #include <Scenery/scenery.hxx>
49 #include <Scenery/tilemgr.hxx>
50 #include <Sound/soundmanager.hxx>
51 #include <Time/TimeManager.hxx>
52 #include <GUI/gui.h>
53 #include <Viewer/splash.hxx>
54 #include <Viewer/renderer.hxx>
55 #include <Navaids/NavDataCache.hxx>
56
57 #include "fg_commands.hxx"
58 #include "fg_io.hxx"
59 #include "main.hxx"
60 #include "util.hxx"
61 #include "fg_init.hxx"
62 #include "fg_os.hxx"
63 #include "fg_props.hxx"
64 #include "positioninit.hxx"
65
66 using namespace flightgear;
67
68 using std::cerr;
69 using std::vector;
70
71 // The atexit() function handler should know when the graphical subsystem
72 // is initialized.
73 extern int _bootstrap_OSInit;
74
75 // What should we do when we have nothing else to do?  Let's get ready
76 // for the next move and update the display?
77 static void fgMainLoop( void )
78 {
79     static SGPropertyNode_ptr frame_signal
80         = fgGetNode("/sim/signals/frame", true);
81
82     frame_signal->fireValueChanged();
83
84     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
85     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
86
87     // compute simulated time (allowing for pause, warp, etc) and
88     // real elapsed time
89     double sim_dt, real_dt;
90     static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
91     timeMgr->computeTimeDeltas(sim_dt, real_dt);
92
93     // update all subsystems
94     globals->get_subsystem_mgr()->update(sim_dt);
95
96     simgear::AtomicChangeListener::fireChangeListeners();
97
98     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
99 }
100
101
102 // This is the top level master main function that is registered as
103 // our idle function
104
105 // The first few passes take care of initialization things (a couple
106 // per pass) and once everything has been initialized fgMainLoop from
107 // then on.
108
109 static void fgIdleFunction ( void ) {
110     // Specify our current idle function state.  This is used to run all
111     // our initializations out of the idle callback so that we can get a
112     // splash screen up and running right away.
113     static int idle_state = 0;
114   
115     if ( idle_state == 0 ) {
116         if (guiInit())
117         {
118             idle_state+=2;
119             fgSplashProgress("loading-aircraft-list");
120         }
121
122     } else if ( idle_state == 2 ) {
123         idle_state++;
124         fgSplashProgress("loading-nav-dat");
125
126     } else if ( idle_state == 3 ) {
127         
128         bool done = fgInitNav();
129         if (done) {
130           ++idle_state;
131           fgSplashProgress("init-scenery");
132         } else {
133           fgSplashProgress("loading-nav-dat");
134         }
135       
136     } else if ( idle_state == 4 ) {
137         idle_state+=2;
138         // based on the requested presets, calculate the true starting
139         // lon, lat
140         flightgear::initPosition();
141         flightgear::initTowerLocationListener();
142
143         TimeManager* t = new TimeManager;
144         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
145         t->init(); // need to init now, not during initSubsystems
146         
147         // Do some quick general initializations
148         if( !fgInitGeneral()) {
149             SG_LOG( SG_GENERAL, SG_ALERT,
150                 "General initialization failed ..." );
151             exit(-1);
152         }
153
154         ////////////////////////////////////////////////////////////////////
155         // Initialize the property-based built-in commands
156         ////////////////////////////////////////////////////////////////////
157         fgInitCommands();
158
159         ////////////////////////////////////////////////////////////////////
160         // Initialize the material manager
161         ////////////////////////////////////////////////////////////////////
162         globals->set_matlib( new SGMaterialLib );
163         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
164         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
165
166         ////////////////////////////////////////////////////////////////////
167         // Initialize the TG scenery subsystem.
168         ////////////////////////////////////////////////////////////////////
169         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
170         globals->add_subsystem("terrasync", terra_sync);
171         globals->set_scenery( new FGScenery );
172         globals->get_scenery()->init();
173         globals->get_scenery()->bind();
174         globals->set_tile_mgr( new FGTileMgr );
175
176         fgSplashProgress("loading-aircraft");
177
178     } else if ( idle_state == 6 ) {
179         idle_state++;
180         fgSplashProgress("creating-subsystems");
181
182     } else if ( idle_state == 7 ) {
183         idle_state++;
184         SGTimeStamp st;
185         st.stamp();
186         fgCreateSubsystems();
187         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
188         fgSplashProgress("binding-subsystems");
189       
190     } else if ( idle_state == 8 ) {
191         idle_state++;
192         SGTimeStamp st;
193         st.stamp();
194         globals->get_subsystem_mgr()->bind();
195         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
196
197         fgSplashProgress("init-subsystems");
198     } else if ( idle_state == 9 ) {
199         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
200         if ( status == SGSubsystem::INIT_DONE) {
201           ++idle_state;
202           fgSplashProgress("finishing-subsystems");
203         } else {
204           fgSplashProgress("init-subsystems");
205         }
206       
207     } else if ( idle_state == 10 ) {
208         idle_state = 900;
209         fgPostInitSubsystems();
210       
211               // Torsten Dreyer:
212         // ugly hack for automatic runway selection on startup based on
213         // metar data. Makes startup.nas obsolete and guarantees the same
214         // runway selection as for AI traffic. However, this code belongs to
215         // somewhere(?) else - if I only new where...
216         if( true == fgGetBool( "/environment/metar/valid" ) ) {
217             SG_LOG(SG_ENVIRONMENT, SG_INFO,
218                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
219             // the realwx_ctrl fetches metar in the foreground on init,
220             // If it was able to fetch a metar or one was given on the commandline,
221             // the valid flag is set here, otherwise it is false
222             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
223             string apt = fgGetString( "/sim/startup/options/airport" );
224             string rwy = fgGetString( "/sim/startup/options/runway" );
225             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
226             string parkpos = fgGetString( "/sim/presets/parkpos" );
227             bool onground = fgGetBool( "/sim/presets/onground", false );
228             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
229             // the other logic is taken from former startup.nas
230             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
231                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
232                 flightgear::setPosFromAirportIDandHdg( apt, hdg );
233             }
234         } else {
235             SG_LOG(SG_ENVIRONMENT, SG_INFO,
236                 "No METAR available to pick active runway" );
237         }
238
239         fgSplashProgress("init-graphics");
240
241     } else if ( idle_state == 900 ) {
242         idle_state = 1000;
243         
244         // setup OpenGL view parameters
245         globals->get_renderer()->setupView();
246
247         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
248                                          fgGetInt("/sim/startup/ysize") );
249
250         int session = fgGetInt("/sim/session",0);
251         session++;
252         fgSetInt("/sim/session",session);
253     }
254
255     if ( idle_state == 1000 ) {
256         // We've finished all our initialization steps, from now on we
257         // run the main loop.
258         fgSetBool("sim/sceneryloaded", false);
259         fgRegisterIdleHandler( fgMainLoop );
260     }
261 }
262
263 static void upper_case_property(const char *name)
264 {
265     using namespace simgear;
266     SGPropertyNode *p = fgGetNode(name, false);
267     if (!p) {
268         p = fgGetNode(name, true);
269         p->setStringValue("");
270     } else {
271         props::Type t = p->getType();
272         if (t == props::NONE || t == props::UNSPECIFIED)
273             p->setStringValue("");
274         else
275             assert(t == props::STRING);
276     }
277     p->addChangeListener(new FGMakeUpperCase);
278 }
279
280
281 // Main top level initialization
282 int fgMainInit( int argc, char **argv ) {
283
284     // set default log levels
285     sglog().setLogLevels( SG_ALL, SG_ALERT );
286
287     string version;
288 #ifdef FLIGHTGEAR_VERSION
289     version = FLIGHTGEAR_VERSION;
290 #else
291     version = "unknown version";
292 #endif
293     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
294             << version );
295     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
296
297     // Allocate global data structures.  This needs to happen before
298     // we parse command line options
299
300     globals = new FGGlobals;
301
302     // seed the random number generator
303     sg_srandom_time();
304
305     string_list *col = new string_list;
306     globals->set_channel_options_list( col );
307
308     fgValidatePath("", false);  // initialize static variables
309     upper_case_property("/sim/presets/airport-id");
310     upper_case_property("/sim/presets/runway");
311     upper_case_property("/sim/tower/airport-id");
312     upper_case_property("/autopilot/route-manager/input");
313
314     // Load the configuration parameters.  (Command line options
315     // override config file options.  Config file options override
316     // defaults.)
317     if ( !fgInitConfig(argc, argv) ) {
318       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
319       exit(-1);
320     }
321
322     // Initialize the Window/Graphics environment.
323     fgOSInit(&argc, argv);
324     _bootstrap_OSInit++;
325
326     fgRegisterIdleHandler( &fgIdleFunction );
327
328     // Initialize sockets (WinSock needs this)
329     simgear::Socket::initSockets();
330
331     // Clouds3D requires an alpha channel
332     fgOSOpenWindow(true /* request stencil buffer */);
333
334     // Initialize the splash screen right away
335     fntInit();
336     fgSplashInit();
337
338     // pass control off to the master event handler
339     int result = fgOSMainLoop();
340     
341     // clean up here; ensure we null globals to avoid
342     // confusing the atexit() handler
343     delete globals;
344     globals = NULL;
345     
346     // delete the NavCache here. This will cause the destruction of many cached
347     // objects (eg, airports, navaids, runways).
348     delete flightgear::NavDataCache::instance();
349   
350     return result;
351 }