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