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