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