]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
0cae08de9a7528c506e885d8ce0228beb00a692d
[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 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <plib/netSocket.h>
38
39 #include <osg/Camera>
40 #include <osg/GraphicsContext>
41 #include <osgDB/Registry>
42
43 // Class references
44 #include <simgear/scene/model/modellib.hxx>
45 #include <simgear/scene/material/matlib.hxx>
46 #include <simgear/scene/model/animation.hxx>
47 #include <simgear/scene/sky/sky.hxx>
48 #include <simgear/structure/event_mgr.hxx>
49 #include <simgear/props/AtomicChangeListener.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/math/sg_random.h>
53
54 #include <Time/light.hxx>
55 #include <Include/general.hxx>
56 #include <Aircraft/replay.hxx>
57 #include <Cockpit/cockpit.hxx>
58 #include <Cockpit/hud.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/modelmgr.hxx>
61 #include <Model/acmodel.hxx>
62 #include <Scenery/scenery.hxx>
63 #include <Scenery/tilemgr.hxx>
64 #include <Sound/fg_fx.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <Sound/fg_fx.hxx>
68 #include <ATCDCL/ATCmgr.hxx>
69 #include <Time/tmp.hxx>
70 #include <Environment/environment_mgr.hxx>
71 #include <Environment/ephemeris.hxx>
72 #include <GUI/new_gui.hxx>
73 #include <MultiPlayer/multiplaymgr.hxx>
74
75 #include "CameraGroup.hxx"
76 #include "fg_commands.hxx"
77 #include "fg_io.hxx"
78 #include "renderer.hxx"
79 #include "splash.hxx"
80 #include "main.hxx"
81 #include "util.hxx"
82 #include "fg_init.hxx"
83 #include "fg_os.hxx"
84 #include "WindowSystemAdapter.hxx"
85 #include <Main/viewer.hxx>
86
87 static double real_delta_time_sec = 0.0;
88 double delta_time_sec = 0.0;
89
90 using namespace flightgear;
91
92 using std::cerr;
93
94 // This is a record containing a bit of global housekeeping information
95 FGGeneral general;
96
97 // Specify our current idle function state.  This is used to run all
98 // our initializations out of the idle callback so that we can get a
99 // splash screen up and running right away.
100 int idle_state = 0;
101 long global_multi_loop;
102
103 SGTimeStamp last_time_stamp;
104 SGTimeStamp current_time_stamp;
105
106 void fgInitSoundManager();
107 void fgSetNewSoundDevice(const char *);
108
109 // The atexit() function handler should know when the graphical subsystem
110 // is initialized.
111 extern int _bootstrap_OSInit;
112
113 // What should we do when we have nothing else to do?  Let's get ready
114 // for the next move and update the display?
115 static void fgMainLoop( void ) {
116     int model_hz = fgGetInt("/sim/model-hz");
117
118     static SGConstPropertyNode_ptr longitude
119         = fgGetNode("/position/longitude-deg");
120     static SGConstPropertyNode_ptr latitude
121         = fgGetNode("/position/latitude-deg");
122     static SGConstPropertyNode_ptr altitude
123         = fgGetNode("/position/altitude-ft");
124     static SGConstPropertyNode_ptr vn_fps
125         = fgGetNode("/velocities/speed-north-fps");
126     static SGConstPropertyNode_ptr ve_fps
127         = fgGetNode("/velocities/speed-east-fps");
128     static SGConstPropertyNode_ptr vd_fps
129         = fgGetNode("/velocities/speed-down-fps");
130     static SGConstPropertyNode_ptr clock_freeze
131         = fgGetNode("/sim/freeze/clock", true);
132     static SGConstPropertyNode_ptr cur_time_override
133         = fgGetNode("/sim/time/cur-time-override", true);
134     static SGConstPropertyNode_ptr max_simtime_per_frame
135         = fgGetNode("/sim/max-simtime-per-frame", true);
136     static SGPropertyNode_ptr frame_signal
137         = fgGetNode("/sim/signals/frame", true);
138
139     frame_signal->fireValueChanged();
140     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
141
142     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
143     bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
144
145     // Update the elapsed time.
146     static bool first_time = true;
147     if ( first_time ) {
148         last_time_stamp.stamp();
149         first_time = false;
150     }
151
152     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
153     if ( throttle_hz > 0.0 && !wait_for_scenery ) {
154         // optionally throttle the frame rate (to get consistent frame
155         // rates or reduce cpu usage.
156
157         double frame_us = 1000000.0 / throttle_hz;
158
159 #define FG_SLEEP_BASED_TIMING 1
160 #if defined(FG_SLEEP_BASED_TIMING)
161         // sleep based timing loop.
162         //
163         // Calling sleep, even usleep() on linux is less accurate than
164         // we like, but it does free up the cpu for other tasks during
165         // the sleep so it is desirable.  Because of the way sleep()
166         // is implemented in consumer operating systems like windows
167         // and linux, you almost always sleep a little longer than the
168         // requested amount.
169         //
170         // To combat the problem of sleeping too long, we calculate the
171         // desired wait time and shorten it by 2000us (2ms) to avoid
172         // [hopefully] over-sleep'ing.  The 2ms value was arrived at
173         // via experimentation.  We follow this up at the end with a
174         // simple busy-wait loop to get the final pause timing exactly
175         // right.
176         //
177         // Assuming we don't oversleep by more than 2000us, this
178         // should be a reasonable compromise between sleep based
179         // waiting, and busy waiting.
180
181         // sleep() will always overshoot by a bit so undersleep by
182         // 2000us in the hopes of never oversleeping.
183         frame_us -= 2000.0;
184         if ( frame_us < 0.0 ) {
185             frame_us = 0.0;
186         }
187         current_time_stamp.stamp();
188         /* Convert to ms */
189         double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
190         if ( elapsed_us < frame_us ) {
191             double requested_us = frame_us - elapsed_us;
192             ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
193         }
194 #endif
195
196         // busy wait timing loop.
197         //
198         // This yields the most accurate timing.  If the previous
199         // ulMilliSecondSleep() call is omitted this will peg the cpu
200         // (which is just fine if FG is the only app you care about.)
201         current_time_stamp.stamp();
202         SGTimeStamp next_time_stamp = last_time_stamp;
203         next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
204         while ( current_time_stamp < next_time_stamp ) {
205             current_time_stamp.stamp();
206         }
207     } else {
208         // run as fast as the app will go
209         current_time_stamp.stamp();
210     }
211
212     real_delta_time_sec = (current_time_stamp - last_time_stamp).toSecs();
213
214     // Limit the time we need to spend in simulation loops
215     // That means, if the /sim/max-simtime-per-frame value is strictly positive
216     // you can limit the maximum amount of time you will do simulations for
217     // one frame to display. The cpu time spent in simulations code is roughly
218     // at least O(real_delta_time_sec). If this is (due to running debug
219     // builds or valgrind or something different blowing up execution times)
220     // larger than the real time you will no longer get any response
221     // from flightgear. This limits that effect. Just set to property from
222     // your .fgfsrc or commandline ...
223     double dtMax = max_simtime_per_frame->getDoubleValue();
224     if (0 < dtMax && dtMax < real_delta_time_sec)
225         real_delta_time_sec = dtMax;
226
227     SGSubsystemGroup* fdmGroup = 
228       globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
229     fdmGroup->set_fixed_update_time(1.0 / model_hz);
230
231     // round the real time down to a multiple of 1/model-hz.
232     // this way all systems are updated the _same_ amount of dt.
233     static double reminder = 0.0;
234     real_delta_time_sec += reminder;
235     global_multi_loop = long(floor(real_delta_time_sec*model_hz));
236     global_multi_loop = SGMisc<long>::max(0, global_multi_loop);
237     reminder = real_delta_time_sec - double(global_multi_loop)/double(model_hz);
238     real_delta_time_sec = double(global_multi_loop)/double(model_hz);
239
240     if (clock_freeze->getBoolValue() || wait_for_scenery) {
241         delta_time_sec = 0;
242     } else {
243         delta_time_sec = real_delta_time_sec;
244     }
245     last_time_stamp = current_time_stamp;
246     globals->inc_sim_time_sec( delta_time_sec );
247
248     // These are useful, especially for Nasal scripts.
249     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
250     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
251
252 #ifdef FANCY_FRAME_COUNTER
253     int i;
254     double accum;
255 #else
256     static time_t last_time = 0;
257     static int frames = 0;
258 #endif // FANCY_FRAME_COUNTER
259
260     SGTime *t = globals->get_time_params();
261
262     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
263     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
264
265     // update "time"
266     static bool last_clock_freeze = false;
267
268     if ( clock_freeze->getBoolValue() ) {
269         // clock freeze requested
270         if ( cur_time_override->getLongValue() == 0 ) {
271             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
272             globals->set_warp( 0 );
273         }
274     } else {
275         // no clock freeze requested
276         if ( last_clock_freeze == true ) {
277             // clock just unfroze, let's set warp as the difference
278             // between frozen time and current time so we don't get a
279             // time jump (and corresponding sky object and lighting
280             // jump.)
281             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
282             fgSetLong( "/sim/time/cur-time-override", 0 );
283         }
284         if ( globals->get_warp_delta() != 0 ) {
285             globals->inc_warp( globals->get_warp_delta() );
286         }
287     }
288
289     last_clock_freeze = clock_freeze->getBoolValue();
290
291     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
292                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
293                cur_time_override->getLongValue(),
294                globals->get_warp() );
295
296     if (globals->get_warp_delta() != 0) {
297         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
298         l->update( 0.5 );
299     }
300
301     // update magvar model
302     globals->get_mag()->update( longitude->getDoubleValue()
303                                 * SGD_DEGREES_TO_RADIANS,
304                                 latitude->getDoubleValue()
305                                 * SGD_DEGREES_TO_RADIANS,
306                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
307                                 globals->get_time_params()->getJD() );
308
309     // Calculate frame rate average
310 #ifdef FANCY_FRAME_COUNTER
311     /* old fps calculation */
312     if ( elapsed > 0 ) {
313         double tmp;
314         accum = 0.0;
315         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
316             tmp = general.get_frame(i);
317             accum += tmp;
318             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
319             general.set_frame(i+1,tmp);
320         }
321         tmp = 1000000.0 / (float)elapsed;
322         general.set_frame(0,tmp);
323         // printf("frame[0] = %.2f\n", general.frames[0]);
324         accum += tmp;
325         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
326         // printf("ave = %.2f\n", general.frame_rate);
327     }
328 #else
329     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
330         general.set_frame_rate( frames );
331         fgSetInt("/sim/frame-rate", frames);
332         SG_LOG( SG_ALL, SG_DEBUG,
333                 "--> Frame rate is = " << general.get_frame_rate() );
334         frames = 0;
335     }
336     last_time = t->get_cur_time();
337     ++frames;
338 #endif
339
340     // Update any multiplayer's network queues, the AIMultiplayer
341     // implementation is an AI model and depends on that
342     globals->get_multiplayer_mgr()->Update();
343
344 #if ENABLE_ATCDCL  
345     // Run ATC subsystem
346     if (fgGetBool("/sim/atc/enabled"))
347         globals->get_ATC_mgr()->update(delta_time_sec);
348 #endif  
349     
350     globals->get_subsystem_mgr()->update(delta_time_sec);
351     globals->get_aircraft_model()->update(delta_time_sec);
352     
353     //
354     // Tile Manager updates - see if we need to load any new scenery tiles.
355     //   this code ties together the fdm, viewer and scenery classes...
356     //   we may want to move this to its own class at some point
357     //
358     double visibility_meters = fgGetDouble("/environment/visibility-m");
359     globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
360
361     // update tile manager for view...
362     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
363     SGGeod geodViewPos = SGGeod::fromCart(viewPos);
364     globals->get_tile_mgr()->update(geodViewPos, visibility_meters);
365
366     // run Nasal's settimer() loops right before the view manager
367     globals->get_event_mgr()->update(delta_time_sec);
368
369     // pick up model coordidnates that Nasal code may have set relative to the
370     // aircraft's
371     globals->get_model_mgr()->update(delta_time_sec);
372
373     // update the view angle as late as possible, but before sound calculations
374     globals->get_viewmgr()->update(real_delta_time_sec);
375
376     // Update the sound manager last so it can use the CPU while the GPU
377     // is processing the scenery (doubled the frame-rate for me) -EMH-
378 #ifdef ENABLE_AUDIO_SUPPORT
379     static bool smgr_init = true;
380     static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
381     if (smgr_init == true) {
382         if (sound_working->getBoolValue() == true) {
383             fgInitSoundManager();
384             smgr_init = false;
385         }
386     } else {
387         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
388         static SGSoundMgr *smgr = globals->get_soundmgr();
389         static bool smgr_enabled = true;
390
391         if (sound_working->getBoolValue() == false) {   // request to reinit
392            smgr->reinit();
393            smgr->resume();
394            sound_working->setBoolValue(true);
395         }
396
397         if (smgr_enabled != sound_enabled->getBoolValue()) {
398             if (smgr_enabled == true) { // request to suspend
399                 smgr->suspend();
400                 smgr_enabled = false;
401             } else {
402                 smgr->resume();
403                 smgr_enabled = true;
404             }
405         }
406
407         if (smgr_enabled == true) {
408             static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
409             smgr->set_volume(volume->getFloatValue());
410             smgr->update(delta_time_sec);
411         }
412     }
413 #endif
414
415     // END Tile Manager udpates
416
417     if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
418         && fgGetBool("sim/fdm-initialized")) {
419         fgSetBool("sim/sceneryloaded",true);
420         if (fgGetBool("/sim/sound/working")) {
421             globals->get_soundmgr()->activate();
422         }
423         globals->get_props()->tie("/sim/sound/devices/name",
424               SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
425     }
426     simgear::AtomicChangeListener::fireChangeListeners();
427     fgRequestRedraw();
428
429     SG_LOG( SG_ALL, SG_DEBUG, "" );
430 }
431
432 void fgInitSoundManager()
433 {
434     SGSoundMgr *smgr = globals->get_soundmgr();
435
436     smgr->bind();
437     smgr->init(fgGetString("/sim/sound/device-name", NULL));
438
439     vector <const char*>devices = smgr->get_available_devices();
440     for (unsigned int i=0; i<devices.size(); i++) {
441         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
442         p->setStringValue(devices[i]);
443     }
444     devices.clear();
445 }
446
447 void fgSetNewSoundDevice(const char *device)
448 {
449     globals->get_soundmgr()->suspend();
450     globals->get_soundmgr()->stop();
451     globals->get_soundmgr()->init(device);
452     globals->get_soundmgr()->resume();
453 }
454
455 // Operation for querying OpenGL parameters. This must be done in a
456 // valid OpenGL context, potentially in another thread.
457 namespace
458 {
459 struct GeneralInitOperation : public GraphicsContextOperation
460 {
461     GeneralInitOperation()
462         : GraphicsContextOperation(std::string("General init"))
463     {
464     }
465     void run(osg::GraphicsContext* gc)
466     {
467         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
468         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
469         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
470         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVendor() );
471         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
472         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVersion() );
473
474         GLint tmp;
475         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
476         general.set_glMaxTexSize( tmp );
477         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
478
479         glGetIntegerv( GL_DEPTH_BITS, &tmp );
480         general.set_glDepthBits( tmp );
481         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
482     }
483 };
484
485
486 osg::Node* load_panel(SGPropertyNode *n)
487 {
488     osg::Geode* geode = new osg::Geode;
489     geode->addDrawable(new FGPanelNode(n));
490     return geode;
491 }
492
493 SGPath resolve_path(const std::string& s)
494 {
495   return globals->resolve_maybe_aircraft_path(s);
496 }
497
498 }
499
500 // This is the top level master main function that is registered as
501 // our idle funciton
502
503 // The first few passes take care of initialization things (a couple
504 // per pass) and once everything has been initialized fgMainLoop from
505 // then on.
506
507 static void fgIdleFunction ( void ) {
508     static osg::ref_ptr<GeneralInitOperation> genOp;
509     if ( idle_state == 0 ) {
510         idle_state++;
511         // Pick some window on which to do queries.
512         // XXX Perhaps all this graphics initialization code should be
513         // moved to renderer.cxx?
514         genOp = new GeneralInitOperation;
515         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
516         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
517         osg::GraphicsContext* gc = 0;
518         if (guiCamera)
519             gc = guiCamera->getGraphicsContext();
520         if (gc) {
521             gc->add(genOp.get());
522         } else {
523             wsa->windows[0]->gc->add(genOp.get());
524         }
525         guiStartInit(gc);
526     } else if ( idle_state == 1 ) {
527         if (genOp.valid()) {
528             if (!genOp->isFinished())
529                 return;
530             genOp = 0;
531         }
532         if (!guiFinishInit())
533             return;
534         idle_state++;
535         fgSplashProgress("reading aircraft list");
536
537
538     } else if ( idle_state == 2 ) {
539         idle_state++;
540                 
541         fgSplashProgress("reading airport & navigation data");
542
543
544     } else if ( idle_state == 3 ) {
545         idle_state++;
546         fgInitNav();
547         fgSplashProgress("setting up scenery");
548
549
550     } else if ( idle_state == 4 ) {
551         idle_state++;
552         // based on the requested presets, calculate the true starting
553         // lon, lat
554         fgInitPosition();
555         fgInitTowerLocationListener();
556
557         SGTime *t = fgInitTime();
558         globals->set_time_params( t );
559
560         // Do some quick general initializations
561         if( !fgInitGeneral()) {
562             SG_LOG( SG_GENERAL, SG_ALERT,
563                 "General initialization failed ..." );
564             exit(-1);
565         }
566
567         ////////////////////////////////////////////////////////////////////
568         // Initialize the property-based built-in commands
569         ////////////////////////////////////////////////////////////////////
570         fgInitCommands();
571
572
573         ////////////////////////////////////////////////////////////////////
574         // Initialize the material manager
575         ////////////////////////////////////////////////////////////////////
576         globals->set_matlib( new SGMaterialLib );
577         simgear::SGModelLib::init(globals->get_fg_root());
578         simgear::SGModelLib::setPropRoot(globals->get_props());
579         simgear::SGModelLib::setResolveFunc(resolve_path);
580         simgear::SGModelLib::setPanelFunc(load_panel);
581         
582         ////////////////////////////////////////////////////////////////////
583         // Initialize the TG scenery subsystem.
584         ////////////////////////////////////////////////////////////////////
585         globals->set_scenery( new FGScenery );
586         globals->get_scenery()->init();
587         globals->get_scenery()->bind();
588         globals->set_tile_mgr( new FGTileMgr );
589
590
591         ////////////////////////////////////////////////////////////////////
592         // Initialize the general model subsystem.
593         ////////////////////////////////////////////////////////////////////
594         globals->set_model_mgr(new FGModelMgr);
595         globals->get_model_mgr()->init();
596         globals->get_model_mgr()->bind();
597         fgSplashProgress("loading aircraft");
598
599
600     } else if ( idle_state == 5 ) {
601         idle_state++;
602
603         ////////////////////////////////////////////////////////////////////
604         // Initialize the 3D aircraft model subsystem (has a dependency on
605         // the scenery subsystem.)
606         ////////////////////////////////////////////////////////////////////
607         FGAircraftModel* acm = new FGAircraftModel;
608         globals->set_aircraft_model(acm);
609         //globals->add_subsystem("aircraft-model", acm);
610         acm->init();
611         acm->bind();
612
613         ////////////////////////////////////////////////////////////////////
614         // Initialize the view manager subsystem.
615         ////////////////////////////////////////////////////////////////////
616         FGViewMgr *viewmgr = new FGViewMgr;
617         globals->set_viewmgr( viewmgr );
618         viewmgr->init();
619         viewmgr->bind();
620         fgSplashProgress("generating sky elements");
621
622
623     } else if ( idle_state == 6 ) {
624         idle_state++;
625         // Initialize the sky
626
627         Ephemeris* eph = new Ephemeris;
628         globals->add_subsystem("ephmeris", eph);
629         eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
630         eph->bind();
631
632         // TODO: move to environment mgr
633         thesky = new SGSky;
634         SGPath texture_path(globals->get_fg_root());
635         texture_path.append("Textures");
636         texture_path.append("Sky");
637         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
638             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
639             thesky->add_cloud_layer(layer);
640         }
641
642         SGPath sky_tex_path( globals->get_fg_root() );
643         sky_tex_path.append( "Textures" );
644         sky_tex_path.append( "Sky" );
645         thesky->texture_path( sky_tex_path.str() );
646
647         // The sun and moon diameters are scaled down numbers of the
648         // actual diameters. This was needed to fit both the sun and the
649         // moon within the distance to the far clip plane.
650         // Moon diameter:    3,476 kilometers
651         // Sun diameter: 1,390,000 kilometers
652         thesky->build( 80000.0, 80000.0,
653                        463.3, 361.8,
654                        *globals->get_ephem(),
655                        fgGetNode("/environment", true));
656
657         // Initialize MagVar model
658         SGMagVar *magvar = new SGMagVar();
659         globals->set_mag( magvar );
660
661
662                                     // kludge to initialize mag compass
663                                     // (should only be done for in-flight
664                                     // startup)
665         // update magvar model
666         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
667                                     * SGD_DEGREES_TO_RADIANS,
668                                     fgGetDouble("/position/latitude-deg")
669                                     * SGD_DEGREES_TO_RADIANS,
670                                     fgGetDouble("/position/altitude-ft")
671                                     * SG_FEET_TO_METER,
672                                     globals->get_time_params()->getJD() );
673         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
674         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
675         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
676
677
678         // airport = new ssgBranch;
679         // airport->setName( "Airport Lighting" );
680         // lighting->addKid( airport );
681
682         // build our custom render states
683         fgSplashProgress("initializing subsystems");
684
685
686     } else if ( idle_state == 7 ) {
687         idle_state++;
688         // Initialize audio support
689 #ifdef ENABLE_AUDIO_SUPPORT
690
691         // Start the intro music
692         if ( fgGetBool("/sim/startup/intro-music") ) {
693             SGPath mp3file( globals->get_fg_root() );
694             mp3file.append( "Sounds/intro.mp3" );
695
696             SG_LOG( SG_GENERAL, SG_INFO,
697                 "Starting intro music: " << mp3file.str() );
698
699 # if defined( __CYGWIN__ )
700             string command = "start /m `cygpath -w " + mp3file.str() + "`";
701 # elif defined( _WIN32 )
702             string command = "start /m " + mp3file.str();
703 # else
704             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
705 # endif
706
707             system ( command.c_str() );
708         }
709 #endif
710         // This is the top level init routine which calls all the
711         // other subsystem initialization routines.  If you are adding
712         // a subsystem to flightgear, its initialization call should be
713         // located in this routine.
714         if( !fgInitSubsystems()) {
715             SG_LOG( SG_GENERAL, SG_ALERT,
716                 "Subsystem initialization failed ..." );
717             exit(-1);
718         }
719         fgSplashProgress("setting up time & renderer");
720
721
722     } else if ( idle_state == 8 ) {
723         idle_state = 1000;
724         // Initialize the time offset (warp) after fgInitSubsystem
725         // (which initializes the lighting interpolation tables.)
726         fgInitTimeOffset();
727
728         // setup OpenGL view parameters
729         globals->get_renderer()->init();
730
731         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
732                                          fgGetInt("/sim/startup/ysize") );
733
734         fgSplashProgress("loading scenery objects");
735         int session = fgGetInt("/sim/session",0);
736         session++;
737         fgSetInt("/sim/session",session);
738     }
739
740     if ( idle_state == 1000 ) {
741         // We've finished all our initialization steps, from now on we
742         // run the main loop.
743         fgSetBool("sim/sceneryloaded", false);
744         fgRegisterIdleHandler( fgMainLoop );
745     }
746 }
747
748
749 static void upper_case_property(const char *name)
750 {
751     using namespace simgear;
752     SGPropertyNode *p = fgGetNode(name, false);
753     if (!p) {
754         p = fgGetNode(name, true);
755         p->setStringValue("");
756     } else {
757         props::Type t = p->getType();
758         if (t == props::NONE || t == props::UNSPECIFIED)
759             p->setStringValue("");
760         else
761             assert(t == props::STRING);
762     }
763     p->addChangeListener(new FGMakeUpperCase);
764 }
765
766
767 // Main top level initialization
768 bool fgMainInit( int argc, char **argv ) {
769
770     // set default log levels
771     sglog().setLogLevels( SG_ALL, SG_ALERT );
772
773     string version;
774 #ifdef FLIGHTGEAR_VERSION
775     version = FLIGHTGEAR_VERSION;
776 #else
777     version = "unknown version";
778 #endif
779     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
780             << version );
781     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
782
783     // Allocate global data structures.  This needs to happen before
784     // we parse command line options
785
786     globals = new FGGlobals;
787
788     // seed the random number generator
789     sg_srandom_time();
790
791     FGControls *controls = new FGControls;
792     globals->set_controls( controls );
793
794     string_list *col = new string_list;
795     globals->set_channel_options_list( col );
796
797     fgValidatePath("", false);  // initialize static variables
798     upper_case_property("/sim/presets/airport-id");
799     upper_case_property("/sim/presets/runway");
800     upper_case_property("/sim/tower/airport-id");
801     upper_case_property("/autopilot/route-manager/input");
802
803     // Scan the config file(s) and command line options to see if
804     // fg_root was specified (ignore all other options for now)
805     fgInitFGRoot(argc, argv);
806
807     // Check for the correct base package version
808     static char required_version[] = "2.0.0";
809     string base_version = fgBasePackageVersion();
810     if ( !(base_version == required_version) ) {
811         // tell the operator how to use this application
812
813         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
814         cerr << endl << "Base package check failed ... " \
815              << "Found version " << base_version << " at: " \
816              << globals->get_fg_root() << endl;
817         cerr << "Please upgrade to version: " << required_version << endl;
818 #ifdef _MSC_VER
819         cerr << "Hit a key to continue..." << endl;
820         cin.get();
821 #endif
822         exit(-1);
823     }
824
825     // Load the configuration parameters.  (Command line options
826     // override config file options.  Config file options override
827     // defaults.)
828     if ( !fgInitConfig(argc, argv) ) {
829         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
830         exit(-1);
831     }
832
833     // Initialize the Window/Graphics environment.
834     fgOSInit(&argc, argv);
835     _bootstrap_OSInit++;
836
837     fgRegisterWindowResizeHandler( &FGRenderer::resize );
838     fgRegisterIdleHandler( &fgIdleFunction );
839     fgRegisterDrawHandler( &FGRenderer::update );
840
841     // Initialize plib net interface
842     netInit( &argc, argv );
843
844     // Clouds3D requires an alpha channel
845     fgOSOpenWindow(true /* request stencil buffer */);
846
847     // Initialize the splash screen right away
848     fntInit();
849     fgSplashInit();
850
851     // pass control off to the master event handler
852     fgOSMainLoop();
853
854     // we never actually get here ... but to avoid compiler warnings,
855     // etc.
856     return false;
857 }
858
859