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