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