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