]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Added support for additional animated, dynamic 3D models configured in
[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 // ssg variables
187 ssgRoot *scene = NULL;
188 ssgBranch *terrain_branch = NULL;
189 ssgBranch *gnd_lights_branch = NULL;
190 ssgBranch *rwy_lights_branch = NULL;
191
192 // fog constants.  I'm a little nervous about putting actual code out
193 // here but it seems to work (?)
194 static const double m_log01 = -log( 0.01 );
195 static const double sqrt_m_log01 = sqrt( m_log01 );
196 static GLfloat fog_exp_density;
197 static GLfloat fog_exp2_density;
198 static GLfloat fog_exp2_punch_through;
199
200 ssgRoot *lighting = NULL;
201 // ssgBranch *airport = NULL;
202
203 #ifdef FG_NETWORK_OLK
204 ssgSelector *fgd_sel = NULL;
205 ssgTransform *fgd_pos = NULL;
206 #endif
207
208 // current fdm/position used for view
209 FGInterface cur_view_fdm;
210
211 // Sky structures
212 SGSky *thesky;
213
214 // hack
215 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
216 {
217   {  1.0f,  0.0f,  0.0f,  0.0f },
218   {  0.0f,  0.0f, -1.0f,  0.0f },
219   {  0.0f,  1.0f,  0.0f,  0.0f },
220   {  0.0f,  0.0f,  0.0f,  1.0f }
221 };
222
223 // The following defines flightgear options. Because glutlib will also
224 // want to parse its own options, those options must not be included here
225 // or they will get parsed by the main program option parser. Hence case
226 // is significant for any option added that might be in conflict with
227 // glutlib's parser.
228 //
229 // glutlib parses for:
230 //    -display
231 //    -direct   (invalid in Win32)
232 //    -geometry
233 //    -gldebug
234 //    -iconized
235 //    -indirect (invalid in Win32)
236 //    -synce
237 //
238 // Note that glutlib depends upon strings while this program's
239 // option parser wants only initial characters followed by numbers
240 // or pathnames.
241 //
242
243
244 ssgSimpleState *default_state;
245 ssgSimpleState *hud_and_panel;
246 ssgSimpleState *menus;
247
248 SGTimeStamp start_time_stamp;
249 SGTimeStamp current_time_stamp;
250
251 void fgBuildRenderStates( void ) {
252     default_state = new ssgSimpleState;
253     default_state->ref();
254     default_state->disable( GL_TEXTURE_2D );
255     default_state->enable( GL_CULL_FACE );
256     default_state->enable( GL_COLOR_MATERIAL );
257     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
258     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
259     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
260     default_state->disable( GL_BLEND );
261     default_state->disable( GL_ALPHA_TEST );
262     default_state->disable( GL_LIGHTING );
263
264     hud_and_panel = new ssgSimpleState;
265     hud_and_panel->ref();
266     hud_and_panel->disable( GL_CULL_FACE );
267     hud_and_panel->disable( GL_TEXTURE_2D );
268     hud_and_panel->disable( GL_LIGHTING );
269     hud_and_panel->enable( GL_BLEND );
270
271     menus = new ssgSimpleState;
272     menus->ref();
273     menus->disable( GL_CULL_FACE );
274     menus->disable( GL_TEXTURE_2D );
275     menus->enable( GL_BLEND );
276 }
277
278
279 // fgInitVisuals() -- Initialize various GL/view parameters
280 void fgInitVisuals( void ) {
281     fgLIGHT *l;
282
283     l = &cur_light_params;
284
285 #ifndef GLUT_WRONG_VERSION
286     // Go full screen if requested ...
287     if ( fgGetBool("/sim/startup/fullscreen") ) {
288         glutFullScreen();
289     }
290 #endif
291
292     // If enabled, normal vectors specified with glNormal are scaled
293     // to unit length after transformation.  Enabling this has
294     // performance implications.  See the docs for glNormal.
295     // glEnable( GL_NORMALIZE );
296
297     glEnable( GL_LIGHTING );
298     glEnable( GL_LIGHT0 );
299     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
300
301     sgVec3 sunpos;
302     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
303     ssgGetLight( 0 ) -> setPosition( sunpos );
304
305     glFogi (GL_FOG_MODE, GL_EXP2);
306     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
307          (!fgGetBool("/sim/rendering/shading"))) {
308         // if fastest fog requested, or if flat shading force fastest
309         glHint ( GL_FOG_HINT, GL_FASTEST );
310     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
311         glHint ( GL_FOG_HINT, GL_NICEST );
312     }
313     if ( fgGetBool("/sim/rendering/wireframe") ) {
314         // draw wire frame
315         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
316     }
317
318     // This is the default anyways, but it can't hurt
319     glFrontFace ( GL_CCW );
320
321     // Just testing ...
322     // glEnable(GL_POINT_SMOOTH);
323     // glEnable(GL_LINE_SMOOTH);
324     // glEnable(GL_POLYGON_SMOOTH);      
325 }
326
327
328 // For HiRes screen Dumps using Brian Pauls TR Library
329 void trRenderFrame( void ) {
330
331     if ( fgPanelVisible() ) {
332         GLfloat height = fgGetInt("/sim/startup/ysize");
333         GLfloat view_h =
334             (current_panel->getViewHeight() - current_panel->getYOffset())
335             * (height / 768.0) + 1;
336         glTranslatef( 0.0, view_h, 0.0 );
337     }
338
339     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
340     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
341
342     fgLIGHT *l = &cur_light_params;
343
344     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
345                  l->adj_fog_color[2], l->adj_fog_color[3]);
346
347     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
348
349     // set the opengl state to known default values
350     default_state->force();
351
352     glEnable( GL_FOG );
353     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
354     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
355     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
356
357     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
358     // we only update GL_AMBIENT for our lights we will never get
359     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
360     // explicitely to black.
361     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
362
363     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
364
365     // texture parameters
366     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
367     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
368
369     // we need a white diffuse light for the phase of the moon
370     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
371     thesky->preDraw();
372
373     // draw the ssg scene
374     // return to the desired diffuse color
375     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
376     glEnable( GL_DEPTH_TEST );
377     ssgSetNearFar( scene_nearplane, scene_farplane );
378     ssgCullAndDraw( scene );
379
380     // draw the lights
381     glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
382     ssgSetNearFar( scene_nearplane, scene_farplane );
383     ssgCullAndDraw( lighting );
384
385     thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
386
387     globals->get_model_mgr()->draw();
388     globals->get_aircraft_model()->draw();
389
390     // need to do this here as hud_and_panel state is static to
391     // main.cxx  and HUD and Panel routines have to be called with
392     // knowledge of the the TR struct < see gui.cxx::HighResDump()
393     hud_and_panel->apply();
394 }
395
396
397 // Update all Visuals (redraws anything graphics related)
398 void fgRenderFrame( void ) {
399   
400     static long old_elapsed_ms = 0;
401
402     int dt_ms = int(globals->get_elapsed_time_ms() - old_elapsed_ms);
403     old_elapsed_ms = globals->get_elapsed_time_ms();
404
405     // Process/manage pending events
406     global_events.update( dt_ms );
407
408     static const SGPropertyNode *longitude
409         = fgGetNode("/position/longitude-deg");
410     static const SGPropertyNode *latitude
411         = fgGetNode("/position/latitude-deg");
412     static const SGPropertyNode *altitude
413         = fgGetNode("/position/altitude-ft");
414
415     // Update the default (kludged) properties.
416     fgUpdateProps();
417
418     FGViewer *current__view = globals->get_current_view();
419
420     fgLIGHT *l = &cur_light_params;
421     static double last_visibility = -9999;
422
423     // update fog params
424     double actual_visibility       = thesky->get_visibility();
425     if ( actual_visibility != last_visibility ) {
426         last_visibility = actual_visibility;
427
428         fog_exp_density = m_log01 / actual_visibility;
429         fog_exp2_density = sqrt_m_log01 / actual_visibility;
430         fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
431     }
432
433     // double angle;
434     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
435     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
436     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
437     // GLfloat mat_shininess[] = { 10.0 };
438     GLbitfield clear_mask;
439     
440     if ( idle_state != 1000 ) {
441         // still initializing, draw the splash screen
442         if ( fgGetBool("/sim/startup/splash-screen") ) {
443             fgSplashUpdate(0.0);
444         }
445         start_time_stamp.stamp(); // Keep resetting the start time
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         // Update the elapsed time.
452         current_time_stamp.stamp();
453         globals->set_elapsed_time_ms( (current_time_stamp - start_time_stamp)
454                                       / 1000L );
455
456         // calculate our current position in cartesian space
457         scenery.set_center( scenery.get_next_center() );
458
459         // update view port
460         fgReshape( fgGetInt("/sim/startup/xsize"),
461                    fgGetInt("/sim/startup/ysize") );
462
463         // set the sun position
464         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
465
466         clear_mask = GL_DEPTH_BUFFER_BIT;
467         if ( fgGetBool("/sim/rendering/wireframe") ) {
468             clear_mask |= GL_COLOR_BUFFER_BIT;
469         }
470
471         if ( fgGetBool("/sim/rendering/skyblend") ) {
472             if ( fgGetBool("/sim/rendering/textures") ) {
473                 // glClearColor(black[0], black[1], black[2], black[3]);
474                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
475                              l->adj_fog_color[2], l->adj_fog_color[3]);
476                 clear_mask |= GL_COLOR_BUFFER_BIT;
477             }
478         } else {
479             glClearColor(l->sky_color[0], l->sky_color[1], 
480                          l->sky_color[2], l->sky_color[3]);
481             clear_mask |= GL_COLOR_BUFFER_BIT;
482         }
483         glClear( clear_mask );
484
485         // Tell GL we are switching to model view parameters
486
487         // I really should create a derived ssg node or use a call
488         // back or something so that I can draw the sky within the
489         // ssgCullAndDraw() function, but for now I just mimic what
490         // ssg does to set up the model view matrix
491         glMatrixMode(GL_MODELVIEW);
492         glLoadIdentity();
493         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
494
495         // set the opengl state to known default values
496         default_state->force();
497
498         // update fog params if visibility has changed
499         double visibility_meters = fgGetDouble("/environment/visibility-m");
500         thesky->set_visibility(visibility_meters);
501
502         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
503                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
504                             / (double)fgGetInt("/sim/model-hz") );
505
506         // Set correct opengl fog density
507         glFogf (GL_FOG_DENSITY, fog_exp2_density);
508
509         // update the sky dome
510         if ( fgGetBool("/sim/rendering/skyblend") ) {
511             /* cout << "thesky->repaint() sky_color = "
512                  << cur_light_params.sky_color[0] << " "
513                  << cur_light_params.sky_color[1] << " "
514                  << cur_light_params.sky_color[2] << " "
515                  << cur_light_params.sky_color[3] << endl;
516             cout << "    fog = "
517                  << cur_light_params.fog_color[0] << " "
518                  << cur_light_params.fog_color[1] << " "
519                  << cur_light_params.fog_color[2] << " "
520                  << cur_light_params.fog_color[3] << endl;
521             cout << "    sun_angle = " << cur_light_params.sun_angle
522                  << "    moon_angle = " << cur_light_params.moon_angle
523                  << endl; */
524             thesky->repaint( cur_light_params.sky_color,
525                              cur_light_params.adj_fog_color,
526                              cur_light_params.sun_angle,
527                              cur_light_params.moon_angle,
528                              globals->get_ephem()->getNumPlanets(),
529                              globals->get_ephem()->getPlanets(),
530                              globals->get_ephem()->getNumStars(),
531                              globals->get_ephem()->getStars() );
532  
533             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
534                  << view_pos[1] << " " << view_pos[2] << endl;
535             cout << "    zero_elev = " << zero_elev[0] << " "
536                  << zero_elev[1] << " " << zero_elev[2]
537                  << " lon = " << cur_fdm_state->get_Longitude()
538                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
539             cout << "    sun_rot = " << cur_light_params.sun_rotation
540                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
541             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
542                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
543                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
544                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
545
546             thesky->reposition( current__view->get_view_pos(),
547                                 current__view->get_zero_elev(),
548                                 current__view->get_world_up(),
549                                 longitude->getDoubleValue()
550                                   * SGD_DEGREES_TO_RADIANS,
551                                 latitude->getDoubleValue()
552                                   * SGD_DEGREES_TO_RADIANS,
553                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
554                                 cur_light_params.sun_rotation,
555                                 globals->get_time_params()->getGst(),
556                                 globals->get_ephem()->getSunRightAscension(),
557                                 globals->get_ephem()->getSunDeclination(),
558                                 50000.0,
559                                 globals->get_ephem()->getMoonRightAscension(),
560                                 globals->get_ephem()->getMoonDeclination(),
561                                 50000.0 );
562         }
563
564         glEnable( GL_DEPTH_TEST );
565         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
566             glEnable( GL_FOG );
567             glFogi( GL_FOG_MODE, GL_EXP2 );
568             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
569         }
570
571         // set sun/lighting parameters
572         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
573
574         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
575         // we only update GL_AMBIENT for our lights we will never get
576         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
577         // explicitely to black.
578         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
579         GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
580         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
581
582         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
583         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
584         // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
585
586         // texture parameters
587         // glEnable( GL_TEXTURE_2D );
588         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
589         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
590
591         // glMatrixMode( GL_PROJECTION );
592         // glLoadIdentity();
593         ssgSetFOV( current__view->get_h_fov(),
594                    current__view->get_v_fov() );
595
596         double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
597             - scenery.get_cur_elev();
598
599 //      if (fgGetBool("/sim/view/internal"))
600 //        ssgSetNearFar( 0.2f, 120000.0f );
601 //      else if ( agl > 10.0)
602
603         if ( agl > 10.0 ) {
604             scene_nearplane = 10.0f;
605             scene_farplane = 120000.0f;
606         } else {
607             scene_nearplane = 0.5f;
608             scene_farplane = 120000.0f;
609         }
610
611         ssgSetNearFar( scene_nearplane, scene_farplane );
612
613         // $$$ begin - added VS Renganthan 17 Oct 2K
614         if(objc)
615           fgUpdateDCS();
616         // $$$ end - added VS Renganthan 17 Oct 2K
617
618 # ifdef FG_NETWORK_OLK
619         if ( fgGetBool("/sim/networking/network-olk") ) {
620             sgCoord fgdpos;
621             other = head->next;             /* put listpointer to start  */
622             while ( other != tail) {        /* display all except myself */
623                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
624                     other->fgd_sel->select(1);
625                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
626                     other->fgd_pos->setTransform( &fgdpos );
627                 }
628                 other = other->next;
629             }
630
631             // fgd_sel->select(1);
632             // sgCopyMat4( sgTUX, current_view.sgVIEW);
633             // sgCoord fgdpos;
634             // sgSetCoord( &fgdpos, sgFGD_VIEW );
635             // fgd_pos->setTransform( &fgdpos);
636         }
637 # endif
638
639         // position tile nodes and update range selectors
640         global_tile_mgr.prep_ssg_nodes(visibility_meters);
641
642         if ( fgGetBool("/sim/rendering/skyblend") ) {
643             // draw the sky backdrop
644
645             // we need a white diffuse light for the phase of the moon
646             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
647
648             thesky->preDraw();
649
650             // return to the desired diffuse color
651             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
652         }
653
654         // draw the ssg scene
655         glEnable( GL_DEPTH_TEST );
656
657         ssgSetNearFar( scene_nearplane, scene_farplane );
658         ssgCullAndDraw( scene );
659
660         // change state for lighting here
661
662         // draw lighting
663         // Set punch through fog density
664         glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
665
666 #ifdef FG_EXPERIMENTAL_LIGHTING
667         // Enable states for drawing points with GL_extension
668         if (glutExtensionSupported("GL_EXT_point_parameters")) {
669             glEnable(GL_POINT_SMOOTH);
670             float quadratic[3] = {1.0, 0.01, 0.0001};
671             // get the address of our OpenGL extensions
672 #if !defined(sgi)
673             glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC) 
674                 wglGetProcAddress("glPointParameterfEXT");
675             glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC) 
676                 wglGetProcAddress("glPointParameterfvEXT");
677 #endif
678             // makes the points fade as they move away
679             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
680             glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
681             glPointSize(4.0);
682
683             // Enable states for drawing runway lights with spherical mapping
684             glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
685             glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
686             glEnable(GL_TEXTURE_GEN_S);
687             glEnable(GL_TEXTURE_GEN_T);
688
689             //Maybe this is not the best way, but it works !!
690             glPolygonMode(GL_FRONT, GL_POINT);
691             glCullFace(GL_BACK);
692             glEnable(GL_CULL_FACE);
693         }
694
695         glDisable( GL_LIGHTING );
696         // blending function for runway lights
697         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
698         glEnable(GL_BLEND);
699 #endif
700
701         ssgSetNearFar( scene_nearplane, scene_farplane );
702         ssgCullAndDraw( lighting );
703
704
705 #ifdef FG_EXPERIMENTAL_LIGHTING
706         if (glutExtensionSupported("GL_EXT_point_parameters")) {
707             // Disable states used for runway lighting
708             glPolygonMode(GL_FRONT, GL_FILL);
709
710             glDisable(GL_TEXTURE_GEN_S);
711             glDisable(GL_TEXTURE_GEN_T);
712             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
713                                   default_attenuation);
714         }
715
716         glPointSize(1.0);
717 #endif
718
719         if ( fgGetBool("/sim/rendering/skyblend") ) {
720             // draw the sky cloud layers
721             thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
722         }
723
724         globals->get_model_mgr()->draw();
725         globals->get_aircraft_model()->draw();
726
727         // display HUD && Panel
728         glDisable( GL_FOG );
729         glDisable( GL_DEPTH_TEST );
730         // glDisable( GL_CULL_FACE );
731         // glDisable( GL_TEXTURE_2D );
732
733         // update the input subsystem
734         current_input.update(dt_ms);
735
736         // update the controls subsystem
737         globals->get_controls()->update(dt_ms);
738
739         hud_and_panel->apply();
740         fgCockpitUpdate();
741
742         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
743         // This only works properly if called before the panel call
744         globals->get_ATC_display()->update(dt_ms);
745
746         // update the panel subsystem
747         if ( current_panel != NULL ) {
748             current_panel->update(dt_ms);
749         }
750
751         // We can do translucent menus, so why not. :-)
752         menus->apply();
753         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
754         puDisplay();
755         // glDisable ( GL_BLEND ) ;
756
757         // glEnable( GL_FOG );
758
759         globals->get_logger()->update(dt_ms);
760     }
761
762     glutSwapBuffers();
763 }
764
765
766 // Update internal time dependent calculations (i.e. flight model)
767 void fgUpdateTimeDepCalcs() {
768     static bool inited = false;
769     static const SGPropertyNode *master_freeze
770         = fgGetNode("/sim/freeze/master");
771
772     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
773
774     fgLIGHT *l = &cur_light_params;
775     int i;
776
777     long multi_loop = 1;
778
779     // Initialize the FDM here if it hasn't been and if we have a
780     // scenery elevation hit.
781
782     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
783     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
784
785     if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
786         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
787         
788         cur_fdm_state->init();
789         if ( cur_fdm_state->get_bound() ) {
790             cur_fdm_state->unbind();
791         }
792         cur_fdm_state->bind();
793     }
794
795     // conceptually, the following block could be done for each fdm
796     // instance ...
797     if ( !cur_fdm_state->get_inited() ) {
798         // do nothing, fdm isn't inited yet
799     } else if ( master_freeze->getBoolValue() ) {
800         // we are frozen, run the fdm's with 0 time slices in case
801         // they want to do something with that.
802
803         cur_fdm_state->update( 0 );
804         FGSteam::update( 0 );
805     } else {
806         // we have been inited, and we are not frozen, we are good to go ...
807
808         if ( !inited ) {
809             cur_fdm_state->stamp();
810             inited = true;
811         }
812
813         SGTimeStamp current;
814         current.stamp();
815         long elapsed = current - cur_fdm_state->get_time_stamp();
816         cur_fdm_state->set_time_stamp( current );
817         elapsed += cur_fdm_state->get_remainder();
818         // cout << "elapsed = " << elapsed << endl;
819         // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
820         multi_loop = (long)(((double)elapsed * 0.000001) /
821                                cur_fdm_state->get_delta_t() );
822         cur_fdm_state->set_multi_loop( multi_loop );
823         long remainder = elapsed - (long)( (multi_loop*1000000) *
824                                      cur_fdm_state->get_delta_t() );
825         cur_fdm_state->set_remainder( remainder );
826         // cout << "remainder = " << remainder << endl;
827
828         // chop max interations to something reasonable if the sim was
829         // delayed for an excesive amount of time
830         if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
831             multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
832             cur_fdm_state->set_remainder( 0 );
833         }
834
835         // cout << "multi_loop = " << multi_loop << endl;
836         for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
837             // run Autopilot system
838             globals->get_autopilot()->update(0); // FIXME: use real dt
839
840             // update FDM
841             cur_fdm_state->update( 1 );
842         }
843         FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
844     }
845
846     if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
847         cur_view_fdm = *cur_fdm_state;
848         // do nothing
849     }
850
851
852     globals->get_model_mgr()->update(multi_loop);
853     globals->get_aircraft_model()->update(multi_loop);
854
855     // update the view angle
856     globals->get_viewmgr()->update(multi_loop);
857
858     l->UpdateAdjFog();
859
860     // Update solar system
861     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
862                                   globals->get_time_params()->getLst(),
863                                   cur_fdm_state->get_Latitude() );
864
865     // Update radio stack model
866     current_radiostack->update(multi_loop);
867 }
868
869
870 void fgInitTimeDepCalcs( void ) {
871     // noop for now
872 }
873
874
875 static const double alt_adjust_ft = 3.758099;
876 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
877
878
879 // What should we do when we have nothing else to do?  Let's get ready
880 // for the next move and update the display?
881 static void fgMainLoop( void ) {
882     static const SGPropertyNode *longitude
883         = fgGetNode("/position/longitude-deg");
884     static const SGPropertyNode *latitude
885         = fgGetNode("/position/latitude-deg");
886     static const SGPropertyNode *altitude
887         = fgGetNode("/position/altitude-ft");
888     static const SGPropertyNode *clock_freeze
889         = fgGetNode("/sim/freeze/clock", true);
890     static const SGPropertyNode *cur_time_override
891         = fgGetNode("/sim/time/cur-time-override", true);
892
893     static long remainder = 0;
894     long elapsed;
895 #ifdef FANCY_FRAME_COUNTER
896     int i;
897     double accum;
898 #else
899     static time_t last_time = 0;
900     static int frames = 0;
901 #endif // FANCY_FRAME_COUNTER
902
903     SGTime *t = globals->get_time_params();
904
905     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
906     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
907
908 #ifdef FG_NETWORK_OLK
909     if ( fgGetBool("/sim/networking/network-olk") ) {
910         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
911             // printf("FGD: Netupdate\n");
912             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
913             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
914         }
915     }
916 #endif
917
918 #if defined( ENABLE_PLIB_JOYSTICK )
919     // Read joystick and update control settings
920     // if ( fgGetString("/sim/control-mode") == "joystick" )
921     // {
922     //    fgJoystickRead();
923     // }
924 #elif defined( ENABLE_GLUT_JOYSTICK )
925     // Glut joystick support works by feeding a joystick handler
926     // function to glut.  This is taken care of once in the joystick
927     // init routine and we don't have to worry about it again.
928 #endif
929
930 #ifdef FG_NEW_ENVIRONMENT
931     globals->get_environment_mgr()->update(0);  // FIXME: use real delta time
932 #endif
933
934     // Fix elevation.  I'm just sticking this here for now, it should
935     // probably move eventually
936
937     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
938            scenery.get_cur_elev(),
939            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
940            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
941
942     if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
943         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
944              (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
945             // now set aircraft altitude above ground
946             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
947                    cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
948                    scenery.get_cur_elev() + alt_adjust_m - 3.0,
949                    scenery.get_cur_elev() + alt_adjust_m );
950             cur_fdm_state->set_Altitude( scenery.get_cur_elev() 
951                                                 + alt_adjust_m );
952
953             SG_LOG( SG_ALL, SG_DEBUG, 
954                     "<*> resetting altitude to " 
955                     << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
956                     << " meters" );
957         }
958     }
959
960     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
961            scenery.get_cur_elev(),
962            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
963            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
964
965     // cout << "Warp = " << globals->get_warp() << endl;
966
967     // update "time"
968     static bool last_clock_freeze = false;
969
970     if ( clock_freeze->getBoolValue() ) {
971         // clock freeze requested
972         if ( cur_time_override->getLongValue() == 0 ) {
973             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
974             globals->set_warp( 0 );
975         }
976     } else {
977         // no clock freeze requested
978         if ( last_clock_freeze == true ) {
979             // clock just unfroze, let's set warp as the difference
980             // between frozen time and current time so we don't get a
981             // time jump (and corresponding sky object and lighting
982             // jump.)
983             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
984             fgSetLong( "/sim/time/cur-time-override", 0 );
985         }
986         if ( globals->get_warp_delta() != 0 ) {
987             globals->inc_warp( globals->get_warp_delta() );
988         }
989     }
990
991     last_clock_freeze = clock_freeze->getBoolValue();
992
993     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
994                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
995                cur_time_override->getLongValue(),
996                globals->get_warp() );
997
998     if ( globals->get_warp_delta() != 0 ) {
999         fgUpdateSkyAndLightingParams();
1000     }
1001
1002     // update magvar model
1003     globals->get_mag()->update( longitude->getDoubleValue()
1004                                   * SGD_DEGREES_TO_RADIANS,
1005                                 latitude->getDoubleValue()
1006                                   * SGD_DEGREES_TO_RADIANS,
1007                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
1008                                 globals->get_time_params()->getJD() );
1009
1010     // Get elapsed time (in usec) for this past frame
1011     elapsed = fgGetTimeInterval();
1012     SG_LOG( SG_ALL, SG_DEBUG, 
1013             "Elapsed time interval is = " << elapsed 
1014             << ", previous remainder is = " << remainder );
1015
1016     // Calculate frame rate average
1017 #ifdef FANCY_FRAME_COUNTER
1018     /* old fps calculation */
1019     if ( elapsed > 0 ) {
1020         double tmp;
1021         accum = 0.0;
1022         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1023             tmp = general.get_frame(i);
1024             accum += tmp;
1025             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1026             general.set_frame(i+1,tmp);
1027         }
1028         tmp = 1000000.0 / (float)elapsed;
1029         general.set_frame(0,tmp);
1030         // printf("frame[0] = %.2f\n", general.frames[0]);
1031         accum += tmp;
1032         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1033         // printf("ave = %.2f\n", general.frame_rate);
1034     }
1035 #else
1036     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1037         general.set_frame_rate( frames );
1038         SG_LOG( SG_ALL, SG_DEBUG, 
1039                 "--> Frame rate is = " << general.get_frame_rate() );
1040         frames = 0;
1041     }
1042     last_time = t->get_cur_time();
1043     ++frames;
1044 #endif
1045
1046     // Run ATC subsystem
1047     globals->get_ATC_mgr()->update(1);  // FIXME - use real dt.
1048
1049     // Run the AI subsystem
1050     globals->get_AI_mgr()->update(1);   // FIXME - use real dt.
1051
1052     // Run flight model
1053
1054     // Calculate model iterations needed for next frame
1055     elapsed += remainder;
1056
1057     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1058                               fgGetInt("/sim/model-hz"));
1059     remainder = elapsed - ( (global_multi_loop*1000000) / 
1060                             fgGetInt("/sim/model-hz") );
1061     SG_LOG( SG_ALL, SG_DEBUG, 
1062             "Model iterations needed = " << global_multi_loop
1063             << ", new remainder = " << remainder );
1064         
1065     // chop max interations to something reasonable if the sim was
1066     // delayed for an excesive amount of time
1067     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1068         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1069         remainder = 0;
1070     }
1071
1072     // flight model
1073     if ( global_multi_loop > 0 ) {
1074         fgUpdateTimeDepCalcs();
1075     } else {
1076         SG_LOG( SG_ALL, SG_DEBUG, 
1077                 "Elapsed time is zero ... we're zinging" );
1078     }
1079
1080 #if ! defined( macintosh )
1081     // Do any I/O channel work that might need to be done
1082     fgIOProcess();
1083 #endif
1084
1085     // see if we need to load any new scenery tiles
1086     double visibility_meters = fgGetDouble("/environment/visibility-m");
1087     global_tile_mgr.update( longitude->getDoubleValue(),
1088                             latitude->getDoubleValue(), visibility_meters );
1089
1090     // see if we need to load any deferred-load textures
1091     material_lib.load_next_deferred();
1092
1093     // Run audio scheduler
1094 #ifdef ENABLE_AUDIO_SUPPORT
1095     if ( fgGetBool("/sim/sound/audible")
1096            && globals->get_soundmgr()->is_working() ) {
1097         globals->get_fx()->update(1); // FIXME: use dt
1098         globals->get_soundmgr()->update(1); // FIXME: use dt
1099     }
1100 #endif
1101
1102     // redraw display
1103     fgRenderFrame();
1104
1105     SG_LOG( SG_ALL, SG_DEBUG, "" );
1106 }
1107
1108
1109 // This is the top level master main function that is registered as
1110 // our idle funciton
1111
1112 // The first few passes take care of initialization things (a couple
1113 // per pass) and once everything has been initialized fgMainLoop from
1114 // then on.
1115
1116 static void fgIdleFunction ( void ) {
1117     // printf("idle state == %d\n", idle_state);
1118
1119     if ( idle_state == 0 ) {
1120         // Initialize the splash screen right away
1121         if ( fgGetBool("/sim/startup/splash-screen") ) {
1122             fgSplashInit();
1123         }
1124         
1125         idle_state++;
1126     } else if ( idle_state == 1 ) {
1127         // Initialize audio support
1128 #ifdef ENABLE_AUDIO_SUPPORT
1129
1130         // Start the intro music
1131         if ( fgGetBool("/sim/startup/intro-music") ) {
1132             SGPath mp3file( globals->get_fg_root() );
1133             mp3file.append( "Sounds/intro.mp3" );
1134
1135             SG_LOG( SG_GENERAL, SG_INFO, 
1136                     "Starting intro music: " << mp3file.str() );
1137
1138 #if defined( __CYGWIN__ )
1139             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1140 #elif defined( WIN32 )
1141             string command = "start /m " + mp3file.str();
1142 #else
1143             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1144 #endif
1145
1146             system ( command.c_str() );
1147         }
1148
1149         // This is an 'easter egg' which is kind of a hard thing to
1150         // hide in an open source project -- so I won't try very hard
1151         // to hide it.  If you are looking at this now, please, you
1152         // don't want to ruin the surprise. :-) Just forget about it
1153         // and don't look any further; unless it is causing an actual
1154         // problem for you, which it shouldn't, and I hope it doesn't!
1155         // :-)
1156         if ( globals->get_time_params()->getGmt()->tm_mon == 4 
1157              && globals->get_time_params()->getGmt()->tm_mday == 19 )
1158         {
1159             string url = "http://www.flightgear.org/Music/invasion.mp3";
1160 #if defined( __CYGWIN__ ) || defined( WIN32 )
1161             string command = "start /m " + url;
1162 #else
1163             string command = "mpg123 " + url + "> /dev/null 2>&1";
1164 #endif
1165             system( command.c_str() );
1166         }
1167
1168 #endif
1169
1170         idle_state++;
1171     } else if ( idle_state == 2 ) {
1172         // These are a few miscellaneous things that aren't really
1173         // "subsystems" but still need to be initialized.
1174
1175 #ifdef USE_GLIDE
1176         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1177             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1178         }
1179 #endif
1180
1181         idle_state++;
1182     } else if ( idle_state == 3 ) {
1183         // This is the top level init routine which calls all the
1184         // other subsystem initialization routines.  If you are adding
1185         // a subsystem to flightgear, its initialization call should
1186         // located in this routine.
1187         if( !fgInitSubsystems()) {
1188             SG_LOG( SG_GENERAL, SG_ALERT,
1189                     "Subsystem initializations failed ..." );
1190             exit(-1);
1191         }
1192
1193         idle_state++;
1194     } else if ( idle_state == 4 ) {
1195         // setup OpenGL view parameters
1196         fgInitVisuals();
1197
1198         idle_state++;
1199     } else if ( idle_state == 5 ) {
1200
1201         idle_state++;
1202     } else if ( idle_state == 6 ) {
1203         // sleep(1);
1204         idle_state = 1000;
1205
1206         cout << "Panel visible = " << fgPanelVisible() << endl;
1207         fgReshape( fgGetInt("/sim/startup/xsize"),
1208                    fgGetInt("/sim/startup/ysize") );
1209     } 
1210
1211     if ( idle_state == 1000 ) {
1212         // We've finished all our initialization steps, from now on we
1213         // run the main loop.
1214
1215         glutIdleFunc(fgMainLoop);
1216     } else {
1217         if ( fgGetBool("/sim/startup/splash-screen") ) {
1218             fgSplashUpdate(0.0);
1219         }
1220     }
1221 }
1222
1223 // options.cxx needs to see this for toggle_panel()
1224 // Handle new window size or exposure
1225 void fgReshape( int width, int height ) {
1226     int view_h;
1227
1228     if ( (!fgGetBool("/sim/virtual-cockpit"))
1229          && fgPanelVisible() && idle_state == 1000 ) {
1230         view_h = (int)(height * (current_panel->getViewHeight() -
1231                                  current_panel->getYOffset()) / 768.0);
1232     } else {
1233         view_h = height;
1234     }
1235
1236     // for all views
1237     FGViewMgr *viewmgr = globals->get_viewmgr();
1238     for ( int i = 0; i < viewmgr->size(); ++i ) {
1239       viewmgr->get_view(i)->
1240         set_aspect_ratio((float)view_h / (float)width);
1241     }
1242
1243     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1244
1245     fgSetInt("/sim/startup/xsize", width);
1246     fgSetInt("/sim/startup/ysize", height);
1247     guiInitMouse(width, height);
1248
1249     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1250                viewmgr->get_current_view()->get_v_fov() );
1251
1252     fgHUDReshape();
1253 }
1254
1255 // Initialize GLUT and define a main window
1256 int fgGlutInit( int *argc, char **argv ) {
1257
1258 #if !defined( macintosh )
1259     // GLUT will extract all glut specific options so later on we only
1260     // need wory about our own.
1261     glutInit(argc, argv);
1262 #endif
1263
1264     // Define Display Parameters
1265     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1266
1267     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1268             fgGetInt("/sim/startup/xsize") << "x"
1269             << fgGetInt("/sim/startup/ysize") );
1270
1271     // Define initial window size
1272     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1273                         fgGetInt("/sim/startup/ysize") );
1274
1275     // Initialize windows
1276     if ( !fgGetBool("/sim/startup/game-mode")) {
1277         // Open the regular window
1278         glutCreateWindow("FlightGear");
1279 #ifndef GLUT_WRONG_VERSION
1280     } else {
1281         // Open the cool new 'game mode' window
1282         char game_mode_str[256];
1283 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1284 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1285 #ifndef ENUM_CURRENT_SETTINGS
1286 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1287 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1288 #endif
1289
1290         DEVMODE dm;
1291         dm.dmSize = sizeof(DEVMODE);
1292         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1293         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1294         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1295         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1296                                                 fgGetInt("/sim/startup/ysize") );
1297         sprintf( game_mode_str, "%dx%d:%d@%d",
1298                          dm.dmPelsWidth,
1299                          dm.dmPelsHeight,
1300                          dm.dmBitsPerPel,
1301                          dm.dmDisplayFrequency );
1302 #else
1303         // Open the cool new 'game mode' window
1304         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1305                  fgGetInt("/sim/startup/xsize"),
1306                  fgGetInt("/sim/startup/ysize"),
1307                  fgGetInt("/sim/rendering/bits-per-pixel"));
1308
1309 #endif // HAVE_WINDOWS_H
1310         SG_LOG( SG_GENERAL, SG_INFO, 
1311                 "game mode params = " << game_mode_str );
1312         glutGameModeString( game_mode_str );
1313         glutEnterGameMode();
1314 #endif // GLUT_WRONG_VERSION
1315     }
1316
1317     // This seems to be the absolute earliest in the init sequence
1318     // that these calls will return valid info.  Too bad it's after
1319     // we've already created and sized out window. :-(
1320     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1321     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1322     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1323     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1324
1325     GLint tmp;
1326     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1327     general.set_glMaxTexSize( tmp );
1328     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1329
1330     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1331     general.set_glDepthBits( tmp );
1332     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1333
1334     return 1;
1335 }
1336
1337
1338 // Initialize GLUT event handlers
1339 int fgGlutInitEvents( void ) {
1340     // call fgReshape() on window resizes
1341     glutReshapeFunc( fgReshape );
1342
1343     // keyboard and mouse callbacks are set in FGInput::init
1344
1345 #ifdef FG_OLD_MOUSE
1346     // call guiMouseFunc() whenever our little rodent is used
1347     glutMouseFunc ( guiMouseFunc );
1348     glutMotionFunc (guiMotionFunc );
1349     glutPassiveMotionFunc (guiMotionFunc );
1350 #endif
1351
1352     // call fgMainLoop() whenever there is
1353     // nothing else to do
1354     glutIdleFunc( fgIdleFunction );
1355
1356     // draw the scene
1357     glutDisplayFunc( fgRenderFrame );
1358
1359     return 1;
1360 }
1361
1362
1363 // Main loop
1364 int mainLoop( int argc, char **argv ) {
1365
1366 #if defined( macintosh )
1367     freopen ("stdout.txt", "w", stdout );
1368     freopen ("stderr.txt", "w", stderr );
1369     argc = ccommand( &argv );
1370 #endif
1371
1372     // set default log levels
1373      sglog().setLogLevels( SG_ALL, SG_INFO );
1374
1375     string version;
1376 #ifdef FLIGHTGEAR_VERSION
1377     version = FLIGHTGEAR_VERSION;
1378 #else
1379     version = "unknown version";
1380 #endif
1381     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1382             << version << endl );
1383
1384     // Allocate global data structures.  This needs to happen before
1385     // we parse command line options
1386
1387     globals = new FGGlobals;
1388
1389 #if defined(FG_NEW_ENVIRONMENT)
1390     globals->set_environment_mgr(new FGEnvironmentMgr);
1391 #endif
1392
1393     // seed the random number generater
1394     sg_srandom_time();
1395
1396     SGRoute *route = new SGRoute;
1397     globals->set_route( route );
1398
1399     FGControls *controls = new FGControls;
1400     globals->set_controls( controls );
1401
1402     string_list *col = new string_list;
1403     globals->set_channel_options_list( col );
1404
1405     // Scan the config file(s) and command line options to see if
1406     // fg_root was specified (ignore all other options for now)
1407     fgInitFGRoot(argc, argv);
1408
1409     // Check for the correct base package version
1410     string base_version = fgBasePackageVersion();
1411     if ( !(base_version == "0.7.9") ) {
1412         // tell the operator how to use this application
1413         fgUsage();
1414
1415         SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1416                 << "Found version " << base_version << " at: "
1417                 << globals->get_fg_root() );
1418         SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1419         exit(-1);
1420     }
1421
1422     // Initialize the Aircraft directory to "" (UIUC)
1423     aircraft_dir = "";
1424
1425     // Load the configuration parameters
1426     if ( !fgInitConfig(argc, argv) ) {
1427         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1428         exit(-1);
1429     }
1430
1431     // Initialize the Window/Graphics environment.
1432     if( !fgGlutInit(&argc, argv) ) {
1433         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1434         exit(-1);
1435     }
1436
1437     // Initialize the various GLUT Event Handlers.
1438     if( !fgGlutInitEvents() ) {
1439         SG_LOG( SG_GENERAL, SG_ALERT, 
1440                 "GLUT event handler initialization failed ..." );
1441         exit(-1);
1442     }
1443
1444     // Initialize plib net interface
1445     netInit( &argc, argv );
1446
1447     // Initialize ssg (from plib).  Needs to come before we do any
1448     // other ssg stuff, but after opengl/glut has been initialized.
1449     ssgInit();
1450
1451     // Initialize the user interface (we need to do this before
1452     // passing off control to glut and before fgInitGeneral to get our
1453     // fonts !!!
1454     guiInit();
1455
1456 #ifdef GL_EXT_texture_lod_bias
1457     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1458 #endif
1459
1460     // Set position relative to glide slope if requested
1461     fgSetPosFromGlideSlope();
1462
1463     // set current_options lon/lat if an airport id is specified
1464     // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1465     if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1466         // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1467         fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1468                                      fgGetDouble("/orientation/heading-deg") );
1469         // set tower position (a little off the heading for single runway airports)
1470         fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"), fgGetDouble("orientation/heading") );
1471     }
1472
1473     SGTime *t = fgInitTime();
1474     globals->set_time_params( t );
1475
1476     // Do some quick general initializations
1477     if( !fgInitGeneral()) {
1478         SG_LOG( SG_GENERAL, SG_ALERT, 
1479                 "General initializations failed ..." );
1480         exit(-1);
1481     }
1482
1483     SGPath modelpath( globals->get_fg_root() );
1484     ssgModelPath( (char *)modelpath.c_str() );
1485   
1486     ////////////////////////////////////////////////////////////////////
1487     // Initialize the general model subsystem.
1488     ////////////////////////////////////////////////////////////////////
1489
1490     globals->set_model_mgr(new FGModelMgr);
1491     globals->get_model_mgr()->init();
1492     globals->get_model_mgr()->bind();
1493
1494     ////////////////////////////////////////////////////////////////////
1495     // Initialize the 3D aircraft model subsystem.
1496     ////////////////////////////////////////////////////////////////////
1497
1498     globals->set_aircraft_model(new FGAircraftModel);
1499     globals->get_aircraft_model()->init();
1500     globals->get_aircraft_model()->bind();
1501
1502     ////////////////////////////////////////////////////////////////////
1503     // Initialize the view manager subsystem.
1504     ////////////////////////////////////////////////////////////////////
1505
1506     FGViewMgr *viewmgr = new FGViewMgr;
1507     globals->set_viewmgr( viewmgr );
1508     viewmgr->init();
1509     viewmgr->bind();
1510
1511
1512     // Scene graph root
1513     scene = new ssgRoot;
1514     scene->setName( "Scene" );
1515
1516     lighting = new ssgRoot;
1517     lighting->setName( "Lighting" );
1518
1519     // Initialize the sky
1520     SGPath ephem_data_path( globals->get_fg_root() );
1521     ephem_data_path.append( "Astro" );
1522     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1523     ephem->update( globals->get_time_params()->getMjd(),
1524                    globals->get_time_params()->getLst(),
1525                    0.0 );
1526     globals->set_ephem( ephem );
1527
1528     thesky = new SGSky;
1529
1530     SGPath sky_tex_path( globals->get_fg_root() );
1531     sky_tex_path.append( "Textures" );
1532     sky_tex_path.append( "Sky" );
1533     thesky->texture_path( sky_tex_path.str() );
1534
1535     thesky->build( 550.0, 550.0,
1536                    globals->get_ephem()->getNumPlanets(), 
1537                    globals->get_ephem()->getPlanets(), 60000.0,
1538                    globals->get_ephem()->getNumStars(),
1539                    globals->get_ephem()->getStars(), 60000.0 );
1540
1541     if ( fgGetBool("/environment/clouds/status") ) {
1542         // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1543         //                          SG_CLOUD_OVERCAST );
1544         thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1545                                  SG_FEET_TO_METER,
1546                                  200.0, 50.0, 40000.0,
1547                                  SG_CLOUD_MOSTLY_CLOUDY );
1548         // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1549         //                          SG_CLOUD_MOSTLY_SUNNY );
1550         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1551                                  SG_CLOUD_CIRRUS );
1552     }
1553
1554     // Initialize MagVar model
1555     SGMagVar *magvar = new SGMagVar();
1556     globals->set_mag( magvar );
1557
1558     // Terrain branch
1559     terrain_branch = new ssgBranch;
1560     terrain_branch->setName( "Terrain" );
1561     scene->addKid( terrain_branch );
1562
1563     // Lighting
1564     gnd_lights_branch = new ssgBranch;
1565     gnd_lights_branch->setName( "Ground Lighting" );
1566     lighting->addKid( gnd_lights_branch );
1567
1568     rwy_lights_branch = new ssgBranch;
1569     rwy_lights_branch->setName( "Runway Lighting" );
1570     lighting->addKid( rwy_lights_branch );
1571
1572     // airport = new ssgBranch;
1573     // airport->setName( "Airport Lighting" );
1574     // lighting->addKid( airport );
1575
1576     // ADA
1577     fgLoadDCS();
1578     // ADA
1579
1580 #ifdef FG_NETWORK_OLK
1581     // Do the network intialization
1582     if ( fgGetBool("/sim/networking/network-olk") ) {
1583         printf("Multipilot mode %s\n", fg_net_init( scene ) );
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                                                         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         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
1972
1973
1974
1975
1976
1977