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