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