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