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 long 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,
483 ( global_multi_loop *
484 fgGetInt("/sim/speed-up") ) /
485 (double)fgGetInt("/sim/model-hz") );
487 double actual_visibility = thesky->get_visibility();
488 // cout << "actual visibility = " << actual_visibility << endl;
490 if ( actual_visibility != last_visibility ) {
491 last_visibility = actual_visibility;
493 // cout << "----> updating fog params" << endl;
496 fog_exp_density = -log(0.01 / actual_visibility);
499 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
500 fog_exp2_punch_through = sqrt( -log(0.01) ) /
501 ( actual_visibility * 1.5 );
504 // Set correct opengl fog density
505 glFogf (GL_FOG_DENSITY, fog_exp2_density);
507 // update the sky dome
508 if ( fgGetBool("/sim/rendering/skyblend") ) {
509 /* cout << "thesky->repaint() sky_color = "
510 << cur_light_params.sky_color[0] << " "
511 << cur_light_params.sky_color[1] << " "
512 << cur_light_params.sky_color[2] << " "
513 << cur_light_params.sky_color[3] << endl;
515 << cur_light_params.fog_color[0] << " "
516 << cur_light_params.fog_color[1] << " "
517 << cur_light_params.fog_color[2] << " "
518 << cur_light_params.fog_color[3] << endl;
519 cout << " sun_angle = " << cur_light_params.sun_angle
520 << " moon_angle = " << cur_light_params.moon_angle
522 thesky->repaint( cur_light_params.sky_color,
523 cur_light_params.adj_fog_color,
524 cur_light_params.sun_angle,
525 cur_light_params.moon_angle,
526 globals->get_ephem()->getNumPlanets(),
527 globals->get_ephem()->getPlanets(),
528 globals->get_ephem()->getNumStars(),
529 globals->get_ephem()->getStars() );
531 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
532 << view_pos[1] << " " << view_pos[2] << endl;
533 cout << " zero_elev = " << zero_elev[0] << " "
534 << zero_elev[1] << " " << zero_elev[2]
535 << " lon = " << cur_fdm_state->get_Longitude()
536 << " lat = " << cur_fdm_state->get_Latitude() << endl;
537 cout << " sun_rot = " << cur_light_params.sun_rotation
538 << " gst = " << SGTime::cur_time_params->getGst() << endl;
539 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
540 << " sun dec = " << globals->get_ephem()->getSunDeclination()
541 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
542 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
544 thesky->reposition( globals->get_current_view()->get_view_pos(),
545 globals->get_current_view()->get_zero_elev(),
546 globals->get_current_view()->get_world_up(),
547 cur_fdm_state->get_Longitude(),
548 cur_fdm_state->get_Latitude(),
549 cur_fdm_state->get_Altitude() * FEET_TO_METER,
550 cur_light_params.sun_rotation,
551 globals->get_time_params()->getGst(),
552 globals->get_ephem()->getSunRightAscension(),
553 globals->get_ephem()->getSunDeclination(),
555 globals->get_ephem()->getMoonRightAscension(),
556 globals->get_ephem()->getMoonDeclination(),
560 glEnable( GL_DEPTH_TEST );
561 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
563 glFogi( GL_FOG_MODE, GL_EXP2 );
564 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
567 // set lighting parameters
568 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
569 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
570 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
571 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
572 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
574 // texture parameters
575 // glEnable( GL_TEXTURE_2D );
576 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
577 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
578 // set base color (I don't think this is doing anything here)
579 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
580 // (GL_FRONT, GL_DIFFUSE, white);
581 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
582 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
585 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
586 ssgGetLight( 0 ) -> setPosition( sunpos );
588 // glMatrixMode( GL_PROJECTION );
590 float fov = globals->get_current_view()->get_fov();
591 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
593 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
596 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
597 // << current_weather.get_visibility() );
600 ssgSetNearFar( 10.0f, 120000.0f );
602 ssgSetNearFar( 0.5f, 120000.0f );
605 if ( globals->get_viewmgr()->get_current() == 0 ) {
606 // disable aircraft model
607 acmodel_selector->select(0);
609 // enable aircraft model and set up its position and orientation
610 acmodel_selector->select(1);
612 FGViewerRPH *pilot_view =
613 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
616 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
619 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
622 sgMakeRotMat4( sgROT, -90.0, ownship_up );
626 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
627 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
629 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
631 sgCopyMat4( sgTUX, sgROT );
632 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
633 sgPostMultMat4( sgTUX, sgTRANS );
636 sgSetCoord( &tuxpos, sgTUX );
637 acmodel_pos->setTransform( &tuxpos );
639 // set up moving parts
640 if (flaps_selector != NULL) {
641 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
644 if (prop_selector != NULL) {
645 int propsel_mask = 0;
646 for (int i = 0; i < acmodel_npropsettings; i++) {
647 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
648 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
649 propsel_mask |= 1 << i;
652 prop_selector->select(propsel_mask);
656 // $$$ begin - added VS Renganthan 17 Oct 2K
658 // $$$ end - added VS Renganthan 17 Oct 2K
660 # ifdef FG_NETWORK_OLK
661 if ( fgGetBool("/sim/networking/network-olk") ) {
663 other = head->next; /* put listpointer to start */
664 while ( other != tail) { /* display all except myself */
665 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
666 other->fgd_sel->select(1);
667 sgSetCoord( &fgdpos, other->sgFGD_COORD );
668 other->fgd_pos->setTransform( &fgdpos );
673 // fgd_sel->select(1);
674 // sgCopyMat4( sgTUX, current_view.sgVIEW);
676 // sgSetCoord( &fgdpos, sgFGD_VIEW );
677 // fgd_pos->setTransform( &fgdpos);
681 // position tile nodes and update range selectors
682 global_tile_mgr.prep_ssg_nodes();
684 if ( fgGetBool("/sim/rendering/skyblend") ) {
685 // draw the sky backdrop
689 // draw the ssg scene
690 glEnable( GL_DEPTH_TEST );
691 ssgCullAndDraw( scene );
693 // change state for lighting here
696 // Set punch through fog density
697 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
699 ssgCullAndDraw( lighting );
701 if ( fgGetBool("/sim/rendering/skyblend") ) {
702 // draw the sky cloud layers
703 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() {
737 static bool inited = false;
739 fgLIGHT *l = &cur_light_params;
744 if ( !globals->get_freeze() && !initial_freeze ) {
745 // conceptually, this could be done for each fdm instance ...
748 cur_fdm_state->stamp();
754 long elapsed = current - cur_fdm_state->get_time_stamp();
755 cur_fdm_state->set_time_stamp( current );
756 elapsed += cur_fdm_state->get_remainder();
757 // cout << "elapsed = " << elapsed << endl;
758 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
759 multi_loop = (long)(((double)elapsed * 0.000001) /
760 cur_fdm_state->get_delta_t() );
761 cur_fdm_state->set_multi_loop( multi_loop );
762 long remainder = elapsed - ( (multi_loop*1000000) *
763 cur_fdm_state->get_delta_t() );
764 cur_fdm_state->set_remainder( remainder );
765 // cout << "remainder = " << remainder << endl;
767 // chop max interations to something reasonable if the sim was
768 // delayed for an excesive amount of time
769 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
770 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
771 cur_fdm_state->set_remainder( 0 );
774 // cout << "multi_loop = " << multi_loop << endl;
775 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
776 // run Autopilot system
777 current_autopilot->run();
780 cur_fdm_state->update( 1 );
782 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
784 cur_fdm_state->update( 0 );
785 FGSteam::update( 0 );
787 if ( global_tile_mgr.queue_size() == 0 ) {
788 initial_freeze = false;
792 if ( fgGetString("/sim/view-mode") == "pilot" ) {
793 cur_view_fdm = *cur_fdm_state;
797 // update the view angle
798 FGViewer *v = globals->get_current_view();
799 for ( i = 0; i < multi_loop; i++ ) {
800 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
801 v->set_view_offset( v->get_goal_view_offset() );
804 // move current_view.view_offset towards
805 // current_view.goal_view_offset
806 if ( v->get_goal_view_offset() > v->get_view_offset() )
808 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
809 v->inc_view_offset( 0.01 );
811 v->inc_view_offset( -0.01 );
814 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
815 v->inc_view_offset( -0.01 );
817 v->inc_view_offset( 0.01 );
820 if ( v->get_view_offset() > FG_2PI ) {
821 v->inc_view_offset( -FG_2PI );
822 } else if ( v->get_view_offset() < 0 ) {
823 v->inc_view_offset( FG_2PI );
828 double tmp = -(l->sun_rotation + FG_PI)
829 - (cur_fdm_state->get_Psi() -
830 globals->get_current_view()->get_view_offset() );
831 while ( tmp < 0.0 ) {
834 while ( tmp > FG_2PI ) {
837 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
838 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
839 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
842 // Update solar system
843 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
844 globals->get_time_params()->getLst(),
845 cur_fdm_state->get_Latitude() );
847 // Update radio stack model
848 current_radiostack->update();
852 void fgInitTimeDepCalcs( void ) {
855 // #ifdef HAVE_SETITIMER
856 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
857 // fgUpdateTimeDepCalcs );
858 // #endif HAVE_SETITIMER
862 static const double alt_adjust_ft = 3.758099;
863 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
866 // What should we do when we have nothing else to do? Let's get ready
867 // for the next move and update the display?
868 static void fgMainLoop( void ) {
869 static long remainder = 0;
871 #ifdef FANCY_FRAME_COUNTER
875 static time_t last_time = 0;
876 static int frames = 0;
877 #endif // FANCY_FRAME_COUNTER
879 SGTime *t = globals->get_time_params();
881 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
882 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
884 #ifdef FG_NETWORK_OLK
885 if ( fgGetBool("/sim/networking/network-olk") ) {
886 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
887 // printf("FGD: Netupdate\n");
888 fgd_send_com( "A", FGFS_host); // Send Mat4 data
889 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
894 #if defined( ENABLE_PLIB_JOYSTICK )
895 // Read joystick and update control settings
896 if ( fgGetString("/sim/control-mode") == "joystick" )
900 #elif defined( ENABLE_GLUT_JOYSTICK )
901 // Glut joystick support works by feeding a joystick handler
902 // function to glut. This is taken care of once in the joystick
903 // init routine and we don't have to worry about it again.
906 #ifdef FG_OLD_WEATHER
907 current_weather.Update();
910 // Fix elevation. I'm just sticking this here for now, it should
911 // probably move eventually
913 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
915 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
916 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
918 if ( scenery.cur_elev > -9990 ) {
919 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
920 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
921 // now set aircraft altitude above ground
922 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
923 cur_fdm_state->get_Altitude() * FEET_TO_METER,
924 scenery.cur_elev + alt_adjust_m - 3.0,
925 scenery.cur_elev + alt_adjust_m );
926 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
927 scenery.cur_elev + alt_adjust_m );
929 FG_LOG( FG_ALL, FG_DEBUG,
930 "<*> resetting altitude to "
931 << cur_fdm_state->get_Altitude() * FEET_TO_METER
936 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
938 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
939 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
942 if ( globals->get_warp_delta() != 0 ) {
943 globals->inc_warp( globals->get_warp_delta() );
946 t->update( cur_fdm_state->get_Longitude(),
947 cur_fdm_state->get_Latitude(),
948 globals->get_warp() );
950 if ( globals->get_warp_delta() != 0 ) {
951 fgUpdateSkyAndLightingParams();
954 // update magvar model
955 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
956 cur_fdm_state->get_Latitude(),
957 cur_fdm_state->get_Altitude()* FEET_TO_METER,
958 globals->get_time_params()->getJD() );
960 // Get elapsed time (in usec) for this past frame
961 elapsed = fgGetTimeInterval();
962 FG_LOG( FG_ALL, FG_DEBUG,
963 "Elapsed time interval is = " << elapsed
964 << ", previous remainder is = " << remainder );
966 // Calculate frame rate average
967 #ifdef FANCY_FRAME_COUNTER
968 /* old fps calculation */
972 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
973 tmp = general.get_frame(i);
975 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
976 general.set_frame(i+1,tmp);
978 tmp = 1000000.0 / (float)elapsed;
979 general.set_frame(0,tmp);
980 // printf("frame[0] = %.2f\n", general.frames[0]);
982 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
983 // printf("ave = %.2f\n", general.frame_rate);
986 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
987 general.set_frame_rate( frames );
988 FG_LOG( FG_ALL, FG_DEBUG,
989 "--> Frame rate is = " << general.get_frame_rate() );
992 last_time = t->get_cur_time();
998 // Calculate model iterations needed for next frame
999 elapsed += remainder;
1001 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1002 fgGetInt("/sim/model-hz"));
1003 remainder = elapsed - ( (global_multi_loop*1000000) /
1004 fgGetInt("/sim/model-hz") );
1005 FG_LOG( FG_ALL, FG_DEBUG,
1006 "Model iterations needed = " << global_multi_loop
1007 << ", new remainder = " << remainder );
1009 // chop max interations to something reasonable if the sim was
1010 // delayed for an excesive amount of time
1011 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1012 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1017 if ( global_multi_loop > 0 ) {
1018 fgUpdateTimeDepCalcs();
1020 FG_LOG( FG_ALL, FG_DEBUG,
1021 "Elapsed time is zero ... we're zinging" );
1024 #if ! defined( macintosh )
1025 // Do any I/O channel work that might need to be done
1029 // see if we need to load any new scenery tiles
1030 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1031 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1033 // Process/manage pending events
1034 global_events.Process();
1036 // Run audio scheduler
1037 #ifdef ENABLE_AUDIO_SUPPORT
1038 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1040 if ( fgGetString("/sim/aircraft") == "c172" ) {
1041 // pitch corresponds to rpm
1042 // volume corresponds to manifold pressure
1045 if ( cur_fdm_state->get_engine(0) != NULL ) {
1046 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1050 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1053 double pitch = 0.3 + rpm_factor * 3.0;
1055 // don't run at absurdly slow rates -- not realistic
1056 // and sounds bad to boot. :-)
1057 if (pitch < 0.7) { pitch = 0.7; }
1058 if (pitch > 5.0) { pitch = 5.0; }
1059 // cout << "pitch = " << pitch << endl;
1062 if ( cur_fdm_state->get_engine(0) != NULL ) {
1064 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1069 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1072 double volume = 0.3 + mp_factor;
1074 if ( volume < 0.3 ) { volume = 0.3; }
1075 if ( volume > 1.0 ) { volume = 1.0; }
1076 // cout << "volume = " << volume << endl;
1078 pitch_envelope.setStep ( 0, 0.01, pitch );
1079 volume_envelope.setStep ( 0, 0.01, volume );
1081 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1082 pitch_envelope.setStep ( 0, 0.01, param );
1083 volume_envelope.setStep ( 0, 0.01, param );
1086 audio_sched -> update();
1093 FG_LOG( FG_ALL, FG_DEBUG, "" );
1097 // This is the top level master main function that is registered as
1098 // our idle funciton
1101 // The first few passes take care of initialization things (a couple
1102 // per pass) and once everything has been initialized fgMainLoop from
1105 static void fgIdleFunction ( void ) {
1106 // printf("idle state == %d\n", idle_state);
1108 if ( idle_state == 0 ) {
1109 // Initialize the splash screen right away
1110 if ( fgGetBool("/sim/startup/splash-screen") ) {
1115 } else if ( idle_state == 1 ) {
1116 // Start the intro music
1118 if ( fgGetBool("/sim/startup/intro-music") ) {
1119 string lockfile = "/tmp/mpg123.running";
1120 FGPath mp3file( globals->get_fg_root() );
1121 mp3file.append( "Sounds/intro.mp3" );
1123 string command = "(touch " + lockfile + "; mpg123 "
1124 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1126 FG_LOG( FG_GENERAL, FG_INFO,
1127 "Starting intro music: " << mp3file.str() );
1128 system ( command.c_str() );
1133 } else if ( idle_state == 2 ) {
1134 // These are a few miscellaneous things that aren't really
1135 // "subsystems" but still need to be initialized.
1138 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1139 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1144 } else if ( idle_state == 3 ) {
1145 // This is the top level init routine which calls all the
1146 // other subsystem initialization routines. If you are adding
1147 // a subsystem to flightgear, its initialization call should
1148 // located in this routine.
1149 if( !fgInitSubsystems()) {
1150 FG_LOG( FG_GENERAL, FG_ALERT,
1151 "Subsystem initializations failed ..." );
1156 } else if ( idle_state == 4 ) {
1157 // setup OpenGL view parameters
1161 } else if ( idle_state == 5 ) {
1164 } else if ( idle_state == 6 ) {
1165 // Initialize audio support
1166 #ifdef ENABLE_AUDIO_SUPPORT
1169 if ( fgGetBool("/sim/startup/intro-music") ) {
1170 // Let's wait for mpg123 to finish
1171 string lockfile = "/tmp/mpg123.running";
1172 struct stat stat_buf;
1174 FG_LOG( FG_GENERAL, FG_INFO,
1175 "Waiting for mpg123 player to finish ..." );
1176 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1177 // file exist, wait ...
1179 FG_LOG( FG_GENERAL, FG_INFO, ".");
1181 FG_LOG( FG_GENERAL, FG_INFO, "");
1185 if ( fgGetBool("/sim/sound") ) {
1186 audio_sched = new slScheduler ( 8000 );
1187 audio_mixer = new smMixer;
1188 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1189 audio_sched -> setSafetyMargin ( 1.0 ) ;
1191 FGPath slfile( globals->get_fg_root() );
1192 slfile.append( "Sounds/wasp.wav" );
1194 s1 = new slSample ( (char *)slfile.c_str() );
1195 FG_LOG( FG_GENERAL, FG_INFO,
1196 "Rate = " << s1 -> getRate()
1197 << " Bps = " << s1 -> getBps()
1198 << " Stereo = " << s1 -> getStereo() );
1199 audio_sched -> loopSample ( s1 );
1201 if ( audio_sched->not_working() ) {
1204 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1205 volume_envelope.setStep ( 0, 0.01, 0.6 );
1207 audio_sched -> addSampleEnvelope( s1, 0, 0,
1209 SL_PITCH_ENVELOPE );
1210 audio_sched -> addSampleEnvelope( s1, 0, 1,
1212 SL_VOLUME_ENVELOPE );
1215 // strcpy(slfile, path);
1216 // strcat(slfile, "thunder.wav");
1217 // s2 -> loadFile ( slfile );
1218 // s2 -> adjustVolume(0.5);
1219 // audio_sched -> playSample ( s2 );
1226 cout << "Panel visible = " << fgPanelVisible() << endl;
1227 fgReshape( fgGetInt("/sim/startup/xsize"),
1228 fgGetInt("/sim/startup/ysize") );
1231 if ( idle_state == 1000 ) {
1232 // We've finished all our initialization steps, from now on we
1233 // run the main loop.
1237 if ( fgGetBool("/sim/startup/splash-screen") ) {
1238 fgSplashUpdate(0.0);
1243 // options.cxx needs to see this for toggle_panel()
1244 // Handle new window size or exposure
1245 void fgReshape( int width, int height ) {
1247 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1248 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1249 globals->get_viewmgr()->get_view(i)->
1250 set_win_ratio( (float)height / (float)width );
1253 int((current_panel->getViewHeight() -
1254 current_panel->getYOffset())
1255 * (height / 768.0)) + 1;
1256 globals->get_viewmgr()->get_view(i)->
1257 set_win_ratio( (float)view_h / (float)width );
1261 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1262 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1265 int((current_panel->getViewHeight() - current_panel->getYOffset())
1266 * (height / 768.0)) + 1;
1267 glViewport(0, (GLint)(height - view_h),
1268 (GLint)(width), (GLint)(view_h) );
1271 fgSetInt("/sim/startup/xsize", width);
1272 fgSetInt("/sim/startup/ysize", height);
1274 float fov = globals->get_current_view()->get_fov();
1275 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1281 // Initialize GLUT and define a main window
1282 int fgGlutInit( int *argc, char **argv ) {
1284 #if !defined( macintosh )
1285 // GLUT will extract all glut specific options so later on we only
1286 // need wory about our own.
1287 glutInit(argc, argv);
1290 // Define Display Parameters
1291 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1293 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1294 fgGetInt("/sim/startup/xsize") << "x"
1295 << fgGetInt("/sim/startup/ysize") );
1297 // Define initial window size
1298 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1299 fgGetInt("/sim/startup/ysize") );
1301 // Initialize windows
1302 if ( !fgGetBool("/sim/startup/game-mode")) {
1303 // Open the regular window
1304 glutCreateWindow("FlightGear");
1305 #ifndef GLUT_WRONG_VERSION
1307 // Open the cool new 'game mode' window
1308 char game_mode_str[256];
1309 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1310 fgGetInt("/sim/startup/xsize"),
1311 fgGetInt("/sim/startup/ysize"),
1312 fgGetInt("/sim/rendering/bits-per-pixel"));
1314 FG_LOG( FG_GENERAL, FG_INFO,
1315 "game mode params = " << game_mode_str );
1316 glutGameModeString( game_mode_str );
1317 glutEnterGameMode();
1321 // This seems to be the absolute earliest in the init sequence
1322 // that these calls will return valid info. Too bad it's after
1323 // we've already created and sized out window. :-(
1324 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1325 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1326 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1327 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1330 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1331 general.set_glMaxTexSize( tmp );
1332 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1334 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1335 general.set_glDepthBits( tmp );
1336 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1342 // Initialize GLUT event handlers
1343 int fgGlutInitEvents( void ) {
1344 // call fgReshape() on window resizes
1345 glutReshapeFunc( fgReshape );
1347 // call GLUTkey() on keyboard event
1348 glutKeyboardFunc( GLUTkey );
1349 glutSpecialFunc( GLUTspecialkey );
1351 // call guiMouseFunc() whenever our little rodent is used
1352 glutMouseFunc ( guiMouseFunc );
1353 glutMotionFunc (guiMotionFunc );
1354 glutPassiveMotionFunc (guiMotionFunc );
1356 // call fgMainLoop() whenever there is
1357 // nothing else to do
1358 glutIdleFunc( fgIdleFunction );
1361 glutDisplayFunc( fgRenderFrame );
1368 int main( int argc, char **argv ) {
1370 #if defined( macintosh )
1371 freopen ("stdout.txt", "w", stdout );
1372 freopen ("stderr.txt", "w", stderr );
1373 argc = ccommand( &argv );
1377 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1380 // set default log levels
1381 fglog().setLogLevels( FG_ALL, FG_INFO );
1384 #ifdef FLIGHTGEAR_VERSION
1385 version = FLIGHTGEAR_VERSION;
1387 version = "unknown version";
1389 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1390 << version << endl );
1392 // Allocate global data structures. This needs to happen before
1393 // we parse command line options
1395 SGPropertyNode *props = new SGPropertyNode;
1396 globals = new FGGlobals;
1397 globals->set_props( props );
1399 // seed the random number generater
1402 SGRoute *route = new SGRoute;
1403 globals->set_route( route );
1405 FGViewMgr *viewmgr = new FGViewMgr;
1406 globals->set_viewmgr( viewmgr );
1408 FGViewerRPH *pv = new FGViewerRPH;
1409 globals->get_viewmgr()->add_view( pv );
1411 FGViewerLookAt *chase = new FGViewerLookAt;
1412 globals->get_viewmgr()->add_view( chase );
1414 string_list *col = new string_list;
1415 globals->set_channel_options_list( col );
1417 // set current view to 0 (first) which is our main pilot view
1418 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1420 // Scan the config file(s) and command line options to see if
1421 // fg_root was specified (ignore all other options for now)
1422 fgInitFGRoot(argc, argv);
1424 // Initialize the Aircraft directory to "" (UIUC)
1427 // Load the configuration parameters
1428 if ( !fgInitConfig(argc, argv) ) {
1429 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1433 // Initialize the Window/Graphics environment.
1434 if( !fgGlutInit(&argc, argv) ) {
1435 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1439 // Initialize the various GLUT Event Handlers.
1440 if( !fgGlutInitEvents() ) {
1441 FG_LOG( FG_GENERAL, FG_ALERT,
1442 "GLUT event handler initialization failed ..." );
1446 // Initialize ssg (from plib). Needs to come before we do any
1447 // other ssg stuff, but after opengl/glut has been initialized.
1450 // Initialize the user interface (we need to do this before
1451 // passing off control to glut and before fgInitGeneral to get our
1455 // set current_options lon/lat if an airport id is specified
1456 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1457 if ( fgGetString("/sim/startup/airport-id").length() ) {
1458 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1459 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1460 fgGetDouble("/orientation/heading") );
1464 FGPath zone( globals->get_fg_root() );
1465 zone.append( "Timezone" );
1466 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1467 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1470 // Handle potential user specified time offsets
1471 time_t cur_time = t->get_cur_time();
1472 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1473 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1474 time_t aircraftLocalTime =
1475 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1477 // Okay, we now have six possible scenarios
1478 int offset = fgGetInt("/sim/startup/time-offset");
1479 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1480 if (offset_type == "system-offset") {
1481 globals->set_warp( offset );
1482 } else if (offset_type == "gmt-offset") {
1483 globals->set_warp( offset - (currGMT - systemLocalTime) );
1484 } else if (offset_type == "latitude-offset") {
1485 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1486 } else if (offset_type == "system") {
1487 globals->set_warp( offset - cur_time );
1488 } else if (offset_type == "gmt") {
1489 globals->set_warp( offset - currGMT );
1490 } else if (offset_type == "latitude") {
1491 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1494 FG_LOG( FG_GENERAL, FG_ALERT,
1495 "Unsupported offset type " << offset_type );
1499 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1500 << globals->get_warp() );
1502 globals->set_warp_delta( 0 );
1504 t->update( 0.0, 0.0, globals->get_warp() );
1506 globals->set_time_params( t );
1508 // Do some quick general initializations
1509 if( !fgInitGeneral()) {
1510 FG_LOG( FG_GENERAL, FG_ALERT,
1511 "General initializations failed ..." );
1515 FGPath modelpath( globals->get_fg_root() );
1516 ssgModelPath( (char *)modelpath.c_str() );
1519 scene = new ssgRoot;
1520 scene->setName( "Scene" );
1522 lighting = new ssgRoot;
1523 lighting->setName( "Lighting" );
1525 // Initialize the sky
1526 FGPath ephem_data_path( globals->get_fg_root() );
1527 ephem_data_path.append( "Astro" );
1528 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1529 ephem->update( globals->get_time_params()->getMjd(),
1530 globals->get_time_params()->getLst(),
1532 globals->set_ephem( ephem );
1534 FGPath sky_tex_path( globals->get_fg_root() );
1535 sky_tex_path.append( "Textures" );
1536 sky_tex_path.append( "Sky" );
1538 thesky->texture_path( sky_tex_path.str() );
1540 thesky->build( 550.0, 550.0,
1541 globals->get_ephem()->getNumPlanets(),
1542 globals->get_ephem()->getPlanets(), 60000.0,
1543 globals->get_ephem()->getNumStars(),
1544 globals->get_ephem()->getStars(), 60000.0 );
1546 if ( fgGetBool("/environment/clouds/status") ) {
1547 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1548 SG_CLOUD_MOSTLY_SUNNY );
1549 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1551 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1552 // SG_CLOUD_MOSTLY_SUNNY );
1553 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1554 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1557 // Initialize MagVar model
1558 SGMagVar *magvar = new SGMagVar();
1559 globals->set_mag( magvar );
1562 terrain = new ssgBranch;
1563 terrain->setName( "Terrain" );
1564 scene->addKid( terrain );
1567 ground = new ssgBranch;
1568 ground->setName( "Ground Lighting" );
1569 lighting->addKid( ground );
1571 airport = new ssgBranch;
1572 airport->setName( "Airport Lighting" );
1573 lighting->addKid( airport );
1575 // temporary visible aircraft "own ship"
1576 acmodel_selector = new ssgSelector;
1577 acmodel_pos = new ssgTransform;
1579 string acmodel_path =
1580 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1582 string full_model = globals->get_fg_root() + "/"
1584 int pos = full_model.rfind("/");
1586 FGPath texturepath( full_model.substr(0, pos) );
1587 cout << "Texture path = " << texturepath.str() << endl;
1588 ssgTexturePath( (char *)texturepath.c_str() );
1590 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1592 // find moving parts (if this is an MDL model)
1593 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1594 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1596 acmodel_npropsettings = 0;
1597 if (prop_selector != NULL) {
1598 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1599 kid = prop_selector->getNextKid()) {
1600 int prop_low, prop_high;
1601 if ( sscanf(kid->getName(), "PROP_%d_%d",
1602 &prop_low, &prop_high) == 2 ) {
1603 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1604 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1605 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1606 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1607 acmodel_npropsettings++;
1609 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1615 // align the model properly for FGFS
1616 ssgTransform *acmodel_align = new ssgTransform;
1617 acmodel_align->addKid(acmodel_obj);
1621 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1622 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1623 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1624 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1625 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1626 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1627 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1628 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1629 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1630 acmodel_align->setTransform(res_matrix);
1632 acmodel_pos->addKid( acmodel_align );
1633 acmodel_selector->addKid( acmodel_pos );
1634 //ssgFlatten( acmodel_obj );
1635 //ssgStripify( acmodel_selector );
1636 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1637 scene->addKid( acmodel_selector );
1639 // $$$ begin - added VS Renganthan 17 Oct 2K
1641 // $$$ end - added VS Renganthan 17 Oct 2K
1643 #ifdef FG_NETWORK_OLK
1644 // Do the network intialization
1645 if ( fgGetBool("/sim/networking/network-olk") ) {
1646 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1650 // build our custom render states
1651 fgBuildRenderStates();
1653 // pass control off to the master GLUT event handler
1656 // we never actually get here ... but to avoid compiler warnings,
1662 // $$$ end - added VS Renganathan, 15 Oct 2K
1663 // - added Venky , 12 Nov 2K
1665 void fgLoadDCS(void) {
1667 ssgEntity *ship_obj = NULL;
1670 char obj_filename[25];
1672 for (int k=0;k<32;k++)
1677 FGPath tile_path( globals->get_fg_root());
1678 tile_path.append( "Scenery" );
1679 tile_path.append( "Objects.txt" );
1680 fg_gzifstream in( tile_path.str() );
1681 if ( ! in.is_open() ) {
1682 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1685 FGPath modelpath( globals->get_fg_root() );
1686 modelpath.append( "Models" );
1687 modelpath.append( "Geometry" );
1689 FGPath texturepath( globals->get_fg_root() );
1690 texturepath.append( "Models" );
1691 texturepath.append( "Textures" );
1693 ssgModelPath( (char *)modelpath.c_str() );
1694 ssgTexturePath( (char *)texturepath.c_str() );
1696 ship_sel = new ssgSelector;
1699 while ( ! in.eof() )
1702 if ( in.get( c ) && c == '#' )
1709 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1710 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1711 int chj=getchar();*/
1713 obj_lon[objc] *=DEG_TO_RAD;
1714 obj_lat[objc] *=DEG_TO_RAD;
1716 ship_pos[objc] = new ssgTransform;
1719 // type "repeat" in objects.txt to load one more instance of the last object.
1721 if ( strcmp(obj_filename,"repeat") != 0)
1722 ship_obj = ssgLoadOBJ( obj_filename );
1724 if ( ship_obj != NULL )
1726 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1727 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1730 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1732 if (in.eof()) break;
1737 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1738 scene->addKid( ship_sel ); //add selector node to root node
1743 void fgUpdateDCS (void) {
1745 // double eye_lat,eye_lon,eye_alt;
1746 // static double obj_head;
1747 double sl_radius,obj_latgc;
1748 // float nresultmat[4][4];
1749 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1752 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1753 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1755 // Deck should be the first object in objects.txt in case of fdm=ada
1757 if (fgGetString("/sim/flight-model") == "ada")
1759 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1760 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1761 obj_alt[0] = fdm->get_aux7();
1764 for (int m=0; m<=objc; m++)
1766 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1769 //Geodetic to Geocentric angles for rotation
1770 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1772 //moving object gbs-posn in cartesian coords
1773 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1774 Point3D obj_pos = sgGeodToCart( obj_posn );
1776 // Translate moving object w.r.t eye
1777 Point3D Objtrans = obj_pos-scenery.center;
1782 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1785 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1787 sgVec3 ship_fwd,ship_rt,ship_up;
1788 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1789 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1790 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1792 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1793 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1794 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1795 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1798 sgCopyMat4( sgTUX, sgROT_hdg );
1799 sgPostMultMat4( sgTUX, sgROT_lat );
1800 sgPostMultMat4( sgTUX, sgROT_lon );
1801 sgPostMultMat4( sgTUX, sgTRANS );
1804 sgSetCoord(&shippos, sgTUX );
1805 ship_pos[m]->setTransform( &shippos );
1807 if ( ship_sel != NULL )
1808 ship_sel->select(0xFFFFFFFF);
1811 // $$$ end - added VS Renganathan, 15 Oct 2K
1812 // added Venky , 12 Nov 2K