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