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