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