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