]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Bugfix: remove the (totally broken) skyblend option
[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/scene/material/Effect.hxx>
41 #include <simgear/props/AtomicChangeListener.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/timing/sg_time.hxx>
44 #include <simgear/io/raw_socket.hxx>
45 #include <simgear/scene/tsync/terrasync.hxx>
46 #include <simgear/math/SGMath.hxx>
47 #include <simgear/math/sg_random.h>
48
49 #include <Model/panelnode.hxx>
50 #include <Scenery/scenery.hxx>
51 #include <Scenery/tilemgr.hxx>
52 #include <Sound/soundmanager.hxx>
53 #include <Time/TimeManager.hxx>
54 #include <GUI/gui.h>
55 #include <Viewer/splash.hxx>
56 #include <Viewer/renderer.hxx>
57 #include <Viewer/WindowSystemAdapter.hxx>
58 #include <Navaids/NavDataCache.hxx>
59
60 #include "fg_commands.hxx"
61 #include "fg_io.hxx"
62 #include "main.hxx"
63 #include "util.hxx"
64 #include "fg_init.hxx"
65 #include "fg_os.hxx"
66 #include "fg_props.hxx"
67 #include "positioninit.hxx"
68 #include "screensaver_control.hxx"
69 #include "subsystemFactory.hxx"
70 #include "options.hxx"
71
72
73 using namespace flightgear;
74
75 using std::cerr;
76 using std::vector;
77
78 // The atexit() function handler should know when the graphical subsystem
79 // is initialized.
80 extern int _bootstrap_OSInit;
81
82 static SGPropertyNode_ptr frame_signal;
83 static TimeManager* timeMgr;
84
85 // What should we do when we have nothing else to do?  Let's get ready
86 // for the next move and update the display?
87 static void fgMainLoop( void )
88 {
89     frame_signal->fireValueChanged();
90
91     // compute simulated time (allowing for pause, warp, etc) and
92     // real elapsed time
93     double sim_dt, real_dt;
94     timeMgr->computeTimeDeltas(sim_dt, real_dt);
95
96     // update all subsystems
97     globals->get_subsystem_mgr()->update(sim_dt);
98
99     simgear::AtomicChangeListener::fireChangeListeners();
100 }
101
102 static void initTerrasync()
103 {
104     if (fgGetBool("/sim/fghome-readonly", false)) {
105         return;
106     }
107     
108     // start TerraSync up now, so it can be synchronizing shared models
109     // and airports data in parallel with a nav-cache rebuild.
110     SGPath tsyncCache(globals->get_fg_home());
111     tsyncCache.append("terrasync-cache.xml");
112     
113     // wipe the cache file if requested
114     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
115         SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
116                tsyncCache);
117         if (tsyncCache.exists()) {
118             tsyncCache.remove();
119         }
120     }
121     
122     fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
123     
124     simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
125     terra_sync->setRoot(globals->get_props());
126     globals->add_subsystem("terrasync", terra_sync);
127     
128     terra_sync->bind();
129     terra_sync->init();
130     
131     // add the terrasync root as a data path so data can be retrieved from it
132     std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
133     globals->append_data_path(terraSyncDir);
134 }
135
136 static void registerMainLoop()
137 {
138     // stash current frame signal property
139     frame_signal = fgGetNode("/sim/signals/frame", true);
140     timeMgr = (TimeManager*) globals->get_subsystem("time");
141     fgRegisterIdleHandler( fgMainLoop );
142 }
143
144 // This is the top level master main function that is registered as
145 // our idle function
146
147 // The first few passes take care of initialization things (a couple
148 // per pass) and once everything has been initialized fgMainLoop from
149 // then on.
150
151 static int idle_state = 0;
152
153 static void fgIdleFunction ( void ) {
154     // Specify our current idle function state.  This is used to run all
155     // our initializations out of the idle callback so that we can get a
156     // splash screen up and running right away.
157     
158     if ( idle_state == 0 ) {
159         if (guiInit())
160         {
161             idle_state+=2;
162             fgSplashProgress("loading-aircraft-list");
163         }
164
165     } else if ( idle_state == 2 ) {
166         initTerrasync();
167         idle_state++;
168         fgSplashProgress("loading-nav-dat");
169
170     } else if ( idle_state == 3 ) {
171         
172         bool done = fgInitNav();
173         if (done) {
174           ++idle_state;
175           fgSplashProgress("init-scenery");
176         } else {
177           fgSplashProgress("loading-nav-dat");
178         }
179       
180     } else if ( idle_state == 4 ) {
181         idle_state++;
182
183         TimeManager* t = new TimeManager;
184         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
185         
186         // Do some quick general initializations
187         if( !fgInitGeneral()) {
188             throw sg_exception("General initialization failed");
189         }
190
191         ////////////////////////////////////////////////////////////////////
192         // Initialize the property-based built-in commands
193         ////////////////////////////////////////////////////////////////////
194         fgInitCommands();
195
196         flightgear::registerSubsystemCommands(globals->get_commands());
197
198         ////////////////////////////////////////////////////////////////////
199         // Initialize the material manager
200         ////////////////////////////////////////////////////////////////////
201         globals->set_matlib( new SGMaterialLib );
202         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
203  
204     } else if (( idle_state == 5 ) || (idle_state == 2005)) {
205         idle_state+=2;
206         flightgear::initPosition();
207         flightgear::initTowerLocationListener();
208         
209         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
210         
211         TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
212         timeManager->init();
213         
214         ////////////////////////////////////////////////////////////////////
215         // Initialize the TG scenery subsystem.
216         ////////////////////////////////////////////////////////////////////
217         
218         globals->set_scenery( new FGScenery );
219         globals->get_scenery()->init();
220         globals->get_scenery()->bind();
221         globals->set_tile_mgr( new FGTileMgr );
222         
223         fgSplashProgress("creating-subsystems");
224     } else if (( idle_state == 7 ) || (idle_state == 2007)) {
225         bool isReset = (idle_state == 2007);
226         idle_state = 8; // from the next state on, reset & startup are identical
227         SGTimeStamp st;
228         st.stamp();
229         fgCreateSubsystems(isReset);
230         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
231         fgSplashProgress("binding-subsystems");
232       
233     } else if ( idle_state == 8 ) {
234         idle_state++;
235         SGTimeStamp st;
236         st.stamp();
237         globals->get_subsystem_mgr()->bind();
238         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
239
240         fgSplashProgress("init-subsystems");
241     } else if ( idle_state == 9 ) {
242         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
243         if ( status == SGSubsystem::INIT_DONE) {
244           ++idle_state;
245           fgSplashProgress("finishing-subsystems");
246         } else {
247           fgSplashProgress("init-subsystems");
248         }
249       
250     } else if ( idle_state == 10 ) {
251         idle_state = 900;
252         fgPostInitSubsystems();
253         fgSplashProgress("finalize-position");
254     } else if ( idle_state == 900 ) {
255         idle_state = 1000;
256         
257         // setup OpenGL view parameters
258         globals->get_renderer()->setupView();
259
260         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
261                                          fgGetInt("/sim/startup/ysize") );
262         WindowSystemAdapter::getWSA()->windows[0]->gc->add(
263           new simgear::canvas::VGInitOperation()
264         );
265
266         int session = fgGetInt("/sim/session",0);
267         session++;
268         fgSetInt("/sim/session",session);
269     }
270
271     if ( idle_state == 1000 ) {
272         // We've finished all our initialization steps, from now on we
273         // run the main loop.
274         fgSetBool("sim/sceneryloaded", false);
275         registerMainLoop();
276     }
277     
278     if ( idle_state == 2000 ) {
279         fgStartNewReset();
280         idle_state = 2005;
281     }
282 }
283
284 void fgResetIdleState()
285 {
286     idle_state = 2000;
287     fgRegisterIdleHandler( &fgIdleFunction );
288 }
289
290
291 static void upper_case_property(const char *name)
292 {
293     using namespace simgear;
294     SGPropertyNode *p = fgGetNode(name, false);
295     if (!p) {
296         p = fgGetNode(name, true);
297         p->setStringValue("");
298     } else {
299         props::Type t = p->getType();
300         if (t == props::NONE || t == props::UNSPECIFIED)
301             p->setStringValue("");
302         else
303             assert(t == props::STRING);
304     }
305     SGPropertyChangeListener* muc = new FGMakeUpperCase;
306     globals->addListenerToCleanup(muc);
307     p->addChangeListener(muc);
308 }
309
310 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
311 // for the details of this.
312 static void ATIScreenSizeHack()
313 {
314     osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
315     hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
316     int prettyMuchAnyInt = 1;
317     hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
318     globals->get_renderer()->addCamera(hackCam, false);
319 }
320
321 // Propose NVIDIA Optimus to use high-end GPU
322 #if defined(SG_WINDOWS)
323 extern "C" {
324     _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
325 }
326 #endif
327
328 static void logToFile()
329 {
330     SGPath logPath = globals->get_fg_home();
331     logPath.append("fgfs.log");
332     if (logPath.exists()) {
333         SGPath prevLogPath = globals->get_fg_home();
334         prevLogPath.append("fgfs_0.log");
335         logPath.rename(prevLogPath);
336         // bit strange, we need to restore the correct value of logPath now
337         logPath = globals->get_fg_home();
338         logPath.append("fgfs.log");
339     }
340     sglog().logToFile(logPath, SG_ALL, SG_INFO);
341 }
342
343 // Main top level initialization
344 int fgMainInit( int argc, char **argv ) {
345
346     // set default log levels
347     sglog().setLogLevels( SG_ALL, SG_ALERT );
348
349     globals = new FGGlobals;
350     if (!fgInitHome()) {
351         return EXIT_FAILURE;
352     }
353     
354     if (!fgGetBool("/sim/fghome-readonly")) {
355         // now home is initialised, we can log to a file inside it
356         logToFile();
357     }
358     
359     std::string version;
360 #ifdef FLIGHTGEAR_VERSION
361     version = FLIGHTGEAR_VERSION;
362 #else
363     version = "unknown version";
364 #endif
365     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
366             << version );
367     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
368
369     // Allocate global data structures.  This needs to happen before
370     // we parse command line options
371
372     
373     
374     // seed the random number generator
375     sg_srandom_time();
376
377     string_list *col = new string_list;
378     globals->set_channel_options_list( col );
379
380     fgValidatePath("", false);  // initialize static variables
381     upper_case_property("/sim/presets/airport-id");
382     upper_case_property("/sim/presets/runway");
383     upper_case_property("/sim/tower/airport-id");
384     upper_case_property("/autopilot/route-manager/input");
385
386     // Load the configuration parameters.  (Command line options
387     // override config file options.  Config file options override
388     // defaults.)
389     int configResult = fgInitConfig(argc, argv, false);
390     if (configResult == flightgear::FG_OPTIONS_ERROR) {
391         return EXIT_FAILURE;
392     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
393         return EXIT_SUCCESS;
394     }
395     
396     configResult = fgInitAircraft(false);
397     if (configResult == flightgear::FG_OPTIONS_ERROR) {
398         return EXIT_FAILURE;
399     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
400         return EXIT_SUCCESS;
401     }
402     
403     configResult = flightgear::Options::sharedInstance()->processOptions();
404     if (configResult == flightgear::FG_OPTIONS_ERROR) {
405         return EXIT_FAILURE;
406     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
407         return EXIT_SUCCESS;
408     }
409     
410     // Initialize the Window/Graphics environment.
411     fgOSInit(&argc, argv);
412     _bootstrap_OSInit++;
413
414     fgRegisterIdleHandler( &fgIdleFunction );
415
416     // Initialize sockets (WinSock needs this)
417     simgear::Socket::initSockets();
418
419     // Clouds3D requires an alpha channel
420     fgOSOpenWindow(true /* request stencil buffer */);
421     fgOSResetProperties();
422     
423     // Initialize the splash screen right away
424     fntInit();
425     fgSplashInit();
426
427     if (fgGetBool("/sim/ati-viewport-hack", true)) {
428         SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
429         ATIScreenSizeHack();
430     }
431     
432     fgOutputSettings();
433     
434     //try to disable the screensaver
435     fgOSDisableScreensaver();
436     
437     // pass control off to the master event handler
438     int result = fgOSMainLoop();
439     frame_signal.clear();
440     fgOSCloseWindow();
441     
442     simgear::clearEffectCache();
443     
444     // clean up here; ensure we null globals to avoid
445     // confusing the atexit() handler
446     delete globals;
447     globals = NULL;
448     
449     // delete the NavCache here. This will cause the destruction of many cached
450     // objects (eg, airports, navaids, runways).
451     delete flightgear::NavDataCache::instance();
452   
453     return result;
454 }