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 #ifdef FG_MATH_EXCEPTION_CLASH
38 #include <simgear/xgl/xgl.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
59 #ifdef ENABLE_AUDIO_SUPPORT
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>
73 #include <Include/general.hxx>
75 #include <Aircraft/aircraft.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
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>
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];
108 // $$$ end - added VS Renganathan
111 #ifndef FG_OLD_WEATHER
112 # include <WeatherCM/FGLocalWeatherDatabase.h>
114 # include <Weather/weather.hxx>
120 #include "fg_init.hxx"
122 #include "globals.hxx"
123 #include "keyboard.hxx"
124 #include "splash.hxx"
127 # include <console.h> // -dw- for command line dialog
131 // This is a record containing a bit of global housekeeping information
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;
140 // attempt to avoid a large bounce at startup
141 static bool initial_freeze = true;
143 // forward declaration
144 void fgReshape( int width, int height );
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;
158 ssgRoot *scene = NULL;
159 ssgBranch *terrain = NULL;
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
169 ssgRoot *lighting = NULL;
170 ssgBranch *ground = NULL;
171 ssgBranch *airport = NULL;
173 #ifdef FG_NETWORK_OLK
174 ssgSelector *fgd_sel = NULL;
175 ssgTransform *fgd_pos = NULL;
178 // current fdm/position used for view
179 FGInterface cur_view_fdm;
185 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
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 }
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
199 // glutlib parses for:
201 // -direct (invalid in Win32)
205 // -indirect (invalid in Win32)
208 // Note that glutlib depends upon strings while this program's
209 // option parser wants only initial characters followed by numbers
214 ssgSimpleState *default_state;
215 ssgSimpleState *hud_and_panel;
216 ssgSimpleState *menus;
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 );
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 );
238 menus = new ssgSimpleState;
240 menus->disable( GL_CULL_FACE );
241 menus->disable( GL_TEXTURE_2D );
242 menus->enable( GL_BLEND );
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 ) {
249 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
250 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
251 while (kid != NULL) {
252 ssgEntity *n = fgFindNode(kid, name);
256 kid = ((ssgBranch*)node)->getNextKid();
263 // fgInitVisuals() -- Initialize various GL/view parameters
264 void fgInitVisuals( void ) {
267 l = &cur_light_params;
269 #ifndef GLUT_WRONG_VERSION
270 // Go full screen if requested ...
271 if ( fgGetBool("/sim/startup/fullscreen") ) {
276 // If enabled, normal vectors specified with glNormal are scaled
277 // to unit length after transformation. See glNormal.
278 // glEnable( GL_NORMALIZE );
280 glEnable( GL_LIGHTING );
281 glEnable( GL_LIGHT0 );
282 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
285 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
286 ssgGetLight( 0 ) -> setPosition( sunpos );
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 );
297 if ( fgGetBool("/sim/rendering/wireframe") ) {
299 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
302 // This is the default anyways, but it can't hurt
303 glFrontFace ( GL_CCW );
306 // glEnable(GL_POINT_SMOOTH);
307 // glEnable(GL_LINE_SMOOTH);
308 // glEnable(GL_POLYGON_SMOOTH);
312 // Update all Visuals (redraws anything graphics related)
313 void fgRenderFrame( void ) {
317 fgLIGHT *l = &cur_light_params;
318 static double last_visibility = -9999;
320 static GLfloat fog_exp_density;
321 static GLfloat fog_exp2_density;
322 static GLfloat fog_exp2_punch_through;
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;
331 if ( idle_state != 1000 ) {
332 // still initializing, draw the splash screen
333 if ( fgGetBool("/sim/startup/splash-screen") ) {
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.
341 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
342 // FG_Altitude * FEET_TO_METER);
344 // this is just a temporary hack, to make me understand Pui
345 // timerText -> setLabel (ctime (&t->cur_time));
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());
353 FGViewerRPH *pilot_view =
354 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
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() *
360 pilot_view->set_sea_level_radius( cur_fdm_state->
361 get_Sea_level_radius() *
363 pilot_view->set_rph( cur_fdm_state->get_Phi(),
364 cur_fdm_state->get_Theta(),
365 cur_fdm_state->get_Psi() );
367 FGViewerLookAt *chase_view =
368 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
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
376 chase_view->get_view_offset() * RAD_TO_DEG -
377 cur_fdm_state->get_Psi() * RAD_TO_DEG,
379 sgVec3 npo; // new pilot offset after rotation
380 sgXformVec3( po, po, pilot_view->get_UP() );
381 sgXformVec3( npo, po, CXFM );
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() *
387 chase_view->set_sea_level_radius( cur_fdm_state->
388 get_Sea_level_radius() *
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 );
396 sgCopyMat4( rph, pilot_view->get_VIEW() );
397 cout << "RPH Matrix = " << endl;
399 for ( i = 0; i < 4; i++ ) {
400 for ( j = 0; j < 4; j++ ) {
401 printf("%10.4f ", rph[i][j]);
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]);
418 fgReshape( fgGetInt("/sim/startup/xsize"),
419 fgGetInt("/sim/startup/ysize") );
424 if ( ! fgPanelVisible() ) {
426 (GLint)(fgGetInt("/sim/startup/xsize")),
427 (GLint)(fgGetInt("/sim/startup/ysize")) );
430 int( (current_panel->getViewHeight() -
431 current_panel->getYOffset())
432 * (fgGetInt("/sim/startup/ysize") / 768.0) );
434 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
435 (GLint)(fgGetInt("/sim/startup/xsize")),
440 // set the sun position
441 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
443 clear_mask = GL_DEPTH_BUFFER_BIT;
444 if ( fgGetBool("/sim/rendering/wireframe") ) {
445 clear_mask |= GL_COLOR_BUFFER_BIT;
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;
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;
460 glClear( clear_mask );
462 // Tell GL we are switching to model view parameters
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);
470 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
472 // set the opengl state to known default values
473 default_state->force();
475 // update fog params if visibility has changed
476 #ifndef FG_OLD_WEATHER
477 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
479 thesky->set_visibility( current_weather.get_visibility() );
482 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
484 ( global_multi_loop *
485 fgGetInt("/sim/speed-up") ) /
486 (double)fgGetInt("/sim/model-hz") );
488 double actual_visibility = thesky->get_visibility();
489 // cout << "actual visibility = " << actual_visibility << endl;
491 if ( actual_visibility != last_visibility ) {
492 last_visibility = actual_visibility;
494 // cout << "----> updating fog params" << endl;
497 fog_exp_density = -log(0.01 / actual_visibility);
500 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
501 fog_exp2_punch_through = sqrt( -log(0.01) ) /
502 ( actual_visibility * 1.5 );
505 // Set correct opengl fog density
506 glFogf (GL_FOG_DENSITY, fog_exp2_density);
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;
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
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() );
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; */
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(),
556 globals->get_ephem()->getMoonRightAscension(),
557 globals->get_ephem()->getMoonDeclination(),
561 glEnable( GL_DEPTH_TEST );
562 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
564 glFogi( GL_FOG_MODE, GL_EXP2 );
565 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
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 );
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);
586 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
587 ssgGetLight( 0 ) -> setPosition( sunpos );
589 // glMatrixMode( GL_PROJECTION );
591 float fov = globals->get_current_view()->get_fov();
592 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
594 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
597 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
598 // << current_weather.get_visibility() );
601 ssgSetNearFar( 10.0f, 120000.0f );
603 ssgSetNearFar( 0.5f, 120000.0f );
606 if ( globals->get_viewmgr()->get_current() == 0 ) {
607 // disable aircraft model
608 acmodel_selector->select(0);
610 // enable aircraft model and set up its position and orientation
611 acmodel_selector->select(1);
613 FGViewerRPH *pilot_view =
614 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
617 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
620 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
623 sgMakeRotMat4( sgROT, -90.0, ownship_up );
627 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
628 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
630 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
632 sgCopyMat4( sgTUX, sgROT );
633 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
634 sgPostMultMat4( sgTUX, sgTRANS );
637 sgSetCoord( &tuxpos, sgTUX );
638 acmodel_pos->setTransform( &tuxpos );
640 // set up moving parts
641 if (flaps_selector != NULL) {
642 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
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;
653 prop_selector->select(propsel_mask);
657 // $$$ begin - added VS Renganthan 17 Oct 2K
659 // $$$ end - added VS Renganthan 17 Oct 2K
661 # ifdef FG_NETWORK_OLK
662 if ( fgGetBool("/sim/networking/network-olk") ) {
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 );
674 // fgd_sel->select(1);
675 // sgCopyMat4( sgTUX, current_view.sgVIEW);
677 // sgSetCoord( &fgdpos, sgFGD_VIEW );
678 // fgd_pos->setTransform( &fgdpos);
682 // position tile nodes and update range selectors
683 global_tile_mgr.prep_ssg_nodes();
685 // draw the sky backdrop
688 // draw the ssg scene
689 glEnable( GL_DEPTH_TEST );
690 ssgCullAndDraw( scene );
692 // change state for lighting here
695 // Set punch through fog density
696 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
698 ssgCullAndDraw( lighting );
700 // draw the sky cloud layers
701 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
703 // display HUD && Panel
705 glDisable( GL_DEPTH_TEST );
706 // glDisable( GL_CULL_FACE );
707 // glDisable( GL_TEXTURE_2D );
709 // update the controls subsystem
712 hud_and_panel->apply();
715 // update the panel subsystem
716 if (current_panel != 0)
717 current_panel->update();
719 // We can do translucent menus, so why not. :-)
721 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
723 // glDisable ( GL_BLEND ) ;
725 // glEnable( GL_FOG );
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;
738 // update the flight model
739 if ( multi_loop < 0 ) {
743 if ( !globals->get_freeze() && !initial_freeze ) {
744 // run Autopilot system
745 current_autopilot->run();
747 cur_fdm_state->update( multi_loop *
748 fgGetInt("/sim/speed-up") );
749 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
751 cur_fdm_state->update( 0 );
752 FGSteam::update( 0 );
754 if ( global_tile_mgr.queue_size() == 0 ) {
755 initial_freeze = false;
759 fdm_list.push_back( *cur_fdm_state );
760 while ( fdm_list.size() > 15 ) {
761 fdm_list.pop_front();
764 if ( fgGetString("/sim/view-mode") == "pilot" ) {
765 cur_view_fdm = *cur_fdm_state;
767 } else if ( fgGetString("/sim/view-mode") == "follow" )
769 cur_view_fdm = fdm_list.front();
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() );
779 // move current_view.view_offset towards
780 // current_view.goal_view_offset
781 if ( v->get_goal_view_offset() > v->get_view_offset() )
783 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
784 v->inc_view_offset( 0.01 );
786 v->inc_view_offset( -0.01 );
789 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
790 v->inc_view_offset( -0.01 );
792 v->inc_view_offset( 0.01 );
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 );
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 ) {
809 while ( tmp > FG_2PI ) {
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); */
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() );
822 // Update radio stack model
823 current_radiostack->update();
827 void fgInitTimeDepCalcs( void ) {
830 // #ifdef HAVE_SETITIMER
831 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
832 // fgUpdateTimeDepCalcs );
833 // #endif HAVE_SETITIMER
837 static const double alt_adjust_ft = 3.758099;
838 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
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;
846 #ifdef FANCY_FRAME_COUNTER
850 static time_t last_time = 0;
851 static int frames = 0;
852 #endif // FANCY_FRAME_COUNTER
854 SGTime *t = globals->get_time_params();
856 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
857 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
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
869 #if defined( ENABLE_PLIB_JOYSTICK )
870 // Read joystick and update control settings
871 if ( fgGetString("/sim/control-mode") == "joystick" )
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.
881 #ifdef FG_OLD_WEATHER
882 current_weather.Update();
885 // Fix elevation. I'm just sticking this here for now, it should
886 // probably move eventually
888 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
890 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
891 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
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 );
904 FG_LOG( FG_ALL, FG_DEBUG,
905 "<*> resetting altitude to "
906 << cur_fdm_state->get_Altitude() * FEET_TO_METER
911 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
913 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
914 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
917 if ( globals->get_warp_delta() != 0 ) {
918 globals->inc_warp( globals->get_warp_delta() );
921 t->update( cur_fdm_state->get_Longitude(),
922 cur_fdm_state->get_Latitude(),
923 globals->get_warp() );
925 if ( globals->get_warp_delta() != 0 ) {
926 fgUpdateSkyAndLightingParams();
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() );
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 );
941 // Calculate frame rate average
942 #ifdef FANCY_FRAME_COUNTER
943 /* old fps calculation */
947 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
948 tmp = general.get_frame(i);
950 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
951 general.set_frame(i+1,tmp);
953 tmp = 1000000.0 / (float)elapsed;
954 general.set_frame(0,tmp);
955 // printf("frame[0] = %.2f\n", general.frames[0]);
957 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
958 // printf("ave = %.2f\n", general.frame_rate);
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() );
967 last_time = t->get_cur_time();
973 // Calculate model iterations needed for next frame
974 elapsed += remainder;
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 );
985 if ( global_multi_loop > 0 ) {
986 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
988 FG_LOG( FG_ALL, FG_DEBUG,
989 "Elapsed time is zero ... we're zinging" );
992 #if ! defined( macintosh )
993 // Do any I/O channel work that might need to be done
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 );
1001 // Process/manage pending events
1002 global_events.Process();
1004 // Run audio scheduler
1005 #ifdef ENABLE_AUDIO_SUPPORT
1006 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1008 if ( fgGetString("/sim/aircraft") == "c172" ) {
1009 // pitch corresponds to rpm
1010 // volume corresponds to manifold pressure
1013 if ( cur_fdm_state->get_engine(0) != NULL ) {
1014 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1018 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1021 double pitch = 0.3 + rpm_factor * 3.0;
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;
1030 if ( cur_fdm_state->get_engine(0) != NULL ) {
1032 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
1037 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1040 double volume = mp_factor;
1042 if ( volume < 0.3 ) { volume = 0.3; }
1043 if ( volume > 2.0 ) { volume = 2.0; }
1044 // cout << "volume = " << volume << endl;
1046 pitch_envelope.setStep ( 0, 0.01, pitch );
1047 volume_envelope.setStep ( 0, 0.01, volume );
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 );
1054 audio_sched -> update();
1061 FG_LOG( FG_ALL, FG_DEBUG, "" );
1065 // This is the top level master main function that is registered as
1066 // our idle funciton
1069 // The first few passes take care of initialization things (a couple
1070 // per pass) and once everything has been initialized fgMainLoop from
1073 static void fgIdleFunction ( void ) {
1074 // printf("idle state == %d\n", idle_state);
1076 if ( idle_state == 0 ) {
1077 // Initialize the splash screen right away
1078 if ( fgGetBool("/sim/startup/splash-screen") ) {
1083 } else if ( idle_state == 1 ) {
1084 // Start the intro music
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" );
1091 string command = "(touch " + lockfile + "; mpg123 "
1092 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1094 FG_LOG( FG_GENERAL, FG_INFO,
1095 "Starting intro music: " << mp3file.str() );
1096 system ( command.c_str() );
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.
1106 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1107 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
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 ..." );
1124 } else if ( idle_state == 4 ) {
1125 // setup OpenGL view parameters
1129 } else if ( idle_state == 5 ) {
1132 } else if ( idle_state == 6 ) {
1133 // Initialize audio support
1134 #ifdef ENABLE_AUDIO_SUPPORT
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;
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 ...
1147 FG_LOG( FG_GENERAL, FG_INFO, ".");
1149 FG_LOG( FG_GENERAL, FG_INFO, "");
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 ) ;
1159 FGPath slfile( globals->get_fg_root() );
1160 slfile.append( "Sounds/wasp.wav" );
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 );
1169 if ( audio_sched->not_working() ) {
1172 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1173 volume_envelope.setStep ( 0, 0.01, 0.6 );
1175 audio_sched -> addSampleEnvelope( s1, 0, 0,
1177 SL_PITCH_ENVELOPE );
1178 audio_sched -> addSampleEnvelope( s1, 0, 1,
1180 SL_VOLUME_ENVELOPE );
1183 // strcpy(slfile, path);
1184 // strcat(slfile, "thunder.wav");
1185 // s2 -> loadFile ( slfile );
1186 // s2 -> adjustVolume(0.5);
1187 // audio_sched -> playSample ( s2 );
1194 cout << "Panel visible = " << fgPanelVisible() << endl;
1195 fgReshape( fgGetInt("/sim/startup/xsize"),
1196 fgGetInt("/sim/startup/ysize") );
1199 if ( idle_state == 1000 ) {
1200 // We've finished all our initialization steps, from now on we
1201 // run the main loop.
1205 if ( fgGetBool("/sim/startup/splash-screen") ) {
1206 fgSplashUpdate(0.0);
1211 // options.cxx needs to see this for toggle_panel()
1212 // Handle new window size or exposure
1213 void fgReshape( int width, int height ) {
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 );
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 );
1229 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1230 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
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) );
1239 fgSetInt("/sim/startup/xsize", width);
1240 fgSetInt("/sim/startup/ysize", height);
1242 float fov = globals->get_current_view()->get_fov();
1243 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1249 // Initialize GLUT and define a main window
1250 int fgGlutInit( int *argc, char **argv ) {
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);
1258 // Define Display Parameters
1259 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1261 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1262 fgGetInt("/sim/startup/xsize") << "x"
1263 << fgGetInt("/sim/startup/ysize") );
1265 // Define initial window size
1266 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1267 fgGetInt("/sim/startup/ysize") );
1269 // Initialize windows
1270 if ( !fgGetBool("/sim/startup/game-mode")) {
1271 // Open the regular window
1272 glutCreateWindow("FlightGear");
1273 #ifndef GLUT_WRONG_VERSION
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"));
1282 FG_LOG( FG_GENERAL, FG_INFO,
1283 "game mode params = " << game_mode_str );
1284 glutGameModeString( game_mode_str );
1285 glutEnterGameMode();
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() );
1298 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1299 general.set_glMaxTexSize( tmp );
1300 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1302 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1303 general.set_glDepthBits( tmp );
1304 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1310 // Initialize GLUT event handlers
1311 int fgGlutInitEvents( void ) {
1312 // call fgReshape() on window resizes
1313 glutReshapeFunc( fgReshape );
1315 // call GLUTkey() on keyboard event
1316 glutKeyboardFunc( GLUTkey );
1317 glutSpecialFunc( GLUTspecialkey );
1319 // call guiMouseFunc() whenever our little rodent is used
1320 glutMouseFunc ( guiMouseFunc );
1321 glutMotionFunc (guiMotionFunc );
1322 glutPassiveMotionFunc (guiMotionFunc );
1324 // call fgMainLoop() whenever there is
1325 // nothing else to do
1326 glutIdleFunc( fgIdleFunction );
1329 glutDisplayFunc( fgRenderFrame );
1336 int main( int argc, char **argv ) {
1338 #if defined( macintosh )
1339 freopen ("stdout.txt", "w", stdout );
1340 freopen ("stderr.txt", "w", stderr );
1341 argc = ccommand( &argv );
1345 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1348 // set default log levels
1349 fglog().setLogLevels( FG_ALL, FG_INFO );
1352 #ifdef FLIGHTGEAR_VERSION
1353 version = FLIGHTGEAR_VERSION;
1355 version = "unknown version";
1357 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1358 << version << endl );
1360 // Allocate global data structures. This needs to happen before
1361 // we parse command line options
1363 SGPropertyNode *props = new SGPropertyNode;
1364 globals = new FGGlobals;
1365 globals->set_props( props );
1367 // seed the random number generater
1370 SGRoute *route = new SGRoute;
1371 globals->set_route( route );
1373 FGViewMgr *viewmgr = new FGViewMgr;
1374 globals->set_viewmgr( viewmgr );
1376 FGViewerRPH *pv = new FGViewerRPH;
1377 globals->get_viewmgr()->add_view( pv );
1379 FGViewerLookAt *chase = new FGViewerLookAt;
1380 globals->get_viewmgr()->add_view( chase );
1382 // set current view to 0 (first) which is our main pilot view
1383 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
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);
1389 // Initialize the Aircraft directory to "" (UIUC)
1392 // Load the configuration parameters
1393 if ( !fgInitConfig(argc, argv) ) {
1394 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1398 // Initialize the Window/Graphics environment.
1399 if( !fgGlutInit(&argc, argv) ) {
1400 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1404 // Initialize the various GLUT Event Handlers.
1405 if( !fgGlutInitEvents() ) {
1406 FG_LOG( FG_GENERAL, FG_ALERT,
1407 "GLUT event handler initialization failed ..." );
1411 // Initialize ssg (from plib). Needs to come before we do any
1412 // other ssg stuff, but after opengl/glut has been initialized.
1415 // Initialize the user interface (we need to do this before
1416 // passing off control to glut and before fgInitGeneral to get our
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") );
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,
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() ) );
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) -
1459 FG_LOG( FG_GENERAL, FG_ALERT,
1460 "Unsupported offset type " << offset_type );
1464 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1465 << globals->get_warp() );
1467 globals->set_warp_delta( 0 );
1469 t->update( 0.0, 0.0, globals->get_warp() );
1471 globals->set_time_params( t );
1473 // Do some quick general initializations
1474 if( !fgInitGeneral()) {
1475 FG_LOG( FG_GENERAL, FG_ALERT,
1476 "General initializations failed ..." );
1480 FGPath modelpath( globals->get_fg_root() );
1481 ssgModelPath( (char *)modelpath.c_str() );
1484 scene = new ssgRoot;
1485 scene->setName( "Scene" );
1487 lighting = new ssgRoot;
1488 lighting->setName( "Lighting" );
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(),
1497 globals->set_ephem( ephem );
1499 FGPath sky_tex_path( globals->get_fg_root() );
1500 sky_tex_path.append( "Textures" );
1501 sky_tex_path.append( "Sky" );
1503 thesky->texture_path( sky_tex_path.str() );
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 );
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,
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 );
1522 // Initialize MagVar model
1523 SGMagVar *magvar = new SGMagVar();
1524 globals->set_mag( magvar );
1527 terrain = new ssgBranch;
1528 terrain->setName( "Terrain" );
1529 scene->addKid( terrain );
1532 ground = new ssgBranch;
1533 ground->setName( "Ground Lighting" );
1534 lighting->addKid( ground );
1536 airport = new ssgBranch;
1537 airport->setName( "Airport Lighting" );
1538 lighting->addKid( airport );
1540 // temporary visible aircraft "own ship"
1541 acmodel_selector = new ssgSelector;
1542 acmodel_pos = new ssgTransform;
1544 string acmodel_path =
1545 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1547 string full_model = globals->get_fg_root() + "/"
1549 int pos = full_model.rfind("/");
1551 FGPath texturepath( full_model.substr(0, pos) );
1552 cout << "Texture path = " << texturepath.str() << endl;
1553 ssgTexturePath( (char *)texturepath.c_str() );
1555 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
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" );
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++;
1574 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1580 // align the model properly for FGFS
1581 ssgTransform *acmodel_align = new ssgTransform;
1582 acmodel_align->addKid(acmodel_obj);
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);
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 );
1604 // $$$ begin - added VS Renganthan 17 Oct 2K
1606 // $$$ end - added VS Renganthan 17 Oct 2K
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 ) );
1615 // build our custom render states
1616 fgBuildRenderStates();
1618 // pass control off to the master GLUT event handler
1621 // we never actually get here ... but to avoid compiler warnings,
1627 // $$$ end - added VS Renganathan, 15 Oct 2K
1628 // - added Venky , 12 Nov 2K
1630 void fgLoadDCS(void) {
1632 ssgEntity *ship_obj;
1635 char obj_filename[25];
1637 for (int k=0;k<32;k++)
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() );
1650 FGPath modelpath( globals->get_fg_root() );
1651 modelpath.append( "Models" );
1652 modelpath.append( "Geometry" );
1654 FGPath texturepath( globals->get_fg_root() );
1655 texturepath.append( "Models" );
1656 texturepath.append( "Textures" );
1658 ssgModelPath( (char *)modelpath.c_str() );
1659 ssgTexturePath( (char *)texturepath.c_str() );
1661 ship_sel = new ssgSelector;
1664 while ( ! in.eof() )
1667 if ( in.get( c ) && 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();*/
1678 obj_lon[objc] *=DEG_TO_RAD;
1679 obj_lat[objc] *=DEG_TO_RAD;
1681 ship_pos[objc] = new ssgTransform;
1684 // type "repeat" in objects.txt to load one more instance of the last object.
1686 if ( strcmp(obj_filename,"repeat") != 0)
1687 ship_obj = ssgLoadOBJ( obj_filename );
1689 if ( ship_obj != NULL )
1691 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1692 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1695 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1697 if (in.eof()) break;
1702 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1703 scene->addKid( ship_sel ); //add selector node to root node
1708 void fgUpdateDCS (void) {
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;
1717 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1718 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1720 // Deck should be the first object in objects.txt in case of fdm=ada
1722 if (fgGetString("/sim/flight-model") == "ada")
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();
1729 for (int m=0; m<=objc; m++)
1731 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1734 //Geodetic to Geocentric angles for rotation
1735 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
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 );
1741 // Translate moving object w.r.t eye
1742 Point3D Objtrans = obj_pos-scenery.center;
1747 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1750 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
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
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 );
1763 sgCopyMat4( sgTUX, sgROT_hdg );
1764 sgPostMultMat4( sgTUX, sgROT_lat );
1765 sgPostMultMat4( sgTUX, sgROT_lon );
1766 sgPostMultMat4( sgTUX, sgTRANS );
1769 sgSetCoord(&shippos, sgTUX );
1770 ship_pos[m]->setTransform( &shippos );
1772 if ( ship_sel != NULL )
1773 ship_sel->select(0xFFFFFFFF);
1776 // $$$ end - added VS Renganathan, 15 Oct 2K
1777 // added Venky , 12 Nov 2K