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