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