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