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