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