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