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