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