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