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