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>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
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>
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>
53 #include <Viewer/splash.hxx>
54 #include <Viewer/renderer.hxx>
55 #include <Navaids/NavDataCache.hxx>
57 #include "fg_commands.hxx"
61 #include "fg_init.hxx"
63 #include "fg_props.hxx"
64 #include "positioninit.hxx"
66 using namespace flightgear;
71 // The atexit() function handler should know when the graphical subsystem
73 extern int _bootstrap_OSInit;
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 )
79 static SGPropertyNode_ptr frame_signal
80 = fgGetNode("/sim/signals/frame", true);
82 frame_signal->fireValueChanged();
84 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
85 SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
87 // compute simulated time (allowing for pause, warp, etc) and
89 double sim_dt, real_dt;
90 static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
91 timeMgr->computeTimeDeltas(sim_dt, real_dt);
93 // update all subsystems
94 globals->get_subsystem_mgr()->update(sim_dt);
96 simgear::AtomicChangeListener::fireChangeListeners();
98 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
102 // This is the top level master main function that is registered as
105 // The first few passes take care of initialization things (a couple
106 // per pass) and once everything has been initialized fgMainLoop from
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;
115 if ( idle_state == 0 ) {
119 fgSplashProgress("loading-aircraft-list");
122 } else if ( idle_state == 2 ) {
124 fgSplashProgress("loading-nav-dat");
126 } else if ( idle_state == 3 ) {
128 bool done = fgInitNav();
131 fgSplashProgress("init-scenery");
133 fgSplashProgress("loading-nav-dat");
136 } else if ( idle_state == 4 ) {
138 // based on the requested presets, calculate the true starting
140 flightgear::initPosition();
141 flightgear::initTowerLocationListener();
143 TimeManager* t = new TimeManager;
144 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
145 t->init(); // need to init now, not during initSubsystems
147 // Do some quick general initializations
148 if( !fgInitGeneral()) {
149 SG_LOG( SG_GENERAL, SG_ALERT,
150 "General initialization failed ..." );
154 ////////////////////////////////////////////////////////////////////
155 // Initialize the property-based built-in commands
156 ////////////////////////////////////////////////////////////////////
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);
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 );
176 fgSplashProgress("loading-aircraft");
178 } else if ( idle_state == 6 ) {
180 fgSplashProgress("creating-subsystems");
182 } else if ( idle_state == 7 ) {
186 fgCreateSubsystems();
187 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
188 fgSplashProgress("binding-subsystems");
190 } else if ( idle_state == 8 ) {
194 globals->get_subsystem_mgr()->bind();
195 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
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) {
202 fgSplashProgress("finishing-subsystems");
204 fgSplashProgress("init-subsystems");
207 } else if ( idle_state == 10 ) {
209 fgPostInitSubsystems();
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 );
235 SG_LOG(SG_ENVIRONMENT, SG_INFO,
236 "No METAR available to pick active runway" );
239 fgSplashProgress("init-graphics");
241 } else if ( idle_state == 900 ) {
244 // setup OpenGL view parameters
245 globals->get_renderer()->setupView();
247 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
248 fgGetInt("/sim/startup/ysize") );
250 int session = fgGetInt("/sim/session",0);
252 fgSetInt("/sim/session",session);
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 );
263 static void upper_case_property(const char *name)
265 using namespace simgear;
266 SGPropertyNode *p = fgGetNode(name, false);
268 p = fgGetNode(name, true);
269 p->setStringValue("");
271 props::Type t = p->getType();
272 if (t == props::NONE || t == props::UNSPECIFIED)
273 p->setStringValue("");
275 assert(t == props::STRING);
277 p->addChangeListener(new FGMakeUpperCase);
281 // Main top level initialization
282 int fgMainInit( int argc, char **argv ) {
284 // set default log levels
285 sglog().setLogLevels( SG_ALL, SG_ALERT );
288 #ifdef FLIGHTGEAR_VERSION
289 version = FLIGHTGEAR_VERSION;
291 version = "unknown version";
293 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
295 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
297 // Allocate global data structures. This needs to happen before
298 // we parse command line options
300 globals = new FGGlobals;
302 // seed the random number generator
305 string_list *col = new string_list;
306 globals->set_channel_options_list( col );
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");
314 // Load the configuration parameters. (Command line options
315 // override config file options. Config file options override
317 if ( !fgInitConfig(argc, argv) ) {
318 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
322 // Initialize the Window/Graphics environment.
323 fgOSInit(&argc, argv);
326 fgRegisterIdleHandler( &fgIdleFunction );
328 // Initialize sockets (WinSock needs this)
329 simgear::Socket::initSockets();
331 // Clouds3D requires an alpha channel
332 fgOSOpenWindow(true /* request stencil buffer */);
334 // Initialize the splash screen right away
338 // pass control off to the master event handler
339 int result = fgOSMainLoop();
341 // clean up here; ensure we null globals to avoid
342 // confusing the atexit() handler
346 // delete the NavCache here. This will cause the destruction of many cached
347 // objects (eg, airports, navaids, runways).
348 delete flightgear::NavDataCache::instance();