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;
146 // forward declaration
147 void fgReshape( int width, int height );
149 // Global structures for the Audio library
150 #ifdef ENABLE_AUDIO_SUPPORT
151 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
152 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
153 slScheduler *audio_sched;
154 smMixer *audio_mixer;
161 ssgRoot *scene = NULL;
162 ssgBranch *terrain = NULL;
164 // aircraft model stuff
165 ssgSelector *acmodel_selector = NULL;
166 ssgTransform *acmodel_pos = NULL;
167 ssgSelector *prop_selector = NULL;
168 ssgSelector *flaps_selector = NULL;
169 int acmodel_npropsettings;
170 int acmodel_proprpms[4][2]; // different propeller settings
172 ssgRoot *lighting = NULL;
173 ssgBranch *ground = NULL;
174 ssgBranch *airport = NULL;
176 #ifdef FG_NETWORK_OLK
177 ssgSelector *fgd_sel = NULL;
178 ssgTransform *fgd_pos = NULL;
181 // current fdm/position used for view
182 FGInterface cur_view_fdm;
188 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
190 { 1.0f, 0.0f, 0.0f, 0.0f },
191 { 0.0f, 0.0f, -1.0f, 0.0f },
192 { 0.0f, 1.0f, 0.0f, 0.0f },
193 { 0.0f, 0.0f, 0.0f, 1.0f }
196 // The following defines flightgear options. Because glutlib will also
197 // want to parse its own options, those options must not be included here
198 // or they will get parsed by the main program option parser. Hence case
199 // is significant for any option added that might be in conflict with
202 // glutlib parses for:
204 // -direct (invalid in Win32)
208 // -indirect (invalid in Win32)
211 // Note that glutlib depends upon strings while this program's
212 // option parser wants only initial characters followed by numbers
217 ssgSimpleState *default_state;
218 ssgSimpleState *hud_and_panel;
219 ssgSimpleState *menus;
221 void fgBuildRenderStates( void ) {
222 default_state = new ssgSimpleState;
223 default_state->ref();
224 default_state->disable( GL_TEXTURE_2D );
225 default_state->enable( GL_CULL_FACE );
226 default_state->enable( GL_COLOR_MATERIAL );
227 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
228 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
229 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
230 default_state->disable( GL_BLEND );
231 default_state->disable( GL_ALPHA_TEST );
232 default_state->disable( GL_LIGHTING );
234 hud_and_panel = new ssgSimpleState;
235 hud_and_panel->ref();
236 hud_and_panel->disable( GL_CULL_FACE );
237 hud_and_panel->disable( GL_TEXTURE_2D );
238 hud_and_panel->disable( GL_LIGHTING );
239 hud_and_panel->enable( GL_BLEND );
241 menus = new ssgSimpleState;
243 menus->disable( GL_CULL_FACE );
244 menus->disable( GL_TEXTURE_2D );
245 menus->enable( GL_BLEND );
248 // fgFindNode -- a function that finds a named node in an ssg graph
249 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
250 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
252 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
253 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
254 while (kid != NULL) {
255 ssgEntity *n = fgFindNode(kid, name);
259 kid = ((ssgBranch*)node)->getNextKid();
266 // fgInitVisuals() -- Initialize various GL/view parameters
267 void fgInitVisuals( void ) {
270 l = &cur_light_params;
272 #ifndef GLUT_WRONG_VERSION
273 // Go full screen if requested ...
274 if ( fgGetBool("/sim/startup/fullscreen") ) {
279 // If enabled, normal vectors specified with glNormal are scaled
280 // to unit length after transformation. See glNormal.
281 // glEnable( GL_NORMALIZE );
283 glEnable( GL_LIGHTING );
284 glEnable( GL_LIGHT0 );
285 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
288 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
289 ssgGetLight( 0 ) -> setPosition( sunpos );
291 // glFogi (GL_FOG_MODE, GL_LINEAR);
292 glFogi (GL_FOG_MODE, GL_EXP2);
293 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
294 (!fgGetBool("/sim/rendering/shading"))) {
295 // if fastest fog requested, or if flat shading force fastest
296 glHint ( GL_FOG_HINT, GL_FASTEST );
297 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
298 glHint ( GL_FOG_HINT, GL_NICEST );
300 if ( fgGetBool("/sim/rendering/wireframe") ) {
302 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
305 // This is the default anyways, but it can't hurt
306 glFrontFace ( GL_CCW );
309 // glEnable(GL_POINT_SMOOTH);
310 // glEnable(GL_LINE_SMOOTH);
311 // glEnable(GL_POLYGON_SMOOTH);
315 // Update all Visuals (redraws anything graphics related)
316 void fgRenderFrame( void ) {
320 fgLIGHT *l = &cur_light_params;
321 static double last_visibility = -9999;
323 static GLfloat fog_exp_density;
324 static GLfloat fog_exp2_density;
325 static GLfloat fog_exp2_punch_through;
328 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
329 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
330 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
331 // GLfloat mat_shininess[] = { 10.0 };
332 GLbitfield clear_mask;
334 if ( idle_state != 1000 ) {
335 // still initializing, draw the splash screen
336 if ( fgGetBool("/sim/startup/splash-screen") ) {
340 // idle_state is now 1000 meaning we've finished all our
341 // initializations and are running the main loop, so this will
342 // now work without seg faulting the system.
344 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
345 // FG_Altitude * FEET_TO_METER);
347 // this is just a temporary hack, to make me understand Pui
348 // timerText -> setLabel (ctime (&t->cur_time));
351 // calculate our current position in cartesian space
352 scenery.center = scenery.next_center;
353 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
354 // scenery.center.y(), scenery.center.z());
356 FGViewerRPH *pilot_view =
357 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
359 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
360 cur_fdm_state->get_Lat_geocentric(),
361 cur_fdm_state->get_Altitude() *
363 pilot_view->set_sea_level_radius( cur_fdm_state->
364 get_Sea_level_radius() *
366 pilot_view->set_rph( cur_fdm_state->get_Phi(),
367 cur_fdm_state->get_Theta(),
368 cur_fdm_state->get_Psi() );
370 FGViewerLookAt *chase_view =
371 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
373 sgVec3 po; // chase view pilot_offset
374 sgVec3 wup; // chase view world up
375 sgSetVec3( po, 0.0, 0.0, 50.0 );
376 sgCopyVec3( wup, pilot_view->get_world_up() );
377 sgMat4 CXFM; // chase view + pilot offset xform
379 chase_view->get_view_offset() * RAD_TO_DEG -
380 cur_fdm_state->get_Psi() * RAD_TO_DEG,
382 sgVec3 npo; // new pilot offset after rotation
383 sgXformVec3( po, po, pilot_view->get_UP() );
384 sgXformVec3( npo, po, CXFM );
386 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
387 cur_fdm_state->get_Lat_geocentric(),
388 cur_fdm_state->get_Altitude() *
390 chase_view->set_sea_level_radius( cur_fdm_state->
391 get_Sea_level_radius() *
393 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
394 chase_view->set_view_forward( pilot_view->get_view_pos() );
395 chase_view->set_view_up( wup );
399 sgCopyMat4( rph, pilot_view->get_VIEW() );
400 cout << "RPH Matrix = " << endl;
402 for ( i = 0; i < 4; i++ ) {
403 for ( j = 0; j < 4; j++ ) {
404 printf("%10.4f ", rph[i][j]);
410 sgCopyMat4( la, chase_view->get_VIEW() );
411 cout << "LookAt Matrix = " << endl;
412 for ( i = 0; i < 4; i++ ) {
413 for ( j = 0; j < 4; j++ ) {
414 printf("%10.4f ", la[i][j]);
421 fgReshape( fgGetInt("/sim/startup/xsize"),
422 fgGetInt("/sim/startup/ysize") );
427 if ( ! fgPanelVisible() ) {
429 (GLint)(fgGetInt("/sim/startup/xsize")),
430 (GLint)(fgGetInt("/sim/startup/ysize")) );
433 int( (current_panel->getViewHeight() -
434 current_panel->getYOffset())
435 * (fgGetInt("/sim/startup/ysize") / 768.0) );
437 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
438 (GLint)(fgGetInt("/sim/startup/xsize")),
443 // set the sun position
444 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
446 clear_mask = GL_DEPTH_BUFFER_BIT;
447 if ( fgGetBool("/sim/rendering/wireframe") ) {
448 clear_mask |= GL_COLOR_BUFFER_BIT;
451 if ( fgGetBool("/sim/rendering/skyblend") ) {
452 if ( fgGetBool("/sim/rendering/textures") ) {
453 // glClearColor(black[0], black[1], black[2], black[3]);
454 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
455 l->adj_fog_color[2], l->adj_fog_color[3]);
456 clear_mask |= GL_COLOR_BUFFER_BIT;
459 glClearColor(l->sky_color[0], l->sky_color[1],
460 l->sky_color[2], l->sky_color[3]);
461 clear_mask |= GL_COLOR_BUFFER_BIT;
463 glClear( clear_mask );
465 // Tell GL we are switching to model view parameters
467 // I really should create a derived ssg node or use a call
468 // back or something so that I can draw the sky within the
469 // ssgCullAndDraw() function, but for now I just mimic what
470 // ssg does to set up the model view matrix
471 glMatrixMode(GL_MODELVIEW);
473 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
475 // set the opengl state to known default values
476 default_state->force();
478 // update fog params if visibility has changed
479 #ifndef FG_OLD_WEATHER
480 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
482 thesky->set_visibility( current_weather.get_visibility() );
485 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
487 ( global_multi_loop *
488 fgGetInt("/sim/speed-up") ) /
489 (double)fgGetInt("/sim/model-hz") );
491 double actual_visibility = thesky->get_visibility();
492 // cout << "actual visibility = " << actual_visibility << endl;
494 if ( actual_visibility != last_visibility ) {
495 last_visibility = actual_visibility;
497 // cout << "----> updating fog params" << endl;
500 fog_exp_density = -log(0.01 / actual_visibility);
503 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
504 fog_exp2_punch_through = sqrt( -log(0.01) ) /
505 ( actual_visibility * 1.5 );
508 // Set correct opengl fog density
509 glFogf (GL_FOG_DENSITY, fog_exp2_density);
511 // update the sky dome
512 if ( fgGetBool("/sim/rendering/skyblend") ) {
513 /* cout << "thesky->repaint() sky_color = "
514 << cur_light_params.sky_color[0] << " "
515 << cur_light_params.sky_color[1] << " "
516 << cur_light_params.sky_color[2] << " "
517 << cur_light_params.sky_color[3] << endl;
519 << cur_light_params.fog_color[0] << " "
520 << cur_light_params.fog_color[1] << " "
521 << cur_light_params.fog_color[2] << " "
522 << cur_light_params.fog_color[3] << endl;
523 cout << " sun_angle = " << cur_light_params.sun_angle
524 << " moon_angle = " << cur_light_params.moon_angle
526 thesky->repaint( cur_light_params.sky_color,
527 cur_light_params.adj_fog_color,
528 cur_light_params.sun_angle,
529 cur_light_params.moon_angle,
530 globals->get_ephem()->getNumPlanets(),
531 globals->get_ephem()->getPlanets(),
532 globals->get_ephem()->getNumStars(),
533 globals->get_ephem()->getStars() );
535 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
536 << view_pos[1] << " " << view_pos[2] << endl;
537 cout << " zero_elev = " << zero_elev[0] << " "
538 << zero_elev[1] << " " << zero_elev[2]
539 << " lon = " << cur_fdm_state->get_Longitude()
540 << " lat = " << cur_fdm_state->get_Latitude() << endl;
541 cout << " sun_rot = " << cur_light_params.sun_rotation
542 << " gst = " << SGTime::cur_time_params->getGst() << endl;
543 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
544 << " sun dec = " << globals->get_ephem()->getSunDeclination()
545 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
546 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
548 thesky->reposition( globals->get_current_view()->get_view_pos(),
549 globals->get_current_view()->get_zero_elev(),
550 globals->get_current_view()->get_world_up(),
551 cur_fdm_state->get_Longitude(),
552 cur_fdm_state->get_Latitude(),
553 cur_fdm_state->get_Altitude() * FEET_TO_METER,
554 cur_light_params.sun_rotation,
555 globals->get_time_params()->getGst(),
556 globals->get_ephem()->getSunRightAscension(),
557 globals->get_ephem()->getSunDeclination(),
559 globals->get_ephem()->getMoonRightAscension(),
560 globals->get_ephem()->getMoonDeclination(),
564 glEnable( GL_DEPTH_TEST );
565 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
567 glFogi( GL_FOG_MODE, GL_EXP2 );
568 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
571 // set lighting parameters
572 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
573 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
574 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
575 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
576 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
578 // texture parameters
579 // glEnable( GL_TEXTURE_2D );
580 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
581 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
582 // set base color (I don't think this is doing anything here)
583 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
584 // (GL_FRONT, GL_DIFFUSE, white);
585 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
586 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
589 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
590 ssgGetLight( 0 ) -> setPosition( sunpos );
592 // glMatrixMode( GL_PROJECTION );
594 float fov = globals->get_current_view()->get_fov();
595 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
597 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
600 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
601 // << current_weather.get_visibility() );
604 ssgSetNearFar( 10.0f, 120000.0f );
606 ssgSetNearFar( 0.5f, 120000.0f );
609 if ( globals->get_viewmgr()->get_current() == 0 ) {
610 // disable aircraft model
611 acmodel_selector->select(0);
613 // enable aircraft model and set up its position and orientation
614 acmodel_selector->select(1);
616 FGViewerRPH *pilot_view =
617 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
620 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
623 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
626 sgMakeRotMat4( sgROT, -90.0, ownship_up );
630 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
631 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
633 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
635 sgCopyMat4( sgTUX, sgROT );
636 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
637 sgPostMultMat4( sgTUX, sgTRANS );
640 sgSetCoord( &tuxpos, sgTUX );
641 acmodel_pos->setTransform( &tuxpos );
643 // set up moving parts
644 if (flaps_selector != NULL) {
645 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
648 if (prop_selector != NULL) {
649 int propsel_mask = 0;
650 for (int i = 0; i < acmodel_npropsettings; i++) {
651 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
652 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
653 propsel_mask |= 1 << i;
656 prop_selector->select(propsel_mask);
660 // $$$ begin - added VS Renganthan 17 Oct 2K
662 // $$$ end - added VS Renganthan 17 Oct 2K
664 # ifdef FG_NETWORK_OLK
665 if ( fgGetBool("/sim/networking/network-olk") ) {
667 other = head->next; /* put listpointer to start */
668 while ( other != tail) { /* display all except myself */
669 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
670 other->fgd_sel->select(1);
671 sgSetCoord( &fgdpos, other->sgFGD_COORD );
672 other->fgd_pos->setTransform( &fgdpos );
677 // fgd_sel->select(1);
678 // sgCopyMat4( sgTUX, current_view.sgVIEW);
680 // sgSetCoord( &fgdpos, sgFGD_VIEW );
681 // fgd_pos->setTransform( &fgdpos);
685 // position tile nodes and update range selectors
686 global_tile_mgr.prep_ssg_nodes();
688 // draw the sky backdrop
691 // draw the ssg scene
692 glEnable( GL_DEPTH_TEST );
693 ssgCullAndDraw( scene );
695 // change state for lighting here
698 // Set punch through fog density
699 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
701 ssgCullAndDraw( lighting );
703 // draw the sky cloud layers
704 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
706 // display HUD && Panel
708 glDisable( GL_DEPTH_TEST );
709 // glDisable( GL_CULL_FACE );
710 // glDisable( GL_TEXTURE_2D );
712 // update the controls subsystem
715 hud_and_panel->apply();
718 // update the panel subsystem
719 if (current_panel != 0)
720 current_panel->update();
722 // We can do translucent menus, so why not. :-)
724 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
726 // glDisable ( GL_BLEND ) ;
728 // glEnable( GL_FOG );
735 // Update internal time dependent calculations (i.e. flight model)
736 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
737 static fdm_state_list fdm_list;
738 fgLIGHT *l = &cur_light_params;
741 // update the flight model
742 if ( multi_loop < 0 ) {
746 if ( !globals->get_freeze() && !initial_freeze ) {
747 // run Autopilot system
748 current_autopilot->run();
750 cur_fdm_state->update( multi_loop *
751 fgGetInt("/sim/speed-up") );
752 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
754 cur_fdm_state->update( 0 );
755 FGSteam::update( 0 );
757 if ( global_tile_mgr.queue_size() == 0 ) {
758 initial_freeze = false;
762 fdm_list.push_back( *cur_fdm_state );
763 while ( fdm_list.size() > 15 ) {
764 fdm_list.pop_front();
767 if ( fgGetString("/sim/view-mode") == "pilot" ) {
768 cur_view_fdm = *cur_fdm_state;
770 } else if ( fgGetString("/sim/view-mode") == "follow" )
772 cur_view_fdm = fdm_list.front();
775 // update the view angle
776 FGViewer *v = globals->get_current_view();
777 for ( i = 0; i < multi_loop; i++ ) {
778 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
779 v->set_view_offset( v->get_goal_view_offset() );
782 // move current_view.view_offset towards
783 // current_view.goal_view_offset
784 if ( v->get_goal_view_offset() > v->get_view_offset() )
786 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
787 v->inc_view_offset( 0.01 );
789 v->inc_view_offset( -0.01 );
792 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
793 v->inc_view_offset( -0.01 );
795 v->inc_view_offset( 0.01 );
798 if ( v->get_view_offset() > FG_2PI ) {
799 v->inc_view_offset( -FG_2PI );
800 } else if ( v->get_view_offset() < 0 ) {
801 v->inc_view_offset( FG_2PI );
806 double tmp = -(l->sun_rotation + FG_PI)
807 - (cur_fdm_state->get_Psi() -
808 globals->get_current_view()->get_view_offset() );
809 while ( tmp < 0.0 ) {
812 while ( tmp > FG_2PI ) {
815 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
816 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
817 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
820 // Update solar system
821 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
822 globals->get_time_params()->getLst(),
823 cur_fdm_state->get_Latitude() );
825 // Update radio stack model
826 current_radiostack->update();
830 void fgInitTimeDepCalcs( void ) {
833 // #ifdef HAVE_SETITIMER
834 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
835 // fgUpdateTimeDepCalcs );
836 // #endif HAVE_SETITIMER
840 static const double alt_adjust_ft = 3.758099;
841 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
844 // What should we do when we have nothing else to do? Let's get ready
845 // for the next move and update the display?
846 static void fgMainLoop( void ) {
847 static long remainder = 0;
849 #ifdef FANCY_FRAME_COUNTER
853 static time_t last_time = 0;
854 static int frames = 0;
855 #endif // FANCY_FRAME_COUNTER
857 SGTime *t = globals->get_time_params();
859 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
860 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
862 #ifdef FG_NETWORK_OLK
863 if ( fgGetBool("/sim/networking/network-olk") ) {
864 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
865 // printf("FGD: Netupdate\n");
866 fgd_send_com( "A", FGFS_host); // Send Mat4 data
867 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
872 #if defined( ENABLE_PLIB_JOYSTICK )
873 // Read joystick and update control settings
874 if ( fgGetString("/sim/control-mode") == "joystick" )
878 #elif defined( ENABLE_GLUT_JOYSTICK )
879 // Glut joystick support works by feeding a joystick handler
880 // function to glut. This is taken care of once in the joystick
881 // init routine and we don't have to worry about it again.
884 #ifdef FG_OLD_WEATHER
885 current_weather.Update();
888 // Fix elevation. I'm just sticking this here for now, it should
889 // probably move eventually
891 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
893 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
894 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
896 if ( scenery.cur_elev > -9990 ) {
897 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
898 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
899 // now set aircraft altitude above ground
900 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
901 cur_fdm_state->get_Altitude() * FEET_TO_METER,
902 scenery.cur_elev + alt_adjust_m - 3.0,
903 scenery.cur_elev + alt_adjust_m );
904 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
905 scenery.cur_elev + alt_adjust_m );
907 FG_LOG( FG_ALL, FG_DEBUG,
908 "<*> resetting altitude to "
909 << cur_fdm_state->get_Altitude() * FEET_TO_METER
914 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
916 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
917 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
920 if ( globals->get_warp_delta() != 0 ) {
921 globals->inc_warp( globals->get_warp_delta() );
924 t->update( cur_fdm_state->get_Longitude(),
925 cur_fdm_state->get_Latitude(),
926 globals->get_warp() );
928 if ( globals->get_warp_delta() != 0 ) {
929 fgUpdateSkyAndLightingParams();
932 // update magvar model
933 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
934 cur_fdm_state->get_Latitude(),
935 cur_fdm_state->get_Altitude()* FEET_TO_METER,
936 globals->get_time_params()->getJD() );
938 // Get elapsed time (in usec) for this past frame
939 elapsed = fgGetTimeInterval();
940 FG_LOG( FG_ALL, FG_DEBUG,
941 "Elapsed time interval is = " << elapsed
942 << ", previous remainder is = " << remainder );
944 // Calculate frame rate average
945 #ifdef FANCY_FRAME_COUNTER
946 /* old fps calculation */
950 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
951 tmp = general.get_frame(i);
953 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
954 general.set_frame(i+1,tmp);
956 tmp = 1000000.0 / (float)elapsed;
957 general.set_frame(0,tmp);
958 // printf("frame[0] = %.2f\n", general.frames[0]);
960 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
961 // printf("ave = %.2f\n", general.frame_rate);
964 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
965 general.set_frame_rate( frames );
966 FG_LOG( FG_ALL, FG_DEBUG,
967 "--> Frame rate is = " << general.get_frame_rate() );
970 last_time = t->get_cur_time();
975 if ( ! use_signals ) {
976 // Calculate model iterations needed for next frame
977 elapsed += remainder;
979 global_multi_loop = (int)(((double)elapsed * 0.000001) *
980 fgGetInt("/sim/model-hz"));
981 remainder = elapsed - ( (global_multi_loop*1000000) /
982 fgGetInt("/sim/model-hz") );
983 FG_LOG( FG_ALL, FG_DEBUG,
984 "Model iterations needed = " << global_multi_loop
985 << ", new remainder = " << remainder );
988 if ( global_multi_loop > 0 ) {
989 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
991 FG_LOG( FG_ALL, FG_DEBUG,
992 "Elapsed time is zero ... we're zinging" );
996 #if ! defined( macintosh )
997 // Do any I/O channel work that might need to be done
1001 // see if we need to load any new scenery tiles
1002 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1003 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1005 // Process/manage pending events
1006 global_events.Process();
1008 // Run audio scheduler
1009 #ifdef ENABLE_AUDIO_SUPPORT
1010 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1012 if ( fgGetString("/sim/aircraft") == "c172" ) {
1013 // pitch corresponds to rpm
1014 // volume corresponds to manifold pressure
1017 if ( cur_fdm_state->get_engine(0) != NULL ) {
1018 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1022 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1025 double pitch = 0.3 + rpm_factor * 3.0;
1027 // don't run at absurdly slow rates -- not realistic
1028 // and sounds bad to boot. :-)
1029 if (pitch < 0.7) { pitch = 0.7; }
1030 if (pitch > 5.0) { pitch = 5.0; }
1031 // cout << "pitch = " << pitch << endl;
1034 if ( cur_fdm_state->get_engine(0) != NULL ) {
1036 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
1041 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1044 double volume = mp_factor;
1046 if ( volume < 0.3 ) { volume = 0.3; }
1047 if ( volume > 2.0 ) { volume = 2.0; }
1048 // cout << "volume = " << volume << endl;
1050 pitch_envelope.setStep ( 0, 0.01, pitch );
1051 volume_envelope.setStep ( 0, 0.01, volume );
1053 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1054 pitch_envelope.setStep ( 0, 0.01, param );
1055 volume_envelope.setStep ( 0, 0.01, param );
1058 audio_sched -> update();
1065 FG_LOG( FG_ALL, FG_DEBUG, "" );
1069 // This is the top level master main function that is registered as
1070 // our idle funciton
1073 // The first few passes take care of initialization things (a couple
1074 // per pass) and once everything has been initialized fgMainLoop from
1077 static void fgIdleFunction ( void ) {
1078 // printf("idle state == %d\n", idle_state);
1080 if ( idle_state == 0 ) {
1081 // Initialize the splash screen right away
1082 if ( fgGetBool("/sim/startup/splash-screen") ) {
1087 } else if ( idle_state == 1 ) {
1088 // Start the intro music
1090 if ( fgGetBool("/sim/startup/intro-music") ) {
1091 string lockfile = "/tmp/mpg123.running";
1092 FGPath mp3file( globals->get_fg_root() );
1093 mp3file.append( "Sounds/intro.mp3" );
1095 string command = "(touch " + lockfile + "; mpg123 "
1096 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1098 FG_LOG( FG_GENERAL, FG_INFO,
1099 "Starting intro music: " << mp3file.str() );
1100 system ( command.c_str() );
1105 } else if ( idle_state == 2 ) {
1106 // These are a few miscellaneous things that aren't really
1107 // "subsystems" but still need to be initialized.
1110 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1111 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1116 } else if ( idle_state == 3 ) {
1117 // This is the top level init routine which calls all the
1118 // other subsystem initialization routines. If you are adding
1119 // a subsystem to flightgear, its initialization call should
1120 // located in this routine.
1121 if( !fgInitSubsystems()) {
1122 FG_LOG( FG_GENERAL, FG_ALERT,
1123 "Subsystem initializations failed ..." );
1128 } else if ( idle_state == 4 ) {
1129 // setup OpenGL view parameters
1132 if ( use_signals ) {
1133 // init timer routines, signals, etc. Arrange for an alarm
1134 // signal to be generated, etc.
1135 fgInitTimeDepCalcs();
1139 } else if ( idle_state == 5 ) {
1142 } else if ( idle_state == 6 ) {
1143 // Initialize audio support
1144 #ifdef ENABLE_AUDIO_SUPPORT
1147 if ( fgGetBool("/sim/startup/intro-music") ) {
1148 // Let's wait for mpg123 to finish
1149 string lockfile = "/tmp/mpg123.running";
1150 struct stat stat_buf;
1152 FG_LOG( FG_GENERAL, FG_INFO,
1153 "Waiting for mpg123 player to finish ..." );
1154 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1155 // file exist, wait ...
1157 FG_LOG( FG_GENERAL, FG_INFO, ".");
1159 FG_LOG( FG_GENERAL, FG_INFO, "");
1163 if ( fgGetBool("/sim/sound") ) {
1164 audio_sched = new slScheduler ( 8000 );
1165 audio_mixer = new smMixer;
1166 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1167 audio_sched -> setSafetyMargin ( 1.0 ) ;
1169 FGPath slfile( globals->get_fg_root() );
1170 slfile.append( "Sounds/wasp.wav" );
1172 s1 = new slSample ( (char *)slfile.c_str() );
1173 FG_LOG( FG_GENERAL, FG_INFO,
1174 "Rate = " << s1 -> getRate()
1175 << " Bps = " << s1 -> getBps()
1176 << " Stereo = " << s1 -> getStereo() );
1177 audio_sched -> loopSample ( s1 );
1179 if ( audio_sched->not_working() ) {
1182 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1183 volume_envelope.setStep ( 0, 0.01, 0.6 );
1185 audio_sched -> addSampleEnvelope( s1, 0, 0,
1187 SL_PITCH_ENVELOPE );
1188 audio_sched -> addSampleEnvelope( s1, 0, 1,
1190 SL_VOLUME_ENVELOPE );
1193 // strcpy(slfile, path);
1194 // strcat(slfile, "thunder.wav");
1195 // s2 -> loadFile ( slfile );
1196 // s2 -> adjustVolume(0.5);
1197 // audio_sched -> playSample ( s2 );
1204 cout << "Panel visible = " << fgPanelVisible() << endl;
1205 fgReshape( fgGetInt("/sim/startup/xsize"),
1206 fgGetInt("/sim/startup/ysize") );
1209 if ( idle_state == 1000 ) {
1210 // We've finished all our initialization steps, from now on we
1211 // run the main loop.
1215 if ( fgGetBool("/sim/startup/splash-screen") ) {
1216 fgSplashUpdate(0.0);
1221 // options.cxx needs to see this for toggle_panel()
1222 // Handle new window size or exposure
1223 void fgReshape( int width, int height ) {
1225 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1226 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1227 globals->get_viewmgr()->get_view(i)->
1228 set_win_ratio( (float)height / (float)width );
1231 int((current_panel->getViewHeight() -
1232 current_panel->getYOffset())
1233 * (height / 768.0)) + 1;
1234 globals->get_viewmgr()->get_view(i)->
1235 set_win_ratio( (float)view_h / (float)width );
1239 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1240 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1243 int((current_panel->getViewHeight() - current_panel->getYOffset())
1244 * (height / 768.0)) + 1;
1245 glViewport(0, (GLint)(height - view_h),
1246 (GLint)(width), (GLint)(view_h) );
1249 fgSetInt("/sim/startup/xsize", width);
1250 fgSetInt("/sim/startup/ysize", height);
1252 float fov = globals->get_current_view()->get_fov();
1253 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1259 // Initialize GLUT and define a main window
1260 int fgGlutInit( int *argc, char **argv ) {
1262 #if !defined( macintosh )
1263 // GLUT will extract all glut specific options so later on we only
1264 // need wory about our own.
1265 glutInit(argc, argv);
1268 // Define Display Parameters
1269 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1271 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1272 fgGetInt("/sim/startup/xsize") << "x"
1273 << fgGetInt("/sim/startup/ysize") );
1275 // Define initial window size
1276 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1277 fgGetInt("/sim/startup/ysize") );
1279 // Initialize windows
1280 if ( !fgGetBool("/sim/startup/game-mode")) {
1281 // Open the regular window
1282 glutCreateWindow("FlightGear");
1283 #ifndef GLUT_WRONG_VERSION
1285 // Open the cool new 'game mode' window
1286 char game_mode_str[256];
1287 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1288 fgGetInt("/sim/startup/xsize"),
1289 fgGetInt("/sim/startup/ysize"),
1290 fgGetInt("/sim/rendering/bits-per-pixel"));
1292 FG_LOG( FG_GENERAL, FG_INFO,
1293 "game mode params = " << game_mode_str );
1294 glutGameModeString( game_mode_str );
1295 glutEnterGameMode();
1299 // This seems to be the absolute earliest in the init sequence
1300 // that these calls will return valid info. Too bad it's after
1301 // we've already created and sized out window. :-(
1302 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1303 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1304 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1305 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1308 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1309 general.set_glMaxTexSize( tmp );
1310 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1312 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1313 general.set_glDepthBits( tmp );
1314 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1320 // Initialize GLUT event handlers
1321 int fgGlutInitEvents( void ) {
1322 // call fgReshape() on window resizes
1323 glutReshapeFunc( fgReshape );
1325 // call GLUTkey() on keyboard event
1326 glutKeyboardFunc( GLUTkey );
1327 glutSpecialFunc( GLUTspecialkey );
1329 // call guiMouseFunc() whenever our little rodent is used
1330 glutMouseFunc ( guiMouseFunc );
1331 glutMotionFunc (guiMotionFunc );
1332 glutPassiveMotionFunc (guiMotionFunc );
1334 // call fgMainLoop() whenever there is
1335 // nothing else to do
1336 glutIdleFunc( fgIdleFunction );
1339 glutDisplayFunc( fgRenderFrame );
1346 int main( int argc, char **argv ) {
1348 #if defined( macintosh )
1349 freopen ("stdout.txt", "w", stdout );
1350 freopen ("stderr.txt", "w", stderr );
1351 argc = ccommand( &argv );
1355 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1358 // set default log levels
1359 fglog().setLogLevels( FG_ALL, FG_INFO );
1362 #ifdef FLIGHTGEAR_VERSION
1363 version = FLIGHTGEAR_VERSION;
1365 version = "unknown version";
1367 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1368 << version << endl );
1370 // Allocate global data structures. This needs to happen before
1371 // we parse command line options
1373 SGPropertyNode *props = new SGPropertyNode;
1374 globals = new FGGlobals;
1375 globals->set_props( props );
1377 // seed the random number generater
1380 SGRoute *route = new SGRoute;
1381 globals->set_route( route );
1383 FGViewMgr *viewmgr = new FGViewMgr;
1384 globals->set_viewmgr( viewmgr );
1386 FGViewerRPH *pv = new FGViewerRPH;
1387 globals->get_viewmgr()->add_view( pv );
1389 FGViewerLookAt *chase = new FGViewerLookAt;
1390 globals->get_viewmgr()->add_view( chase );
1392 // set current view to 0 (first) which is our main pilot view
1393 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1395 // Scan the config file(s) and command line options to see if
1396 // fg_root was specified (ignore all other options for now)
1397 fgInitFGRoot(argc, argv);
1399 // Initialize the Aircraft directory to "" (UIUC)
1402 // Load the configuration parameters
1403 if ( !fgInitConfig(argc, argv) ) {
1404 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1408 // Initialize the Window/Graphics environment.
1409 if( !fgGlutInit(&argc, argv) ) {
1410 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1414 // Initialize the various GLUT Event Handlers.
1415 if( !fgGlutInitEvents() ) {
1416 FG_LOG( FG_GENERAL, FG_ALERT,
1417 "GLUT event handler initialization failed ..." );
1421 // Initialize ssg (from plib). Needs to come before we do any
1422 // other ssg stuff, but after opengl/glut has been initialized.
1425 // Initialize the user interface (we need to do this before
1426 // passing off control to glut and before fgInitGeneral to get our
1430 // set current_options lon/lat if an airport id is specified
1431 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1432 if ( fgGetString("/sim/startup/airport-id").length() ) {
1433 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1434 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1435 fgGetDouble("/orientation/heading") );
1439 FGPath zone( globals->get_fg_root() );
1440 zone.append( "Timezone" );
1441 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1442 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1445 // Handle potential user specified time offsets
1446 time_t cur_time = t->get_cur_time();
1447 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1448 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1449 time_t aircraftLocalTime =
1450 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1452 // Okay, we now have six possible scenarios
1453 int offset = fgGetInt("/sim/startup/time-offset");
1454 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1455 if (offset_type == "system-offset") {
1456 globals->set_warp( offset );
1457 } else if (offset_type == "gmt-offset") {
1458 globals->set_warp( offset - (currGMT - systemLocalTime) );
1459 } else if (offset_type == "latitude-offset") {
1460 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1461 } else if (offset_type == "system") {
1462 globals->set_warp( offset - cur_time );
1463 } else if (offset_type == "gmt") {
1464 globals->set_warp( offset - currGMT );
1465 } else if (offset_type == "latitude") {
1466 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1469 FG_LOG( FG_GENERAL, FG_ALERT,
1470 "Unsupported offset type " << offset_type );
1474 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1475 << globals->get_warp() );
1477 globals->set_warp_delta( 0 );
1479 t->update( 0.0, 0.0, globals->get_warp() );
1481 globals->set_time_params( t );
1483 // Do some quick general initializations
1484 if( !fgInitGeneral()) {
1485 FG_LOG( FG_GENERAL, FG_ALERT,
1486 "General initializations failed ..." );
1490 FGPath modelpath( globals->get_fg_root() );
1491 ssgModelPath( (char *)modelpath.c_str() );
1494 scene = new ssgRoot;
1495 scene->setName( "Scene" );
1497 lighting = new ssgRoot;
1498 lighting->setName( "Lighting" );
1500 // Initialize the sky
1501 FGPath ephem_data_path( globals->get_fg_root() );
1502 ephem_data_path.append( "Astro" );
1503 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1504 ephem->update( globals->get_time_params()->getMjd(),
1505 globals->get_time_params()->getLst(),
1507 globals->set_ephem( ephem );
1509 FGPath sky_tex_path( globals->get_fg_root() );
1510 sky_tex_path.append( "Textures" );
1511 sky_tex_path.append( "Sky" );
1513 thesky->texture_path( sky_tex_path.str() );
1515 thesky->build( 550.0, 550.0,
1516 globals->get_ephem()->getNumPlanets(),
1517 globals->get_ephem()->getPlanets(), 60000.0,
1518 globals->get_ephem()->getNumStars(),
1519 globals->get_ephem()->getStars(), 60000.0 );
1521 if ( fgGetBool("/environment/clouds/status") ) {
1522 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1523 SG_CLOUD_MOSTLY_SUNNY );
1524 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1526 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1527 // SG_CLOUD_MOSTLY_SUNNY );
1528 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1529 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1532 // Initialize MagVar model
1533 SGMagVar *magvar = new SGMagVar();
1534 globals->set_mag( magvar );
1537 terrain = new ssgBranch;
1538 terrain->setName( "Terrain" );
1539 scene->addKid( terrain );
1542 ground = new ssgBranch;
1543 ground->setName( "Ground Lighting" );
1544 lighting->addKid( ground );
1546 airport = new ssgBranch;
1547 airport->setName( "Airport Lighting" );
1548 lighting->addKid( airport );
1550 // temporary visible aircraft "own ship"
1551 acmodel_selector = new ssgSelector;
1552 acmodel_pos = new ssgTransform;
1554 string acmodel_path =
1555 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1557 string full_model = globals->get_fg_root() + "/"
1559 int pos = full_model.rfind("/");
1561 FGPath texturepath( full_model.substr(0, pos) );
1562 cout << "Texture path = " << texturepath.str() << endl;
1563 ssgTexturePath( (char *)texturepath.c_str() );
1565 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1567 // find moving parts (if this is an MDL model)
1568 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1569 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1571 acmodel_npropsettings = 0;
1572 if (prop_selector != NULL) {
1573 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1574 kid = prop_selector->getNextKid()) {
1575 int prop_low, prop_high;
1576 if ( sscanf(kid->getName(), "PROP_%d_%d",
1577 &prop_low, &prop_high) == 2 ) {
1578 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1579 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1580 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1581 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1582 acmodel_npropsettings++;
1584 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1590 // align the model properly for FGFS
1591 ssgTransform *acmodel_align = new ssgTransform;
1592 acmodel_align->addKid(acmodel_obj);
1596 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1597 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1598 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1599 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1600 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1601 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1602 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1603 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1604 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1605 acmodel_align->setTransform(res_matrix);
1607 acmodel_pos->addKid( acmodel_align );
1608 acmodel_selector->addKid( acmodel_pos );
1609 //ssgFlatten( acmodel_obj );
1610 //ssgStripify( acmodel_selector );
1611 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1612 scene->addKid( acmodel_selector );
1614 // $$$ begin - added VS Renganthan 17 Oct 2K
1616 // $$$ end - added VS Renganthan 17 Oct 2K
1618 #ifdef FG_NETWORK_OLK
1619 // Do the network intialization
1620 if ( fgGetBool("/sim/networking/network-olk") ) {
1621 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1625 // build our custom render states
1626 fgBuildRenderStates();
1628 // pass control off to the master GLUT event handler
1631 // we never actually get here ... but to avoid compiler warnings,
1637 // $$$ end - added VS Renganathan, 15 Oct 2K
1638 // - added Venky , 12 Nov 2K
1640 void fgLoadDCS(void) {
1642 ssgEntity *ship_obj;
1645 char obj_filename[25];
1647 for (int k=0;k<32;k++)
1652 FGPath tile_path( globals->get_fg_root());
1653 tile_path.append( "Scenery" );
1654 tile_path.append( "Objects.txt" );
1655 fg_gzifstream in( tile_path.str() );
1656 if ( ! in.is_open() ) {
1657 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1660 FGPath modelpath( globals->get_fg_root() );
1661 modelpath.append( "Models" );
1662 modelpath.append( "Geometry" );
1664 FGPath texturepath( globals->get_fg_root() );
1665 texturepath.append( "Models" );
1666 texturepath.append( "Textures" );
1668 ssgModelPath( (char *)modelpath.c_str() );
1669 ssgTexturePath( (char *)texturepath.c_str() );
1671 ship_sel = new ssgSelector;
1674 while ( ! in.eof() )
1677 if ( in.get( c ) && c == '#' )
1684 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1685 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1686 int chj=getchar();*/
1688 obj_lon[objc] *=DEG_TO_RAD;
1689 obj_lat[objc] *=DEG_TO_RAD;
1691 ship_pos[objc] = new ssgTransform;
1694 // type "repeat" in objects.txt to load one more instance of the last object.
1696 if ( strcmp(obj_filename,"repeat") != 0)
1697 ship_obj = ssgLoadOBJ( obj_filename );
1699 if ( ship_obj != NULL )
1701 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1702 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1705 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1707 if (in.eof()) break;
1712 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1713 scene->addKid( ship_sel ); //add selector node to root node
1718 void fgUpdateDCS (void) {
1720 double eye_lat,eye_lon,eye_alt;
1721 static double obj_head;
1722 double sl_radius,obj_latgc;
1723 float nresultmat[4][4];
1724 sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1727 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1728 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1730 // Deck should be the first object in objects.txt in case of fdm=ada
1732 if (fgGetString("/sim/flight-model") == "ada")
1734 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1735 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1736 obj_alt[0] = fdm->get_aux7();
1739 for (int m=0; m<=objc; m++)
1741 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1744 //Geodetic to Geocentric angles for rotation
1745 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1747 //moving object gbs-posn in cartesian coords
1748 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1749 Point3D obj_pos = sgGeodToCart( obj_posn );
1751 // Translate moving object w.r.t eye
1752 Point3D Objtrans = obj_pos-scenery.center;
1757 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1760 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1762 sgVec3 ship_fwd,ship_rt,ship_up;
1763 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1764 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1765 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1767 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1768 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1769 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1770 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1773 sgCopyMat4( sgTUX, sgROT_hdg );
1774 sgPostMultMat4( sgTUX, sgROT_lat );
1775 sgPostMultMat4( sgTUX, sgROT_lon );
1776 sgPostMultMat4( sgTUX, sgTRANS );
1779 sgSetCoord(&shippos, sgTUX );
1780 ship_pos[m]->setTransform( &shippos );
1782 if ( ship_sel != NULL )
1783 ship_sel->select(0xFFFFFFFF);
1786 // $$$ end - added VS Renganathan, 15 Oct 2K
1787 // added Venky , 12 Nov 2K