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