]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Frederic Bouvier:
[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/ssg.h>
45 #include <plib/netSocket.h>
46
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
57
58 #ifdef FG_USE_CLOUDS_3D
59 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
61 #endif
62
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
87
88 #ifdef FG_MPLAYER_AS
89 #include <MultiPlayer/multiplaytxmgr.hxx>
90 #include <MultiPlayer/multiplayrxmgr.hxx>
91 #endif
92
93 #include "splash.hxx"
94 #include "fg_commands.hxx"
95 #include "fg_io.hxx"
96 #include "main.hxx"
97
98 float default_attenuation[3] = {1.0, 0.0, 0.0};
99 ssgSelector *ship_sel=NULL;
100 // upto 32 instances of a same object can be loaded.
101 ssgTransform *ship_pos[32];
102 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
103 int objc=0;
104 ssgSelector *lightpoints_brightness = new ssgSelector;
105 ssgTransform *lightpoints_transform = new ssgTransform;
106 FGTileEntry *dummy_tile;
107 sgVec3 rway_ols;
108 // ADA
109 // Clip plane settings...
110 float scene_nearplane = 0.5f;
111 float scene_farplane = 120000.0f;
112
113 static double real_delta_time_sec = 0.0;
114 static double delta_time_sec = 0.0;
115
116 glPointParameterfProc glPointParameterfPtr = 0;
117 glPointParameterfvProc glPointParameterfvPtr = 0;
118 bool glPointParameterIsSupported = false;
119
120
121 #ifdef macintosh
122 #  include <console.h>          // -dw- for command line dialog
123 #endif
124
125 // This is a record containing a bit of global housekeeping information
126 FGGeneral general;
127
128 // Specify our current idle function state.  This is used to run all
129 // our initializations out of the idle callback so that we can get a
130 // splash screen up and running right away.
131 static int idle_state = 0;
132 static long global_multi_loop;
133
134 // fog constants.  I'm a little nervous about putting actual code out
135 // here but it seems to work (?)
136 static const double m_log01 = -log( 0.01 );
137 static const double sqrt_m_log01 = sqrt( m_log01 );
138 static GLfloat fog_exp_density;
139 static GLfloat fog_exp2_density;
140 static GLfloat rwy_exp2_punch_through;
141 static GLfloat taxi_exp2_punch_through;
142 static GLfloat ground_exp2_punch_through;
143
144 // Sky structures
145 SGSky *thesky;
146
147 #ifdef FG_USE_CLOUDS_3D
148   SkySceneLoader *sgClouds3d;
149   bool _bcloud_orig = true;
150 #endif
151
152 // hack
153 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
154 {
155   {  1.0f,  0.0f,  0.0f,  0.0f },
156   {  0.0f,  0.0f, -1.0f,  0.0f },
157   {  0.0f,  1.0f,  0.0f,  0.0f },
158   {  0.0f,  0.0f,  0.0f,  1.0f }
159 };
160
161 ssgSimpleState *cloud3d_imposter_state;
162 ssgSimpleState *default_state;
163 ssgSimpleState *hud_and_panel;
164 ssgSimpleState *menus;
165
166 SGTimeStamp last_time_stamp;
167 SGTimeStamp current_time_stamp;
168
169
170 void fgBuildRenderStates( void ) {
171     default_state = new ssgSimpleState;
172     default_state->ref();
173     default_state->disable( GL_TEXTURE_2D );
174     default_state->enable( GL_CULL_FACE );
175     default_state->enable( GL_COLOR_MATERIAL );
176     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
177     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
178     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
179     default_state->disable( GL_BLEND );
180     default_state->disable( GL_ALPHA_TEST );
181     default_state->disable( GL_LIGHTING );
182
183     cloud3d_imposter_state = new ssgSimpleState;
184     cloud3d_imposter_state->ref();
185     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
186     cloud3d_imposter_state->enable( GL_CULL_FACE );
187     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
188     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
189     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
190     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
191     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
192     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
193     cloud3d_imposter_state->enable( GL_BLEND );
194     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
195     cloud3d_imposter_state->disable( GL_LIGHTING );
196
197     hud_and_panel = new ssgSimpleState;
198     hud_and_panel->ref();
199     hud_and_panel->disable( GL_CULL_FACE );
200     hud_and_panel->disable( GL_TEXTURE_2D );
201     hud_and_panel->disable( GL_LIGHTING );
202     hud_and_panel->enable( GL_BLEND );
203
204     menus = new ssgSimpleState;
205     menus->ref();
206     menus->disable( GL_CULL_FACE );
207     menus->disable( GL_TEXTURE_2D );
208     menus->enable( GL_BLEND );
209 }
210
211
212 // fgInitVisuals() -- Initialize various GL/view parameters
213 void fgInitVisuals( void ) {
214
215     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
216
217     // Go full screen if requested ...
218     if ( fgGetBool("/sim/startup/fullscreen") ) {
219         fgOSFullScreen();
220     }
221
222     // If enabled, normal vectors specified with glNormal are scaled
223     // to unit length after transformation.  Enabling this has
224     // performance implications.  See the docs for glNormal.
225     // glEnable( GL_NORMALIZE );
226
227     glEnable( GL_LIGHTING );
228     glEnable( GL_LIGHT0 );
229     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
230
231     sgVec3 sunpos;
232     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
233     ssgGetLight( 0 ) -> setPosition( sunpos );
234
235     glFogi (GL_FOG_MODE, GL_EXP2);
236     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
237          (!fgGetBool("/sim/rendering/shading"))) {
238         // if fastest fog requested, or if flat shading force fastest
239         glHint ( GL_FOG_HINT, GL_FASTEST );
240     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
241         glHint ( GL_FOG_HINT, GL_NICEST );
242     }
243     if ( fgGetBool("/sim/rendering/wireframe") ) {
244         // draw wire frame
245         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
246     }
247
248     // This is the default anyways, but it can't hurt
249     glFrontFace ( GL_CCW );
250
251     // Just testing ...
252     // glEnable(GL_POINT_SMOOTH);
253     // glEnable(GL_LINE_SMOOTH);
254     // glEnable(GL_POLYGON_SMOOTH);      
255 }
256
257
258 // For HiRes screen Dumps using Brian Pauls TR Library
259 void trRenderFrame( void ) {
260 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
261     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
262 #else
263     bool multi_pass_clouds = false;
264 #endif
265     bool draw_clouds = fgGetBool("/environment/clouds/status");
266
267     if ( fgPanelVisible() ) {
268         GLfloat height = fgGetInt("/sim/startup/ysize");
269         GLfloat view_h =
270             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
271             * (height / 768.0) + 1;
272         glTranslatef( 0.0, view_h, 0.0 );
273     }
274
275     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
276     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
277
278     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
279
280     glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1], 
281                  l->adj_fog_color()[2], l->adj_fog_color()[3]);
282
283     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
284
285     // set the opengl state to known default values
286     default_state->force();
287
288     glEnable( GL_FOG );
289     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
290     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
291     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color() );
292
293     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
294     // we only update GL_AMBIENT for our lights we will never get
295     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
296     // explicitely to black.
297     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
298     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
299
300     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
301
302     // texture parameters
303     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
304     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
305
306     // we need a white diffuse light for the phase of the moon
307     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
308     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
309                      fog_exp2_density );
310
311     // draw the ssg scene
312     // return to the desired diffuse color
313     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
314     glEnable( GL_DEPTH_TEST );
315     ssgSetNearFar( scene_nearplane, scene_farplane );
316     if ( draw_clouds ) {
317         // Draw the terrain
318         FGTileMgr::set_tile_filter( true );
319         sgSetModelFilter( false );
320         globals->get_aircraft_model()->select( false );
321         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
322         // Disable depth buffer update, draw the clouds
323         glDepthMask( GL_FALSE );
324         thesky->drawUpperClouds();
325         if ( multi_pass_clouds ) {
326             thesky->drawLowerClouds();
327         }
328         glDepthMask( GL_TRUE );
329         if ( multi_pass_clouds ) {
330             // Draw the objects except the aircraft
331             //  and update the stencil buffer with 1
332             glEnable( GL_STENCIL_TEST );
333             glStencilFunc( GL_ALWAYS, 1, 1 );
334             glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
335         }
336         FGTileMgr::set_tile_filter( false );
337         sgSetModelFilter( true );
338         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
339         if ( multi_pass_clouds ) {
340             // Disable depth buffer update, draw the clouds where the
341             //  objects overwrite the already drawn clouds, by testing
342             //  the stencil buffer against 1
343             glDepthMask( GL_FALSE );
344             glStencilFunc( GL_EQUAL, 1, 1 );
345             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
346             thesky->drawUpperClouds();
347             thesky->drawLowerClouds();
348             glDepthMask( GL_TRUE );
349             glDisable( GL_STENCIL_TEST );
350         } else {
351             glDepthMask( GL_FALSE );
352             thesky->drawLowerClouds();
353             glDepthMask( GL_TRUE );
354         }
355
356         // Draw the aircraft
357         sgSetModelFilter( false );
358         globals->get_aircraft_model()->select( true );
359         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
360         FGTileMgr::set_tile_filter( true );
361         sgSetModelFilter( true );
362     } else {
363         FGTileMgr::set_tile_filter( true );
364         sgSetModelFilter( true );
365         globals->get_aircraft_model()->select( true );
366         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
367     }
368
369     // draw the lights
370     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
371     ssgSetNearFar( scene_nearplane, scene_farplane );
372     ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
373     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
374
375     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
376
377     if (fgGetBool("/environment/clouds/status"))
378         thesky->drawLowerClouds();
379
380     globals->get_model_mgr()->draw();
381     globals->get_aircraft_model()->draw();
382 }
383
384
385 // Update all Visuals (redraws anything graphics related)
386 void fgRenderFrame() {
387     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
388     bool skyblend = fgGetBool("/sim/rendering/skyblend");
389     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
390     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
391 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
392     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
393 #else
394     bool multi_pass_clouds = false;
395 #endif
396     bool draw_clouds = fgGetBool("/environment/clouds/status");
397
398     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
399     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
400
401     // static const SGPropertyNode *longitude
402     //     = fgGetNode("/position/longitude-deg");
403     // static const SGPropertyNode *latitude
404     //     = fgGetNode("/position/latitude-deg");
405     // static const SGPropertyNode *altitude
406     //     = fgGetNode("/position/altitude-ft");
407     static const SGPropertyNode *groundlevel_nearplane
408         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
409
410     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
411     static double last_visibility = -9999;
412
413     // update fog params
414     double actual_visibility;
415     if (fgGetBool("/environment/clouds/status"))
416         actual_visibility = thesky->get_visibility();
417     else
418         actual_visibility = fgGetDouble("/environment/visibility-m");
419     if ( actual_visibility != last_visibility ) {
420         last_visibility = actual_visibility;
421
422         fog_exp_density = m_log01 / actual_visibility;
423         fog_exp2_density = sqrt_m_log01 / actual_visibility;
424         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
425         if ( actual_visibility < 8000 ) {
426             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
427             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
428         } else {
429             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
430             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
431         }
432     }
433
434     // double angle;
435     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
436     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
437     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
438     // GLfloat mat_shininess[] = { 10.0 };
439     GLbitfield clear_mask;
440
441     if ( idle_state != 1000 ) {
442         // still initializing, draw the splash screen
443         if ( fgGetBool("/sim/startup/splash-screen") ) {
444             fgSplashUpdate(0.0, 1.0);
445         }
446         // Keep resetting sim time while the sim is initializing
447         globals->set_sim_time_sec( 0.0 );
448         SGAnimation::set_sim_time_sec( 0.0 );
449     } else {
450         // idle_state is now 1000 meaning we've finished all our
451         // initializations and are running the main loop, so this will
452         // now work without seg faulting the system.
453
454         FGViewer *current__view = globals->get_current_view();
455
456         // calculate our current position in cartesian space
457         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
458
459         // update view port
460         fgReshape( fgGetInt("/sim/startup/xsize"),
461                    fgGetInt("/sim/startup/ysize") );
462
463         if ( fgGetBool("/sim/rendering/clouds3d") ) {
464             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
465             cloud3d_imposter_state->force();
466             glDisable( GL_FOG );
467             glColor4f( 1.0, 1.0, 1.0, 1.0 );
468             glEnable(GL_DEPTH_TEST);
469             glEnable(GL_BLEND);
470             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
471
472 #ifdef FG_USE_CLOUDS_3D
473             if ( _bcloud_orig ) {
474                 Point3D c = globals->get_scenery()->get_center();
475                 sgClouds3d->Set_Cloud_Orig( &c );
476                 _bcloud_orig = false;
477             }
478             sgClouds3d->Update( current__view->get_absolute_view_pos() );
479 #endif
480             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
481             glDisable(GL_DEPTH_TEST);
482         }
483
484         clear_mask = GL_DEPTH_BUFFER_BIT;
485         if ( fgGetBool("/sim/rendering/wireframe") ) {
486             clear_mask |= GL_COLOR_BUFFER_BIT;
487         }
488
489         if ( skyblend ) {
490             if ( fgGetBool("/sim/rendering/textures") ) {
491             // glClearColor(black[0], black[1], black[2], black[3]);
492             glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
493                          l->adj_fog_color()[2], l->adj_fog_color()[3]);
494             clear_mask |= GL_COLOR_BUFFER_BIT;
495             }
496         } else {
497             glClearColor(l->sky_color()[0], l->sky_color()[1],
498                          l->sky_color()[2], l->sky_color()[3]);
499             clear_mask |= GL_COLOR_BUFFER_BIT;
500         }
501         if ( multi_pass_clouds && draw_clouds ) {
502             glClearStencil( 0 );
503             clear_mask |= GL_STENCIL_BUFFER_BIT;
504         }
505         glClear( clear_mask );
506
507         // Tell GL we are switching to model view parameters
508
509         // I really should create a derived ssg node or use a call
510         // back or something so that I can draw the sky within the
511         // ssgCullAndDraw() function, but for now I just mimic what
512         // ssg does to set up the model view matrix
513         glMatrixMode(GL_MODELVIEW);
514         glLoadIdentity();
515         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
516
517         // set the opengl state to known default values
518         default_state->force();
519
520         // update fog params if visibility has changed
521         double visibility_meters = fgGetDouble("/environment/visibility-m");
522         thesky->set_visibility(visibility_meters);
523
524         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
525                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
526                             / (double)fgGetInt("/sim/model-hz") );
527
528         // Set correct opengl fog density
529         glFogf (GL_FOG_DENSITY, fog_exp2_density);
530
531         // update the sky dome
532         if ( skyblend ) {
533             /*
534              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
535              << l->sky_color()[0] << " "
536              << l->sky_color()[1] << " "
537              << l->sky_color()[2] << " "
538              << l->sky_color()[3] );
539             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
540              << l->fog_color()[0] << " "
541              << l->fog_color()[1] << " "
542              << l->fog_color()[2] << " "
543              << l->fog_color()[3] ); 
544             SG_LOG( SG_GENERAL, SG_BULK,
545                     "    sun_angle = " << l->sun_angle
546              << "    moon_angle = " << l->moon_angle );
547             */
548
549             static SGSkyColor scolor;
550             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
551
552             scolor.sky_color   = l->sky_color();
553             scolor.fog_color   = l->adj_fog_color();
554             scolor.cloud_color = l->cloud_color();
555             scolor.sun_angle   = l->get_sun_angle();
556             scolor.moon_angle  = l->get_moon_angle();
557             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
558             scolor.nstars      = globals->get_ephem()->getNumStars();
559             scolor.planet_data = globals->get_ephem()->getPlanets();
560             scolor.star_data   = globals->get_ephem()->getStars();
561
562             thesky->repaint( scolor );
563
564             /*
565             SG_LOG( SG_GENERAL, SG_BULK,
566                     "thesky->reposition( view_pos = " << view_pos[0] << " "
567              << view_pos[1] << " " << view_pos[2] );
568             SG_LOG( SG_GENERAL, SG_BULK,
569                     "    zero_elev = " << zero_elev[0] << " "
570              << zero_elev[1] << " " << zero_elev[2]
571              << " lon = " << cur_fdm_state->get_Longitude()
572              << " lat = " << cur_fdm_state->get_Latitude() );
573             SG_LOG( SG_GENERAL, SG_BULK,
574                     "    sun_rot = " << l->get_sun_rotation
575              << " gst = " << SGTime::cur_time_params->getGst() );
576             SG_LOG( SG_GENERAL, SG_BULK,
577                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
578               << " sun dec = " << globals->get_ephem()->getSunDeclination()
579               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
580               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
581             */
582
583             // The sun and moon distances are scaled down versions
584             // of the actual distance to get both the moon and the sun
585             // within the range of the far clip plane.
586             // Moon distance:    384,467 kilometers
587             // Sun distance: 150,000,000 kilometers
588             double sun_horiz_eff, moon_horiz_eff;
589             if (fgGetBool("/sim/rendering/horizon-effect")) {
590             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
591             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
592             } else {
593                sun_horiz_eff = moon_horiz_eff = 1.0;
594             }
595
596             static SGSkyState sstate;
597
598             sstate.view_pos  = current__view->get_view_pos();
599             sstate.zero_elev = current__view->get_zero_elev();
600             sstate.view_up   = current__view->get_world_up();
601             sstate.lon       = current__view->getLongitude_deg()
602                                 * SGD_DEGREES_TO_RADIANS;
603             sstate.lat       = current__view->getLatitude_deg()
604                                 * SGD_DEGREES_TO_RADIANS;
605             sstate.alt       = current__view->getAltitudeASL_ft()
606                                 * SG_FEET_TO_METER;
607             sstate.spin      = l->get_sun_rotation();
608             sstate.gst       = globals->get_time_params()->getGst();
609             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
610             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
611             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
612             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
613             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
614             sstate.moon_dist = 40000.0 * moon_horiz_eff;
615
616             thesky->reposition( sstate, delta_time_sec );
617         }
618
619         glEnable( GL_DEPTH_TEST );
620         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
621             glEnable( GL_FOG );
622             glFogi( GL_FOG_MODE, GL_EXP2 );
623             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
624         }
625
626         // set sun/lighting parameters
627         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
628
629         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
630         // we only update GL_AMBIENT for our lights we will never get
631         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
632         // explicitely to black.
633         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
634
635         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
636         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
637         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
638
639         // texture parameters
640         // glEnable( GL_TEXTURE_2D );
641         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
642         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
643
644         // glMatrixMode( GL_PROJECTION );
645         // glLoadIdentity();
646         ssgSetFOV( current__view->get_h_fov(),
647                    current__view->get_v_fov() );
648
649         double agl =
650             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
651             - globals->get_scenery()->get_cur_elev();
652
653         if ( agl > 10.0 ) {
654             scene_nearplane = 10.0f;
655             scene_farplane = 120000.0f;
656         } else {
657             scene_nearplane = groundlevel_nearplane->getDoubleValue();
658             scene_farplane = 120000.0f;
659         }
660
661         ssgSetNearFar( scene_nearplane, scene_farplane );
662
663 #ifdef FG_MPLAYER_AS
664         // Update any multiplayer models
665         globals->get_multiplayer_rx_mgr()->Update();
666 #endif
667
668         if ( draw_otw && skyblend ) {
669             // draw the sky backdrop
670
671             // we need a white diffuse light for the phase of the moon
672             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
673             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
674                              fog_exp2_density );
675             // return to the desired diffuse color
676             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
677         }
678
679         // draw the ssg scene
680         glEnable( GL_DEPTH_TEST );
681
682         ssgSetNearFar( scene_nearplane, scene_farplane );
683
684         if ( fgGetBool("/sim/rendering/wireframe") ) {
685             // draw wire frame
686             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
687         }
688         if ( draw_otw ) {
689             if ( draw_clouds ) {
690
691                 // Draw the terrain
692                 FGTileMgr::set_tile_filter( true );
693                 sgSetModelFilter( false );
694                 globals->get_aircraft_model()->select( false );
695                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
696
697                 // Disable depth buffer update, draw the clouds
698                 glDepthMask( GL_FALSE );
699                 thesky->drawUpperClouds();
700                 if ( multi_pass_clouds ) {
701                     thesky->drawLowerClouds();
702                 }
703                 glDepthMask( GL_TRUE );
704
705                 if ( multi_pass_clouds ) {
706                     // Draw the objects except the aircraft
707                     //  and update the stencil buffer with 1
708                     glEnable( GL_STENCIL_TEST );
709                     glStencilFunc( GL_ALWAYS, 1, 1 );
710                     glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
711                 }
712                 FGTileMgr::set_tile_filter( false );
713                 sgSetModelFilter( true );
714                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
715
716                 if ( multi_pass_clouds ) {
717                     // Disable depth buffer update, draw the clouds where the
718                     //  objects overwrite the already drawn clouds, by testing
719                     //  the stencil buffer against 1
720                     glDepthMask( GL_FALSE );
721                     glStencilFunc( GL_EQUAL, 1, 1 );
722                     glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
723                     thesky->drawUpperClouds();
724                     thesky->drawLowerClouds();
725                     glDepthMask( GL_TRUE );
726                     glDisable( GL_STENCIL_TEST );
727                 } else {
728                     glDepthMask( GL_FALSE );
729                     thesky->drawLowerClouds();
730                     glDepthMask( GL_TRUE );
731                 }
732
733                 // Draw the aircraft
734                 sgSetModelFilter( false );
735                 globals->get_aircraft_model()->select( true );
736                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
737                 FGTileMgr::set_tile_filter( true );
738                 sgSetModelFilter( true );
739             } else {
740                 FGTileMgr::set_tile_filter( true );
741                 sgSetModelFilter( true );
742                 globals->get_aircraft_model()->select( true );
743                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
744             }
745         }
746
747         // This is a bit kludgy.  Every 200 frames, do an extra
748         // traversal of the scene graph without drawing anything, but
749         // with the field-of-view set to 360x360 degrees.  This
750         // ensures that out-of-range random objects that are not in
751         // the current view frustum will still be freed properly.
752         static int counter = 0;
753         counter++;
754         if (counter == 200) {
755           sgFrustum f;
756           f.setFOV(360, 360);
757                             // No need to put the near plane too close;
758                             // this way, at least the aircraft can be
759                             // culled.
760           f.setNearFar(1000, 1000000);
761           sgMat4 m;
762           ssgGetModelviewMatrix(m);
763           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
764           counter = 0;
765         }
766
767         // change state for lighting here
768
769         // draw runway lighting
770         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
771         ssgSetNearFar( scene_nearplane, scene_farplane );
772
773         if ( enhanced_lighting ) {
774
775             // Enable states for drawing points with GL_extension
776             glEnable(GL_POINT_SMOOTH);
777
778             if ( distance_attenuation && glPointParameterIsSupported )
779             {
780                 // Enable states for drawing points with GL_extension
781                 glEnable(GL_POINT_SMOOTH);
782
783                 float quadratic[3] = {1.0, 0.001, 0.0000001};
784                 // makes the points fade as they move away
785                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
786                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
787             }
788
789             glPointSize(4.0);
790
791             // blending function for runway lights
792             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
793         }
794
795         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
796         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
797         glEnable(GL_TEXTURE_GEN_S);
798         glEnable(GL_TEXTURE_GEN_T);
799         glPolygonMode(GL_FRONT, GL_POINT);
800
801         // draw runway lighting
802         if ( draw_otw ) {
803             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
804             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
805         }
806
807         // change punch through and then draw taxi lighting
808         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
809         // sgVec3 taxi_fog;
810         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
811         // glFogfv ( GL_FOG_COLOR, taxi_fog );
812         if ( draw_otw ) {
813             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
814         }
815
816         // clean up lighting
817         glPolygonMode(GL_FRONT, GL_FILL);
818         glDisable(GL_TEXTURE_GEN_S);
819         glDisable(GL_TEXTURE_GEN_T);
820
821         //static int _frame_count = 0;
822         //if (_frame_count % 30 == 0) {
823         //  printf("SSG: %s\n", ssgShowStats());
824         //}
825         //else {
826         //  ssgShowStats();
827         //}
828         //_frame_count++;
829
830
831         if ( enhanced_lighting ) {
832             if ( distance_attenuation && glPointParameterIsSupported )
833             {
834                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
835                                       default_attenuation);
836             }
837
838             glPointSize(1.0);
839             glDisable(GL_POINT_SMOOTH);
840         }
841
842         // draw ground lighting
843         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
844         if ( draw_otw ) {
845             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
846         }
847
848         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
849         {
850             glDisable( GL_FOG );
851             glDisable( GL_LIGHTING );
852             // cout << "drawing new clouds" << endl;
853
854             glEnable(GL_DEPTH_TEST);
855             glEnable(GL_BLEND);
856             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
857
858             /*
859             glEnable( GL_TEXTURE_2D );
860             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
861             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
862             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
863             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
864             */
865
866 #ifdef FG_USE_CLOUDS_3D
867             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
868 #endif
869             glEnable( GL_FOG );
870             glEnable( GL_LIGHTING );
871             glEnable( GL_DEPTH_TEST );
872             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
873         }
874
875         if ( draw_otw ) {
876             globals->get_model_mgr()->draw();
877             globals->get_aircraft_model()->draw();
878         }
879
880         // display HUD && Panel
881         glDisable( GL_FOG );
882         glDisable( GL_DEPTH_TEST );
883         // glDisable( GL_CULL_FACE );
884         // glDisable( GL_TEXTURE_2D );
885
886         // update the controls subsystem
887         globals->get_controls()->update(delta_time_sec);
888
889         hud_and_panel->apply();
890         fgCockpitUpdate();
891
892         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
893         // This only works properly if called before the panel call
894         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
895             globals->get_ATC_display()->update(delta_time_sec);
896
897         // update the panel subsystem
898         if ( globals->get_current_panel() != NULL ) {
899             globals->get_current_panel()->update(delta_time_sec);
900         }
901         fgUpdate3DPanels();
902
903         // We can do translucent menus, so why not. :-)
904         menus->apply();
905         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
906         puDisplay();
907         // glDisable ( GL_BLEND ) ;
908
909         glEnable( GL_DEPTH_TEST );
910         glEnable( GL_FOG );
911
912         // Fade out the splash screen over the first three seconds.
913         double t = globals->get_sim_time_sec();
914         if ( t <= 1.0 ) {
915             fgSplashUpdate(0.0, 1.0);
916         } else if ( t <= 3.0) {
917             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
918         }
919     }
920 }
921
922
923 // Update internal time dependent calculations (i.e. flight model)
924 // FIXME: this distinction is obsolete; all subsystems now get delta
925 // time on update.
926 void fgUpdateTimeDepCalcs() {
927     static bool inited = false;
928
929     static const SGPropertyNode *replay_master
930         = fgGetNode( "/sim/freeze/replay", true );
931     static SGPropertyNode *replay_time
932         = fgGetNode( "/sim/replay/time", true );
933     // static const SGPropertyNode *replay_end_time
934     //     = fgGetNode( "/sim/replay/end-time", true );
935
936     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
937
938     // Initialize the FDM here if it hasn't been and if we have a
939     // scenery elevation hit.
940
941     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
942     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
943
944     if ( !cur_fdm_state->get_inited() &&
945          globals->get_scenery()->get_cur_elev() > -9990 )
946     {
947         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
948         cur_fdm_state->init();
949         if ( cur_fdm_state->get_bound() ) {
950             cur_fdm_state->unbind();
951         }
952         cur_fdm_state->bind();
953     }
954
955     // conceptually, the following block could be done for each fdm
956     // instance ...
957     if ( cur_fdm_state->get_inited() ) {
958         // we have been inited, and  we are good to go ...
959
960         if ( !inited ) {
961             inited = true;
962         }
963
964         if ( ! replay_master->getBoolValue() ) {
965             cur_fdm_state->update( delta_time_sec );
966         } else {
967             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
968             r->replay( replay_time->getDoubleValue() );
969             replay_time->setDoubleValue( replay_time->getDoubleValue()
970                                          + ( delta_time_sec
971                                              * fgGetInt("/sim/speed-up") ) );
972         }
973     } else {
974         // do nothing, fdm isn't inited yet
975     }
976
977     globals->get_model_mgr()->update(delta_time_sec);
978     globals->get_aircraft_model()->update(delta_time_sec);
979
980     // update the view angle
981     globals->get_viewmgr()->update(delta_time_sec);
982
983     // Update solar system
984     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
985                                   globals->get_time_params()->getLst(),
986                                   cur_fdm_state->get_Latitude() );
987
988     // Update radio stack model
989     current_radiostack->update(delta_time_sec);
990 }
991
992
993 void fgInitTimeDepCalcs( void ) {
994     // noop for now
995 }
996
997
998 static const double alt_adjust_ft = 3.758099;
999 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1000
1001
1002 // What should we do when we have nothing else to do?  Let's get ready
1003 // for the next move and update the display?
1004 static void fgMainLoop( void ) {
1005     int model_hz = fgGetInt("/sim/model-hz");
1006
1007     static const SGPropertyNode *longitude
1008         = fgGetNode("/position/longitude-deg");
1009     static const SGPropertyNode *latitude
1010         = fgGetNode("/position/latitude-deg");
1011     static const SGPropertyNode *altitude
1012         = fgGetNode("/position/altitude-ft");
1013     static const SGPropertyNode *clock_freeze
1014         = fgGetNode("/sim/freeze/clock", true);
1015     static const SGPropertyNode *cur_time_override
1016         = fgGetNode("/sim/time/cur-time-override", true);
1017     // static const SGPropertyNode *replay_master
1018     //     = fgGetNode("/sim/freeze/replay", true);
1019
1020     // Update the elapsed time.
1021     static bool first_time = true;
1022     if ( first_time ) {
1023         last_time_stamp.stamp();
1024         first_time = false;
1025     }
1026
1027     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1028     if ( throttle_hz > 0.0 ) {
1029         // simple frame rate throttle
1030         double dt = 1000000.0 / throttle_hz;
1031         current_time_stamp.stamp();
1032         while ( current_time_stamp - last_time_stamp < dt ) {
1033             current_time_stamp.stamp();
1034         }
1035     } else {
1036         // run as fast as the app will go
1037         current_time_stamp.stamp();
1038     }
1039
1040     real_delta_time_sec
1041         = double(current_time_stamp - last_time_stamp) / 1000000.0;
1042     if ( clock_freeze->getBoolValue() ) {
1043         delta_time_sec = 0;
1044     } else {
1045         delta_time_sec = real_delta_time_sec;
1046     }
1047     last_time_stamp = current_time_stamp;
1048     globals->inc_sim_time_sec( delta_time_sec );
1049     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1050
1051     // These are useful, especially for Nasal scripts.
1052     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1053     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1054
1055     static long remainder = 0;
1056     long elapsed;
1057 #ifdef FANCY_FRAME_COUNTER
1058     int i;
1059     double accum;
1060 #else
1061     static time_t last_time = 0;
1062     static int frames = 0;
1063 #endif // FANCY_FRAME_COUNTER
1064
1065     SGTime *t = globals->get_time_params();
1066
1067     globals->get_event_mgr()->update(delta_time_sec);
1068
1069     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1070     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1071
1072 #if defined( ENABLE_PLIB_JOYSTICK )
1073     // Read joystick and update control settings
1074     // if ( fgGetString("/sim/control-mode") == "joystick" )
1075     // {
1076     //    fgJoystickRead();
1077     // }
1078 #endif
1079
1080     // Fix elevation.  I'm just sticking this here for now, it should
1081     // probably move eventually
1082
1083     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1084            scenery.get_cur_elev(),
1085            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1086            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1087
1088     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1089            scenery.get_cur_elev(),
1090            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1091            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1092
1093     // cout << "Warp = " << globals->get_warp() << endl;
1094
1095     // update "time"
1096     static bool last_clock_freeze = false;
1097
1098     if ( clock_freeze->getBoolValue() ) {
1099         // clock freeze requested
1100         if ( cur_time_override->getLongValue() == 0 ) {
1101             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1102             globals->set_warp( 0 );
1103         }
1104     } else {
1105         // no clock freeze requested
1106         if ( last_clock_freeze == true ) {
1107             // clock just unfroze, let's set warp as the difference
1108             // between frozen time and current time so we don't get a
1109             // time jump (and corresponding sky object and lighting
1110             // jump.)
1111             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1112             fgSetLong( "/sim/time/cur-time-override", 0 );
1113         }
1114         if ( globals->get_warp_delta() != 0 ) {
1115             globals->inc_warp( globals->get_warp_delta() );
1116         }
1117     }
1118
1119     last_clock_freeze = clock_freeze->getBoolValue();
1120
1121     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1122                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1123                cur_time_override->getLongValue(),
1124                globals->get_warp() );
1125
1126     if (globals->get_warp_delta() != 0) {
1127         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1128         l->update( 0.5 );
1129     }
1130
1131     // update magvar model
1132     globals->get_mag()->update( longitude->getDoubleValue()
1133                               * SGD_DEGREES_TO_RADIANS,
1134                             latitude->getDoubleValue()
1135                               * SGD_DEGREES_TO_RADIANS,
1136                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1137                             globals->get_time_params()->getJD() );
1138
1139     // Get elapsed time (in usec) for this past frame
1140     elapsed = fgGetTimeInterval();
1141     SG_LOG( SG_ALL, SG_DEBUG, 
1142             "Elapsed time interval is = " << elapsed 
1143             << ", previous remainder is = " << remainder );
1144
1145     // Calculate frame rate average
1146 #ifdef FANCY_FRAME_COUNTER
1147     /* old fps calculation */
1148     if ( elapsed > 0 ) {
1149         double tmp;
1150         accum = 0.0;
1151         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1152             tmp = general.get_frame(i);
1153             accum += tmp;
1154             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1155             general.set_frame(i+1,tmp);
1156         }
1157         tmp = 1000000.0 / (float)elapsed;
1158         general.set_frame(0,tmp);
1159         // printf("frame[0] = %.2f\n", general.frames[0]);
1160         accum += tmp;
1161         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1162         // printf("ave = %.2f\n", general.frame_rate);
1163     }
1164 #else
1165     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1166         general.set_frame_rate( frames );
1167         fgSetInt("/sim/frame-rate", frames);
1168         SG_LOG( SG_ALL, SG_DEBUG, 
1169             "--> Frame rate is = " << general.get_frame_rate() );
1170         frames = 0;
1171     }
1172     last_time = t->get_cur_time();
1173     ++frames;
1174 #endif
1175
1176     // Run ATC subsystem
1177     if (fgGetBool("/sim/ATC/enabled"))
1178         globals->get_ATC_mgr()->update(delta_time_sec);
1179
1180     // Run the AI subsystem
1181     if (fgGetBool("/sim/ai-traffic/enabled"))
1182         globals->get_AI_mgr()->update(delta_time_sec);
1183
1184     // Run flight model
1185
1186     // Calculate model iterations needed for next frame
1187     elapsed += remainder;
1188
1189     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1190     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1191     SG_LOG( SG_ALL, SG_DEBUG, 
1192             "Model iterations needed = " << global_multi_loop
1193             << ", new remainder = " << remainder );
1194         
1195     // chop max interations to something reasonable if the sim was
1196     // delayed for an excesive amount of time
1197     if ( global_multi_loop > 2.0 * model_hz ) {
1198         global_multi_loop = (int)(2.0 * model_hz );
1199         remainder = 0;
1200     }
1201
1202     // flight model
1203     if ( global_multi_loop > 0 ) {
1204         fgUpdateTimeDepCalcs();
1205     } else {
1206         SG_LOG( SG_ALL, SG_DEBUG, 
1207             "Elapsed time is zero ... we're zinging" );
1208     }
1209
1210     // Do any I/O channel work that might need to be done
1211     globals->get_io()->update( real_delta_time_sec );
1212
1213     // see if we need to load any deferred-load textures
1214     globals->get_matlib()->load_next_deferred();
1215
1216     // Run audio scheduler
1217 #ifdef ENABLE_AUDIO_SUPPORT
1218     if ( fgGetBool("/sim/sound/audible")
1219            && globals->get_soundmgr()->is_working() ) {
1220         globals->get_soundmgr()->update( delta_time_sec );
1221     }
1222 #endif
1223
1224     globals->get_subsystem_mgr()->update(delta_time_sec);
1225
1226     //
1227     // Tile Manager updates - see if we need to load any new scenery tiles.
1228     //   this code ties together the fdm, viewer and scenery classes...
1229     //   we may want to move this to it's own class at some point
1230     //
1231     double visibility_meters = fgGetDouble("/environment/visibility-m");
1232     FGViewer *current_view = globals->get_current_view();
1233
1234     // get the location data for the primary FDM (now hardcoded to ac model)...
1235     SGLocation * acmodel_location = 0;
1236     acmodel_location = (SGLocation *)  globals->get_aircraft_model()->get3DModel()->getSGLocation();
1237
1238     // update tile manager for FDM...
1239     // ...only if location is different than the current-view location (to avoid duplicating effort)
1240     if( !fgGetBool("/sim/current-view/config/from-model") ) {
1241       if( acmodel_location != 0 ) {
1242         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1243                                                  visibility_meters );
1244         globals->get_tile_mgr()->
1245             update( acmodel_location, visibility_meters,
1246                     acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1247         // save results of update in SGLocation for fdm...
1248         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1249           acmodel_location->
1250               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1251           fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1252         }
1253         acmodel_location->
1254             set_tile_center( globals->get_scenery()->get_next_center() );
1255       }
1256     }
1257
1258     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1259                                              visibility_meters );
1260     // update tile manager for view...
1261     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1262     // after the FDM's until all of Flight Gear code references the viewer's location
1263     // for elevation instead of the "scenery's" current elevation.
1264     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1265     globals->get_tile_mgr()->update( view_location, visibility_meters,
1266                                      current_view->get_absolute_view_pos() );
1267     // save results of update in SGLocation for fdm...
1268     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1269       current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1270     }
1271     current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1272
1273     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1274     //   above so we need to save the viewer results in the fdm SGLocation as well...
1275     if( fgGetBool("/sim/current-view/config/from-model") ) {
1276       if( acmodel_location != 0 ) {
1277         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1278           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1279           fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1280         }
1281         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1282       }
1283     }
1284
1285     // END Tile Manager udpates
1286
1287     if (fgGetBool("/sim/rendering/specular-highlight")) {
1288         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1289         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1290     } else {
1291         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1292         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1293     }
1294
1295     fgRequestRedraw();
1296
1297     SG_LOG( SG_ALL, SG_DEBUG, "" );
1298 }
1299
1300
1301 // This is the top level master main function that is registered as
1302 // our idle funciton
1303
1304 // The first few passes take care of initialization things (a couple
1305 // per pass) and once everything has been initialized fgMainLoop from
1306 // then on.
1307
1308 static void fgIdleFunction ( void ) {
1309     // printf("idle state == %d\n", idle_state);
1310
1311     if ( idle_state == 0 ) {
1312         // Initialize the splash screen right away
1313         if ( fgGetBool("/sim/startup/splash-screen") ) {
1314             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1315         }
1316         
1317         idle_state++;
1318     } else if ( idle_state == 1 ) {
1319         // Initialize audio support
1320 #ifdef ENABLE_AUDIO_SUPPORT
1321
1322         // Start the intro music
1323         if ( fgGetBool("/sim/startup/intro-music") ) {
1324             SGPath mp3file( globals->get_fg_root() );
1325             mp3file.append( "Sounds/intro.mp3" );
1326
1327             SG_LOG( SG_GENERAL, SG_INFO, 
1328                 "Starting intro music: " << mp3file.str() );
1329
1330 #if defined( __CYGWIN__ )
1331             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1332 #elif defined( WIN32 )
1333             string command = "start /m " + mp3file.str();
1334 #else
1335             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1336 #endif
1337
1338             system ( command.c_str() );
1339         }
1340 #endif
1341
1342         idle_state++;
1343     } else if ( idle_state == 2 ) {
1344         // These are a few miscellaneous things that aren't really
1345         // "subsystems" but still need to be initialized.
1346
1347 #ifdef USE_GLIDE
1348         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1349             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1350         }
1351 #endif
1352
1353         idle_state++;
1354     } else if ( idle_state == 3 ) {
1355         // This is the top level init routine which calls all the
1356         // other subsystem initialization routines.  If you are adding
1357         // a subsystem to flightgear, its initialization call should
1358         // located in this routine.
1359         if( !fgInitSubsystems()) {
1360             SG_LOG( SG_GENERAL, SG_ALERT,
1361                 "Subsystem initializations failed ..." );
1362             exit(-1);
1363         }
1364
1365         idle_state++;
1366     } else if ( idle_state == 4 ) {
1367         // Initialize the time offset (warp) after fgInitSubsystem
1368         // (which initializes the lighting interpolation tables.)
1369         fgInitTimeOffset();
1370
1371         // setup OpenGL view parameters
1372         fgInitVisuals();
1373
1374         // Read the list of available aircrafts
1375         fgReadAircraft();
1376
1377         idle_state++;
1378     } else if ( idle_state == 5 ) {
1379
1380         idle_state++;
1381     } else if ( idle_state == 6 ) {
1382         // sleep(1);
1383
1384         idle_state = 1000;
1385
1386         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1387         fgReshape( fgGetInt("/sim/startup/xsize"),
1388                fgGetInt("/sim/startup/ysize") );
1389
1390     } 
1391
1392     if ( idle_state == 1000 ) {
1393         // We've finished all our initialization steps, from now on we
1394         // run the main loop.
1395
1396         fgRegisterIdleHandler(fgMainLoop);
1397     } else {
1398         if ( fgGetBool("/sim/startup/splash-screen") ) {
1399             fgSplashUpdate(0.0, 1.0);
1400         }
1401     }
1402 }
1403
1404 // options.cxx needs to see this for toggle_panel()
1405 // Handle new window size or exposure
1406 void fgReshape( int width, int height ) {
1407     int view_h;
1408
1409     if ( (!fgGetBool("/sim/virtual-cockpit"))
1410          && fgPanelVisible() && idle_state == 1000 ) {
1411         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1412                              globals->get_current_panel()->getYOffset()) / 768.0);
1413     } else {
1414         view_h = height;
1415     }
1416
1417     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1418
1419     fgSetInt("/sim/startup/xsize", width);
1420     fgSetInt("/sim/startup/ysize", height);
1421     guiInitMouse(width, height);
1422
1423     // for all views
1424     FGViewMgr *viewmgr = globals->get_viewmgr();
1425     if (viewmgr) {
1426       for ( int i = 0; i < viewmgr->size(); ++i ) {
1427         viewmgr->get_view(i)->
1428           set_aspect_ratio((float)view_h / (float)width);
1429       }
1430
1431       ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1432                viewmgr->get_current_view()->get_v_fov() );
1433
1434 #ifdef FG_USE_CLOUDS_3D
1435       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1436                viewmgr->get_current_view()->get_v_fov() );
1437 #endif
1438     }
1439
1440     fgHUDReshape();
1441
1442 }
1443
1444 // Main top level initialization
1445 bool fgMainInit( int argc, char **argv ) {
1446
1447 #if defined( macintosh )
1448     freopen ("stdout.txt", "w", stdout );
1449     freopen ("stderr.txt", "w", stderr );
1450     argc = ccommand( &argv );
1451 #endif
1452
1453     // set default log levels
1454     sglog().setLogLevels( SG_ALL, SG_ALERT );
1455
1456     string version;
1457 #ifdef FLIGHTGEAR_VERSION
1458     version = FLIGHTGEAR_VERSION;
1459 #else
1460     version = "unknown version";
1461 #endif
1462     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1463             << version );
1464     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1465
1466     // Allocate global data structures.  This needs to happen before
1467     // we parse command line options
1468
1469     globals = new FGGlobals;
1470
1471     // seed the random number generater
1472     sg_srandom_time();
1473
1474     FGControls *controls = new FGControls;
1475     globals->set_controls( controls );
1476
1477     string_list *col = new string_list;
1478     globals->set_channel_options_list( col );
1479
1480     // Scan the config file(s) and command line options to see if
1481     // fg_root was specified (ignore all other options for now)
1482     fgInitFGRoot(argc, argv);
1483
1484     // Check for the correct base package version
1485     static char required_version[] = "0.9.4";
1486     string base_version = fgBasePackageVersion();
1487     if ( !(base_version == required_version) ) {
1488         // tell the operator how to use this application
1489
1490         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1491         cerr << endl << "Base package check failed ... " \
1492              << "Found version " << base_version << " at: " \
1493              << globals->get_fg_root() << endl;
1494         cerr << "Please upgrade to version: " << required_version << endl;
1495 #ifdef _MSC_VER
1496         cerr << "Hit a key to continue..." << endl;
1497         cin.get();
1498 #endif
1499         exit(-1);
1500     }
1501
1502     // Initialize the Aircraft directory to "" (UIUC)
1503     aircraft_dir = "";
1504
1505     // Load the configuration parameters.  (Command line options
1506     // overrides config file options.  Config file options override
1507     // defaults.)
1508     if ( !fgInitConfig(argc, argv) ) {
1509         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1510         exit(-1);
1511     }
1512
1513     // Initialize the Window/Graphics environment.
1514 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1515     // Mac OS X command line ("non-bundle") applications call this
1516     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
1517     // feel free to add comments...
1518     fgOSInit(&argc, argv);
1519 #endif
1520
1521     fgRegisterWindowResizeHandler( fgReshape );
1522     fgRegisterIdleHandler( fgIdleFunction );
1523     fgRegisterDrawHandler( fgRenderFrame );
1524
1525 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1526     bool get_stencil_buffer = true;
1527 #else
1528     bool get_stencil_buffer = false;
1529 #endif
1530
1531     // Clouds3D requires an alpha channel
1532     // clouds may require stencil buffer
1533     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1534                     fgGetInt("/sim/startup/ysize"),
1535                     fgGetInt("/sim/rendering/bits-per-pixel"),
1536                     fgGetBool("/sim/rendering/clouds3d"),
1537                     get_stencil_buffer );
1538
1539     // This seems to be the absolute earliest in the init sequence
1540     // that these calls will return valid info.  Too bad it's after
1541     // we've already created and sized out window. :-(
1542     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1543     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1544     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1545     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1546
1547     GLint tmp;
1548     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1549     general.set_glMaxTexSize( tmp );
1550     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1551
1552     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1553     general.set_glDepthBits( tmp );
1554     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1555
1556     // Initialize plib net interface
1557     netInit( &argc, argv );
1558
1559     // Initialize ssg (from plib).  Needs to come before we do any
1560     // other ssg stuff, but after opengl has been initialized.
1561     ssgInit();
1562
1563     // Initialize the user interface (we need to do this before
1564     // passing off control to the OS main loop and before
1565     // fgInitGeneral to get our fonts !!!
1566     guiInit();
1567
1568     // Read the list of available aircrafts
1569     fgReadAircraft();
1570
1571 #ifdef GL_EXT_texture_lod_bias
1572     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1573 #endif
1574
1575             // get the address of our OpenGL extensions
1576     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1577     {
1578         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1579             glPointParameterIsSupported = true;
1580             glPointParameterfPtr = (glPointParameterfProc)
1581                                    SGLookupFunction("glPointParameterfEXT");
1582             glPointParameterfvPtr = (glPointParameterfvProc)
1583                                     SGLookupFunction("glPointParameterfvEXT");
1584
1585         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1586             glPointParameterIsSupported = true;
1587             glPointParameterfPtr = (glPointParameterfProc)
1588                                    SGLookupFunction("glPointParameterfARB");
1589             glPointParameterfvPtr = (glPointParameterfvProc)
1590                                     SGLookupFunction("glPointParameterfvARB");
1591         } else
1592             glPointParameterIsSupported = false;
1593    }
1594
1595     // based on the requested presets, calculate the true starting
1596     // lon, lat
1597     fgInitNav();
1598     fgInitPosition();
1599
1600     SGTime *t = fgInitTime();
1601     globals->set_time_params( t );
1602
1603     // Do some quick general initializations
1604     if( !fgInitGeneral()) {
1605         SG_LOG( SG_GENERAL, SG_ALERT, 
1606             "General initializations failed ..." );
1607         exit(-1);
1608     }
1609
1610     ////////////////////////////////////////////////////////////////////
1611     // Initialize the property-based built-in commands
1612     ////////////////////////////////////////////////////////////////////
1613     fgInitCommands();
1614
1615     ////////////////////////////////////////////////////////////////////
1616     // Initialize the material manager
1617     ////////////////////////////////////////////////////////////////////
1618     globals->set_matlib( new SGMaterialLib );
1619
1620     globals->set_model_lib(new SGModelLib);
1621
1622     ////////////////////////////////////////////////////////////////////
1623     // Initialize the TG scenery subsystem.
1624     ////////////////////////////////////////////////////////////////////
1625     globals->set_scenery( new FGScenery );
1626     globals->get_scenery()->init();
1627     globals->get_scenery()->bind();
1628     globals->set_tile_mgr( new FGTileMgr );
1629
1630     ////////////////////////////////////////////////////////////////////
1631     // Initialize the general model subsystem.
1632     ////////////////////////////////////////////////////////////////////
1633     globals->set_model_mgr(new FGModelMgr);
1634     globals->get_model_mgr()->init();
1635     globals->get_model_mgr()->bind();
1636
1637     ////////////////////////////////////////////////////////////////////
1638     // Initialize the 3D aircraft model subsystem (has a dependency on
1639     // the scenery subsystem.)
1640     ////////////////////////////////////////////////////////////////////
1641     globals->set_aircraft_model(new FGAircraftModel);
1642     globals->get_aircraft_model()->init();
1643     globals->get_aircraft_model()->bind();
1644
1645     ////////////////////////////////////////////////////////////////////
1646     // Initialize the view manager subsystem.
1647     ////////////////////////////////////////////////////////////////////
1648     FGViewMgr *viewmgr = new FGViewMgr;
1649     globals->set_viewmgr( viewmgr );
1650     viewmgr->init();
1651     viewmgr->bind();
1652
1653
1654     // Initialize the sky
1655     SGPath ephem_data_path( globals->get_fg_root() );
1656     ephem_data_path.append( "Astro" );
1657     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1658     ephem->update( globals->get_time_params()->getMjd(),
1659                    globals->get_time_params()->getLst(),
1660                    0.0 );
1661     globals->set_ephem( ephem );
1662
1663     // TODO: move to environment mgr
1664     thesky = new SGSky;
1665     SGPath texture_path(globals->get_fg_root());
1666     texture_path.append("Textures");
1667     texture_path.append("Sky");
1668     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1669         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1670         thesky->add_cloud_layer(layer);
1671     }
1672
1673     SGPath sky_tex_path( globals->get_fg_root() );
1674     sky_tex_path.append( "Textures" );
1675     sky_tex_path.append( "Sky" );
1676     thesky->texture_path( sky_tex_path.str() );
1677
1678     // The sun and moon diameters are scaled down numbers of the
1679     // actual diameters. This was needed to fit bot the sun and the
1680     // moon within the distance to the far clip plane.
1681     // Moon diameter:    3,476 kilometers
1682     // Sun diameter: 1,390,000 kilometers
1683     thesky->build( 80000.0, 80000.0,
1684                    463.3, 361.8,
1685                    globals->get_ephem()->getNumPlanets(), 
1686                    globals->get_ephem()->getPlanets(),
1687                    globals->get_ephem()->getNumStars(),
1688                    globals->get_ephem()->getStars() );
1689
1690     // Initialize MagVar model
1691     SGMagVar *magvar = new SGMagVar();
1692     globals->set_mag( magvar );
1693
1694
1695                                 // kludge to initialize mag compass
1696                                 // (should only be done for in-flight
1697                                 // startup)
1698     // update magvar model
1699     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1700                                 * SGD_DEGREES_TO_RADIANS,
1701                                 fgGetDouble("/position/latitude-deg")
1702                                 * SGD_DEGREES_TO_RADIANS,
1703                                 fgGetDouble("/position/altitude-ft")
1704                                 * SG_FEET_TO_METER,
1705                                 globals->get_time_params()->getJD() );
1706     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1707     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1708
1709     // airport = new ssgBranch;
1710     // airport->setName( "Airport Lighting" );
1711     // lighting->addKid( airport );
1712
1713     // build our custom render states
1714     fgBuildRenderStates();
1715     
1716     // pass control off to the master event handler
1717     fgOSMainLoop();
1718
1719     // we never actually get here ... but to avoid compiler warnings,
1720     // etc.
1721     return false;
1722 }
1723
1724
1725 // end of main.cxx