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