]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Initial revision.
[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 SG_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/sg_path.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/sgstream.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 * SG_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                                        SG_FEET_TO_METER );
356         pilot_view->set_sea_level_radius( cur_fdm_state->
357                                           get_Sea_level_radius() *
358                                           SG_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() * SGD_RADIANS_TO_DEGREES -
373                        cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
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                                        SG_FEET_TO_METER );
384         chase_view->set_sea_level_radius( cur_fdm_state->
385                                           get_Sea_level_radius() *
386                                           SG_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() * SG_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() * SG_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 sun/lighting parameters
565         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
566
567         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
568         // we only update GL_AMBIENT for our lights we will never get
569         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
570         // explicitely to black.
571         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
572         GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
573         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
574
575         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
576         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
577         // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
578
579         // texture parameters
580         // glEnable( GL_TEXTURE_2D );
581         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
582         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
583
584         // glMatrixMode( GL_PROJECTION );
585         // glLoadIdentity();
586         float fov = globals->get_current_view()->get_fov();
587         ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
588
589         double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
590             - scenery.cur_elev;
591
592         // SG_LOG( SG_ALL, SG_INFO, "visibility is " 
593         //         << current_weather.get_visibility() );
594             
595         if ( agl > 10.0 ) {
596             ssgSetNearFar( 10.0f, 120000.0f );
597         } else {
598             ssgSetNearFar( 0.5f, 120000.0f );
599         }
600
601         if ( globals->get_viewmgr()->get_current() == 0 ) {
602             // disable aircraft model
603             acmodel_selector->select(0);
604         } else { 
605             // enable aircraft model and set up its position and orientation
606             acmodel_selector->select(1);
607
608             FGViewerRPH *pilot_view =
609                 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
610
611             sgMat4 sgTRANS;
612             sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
613
614             sgVec3 ownship_up;
615             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
616
617             sgMat4 sgROT;
618             sgMakeRotMat4( sgROT, -90.0, ownship_up );
619
620             // sgMat4 sgTMP;
621             // sgMat4 sgTUX;
622             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
623             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
624
625             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
626             sgMat4 sgTUX;
627             sgCopyMat4( sgTUX, sgROT );
628             sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
629             sgPostMultMat4( sgTUX, sgTRANS );
630         
631             sgCoord tuxpos;
632             sgSetCoord( &tuxpos, sgTUX );
633             acmodel_pos->setTransform( &tuxpos );
634
635             // set up moving parts
636             if (flaps_selector != NULL) {
637               flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
638             }
639
640             if (prop_selector != NULL) {
641               int propsel_mask = 0;
642               for (int i = 0; i < acmodel_npropsettings; i++) {
643                 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
644                     FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
645                   propsel_mask |= 1 << i;
646                 }
647               }
648               prop_selector->select(propsel_mask);
649             }
650         }
651
652         // $$$ begin - added VS Renganthan 17 Oct 2K
653         fgUpdateDCS();
654         // $$$ end - added VS Renganthan 17 Oct 2K
655
656 # ifdef FG_NETWORK_OLK
657         if ( fgGetBool("/sim/networking/network-olk") ) {
658             sgCoord fgdpos;
659             other = head->next;             /* put listpointer to start  */
660             while ( other != tail) {        /* display all except myself */
661                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
662                     other->fgd_sel->select(1);
663                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
664                     other->fgd_pos->setTransform( &fgdpos );
665                 }
666                 other = other->next;
667             }
668
669             // fgd_sel->select(1);
670             // sgCopyMat4( sgTUX, current_view.sgVIEW);
671             // sgCoord fgdpos;
672             // sgSetCoord( &fgdpos, sgFGD_VIEW );
673             // fgd_pos->setTransform( &fgdpos);
674         }
675 # endif
676
677         // position tile nodes and update range selectors
678         global_tile_mgr.prep_ssg_nodes();
679
680         if ( fgGetBool("/sim/rendering/skyblend") ) {
681             // draw the sky backdrop
682
683             // we need a white diffuse light for the phase of the moon
684             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
685
686             thesky->preDraw();
687
688             // return to the desired diffuse color
689             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
690         }
691
692         // draw the ssg scene
693         glEnable( GL_DEPTH_TEST );
694         ssgCullAndDraw( scene );
695
696         // change state for lighting here
697
698         // draw lighting
699         // Set punch through fog density
700         glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
701
702         ssgCullAndDraw( lighting );
703
704         if ( fgGetBool("/sim/rendering/skyblend") ) {
705             // draw the sky cloud layers
706             thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
707         }
708
709         // display HUD && Panel
710         glDisable( GL_FOG );
711         glDisable( GL_DEPTH_TEST );
712         // glDisable( GL_CULL_FACE );
713         // glDisable( GL_TEXTURE_2D );
714
715         // update the controls subsystem
716         controls.update();
717
718         hud_and_panel->apply();
719         fgCockpitUpdate();
720
721         // update the panel subsystem
722         if (current_panel != 0)
723           current_panel->update();
724
725         // We can do translucent menus, so why not. :-)
726         menus->apply();
727         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
728         puDisplay();
729         // glDisable ( GL_BLEND ) ;
730
731         // glEnable( GL_FOG );
732     }
733
734     glutSwapBuffers();
735 }
736
737
738 // Update internal time dependent calculations (i.e. flight model)
739 void fgUpdateTimeDepCalcs() {
740     static bool inited = false;
741
742     fgLIGHT *l = &cur_light_params;
743     int i;
744
745     long multi_loop = 1;
746
747     if ( !globals->get_freeze() && !initial_freeze ) {
748         // conceptually, this could be done for each fdm instance ...
749
750         if ( !inited ) {
751             cur_fdm_state->stamp();
752             inited = true;
753         }
754
755         SGTimeStamp current;
756         current.stamp();
757         long elapsed = current - cur_fdm_state->get_time_stamp();
758         cur_fdm_state->set_time_stamp( current );
759         elapsed += cur_fdm_state->get_remainder();
760         // cout << "elapsed = " << elapsed << endl;
761         // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
762         multi_loop = (long)(((double)elapsed * 0.000001) /
763                                cur_fdm_state->get_delta_t() );
764         cur_fdm_state->set_multi_loop( multi_loop );
765         long remainder = elapsed - (long)( (multi_loop*1000000) *
766                                      cur_fdm_state->get_delta_t() );
767         cur_fdm_state->set_remainder( remainder );
768         // cout << "remainder = " << remainder << endl;
769
770         // chop max interations to something reasonable if the sim was
771         // delayed for an excesive amount of time
772         if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
773             multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
774             cur_fdm_state->set_remainder( 0 );
775         }
776
777         // cout << "multi_loop = " << multi_loop << endl;
778         for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
779             // run Autopilot system
780             current_autopilot->run();
781
782             // update autopilot
783             cur_fdm_state->update( 1 );
784         }
785         FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
786     } else {
787         cur_fdm_state->update( 0 );
788         FGSteam::update( 0 );
789
790         if ( global_tile_mgr.queue_size() == 0 ) {
791             initial_freeze = false;
792         }
793     }
794
795     if ( fgGetString("/sim/view-mode") == "pilot" ) {
796         cur_view_fdm = *cur_fdm_state;
797         // do nothing
798     }
799
800     // update the view angle
801     FGViewer *v = globals->get_current_view();
802     for ( i = 0; i < multi_loop; i++ ) {
803         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
804             v->set_view_offset( v->get_goal_view_offset() );
805             break;
806         } else {
807             // move current_view.view_offset towards
808             // current_view.goal_view_offset
809             if ( v->get_goal_view_offset() > v->get_view_offset() )
810             {
811                 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
812                     v->inc_view_offset( 0.01 );
813                 } else {
814                     v->inc_view_offset( -0.01 );
815                 }
816             } else {
817                 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
818                     v->inc_view_offset( -0.01 );
819                 } else {
820                     v->inc_view_offset( 0.01 );
821                 }
822             }
823             if ( v->get_view_offset() > SGD_2PI ) {
824                 v->inc_view_offset( -SGD_2PI );
825             } else if ( v->get_view_offset() < 0 ) {
826                 v->inc_view_offset( SGD_2PI );
827             }
828         }
829     }
830
831     double tmp = -(l->sun_rotation + SGD_PI) 
832         - (cur_fdm_state->get_Psi() -
833            globals->get_current_view()->get_view_offset() );
834     while ( tmp < 0.0 ) {
835         tmp += SGD_2PI;
836     }
837     while ( tmp > SGD_2PI ) {
838         tmp -= SGD_2PI;
839     }
840     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
841            FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES, 
842            -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
843     l->UpdateAdjFog();
844
845     // Update solar system
846     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
847                                   globals->get_time_params()->getLst(),
848                                   cur_fdm_state->get_Latitude() );
849
850     // Update radio stack model
851     current_radiostack->update();
852 }
853
854
855 void fgInitTimeDepCalcs( void ) {
856     // initialize timer
857
858     // #ifdef HAVE_SETITIMER
859     //   fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"), 
860     //                fgUpdateTimeDepCalcs );
861     // #endif HAVE_SETITIMER
862 }
863
864
865 static const double alt_adjust_ft = 3.758099;
866 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
867
868
869 // What should we do when we have nothing else to do?  Let's get ready
870 // for the next move and update the display?
871 static void fgMainLoop( void ) {
872     static long remainder = 0;
873     long elapsed;
874 #ifdef FANCY_FRAME_COUNTER
875     int i;
876     double accum;
877 #else
878     static time_t last_time = 0;
879     static int frames = 0;
880 #endif // FANCY_FRAME_COUNTER
881
882     SGTime *t = globals->get_time_params();
883
884     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
885     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
886
887 #ifdef FG_NETWORK_OLK
888     if ( fgGetBool("/sim/networking/network-olk") ) {
889         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
890             // printf("FGD: Netupdate\n");
891             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
892             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
893         }
894     }
895 #endif
896
897 #if defined( ENABLE_PLIB_JOYSTICK )
898     // Read joystick and update control settings
899     if ( fgGetString("/sim/control-mode") == "joystick" )
900     {
901         fgJoystickRead();
902     }
903 #elif defined( ENABLE_GLUT_JOYSTICK )
904     // Glut joystick support works by feeding a joystick handler
905     // function to glut.  This is taken care of once in the joystick
906     // init routine and we don't have to worry about it again.
907 #endif
908
909 #ifdef FG_OLD_WEATHER
910     current_weather.Update();
911 #endif
912
913     // Fix elevation.  I'm just sticking this here for now, it should
914     // probably move eventually
915
916     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
917            scenery.cur_elev,
918            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
919            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
920
921     if ( scenery.cur_elev > -9990 ) {
922         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
923              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
924             // now set aircraft altitude above ground
925             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
926                    cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
927                    scenery.cur_elev + alt_adjust_m - 3.0,
928                    scenery.cur_elev + alt_adjust_m );
929             fgFDMForceAltitude( fgGetString("/sim/flight-model"), 
930                                 scenery.cur_elev + alt_adjust_m );
931
932             SG_LOG( SG_ALL, SG_DEBUG, 
933                     "<*> resetting altitude to " 
934                     << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
935                     << " meters" );
936         }
937     }
938
939     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
940            scenery.cur_elev,
941            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
942            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
943
944     // update "time"
945     if ( globals->get_warp_delta() != 0 ) {
946         globals->inc_warp( globals->get_warp_delta() );
947     }
948
949     t->update( cur_fdm_state->get_Longitude(),
950                cur_fdm_state->get_Latitude(),
951                globals->get_warp() );
952
953     if ( globals->get_warp_delta() != 0 ) {
954         fgUpdateSkyAndLightingParams();
955     }
956
957     // update magvar model
958     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
959                                 cur_fdm_state->get_Latitude(),
960                                 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
961                                 globals->get_time_params()->getJD() );
962
963     // Get elapsed time (in usec) for this past frame
964     elapsed = fgGetTimeInterval();
965     SG_LOG( SG_ALL, SG_DEBUG, 
966             "Elapsed time interval is = " << elapsed 
967             << ", previous remainder is = " << remainder );
968
969     // Calculate frame rate average
970 #ifdef FANCY_FRAME_COUNTER
971     /* old fps calculation */
972     if ( elapsed > 0 ) {
973         double tmp;
974         accum = 0.0;
975         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
976             tmp = general.get_frame(i);
977             accum += tmp;
978             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
979             general.set_frame(i+1,tmp);
980         }
981         tmp = 1000000.0 / (float)elapsed;
982         general.set_frame(0,tmp);
983         // printf("frame[0] = %.2f\n", general.frames[0]);
984         accum += tmp;
985         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
986         // printf("ave = %.2f\n", general.frame_rate);
987     }
988 #else
989     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
990         general.set_frame_rate( frames );
991         SG_LOG( SG_ALL, SG_DEBUG, 
992                 "--> Frame rate is = " << general.get_frame_rate() );
993         frames = 0;
994     }
995     last_time = t->get_cur_time();
996     ++frames;
997 #endif
998
999     // Run flight model
1000
1001     // Calculate model iterations needed for next frame
1002     elapsed += remainder;
1003
1004     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1005                               fgGetInt("/sim/model-hz"));
1006     remainder = elapsed - ( (global_multi_loop*1000000) / 
1007                             fgGetInt("/sim/model-hz") );
1008     SG_LOG( SG_ALL, SG_DEBUG, 
1009             "Model iterations needed = " << global_multi_loop
1010             << ", new remainder = " << remainder );
1011         
1012     // chop max interations to something reasonable if the sim was
1013     // delayed for an excesive amount of time
1014     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1015         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1016         remainder = 0;
1017     }
1018
1019     // flight model
1020     if ( global_multi_loop > 0 ) {
1021         fgUpdateTimeDepCalcs();
1022     } else {
1023         SG_LOG( SG_ALL, SG_DEBUG, 
1024                 "Elapsed time is zero ... we're zinging" );
1025     }
1026
1027 #if ! defined( macintosh )
1028     // Do any I/O channel work that might need to be done
1029     fgIOProcess();
1030 #endif
1031
1032     // see if we need to load any new scenery tiles
1033     global_tile_mgr.update( cur_fdm_state->get_Longitude()
1034                             * SGD_RADIANS_TO_DEGREES,
1035                             cur_fdm_state->get_Latitude()
1036                             * SGD_RADIANS_TO_DEGREES );
1037
1038     // Process/manage pending events
1039     global_events.Process();
1040
1041     // Run audio scheduler
1042 #ifdef ENABLE_AUDIO_SUPPORT
1043     if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1044         if ( fgGetString("/sim/aircraft") == "c172" ) {
1045             // pitch corresponds to rpm
1046             // volume corresponds to manifold pressure
1047
1048             // cout << "AUDIO working = "
1049             //      << globals->get_soundmgr()->is_working() << endl;
1050
1051             double rpm_factor;
1052             if ( cur_fdm_state->get_engine(0) != NULL ) {
1053                 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1054             } else {
1055                 rpm_factor = 1.0;
1056             }
1057             // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1058             //      << endl;
1059
1060             double pitch = 0.3 + rpm_factor * 3.0;
1061         
1062             // don't run at absurdly slow rates -- not realistic
1063             // and sounds bad to boot.  :-)
1064             if (pitch < 0.7) { pitch = 0.7; }
1065             if (pitch > 5.0) { pitch = 5.0; }
1066
1067             double mp_factor;
1068             if ( cur_fdm_state->get_engine(0) != NULL ) {
1069                 mp_factor = 
1070                     cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1071             } else {
1072                 mp_factor = 0.3;
1073             }
1074             /* cout << "mp = " 
1075                  << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1076                  << endl; */
1077
1078             double volume = 0.15 + mp_factor / 2.0;
1079
1080             if ( volume < 0.15 ) { volume = 0.15; }
1081             if ( volume > 0.5 ) { volume = 0.5; }
1082             // cout << "volume = " << volume << endl;
1083
1084             s1->set_pitch( pitch );
1085             s1->set_volume( volume );
1086         } else {
1087             double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1088             s1->set_pitch( param );
1089             s1->set_volume( param );
1090         }
1091
1092         globals->get_soundmgr()->update();
1093     }
1094 #endif
1095
1096     // redraw display
1097     fgRenderFrame();
1098
1099     SG_LOG( SG_ALL, SG_DEBUG, "" );
1100 }
1101
1102
1103 // This is the top level master main function that is registered as
1104 // our idle funciton
1105 //
1106
1107 // The first few passes take care of initialization things (a couple
1108 // per pass) and once everything has been initialized fgMainLoop from
1109 // then on.
1110
1111 static void fgIdleFunction ( void ) {
1112     // printf("idle state == %d\n", idle_state);
1113
1114     if ( idle_state == 0 ) {
1115         // Initialize the splash screen right away
1116         if ( fgGetBool("/sim/startup/splash-screen") ) {
1117             fgSplashInit();
1118         }
1119         
1120         idle_state++;
1121     } else if ( idle_state == 1 ) {
1122         // Start the intro music
1123 #if !defined(WIN32)
1124         if ( fgGetBool("/sim/startup/intro-music") ) {
1125             string lockfile = "/tmp/mpg123.running";
1126             SGPath mp3file( globals->get_fg_root() );
1127             mp3file.append( "Sounds/intro.mp3" );
1128
1129             string command = "(touch " + lockfile + "; mpg123 "
1130                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1131                 + lockfile + ") &";
1132             SG_LOG( SG_GENERAL, SG_INFO, 
1133                     "Starting intro music: " << mp3file.str() );
1134             system ( command.c_str() );
1135         }
1136 #endif
1137
1138         idle_state++;
1139     } else if ( idle_state == 2 ) {
1140         // These are a few miscellaneous things that aren't really
1141         // "subsystems" but still need to be initialized.
1142
1143 #ifdef USE_GLIDE
1144         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1145             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1146         }
1147 #endif
1148
1149         idle_state++;
1150     } else if ( idle_state == 3 ) {
1151         // This is the top level init routine which calls all the
1152         // other subsystem initialization routines.  If you are adding
1153         // a subsystem to flightgear, its initialization call should
1154         // located in this routine.
1155         if( !fgInitSubsystems()) {
1156             SG_LOG( SG_GENERAL, SG_ALERT,
1157                     "Subsystem initializations failed ..." );
1158             exit(-1);
1159         }
1160
1161         idle_state++;
1162     } else if ( idle_state == 4 ) {
1163         // setup OpenGL view parameters
1164         fgInitVisuals();
1165
1166         idle_state++;
1167     } else if ( idle_state == 5 ) {
1168
1169         idle_state++;
1170     } else if ( idle_state == 6 ) {
1171         // Initialize audio support
1172 #ifdef ENABLE_AUDIO_SUPPORT
1173
1174 #if !defined(WIN32)
1175         if ( fgGetBool("/sim/startup/intro-music") ) {
1176             // Let's wait for mpg123 to finish
1177             string lockfile = "/tmp/mpg123.running";
1178             struct stat stat_buf;
1179
1180             SG_LOG( SG_GENERAL, SG_INFO, 
1181                     "Waiting for mpg123 player to finish ..." );
1182             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1183                 // file exist, wait ...
1184                 sleep(1);
1185                 SG_LOG( SG_GENERAL, SG_INFO, ".");
1186             }
1187             SG_LOG( SG_GENERAL, SG_INFO, "");
1188         }
1189 #endif // WIN32
1190
1191         if ( fgGetBool("/sim/sound") ) {
1192             globals->get_soundmgr()->init();
1193
1194             s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1195                                                 "Sounds/wasp.wav") );
1196             globals->get_soundmgr()->add( s1, "engine loop" );
1197             globals->get_soundmgr()->play_looped( "engine loop" );
1198             SG_LOG( SG_GENERAL, SG_INFO,
1199                     "Rate = " << s1->get_sample()->getRate()
1200                     << "  Bps = " << s1->get_sample()->getBps()
1201                     << "  Stereo = " << s1->get_sample()->getStereo() );
1202
1203             s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1204             // FGMorse mmm;
1205             // mmm.init();
1206             // s2 = mmm.make_ident( "JLI" );
1207             s2->set_volume( 0.3 );
1208             globals->get_soundmgr()->add( s2, "flaps" );
1209         }
1210 #endif
1211
1212         // sleep(1);
1213         idle_state = 1000;
1214
1215         cout << "Panel visible = " << fgPanelVisible() << endl;
1216         fgReshape( fgGetInt("/sim/startup/xsize"),
1217                    fgGetInt("/sim/startup/ysize") );
1218     } 
1219
1220     if ( idle_state == 1000 ) {
1221         // We've finished all our initialization steps, from now on we
1222         // run the main loop.
1223
1224         fgMainLoop();
1225     } else {
1226         if ( fgGetBool("/sim/startup/splash-screen") ) {
1227             fgSplashUpdate(0.0);
1228         }
1229     }
1230 }
1231
1232 // options.cxx needs to see this for toggle_panel()
1233 // Handle new window size or exposure
1234 void fgReshape( int width, int height ) {
1235     // for all views
1236     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1237         if ( ! fgPanelVisible() || idle_state != 1000 ) {
1238             globals->get_viewmgr()->get_view(i)->
1239                 set_win_ratio( (float)height / (float)width );
1240         } else {
1241             int view_h =
1242                 int((current_panel->getViewHeight() -
1243                      current_panel->getYOffset())
1244                     * (height / 768.0)) + 1;
1245             globals->get_viewmgr()->get_view(i)->
1246                 set_win_ratio( (float)view_h / (float)width );
1247         }
1248     }
1249
1250     if ( ! fgPanelVisible() || idle_state != 1000 ) {
1251         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1252     } else {
1253         int view_h =
1254             int((current_panel->getViewHeight() - current_panel->getYOffset())
1255                 * (height / 768.0)) + 1;
1256         glViewport(0, (GLint)(height - view_h),
1257                    (GLint)(width), (GLint)(view_h) );
1258     }
1259
1260     fgSetInt("/sim/startup/xsize", width);
1261     fgSetInt("/sim/startup/ysize", height);
1262
1263     float fov = globals->get_current_view()->get_fov();
1264     ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1265
1266     fgHUDReshape();
1267 }
1268
1269
1270 // Initialize GLUT and define a main window
1271 int fgGlutInit( int *argc, char **argv ) {
1272
1273 #if !defined( macintosh )
1274     // GLUT will extract all glut specific options so later on we only
1275     // need wory about our own.
1276     glutInit(argc, argv);
1277 #endif
1278
1279     // Define Display Parameters
1280     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1281
1282     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1283             fgGetInt("/sim/startup/xsize") << "x"
1284             << fgGetInt("/sim/startup/ysize") );
1285
1286     // Define initial window size
1287     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1288                         fgGetInt("/sim/startup/ysize") );
1289
1290     // Initialize windows
1291     if ( !fgGetBool("/sim/startup/game-mode")) {
1292         // Open the regular window
1293         glutCreateWindow("FlightGear");
1294 #ifndef GLUT_WRONG_VERSION
1295     } else {
1296         // Open the cool new 'game mode' window
1297         char game_mode_str[256];
1298         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1299                  fgGetInt("/sim/startup/xsize"),
1300                  fgGetInt("/sim/startup/ysize"),
1301                  fgGetInt("/sim/rendering/bits-per-pixel"));
1302
1303         SG_LOG( SG_GENERAL, SG_INFO, 
1304                 "game mode params = " << game_mode_str );
1305         glutGameModeString( game_mode_str );
1306         glutEnterGameMode();
1307 #endif
1308     }
1309
1310     // This seems to be the absolute earliest in the init sequence
1311     // that these calls will return valid info.  Too bad it's after
1312     // we've already created and sized out window. :-(
1313     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1314     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1315     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1316     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1317
1318     GLint tmp;
1319     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1320     general.set_glMaxTexSize( tmp );
1321     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1322
1323     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1324     general.set_glDepthBits( tmp );
1325     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1326
1327     return 1;
1328 }
1329
1330
1331 // Initialize GLUT event handlers
1332 int fgGlutInitEvents( void ) {
1333     // call fgReshape() on window resizes
1334     glutReshapeFunc( fgReshape );
1335
1336     // call GLUTkey() on keyboard event
1337     glutKeyboardFunc( GLUTkey );
1338     glutSpecialFunc( GLUTspecialkey );
1339
1340     // call guiMouseFunc() whenever our little rodent is used
1341     glutMouseFunc ( guiMouseFunc );
1342     glutMotionFunc (guiMotionFunc );
1343     glutPassiveMotionFunc (guiMotionFunc );
1344
1345     // call fgMainLoop() whenever there is
1346     // nothing else to do
1347     glutIdleFunc( fgIdleFunction );
1348
1349     // draw the scene
1350     glutDisplayFunc( fgRenderFrame );
1351
1352     return(1);
1353 }
1354
1355
1356 // Main ...
1357 int main( int argc, char **argv ) {
1358
1359 #if defined( macintosh )
1360     freopen ("stdout.txt", "w", stdout );
1361     freopen ("stderr.txt", "w", stderr );
1362     argc = ccommand( &argv );
1363 #endif
1364
1365 #ifdef HAVE_BC5PLUS
1366     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1367 #endif
1368
1369     // set default log levels
1370     sglog().setLogLevels( SG_ALL, SG_INFO );
1371
1372     string version;
1373 #ifdef FLIGHTGEAR_VERSION
1374     version = FLIGHTGEAR_VERSION;
1375 #else
1376     version = "unknown version";
1377 #endif
1378     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1379             << version << endl );
1380
1381     // Allocate global data structures.  This needs to happen before
1382     // we parse command line options
1383
1384     SGPropertyNode *props = new SGPropertyNode;
1385     globals = new FGGlobals;
1386     globals->set_props( props );
1387
1388     // seed the random number generater
1389     sg_srandom_time();
1390
1391     SGRoute *route = new SGRoute;
1392     globals->set_route( route );
1393
1394 #ifdef ENABLE_AUDIO_SUPPORT
1395     FGSoundMgr *soundmgr = new FGSoundMgr;
1396     globals->set_soundmgr( soundmgr );
1397 #endif
1398
1399     FGViewMgr *viewmgr = new FGViewMgr;
1400     globals->set_viewmgr( viewmgr );
1401
1402     FGViewerRPH *pv = new FGViewerRPH;
1403     globals->get_viewmgr()->add_view( pv );
1404
1405     FGViewerLookAt *chase = new FGViewerLookAt;
1406     globals->get_viewmgr()->add_view( chase );
1407
1408     string_list *col = new string_list;
1409     globals->set_channel_options_list( col );
1410
1411     // set current view to 0 (first) which is our main pilot view
1412     globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1413
1414     // Scan the config file(s) and command line options to see if
1415     // fg_root was specified (ignore all other options for now)
1416     fgInitFGRoot(argc, argv);
1417
1418     // Initialize the Aircraft directory to "" (UIUC)
1419     aircraft_dir = "";
1420
1421     // Load the configuration parameters
1422     if ( !fgInitConfig(argc, argv) ) {
1423         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1424         exit(-1);
1425     }
1426
1427     // Initialize the Window/Graphics environment.
1428     if( !fgGlutInit(&argc, argv) ) {
1429         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1430         exit(-1);
1431     }
1432
1433     // Initialize the various GLUT Event Handlers.
1434     if( !fgGlutInitEvents() ) {
1435         SG_LOG( SG_GENERAL, SG_ALERT, 
1436                 "GLUT event handler initialization failed ..." );
1437         exit(-1);
1438     }
1439  
1440     // Initialize ssg (from plib).  Needs to come before we do any
1441     // other ssg stuff, but after opengl/glut has been initialized.
1442     ssgInit();
1443
1444     // Initialize the user interface (we need to do this before
1445     // passing off control to glut and before fgInitGeneral to get our
1446     // fonts !!!
1447     guiInit();
1448
1449     // set current_options lon/lat if an airport id is specified
1450     // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1451     if ( fgGetString("/sim/startup/airport-id").length() ) {
1452         // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1453         fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1454                                      fgGetDouble("/orientation/heading") );
1455     }
1456
1457     // Initialize time
1458     SGPath zone( globals->get_fg_root() );
1459     zone.append( "Timezone" );
1460     SGTime *t = new SGTime( fgGetDouble("/position/longitude") * SGD_DEGREES_TO_RADIANS,
1461                             fgGetDouble("/position/latitude") * SGD_DEGREES_TO_RADIANS,
1462                             zone.str() );
1463
1464     // Handle potential user specified time offsets
1465     time_t cur_time = t->get_cur_time();
1466     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1467     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1468     time_t aircraftLocalTime = 
1469         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1470
1471     // Okay, we now have six possible scenarios
1472     int offset = fgGetInt("/sim/startup/time-offset");
1473     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1474     if (offset_type == "system-offset") {
1475         globals->set_warp( offset );
1476     } else if (offset_type == "gmt-offset") {
1477         globals->set_warp( offset - (currGMT - systemLocalTime) );
1478     } else if (offset_type == "latitude-offset") {
1479         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1480     } else if (offset_type == "system") {
1481         globals->set_warp( offset - cur_time );
1482     } else if (offset_type == "gmt") {
1483         globals->set_warp( offset - currGMT );
1484     } else if (offset_type == "latitude") {
1485         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1486                            cur_time ); 
1487     } else {
1488         SG_LOG( SG_GENERAL, SG_ALERT,
1489                 "Unsupported offset type " << offset_type );
1490         exit( -1 );
1491     }
1492
1493     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1494             << globals->get_warp() );
1495
1496     globals->set_warp_delta( 0 );
1497
1498     t->update( 0.0, 0.0, globals->get_warp() );
1499
1500     globals->set_time_params( t );
1501
1502     // Do some quick general initializations
1503     if( !fgInitGeneral()) {
1504         SG_LOG( SG_GENERAL, SG_ALERT, 
1505                 "General initializations failed ..." );
1506         exit(-1);
1507     }
1508
1509     SGPath modelpath( globals->get_fg_root() );
1510     ssgModelPath( (char *)modelpath.c_str() );
1511   
1512     // Scene graph root
1513     scene = new ssgRoot;
1514     scene->setName( "Scene" );
1515
1516     lighting = new ssgRoot;
1517     lighting->setName( "Lighting" );
1518
1519     // Initialize the sky
1520     SGPath ephem_data_path( globals->get_fg_root() );
1521     ephem_data_path.append( "Astro" );
1522     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1523     ephem->update( globals->get_time_params()->getMjd(),
1524                    globals->get_time_params()->getLst(),
1525                    0.0 );
1526     globals->set_ephem( ephem );
1527
1528     SGPath sky_tex_path( globals->get_fg_root() );
1529     sky_tex_path.append( "Textures" );
1530     sky_tex_path.append( "Sky" );
1531     thesky = new SGSky;
1532     thesky->texture_path( sky_tex_path.str() );
1533
1534     thesky->build( 550.0, 550.0,
1535                    globals->get_ephem()->getNumPlanets(), 
1536                    globals->get_ephem()->getPlanets(), 60000.0,
1537                    globals->get_ephem()->getNumStars(),
1538                    globals->get_ephem()->getStars(), 60000.0 );
1539
1540     if ( fgGetBool("/environment/clouds/status") ) {
1541         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1542                                  SG_CLOUD_MOSTLY_SUNNY );
1543         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1544                                  SG_CLOUD_CIRRUS );
1545         // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1546         //                          SG_CLOUD_MOSTLY_SUNNY );
1547         // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1548         // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1549     }
1550
1551     // Initialize MagVar model
1552     SGMagVar *magvar = new SGMagVar();
1553     globals->set_mag( magvar );
1554
1555     // Terrain branch
1556     terrain = new ssgBranch;
1557     terrain->setName( "Terrain" );
1558     scene->addKid( terrain );
1559
1560     // Lighting
1561     ground = new ssgBranch;
1562     ground->setName( "Ground Lighting" );
1563     lighting->addKid( ground );
1564
1565     airport = new ssgBranch;
1566     airport->setName( "Airport Lighting" );
1567     lighting->addKid( airport );
1568
1569     // temporary visible aircraft "own ship"
1570     acmodel_selector = new ssgSelector;
1571     acmodel_pos = new ssgTransform;
1572
1573     // Get the model location, and load textures from the same
1574     // directory.  Use an absolute path for the model to avoid
1575     // incompatibilities in different versions of PLIB.
1576     string acmodel_path =
1577         fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1578     SGPath full_model = globals->get_fg_root();
1579     full_model.append(acmodel_path);
1580     // this should be redundant...
1581     ssgModelPath( (char *)full_model.dir().c_str() );
1582     ssgTexturePath( (char *)full_model.dir().c_str() );
1583     ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1584
1585     // find moving parts (if this is an MDL model)
1586     flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1587     prop_selector  = (ssgSelector*)fgFindNode( acmodel_obj, "PROP"  );
1588
1589     acmodel_npropsettings = 0;
1590     if (prop_selector != NULL) {
1591       for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1592            kid = prop_selector->getNextKid()) {
1593         int prop_low, prop_high;
1594         if ( sscanf(kid->getName(), "PROP_%d_%d", 
1595                     &prop_low, &prop_high) == 2 ) {
1596           prop_low  = (int)((float)prop_low  * (5000.0f / 32767.0f));
1597           prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1598           acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1599           acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1600           acmodel_npropsettings++;
1601
1602           SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1603                   " " << prop_high );
1604         }
1605       }
1606     }
1607
1608     // align the model properly for FGFS
1609     ssgTransform *acmodel_align = new ssgTransform;
1610     acmodel_align->addKid(acmodel_obj);
1611     sgMat4 rot_matrix;
1612     sgMat4 off_matrix;
1613     sgMat4 res_matrix;
1614     float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1615     float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1616     float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1617     float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1618     float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1619     float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1620     sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1621     sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1622     sgMultMat4(res_matrix, off_matrix, rot_matrix);
1623     acmodel_align->setTransform(res_matrix);
1624
1625     acmodel_pos->addKid( acmodel_align );
1626     acmodel_selector->addKid( acmodel_pos );
1627     //ssgFlatten( acmodel_obj );
1628     //ssgStripify( acmodel_selector );
1629     acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1630     scene->addKid( acmodel_selector );
1631
1632     // $$$ begin - added VS Renganthan 17 Oct 2K
1633     fgLoadDCS();
1634     // $$$ end - added VS Renganthan 17 Oct 2K
1635
1636 #ifdef FG_NETWORK_OLK
1637     // Do the network intialization
1638     if ( fgGetBool("/sim/networking/network-olk") ) {
1639         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1640     }
1641 #endif
1642
1643     // build our custom render states
1644     fgBuildRenderStates();
1645
1646     // pass control off to the master GLUT event handler
1647     glutMainLoop();
1648
1649     // we never actually get here ... but to avoid compiler warnings,
1650     // etc.
1651     return 0;
1652 }
1653
1654
1655 // $$$ end - added VS Renganathan, 15 Oct 2K
1656 //         - added Venky         , 12 Nov 2K
1657
1658 void fgLoadDCS(void) {
1659
1660     ssgEntity *ship_obj = NULL;
1661     // double bz[3];
1662     // int j=0;
1663     char obj_filename[25];
1664
1665     for ( int k = 0; k < 32; k++ ) {
1666         ship_pos[k]=NULL;
1667     }
1668
1669     SGPath tile_path( globals->get_fg_root());
1670     tile_path.append( "Scenery" );
1671     tile_path.append( "Objects.txt" );
1672     sg_gzifstream in( tile_path.str() );
1673     if ( ! in.is_open() ) {
1674         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1675     } else {
1676
1677         SGPath modelpath( globals->get_fg_root() );
1678         modelpath.append( "Models" );
1679         modelpath.append( "Geometry" );
1680   
1681         SGPath texturepath( globals->get_fg_root() );
1682         texturepath.append( "Models" );
1683         texturepath.append( "Textures" );
1684  
1685         ssgModelPath( (char *)modelpath.c_str() );
1686         ssgTexturePath( (char *)texturepath.c_str() );
1687
1688         ship_sel = new ssgSelector;
1689
1690         char c;
1691         while ( ! in.eof() ) {
1692             in >> ::skipws;
1693             if ( in.get( c ) && c == '#' ) { 
1694                 in >> skipeol;
1695             } else { 
1696                 in.putback(c);
1697                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1698                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1699                    int chj=getchar();*/
1700                 
1701                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1702                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1703                 
1704                 ship_pos[objc] = new ssgTransform;
1705        
1706                 // type "repeat" in objects.txt to load one more
1707                 // instance of the last object.
1708
1709                 if ( strcmp(obj_filename,"repeat") != 0) {
1710                     ship_obj = ssgLoadOBJ( obj_filename );
1711                 }
1712       
1713                 if ( ship_obj != NULL ) {
1714                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1715                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1716                 } else {
1717                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1718                             << obj_filename );
1719                 }
1720             
1721                 objc++;
1722
1723                 if (in.eof()) break;
1724             }
1725         } // while
1726
1727         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1728
1729         ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1730         scene->addKid( ship_sel ); //add selector node to root node
1731     }
1732
1733     return;
1734  }
1735
1736
1737 void fgUpdateDCS (void) {
1738
1739     // double eye_lat,eye_lon,eye_alt;
1740     // static double obj_head;
1741     double sl_radius,obj_latgc;
1742     // float nresultmat[4][4];
1743     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1744     double bz[3];
1745
1746     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1747     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1748     
1749     // Deck should be the first object in objects.txt in case of fdm=ada
1750
1751     if (fgGetString("/sim/flight-model") == "ada") {
1752         obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1753         obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1754         obj_alt[0] = fdm->get_aux7();
1755     }
1756     
1757     for ( int m = 0; m < objc; m++ ) {
1758         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1759         //int v=getchar();
1760
1761         //Geodetic to Geocentric angles for rotation
1762         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1763
1764         //moving object gbs-posn in cartesian coords
1765         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1766         Point3D obj_pos = sgGeodToCart( obj_posn );
1767
1768         // Translate moving object w.r.t eye
1769         Point3D Objtrans = obj_pos-scenery.center;
1770         bz[0]=Objtrans.x();
1771         bz[1]=Objtrans.y();
1772         bz[2]=Objtrans.z();
1773
1774        // rotate dynamic objects for lat,lon & alt and other motion about its axes
1775         
1776         sgMat4 sgTRANS;
1777         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1778
1779         sgVec3 ship_fwd,ship_rt,ship_up;
1780         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1781         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1782         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1783
1784         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1785         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1786         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1787         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1788         
1789         sgMat4 sgTUX;
1790         sgCopyMat4( sgTUX, sgROT_hdg );
1791         sgPostMultMat4( sgTUX, sgROT_lat );
1792         sgPostMultMat4( sgTUX, sgROT_lon );
1793         sgPostMultMat4( sgTUX, sgTRANS );
1794
1795         sgCoord shippos;
1796         sgSetCoord(&shippos, sgTUX );
1797         ship_pos[m]->setTransform( &shippos );
1798     }
1799     if ( ship_sel != NULL ) {
1800         ship_sel->select(0xFFFFFFFF);
1801     }
1802 }
1803
1804 // $$$ end - added VS Renganathan, 15 Oct 2K
1805 //           added Venky         , 12 Nov 2K