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