]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Constant-speed props were seeking to engine speed, not prop speed.
[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., 675 Mass Ave, Cambridge, MA 02139, 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 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/netSocket.h>
45
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
49
50 // Class refferences
51 #include <simgear/ephemeris/ephemeris.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/animation.hxx>
55 #include <simgear/scene/sky/sky.hxx>
56 #include <Time/light.hxx>
57
58
59
60 #include <Include/general.hxx>
61 #include <Cockpit/cockpit.hxx>
62 #include <Cockpit/hud.hxx>
63 #include <Model/panelnode.hxx>
64 #include <Model/modelmgr.hxx>
65 #include <Model/acmodel.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Scenery/tilemgr.hxx>
68 #include <Sound/beacon.hxx>
69 #include <Sound/morse.hxx>
70 #include <FDM/flight.hxx>
71 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
72 // #include <FDM/ADA.hxx>
73 #include <ATC/ATCdisplay.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/AIMgr.hxx>
76 #include <Replay/replay.hxx>
77 #include <Time/tmp.hxx>
78 #include <Time/fg_timer.hxx>
79 #include <Environment/environment_mgr.hxx>
80 #include <GUI/new_gui.hxx>
81
82 #ifdef FG_MPLAYER_AS
83 #include <MultiPlayer/multiplaytxmgr.hxx>
84 #include <MultiPlayer/multiplayrxmgr.hxx>
85 #endif
86
87
88
89 #include "fg_commands.hxx"
90 #include "fg_io.hxx"
91 #include "renderer.hxx"
92 #include "splash.hxx"
93 #include "main.hxx"
94
95
96
97 static double real_delta_time_sec = 0.0;
98 double delta_time_sec = 0.0;
99 extern float init_volume;
100
101
102 #ifdef macintosh
103 #  include <console.h>          // -dw- for command line dialog
104 #endif
105
106 // This is a record containing a bit of global housekeeping information
107 FGGeneral general;
108
109 // Specify our current idle function state.  This is used to run all
110 // our initializations out of the idle callback so that we can get a
111 // splash screen up and running right away.
112 int idle_state = 0;
113 long global_multi_loop;
114
115 SGTimeStamp last_time_stamp;
116 SGTimeStamp current_time_stamp;
117
118 // The atexit() functio handler should know when the graphical subsystem
119 // is initialized.
120 extern int _bootstrap_OSInit;
121
122
123
124 // Update internal time dependent calculations (i.e. flight model)
125 // FIXME: this distinction is obsolete; all subsystems now get delta
126 // time on update.
127 void fgUpdateTimeDepCalcs() {
128     static bool inited = false;
129
130     static const SGPropertyNode *replay_state
131         = fgGetNode( "/sim/freeze/replay-state", true );
132     static SGPropertyNode *replay_time
133         = fgGetNode( "/sim/replay/time", true );
134     // static const SGPropertyNode *replay_end_time
135     //     = fgGetNode( "/sim/replay/end-time", true );
136
137     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
138
139     // Initialize the FDM here if it hasn't been and if we have a
140     // scenery elevation hit.
141
142     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
143     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
144
145     if ( !cur_fdm_state->get_inited() &&
146          globals->get_scenery()->get_cur_elev() > -9990 )
147     {
148         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
149         cur_fdm_state->init();
150         if ( cur_fdm_state->get_bound() ) {
151             cur_fdm_state->unbind();
152         }
153         cur_fdm_state->bind();
154     }
155
156     // conceptually, the following block could be done for each fdm
157     // instance ...
158     if ( cur_fdm_state->get_inited() ) {
159         // we have been inited, and  we are good to go ...
160
161         if ( !inited ) {
162             inited = true;
163         }
164
165         if ( replay_state->getIntValue() == 0 ) {
166             // replay off, run fdm
167             cur_fdm_state->update( delta_time_sec );
168         } else {
169             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
170             r->replay( replay_time->getDoubleValue() );
171             if ( replay_state->getIntValue() == 1 ) {
172                 // normal playback
173                 replay_time->setDoubleValue( replay_time->getDoubleValue()
174                                              + ( delta_time_sec
175                                                * fgGetInt("/sim/speed-up") ) );
176             } else if ( replay_state->getIntValue() == 2 ) {
177                 // paused playback (don't advance replay time)
178             }
179         }
180     } else {
181         // do nothing, fdm isn't inited yet
182     }
183
184     globals->get_model_mgr()->update(delta_time_sec);
185     globals->get_aircraft_model()->update(delta_time_sec);
186
187     // update the view angle
188     globals->get_viewmgr()->update(delta_time_sec);
189
190     // Update solar system
191     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
192                                   globals->get_time_params()->getLst(),
193                                   cur_fdm_state->get_Latitude() );
194
195 }
196
197
198 void fgInitTimeDepCalcs( void ) {
199     // noop for now
200 }
201
202
203 static const double alt_adjust_ft = 3.758099;
204 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
205
206
207 // What should we do when we have nothing else to do?  Let's get ready
208 // for the next move and update the display?
209 static void fgMainLoop( void ) {
210     int model_hz = fgGetInt("/sim/model-hz");
211
212     static const SGPropertyNode *longitude
213         = fgGetNode("/position/longitude-deg");
214     static const SGPropertyNode *latitude
215         = fgGetNode("/position/latitude-deg");
216     static const SGPropertyNode *altitude
217         = fgGetNode("/position/altitude-ft");
218     static const SGPropertyNode *clock_freeze
219         = fgGetNode("/sim/freeze/clock", true);
220     static const SGPropertyNode *cur_time_override
221         = fgGetNode("/sim/time/cur-time-override", true);
222
223     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
224
225     // Update the elapsed time.
226     static bool first_time = true;
227     if ( first_time ) {
228         last_time_stamp.stamp();
229         first_time = false;
230     }
231
232     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
233     if ( throttle_hz > 0.0 ) {
234         // simple frame rate throttle
235         double dt = 1000000.0 / throttle_hz;
236         current_time_stamp.stamp();
237         while ( current_time_stamp - last_time_stamp < dt ) {
238             current_time_stamp.stamp();
239         }
240     } else {
241         // run as fast as the app will go
242         current_time_stamp.stamp();
243     }
244
245     real_delta_time_sec
246         = double(current_time_stamp - last_time_stamp) / 1000000.0;
247     // round the real time down to a multiple of 1/model-hz.
248     // this way all systems are updated the _same_ amount of dt.
249     {
250       static double rem = 0.0;
251       real_delta_time_sec += rem;
252       double hz = model_hz;
253       double nit = floor(real_delta_time_sec*hz);
254       rem = real_delta_time_sec - nit/hz;
255       real_delta_time_sec = nit/hz;
256     }
257
258
259     if ( clock_freeze->getBoolValue() ) {
260         delta_time_sec = 0;
261     } else {
262         delta_time_sec = real_delta_time_sec;
263     }
264     last_time_stamp = current_time_stamp;
265     globals->inc_sim_time_sec( delta_time_sec );
266     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
267
268     // These are useful, especially for Nasal scripts.
269     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
270     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
271
272     static long remainder = 0;
273     long elapsed;
274 #ifdef FANCY_FRAME_COUNTER
275     int i;
276     double accum;
277 #else
278     static time_t last_time = 0;
279     static int frames = 0;
280 #endif // FANCY_FRAME_COUNTER
281
282     SGTime *t = globals->get_time_params();
283
284     globals->get_event_mgr()->update(delta_time_sec);
285
286     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
287     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
288
289 #if defined( ENABLE_PLIB_JOYSTICK )
290     // Read joystick and update control settings
291     // if ( fgGetString("/sim/control-mode") == "joystick" )
292     // {
293     //    fgJoystickRead();
294     // }
295 #endif
296
297     // Fix elevation.  I'm just sticking this here for now, it should
298     // probably move eventually
299
300     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
301            scenery.get_cur_elev(),
302            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
303            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
304
305     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
306            scenery.get_cur_elev(),
307            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
308            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
309
310     // cout << "Warp = " << globals->get_warp() << endl;
311
312     // update "time"
313     static bool last_clock_freeze = false;
314
315     if ( clock_freeze->getBoolValue() ) {
316         // clock freeze requested
317         if ( cur_time_override->getLongValue() == 0 ) {
318             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
319             globals->set_warp( 0 );
320         }
321     } else {
322         // no clock freeze requested
323         if ( last_clock_freeze == true ) {
324             // clock just unfroze, let's set warp as the difference
325             // between frozen time and current time so we don't get a
326             // time jump (and corresponding sky object and lighting
327             // jump.)
328             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
329             fgSetLong( "/sim/time/cur-time-override", 0 );
330         }
331         if ( globals->get_warp_delta() != 0 ) {
332             globals->inc_warp( globals->get_warp_delta() );
333         }
334     }
335
336     last_clock_freeze = clock_freeze->getBoolValue();
337
338     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
339                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
340                cur_time_override->getLongValue(),
341                globals->get_warp() );
342
343     if (globals->get_warp_delta() != 0) {
344         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
345         l->update( 0.5 );
346     }
347
348     // update magvar model
349     globals->get_mag()->update( longitude->getDoubleValue()
350                               * SGD_DEGREES_TO_RADIANS,
351                             latitude->getDoubleValue()
352                               * SGD_DEGREES_TO_RADIANS,
353                             altitude->getDoubleValue() * SG_FEET_TO_METER,
354                             globals->get_time_params()->getJD() );
355
356     // Get elapsed time (in usec) for this past frame
357     elapsed = fgGetTimeInterval();
358     SG_LOG( SG_ALL, SG_DEBUG, 
359             "Elapsed time interval is = " << elapsed 
360             << ", previous remainder is = " << remainder );
361
362     // Calculate frame rate average
363 #ifdef FANCY_FRAME_COUNTER
364     /* old fps calculation */
365     if ( elapsed > 0 ) {
366         double tmp;
367         accum = 0.0;
368         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
369             tmp = general.get_frame(i);
370             accum += tmp;
371             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
372             general.set_frame(i+1,tmp);
373         }
374         tmp = 1000000.0 / (float)elapsed;
375         general.set_frame(0,tmp);
376         // printf("frame[0] = %.2f\n", general.frames[0]);
377         accum += tmp;
378         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
379         // printf("ave = %.2f\n", general.frame_rate);
380     }
381 #else
382     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
383         general.set_frame_rate( frames );
384         fgSetInt("/sim/frame-rate", frames);
385         SG_LOG( SG_ALL, SG_DEBUG, 
386             "--> Frame rate is = " << general.get_frame_rate() );
387         frames = 0;
388     }
389     last_time = t->get_cur_time();
390     ++frames;
391 #endif
392
393     // Run ATC subsystem
394     if (fgGetBool("/sim/ATC/enabled"))
395         globals->get_ATC_mgr()->update(delta_time_sec);
396
397     // Run the AI subsystem
398     if (fgGetBool("/sim/ai-traffic/enabled"))
399         globals->get_AI_mgr()->update(delta_time_sec);
400
401 #ifdef FG_MPLAYER_AS
402     // Update any multiplayer models
403     globals->get_multiplayer_rx_mgr()->Update();
404 #endif
405
406     // Run flight model
407
408     // Calculate model iterations needed for next frame
409     elapsed += remainder;
410
411     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
412     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
413     SG_LOG( SG_ALL, SG_DEBUG, 
414             "Model iterations needed = " << global_multi_loop
415             << ", new remainder = " << remainder );
416         
417     // chop max interations to something reasonable if the sim was
418     // delayed for an excesive amount of time
419     if ( global_multi_loop > 2.0 * model_hz ) {
420         global_multi_loop = (int)(2.0 * model_hz );
421         remainder = 0;
422     }
423
424     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
425
426     // flight model
427     if ( global_multi_loop > 0) {
428         // first run the flight model each frame until it is intialized
429         // then continue running each frame only after initial scenery load is complete.
430         if (!cur_fdm_state->get_inited() || scenery_loaded) {
431             fgUpdateTimeDepCalcs();
432         }
433     } else {
434         SG_LOG( SG_ALL, SG_DEBUG, 
435             "Elapsed time is zero ... we're zinging" );
436     }
437
438     // Do any I/O channel work that might need to be done
439     globals->get_io()->update( real_delta_time_sec );
440
441     // see if we need to load any deferred-load textures
442     globals->get_matlib()->load_next_deferred();
443
444     // Run audio scheduler
445 #ifdef ENABLE_AUDIO_SUPPORT
446     if ( globals->get_soundmgr()->is_working() ) {
447         globals->get_soundmgr()->update( delta_time_sec );
448     }
449 #endif
450
451     globals->get_subsystem_mgr()->update(delta_time_sec);
452
453     //
454     // Tile Manager updates - see if we need to load any new scenery tiles.
455     //   this code ties together the fdm, viewer and scenery classes...
456     //   we may want to move this to it's own class at some point
457     //
458     double visibility_meters = fgGetDouble("/environment/visibility-m");
459     FGViewer *current_view = globals->get_current_view();
460
461     // get the location data for the primary FDM (now hardcoded to ac model)...
462     SGLocation *acmodel_loc = NULL;
463     acmodel_loc = (SGLocation *)globals->
464         get_aircraft_model()->get3DModel()->getSGLocation();
465
466     // update tile manager for FDM...
467     // ...only if location is different than the current-view location
468     // (to avoid duplicating effort)
469     if( !fgGetBool("/sim/current-view/config/from-model") ) {
470         if( acmodel_loc != NULL ) {
471             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
472                                                      visibility_meters );
473             globals->get_tile_mgr()->
474                 update( acmodel_loc, visibility_meters,
475                         acmodel_loc->
476                         get_absolute_view_pos(globals->
477                                               get_scenery()->get_center()) );
478             // save results of update in SGLocation for fdm...
479             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
480                 acmodel_loc->
481                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
482                 fgSetDouble("/position/ground-elev-m",
483                             globals->get_scenery()->get_cur_elev());
484             }
485             acmodel_loc->
486                 set_tile_center( globals->get_scenery()->get_next_center() );
487         }
488     }
489
490     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
491                                              visibility_meters );
492     // update tile manager for view...
493     // IMPORTANT!!! the tilemgr update for view location _must_ be
494     // done last after the FDM's until all of Flight Gear code
495     // references the viewer's location for elevation instead of the
496     // "scenery's" current elevation.
497     SGLocation *view_location = globals->get_current_view()->getSGLocation();
498     globals->get_tile_mgr()->update( view_location, visibility_meters,
499                                      current_view->get_absolute_view_pos() );
500     // save results of update in SGLocation for fdm...
501     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
502         current_view->getSGLocation()->
503             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
504     }
505     current_view->getSGLocation()->
506         set_tile_center( globals->get_scenery()->get_next_center() );
507
508 #ifdef ENABLE_AUDIO_SUPPORT
509     // Right now we make a simplifying assumption that the primary
510     // aircraft is the source of all sounds and that all sounds are
511     // positioned relative to the current view position.
512
513     static sgVec3 last_pos_offset;
514
515     // set positional offset for sources
516     sgVec3 source_pos_offset;
517     sgSubVec3( source_pos_offset,
518                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
519     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
520     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
521
522     // set the velocity
523     sgVec3 source_vel;
524     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
525     sgScaleVec3( source_vel, delta_time_sec );
526     sgCopyVec3( last_pos_offset, source_pos_offset );
527     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
528     globals->get_soundmgr()->set_source_vel_all( source_vel );
529
530     // Right now we make a simplifying assumption that the listener is
531     // always positioned at the origin.
532     sgVec3 listener_pos;
533     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
534     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
535     globals->get_soundmgr()->set_listener_pos( listener_pos );
536 #endif
537
538     // If fdm location is same as viewer's then we didn't do the
539     // update for fdm location above so we need to save the viewer
540     // results in the fdm SGLocation as well...
541     if( fgGetBool("/sim/current-view/config/from-model") ) {
542         if( acmodel_loc != 0 ) {
543             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
544                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
545                                              get_cur_elev() );
546                 fgSetDouble("/position/ground-elev-m",
547                             globals->get_scenery()->get_cur_elev());
548             }
549             acmodel_loc->set_tile_center( globals->get_scenery()->
550                                           get_next_center() );
551         }
552     }
553
554     // END Tile Manager udpates
555
556     if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
557         fgSetBool("sim/sceneryloaded",true);
558         fgSetFloat("/sim/sound/volume", init_volume);
559         globals->get_soundmgr()->set_volume(init_volume);
560     }
561
562     if (fgGetBool("/sim/rendering/specular-highlight")) {
563         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
564         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
565     } else {
566         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
567         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
568     }
569
570     fgRequestRedraw();
571
572     SG_LOG( SG_ALL, SG_DEBUG, "" );
573 }
574
575
576 // This is the top level master main function that is registered as
577 // our idle funciton
578
579 // The first few passes take care of initialization things (a couple
580 // per pass) and once everything has been initialized fgMainLoop from
581 // then on.
582
583 static void fgIdleFunction ( void ) {
584     // printf("idle state == %d\n", idle_state);
585
586     if ( idle_state == 0 ) {
587         // Initialize the splash screen right away
588         if ( fgGetBool("/sim/startup/splash-screen") ) {
589             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
590         }
591         
592         idle_state++;
593     } else if ( idle_state == 1 ) {
594         // Initialize audio support
595 #ifdef ENABLE_AUDIO_SUPPORT
596
597         // Start the intro music
598         if ( fgGetBool("/sim/startup/intro-music") ) {
599             SGPath mp3file( globals->get_fg_root() );
600             mp3file.append( "Sounds/intro.mp3" );
601
602             SG_LOG( SG_GENERAL, SG_INFO, 
603                 "Starting intro music: " << mp3file.str() );
604
605 #if defined( __CYGWIN__ )
606             string command = "start /m `cygpath -w " + mp3file.str() + "`";
607 #elif defined( WIN32 )
608             string command = "start /m " + mp3file.str();
609 #else
610             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
611 #endif
612
613             system ( command.c_str() );
614         }
615 #endif
616
617         idle_state++;
618     } else if ( idle_state == 2 ) {
619         // These are a few miscellaneous things that aren't really
620         // "subsystems" but still need to be initialized.
621
622 #ifdef USE_GLIDE
623         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
624             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
625         }
626 #endif
627
628         idle_state++;
629     } else if ( idle_state == 3 ) {
630         // This is the top level init routine which calls all the
631         // other subsystem initialization routines.  If you are adding
632         // a subsystem to flightgear, its initialization call should
633         // located in this routine.
634         if( !fgInitSubsystems()) {
635             SG_LOG( SG_GENERAL, SG_ALERT,
636                 "Subsystem initializations failed ..." );
637             exit(-1);
638         }
639
640         idle_state++;
641     } else if ( idle_state == 4 ) {
642         // Initialize the time offset (warp) after fgInitSubsystem
643         // (which initializes the lighting interpolation tables.)
644         fgInitTimeOffset();
645
646         // setup OpenGL view parameters
647         globals->get_renderer()->init();
648
649         // Read the list of available aircrafts
650         fgReadAircraft();
651
652         idle_state++;
653     } else if ( idle_state == 5 ) {
654
655         idle_state++;
656     } else if ( idle_state == 6 ) {
657         // sleep(1);
658
659         idle_state = 1000;
660
661         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
662         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
663                                          fgGetInt("/sim/startup/ysize") );
664
665     } 
666
667     if ( idle_state == 1000 ) {
668         // We've finished all our initialization steps, from now on we
669         // run the main loop.
670         fgSetBool("sim/sceneryloaded",false);
671
672         fgRegisterIdleHandler(fgMainLoop);
673     } else {
674         if ( fgGetBool("/sim/startup/splash-screen") ) {
675             fgSplashUpdate(0.0, 1.0);
676         }
677     }
678 }
679
680
681 // Main top level initialization
682 bool fgMainInit( int argc, char **argv ) {
683
684 #if defined( macintosh )
685     freopen ("stdout.txt", "w", stdout );
686     freopen ("stderr.txt", "w", stderr );
687     argc = ccommand( &argv );
688 #endif
689
690     // set default log levels
691     sglog().setLogLevels( SG_ALL, SG_ALERT );
692
693     string version;
694 #ifdef FLIGHTGEAR_VERSION
695     version = FLIGHTGEAR_VERSION;
696 #else
697     version = "unknown version";
698 #endif
699     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
700             << version );
701     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
702
703     // Allocate global data structures.  This needs to happen before
704     // we parse command line options
705
706     globals = new FGGlobals;
707
708     // seed the random number generater
709     sg_srandom_time();
710
711     FGControls *controls = new FGControls;
712     globals->set_controls( controls );
713
714     string_list *col = new string_list;
715     globals->set_channel_options_list( col );
716
717     // Scan the config file(s) and command line options to see if
718     // fg_root was specified (ignore all other options for now)
719     fgInitFGRoot(argc, argv);
720
721     // Check for the correct base package version
722     static char required_version[] = "0.9.8";
723     string base_version = fgBasePackageVersion();
724     if ( !(base_version == required_version) ) {
725         // tell the operator how to use this application
726
727         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
728         cerr << endl << "Base package check failed ... " \
729              << "Found version " << base_version << " at: " \
730              << globals->get_fg_root() << endl;
731         cerr << "Please upgrade to version: " << required_version << endl;
732 #ifdef _MSC_VER
733         cerr << "Hit a key to continue..." << endl;
734         cin.get();
735 #endif
736         exit(-1);
737     }
738
739     sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
740
741     // Initialize the Aircraft directory to "" (UIUC)
742     aircraft_dir = "";
743
744     // Load the configuration parameters.  (Command line options
745     // overrides config file options.  Config file options override
746     // defaults.)
747     if ( !fgInitConfig(argc, argv) ) {
748         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
749         exit(-1);
750     }
751
752     // Initialize the Window/Graphics environment.
753 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
754     // Mac OS X command line ("non-bundle") applications call this
755     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
756     // feel free to add comments...
757     fgOSInit(&argc, argv);
758     _bootstrap_OSInit++;
759 #endif
760
761     fgRegisterWindowResizeHandler( &FGRenderer::resize );
762     fgRegisterIdleHandler( &fgIdleFunction );
763     fgRegisterDrawHandler( &FGRenderer::update );
764
765 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
766     bool get_stencil_buffer = true;
767 #else
768     bool get_stencil_buffer = false;
769 #endif
770
771     // Clouds3D requires an alpha channel
772     // clouds may require stencil buffer
773     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
774                     fgGetInt("/sim/startup/ysize"),
775                     fgGetInt("/sim/rendering/bits-per-pixel"),
776                     fgGetBool("/sim/rendering/clouds3d"),
777                     get_stencil_buffer,
778                     fgGetBool("/sim/startup/fullscreen") );
779
780     // This seems to be the absolute earliest in the init sequence
781     // that these calls will return valid info.  Too bad it's after
782     // we've already created and sized out window. :-(
783     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
784     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
785     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
786     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
787
788     GLint tmp;
789     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
790     general.set_glMaxTexSize( tmp );
791     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
792
793     glGetIntegerv( GL_DEPTH_BITS, &tmp );
794     general.set_glDepthBits( tmp );
795     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
796
797     // Initialize plib net interface
798     netInit( &argc, argv );
799
800     // Initialize ssg (from plib).  Needs to come before we do any
801     // other ssg stuff, but after opengl has been initialized.
802     ssgInit();
803
804     // Initialize the user interface (we need to do this before
805     // passing off control to the OS main loop and before
806     // fgInitGeneral to get our fonts !!!
807     guiInit();
808
809     // Read the list of available aircrafts
810     fgReadAircraft();
811
812 #ifdef GL_EXT_texture_lod_bias
813     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
814 #endif
815
816             // get the address of our OpenGL extensions
817     if ( fgGetBool("/sim/rendering/distance-attenuation") )
818     {
819         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
820             glPointParameterIsSupported = true;
821             glPointParameterfPtr = (glPointParameterfProc)
822                                    SGLookupFunction("glPointParameterfEXT");
823             glPointParameterfvPtr = (glPointParameterfvProc)
824                                     SGLookupFunction("glPointParameterfvEXT");
825
826         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
827             glPointParameterIsSupported = true;
828             glPointParameterfPtr = (glPointParameterfProc)
829                                    SGLookupFunction("glPointParameterfARB");
830             glPointParameterfvPtr = (glPointParameterfvProc)
831                                     SGLookupFunction("glPointParameterfvARB");
832         } else
833             glPointParameterIsSupported = false;
834    }
835
836     // based on the requested presets, calculate the true starting
837     // lon, lat
838     fgInitNav();
839     fgInitPosition();
840
841     SGTime *t = fgInitTime();
842     globals->set_time_params( t );
843
844     // Do some quick general initializations
845     if( !fgInitGeneral()) {
846         SG_LOG( SG_GENERAL, SG_ALERT, 
847             "General initializations failed ..." );
848         exit(-1);
849     }
850
851     ////////////////////////////////////////////////////////////////////
852     // Initialize the property-based built-in commands
853     ////////////////////////////////////////////////////////////////////
854     fgInitCommands();
855
856     ////////////////////////////////////////////////////////////////////
857     // Initialize the material manager
858     ////////////////////////////////////////////////////////////////////
859     globals->set_matlib( new SGMaterialLib );
860
861     globals->set_model_lib(new SGModelLib);
862
863     ////////////////////////////////////////////////////////////////////
864     // Initialize the TG scenery subsystem.
865     ////////////////////////////////////////////////////////////////////
866     globals->set_scenery( new FGScenery );
867     globals->get_scenery()->init();
868     globals->get_scenery()->bind();
869     globals->set_tile_mgr( new FGTileMgr );
870
871     ////////////////////////////////////////////////////////////////////
872     // Initialize the general model subsystem.
873     ////////////////////////////////////////////////////////////////////
874     globals->set_model_mgr(new FGModelMgr);
875     globals->get_model_mgr()->init();
876     globals->get_model_mgr()->bind();
877
878     ////////////////////////////////////////////////////////////////////
879     // Initialize the 3D aircraft model subsystem (has a dependency on
880     // the scenery subsystem.)
881     ////////////////////////////////////////////////////////////////////
882     globals->set_aircraft_model(new FGAircraftModel);
883     globals->get_aircraft_model()->init();
884     globals->get_aircraft_model()->bind();
885
886     ////////////////////////////////////////////////////////////////////
887     // Initialize the view manager subsystem.
888     ////////////////////////////////////////////////////////////////////
889     FGViewMgr *viewmgr = new FGViewMgr;
890     globals->set_viewmgr( viewmgr );
891     viewmgr->init();
892     viewmgr->bind();
893
894
895     // Initialize the sky
896     SGPath ephem_data_path( globals->get_fg_root() );
897     ephem_data_path.append( "Astro" );
898     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
899     ephem->update( globals->get_time_params()->getMjd(),
900                    globals->get_time_params()->getLst(),
901                    0.0 );
902     globals->set_ephem( ephem );
903
904     // TODO: move to environment mgr
905     thesky = new SGSky;
906     SGPath texture_path(globals->get_fg_root());
907     texture_path.append("Textures");
908     texture_path.append("Sky");
909     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
910         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
911         thesky->add_cloud_layer(layer);
912     }
913
914     SGPath sky_tex_path( globals->get_fg_root() );
915     sky_tex_path.append( "Textures" );
916     sky_tex_path.append( "Sky" );
917     thesky->texture_path( sky_tex_path.str() );
918
919     // The sun and moon diameters are scaled down numbers of the
920     // actual diameters. This was needed to fit bot the sun and the
921     // moon within the distance to the far clip plane.
922     // Moon diameter:    3,476 kilometers
923     // Sun diameter: 1,390,000 kilometers
924     thesky->build( 80000.0, 80000.0,
925                    463.3, 361.8,
926                    globals->get_ephem()->getNumPlanets(), 
927                    globals->get_ephem()->getPlanets(),
928                    globals->get_ephem()->getNumStars(),
929                    globals->get_ephem()->getStars() );
930
931     // Initialize MagVar model
932     SGMagVar *magvar = new SGMagVar();
933     globals->set_mag( magvar );
934
935
936                                 // kludge to initialize mag compass
937                                 // (should only be done for in-flight
938                                 // startup)
939     // update magvar model
940     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
941                                 * SGD_DEGREES_TO_RADIANS,
942                                 fgGetDouble("/position/latitude-deg")
943                                 * SGD_DEGREES_TO_RADIANS,
944                                 fgGetDouble("/position/altitude-ft")
945                                 * SG_FEET_TO_METER,
946                                 globals->get_time_params()->getJD() );
947     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
948     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
949
950     // airport = new ssgBranch;
951     // airport->setName( "Airport Lighting" );
952     // lighting->addKid( airport );
953
954     // build our custom render states
955     globals->get_renderer()->build_states();
956
957     // pass control off to the master event handler
958     fgOSMainLoop();
959
960     // we never actually get here ... but to avoid compiler warnings,
961     // etc.
962     return false;
963 }
964
965
966 // end of main.cxx