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