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