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