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