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