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