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