1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
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.
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.
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.
28 #include <simgear/compiler.h>
30 #ifdef SG_MATH_EXCEPTION_CLASH
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h> // for stat()
55 # include <unistd.h> // for stat()
59 // # include <GL/glext.h>
65 #include <simgear/constants.h> // for VERSION
66 #include <simgear/debug/logstream.hxx>
67 #include <simgear/math/polar3d.hxx>
68 #include <simgear/math/sg_random.h>
69 #include <simgear/misc/sg_path.hxx>
70 #include <simgear/sky/sky.hxx>
71 #include <simgear/timing/sg_time.hxx>
72 #include <simgear/timing/lowleveltime.h>
74 #include <Include/general.hxx>
76 #include <Aircraft/aircraft.hxx>
78 #include <Autopilot/newauto.hxx>
79 #include <Cockpit/cockpit.hxx>
80 #include <Cockpit/radiostack.hxx>
81 #include <Cockpit/steam.hxx>
83 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
85 #include <GUI/sgVec3Slider.hxx>
86 // #include <Joystick/joystick.hxx>
88 #include <NetworkOLK/network.h>
90 #include <Objects/matlib.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/tilemgr.hxx>
93 #ifdef ENABLE_AUDIO_SUPPORT
94 # include <Sound/soundmgr.hxx>
95 # include <Sound/morse.hxx>
97 #include <Time/event.hxx>
98 #include <Time/fg_timer.hxx>
99 #include <Time/light.hxx>
100 #include <Time/sunpos.hxx>
101 #include <Time/tmp.hxx>
103 #include <Input/input.hxx>
105 // begin - added Venky
106 // $$$ begin - added VS Renganathan
107 #include <simgear/misc/sgstream.hxx>
108 #include <FDM/flight.hxx>
109 #include <FDM/ADA.hxx>
110 void fgLoadDCS (void);
111 void fgUpdateDCS (void);
112 ssgSelector *ship_sel=NULL;
113 // upto 32 instances of a same object can be loaded.
114 ssgTransform *ship_pos[32];
115 double obj_lat[32],obj_lon[32],obj_alt[32];
117 // $$$ end - added VS Renganathan
120 #ifndef FG_OLD_WEATHER
121 # include <WeatherCM/FGLocalWeatherDatabase.h>
123 # include <Weather/weather.hxx>
128 #include "fg_init.hxx"
130 #include "fg_props.hxx"
131 #include "globals.hxx"
132 #include "splash.hxx"
135 # include <console.h> // -dw- for command line dialog
139 // This is a record containing a bit of global housekeeping information
142 // Specify our current idle function state. This is used to run all
143 // our initializations out of the glutIdleLoop() so that we can get a
144 // splash screen up and running right away.
145 static int idle_state = 0;
146 static long global_multi_loop;
148 // attempt to avoid a large bounce at startup
149 static bool initial_freeze = true;
151 // forward declaration
152 void fgReshape( int width, int height );
154 // Global structures for the Audio library
155 #ifdef ENABLE_AUDIO_SUPPORT
156 static FGSimpleSound *s1;
157 static FGSimpleSound *s2;
162 ssgRoot *scene = NULL;
163 ssgBranch *terrain = NULL;
165 // aircraft model stuff
166 ssgSelector *acmodel_selector = NULL;
167 ssgTransform *acmodel_pos = NULL;
168 ssgSelector *prop_selector = NULL;
169 ssgSelector *flaps_selector = NULL;
170 int acmodel_npropsettings;
171 int acmodel_proprpms[4][2]; // different propeller settings
173 ssgRoot *lighting = NULL;
174 ssgBranch *ground = NULL;
175 ssgBranch *airport = NULL;
177 #ifdef FG_NETWORK_OLK
178 ssgSelector *fgd_sel = NULL;
179 ssgTransform *fgd_pos = NULL;
182 // current fdm/position used for view
183 FGInterface cur_view_fdm;
189 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
191 { 1.0f, 0.0f, 0.0f, 0.0f },
192 { 0.0f, 0.0f, -1.0f, 0.0f },
193 { 0.0f, 1.0f, 0.0f, 0.0f },
194 { 0.0f, 0.0f, 0.0f, 1.0f }
197 // The following defines flightgear options. Because glutlib will also
198 // want to parse its own options, those options must not be included here
199 // or they will get parsed by the main program option parser. Hence case
200 // is significant for any option added that might be in conflict with
203 // glutlib parses for:
205 // -direct (invalid in Win32)
209 // -indirect (invalid in Win32)
212 // Note that glutlib depends upon strings while this program's
213 // option parser wants only initial characters followed by numbers
218 ssgSimpleState *default_state;
219 ssgSimpleState *hud_and_panel;
220 ssgSimpleState *menus;
222 void fgBuildRenderStates( void ) {
223 default_state = new ssgSimpleState;
224 default_state->ref();
225 default_state->disable( GL_TEXTURE_2D );
226 default_state->enable( GL_CULL_FACE );
227 default_state->enable( GL_COLOR_MATERIAL );
228 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
229 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
230 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
231 default_state->disable( GL_BLEND );
232 default_state->disable( GL_ALPHA_TEST );
233 default_state->disable( GL_LIGHTING );
235 hud_and_panel = new ssgSimpleState;
236 hud_and_panel->ref();
237 hud_and_panel->disable( GL_CULL_FACE );
238 hud_and_panel->disable( GL_TEXTURE_2D );
239 hud_and_panel->disable( GL_LIGHTING );
240 hud_and_panel->enable( GL_BLEND );
242 menus = new ssgSimpleState;
244 menus->disable( GL_CULL_FACE );
245 menus->disable( GL_TEXTURE_2D );
246 menus->enable( GL_BLEND );
249 // fgFindNode -- a function that finds a named node in an ssg graph
250 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
251 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
253 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
254 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
255 while (kid != NULL) {
256 ssgEntity *n = fgFindNode(kid, name);
260 kid = ((ssgBranch*)node)->getNextKid();
267 // fgInitVisuals() -- Initialize various GL/view parameters
268 void fgInitVisuals( void ) {
271 l = &cur_light_params;
273 #ifndef GLUT_WRONG_VERSION
274 // Go full screen if requested ...
275 if ( fgGetBool("/sim/startup/fullscreen") ) {
280 // If enabled, normal vectors specified with glNormal are scaled
281 // to unit length after transformation. See glNormal.
282 // glEnable( GL_NORMALIZE );
284 glEnable( GL_LIGHTING );
285 glEnable( GL_LIGHT0 );
286 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
289 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
290 ssgGetLight( 0 ) -> setPosition( sunpos );
292 // glFogi (GL_FOG_MODE, GL_LINEAR);
293 glFogi (GL_FOG_MODE, GL_EXP2);
294 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
295 (!fgGetBool("/sim/rendering/shading"))) {
296 // if fastest fog requested, or if flat shading force fastest
297 glHint ( GL_FOG_HINT, GL_FASTEST );
298 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
299 glHint ( GL_FOG_HINT, GL_NICEST );
301 if ( fgGetBool("/sim/rendering/wireframe") ) {
303 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
306 // This is the default anyways, but it can't hurt
307 glFrontFace ( GL_CCW );
310 // glEnable(GL_POINT_SMOOTH);
311 // glEnable(GL_LINE_SMOOTH);
312 // glEnable(GL_POLYGON_SMOOTH);
316 // For HiRes screen Dumps using Brian Pauls TR Library
317 void trRenderFrame( void ) {
319 if ( fgPanelVisible() ) {
320 GLfloat height = fgGetInt("/sim/startup/ysize");
322 (current_panel->getViewHeight() - current_panel->getYOffset())
323 * (height / 768.0) + 1;
324 glTranslatef( 0.0, view_h, 0.0 );
327 static double m_log01 = -log( 0.01 );
328 static double sqrt_m_log01 = sqrt( m_log01 );
330 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
331 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
333 fgLIGHT *l = &cur_light_params;
335 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
336 l->adj_fog_color[2], l->adj_fog_color[3]);
338 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
340 // set the opengl state to known default values
341 default_state->force();
344 double actual_visibility = thesky->get_visibility();
345 // GLfloat fog_exp_density = m_log01 / actual_visibility;
346 GLfloat fog_exp2_density = sqrt_m_log01 / actual_visibility;
347 GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
350 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
351 glFogi ( GL_FOG_MODE, GL_EXP2 );
352 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
354 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
355 // we only update GL_AMBIENT for our lights we will never get
356 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
357 // explicitely to black.
358 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
360 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
362 // texture parameters
363 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
364 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
366 // we need a white diffuse light for the phase of the moon
367 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
370 // draw the ssg scene
371 // return to the desired diffuse color
372 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
373 glEnable( GL_DEPTH_TEST );
374 ssgCullAndDraw( scene );
377 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
378 ssgCullAndDraw( lighting );
380 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
382 // need to do this here as hud_and_panel state is static to
383 // main.cxx and HUD and Panel routines have to be called with
384 // knowledge of the the TR struct < see gui.cxx::HighResDump()
385 hud_and_panel->apply();
389 // Update all Visuals (redraws anything graphics related)
390 void fgRenderFrame( void ) {
391 // Update the default (kludged) properties.
394 fgLIGHT *l = &cur_light_params;
395 static double last_visibility = -9999;
397 static GLfloat fog_exp_density;
398 static GLfloat fog_exp2_density;
399 static GLfloat fog_exp2_punch_through;
402 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
403 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
404 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
405 // GLfloat mat_shininess[] = { 10.0 };
406 GLbitfield clear_mask;
408 if ( idle_state != 1000 ) {
409 // still initializing, draw the splash screen
410 if ( fgGetBool("/sim/startup/splash-screen") ) {
414 // idle_state is now 1000 meaning we've finished all our
415 // initializations and are running the main loop, so this will
416 // now work without seg faulting the system.
418 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
419 // FG_Altitude * SG_FEET_TO_METER);
421 // this is just a temporary hack, to make me understand Pui
422 // timerText -> setLabel (ctime (&t->cur_time));
425 // calculate our current position in cartesian space
426 scenery.center = scenery.next_center;
427 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
428 // scenery.center.y(), scenery.center.z());
430 FGViewerRPH *pilot_view =
431 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
433 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
434 cur_fdm_state->get_Lat_geocentric(),
435 cur_fdm_state->get_Altitude() *
437 pilot_view->set_sea_level_radius( cur_fdm_state->
438 get_Sea_level_radius() *
440 pilot_view->set_rph( cur_fdm_state->get_Phi(),
441 cur_fdm_state->get_Theta(),
442 cur_fdm_state->get_Psi() );
444 FGViewerLookAt *chase_view =
445 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
447 sgVec3 po; // chase view pilot_offset
448 sgVec3 wup; // chase view world up
449 sgSetVec3( po, 0.0, 0.0, 100.0 );
450 sgCopyVec3( wup, pilot_view->get_world_up() );
451 sgMat4 CXFM; // chase view + pilot offset xform
453 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
454 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
456 sgVec3 npo; // new pilot offset after rotation
457 sgVec3 *pPO = PilotOffsetGet();
458 sgXformVec3( po, *pPO, pilot_view->get_UP() );
459 sgXformVec3( npo, po, CXFM );
461 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
462 cur_fdm_state->get_Lat_geocentric(),
463 cur_fdm_state->get_Altitude() *
465 chase_view->set_sea_level_radius( cur_fdm_state->
466 get_Sea_level_radius() *
468 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
469 chase_view->set_view_forward( pilot_view->get_view_pos() );
470 chase_view->set_view_up( wup );
474 sgCopyMat4( rph, pilot_view->get_VIEW() );
475 cout << "RPH Matrix = " << endl;
477 for ( i = 0; i < 4; i++ ) {
478 for ( j = 0; j < 4; j++ ) {
479 printf("%10.4f ", rph[i][j]);
485 sgCopyMat4( la, chase_view->get_VIEW() );
486 cout << "LookAt Matrix = " << endl;
487 for ( i = 0; i < 4; i++ ) {
488 for ( j = 0; j < 4; j++ ) {
489 printf("%10.4f ", la[i][j]);
496 fgReshape( fgGetInt("/sim/startup/xsize"),
497 fgGetInt("/sim/startup/ysize") );
502 if ( ! fgPanelVisible() ) {
504 (GLint)(fgGetInt("/sim/startup/xsize")),
505 (GLint)(fgGetInt("/sim/startup/ysize")) );
508 int( (current_panel->getViewHeight() -
509 current_panel->getYOffset())
510 * (fgGetInt("/sim/startup/ysize") / 768.0) );
512 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
513 (GLint)(fgGetInt("/sim/startup/xsize")),
518 // set the sun position
519 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
521 clear_mask = GL_DEPTH_BUFFER_BIT;
522 if ( fgGetBool("/sim/rendering/wireframe") ) {
523 clear_mask |= GL_COLOR_BUFFER_BIT;
526 if ( fgGetBool("/sim/rendering/skyblend") ) {
527 if ( fgGetBool("/sim/rendering/textures") ) {
528 // glClearColor(black[0], black[1], black[2], black[3]);
529 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
530 l->adj_fog_color[2], l->adj_fog_color[3]);
531 clear_mask |= GL_COLOR_BUFFER_BIT;
534 glClearColor(l->sky_color[0], l->sky_color[1],
535 l->sky_color[2], l->sky_color[3]);
536 clear_mask |= GL_COLOR_BUFFER_BIT;
538 glClear( clear_mask );
540 // Tell GL we are switching to model view parameters
542 // I really should create a derived ssg node or use a call
543 // back or something so that I can draw the sky within the
544 // ssgCullAndDraw() function, but for now I just mimic what
545 // ssg does to set up the model view matrix
546 glMatrixMode(GL_MODELVIEW);
548 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
550 // set the opengl state to known default values
551 default_state->force();
553 // update fog params if visibility has changed
554 #ifndef FG_OLD_WEATHER
555 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
557 thesky->set_visibility( current_weather.get_visibility() );
560 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
561 ( global_multi_loop *
562 fgGetInt("/sim/speed-up") ) /
563 (double)fgGetInt("/sim/model-hz") );
565 double actual_visibility = thesky->get_visibility();
566 // cout << "actual visibility = " << actual_visibility << endl;
568 if ( actual_visibility != last_visibility ) {
569 last_visibility = actual_visibility;
571 // cout << "----> updating fog params" << endl;
574 fog_exp_density = -log(0.01) / actual_visibility;
577 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
578 fog_exp2_punch_through = sqrt( -log(0.01) ) /
579 ( actual_visibility * 1.5 );
582 // Set correct opengl fog density
583 glFogf (GL_FOG_DENSITY, fog_exp2_density);
585 // update the sky dome
586 if ( fgGetBool("/sim/rendering/skyblend") ) {
587 /* cout << "thesky->repaint() sky_color = "
588 << cur_light_params.sky_color[0] << " "
589 << cur_light_params.sky_color[1] << " "
590 << cur_light_params.sky_color[2] << " "
591 << cur_light_params.sky_color[3] << endl;
593 << cur_light_params.fog_color[0] << " "
594 << cur_light_params.fog_color[1] << " "
595 << cur_light_params.fog_color[2] << " "
596 << cur_light_params.fog_color[3] << endl;
597 cout << " sun_angle = " << cur_light_params.sun_angle
598 << " moon_angle = " << cur_light_params.moon_angle
600 thesky->repaint( cur_light_params.sky_color,
601 cur_light_params.adj_fog_color,
602 cur_light_params.sun_angle,
603 cur_light_params.moon_angle,
604 globals->get_ephem()->getNumPlanets(),
605 globals->get_ephem()->getPlanets(),
606 globals->get_ephem()->getNumStars(),
607 globals->get_ephem()->getStars() );
609 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
610 << view_pos[1] << " " << view_pos[2] << endl;
611 cout << " zero_elev = " << zero_elev[0] << " "
612 << zero_elev[1] << " " << zero_elev[2]
613 << " lon = " << cur_fdm_state->get_Longitude()
614 << " lat = " << cur_fdm_state->get_Latitude() << endl;
615 cout << " sun_rot = " << cur_light_params.sun_rotation
616 << " gst = " << SGTime::cur_time_params->getGst() << endl;
617 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
618 << " sun dec = " << globals->get_ephem()->getSunDeclination()
619 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
620 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
622 thesky->reposition( globals->get_current_view()->get_view_pos(),
623 globals->get_current_view()->get_zero_elev(),
624 globals->get_current_view()->get_world_up(),
625 cur_fdm_state->get_Longitude(),
626 cur_fdm_state->get_Latitude(),
627 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
628 cur_light_params.sun_rotation,
629 globals->get_time_params()->getGst(),
630 globals->get_ephem()->getSunRightAscension(),
631 globals->get_ephem()->getSunDeclination(),
633 globals->get_ephem()->getMoonRightAscension(),
634 globals->get_ephem()->getMoonDeclination(),
638 glEnable( GL_DEPTH_TEST );
639 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
641 glFogi( GL_FOG_MODE, GL_EXP2 );
642 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
645 // set sun/lighting parameters
646 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
648 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
649 // we only update GL_AMBIENT for our lights we will never get
650 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
651 // explicitely to black.
652 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
653 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
654 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
656 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
657 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
658 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
660 // texture parameters
661 // glEnable( GL_TEXTURE_2D );
662 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
663 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
665 // glMatrixMode( GL_PROJECTION );
667 float fov = globals->get_current_view()->get_fov();
668 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
670 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
673 // SG_LOG( SG_ALL, SG_INFO, "visibility is "
674 // << current_weather.get_visibility() );
677 ssgSetNearFar( 10.0f, 120000.0f );
679 ssgSetNearFar( 0.5f, 120000.0f );
682 if ( globals->get_viewmgr()->get_current() == 0 ) {
683 // disable aircraft model
684 acmodel_selector->select(0);
686 // enable aircraft model and set up its position and orientation
687 acmodel_selector->select(1);
689 FGViewerRPH *pilot_view =
690 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
693 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
696 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
699 sgMakeRotMat4( sgROT, -90.0, ownship_up );
703 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
704 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
706 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
708 sgCopyMat4( sgTUX, sgROT );
709 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
710 sgPostMultMat4( sgTUX, sgTRANS );
713 sgSetCoord( &tuxpos, sgTUX );
714 acmodel_pos->setTransform( &tuxpos );
716 // set up moving parts
717 if (flaps_selector != NULL) {
718 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
721 if (prop_selector != NULL) {
722 int propsel_mask = 0;
723 double rpm = fgGetDouble("/engines/engine[0]/rpm");
724 for (int i = 0; i < acmodel_npropsettings; i++) {
725 if (rpm >= acmodel_proprpms[i][0] &&
726 rpm <= acmodel_proprpms[i][1]) {
727 propsel_mask |= 1 << i;
730 prop_selector->select(propsel_mask);
734 // $$$ begin - added VS Renganthan 17 Oct 2K
736 // $$$ end - added VS Renganthan 17 Oct 2K
738 # ifdef FG_NETWORK_OLK
739 if ( fgGetBool("/sim/networking/network-olk") ) {
741 other = head->next; /* put listpointer to start */
742 while ( other != tail) { /* display all except myself */
743 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
744 other->fgd_sel->select(1);
745 sgSetCoord( &fgdpos, other->sgFGD_COORD );
746 other->fgd_pos->setTransform( &fgdpos );
751 // fgd_sel->select(1);
752 // sgCopyMat4( sgTUX, current_view.sgVIEW);
754 // sgSetCoord( &fgdpos, sgFGD_VIEW );
755 // fgd_pos->setTransform( &fgdpos);
759 // position tile nodes and update range selectors
760 global_tile_mgr.prep_ssg_nodes();
762 if ( fgGetBool("/sim/rendering/skyblend") ) {
763 // draw the sky backdrop
765 // we need a white diffuse light for the phase of the moon
766 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
770 // return to the desired diffuse color
771 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
774 // draw the ssg scene
775 glEnable( GL_DEPTH_TEST );
776 ssgCullAndDraw( scene );
778 // change state for lighting here
781 // Set punch through fog density
782 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
784 ssgCullAndDraw( lighting );
786 if ( fgGetBool("/sim/rendering/skyblend") ) {
787 // draw the sky cloud layers
788 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
791 // display HUD && Panel
793 glDisable( GL_DEPTH_TEST );
794 // glDisable( GL_CULL_FACE );
795 // glDisable( GL_TEXTURE_2D );
797 // update the input subsystem
798 current_input.update();
800 // update the controls subsystem
803 hud_and_panel->apply();
806 // update the panel subsystem
807 if (current_panel != 0)
808 current_panel->update();
810 // We can do translucent menus, so why not. :-)
812 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
814 // glDisable ( GL_BLEND ) ;
816 // glEnable( GL_FOG );
823 // Update internal time dependent calculations (i.e. flight model)
824 void fgUpdateTimeDepCalcs() {
825 static bool inited = false;
827 fgLIGHT *l = &cur_light_params;
832 if ( !globals->get_freeze() && !initial_freeze ) {
833 // conceptually, this could be done for each fdm instance ...
836 cur_fdm_state->stamp();
842 long elapsed = current - cur_fdm_state->get_time_stamp();
843 cur_fdm_state->set_time_stamp( current );
844 elapsed += cur_fdm_state->get_remainder();
845 // cout << "elapsed = " << elapsed << endl;
846 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
847 multi_loop = (long)(((double)elapsed * 0.000001) /
848 cur_fdm_state->get_delta_t() );
849 cur_fdm_state->set_multi_loop( multi_loop );
850 long remainder = elapsed - (long)( (multi_loop*1000000) *
851 cur_fdm_state->get_delta_t() );
852 cur_fdm_state->set_remainder( remainder );
853 // cout << "remainder = " << remainder << endl;
855 // chop max interations to something reasonable if the sim was
856 // delayed for an excesive amount of time
857 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
858 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
859 cur_fdm_state->set_remainder( 0 );
862 // cout << "multi_loop = " << multi_loop << endl;
863 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
864 // run Autopilot system
865 current_autopilot->run();
868 cur_fdm_state->update( 1 );
870 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
872 cur_fdm_state->update( 0 );
873 FGSteam::update( 0 );
875 //if ( global_tile_mgr.queue_size() == 0 ) {
876 initial_freeze = false;
880 if ( fgGetString("/sim/view-mode") == "pilot" ) {
881 cur_view_fdm = *cur_fdm_state;
885 // update the view angle
886 FGViewer *v = globals->get_current_view();
887 for ( i = 0; i < multi_loop; i++ ) {
888 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
889 v->set_view_offset( v->get_goal_view_offset() );
892 // move current_view.view_offset towards
893 // current_view.goal_view_offset
894 if ( v->get_goal_view_offset() > v->get_view_offset() )
896 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
897 v->inc_view_offset( 0.01 );
899 v->inc_view_offset( -0.01 );
902 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
903 v->inc_view_offset( -0.01 );
905 v->inc_view_offset( 0.01 );
908 if ( v->get_view_offset() > SGD_2PI ) {
909 v->inc_view_offset( -SGD_2PI );
910 } else if ( v->get_view_offset() < 0 ) {
911 v->inc_view_offset( SGD_2PI );
916 double tmp = -(l->sun_rotation + SGD_PI)
917 - (cur_fdm_state->get_Psi() -
918 globals->get_current_view()->get_view_offset() );
919 while ( tmp < 0.0 ) {
922 while ( tmp > SGD_2PI ) {
925 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
926 FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES,
927 -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
930 // Update solar system
931 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
932 globals->get_time_params()->getLst(),
933 cur_fdm_state->get_Latitude() );
935 // Update radio stack model
936 current_radiostack->update();
940 void fgInitTimeDepCalcs( void ) {
943 // #ifdef HAVE_SETITIMER
944 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
945 // fgUpdateTimeDepCalcs );
946 // #endif HAVE_SETITIMER
950 static const double alt_adjust_ft = 3.758099;
951 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
954 // What should we do when we have nothing else to do? Let's get ready
955 // for the next move and update the display?
956 static void fgMainLoop( void ) {
957 static long remainder = 0;
959 #ifdef FANCY_FRAME_COUNTER
963 static time_t last_time = 0;
964 static int frames = 0;
965 #endif // FANCY_FRAME_COUNTER
967 SGTime *t = globals->get_time_params();
969 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
970 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
972 #ifdef FG_NETWORK_OLK
973 if ( fgGetBool("/sim/networking/network-olk") ) {
974 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
975 // printf("FGD: Netupdate\n");
976 fgd_send_com( "A", FGFS_host); // Send Mat4 data
977 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
982 #if defined( ENABLE_PLIB_JOYSTICK )
983 // Read joystick and update control settings
984 // if ( fgGetString("/sim/control-mode") == "joystick" )
988 #elif defined( ENABLE_GLUT_JOYSTICK )
989 // Glut joystick support works by feeding a joystick handler
990 // function to glut. This is taken care of once in the joystick
991 // init routine and we don't have to worry about it again.
994 #ifdef FG_OLD_WEATHER
995 current_weather.Update();
998 // Fix elevation. I'm just sticking this here for now, it should
999 // probably move eventually
1001 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1003 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1004 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1006 if ( scenery.cur_elev > -9990 ) {
1007 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1008 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
1009 // now set aircraft altitude above ground
1010 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1011 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1012 scenery.cur_elev + alt_adjust_m - 3.0,
1013 scenery.cur_elev + alt_adjust_m );
1014 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
1015 scenery.cur_elev + alt_adjust_m );
1017 SG_LOG( SG_ALL, SG_DEBUG,
1018 "<*> resetting altitude to "
1019 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1024 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1026 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1027 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1029 // cout << "Warp = " << globals->get_warp() << endl;
1032 if ( globals->get_warp_delta() != 0 ) {
1033 globals->inc_warp( globals->get_warp_delta() );
1036 t->update( cur_fdm_state->get_Longitude(),
1037 cur_fdm_state->get_Latitude(),
1038 globals->get_warp() );
1040 if ( globals->get_warp_delta() != 0 ) {
1041 fgUpdateSkyAndLightingParams();
1044 // update magvar model
1045 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1046 cur_fdm_state->get_Latitude(),
1047 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1048 globals->get_time_params()->getJD() );
1050 // Get elapsed time (in usec) for this past frame
1051 elapsed = fgGetTimeInterval();
1052 SG_LOG( SG_ALL, SG_DEBUG,
1053 "Elapsed time interval is = " << elapsed
1054 << ", previous remainder is = " << remainder );
1056 // Calculate frame rate average
1057 #ifdef FANCY_FRAME_COUNTER
1058 /* old fps calculation */
1059 if ( elapsed > 0 ) {
1062 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1063 tmp = general.get_frame(i);
1065 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1066 general.set_frame(i+1,tmp);
1068 tmp = 1000000.0 / (float)elapsed;
1069 general.set_frame(0,tmp);
1070 // printf("frame[0] = %.2f\n", general.frames[0]);
1072 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1073 // printf("ave = %.2f\n", general.frame_rate);
1076 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1077 general.set_frame_rate( frames );
1078 SG_LOG( SG_ALL, SG_DEBUG,
1079 "--> Frame rate is = " << general.get_frame_rate() );
1082 last_time = t->get_cur_time();
1088 // Calculate model iterations needed for next frame
1089 elapsed += remainder;
1091 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1092 fgGetInt("/sim/model-hz"));
1093 remainder = elapsed - ( (global_multi_loop*1000000) /
1094 fgGetInt("/sim/model-hz") );
1095 SG_LOG( SG_ALL, SG_DEBUG,
1096 "Model iterations needed = " << global_multi_loop
1097 << ", new remainder = " << remainder );
1099 // chop max interations to something reasonable if the sim was
1100 // delayed for an excesive amount of time
1101 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1102 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1107 if ( global_multi_loop > 0 ) {
1108 fgUpdateTimeDepCalcs();
1110 SG_LOG( SG_ALL, SG_DEBUG,
1111 "Elapsed time is zero ... we're zinging" );
1114 #if ! defined( macintosh )
1115 // Do any I/O channel work that might need to be done
1119 // see if we need to load any new scenery tiles
1120 global_tile_mgr.update( cur_fdm_state->get_Longitude()
1121 * SGD_RADIANS_TO_DEGREES,
1122 cur_fdm_state->get_Latitude()
1123 * SGD_RADIANS_TO_DEGREES );
1125 // see if we need to load any deferred-load textures
1126 material_lib.load_next_deferred();
1128 // Process/manage pending events
1129 global_events.Process();
1131 // Run audio scheduler
1132 #ifdef ENABLE_AUDIO_SUPPORT
1133 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1134 if ( fgGetString("/sim/aircraft") == "c172" ) {
1135 // pitch corresponds to rpm
1136 // volume corresponds to manifold pressure
1138 // cout << "AUDIO working = "
1139 // << globals->get_soundmgr()->is_working() << endl;
1142 if ( cur_fdm_state->get_engine(0) != NULL ) {
1143 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1147 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1150 double pitch = 0.3 + rpm_factor * 3.0;
1152 // don't run at absurdly slow rates -- not realistic
1153 // and sounds bad to boot. :-)
1154 if (pitch < 0.7) { pitch = 0.7; }
1155 if (pitch > 5.0) { pitch = 5.0; }
1158 if ( cur_fdm_state->get_engine(0) != NULL ) {
1160 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1165 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1168 double volume = 0.15 + mp_factor / 2.0;
1170 if ( volume < 0.15 ) { volume = 0.15; }
1171 if ( volume > 0.5 ) { volume = 0.5; }
1172 // cout << "volume = " << volume << endl;
1174 s1->set_pitch( pitch );
1175 s1->set_volume( volume );
1177 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1178 s1->set_pitch( param );
1179 s1->set_volume( param );
1182 globals->get_soundmgr()->update();
1189 SG_LOG( SG_ALL, SG_DEBUG, "" );
1193 // This is the top level master main function that is registered as
1194 // our idle funciton
1197 // The first few passes take care of initialization things (a couple
1198 // per pass) and once everything has been initialized fgMainLoop from
1201 static void fgIdleFunction ( void ) {
1202 // printf("idle state == %d\n", idle_state);
1204 if ( idle_state == 0 ) {
1205 // Initialize the splash screen right away
1206 if ( fgGetBool("/sim/startup/splash-screen") ) {
1211 } else if ( idle_state == 1 ) {
1212 // Initialize audio support
1213 #ifdef ENABLE_AUDIO_SUPPORT
1215 // Start the intro music
1217 if ( fgGetBool("/sim/startup/intro-music") ) {
1218 SGPath mp3file( globals->get_fg_root() );
1219 mp3file.append( "Sounds/intro.mp3" );
1221 SG_LOG( SG_GENERAL, SG_INFO,
1222 "Starting intro music: " << mp3file.str() );
1224 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1225 system ( command.c_str() );
1229 FGSoundMgr *soundmgr = new FGSoundMgr;
1230 globals->set_soundmgr( soundmgr );
1232 if ( fgGetBool("/sim/sound") ) {
1233 globals->get_soundmgr()->init();
1235 s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1236 "Sounds/wasp.wav") );
1237 globals->get_soundmgr()->add( s1, "engine loop" );
1238 globals->get_soundmgr()->play_looped( "engine loop" );
1239 SG_LOG( SG_GENERAL, SG_INFO,
1240 "Rate = " << s1->get_sample()->getRate()
1241 << " Bps = " << s1->get_sample()->getBps()
1242 << " Stereo = " << s1->get_sample()->getStereo() );
1244 // s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1245 // s2->set_volume( 0.3 );
1246 // globals->get_soundmgr()->add( s2, "flaps" );
1251 } else if ( idle_state == 2 ) {
1252 // These are a few miscellaneous things that aren't really
1253 // "subsystems" but still need to be initialized.
1256 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1257 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1262 } else if ( idle_state == 3 ) {
1263 // This is the top level init routine which calls all the
1264 // other subsystem initialization routines. If you are adding
1265 // a subsystem to flightgear, its initialization call should
1266 // located in this routine.
1267 if( !fgInitSubsystems()) {
1268 SG_LOG( SG_GENERAL, SG_ALERT,
1269 "Subsystem initializations failed ..." );
1274 } else if ( idle_state == 4 ) {
1275 // setup OpenGL view parameters
1279 } else if ( idle_state == 5 ) {
1282 } else if ( idle_state == 6 ) {
1286 cout << "Panel visible = " << fgPanelVisible() << endl;
1287 fgReshape( fgGetInt("/sim/startup/xsize"),
1288 fgGetInt("/sim/startup/ysize") );
1291 if ( idle_state == 1000 ) {
1292 // We've finished all our initialization steps, from now on we
1293 // run the main loop.
1297 if ( fgGetBool("/sim/startup/splash-screen") ) {
1298 fgSplashUpdate(0.0);
1303 // options.cxx needs to see this for toggle_panel()
1304 // Handle new window size or exposure
1305 void fgReshape( int width, int height ) {
1307 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1308 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1309 globals->get_viewmgr()->get_view(i)->
1310 set_win_ratio( (float)height / (float)width );
1313 int((current_panel->getViewHeight() -
1314 current_panel->getYOffset())
1315 * (height / 768.0)) + 1;
1316 globals->get_viewmgr()->get_view(i)->
1317 set_win_ratio( (float)view_h / (float)width );
1321 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1322 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1325 int((current_panel->getViewHeight() - current_panel->getYOffset())
1326 * (height / 768.0)) + 1;
1327 glViewport(0, (GLint)(height - view_h),
1328 (GLint)(width), (GLint)(view_h) );
1331 fgSetInt("/sim/startup/xsize", width);
1332 fgSetInt("/sim/startup/ysize", height);
1334 float fov = globals->get_current_view()->get_fov();
1335 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1341 // Initialize GLUT and define a main window
1342 int fgGlutInit( int *argc, char **argv ) {
1344 #if !defined( macintosh )
1345 // GLUT will extract all glut specific options so later on we only
1346 // need wory about our own.
1347 glutInit(argc, argv);
1350 // Define Display Parameters
1351 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1353 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1354 fgGetInt("/sim/startup/xsize") << "x"
1355 << fgGetInt("/sim/startup/ysize") );
1357 // Define initial window size
1358 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1359 fgGetInt("/sim/startup/ysize") );
1361 // Initialize windows
1362 if ( !fgGetBool("/sim/startup/game-mode")) {
1363 // Open the regular window
1364 glutCreateWindow("FlightGear");
1365 #ifndef GLUT_WRONG_VERSION
1367 // Open the cool new 'game mode' window
1368 char game_mode_str[256];
1369 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1370 fgGetInt("/sim/startup/xsize"),
1371 fgGetInt("/sim/startup/ysize"),
1372 fgGetInt("/sim/rendering/bits-per-pixel"));
1374 SG_LOG( SG_GENERAL, SG_INFO,
1375 "game mode params = " << game_mode_str );
1376 glutGameModeString( game_mode_str );
1377 glutEnterGameMode();
1381 // This seems to be the absolute earliest in the init sequence
1382 // that these calls will return valid info. Too bad it's after
1383 // we've already created and sized out window. :-(
1384 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1385 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1386 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1387 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1390 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1391 general.set_glMaxTexSize( tmp );
1392 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1394 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1395 general.set_glDepthBits( tmp );
1396 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1402 // Initialize GLUT event handlers
1403 int fgGlutInitEvents( void ) {
1404 // call fgReshape() on window resizes
1405 glutReshapeFunc( fgReshape );
1407 // call GLUTkey() on keyboard event
1408 glutKeyboardFunc(GLUTkey);
1409 glutKeyboardUpFunc(GLUTkeyup);
1410 glutSpecialFunc(GLUTspecialkey);
1411 glutSpecialUpFunc(GLUTspecialkeyup);
1413 // call guiMouseFunc() whenever our little rodent is used
1414 glutMouseFunc ( guiMouseFunc );
1415 glutMotionFunc (guiMotionFunc );
1416 glutPassiveMotionFunc (guiMotionFunc );
1418 // call fgMainLoop() whenever there is
1419 // nothing else to do
1420 glutIdleFunc( fgIdleFunction );
1423 glutDisplayFunc( fgRenderFrame );
1430 int main( int argc, char **argv ) {
1432 #if defined( macintosh )
1433 freopen ("stdout.txt", "w", stdout );
1434 freopen ("stderr.txt", "w", stderr );
1435 argc = ccommand( &argv );
1439 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1442 // set default log levels
1443 sglog().setLogLevels( SG_ALL, SG_INFO );
1446 #ifdef FLIGHTGEAR_VERSION
1447 version = FLIGHTGEAR_VERSION;
1449 version = "unknown version";
1451 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1452 << version << endl );
1454 // Allocate global data structures. This needs to happen before
1455 // we parse command line options
1457 globals = new FGGlobals;
1459 // seed the random number generater
1462 SGRoute *route = new SGRoute;
1463 globals->set_route( route );
1465 FGViewMgr *viewmgr = new FGViewMgr;
1466 globals->set_viewmgr( viewmgr );
1468 FGViewerRPH *pv = new FGViewerRPH;
1469 globals->get_viewmgr()->add_view( pv );
1471 FGViewerLookAt *chase = new FGViewerLookAt;
1472 globals->get_viewmgr()->add_view( chase );
1474 string_list *col = new string_list;
1475 globals->set_channel_options_list( col );
1477 // set current view to 0 (first) which is our main pilot view
1478 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1480 // Scan the config file(s) and command line options to see if
1481 // fg_root was specified (ignore all other options for now)
1482 fgInitFGRoot(argc, argv);
1484 // Check for the correct base package version
1485 string base_version = fgBasePackageVersion();
1486 if ( !(base_version == "0.7.9") ) {
1487 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1488 << "Found version " << base_version );
1489 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1493 // Initialize the Aircraft directory to "" (UIUC)
1496 // Load the configuration parameters
1497 if ( !fgInitConfig(argc, argv) ) {
1498 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1502 // Initialize the Window/Graphics environment.
1503 if( !fgGlutInit(&argc, argv) ) {
1504 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1508 // Initialize the various GLUT Event Handlers.
1509 if( !fgGlutInitEvents() ) {
1510 SG_LOG( SG_GENERAL, SG_ALERT,
1511 "GLUT event handler initialization failed ..." );
1515 // Initialize ssg (from plib). Needs to come before we do any
1516 // other ssg stuff, but after opengl/glut has been initialized.
1519 // Initialize the user interface (we need to do this before
1520 // passing off control to glut and before fgInitGeneral to get our
1524 #ifdef GL_EXT_texture_lod_bias
1525 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1529 #ifdef GL_EXT_texture_filter_anisotropic
1530 float max_anisotropy;
1531 glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1532 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1534 cout << "Max anisotropy = " << max_anisotropy << endl;
1538 // set current_options lon/lat if an airport id is specified
1539 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1540 if ( fgGetString("/sim/startup/airport-id").length() ) {
1541 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1542 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1543 fgGetDouble("/orientation/heading-deg") );
1547 SGPath zone( globals->get_fg_root() );
1548 zone.append( "Timezone" );
1549 SGTime *t = new SGTime( fgGetDouble("/position/longitude-deg") * SGD_DEGREES_TO_RADIANS,
1550 fgGetDouble("/position/latitude-deg") * SGD_DEGREES_TO_RADIANS,
1553 // Handle potential user specified time offsets
1554 time_t cur_time = t->get_cur_time();
1555 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1556 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1557 time_t aircraftLocalTime =
1558 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1560 // Okay, we now have six possible scenarios
1561 int offset = fgGetInt("/sim/startup/time-offset");
1562 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1563 if (offset_type == "system-offset") {
1564 globals->set_warp( offset );
1565 } else if (offset_type == "gmt-offset") {
1566 globals->set_warp( offset - (currGMT - systemLocalTime) );
1567 } else if (offset_type == "latitude-offset") {
1568 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1569 } else if (offset_type == "system") {
1570 globals->set_warp( offset - cur_time );
1571 } else if (offset_type == "gmt") {
1572 globals->set_warp( offset - currGMT );
1573 } else if (offset_type == "latitude") {
1574 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1577 SG_LOG( SG_GENERAL, SG_ALERT,
1578 "Unsupported offset type " << offset_type );
1582 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1583 << globals->get_warp() );
1585 globals->set_warp_delta( 0 );
1587 t->update( 0.0, 0.0, globals->get_warp() );
1589 globals->set_time_params( t );
1591 // Do some quick general initializations
1592 if( !fgInitGeneral()) {
1593 SG_LOG( SG_GENERAL, SG_ALERT,
1594 "General initializations failed ..." );
1598 SGPath modelpath( globals->get_fg_root() );
1599 ssgModelPath( (char *)modelpath.c_str() );
1602 scene = new ssgRoot;
1603 scene->setName( "Scene" );
1605 lighting = new ssgRoot;
1606 lighting->setName( "Lighting" );
1608 // Initialize the sky
1609 SGPath ephem_data_path( globals->get_fg_root() );
1610 ephem_data_path.append( "Astro" );
1611 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1612 ephem->update( globals->get_time_params()->getMjd(),
1613 globals->get_time_params()->getLst(),
1615 globals->set_ephem( ephem );
1619 SGPath sky_tex_path( globals->get_fg_root() );
1620 sky_tex_path.append( "Textures" );
1621 sky_tex_path.append( "Sky" );
1622 thesky->texture_path( sky_tex_path.str() );
1624 thesky->build( 550.0, 550.0,
1625 globals->get_ephem()->getNumPlanets(),
1626 globals->get_ephem()->getPlanets(), 60000.0,
1627 globals->get_ephem()->getNumStars(),
1628 globals->get_ephem()->getStars(), 60000.0 );
1630 if ( fgGetBool("/environment/clouds/status") ) {
1631 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1632 // SG_CLOUD_OVERCAST );
1633 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1634 SG_CLOUD_MOSTLY_CLOUDY );
1635 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1636 // SG_CLOUD_MOSTLY_SUNNY );
1637 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1641 // Initialize MagVar model
1642 SGMagVar *magvar = new SGMagVar();
1643 globals->set_mag( magvar );
1646 terrain = new ssgBranch;
1647 terrain->setName( "Terrain" );
1648 scene->addKid( terrain );
1651 ground = new ssgBranch;
1652 ground->setName( "Ground Lighting" );
1653 lighting->addKid( ground );
1655 airport = new ssgBranch;
1656 airport->setName( "Airport Lighting" );
1657 lighting->addKid( airport );
1659 // temporary visible aircraft "own ship"
1660 acmodel_selector = new ssgSelector;
1661 acmodel_pos = new ssgTransform;
1663 // Get the model location, and load textures from the same
1664 // directory. Use an absolute path for the model to avoid
1665 // incompatibilities in different versions of PLIB.
1666 string acmodel_path =
1667 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1668 SGPath full_model = globals->get_fg_root();
1669 full_model.append(acmodel_path);
1671 #if !defined( PLIB_1_2_X )
1672 // this should be redundant ... but it breaks for relative paths
1673 // ssgModelPath( (char *)full_model.dir().c_str() );
1676 ssgTexturePath( (char *)full_model.dir().c_str() );
1677 ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1678 if( !acmodel_obj ) {
1679 // fall back to default
1680 acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1681 if( !acmodel_obj ) {
1682 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1687 // find moving parts (if this is an MDL model)
1688 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1689 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1691 acmodel_npropsettings = 0;
1692 if (prop_selector != NULL) {
1693 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1694 kid = prop_selector->getNextKid()) {
1695 int prop_low, prop_high;
1696 if ( sscanf(kid->getName(), "PROP_%d_%d",
1697 &prop_low, &prop_high) == 2 ) {
1698 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1699 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1700 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1701 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1702 acmodel_npropsettings++;
1704 SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1710 // align the model properly for FGFS
1711 ssgTransform *acmodel_align = new ssgTransform;
1712 acmodel_align->addKid(acmodel_obj);
1716 float h_rot = fgGetFloat("/sim/model/heading-offset-deg", 0.0);
1717 float p_rot = fgGetFloat("/sim/model/roll-offset-deg", 0.0);
1718 float r_rot = fgGetFloat("/sim/model/pitch-offset-deg", 0.0);
1719 float x_off = fgGetFloat("/sim/model/x-offset-m", 0.0);
1720 float y_off = fgGetFloat("/sim/model/y-offset-m", 0.0);
1721 float z_off = fgGetFloat("/sim/model/z-offset-m", 0.0);
1722 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1723 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1724 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1725 acmodel_align->setTransform(res_matrix);
1727 acmodel_pos->addKid( acmodel_align );
1728 acmodel_selector->addKid( acmodel_pos );
1729 //ssgFlatten( acmodel_obj );
1730 //ssgStripify( acmodel_selector );
1731 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1732 scene->addKid( acmodel_selector );
1734 // $$$ begin - added VS Renganthan 17 Oct 2K
1736 // $$$ end - added VS Renganthan 17 Oct 2K
1738 #ifdef FG_NETWORK_OLK
1739 // Do the network intialization
1740 if ( fgGetBool("/sim/networking/network-olk") ) {
1741 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1745 // build our custom render states
1746 fgBuildRenderStates();
1748 // pass control off to the master GLUT event handler
1751 // we never actually get here ... but to avoid compiler warnings,
1757 // $$$ end - added VS Renganathan, 15 Oct 2K
1758 // - added Venky , 12 Nov 2K
1760 void fgLoadDCS(void) {
1762 ssgEntity *ship_obj = NULL;
1765 char obj_filename[25];
1767 for ( int k = 0; k < 32; k++ ) {
1771 SGPath tile_path( globals->get_fg_root());
1772 tile_path.append( "Scenery" );
1773 tile_path.append( "Objects.txt" );
1774 sg_gzifstream in( tile_path.str() );
1775 if ( ! in.is_open() ) {
1776 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1779 SGPath modelpath( globals->get_fg_root() );
1780 modelpath.append( "Models" );
1781 modelpath.append( "Geometry" );
1783 SGPath texturepath( globals->get_fg_root() );
1784 texturepath.append( "Models" );
1785 texturepath.append( "Textures" );
1787 ssgModelPath( (char *)modelpath.c_str() );
1788 ssgTexturePath( (char *)texturepath.c_str() );
1790 ship_sel = new ssgSelector;
1793 while ( ! in.eof() ) {
1795 if ( in.get( c ) && c == '#' ) {
1799 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1800 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1801 int chj=getchar();*/
1803 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1804 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1806 ship_pos[objc] = new ssgTransform;
1808 // type "repeat" in objects.txt to load one more
1809 // instance of the last object.
1811 if ( strcmp(obj_filename,"repeat") != 0) {
1812 ship_obj = ssgLoadOBJ( obj_filename );
1815 if ( ship_obj != NULL ) {
1816 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1817 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1819 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1825 if (in.eof()) break;
1829 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1831 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1832 scene->addKid( ship_sel ); //add selector node to root node
1839 void fgUpdateDCS (void) {
1841 // double eye_lat,eye_lon,eye_alt;
1842 // static double obj_head;
1843 double sl_radius,obj_latgc;
1844 // float nresultmat[4][4];
1845 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1848 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1849 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1851 // Deck should be the first object in objects.txt in case of fdm=ada
1853 if (fgGetString("/sim/flight-model") == "ada") {
1854 obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1855 obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1856 obj_alt[0] = fdm->get_aux7();
1859 for ( int m = 0; m < objc; m++ ) {
1860 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1863 //Geodetic to Geocentric angles for rotation
1864 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1866 //moving object gbs-posn in cartesian coords
1867 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1868 Point3D obj_pos = sgGeodToCart( obj_posn );
1870 // Translate moving object w.r.t eye
1871 Point3D Objtrans = obj_pos-scenery.center;
1876 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1879 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1881 sgVec3 ship_fwd,ship_rt,ship_up;
1882 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1883 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1884 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1886 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1887 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1888 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1889 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1892 sgCopyMat4( sgTUX, sgROT_hdg );
1893 sgPostMultMat4( sgTUX, sgROT_lat );
1894 sgPostMultMat4( sgTUX, sgROT_lon );
1895 sgPostMultMat4( sgTUX, sgTRANS );
1898 sgSetCoord(&shippos, sgTUX );
1899 ship_pos[m]->setTransform( &shippos );
1901 if ( ship_sel != NULL ) {
1902 ship_sel->select(0xFFFFFFFF);
1906 // $$$ end - added VS Renganathan, 15 Oct 2K
1907 // added Venky , 12 Nov 2K