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