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