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