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