]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
1a372b3bf2f16a30f8ba579e82d2f81eff94458a
[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 #ifdef FG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #ifdef HAVE_WINDOWS_H
33 #  include <windows.h>                     
34 #  include <float.h>                    
35 #endif
36
37 #include <GL/glut.h>
38 #include <simgear/xgl/xgl.h>
39
40 #include <stdio.h>
41 #include <string.h>
42 #include <string>
43
44 #ifdef HAVE_STDLIB_H
45 #   include <stdlib.h>
46 #endif
47
48 #ifdef HAVE_SYS_STAT_H
49 #  include <sys/stat.h> /* for stat() */
50 #endif
51
52 #ifdef HAVE_UNISTD_H
53 #  include <unistd.h>    /* for stat() */
54 #endif
55
56 #include <plib/pu.h>                    // plib include
57 #include <plib/ssg.h>           // plib include
58
59 #ifdef ENABLE_AUDIO_SUPPORT
60 #  include <plib/sl.h>          // plib include
61 #  include <plib/sm.h>          // plib include
62 #endif
63
64 #include <simgear/constants.h>  // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/fg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
72
73 #include <Include/general.hxx>
74
75 #include <Aircraft/aircraft.hxx>
76
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
81
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
83 #include <GUI/gui.h>
84 #include <Joystick/joystick.hxx>
85 #ifdef FG_NETWORK_OLK
86 #include <NetworkOLK/network.h>
87 #endif
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/sunpos.hxx>
93 #include <Time/tmp.hxx>
94
95 // $$$ begin - added VS Renganathan
96 #include <simgear/misc/fgstream.hxx>
97 #include <FDM/flight.hxx>
98 void fgLoadDCS (void);
99 void fgUpdateDCS (void);
100 ssgSelector *ship_sel = NULL;
101 ssgTransform *ship_pos = NULL;
102 //int totalDCSobj = 0;
103 // $$$ end - added VS Renganathan
104
105 #ifndef FG_OLD_WEATHER
106 #  include <WeatherCM/FGLocalWeatherDatabase.h>
107 #else
108 #  include <Weather/weather.hxx>
109 #endif
110
111 #include "version.h"
112
113 #include "bfi.hxx"
114 #include "fg_init.hxx"
115 #include "fg_io.hxx"
116 #include "globals.hxx"
117 #include "keyboard.hxx"
118 #include "splash.hxx"
119
120
121 // -dw- use custom sioux settings so I can see output window
122 #ifdef macintosh
123 #  ifndef FG_NDEBUG
124 #    include <sioux.h> // settings for output window
125 #  endif
126 #  include <console.h>
127 #endif
128
129
130 // This is a record containing a bit of global housekeeping information
131 FGGeneral general;
132
133 // Specify our current idle function state.  This is used to run all
134 // our initializations out of the glutIdleLoop() so that we can get a
135 // splash screen up and running right away.
136 static int idle_state = 0;
137 static int global_multi_loop;
138
139 // attempt to avoid a large bounce at startup
140 static bool initial_freeze = true;
141
142 // Another hack
143 int use_signals = 0;
144
145 // forward declaration
146 void fgReshape( int width, int height );
147
148 // Global structures for the Audio library
149 #ifdef ENABLE_AUDIO_SUPPORT
150 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
151 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
152 slScheduler *audio_sched;
153 smMixer *audio_mixer;
154 slSample *s1;
155 slSample *s2;
156 #endif
157
158
159 // ssg variables
160 ssgRoot *scene = NULL;
161 ssgBranch *terrain = NULL;
162 ssgSelector *penguin_sel = NULL;
163 ssgTransform *penguin_pos = NULL;
164
165 #ifdef FG_NETWORK_OLK
166 ssgSelector *fgd_sel = NULL;
167 ssgTransform *fgd_pos = NULL;
168 //sgMat4 sgTUX;
169 #endif
170
171 // current fdm/position used for view
172 FGInterface cur_view_fdm;
173
174 // Sky structures
175 SGSky *thesky;
176
177 // hack
178 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
179 {
180   {  1.0f,  0.0f,  0.0f,  0.0f },
181   {  0.0f,  0.0f, -1.0f,  0.0f },
182   {  0.0f,  1.0f,  0.0f,  0.0f },
183   {  0.0f,  0.0f,  0.0f,  1.0f }
184 } ;
185
186 // The following defines flightgear options. Because glutlib will also
187 // want to parse its own options, those options must not be included here
188 // or they will get parsed by the main program option parser. Hence case
189 // is significant for any option added that might be in conflict with
190 // glutlib's parser.
191 //
192 // glutlib parses for:
193 //    -display
194 //    -direct   (invalid in Win32)
195 //    -geometry
196 //    -gldebug
197 //    -iconized
198 //    -indirect (invalid in Win32)
199 //    -synce
200 //
201 // Note that glutlib depends upon strings while this program's
202 // option parser wants only initial characters followed by numbers
203 // or pathnames.
204 //
205
206
207 ssgSimpleState *default_state;
208 ssgSimpleState *hud_and_panel;
209 ssgSimpleState *menus;
210
211 void fgBuildRenderStates( void ) {
212     default_state = new ssgSimpleState;
213     default_state->ref();
214     default_state->disable( GL_TEXTURE_2D );
215     default_state->enable( GL_CULL_FACE );
216     default_state->enable( GL_COLOR_MATERIAL );
217     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
218     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
219     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
220     default_state->disable( GL_BLEND );
221     default_state->disable( GL_ALPHA_TEST );
222     default_state->disable( GL_LIGHTING );
223
224     hud_and_panel = new ssgSimpleState;
225     hud_and_panel->ref();
226     hud_and_panel->disable( GL_CULL_FACE );
227     hud_and_panel->disable( GL_TEXTURE_2D );
228     hud_and_panel->disable( GL_LIGHTING );
229     hud_and_panel->enable( GL_BLEND );
230
231     menus = new ssgSimpleState;
232     menus->ref();
233     menus->disable( GL_CULL_FACE );
234     menus->disable( GL_TEXTURE_2D );
235     menus->enable( GL_BLEND );
236 }
237
238
239 // fgInitVisuals() -- Initialize various GL/view parameters
240 void fgInitVisuals( void ) {
241     fgLIGHT *l;
242
243     l = &cur_light_params;
244
245 #ifndef GLUT_WRONG_VERSION
246     // Go full screen if requested ...
247     if ( globals->get_options()->get_fullscreen() ) {
248         glutFullScreen();
249     }
250 #endif
251
252     // If enabled, normal vectors specified with glNormal are scaled
253     // to unit length after transformation.  See glNormal.
254     // glEnable( GL_NORMALIZE );
255
256     glEnable( GL_LIGHTING );
257     glEnable( GL_LIGHT0 );
258     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
259
260     sgVec3 sunpos;
261     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
262     ssgGetLight( 0 ) -> setPosition( sunpos );
263
264     // glFogi (GL_FOG_MODE, GL_LINEAR);
265     glFogi (GL_FOG_MODE, GL_EXP2);
266     if ( (globals->get_options()->get_fog() == 1) || 
267          (globals->get_options()->get_shading() == 0) ) {
268         // if fastest fog requested, or if flat shading force fastest
269         glHint ( GL_FOG_HINT, GL_FASTEST );
270     } else if ( globals->get_options()->get_fog() == 2 ) {
271         glHint ( GL_FOG_HINT, GL_NICEST );
272     }
273     if ( globals->get_options()->get_wireframe() ) {
274         // draw wire frame
275         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
276     }
277
278     // This is the default anyways, but it can't hurt
279     glFrontFace ( GL_CCW );
280
281     // Just testing ...
282     // glEnable(GL_POINT_SMOOTH);
283     // glEnable(GL_LINE_SMOOTH);
284     // glEnable(GL_POLYGON_SMOOTH);      
285 }
286
287
288 // Update all Visuals (redraws anything graphics related)
289 void fgRenderFrame( void ) {
290     // Update the BFI.
291     FGBFI::update();
292
293     fgLIGHT *l = &cur_light_params;
294     static double last_visibility = -9999;
295
296     // double angle;
297     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
298     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
299     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
300     // GLfloat mat_shininess[] = { 10.0 };
301     GLbitfield clear_mask;
302     
303     if ( idle_state != 1000 ) {
304         // still initializing, draw the splash screen
305         if ( globals->get_options()->get_splash_screen() == 1 ) {
306             fgSplashUpdate(0.0);
307         }
308     } else {
309         // idle_state is now 1000 meaning we've finished all our
310         // initializations and are running the main loop, so this will
311         // now work without seg faulting the system.
312
313         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
314         //        FG_Altitude * FEET_TO_METER);
315     
316         // this is just a temporary hack, to make me understand Pui
317         // timerText -> setLabel (ctime (&t->cur_time));
318         // end of hack
319
320         // calculate our current position in cartesian space
321         scenery.center = scenery.next_center;
322         // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
323         //        scenery.center.y(), scenery.center.z());
324
325         globals->get_current_view()->
326             set_geod_view_pos( cur_fdm_state->get_Longitude(), 
327                                cur_fdm_state->get_Lat_geocentric(), 
328                                cur_fdm_state->get_Altitude() *
329                                FEET_TO_METER );
330         globals->get_current_view()->
331             set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
332                                   FEET_TO_METER ); 
333         globals->get_current_view()->
334             set_rph( cur_fdm_state->get_Phi(),
335                      cur_fdm_state->get_Theta(),
336                      cur_fdm_state->get_Psi() );
337
338         // update view volume parameters
339         // cout << "before pilot_view update" << endl;
340         if ( globals->get_options()->get_view_mode() ==
341              FGOptions::FG_VIEW_FOLLOW )
342         {
343             float * offset = globals->get_current_view()->get_pilot_offset();
344             globals->get_current_view()->set_pilot_offset( offset[0],
345                                                            offset[1],
346                                                            offset[2] );
347         } else {
348             globals->get_current_view()->set_pilot_offset(0.0, 0.0, 0.0);
349         }
350
351         if ( ! fgPanelVisible() ) {
352             xglViewport( 0, 0 ,
353                          (GLint)(globals->get_options()->get_xsize()),
354                          (GLint)(globals->get_options()->get_ysize()) );
355         } else {
356             int view_h =
357                 int( (current_panel->getViewHeight() -
358                       current_panel->getYOffset())
359                      * (globals->get_options()->get_ysize() / 768.0) );
360             glViewport( 0, 
361                         (GLint)(globals->get_options()->get_ysize() - view_h),
362                         (GLint)(globals->get_options()->get_xsize()),
363                         (GLint)(view_h) );
364         }
365
366         // set the sun position
367         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
368
369         clear_mask = GL_DEPTH_BUFFER_BIT;
370         if ( globals->get_options()->get_wireframe() ) {
371             clear_mask |= GL_COLOR_BUFFER_BIT;
372         }
373
374         if ( globals->get_options()->get_skyblend() ) {
375             if ( globals->get_options()->get_textures() ) {
376                 // glClearColor(black[0], black[1], black[2], black[3]);
377                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
378                              l->adj_fog_color[2], l->adj_fog_color[3]);
379                 clear_mask |= GL_COLOR_BUFFER_BIT;
380             }
381         } else {
382             glClearColor(l->sky_color[0], l->sky_color[1], 
383                          l->sky_color[2], l->sky_color[3]);
384             clear_mask |= GL_COLOR_BUFFER_BIT;
385         }
386         glClear( clear_mask );
387
388         // Tell GL we are switching to model view parameters
389
390         // I really should create a derived ssg node or use a call
391         // back or something so that I can draw the sky within the
392         // ssgCullAndDraw() function, but for now I just mimic what
393         // ssg does to set up the model view matrix
394         glMatrixMode(GL_MODELVIEW);
395         glLoadIdentity();
396         ssgSetCamera( (sgMat4)globals->get_current_view()->get_VIEW() );
397
398         /*
399         sgMat4 vm_tmp, view_mat;
400         sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
401         sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
402         sgPreMultMat4( view_mat, vm_tmp ) ;
403         glLoadMatrixf( (float *)view_mat );
404         */
405
406         // set the opengl state to known default values
407         default_state->force();
408
409         // update fog params if visibility has changed
410 #ifndef FG_OLD_WEATHER
411         thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
412 #else
413         thesky->set_visibility( current_weather.get_visibility() );
414 #endif
415
416         thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
417                                 
418                             ( global_multi_loop * 
419                               globals->get_options()->get_speed_up() ) /
420                             (double)globals->get_options()->get_model_hz() );
421
422         double actual_visibility = thesky->get_visibility();
423         // cout << "actual visibility = " << actual_visibility << endl;
424
425         if ( actual_visibility != last_visibility ) {
426             last_visibility = actual_visibility;
427
428             // cout << "----> updating fog params" << endl;
429                 
430             GLfloat fog_exp_density;
431             GLfloat fog_exp2_density;
432     
433             // for GL_FOG_EXP
434             fog_exp_density = -log(0.01 / actual_visibility);
435     
436             // for GL_FOG_EXP2
437             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
438     
439             // Set correct opengl fog density
440             glFogf (GL_FOG_DENSITY, fog_exp2_density);
441         }
442  
443         // update the sky dome
444         if ( globals->get_options()->get_skyblend() ) {
445             /* cout << "thesky->repaint() sky_color = "
446                  << cur_light_params.sky_color[0] << " "
447                  << cur_light_params.sky_color[1] << " "
448                  << cur_light_params.sky_color[2] << " "
449                  << cur_light_params.sky_color[3] << endl;
450             cout << "    fog = "
451                  << cur_light_params.fog_color[0] << " "
452                  << cur_light_params.fog_color[1] << " "
453                  << cur_light_params.fog_color[2] << " "
454                  << cur_light_params.fog_color[3] << endl;
455             cout << "    sun_angle = " << cur_light_params.sun_angle
456                  << "    moon_angle = " << cur_light_params.moon_angle
457                  << endl; */
458             thesky->repaint( cur_light_params.sky_color,
459                              cur_light_params.adj_fog_color,
460                              cur_light_params.sun_angle,
461                              cur_light_params.moon_angle,
462                              globals->get_ephem()->getNumPlanets(),
463                              globals->get_ephem()->getPlanets(),
464                              globals->get_ephem()->getNumStars(),
465                              globals->get_ephem()->getStars() );
466  
467             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
468                  << view_pos[1] << " " << view_pos[2] << endl;
469             cout << "    zero_elev = " << zero_elev[0] << " "
470                  << zero_elev[1] << " " << zero_elev[2]
471                  << " lon = " << cur_fdm_state->get_Longitude()
472                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
473             cout << "    sun_rot = " << cur_light_params.sun_rotation
474                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
475             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
476                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
477                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
478                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
479
480             thesky->reposition( globals->get_current_view()->get_view_pos(),
481                                 globals->get_current_view()->get_zero_elev(),
482                                 globals->get_current_view()->get_local_up(),
483                                 cur_fdm_state->get_Longitude(),
484                                 cur_fdm_state->get_Latitude(),
485                                 cur_fdm_state->get_Altitude() * FEET_TO_METER,
486                                 cur_light_params.sun_rotation,
487                                 globals->get_time_params()->getGst(),
488                                 globals->get_ephem()->getSunRightAscension(),
489                                 globals->get_ephem()->getSunDeclination(),
490                                 50000.0,
491                                 globals->get_ephem()->getMoonRightAscension(),
492                                 globals->get_ephem()->getMoonDeclination(),
493                                 50000.0 );
494         }
495
496         glEnable( GL_DEPTH_TEST );
497         if ( globals->get_options()->get_fog() > 0 ) {
498             glEnable( GL_FOG );
499             glFogi( GL_FOG_MODE, GL_EXP2 );
500             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
501         }
502
503         // set lighting parameters
504         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
505         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
506         glLightfv( GL_LIGHT0, GL_AMBIENT, black );
507         glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
508         // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
509
510         // texture parameters
511         // glEnable( GL_TEXTURE_2D );
512         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
513         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
514         // set base color (I don't think this is doing anything here)
515         // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
516         //  (GL_FRONT, GL_DIFFUSE, white);
517         // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
518         // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
519
520         sgVec3 sunpos;
521         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
522         ssgGetLight( 0 ) -> setPosition( sunpos );
523
524         // glMatrixMode( GL_PROJECTION );
525         // glLoadIdentity();
526         float fov = globals->get_options()->get_fov();
527         ssgSetFOV(fov, fov * globals->get_options()->get_win_ratio());
528
529         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
530             - scenery.cur_elev;
531
532         // FG_LOG( FG_ALL, FG_INFO, "visibility is " 
533         //         << current_weather.get_visibility() );
534             
535         if ( agl > 10.0 ) {
536             ssgSetNearFar( 10.0f, 120000.0f );
537         } else {
538             ssgSetNearFar( 0.5f, 120000.0f );
539         }
540
541         if ( globals->get_options()->get_view_mode() == 
542              FGOptions::FG_VIEW_PILOT )
543         {
544             // disable TuX
545             penguin_sel->select(0);
546         } else if ( globals->get_options()->get_view_mode() == 
547                     FGOptions::FG_VIEW_FOLLOW )
548         {
549             // select view matrix from front of view matrix queue
550             // FGMat4Wrapper tmp = current_view.follow.front();
551             // sgCopyMat4( sgVIEW, tmp.m );
552
553             // enable TuX and set up his position and orientation
554             penguin_sel->select(1);
555
556             sgMat4 sgTRANS;
557             sgMakeTransMat4( sgTRANS, 
558                              globals->get_current_view()->get_view_pos() );
559
560             sgVec3 ownship_up;
561             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
562
563             sgMat4 sgROT;
564             sgMakeRotMat4( sgROT, -90.0, ownship_up );
565
566             // sgMat4 sgTMP;
567             // sgMat4 sgTUX;
568             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
569             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
570
571             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
572             sgMat4 sgTUX;
573             sgCopyMat4( sgTUX, sgROT );
574             sgPostMultMat4( sgTUX, globals->get_current_view()->get_VIEW_ROT() );
575             sgPostMultMat4( sgTUX, sgTRANS );
576         
577             sgCoord tuxpos;
578             sgSetCoord( &tuxpos, sgTUX );
579             penguin_pos->setTransform( &tuxpos );
580         }
581
582         // $$$ begin - added VS Renganthan 17 Oct 2K
583         fgUpdateDCS();
584         // $$$ end - added VS Renganthan 17 Oct 2K
585
586 # ifdef FG_NETWORK_OLK
587         if ( globals->get_options()->get_network_olk() ) {
588             sgCoord fgdpos;
589             other = head->next;             /* put listpointer to start  */
590             while ( other != tail) {        /* display all except myself */
591                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
592                     other->fgd_sel->select(1);
593                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
594                     other->fgd_pos->setTransform( &fgdpos );
595                 }
596                 other = other->next;
597             }
598
599             // fgd_sel->select(1);
600             // sgCopyMat4( sgTUX, current_view.sgVIEW);
601             // sgCoord fgdpos;
602             // sgSetCoord( &fgdpos, sgFGD_VIEW );
603             // fgd_pos->setTransform( &fgdpos);
604         }
605 # endif
606
607         // ssgSetCamera( current_view.VIEW );
608
609         // position tile nodes and update range selectors
610         global_tile_mgr.prep_ssg_nodes();
611
612         // force the default state so ssg can get back on track if
613         // we've changed things elsewhere (this is now handled
614         // differently)
615         // 
616         // FGMaterialSlot m_slot;
617         // FGMaterialSlot *m_ptr = &m_slot;
618         // if ( material_mgr.find( "Default", m_ptr ) ) {
619         //    m_ptr->get_state()->force();
620         // }
621
622         // draw the sky backdrop
623         thesky->preDraw();
624
625         // draw the ssg scene
626         glEnable( GL_DEPTH_TEST );
627         ssgCullAndDraw( scene );
628
629         // draw the sky cloud layers
630         thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
631
632         // display HUD && Panel
633         glDisable( GL_FOG );
634         glDisable( GL_DEPTH_TEST );
635         // glDisable( GL_CULL_FACE );
636         // glDisable( GL_TEXTURE_2D );
637         hud_and_panel->apply();
638         fgCockpitUpdate();
639
640         // We can do translucent menus, so why not. :-)
641         // glEnable ( GL_BLEND ) ;
642         menus->apply();
643         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
644         puDisplay();
645         // glDisable ( GL_BLEND ) ;
646
647         // glEnable( GL_FOG );
648     }
649
650     glutSwapBuffers();
651 }
652
653
654 // Update internal time dependent calculations (i.e. flight model)
655 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
656     static fdm_state_list fdm_list;
657     fgLIGHT *l = &cur_light_params;
658     int i;
659
660     // update the flight model
661     if ( multi_loop < 0 ) {
662         multi_loop = 1;
663     }
664
665     if ( !globals->get_freeze() && !initial_freeze ) {
666         // run Autopilot system
667         current_autopilot->run();
668
669         // printf("updating flight model x %d\n", multi_loop);
670         /* fgFDMUpdate( globals->get_options()->get_flight_model(), 
671                      fdm_state, 
672                      multi_loop * globals->get_options()->get_speed_up(),
673                      remainder ); */
674         cur_fdm_state->update( multi_loop *
675                                globals->get_options()->get_speed_up() );
676         FGSteam::update( multi_loop * globals->get_options()->get_speed_up() );
677     } else {
678         // fgFDMUpdate( globals->get_options()->get_flight_model(), 
679         //              fdm_state, 0, remainder );
680         cur_fdm_state->update( 0 );
681         FGSteam::update( 0 );
682
683         if ( global_tile_mgr.queue_size() == 0 ) {
684             initial_freeze = false;
685         }
686     }
687
688     fdm_list.push_back( *cur_fdm_state );
689     while ( fdm_list.size() > 15 ) {
690         fdm_list.pop_front();
691     }
692
693     if ( globals->get_options()->get_view_mode() == FGOptions::FG_VIEW_PILOT ) {
694         cur_view_fdm = *cur_fdm_state;
695         // do nothing
696     } else if ( globals->get_options()->get_view_mode()
697                 == FGOptions::FG_VIEW_FOLLOW )
698     {
699         cur_view_fdm = fdm_list.front();
700     }
701
702     // update the view angle
703     for ( i = 0; i < multi_loop; i++ ) {
704         if ( fabs(globals->get_current_view()->get_goal_view_offset() - 
705                   globals->get_current_view()->get_view_offset()) < 0.05 )
706         {
707             globals->get_current_view()->set_view_offset( globals->get_current_view()->get_goal_view_offset() );
708             break;
709         } else {
710             // move current_view.view_offset towards
711             // current_view.goal_view_offset
712             if ( globals->get_current_view()->get_goal_view_offset() > 
713                  globals->get_current_view()->get_view_offset() )
714             {
715                 if ( globals->get_current_view()->get_goal_view_offset() - 
716                      globals->get_current_view()->get_view_offset() < FG_PI )
717                 {
718                     globals->get_current_view()->inc_view_offset( 0.01 );
719                 } else {
720                     globals->get_current_view()->inc_view_offset( -0.01 );
721                 }
722             } else {
723                 if ( globals->get_current_view()->get_view_offset() - 
724                      globals->get_current_view()->get_goal_view_offset() <
725                      FG_PI )
726                 {
727                     globals->get_current_view()->inc_view_offset( -0.01 );
728                 } else {
729                     globals->get_current_view()->inc_view_offset( 0.01 );
730                 }
731             }
732             if ( globals->get_current_view()->get_view_offset() > FG_2PI ) {
733                 globals->get_current_view()->inc_view_offset( -FG_2PI );
734             } else if ( globals->get_current_view()->get_view_offset() < 0 ) {
735                 globals->get_current_view()->inc_view_offset( FG_2PI );
736             }
737         }
738     }
739
740     double tmp = -(l->sun_rotation + FG_PI) 
741         - (cur_fdm_state->get_Psi() -
742            globals->get_current_view()->get_view_offset() );
743     while ( tmp < 0.0 ) {
744         tmp += FG_2PI;
745     }
746     while ( tmp > FG_2PI ) {
747         tmp -= FG_2PI;
748     }
749     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
750            FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG, 
751            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
752     l->UpdateAdjFog();
753
754     // Update solar system
755     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
756                                   globals->get_time_params()->getLst(),
757                                   cur_fdm_state->get_Latitude() );
758
759     // Update radio stack model
760     current_radiostack->update( cur_fdm_state->get_Longitude(),
761                                 cur_fdm_state->get_Latitude(),
762                                 cur_fdm_state->get_Altitude() * FEET_TO_METER );
763 }
764
765
766 void fgInitTimeDepCalcs( void ) {
767     // initialize timer
768
769     // #ifdef HAVE_SETITIMER
770     //   fgTimerInit( 1.0 / globals->get_options()->get_model_hz(), 
771     //                fgUpdateTimeDepCalcs );
772     // #endif HAVE_SETITIMER
773 }
774
775
776 static const double alt_adjust_ft = 3.758099;
777 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
778
779
780 // What should we do when we have nothing else to do?  Let's get ready
781 // for the next move and update the display?
782 static void fgMainLoop( void ) {
783     static long remainder = 0;
784     long elapsed;
785 #ifdef FANCY_FRAME_COUNTER
786     int i;
787     double accum;
788 #else
789     static time_t last_time = 0;
790     static int frames = 0;
791 #endif // FANCY_FRAME_COUNTER
792
793     SGTime *t = globals->get_time_params();
794
795     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
796     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
797
798 #ifdef FG_NETWORK_OLK
799     if ( globals->get_options()->get_network_olk() ) {
800         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
801             // printf("FGD: Netupdate\n");
802             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
803             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
804         }
805     }
806 #endif
807
808 #if defined( ENABLE_PLIB_JOYSTICK )
809     // Read joystick and update control settings
810     if ( globals->get_options()->get_control_mode() == FGOptions::FG_JOYSTICK )
811     {
812         fgJoystickRead();
813     }
814 #elif defined( ENABLE_GLUT_JOYSTICK )
815     // Glut joystick support works by feeding a joystick handler
816     // function to glut.  This is taken care of once in the joystick
817     // init routine and we don't have to worry about it again.
818 #endif
819
820 #ifdef FG_OLD_WEATHER
821     current_weather.Update();
822 #endif
823
824     // Fix elevation.  I'm just sticking this here for now, it should
825     // probably move eventually
826
827     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
828            scenery.cur_elev,
829            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
830            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
831
832     if ( scenery.cur_elev > -9990 ) {
833         if ( cur_fdm_state->get_Altitude() * FEET_TO_METER < 
834              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
835             // now set aircraft altitude above ground
836             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
837                    cur_fdm_state->get_Altitude() * FEET_TO_METER,
838                    scenery.cur_elev + alt_adjust_m - 3.0,
839                    scenery.cur_elev + alt_adjust_m );
840             fgFDMForceAltitude( globals->get_options()->get_flight_model(), 
841                                 scenery.cur_elev + alt_adjust_m );
842
843             FG_LOG( FG_ALL, FG_DEBUG, 
844                     "<*> resetting altitude to " 
845                     << cur_fdm_state->get_Altitude() * FEET_TO_METER
846                     << " meters" );
847         }
848         //fgFDMSetGroundElevation( globals->get_options()->get_flight_model(),
849         //                       scenery.cur_elev );  // meters
850     }
851
852     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
853            scenery.cur_elev,
854            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
855            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
856
857     // update "time"
858     if ( globals->get_warp_delta() != 0 ) {
859         globals->inc_warp( globals->get_warp_delta() );
860     }
861
862     t->update( cur_fdm_state->get_Longitude(),
863                cur_fdm_state->get_Latitude(),
864                globals->get_warp() );
865
866     if ( globals->get_warp_delta() != 0 ) {
867         fgUpdateSkyAndLightingParams();
868     }
869
870     // update magvar model
871     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
872                                 cur_fdm_state->get_Latitude(),
873                                 cur_fdm_state->get_Altitude()* FEET_TO_METER,
874                                 globals->get_time_params()->getJD() );
875
876     // Get elapsed time (in usec) for this past frame
877     elapsed = fgGetTimeInterval();
878     FG_LOG( FG_ALL, FG_DEBUG, 
879             "Elapsed time interval is = " << elapsed 
880             << ", previous remainder is = " << remainder );
881
882     // Calculate frame rate average
883 #ifdef FANCY_FRAME_COUNTER
884     /* old fps calculation */
885     if ( elapsed > 0 ) {
886         double tmp;
887         accum = 0.0;
888         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
889             tmp = general.get_frame(i);
890             accum += tmp;
891             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
892             general.set_frame(i+1,tmp);
893         }
894         tmp = 1000000.0 / (float)elapsed;
895         general.set_frame(0,tmp);
896         // printf("frame[0] = %.2f\n", general.frames[0]);
897         accum += tmp;
898         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
899         // printf("ave = %.2f\n", general.frame_rate);
900     }
901 #else
902     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
903         general.set_frame_rate( frames );
904         FG_LOG( FG_ALL, FG_DEBUG, 
905                 "--> Frame rate is = " << general.get_frame_rate() );
906         frames = 0;
907     }
908     last_time = t->get_cur_time();
909     ++frames;
910 #endif
911
912     // Run flight model
913     if ( ! use_signals ) {
914         // Calculate model iterations needed for next frame
915         elapsed += remainder;
916
917         global_multi_loop = (int)(((double)elapsed * 0.000001) * 
918                            globals->get_options()->get_model_hz());
919         remainder = elapsed - ( (global_multi_loop*1000000) / 
920                                 globals->get_options()->get_model_hz() );
921         FG_LOG( FG_ALL, FG_DEBUG, 
922                 "Model iterations needed = " << global_multi_loop
923                 << ", new remainder = " << remainder );
924         
925         // flight model
926         if ( global_multi_loop > 0 ) {
927             fgUpdateTimeDepCalcs(global_multi_loop, remainder);
928         } else {
929             FG_LOG( FG_ALL, FG_DEBUG, 
930                     "Elapsed time is zero ... we're zinging" );
931         }
932     }
933
934 #if ! defined( macintosh )
935     // Do any I/O channel work that might need to be done
936     fgIOProcess();
937 #endif
938
939     // see if we need to load any new scenery tiles
940     global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
941                             cur_fdm_state->get_Latitude() * RAD_TO_DEG );
942
943     // Process/manage pending events
944     global_events.Process();
945
946     // Run audio scheduler
947 #ifdef ENABLE_AUDIO_SUPPORT
948     if ( globals->get_options()->get_sound() && !audio_sched->not_working() ) {
949
950         if ( globals->get_options()->get_aircraft() == "c172" ) {
951             // pitch corresponds to rpm
952             // volume corresponds to manifold pressure
953
954             double rpm_factor;
955             if ( cur_fdm_state->get_engine(0) != NULL ) {
956                 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
957             } else {
958                 rpm_factor = 1.0;
959             }
960             // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
961             //      << endl;
962
963             double pitch = 0.3 + rpm_factor * 3.0;
964         
965             // don't run at absurdly slow rates -- not realistic
966             // and sounds bad to boot.  :-)
967             if (pitch < 0.7) { pitch = 0.7; }
968             if (pitch > 5.0) { pitch = 5.0; }
969             // cout << "pitch = " << pitch << endl;
970
971             double mp_factor;
972             if ( cur_fdm_state->get_engine(0) != NULL ) {
973                 mp_factor = 
974                     cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
975             } else {
976                 mp_factor = 1.0;
977             }
978             // cout << "mp = " 
979             //      << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
980             //      << endl;
981
982             double volume = mp_factor;
983
984             if ( volume < 0.3 ) { volume = 0.3; }
985             if ( volume > 2.0 ) { volume = 2.0; }
986             // cout << "volume = " << volume << endl;
987
988             pitch_envelope.setStep  ( 0, 0.01, pitch );
989             volume_envelope.setStep ( 0, 0.01, volume );
990         } else {
991             double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
992             pitch_envelope.setStep  ( 0, 0.01, param );
993             volume_envelope.setStep ( 0, 0.01, param );
994         }
995
996         audio_sched -> update();
997     }
998 #endif
999
1000     // redraw display
1001     fgRenderFrame();
1002
1003     FG_LOG( FG_ALL, FG_DEBUG, "" );
1004 }
1005
1006
1007 // This is the top level master main function that is registered as
1008 // our idle funciton
1009 //
1010
1011 // The first few passes take care of initialization things (a couple
1012 // per pass) and once everything has been initialized fgMainLoop from
1013 // then on.
1014
1015 static void fgIdleFunction ( void ) {
1016     // printf("idle state == %d\n", idle_state);
1017
1018     if ( idle_state == 0 ) {
1019         // Initialize the splash screen right away
1020         if ( globals->get_options()->get_splash_screen() ) {
1021             fgSplashInit();
1022         }
1023         
1024         idle_state++;
1025     } else if ( idle_state == 1 ) {
1026         // Start the intro music
1027 #if !defined(WIN32)
1028         if ( globals->get_options()->get_intro_music() ) {
1029             string lockfile = "/tmp/mpg123.running";
1030             FGPath mp3file( globals->get_options()->get_fg_root() );
1031             mp3file.append( "Sounds/intro.mp3" );
1032
1033             string command = "(touch " + lockfile + "; mpg123 "
1034                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1035                 + lockfile + ") &";
1036             FG_LOG( FG_GENERAL, FG_INFO, 
1037                     "Starting intro music: " << mp3file.str() );
1038             system ( command.c_str() );
1039         }
1040 #endif
1041
1042         idle_state++;
1043     } else if ( idle_state == 2 ) {
1044         // These are a few miscellaneous things that aren't really
1045         // "subsystems" but still need to be initialized.
1046
1047 #ifdef USE_GLIDE
1048         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1049             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1050         }
1051 #endif
1052
1053         idle_state++;
1054     } else if ( idle_state == 3 ) {
1055         // This is the top level init routine which calls all the
1056         // other subsystem initialization routines.  If you are adding
1057         // a subsystem to flightgear, its initialization call should
1058         // located in this routine.
1059         if( !fgInitSubsystems()) {
1060             FG_LOG( FG_GENERAL, FG_ALERT,
1061                     "Subsystem initializations failed ..." );
1062             exit(-1);
1063         }
1064
1065         idle_state++;
1066     } else if ( idle_state == 4 ) {
1067         // setup OpenGL view parameters
1068         fgInitVisuals();
1069
1070         if ( use_signals ) {
1071             // init timer routines, signals, etc.  Arrange for an alarm
1072             // signal to be generated, etc.
1073             fgInitTimeDepCalcs();
1074         }
1075
1076         idle_state++;
1077     } else if ( idle_state == 5 ) {
1078
1079         idle_state++;
1080     } else if ( idle_state == 6 ) {
1081         // Initialize audio support
1082 #ifdef ENABLE_AUDIO_SUPPORT
1083
1084 #if !defined(WIN32)
1085         if ( globals->get_options()->get_intro_music() ) {
1086             // Let's wait for mpg123 to finish
1087             string lockfile = "/tmp/mpg123.running";
1088             struct stat stat_buf;
1089
1090             FG_LOG( FG_GENERAL, FG_INFO, 
1091                     "Waiting for mpg123 player to finish ..." );
1092             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1093                 // file exist, wait ...
1094                 sleep(1);
1095                 FG_LOG( FG_GENERAL, FG_INFO, ".");
1096             }
1097             FG_LOG( FG_GENERAL, FG_INFO, "");
1098         }
1099 #endif // WIN32
1100
1101         if ( globals->get_options()->get_sound() ) {
1102             audio_sched = new slScheduler ( 8000 );
1103             audio_mixer = new smMixer;
1104             audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
1105             audio_sched -> setSafetyMargin ( 1.0 ) ;
1106
1107             FGPath slfile( globals->get_options()->get_fg_root() );
1108             slfile.append( "Sounds/wasp.wav" );
1109
1110             s1 = new slSample ( (char *)slfile.c_str() );
1111             FG_LOG( FG_GENERAL, FG_INFO,
1112                     "Rate = " << s1 -> getRate()
1113                     << "  Bps = " << s1 -> getBps()
1114                     << "  Stereo = " << s1 -> getStereo() );
1115             audio_sched -> loopSample ( s1 );
1116
1117             if ( audio_sched->not_working() ) {
1118                 // skip
1119             } else {
1120                 pitch_envelope.setStep  ( 0, 0.01, 0.6 );
1121                 volume_envelope.setStep ( 0, 0.01, 0.6 );
1122
1123                 audio_sched -> addSampleEnvelope( s1, 0, 0, 
1124                                                   &pitch_envelope,
1125                                                   SL_PITCH_ENVELOPE );
1126                 audio_sched -> addSampleEnvelope( s1, 0, 1, 
1127                                                   &volume_envelope,
1128                                                   SL_VOLUME_ENVELOPE );
1129             }
1130
1131             // strcpy(slfile, path);
1132             // strcat(slfile, "thunder.wav");
1133             // s2 -> loadFile ( slfile );
1134             // s2 -> adjustVolume(0.5);
1135             // audio_sched -> playSample ( s2 );
1136         }
1137 #endif
1138
1139         // sleep(1);
1140         idle_state = 1000;
1141
1142         cout << "Panel visible = " << fgPanelVisible() << endl;
1143         fgReshape( globals->get_options()->get_xsize(),
1144                    globals->get_options()->get_ysize() );
1145     } 
1146
1147     if ( idle_state == 1000 ) {
1148         // We've finished all our initialization steps, from now on we
1149         // run the main loop.
1150
1151         fgMainLoop();
1152     } else {
1153         if ( globals->get_options()->get_splash_screen() == 1 ) {
1154             fgSplashUpdate(0.0);
1155         }
1156     }
1157 }
1158
1159 // options.cxx needs to see this for toggle_panel()
1160 // Handle new window size or exposure
1161 void fgReshape( int width, int height ) {
1162     if ( ! fgPanelVisible() || idle_state != 1000 ) {
1163         globals->get_options()->set_win_ratio( (float)height /
1164                                                (float)width );
1165         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1166     } else {
1167         int view_h =
1168           int((current_panel->getViewHeight() - current_panel->getYOffset())
1169               * (height / 768.0)) + 1;
1170         globals->get_options()->set_win_ratio( (float)view_h /
1171                                                (float)width );
1172         glViewport(0, (GLint)(height - view_h),
1173                    (GLint)(width), (GLint)(view_h) );
1174     }
1175
1176     globals->get_options()->set_xsize( width );
1177     globals->get_options()->set_ysize( height );
1178
1179     float fov = globals->get_options()->get_fov();
1180     ssgSetFOV(fov, fov * globals->get_options()->get_win_ratio());
1181
1182     fgHUDReshape();
1183
1184     if ( idle_state == 1000 ) {
1185         // yes we've finished all our initializations and are running
1186         // the main loop, so this will now work without seg faulting
1187         // the system.
1188         // globals->get_current_view()->UpdateViewParams();
1189     }
1190 }
1191
1192
1193 // Initialize GLUT and define a main window
1194 int fgGlutInit( int *argc, char **argv ) {
1195
1196 #if !defined( macintosh )
1197     // GLUT will extract all glut specific options so later on we only
1198     // need wory about our own.
1199     glutInit(argc, argv);
1200 #endif
1201
1202     // Define Display Parameters
1203     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1204
1205     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1206             globals->get_options()->get_xsize() << "x"
1207             << globals->get_options()->get_ysize() );
1208
1209     // Define initial window size
1210     glutInitWindowSize( globals->get_options()->get_xsize(),
1211                          globals->get_options()->get_ysize() );
1212
1213     // Initialize windows
1214     if ( globals->get_options()->get_game_mode() == 0 ) {
1215         // Open the regular window
1216         glutCreateWindow("FlightGear");
1217 #ifndef GLUT_WRONG_VERSION
1218     } else {
1219         // Open the cool new 'game mode' window
1220         char game_mode_str[256];
1221         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1222                  globals->get_options()->get_xsize(),
1223                  globals->get_options()->get_ysize(),
1224                  globals->get_options()->get_bpp());
1225
1226         FG_LOG( FG_GENERAL, FG_INFO, 
1227                 "game mode params = " << game_mode_str );
1228         glutGameModeString( game_mode_str );
1229         glutEnterGameMode();
1230 #endif
1231     }
1232
1233     // This seems to be the absolute earliest in the init sequence
1234     // that these calls will return valid info.  Too bad it's after
1235     // we've already created and sized out window. :-(
1236     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1237     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1238     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1239     int tmp;
1240     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1241     general.set_glMaxTexSize( tmp );
1242     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1243     FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1244
1245 #if 0
1246     // try to determine if we should adjust the initial default
1247     // display resolution.  The options class defaults (is
1248     // initialized) to 640x480.
1249     string renderer = general.glRenderer;
1250
1251     // currently we only know how to deal with Mesa/Glide/Voodoo cards
1252     if ( renderer.find( "Glide" ) != string::npos ) {
1253         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1254         if ( renderer.find( "FB/8" ) != string::npos ) {
1255             // probably a voodoo-2
1256             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1257                 // probably two SLI'd Voodoo-2's
1258                 globals->get_options()->set_xsize( 1024 );
1259                 globals->get_options()->set_ysize( 768 );
1260                 FG_LOG( FG_GENERAL, FG_INFO,
1261                         "It looks like you have two sli'd voodoo-2's." << endl
1262                         << "upgrading your win resolution to 1024 x 768" );
1263                 glutReshapeWindow(1024, 768);
1264             } else {
1265                 // probably a single non-SLI'd Voodoo-2
1266                 globals->get_options()->set_xsize( 800 );
1267                 globals->get_options()->set_ysize( 600 );
1268                 FG_LOG( FG_GENERAL, FG_INFO,
1269                         "It looks like you have a voodoo-2." << endl
1270                         << "upgrading your win resolution to 800 x 600" );
1271                 glutReshapeWindow(800, 600);
1272             }
1273         } else if ( renderer.find( "FB/2" ) != string::npos ) {
1274             // probably a voodoo-1, stick with the default
1275         }
1276     } else {
1277         // we have no special knowledge of this card, stick with the default
1278     }
1279 #endif
1280
1281     return(1);
1282 }
1283
1284
1285 // Initialize GLUT event handlers
1286 int fgGlutInitEvents( void ) {
1287     // call fgReshape() on window resizes
1288     glutReshapeFunc( fgReshape );
1289
1290     // call GLUTkey() on keyboard event
1291     glutKeyboardFunc( GLUTkey );
1292     glutSpecialFunc( GLUTspecialkey );
1293
1294     // call guiMouseFunc() whenever our little rodent is used
1295     glutMouseFunc ( guiMouseFunc );
1296     glutMotionFunc (guiMotionFunc );
1297     glutPassiveMotionFunc (guiMotionFunc );
1298
1299     // call fgMainLoop() whenever there is
1300     // nothing else to do
1301     glutIdleFunc( fgIdleFunction );
1302
1303     // draw the scene
1304     glutDisplayFunc( fgRenderFrame );
1305
1306     return(1);
1307 }
1308
1309
1310 // Main ...
1311 int main( int argc, char **argv ) {
1312
1313 #if defined( macintosh )
1314     freopen ("stdout.txt", "w", stdout );
1315     freopen ("stderr.txt", "w", stderr );
1316     argc = ccommand( &argv );
1317 #endif
1318
1319 #ifdef HAVE_BC5PLUS
1320     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1321 #endif
1322
1323     // set default log levels
1324     fglog().setLogLevels( FG_ALL, FG_INFO );
1325
1326     FG_LOG( FG_GENERAL, FG_INFO, "FlightGear:  Version "
1327             << FLIGHTGEAR_VERSION << endl );
1328
1329     // seed the random number generater
1330     fg_srandom();
1331
1332     // Allocate global data structures.  This needs to happen before
1333     // we parse command line options
1334     globals = new FGGlobals;
1335
1336     SGRoute *route = new SGRoute;
1337     globals->set_route( route );
1338
1339     FGOptions *options = new FGOptions;
1340     globals->set_options( options );
1341
1342     FGViewer *pv = new FGViewer;
1343     globals->set_current_view( pv );
1344     // FGViewer *cv = new FGViewer;
1345     // globals->set_current_view( cv );
1346     
1347     // Scan the config file(s) and command line options to see if
1348     // fg_root was specified (ignore all other options for now)
1349     fgInitFGRoot(argc, argv);
1350
1351     // cout << "1. airport_id = " << globals->get_options()->get_airport_id() << endl;
1352
1353     // Read global preferences from $FG_ROOT/preferences.xml
1354     FGPath props_path(globals->get_options()->get_fg_root());
1355     props_path.append("preferences.xml");
1356     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
1357     if (!readPropertyList(props_path.str(), &current_properties)) {
1358       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
1359              << props_path.str());
1360     } else {
1361       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
1362     }
1363
1364     // cout << "2. airport_id = " << globals->get_options()->get_airport_id() << endl;
1365
1366     // Initialize the Aircraft directory to "" (UIUC)
1367     aircraft_dir = "";
1368
1369     // Load the configuration parameters
1370     if ( !fgInitConfig(argc, argv) ) {
1371         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1372         exit(-1);
1373     }
1374
1375     // Initialize the Window/Graphics environment.
1376     if( !fgGlutInit(&argc, argv) ) {
1377         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1378         exit(-1);
1379     }
1380
1381     // Initialize the various GLUT Event Handlers.
1382     if( !fgGlutInitEvents() ) {
1383         FG_LOG( FG_GENERAL, FG_ALERT, 
1384                 "GLUT event handler initialization failed ..." );
1385         exit(-1);
1386     }
1387  
1388     // Initialize ssg (from plib).  Needs to come before we do any
1389     // other ssg stuff, but after opengl/glut has been initialized.
1390     ssgInit();
1391
1392     // Initialize the user interface (we need to do this before
1393     // passing off control to glut and before fgInitGeneral to get our
1394     // fonts !!!
1395     guiInit();
1396
1397     // set current_options lon/lat if an airport id is specified
1398     // cout << "3. airport_id = " << globals->get_options()->get_airport_id() << endl;
1399     if ( globals->get_options()->get_airport_id().length() ) {
1400         // fgSetPosFromAirportID( globals->get_options()->get_airport_id() );
1401         fgSetPosFromAirportIDandHdg( globals->get_options()->get_airport_id(),
1402                                      globals->get_options()->get_heading() );
1403     }
1404
1405     // Initialize time
1406     FGPath zone( globals->get_options()->get_fg_root() );
1407     zone.append( "Timezone" );
1408     SGTime *t = new SGTime( globals->get_options()->get_lon() * DEG_TO_RAD,
1409                             globals->get_options()->get_lat() * DEG_TO_RAD,
1410                             zone.str() );
1411
1412     // Handle potential user specified time offsets
1413     time_t cur_time = t->get_cur_time();
1414     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1415     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1416     time_t aircraftLocalTime = 
1417         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1418
1419     // Okay, we now have six possible scenarios
1420     switch ( globals->get_options()->get_time_offset_type() ) {
1421     case FGOptions::FG_TIME_SYS_OFFSET:
1422         globals->set_warp( globals->get_options()->get_time_offset() );
1423         break;
1424     case FGOptions::FG_TIME_GMT_OFFSET:
1425         globals->set_warp( globals->get_options()->get_time_offset() - 
1426                            (currGMT - systemLocalTime) );
1427         break;
1428     case FGOptions::FG_TIME_LAT_OFFSET:
1429         globals->set_warp( globals->get_options()->get_time_offset() - 
1430                            (aircraftLocalTime - systemLocalTime) );
1431         break;
1432     case FGOptions::FG_TIME_SYS_ABSOLUTE:
1433         globals->set_warp( globals->get_options()->get_time_offset() -
1434                            cur_time );
1435         //printf("warp = %d\n", warp); 
1436         break;
1437     case FGOptions::FG_TIME_GMT_ABSOLUTE:
1438         globals->set_warp( globals->get_options()->get_time_offset() -
1439                            currGMT );
1440         break;
1441     case FGOptions::FG_TIME_LAT_ABSOLUTE:
1442         globals->set_warp( globals->get_options()->get_time_offset() - 
1443                            (aircraftLocalTime - systemLocalTime) - 
1444                            cur_time ); 
1445         break;
1446     default:
1447         FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1448         exit( -1 );
1449     }
1450
1451     FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = " 
1452             << globals->get_warp() );
1453
1454     globals->set_warp_delta( 0 );
1455
1456     t->update( 0.0, 0.0, globals->get_warp() );
1457
1458     globals->set_time_params( t );
1459
1460     // Do some quick general initializations
1461     if( !fgInitGeneral()) {
1462         FG_LOG( FG_GENERAL, FG_ALERT, 
1463                 "General initializations failed ..." );
1464         exit(-1);
1465     }
1466
1467     //
1468     // some ssg test stuff (requires data from the plib source
1469     // distribution) specifically from the ssg tux example
1470     //
1471
1472     FGPath modelpath( globals->get_options()->get_fg_root() );
1473     // modelpath.append( "Models" );
1474     // modelpath.append( "Geometry" );
1475   
1476     FGPath texturepath( globals->get_options()->get_fg_root() );
1477     texturepath.append( "Models" );
1478     texturepath.append( "Textures" );
1479   
1480     ssgModelPath( (char *)modelpath.c_str() );
1481     ssgTexturePath( (char *)texturepath.c_str() );
1482
1483     // Scene graph root
1484     scene = new ssgRoot;
1485     scene->setName( "Scene" );
1486
1487     // Initialize the sky
1488     FGPath ephem_data_path( globals->get_options()->get_fg_root() );
1489     ephem_data_path.append( "Astro" );
1490     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1491     ephem->update( globals->get_time_params()->getMjd(),
1492                    globals->get_time_params()->getLst(),
1493                    0.0 );
1494     globals->set_ephem( ephem );
1495
1496     FGPath sky_tex_path( globals->get_options()->get_fg_root() );
1497     sky_tex_path.append( "Textures" );
1498     sky_tex_path.append( "Sky" );
1499     thesky = new SGSky;
1500     thesky->texture_path( sky_tex_path.str() );
1501
1502     thesky->build( 550.0, 550.0,
1503                    globals->get_ephem()->getNumPlanets(), 
1504                    globals->get_ephem()->getPlanets(), 60000.0,
1505                    globals->get_ephem()->getNumStars(),
1506                    globals->get_ephem()->getStars(), 60000.0 );
1507
1508     if ( globals->get_options()->get_clouds() == true ) {
1509         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1510                                  SG_CLOUD_MOSTLY_SUNNY );
1511         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1512                                  SG_CLOUD_CIRRUS );
1513         // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1514         //                          SG_CLOUD_MOSTLY_SUNNY );
1515         // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1516         // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1517     }
1518
1519     // Initialize MagVar model
1520     SGMagVar *magvar = new SGMagVar();
1521     globals->set_mag( magvar );
1522
1523     // Terrain branch
1524     terrain = new ssgBranch;
1525     terrain->setName( "Terrain" );
1526     scene->addKid( terrain );
1527
1528     // temporary visible aircraft "own ship"
1529     penguin_sel = new ssgSelector;
1530     penguin_pos = new ssgTransform;
1531     string tux_path =
1532       current_properties.getStringValue("/sim/model/path",
1533                                         "Models/Geometry/glider.ac");
1534     ssgEntity *tux_obj = ssgLoad((char *)(tux_path.c_str()));
1535
1536     // align the model properly for FGFS
1537     ssgTransform *tux_align = new ssgTransform;
1538     tux_align->addKid(tux_obj);
1539     sgMat4 tux_matrix;
1540     float h_rot =
1541       current_properties.getFloatValue("/sim/model/h-rotation", 0.0);
1542     float p_rot =
1543       current_properties.getFloatValue("/sim/model/p-rotation", 0.0);
1544     float r_rot =
1545       current_properties.getFloatValue("/sim/model/r-rotation", 0.0);
1546     sgMakeRotMat4(tux_matrix, h_rot, h_rot, r_rot);
1547     tux_align->setTransform(tux_matrix);
1548
1549     penguin_pos->addKid( tux_align );
1550     penguin_sel->addKid( penguin_pos );
1551     ssgFlatten( tux_obj );
1552     ssgStripify( penguin_sel );
1553     penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1554     scene->addKid( penguin_sel );
1555
1556     // $$$ begin - added VS Renganthan 17 Oct 2K
1557     fgLoadDCS();
1558     // $$$ end - added VS Renganthan 17 Oct 2K
1559
1560 #ifdef FG_NETWORK_OLK
1561     // Do the network intialization
1562     if ( globals->get_options()->get_network_olk() ) {
1563         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1564     }
1565 #endif
1566
1567     // build our custom render states
1568     fgBuildRenderStates();
1569
1570     // pass control off to the master GLUT event handler
1571     glutMainLoop();
1572
1573     // we never actually get here ... but to avoid compiler warnings,
1574     // etc.
1575     return 0;
1576 }
1577
1578
1579 // $$$ end - added VS Renganathan, 15 Oct 2K
1580 void fgLoadDCS(void) {
1581
1582     string obj_filename;
1583
1584     FGPath tile_path( globals->get_options()->get_fg_root());
1585     tile_path.append( "Scenery" );
1586     tile_path.append( "Objects.txt" );
1587     fg_gzifstream in( tile_path.str() );
1588     if ( ! in.is_open() ) {
1589         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1590     }
1591
1592     FGPath modelpath( globals->get_options()->get_fg_root() );
1593     modelpath.append( "Models" );
1594     modelpath.append( "Geometry" );
1595   
1596     FGPath texturepath( globals->get_options()->get_fg_root() );
1597     texturepath.append( "Models" );
1598     texturepath.append( "Textures" );
1599  
1600     ssgModelPath( (char *)modelpath.c_str() );
1601     ssgTexturePath( (char *)texturepath.c_str() );
1602
1603     // while ( ! in.eof() ) {
1604     //     in >> obj_filename >> obj_lat >> obj_lon >> obj_alt;
1605     //     totalDCSobj = totalDCSobj+1;
1606
1607     ship_sel = new ssgSelector;
1608     ship_pos = new ssgTransform;
1609     ssgEntity *ship_obj = ssgLoadOBJ( "saratoga.obj" );
1610     if ( ship_obj != NULL ) {
1611         ship_pos->addKid( ship_obj ); // add object to transform node
1612         ship_sel->addKid( ship_pos ); // add transform node to selector
1613         // ssgFlatten( ship_obj );
1614         // ssgStripify( ship_sel );
1615         ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1616         scene->addKid( ship_sel ); //add selector node to root node
1617     } else {
1618         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << "saratoga.obj" );
1619     }
1620
1621     //     if (in.eof()) break;
1622
1623     // } // while
1624     return;
1625 }
1626
1627
1628 void fgUpdateDCS (void) {
1629
1630     // double eye_lat,eye_lon,eye_alt;
1631     static double obj_lat=15.377603*DEG_TO_RAD;
1632     static double obj_lon= 73.816436*DEG_TO_RAD;
1633     static double obj_alt=0.15;
1634     // static double obj_head;
1635     double sl_radius,obj_latgc;
1636     // float nresultmat[4][4];
1637     double bz[3];
1638
1639     obj_lat = obj_lat + 0.0000001;
1640
1641     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1642     //    obj_lon = current_aircraft.fdm_state->get_aux5()*DEG_TO_RAD;
1643     //    obj_lat = current_aircraft.fdm_state->get_aux6()*DEG_TO_RAD;
1644     //    obj_alt = current_aircraft.fdm_state->get_aux7();
1645           
1646     // Geodetic to Geocentric angles for rotation
1647     sgGeodToGeoc(obj_lat,obj_alt,&sl_radius,&obj_latgc);
1648
1649     // moving object gbs-posn in cartesian coords
1650     Point3D obj_posn = Point3D( obj_lon,obj_lat,obj_alt);
1651     Point3D obj_pos = sgGeodToCart( obj_posn );
1652
1653     // Translate moving object w.r.t eye
1654     Point3D Objtrans = obj_pos-scenery.center;
1655     bz[0]=Objtrans.x();
1656     bz[1]=Objtrans.y();
1657     bz[2]=Objtrans.z();
1658
1659     // rotate dynamic objects for lat,lon & alt and other motion about its axes
1660     if ( ship_sel != NULL ) {
1661         ship_sel->select(1);
1662         
1663         sgMat4 sgTRANS;
1664         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1665
1666         sgVec3 ship_fwd,ship_rt,ship_up;
1667         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1668         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1669         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1670
1671         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1672         sgMakeRotMat4( sgROT_lon, obj_lon*RAD_TO_DEG, ship_up );
1673         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1674         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1675         
1676         sgMat4 sgTUX;
1677         sgCopyMat4( sgTUX, sgROT_hdg );
1678         sgPostMultMat4( sgTUX, sgROT_lat );
1679         sgPostMultMat4( sgTUX, sgROT_lon );
1680         sgPostMultMat4( sgTUX, sgTRANS );
1681
1682         sgCoord shippos;
1683         sgSetCoord( &shippos, sgTUX );
1684         ship_pos->setTransform( &shippos );
1685     }
1686 }
1687
1688 // $$$ end - added VS Renganathan, 15 Oct 2K