1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #ifdef FG_MATH_EXCEPTION_CLASH
38 #include <simgear/xgl/xgl.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
59 #ifdef ENABLE_AUDIO_SUPPORT
64 #include <simgear/constants.h> // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/sg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
73 #include <Include/general.hxx>
75 #include <Aircraft/aircraft.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/light.hxx>
93 #include <Time/sunpos.hxx>
94 #include <Time/tmp.hxx>
96 // begin - added Venky
97 // $$$ begin - added VS Renganathan
98 #include <simgear/misc/fgstream.hxx>
99 #include <FDM/flight.hxx>
100 #include <FDM/ADA.hxx>
101 void fgLoadDCS (void);
102 void fgUpdateDCS (void);
103 ssgSelector *ship_sel=NULL;
104 // upto 32 instances of a same object can be loaded.
105 ssgTransform *ship_pos[32];
106 double obj_lat[32],obj_lon[32],obj_alt[32];
108 // $$$ end - added VS Renganathan
111 #ifndef FG_OLD_WEATHER
112 # include <WeatherCM/FGLocalWeatherDatabase.h>
114 # include <Weather/weather.hxx>
120 #include "fg_init.hxx"
122 #include "globals.hxx"
123 #include "keyboard.hxx"
124 #include "splash.hxx"
127 # include <console.h> // -dw- for command line dialog
131 // This is a record containing a bit of global housekeeping information
134 // Specify our current idle function state. This is used to run all
135 // our initializations out of the glutIdleLoop() so that we can get a
136 // splash screen up and running right away.
137 static int idle_state = 0;
138 static int global_multi_loop;
140 // attempt to avoid a large bounce at startup
141 static bool initial_freeze = true;
143 // forward declaration
144 void fgReshape( int width, int height );
146 // Global structures for the Audio library
147 #ifdef ENABLE_AUDIO_SUPPORT
148 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
149 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
150 slScheduler *audio_sched;
151 smMixer *audio_mixer;
158 ssgRoot *scene = NULL;
159 ssgBranch *terrain = NULL;
161 // aircraft model stuff
162 ssgSelector *acmodel_selector = NULL;
163 ssgTransform *acmodel_pos = NULL;
164 ssgSelector *prop_selector = NULL;
165 ssgSelector *flaps_selector = NULL;
166 int acmodel_npropsettings;
167 int acmodel_proprpms[4][2]; // different propeller settings
169 ssgRoot *lighting = NULL;
170 ssgBranch *ground = NULL;
171 ssgBranch *airport = NULL;
173 #ifdef FG_NETWORK_OLK
174 ssgSelector *fgd_sel = NULL;
175 ssgTransform *fgd_pos = NULL;
178 // current fdm/position used for view
179 FGInterface cur_view_fdm;
185 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
187 { 1.0f, 0.0f, 0.0f, 0.0f },
188 { 0.0f, 0.0f, -1.0f, 0.0f },
189 { 0.0f, 1.0f, 0.0f, 0.0f },
190 { 0.0f, 0.0f, 0.0f, 1.0f }
193 // The following defines flightgear options. Because glutlib will also
194 // want to parse its own options, those options must not be included here
195 // or they will get parsed by the main program option parser. Hence case
196 // is significant for any option added that might be in conflict with
199 // glutlib parses for:
201 // -direct (invalid in Win32)
205 // -indirect (invalid in Win32)
208 // Note that glutlib depends upon strings while this program's
209 // option parser wants only initial characters followed by numbers
214 ssgSimpleState *default_state;
215 ssgSimpleState *hud_and_panel;
216 ssgSimpleState *menus;
218 void fgBuildRenderStates( void ) {
219 default_state = new ssgSimpleState;
220 default_state->ref();
221 default_state->disable( GL_TEXTURE_2D );
222 default_state->enable( GL_CULL_FACE );
223 default_state->enable( GL_COLOR_MATERIAL );
224 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
225 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
226 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
227 default_state->disable( GL_BLEND );
228 default_state->disable( GL_ALPHA_TEST );
229 default_state->disable( GL_LIGHTING );
231 hud_and_panel = new ssgSimpleState;
232 hud_and_panel->ref();
233 hud_and_panel->disable( GL_CULL_FACE );
234 hud_and_panel->disable( GL_TEXTURE_2D );
235 hud_and_panel->disable( GL_LIGHTING );
236 hud_and_panel->enable( GL_BLEND );
238 menus = new ssgSimpleState;
240 menus->disable( GL_CULL_FACE );
241 menus->disable( GL_TEXTURE_2D );
242 menus->enable( GL_BLEND );
245 // fgFindNode -- a function that finds a named node in an ssg graph
246 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
247 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
249 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
250 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
251 while (kid != NULL) {
252 ssgEntity *n = fgFindNode(kid, name);
256 kid = ((ssgBranch*)node)->getNextKid();
263 // fgInitVisuals() -- Initialize various GL/view parameters
264 void fgInitVisuals( void ) {
267 l = &cur_light_params;
269 #ifndef GLUT_WRONG_VERSION
270 // Go full screen if requested ...
271 if ( fgGetBool("/sim/startup/fullscreen") ) {
276 // If enabled, normal vectors specified with glNormal are scaled
277 // to unit length after transformation. See glNormal.
278 // glEnable( GL_NORMALIZE );
280 glEnable( GL_LIGHTING );
281 glEnable( GL_LIGHT0 );
282 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
285 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
286 ssgGetLight( 0 ) -> setPosition( sunpos );
288 // glFogi (GL_FOG_MODE, GL_LINEAR);
289 glFogi (GL_FOG_MODE, GL_EXP2);
290 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
291 (!fgGetBool("/sim/rendering/shading"))) {
292 // if fastest fog requested, or if flat shading force fastest
293 glHint ( GL_FOG_HINT, GL_FASTEST );
294 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
295 glHint ( GL_FOG_HINT, GL_NICEST );
297 if ( fgGetBool("/sim/rendering/wireframe") ) {
299 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
302 // This is the default anyways, but it can't hurt
303 glFrontFace ( GL_CCW );
306 // glEnable(GL_POINT_SMOOTH);
307 // glEnable(GL_LINE_SMOOTH);
308 // glEnable(GL_POLYGON_SMOOTH);
312 // Update all Visuals (redraws anything graphics related)
313 void fgRenderFrame( void ) {
317 fgLIGHT *l = &cur_light_params;
318 static double last_visibility = -9999;
320 static GLfloat fog_exp_density;
321 static GLfloat fog_exp2_density;
322 static GLfloat fog_exp2_punch_through;
325 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
326 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
327 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
328 // GLfloat mat_shininess[] = { 10.0 };
329 GLbitfield clear_mask;
331 if ( idle_state != 1000 ) {
332 // still initializing, draw the splash screen
333 if ( fgGetBool("/sim/startup/splash-screen") ) {
337 // idle_state is now 1000 meaning we've finished all our
338 // initializations and are running the main loop, so this will
339 // now work without seg faulting the system.
341 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
342 // FG_Altitude * FEET_TO_METER);
344 // this is just a temporary hack, to make me understand Pui
345 // timerText -> setLabel (ctime (&t->cur_time));
348 // calculate our current position in cartesian space
349 scenery.center = scenery.next_center;
350 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
351 // scenery.center.y(), scenery.center.z());
353 FGViewerRPH *pilot_view =
354 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
356 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
357 cur_fdm_state->get_Lat_geocentric(),
358 cur_fdm_state->get_Altitude() *
360 pilot_view->set_sea_level_radius( cur_fdm_state->
361 get_Sea_level_radius() *
363 pilot_view->set_rph( cur_fdm_state->get_Phi(),
364 cur_fdm_state->get_Theta(),
365 cur_fdm_state->get_Psi() );
367 FGViewerLookAt *chase_view =
368 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
370 sgVec3 po; // chase view pilot_offset
371 sgVec3 wup; // chase view world up
372 sgSetVec3( po, 0.0, 0.0, 50.0 );
373 sgCopyVec3( wup, pilot_view->get_world_up() );
374 sgMat4 CXFM; // chase view + pilot offset xform
376 chase_view->get_view_offset() * RAD_TO_DEG -
377 cur_fdm_state->get_Psi() * RAD_TO_DEG,
379 sgVec3 npo; // new pilot offset after rotation
380 sgXformVec3( po, po, pilot_view->get_UP() );
381 sgXformVec3( npo, po, CXFM );
383 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
384 cur_fdm_state->get_Lat_geocentric(),
385 cur_fdm_state->get_Altitude() *
387 chase_view->set_sea_level_radius( cur_fdm_state->
388 get_Sea_level_radius() *
390 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
391 chase_view->set_view_forward( pilot_view->get_view_pos() );
392 chase_view->set_view_up( wup );
396 sgCopyMat4( rph, pilot_view->get_VIEW() );
397 cout << "RPH Matrix = " << endl;
399 for ( i = 0; i < 4; i++ ) {
400 for ( j = 0; j < 4; j++ ) {
401 printf("%10.4f ", rph[i][j]);
407 sgCopyMat4( la, chase_view->get_VIEW() );
408 cout << "LookAt Matrix = " << endl;
409 for ( i = 0; i < 4; i++ ) {
410 for ( j = 0; j < 4; j++ ) {
411 printf("%10.4f ", la[i][j]);
418 fgReshape( fgGetInt("/sim/startup/xsize"),
419 fgGetInt("/sim/startup/ysize") );
424 if ( ! fgPanelVisible() ) {
426 (GLint)(fgGetInt("/sim/startup/xsize")),
427 (GLint)(fgGetInt("/sim/startup/ysize")) );
430 int( (current_panel->getViewHeight() -
431 current_panel->getYOffset())
432 * (fgGetInt("/sim/startup/ysize") / 768.0) );
434 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
435 (GLint)(fgGetInt("/sim/startup/xsize")),
440 // set the sun position
441 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
443 clear_mask = GL_DEPTH_BUFFER_BIT;
444 if ( fgGetBool("/sim/rendering/wireframe") ) {
445 clear_mask |= GL_COLOR_BUFFER_BIT;
448 if ( fgGetBool("/sim/rendering/skyblend") ) {
449 if ( fgGetBool("/sim/rendering/textures") ) {
450 // glClearColor(black[0], black[1], black[2], black[3]);
451 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
452 l->adj_fog_color[2], l->adj_fog_color[3]);
453 clear_mask |= GL_COLOR_BUFFER_BIT;
456 glClearColor(l->sky_color[0], l->sky_color[1],
457 l->sky_color[2], l->sky_color[3]);
458 clear_mask |= GL_COLOR_BUFFER_BIT;
460 glClear( clear_mask );
462 // Tell GL we are switching to model view parameters
464 // I really should create a derived ssg node or use a call
465 // back or something so that I can draw the sky within the
466 // ssgCullAndDraw() function, but for now I just mimic what
467 // ssg does to set up the model view matrix
468 glMatrixMode(GL_MODELVIEW);
470 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
472 // set the opengl state to known default values
473 default_state->force();
475 // update fog params if visibility has changed
476 #ifndef FG_OLD_WEATHER
477 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
479 thesky->set_visibility( current_weather.get_visibility() );
482 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
484 ( global_multi_loop *
485 fgGetInt("/sim/speed-up") ) /
486 (double)fgGetInt("/sim/model-hz") );
488 double actual_visibility = thesky->get_visibility();
489 // cout << "actual visibility = " << actual_visibility << endl;
491 if ( actual_visibility != last_visibility ) {
492 last_visibility = actual_visibility;
494 // cout << "----> updating fog params" << endl;
497 fog_exp_density = -log(0.01 / actual_visibility);
500 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
501 fog_exp2_punch_through = sqrt( -log(0.01) ) /
502 ( actual_visibility * 1.5 );
505 // Set correct opengl fog density
506 glFogf (GL_FOG_DENSITY, fog_exp2_density);
508 // update the sky dome
509 if ( fgGetBool("/sim/rendering/skyblend") ) {
510 /* cout << "thesky->repaint() sky_color = "
511 << cur_light_params.sky_color[0] << " "
512 << cur_light_params.sky_color[1] << " "
513 << cur_light_params.sky_color[2] << " "
514 << cur_light_params.sky_color[3] << endl;
516 << cur_light_params.fog_color[0] << " "
517 << cur_light_params.fog_color[1] << " "
518 << cur_light_params.fog_color[2] << " "
519 << cur_light_params.fog_color[3] << endl;
520 cout << " sun_angle = " << cur_light_params.sun_angle
521 << " moon_angle = " << cur_light_params.moon_angle
523 thesky->repaint( cur_light_params.sky_color,
524 cur_light_params.adj_fog_color,
525 cur_light_params.sun_angle,
526 cur_light_params.moon_angle,
527 globals->get_ephem()->getNumPlanets(),
528 globals->get_ephem()->getPlanets(),
529 globals->get_ephem()->getNumStars(),
530 globals->get_ephem()->getStars() );
532 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
533 << view_pos[1] << " " << view_pos[2] << endl;
534 cout << " zero_elev = " << zero_elev[0] << " "
535 << zero_elev[1] << " " << zero_elev[2]
536 << " lon = " << cur_fdm_state->get_Longitude()
537 << " lat = " << cur_fdm_state->get_Latitude() << endl;
538 cout << " sun_rot = " << cur_light_params.sun_rotation
539 << " gst = " << SGTime::cur_time_params->getGst() << endl;
540 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
541 << " sun dec = " << globals->get_ephem()->getSunDeclination()
542 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
543 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
545 thesky->reposition( globals->get_current_view()->get_view_pos(),
546 globals->get_current_view()->get_zero_elev(),
547 globals->get_current_view()->get_world_up(),
548 cur_fdm_state->get_Longitude(),
549 cur_fdm_state->get_Latitude(),
550 cur_fdm_state->get_Altitude() * FEET_TO_METER,
551 cur_light_params.sun_rotation,
552 globals->get_time_params()->getGst(),
553 globals->get_ephem()->getSunRightAscension(),
554 globals->get_ephem()->getSunDeclination(),
556 globals->get_ephem()->getMoonRightAscension(),
557 globals->get_ephem()->getMoonDeclination(),
561 glEnable( GL_DEPTH_TEST );
562 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
564 glFogi( GL_FOG_MODE, GL_EXP2 );
565 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
568 // set lighting parameters
569 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
570 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
571 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
572 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
573 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
575 // texture parameters
576 // glEnable( GL_TEXTURE_2D );
577 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
578 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
579 // set base color (I don't think this is doing anything here)
580 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
581 // (GL_FRONT, GL_DIFFUSE, white);
582 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
583 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
586 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
587 ssgGetLight( 0 ) -> setPosition( sunpos );
589 // glMatrixMode( GL_PROJECTION );
591 float fov = globals->get_current_view()->get_fov();
592 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
594 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
597 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
598 // << current_weather.get_visibility() );
601 ssgSetNearFar( 10.0f, 120000.0f );
603 ssgSetNearFar( 0.5f, 120000.0f );
606 if ( globals->get_viewmgr()->get_current() == 0 ) {
607 // disable aircraft model
608 acmodel_selector->select(0);
610 // enable aircraft model and set up its position and orientation
611 acmodel_selector->select(1);
613 FGViewerRPH *pilot_view =
614 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
617 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
620 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
623 sgMakeRotMat4( sgROT, -90.0, ownship_up );
627 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
628 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
630 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
632 sgCopyMat4( sgTUX, sgROT );
633 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
634 sgPostMultMat4( sgTUX, sgTRANS );
637 sgSetCoord( &tuxpos, sgTUX );
638 acmodel_pos->setTransform( &tuxpos );
640 // set up moving parts
641 if (flaps_selector != NULL) {
642 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
645 if (prop_selector != NULL) {
646 int propsel_mask = 0;
647 for (int i = 0; i < acmodel_npropsettings; i++) {
648 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
649 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
650 propsel_mask |= 1 << i;
653 prop_selector->select(propsel_mask);
657 // $$$ begin - added VS Renganthan 17 Oct 2K
659 // $$$ end - added VS Renganthan 17 Oct 2K
661 # ifdef FG_NETWORK_OLK
662 if ( fgGetBool("/sim/networking/network-olk") ) {
664 other = head->next; /* put listpointer to start */
665 while ( other != tail) { /* display all except myself */
666 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
667 other->fgd_sel->select(1);
668 sgSetCoord( &fgdpos, other->sgFGD_COORD );
669 other->fgd_pos->setTransform( &fgdpos );
674 // fgd_sel->select(1);
675 // sgCopyMat4( sgTUX, current_view.sgVIEW);
677 // sgSetCoord( &fgdpos, sgFGD_VIEW );
678 // fgd_pos->setTransform( &fgdpos);
682 // position tile nodes and update range selectors
683 global_tile_mgr.prep_ssg_nodes();
685 // draw the sky backdrop
688 // draw the ssg scene
689 glEnable( GL_DEPTH_TEST );
690 ssgCullAndDraw( scene );
692 // change state for lighting here
695 // Set punch through fog density
696 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
698 ssgCullAndDraw( lighting );
700 // draw the sky cloud layers
701 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
703 // display HUD && Panel
705 glDisable( GL_DEPTH_TEST );
706 // glDisable( GL_CULL_FACE );
707 // glDisable( GL_TEXTURE_2D );
709 // update the controls subsystem
712 hud_and_panel->apply();
715 // update the panel subsystem
716 if (current_panel != 0)
717 current_panel->update();
719 // We can do translucent menus, so why not. :-)
721 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
723 // glDisable ( GL_BLEND ) ;
725 // glEnable( GL_FOG );
732 // Update internal time dependent calculations (i.e. flight model)
733 void fgUpdateTimeDepCalcs() {
734 fgLIGHT *l = &cur_light_params;
739 if ( !globals->get_freeze() && !initial_freeze ) {
742 long elapsed = current - cur_fdm_state->get_time_stamp();
743 cur_fdm_state->set_time_stamp( current );
744 elapsed += cur_fdm_state->get_remainder();
745 // cout << "elapsed = " << elapsed << endl;
746 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
747 multi_loop = (int)(((double)elapsed * 0.000001) /
748 cur_fdm_state->get_delta_t() );
749 cur_fdm_state->set_multi_loop( multi_loop );
750 long remainder = elapsed - ( (multi_loop*1000000) *
751 cur_fdm_state->get_delta_t() );
752 cur_fdm_state->set_remainder( remainder );
754 // cout << "multi_loop = " << multi_loop << endl;
755 for ( i = 0; i < multi_loop; ++i ) {
756 // run Autopilot system
757 current_autopilot->run();
760 cur_fdm_state->update( 1 * fgGetInt("/sim/speed-up") );
762 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
764 cur_fdm_state->update( 0 );
765 FGSteam::update( 0 );
767 if ( global_tile_mgr.queue_size() == 0 ) {
768 initial_freeze = false;
772 if ( fgGetString("/sim/view-mode") == "pilot" ) {
773 cur_view_fdm = *cur_fdm_state;
777 // update the view angle
778 FGViewer *v = globals->get_current_view();
779 for ( i = 0; i < multi_loop; i++ ) {
780 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
781 v->set_view_offset( v->get_goal_view_offset() );
784 // move current_view.view_offset towards
785 // current_view.goal_view_offset
786 if ( v->get_goal_view_offset() > v->get_view_offset() )
788 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
789 v->inc_view_offset( 0.01 );
791 v->inc_view_offset( -0.01 );
794 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
795 v->inc_view_offset( -0.01 );
797 v->inc_view_offset( 0.01 );
800 if ( v->get_view_offset() > FG_2PI ) {
801 v->inc_view_offset( -FG_2PI );
802 } else if ( v->get_view_offset() < 0 ) {
803 v->inc_view_offset( FG_2PI );
808 double tmp = -(l->sun_rotation + FG_PI)
809 - (cur_fdm_state->get_Psi() -
810 globals->get_current_view()->get_view_offset() );
811 while ( tmp < 0.0 ) {
814 while ( tmp > FG_2PI ) {
817 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
818 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
819 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
822 // Update solar system
823 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
824 globals->get_time_params()->getLst(),
825 cur_fdm_state->get_Latitude() );
827 // Update radio stack model
828 current_radiostack->update();
832 void fgInitTimeDepCalcs( void ) {
835 // #ifdef HAVE_SETITIMER
836 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
837 // fgUpdateTimeDepCalcs );
838 // #endif HAVE_SETITIMER
842 static const double alt_adjust_ft = 3.758099;
843 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
846 // What should we do when we have nothing else to do? Let's get ready
847 // for the next move and update the display?
848 static void fgMainLoop( void ) {
849 static long remainder = 0;
851 #ifdef FANCY_FRAME_COUNTER
855 static time_t last_time = 0;
856 static int frames = 0;
857 #endif // FANCY_FRAME_COUNTER
859 SGTime *t = globals->get_time_params();
861 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
862 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
864 #ifdef FG_NETWORK_OLK
865 if ( fgGetBool("/sim/networking/network-olk") ) {
866 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
867 // printf("FGD: Netupdate\n");
868 fgd_send_com( "A", FGFS_host); // Send Mat4 data
869 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
874 #if defined( ENABLE_PLIB_JOYSTICK )
875 // Read joystick and update control settings
876 if ( fgGetString("/sim/control-mode") == "joystick" )
880 #elif defined( ENABLE_GLUT_JOYSTICK )
881 // Glut joystick support works by feeding a joystick handler
882 // function to glut. This is taken care of once in the joystick
883 // init routine and we don't have to worry about it again.
886 #ifdef FG_OLD_WEATHER
887 current_weather.Update();
890 // Fix elevation. I'm just sticking this here for now, it should
891 // probably move eventually
893 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
895 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
896 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
898 if ( scenery.cur_elev > -9990 ) {
899 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
900 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
901 // now set aircraft altitude above ground
902 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
903 cur_fdm_state->get_Altitude() * FEET_TO_METER,
904 scenery.cur_elev + alt_adjust_m - 3.0,
905 scenery.cur_elev + alt_adjust_m );
906 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
907 scenery.cur_elev + alt_adjust_m );
909 FG_LOG( FG_ALL, FG_DEBUG,
910 "<*> resetting altitude to "
911 << cur_fdm_state->get_Altitude() * FEET_TO_METER
916 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
918 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
919 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
922 if ( globals->get_warp_delta() != 0 ) {
923 globals->inc_warp( globals->get_warp_delta() );
926 t->update( cur_fdm_state->get_Longitude(),
927 cur_fdm_state->get_Latitude(),
928 globals->get_warp() );
930 if ( globals->get_warp_delta() != 0 ) {
931 fgUpdateSkyAndLightingParams();
934 // update magvar model
935 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
936 cur_fdm_state->get_Latitude(),
937 cur_fdm_state->get_Altitude()* FEET_TO_METER,
938 globals->get_time_params()->getJD() );
940 // Get elapsed time (in usec) for this past frame
941 elapsed = fgGetTimeInterval();
942 FG_LOG( FG_ALL, FG_DEBUG,
943 "Elapsed time interval is = " << elapsed
944 << ", previous remainder is = " << remainder );
946 // Calculate frame rate average
947 #ifdef FANCY_FRAME_COUNTER
948 /* old fps calculation */
952 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
953 tmp = general.get_frame(i);
955 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
956 general.set_frame(i+1,tmp);
958 tmp = 1000000.0 / (float)elapsed;
959 general.set_frame(0,tmp);
960 // printf("frame[0] = %.2f\n", general.frames[0]);
962 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
963 // printf("ave = %.2f\n", general.frame_rate);
966 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
967 general.set_frame_rate( frames );
968 FG_LOG( FG_ALL, FG_DEBUG,
969 "--> Frame rate is = " << general.get_frame_rate() );
972 last_time = t->get_cur_time();
978 // Calculate model iterations needed for next frame
979 elapsed += remainder;
981 global_multi_loop = (int)(((double)elapsed * 0.000001) *
982 fgGetInt("/sim/model-hz"));
983 remainder = elapsed - ( (global_multi_loop*1000000) /
984 fgGetInt("/sim/model-hz") );
985 FG_LOG( FG_ALL, FG_DEBUG,
986 "Model iterations needed = " << global_multi_loop
987 << ", new remainder = " << remainder );
990 if ( global_multi_loop > 0 ) {
991 fgUpdateTimeDepCalcs();
993 FG_LOG( FG_ALL, FG_DEBUG,
994 "Elapsed time is zero ... we're zinging" );
997 #if ! defined( macintosh )
998 // Do any I/O channel work that might need to be done
1002 // see if we need to load any new scenery tiles
1003 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1004 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1006 // Process/manage pending events
1007 global_events.Process();
1009 // Run audio scheduler
1010 #ifdef ENABLE_AUDIO_SUPPORT
1011 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1013 if ( fgGetString("/sim/aircraft") == "c172" ) {
1014 // pitch corresponds to rpm
1015 // volume corresponds to manifold pressure
1018 if ( cur_fdm_state->get_engine(0) != NULL ) {
1019 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1023 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1026 double pitch = 0.3 + rpm_factor * 3.0;
1028 // don't run at absurdly slow rates -- not realistic
1029 // and sounds bad to boot. :-)
1030 if (pitch < 0.7) { pitch = 0.7; }
1031 if (pitch > 5.0) { pitch = 5.0; }
1032 // cout << "pitch = " << pitch << endl;
1035 if ( cur_fdm_state->get_engine(0) != NULL ) {
1037 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
1042 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1045 double volume = mp_factor;
1047 if ( volume < 0.3 ) { volume = 0.3; }
1048 if ( volume > 2.0 ) { volume = 2.0; }
1049 // cout << "volume = " << volume << endl;
1051 pitch_envelope.setStep ( 0, 0.01, pitch );
1052 volume_envelope.setStep ( 0, 0.01, volume );
1054 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1055 pitch_envelope.setStep ( 0, 0.01, param );
1056 volume_envelope.setStep ( 0, 0.01, param );
1059 audio_sched -> update();
1066 FG_LOG( FG_ALL, FG_DEBUG, "" );
1070 // This is the top level master main function that is registered as
1071 // our idle funciton
1074 // The first few passes take care of initialization things (a couple
1075 // per pass) and once everything has been initialized fgMainLoop from
1078 static void fgIdleFunction ( void ) {
1079 // printf("idle state == %d\n", idle_state);
1081 if ( idle_state == 0 ) {
1082 // Initialize the splash screen right away
1083 if ( fgGetBool("/sim/startup/splash-screen") ) {
1088 } else if ( idle_state == 1 ) {
1089 // Start the intro music
1091 if ( fgGetBool("/sim/startup/intro-music") ) {
1092 string lockfile = "/tmp/mpg123.running";
1093 FGPath mp3file( globals->get_fg_root() );
1094 mp3file.append( "Sounds/intro.mp3" );
1096 string command = "(touch " + lockfile + "; mpg123 "
1097 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1099 FG_LOG( FG_GENERAL, FG_INFO,
1100 "Starting intro music: " << mp3file.str() );
1101 system ( command.c_str() );
1106 } else if ( idle_state == 2 ) {
1107 // These are a few miscellaneous things that aren't really
1108 // "subsystems" but still need to be initialized.
1111 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1112 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1117 } else if ( idle_state == 3 ) {
1118 // This is the top level init routine which calls all the
1119 // other subsystem initialization routines. If you are adding
1120 // a subsystem to flightgear, its initialization call should
1121 // located in this routine.
1122 if( !fgInitSubsystems()) {
1123 FG_LOG( FG_GENERAL, FG_ALERT,
1124 "Subsystem initializations failed ..." );
1129 } else if ( idle_state == 4 ) {
1130 // setup OpenGL view parameters
1134 } else if ( idle_state == 5 ) {
1137 } else if ( idle_state == 6 ) {
1138 // Initialize audio support
1139 #ifdef ENABLE_AUDIO_SUPPORT
1142 if ( fgGetBool("/sim/startup/intro-music") ) {
1143 // Let's wait for mpg123 to finish
1144 string lockfile = "/tmp/mpg123.running";
1145 struct stat stat_buf;
1147 FG_LOG( FG_GENERAL, FG_INFO,
1148 "Waiting for mpg123 player to finish ..." );
1149 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1150 // file exist, wait ...
1152 FG_LOG( FG_GENERAL, FG_INFO, ".");
1154 FG_LOG( FG_GENERAL, FG_INFO, "");
1158 if ( fgGetBool("/sim/sound") ) {
1159 audio_sched = new slScheduler ( 8000 );
1160 audio_mixer = new smMixer;
1161 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1162 audio_sched -> setSafetyMargin ( 1.0 ) ;
1164 FGPath slfile( globals->get_fg_root() );
1165 slfile.append( "Sounds/wasp.wav" );
1167 s1 = new slSample ( (char *)slfile.c_str() );
1168 FG_LOG( FG_GENERAL, FG_INFO,
1169 "Rate = " << s1 -> getRate()
1170 << " Bps = " << s1 -> getBps()
1171 << " Stereo = " << s1 -> getStereo() );
1172 audio_sched -> loopSample ( s1 );
1174 if ( audio_sched->not_working() ) {
1177 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1178 volume_envelope.setStep ( 0, 0.01, 0.6 );
1180 audio_sched -> addSampleEnvelope( s1, 0, 0,
1182 SL_PITCH_ENVELOPE );
1183 audio_sched -> addSampleEnvelope( s1, 0, 1,
1185 SL_VOLUME_ENVELOPE );
1188 // strcpy(slfile, path);
1189 // strcat(slfile, "thunder.wav");
1190 // s2 -> loadFile ( slfile );
1191 // s2 -> adjustVolume(0.5);
1192 // audio_sched -> playSample ( s2 );
1199 cout << "Panel visible = " << fgPanelVisible() << endl;
1200 fgReshape( fgGetInt("/sim/startup/xsize"),
1201 fgGetInt("/sim/startup/ysize") );
1204 if ( idle_state == 1000 ) {
1205 // We've finished all our initialization steps, from now on we
1206 // run the main loop.
1210 if ( fgGetBool("/sim/startup/splash-screen") ) {
1211 fgSplashUpdate(0.0);
1216 // options.cxx needs to see this for toggle_panel()
1217 // Handle new window size or exposure
1218 void fgReshape( int width, int height ) {
1220 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1221 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1222 globals->get_viewmgr()->get_view(i)->
1223 set_win_ratio( (float)height / (float)width );
1226 int((current_panel->getViewHeight() -
1227 current_panel->getYOffset())
1228 * (height / 768.0)) + 1;
1229 globals->get_viewmgr()->get_view(i)->
1230 set_win_ratio( (float)view_h / (float)width );
1234 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1235 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1238 int((current_panel->getViewHeight() - current_panel->getYOffset())
1239 * (height / 768.0)) + 1;
1240 glViewport(0, (GLint)(height - view_h),
1241 (GLint)(width), (GLint)(view_h) );
1244 fgSetInt("/sim/startup/xsize", width);
1245 fgSetInt("/sim/startup/ysize", height);
1247 float fov = globals->get_current_view()->get_fov();
1248 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1254 // Initialize GLUT and define a main window
1255 int fgGlutInit( int *argc, char **argv ) {
1257 #if !defined( macintosh )
1258 // GLUT will extract all glut specific options so later on we only
1259 // need wory about our own.
1260 glutInit(argc, argv);
1263 // Define Display Parameters
1264 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1266 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1267 fgGetInt("/sim/startup/xsize") << "x"
1268 << fgGetInt("/sim/startup/ysize") );
1270 // Define initial window size
1271 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1272 fgGetInt("/sim/startup/ysize") );
1274 // Initialize windows
1275 if ( !fgGetBool("/sim/startup/game-mode")) {
1276 // Open the regular window
1277 glutCreateWindow("FlightGear");
1278 #ifndef GLUT_WRONG_VERSION
1280 // Open the cool new 'game mode' window
1281 char game_mode_str[256];
1282 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1283 fgGetInt("/sim/startup/xsize"),
1284 fgGetInt("/sim/startup/ysize"),
1285 fgGetInt("/sim/rendering/bits-per-pixel"));
1287 FG_LOG( FG_GENERAL, FG_INFO,
1288 "game mode params = " << game_mode_str );
1289 glutGameModeString( game_mode_str );
1290 glutEnterGameMode();
1294 // This seems to be the absolute earliest in the init sequence
1295 // that these calls will return valid info. Too bad it's after
1296 // we've already created and sized out window. :-(
1297 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1298 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1299 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1300 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1303 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1304 general.set_glMaxTexSize( tmp );
1305 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1307 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1308 general.set_glDepthBits( tmp );
1309 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1315 // Initialize GLUT event handlers
1316 int fgGlutInitEvents( void ) {
1317 // call fgReshape() on window resizes
1318 glutReshapeFunc( fgReshape );
1320 // call GLUTkey() on keyboard event
1321 glutKeyboardFunc( GLUTkey );
1322 glutSpecialFunc( GLUTspecialkey );
1324 // call guiMouseFunc() whenever our little rodent is used
1325 glutMouseFunc ( guiMouseFunc );
1326 glutMotionFunc (guiMotionFunc );
1327 glutPassiveMotionFunc (guiMotionFunc );
1329 // call fgMainLoop() whenever there is
1330 // nothing else to do
1331 glutIdleFunc( fgIdleFunction );
1334 glutDisplayFunc( fgRenderFrame );
1341 int main( int argc, char **argv ) {
1343 #if defined( macintosh )
1344 freopen ("stdout.txt", "w", stdout );
1345 freopen ("stderr.txt", "w", stderr );
1346 argc = ccommand( &argv );
1350 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1353 // set default log levels
1354 fglog().setLogLevels( FG_ALL, FG_INFO );
1357 #ifdef FLIGHTGEAR_VERSION
1358 version = FLIGHTGEAR_VERSION;
1360 version = "unknown version";
1362 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1363 << version << endl );
1365 // Allocate global data structures. This needs to happen before
1366 // we parse command line options
1368 SGPropertyNode *props = new SGPropertyNode;
1369 globals = new FGGlobals;
1370 globals->set_props( props );
1372 // seed the random number generater
1375 SGRoute *route = new SGRoute;
1376 globals->set_route( route );
1378 FGViewMgr *viewmgr = new FGViewMgr;
1379 globals->set_viewmgr( viewmgr );
1381 FGViewerRPH *pv = new FGViewerRPH;
1382 globals->get_viewmgr()->add_view( pv );
1384 FGViewerLookAt *chase = new FGViewerLookAt;
1385 globals->get_viewmgr()->add_view( chase );
1387 // set current view to 0 (first) which is our main pilot view
1388 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1390 // Scan the config file(s) and command line options to see if
1391 // fg_root was specified (ignore all other options for now)
1392 fgInitFGRoot(argc, argv);
1394 // Initialize the Aircraft directory to "" (UIUC)
1397 // Load the configuration parameters
1398 if ( !fgInitConfig(argc, argv) ) {
1399 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1403 // Initialize the Window/Graphics environment.
1404 if( !fgGlutInit(&argc, argv) ) {
1405 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1409 // Initialize the various GLUT Event Handlers.
1410 if( !fgGlutInitEvents() ) {
1411 FG_LOG( FG_GENERAL, FG_ALERT,
1412 "GLUT event handler initialization failed ..." );
1416 // Initialize ssg (from plib). Needs to come before we do any
1417 // other ssg stuff, but after opengl/glut has been initialized.
1420 // Initialize the user interface (we need to do this before
1421 // passing off control to glut and before fgInitGeneral to get our
1425 // set current_options lon/lat if an airport id is specified
1426 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1427 if ( fgGetString("/sim/startup/airport-id").length() ) {
1428 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1429 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1430 fgGetDouble("/orientation/heading") );
1434 FGPath zone( globals->get_fg_root() );
1435 zone.append( "Timezone" );
1436 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1437 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1440 // Handle potential user specified time offsets
1441 time_t cur_time = t->get_cur_time();
1442 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1443 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1444 time_t aircraftLocalTime =
1445 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1447 // Okay, we now have six possible scenarios
1448 int offset = fgGetInt("/sim/startup/time-offset");
1449 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1450 if (offset_type == "system-offset") {
1451 globals->set_warp( offset );
1452 } else if (offset_type == "gmt-offset") {
1453 globals->set_warp( offset - (currGMT - systemLocalTime) );
1454 } else if (offset_type == "latitude-offset") {
1455 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1456 } else if (offset_type == "system") {
1457 globals->set_warp( offset - cur_time );
1458 } else if (offset_type == "gmt") {
1459 globals->set_warp( offset - currGMT );
1460 } else if (offset_type == "latitude") {
1461 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1464 FG_LOG( FG_GENERAL, FG_ALERT,
1465 "Unsupported offset type " << offset_type );
1469 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1470 << globals->get_warp() );
1472 globals->set_warp_delta( 0 );
1474 t->update( 0.0, 0.0, globals->get_warp() );
1476 globals->set_time_params( t );
1478 // Do some quick general initializations
1479 if( !fgInitGeneral()) {
1480 FG_LOG( FG_GENERAL, FG_ALERT,
1481 "General initializations failed ..." );
1485 FGPath modelpath( globals->get_fg_root() );
1486 ssgModelPath( (char *)modelpath.c_str() );
1489 scene = new ssgRoot;
1490 scene->setName( "Scene" );
1492 lighting = new ssgRoot;
1493 lighting->setName( "Lighting" );
1495 // Initialize the sky
1496 FGPath ephem_data_path( globals->get_fg_root() );
1497 ephem_data_path.append( "Astro" );
1498 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1499 ephem->update( globals->get_time_params()->getMjd(),
1500 globals->get_time_params()->getLst(),
1502 globals->set_ephem( ephem );
1504 FGPath sky_tex_path( globals->get_fg_root() );
1505 sky_tex_path.append( "Textures" );
1506 sky_tex_path.append( "Sky" );
1508 thesky->texture_path( sky_tex_path.str() );
1510 thesky->build( 550.0, 550.0,
1511 globals->get_ephem()->getNumPlanets(),
1512 globals->get_ephem()->getPlanets(), 60000.0,
1513 globals->get_ephem()->getNumStars(),
1514 globals->get_ephem()->getStars(), 60000.0 );
1516 if ( fgGetBool("/environment/clouds/status") ) {
1517 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1518 SG_CLOUD_MOSTLY_SUNNY );
1519 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1521 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1522 // SG_CLOUD_MOSTLY_SUNNY );
1523 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1524 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1527 // Initialize MagVar model
1528 SGMagVar *magvar = new SGMagVar();
1529 globals->set_mag( magvar );
1532 terrain = new ssgBranch;
1533 terrain->setName( "Terrain" );
1534 scene->addKid( terrain );
1537 ground = new ssgBranch;
1538 ground->setName( "Ground Lighting" );
1539 lighting->addKid( ground );
1541 airport = new ssgBranch;
1542 airport->setName( "Airport Lighting" );
1543 lighting->addKid( airport );
1545 // temporary visible aircraft "own ship"
1546 acmodel_selector = new ssgSelector;
1547 acmodel_pos = new ssgTransform;
1549 string acmodel_path =
1550 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1552 string full_model = globals->get_fg_root() + "/"
1554 int pos = full_model.rfind("/");
1556 FGPath texturepath( full_model.substr(0, pos) );
1557 cout << "Texture path = " << texturepath.str() << endl;
1558 ssgTexturePath( (char *)texturepath.c_str() );
1560 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1562 // find moving parts (if this is an MDL model)
1563 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1564 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1566 acmodel_npropsettings = 0;
1567 if (prop_selector != NULL) {
1568 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1569 kid = prop_selector->getNextKid()) {
1570 int prop_low, prop_high;
1571 if ( sscanf(kid->getName(), "PROP_%d_%d",
1572 &prop_low, &prop_high) == 2 ) {
1573 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1574 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1575 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1576 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1577 acmodel_npropsettings++;
1579 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1585 // align the model properly for FGFS
1586 ssgTransform *acmodel_align = new ssgTransform;
1587 acmodel_align->addKid(acmodel_obj);
1591 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1592 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1593 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1594 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1595 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1596 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1597 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1598 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1599 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1600 acmodel_align->setTransform(res_matrix);
1602 acmodel_pos->addKid( acmodel_align );
1603 acmodel_selector->addKid( acmodel_pos );
1604 //ssgFlatten( acmodel_obj );
1605 //ssgStripify( acmodel_selector );
1606 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1607 scene->addKid( acmodel_selector );
1609 // $$$ begin - added VS Renganthan 17 Oct 2K
1611 // $$$ end - added VS Renganthan 17 Oct 2K
1613 #ifdef FG_NETWORK_OLK
1614 // Do the network intialization
1615 if ( fgGetBool("/sim/networking/network-olk") ) {
1616 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1620 // build our custom render states
1621 fgBuildRenderStates();
1623 // pass control off to the master GLUT event handler
1626 // we never actually get here ... but to avoid compiler warnings,
1632 // $$$ end - added VS Renganathan, 15 Oct 2K
1633 // - added Venky , 12 Nov 2K
1635 void fgLoadDCS(void) {
1637 ssgEntity *ship_obj = NULL;
1640 char obj_filename[25];
1642 for (int k=0;k<32;k++)
1647 FGPath tile_path( globals->get_fg_root());
1648 tile_path.append( "Scenery" );
1649 tile_path.append( "Objects.txt" );
1650 fg_gzifstream in( tile_path.str() );
1651 if ( ! in.is_open() ) {
1652 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1655 FGPath modelpath( globals->get_fg_root() );
1656 modelpath.append( "Models" );
1657 modelpath.append( "Geometry" );
1659 FGPath texturepath( globals->get_fg_root() );
1660 texturepath.append( "Models" );
1661 texturepath.append( "Textures" );
1663 ssgModelPath( (char *)modelpath.c_str() );
1664 ssgTexturePath( (char *)texturepath.c_str() );
1666 ship_sel = new ssgSelector;
1669 while ( ! in.eof() )
1672 if ( in.get( c ) && c == '#' )
1679 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1680 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1681 int chj=getchar();*/
1683 obj_lon[objc] *=DEG_TO_RAD;
1684 obj_lat[objc] *=DEG_TO_RAD;
1686 ship_pos[objc] = new ssgTransform;
1689 // type "repeat" in objects.txt to load one more instance of the last object.
1691 if ( strcmp(obj_filename,"repeat") != 0)
1692 ship_obj = ssgLoadOBJ( obj_filename );
1694 if ( ship_obj != NULL )
1696 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1697 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1700 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1702 if (in.eof()) break;
1707 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1708 scene->addKid( ship_sel ); //add selector node to root node
1713 void fgUpdateDCS (void) {
1715 // double eye_lat,eye_lon,eye_alt;
1716 // static double obj_head;
1717 double sl_radius,obj_latgc;
1718 // float nresultmat[4][4];
1719 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1722 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1723 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1725 // Deck should be the first object in objects.txt in case of fdm=ada
1727 if (fgGetString("/sim/flight-model") == "ada")
1729 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1730 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1731 obj_alt[0] = fdm->get_aux7();
1734 for (int m=0; m<=objc; m++)
1736 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1739 //Geodetic to Geocentric angles for rotation
1740 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1742 //moving object gbs-posn in cartesian coords
1743 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1744 Point3D obj_pos = sgGeodToCart( obj_posn );
1746 // Translate moving object w.r.t eye
1747 Point3D Objtrans = obj_pos-scenery.center;
1752 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1755 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1757 sgVec3 ship_fwd,ship_rt,ship_up;
1758 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1759 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1760 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1762 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1763 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1764 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1765 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1768 sgCopyMat4( sgTUX, sgROT_hdg );
1769 sgPostMultMat4( sgTUX, sgROT_lat );
1770 sgPostMultMat4( sgTUX, sgROT_lon );
1771 sgPostMultMat4( sgTUX, sgTRANS );
1774 sgSetCoord(&shippos, sgTUX );
1775 ship_pos[m]->setTransform( &shippos );
1777 if ( ship_sel != NULL )
1778 ship_sel->select(0xFFFFFFFF);
1781 // $$$ end - added VS Renganathan, 15 Oct 2K
1782 // added Venky , 12 Nov 2K