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 SG_MATH_EXCEPTION_CLASH
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
57 # include <GL/glext.h>
63 #include <simgear/constants.h> // for VERSION
64 #include <simgear/debug/logstream.hxx>
65 #include <simgear/math/polar3d.hxx>
66 #include <simgear/math/sg_random.h>
67 #include <simgear/misc/sg_path.hxx>
68 #include <simgear/sky/sky.hxx>
69 #include <simgear/timing/sg_time.hxx>
70 #include <simgear/timing/lowleveltime.h>
72 #include <Include/general.hxx>
74 #include <Aircraft/aircraft.hxx>
76 #include <Autopilot/newauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/radiostack.hxx>
79 #include <Cockpit/steam.hxx>
81 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
83 #include <GUI/sgVec3Slider.hxx>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Objects/matlib.hxx>
89 #include <Scenery/scenery.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #ifdef ENABLE_AUDIO_SUPPORT
92 # include <Sound/soundmgr.hxx>
93 # include <Sound/morse.hxx>
95 #include <Time/event.hxx>
96 #include <Time/fg_timer.hxx>
97 #include <Time/light.hxx>
98 #include <Time/sunpos.hxx>
99 #include <Time/tmp.hxx>
101 // begin - added Venky
102 // $$$ begin - added VS Renganathan
103 #include <simgear/misc/sgstream.hxx>
104 #include <FDM/flight.hxx>
105 #include <FDM/ADA.hxx>
106 void fgLoadDCS (void);
107 void fgUpdateDCS (void);
108 ssgSelector *ship_sel=NULL;
109 // upto 32 instances of a same object can be loaded.
110 ssgTransform *ship_pos[32];
111 double obj_lat[32],obj_lon[32],obj_alt[32];
113 // $$$ end - added VS Renganathan
116 #ifndef FG_OLD_WEATHER
117 # include <WeatherCM/FGLocalWeatherDatabase.h>
119 # include <Weather/weather.hxx>
125 #include "fg_init.hxx"
127 #include "globals.hxx"
128 #include "keyboard.hxx"
129 #include "splash.hxx"
132 # include <console.h> // -dw- for command line dialog
136 // This is a record containing a bit of global housekeeping information
139 // Specify our current idle function state. This is used to run all
140 // our initializations out of the glutIdleLoop() so that we can get a
141 // splash screen up and running right away.
142 static int idle_state = 0;
143 static long global_multi_loop;
145 // attempt to avoid a large bounce at startup
146 static bool initial_freeze = true;
148 // forward declaration
149 void fgReshape( int width, int height );
151 // Global structures for the Audio library
152 #ifdef ENABLE_AUDIO_SUPPORT
153 static FGSimpleSound *s1;
154 static FGSimpleSound *s2;
159 ssgRoot *scene = NULL;
160 ssgBranch *terrain = NULL;
162 // aircraft model stuff
163 ssgSelector *acmodel_selector = NULL;
164 ssgTransform *acmodel_pos = NULL;
165 ssgSelector *prop_selector = NULL;
166 ssgSelector *flaps_selector = NULL;
167 int acmodel_npropsettings;
168 int acmodel_proprpms[4][2]; // different propeller settings
170 ssgRoot *lighting = NULL;
171 ssgBranch *ground = NULL;
172 ssgBranch *airport = NULL;
174 #ifdef FG_NETWORK_OLK
175 ssgSelector *fgd_sel = NULL;
176 ssgTransform *fgd_pos = NULL;
179 // current fdm/position used for view
180 FGInterface cur_view_fdm;
186 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
188 { 1.0f, 0.0f, 0.0f, 0.0f },
189 { 0.0f, 0.0f, -1.0f, 0.0f },
190 { 0.0f, 1.0f, 0.0f, 0.0f },
191 { 0.0f, 0.0f, 0.0f, 1.0f }
194 // The following defines flightgear options. Because glutlib will also
195 // want to parse its own options, those options must not be included here
196 // or they will get parsed by the main program option parser. Hence case
197 // is significant for any option added that might be in conflict with
200 // glutlib parses for:
202 // -direct (invalid in Win32)
206 // -indirect (invalid in Win32)
209 // Note that glutlib depends upon strings while this program's
210 // option parser wants only initial characters followed by numbers
215 ssgSimpleState *default_state;
216 ssgSimpleState *hud_and_panel;
217 ssgSimpleState *menus;
219 void fgBuildRenderStates( void ) {
220 default_state = new ssgSimpleState;
221 default_state->ref();
222 default_state->disable( GL_TEXTURE_2D );
223 default_state->enable( GL_CULL_FACE );
224 default_state->enable( GL_COLOR_MATERIAL );
225 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
226 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
227 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
228 default_state->disable( GL_BLEND );
229 default_state->disable( GL_ALPHA_TEST );
230 default_state->disable( GL_LIGHTING );
232 hud_and_panel = new ssgSimpleState;
233 hud_and_panel->ref();
234 hud_and_panel->disable( GL_CULL_FACE );
235 hud_and_panel->disable( GL_TEXTURE_2D );
236 hud_and_panel->disable( GL_LIGHTING );
237 hud_and_panel->enable( GL_BLEND );
239 menus = new ssgSimpleState;
241 menus->disable( GL_CULL_FACE );
242 menus->disable( GL_TEXTURE_2D );
243 menus->enable( GL_BLEND );
246 // fgFindNode -- a function that finds a named node in an ssg graph
247 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
248 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
250 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
251 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
252 while (kid != NULL) {
253 ssgEntity *n = fgFindNode(kid, name);
257 kid = ((ssgBranch*)node)->getNextKid();
264 // fgInitVisuals() -- Initialize various GL/view parameters
265 void fgInitVisuals( void ) {
268 l = &cur_light_params;
270 #ifndef GLUT_WRONG_VERSION
271 // Go full screen if requested ...
272 if ( fgGetBool("/sim/startup/fullscreen") ) {
277 // If enabled, normal vectors specified with glNormal are scaled
278 // to unit length after transformation. See glNormal.
279 // glEnable( GL_NORMALIZE );
281 glEnable( GL_LIGHTING );
282 glEnable( GL_LIGHT0 );
283 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
286 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
287 ssgGetLight( 0 ) -> setPosition( sunpos );
289 // glFogi (GL_FOG_MODE, GL_LINEAR);
290 glFogi (GL_FOG_MODE, GL_EXP2);
291 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
292 (!fgGetBool("/sim/rendering/shading"))) {
293 // if fastest fog requested, or if flat shading force fastest
294 glHint ( GL_FOG_HINT, GL_FASTEST );
295 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
296 glHint ( GL_FOG_HINT, GL_NICEST );
298 if ( fgGetBool("/sim/rendering/wireframe") ) {
300 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
303 // This is the default anyways, but it can't hurt
304 glFrontFace ( GL_CCW );
307 // glEnable(GL_POINT_SMOOTH);
308 // glEnable(GL_LINE_SMOOTH);
309 // glEnable(GL_POLYGON_SMOOTH);
313 // Update all Visuals (redraws anything graphics related)
314 void fgRenderFrame( void ) {
318 fgLIGHT *l = &cur_light_params;
319 static double last_visibility = -9999;
321 static GLfloat fog_exp_density;
322 static GLfloat fog_exp2_density;
323 static GLfloat fog_exp2_punch_through;
326 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
327 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
328 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
329 // GLfloat mat_shininess[] = { 10.0 };
330 GLbitfield clear_mask;
332 if ( idle_state != 1000 ) {
333 // still initializing, draw the splash screen
334 if ( fgGetBool("/sim/startup/splash-screen") ) {
338 // idle_state is now 1000 meaning we've finished all our
339 // initializations and are running the main loop, so this will
340 // now work without seg faulting the system.
342 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
343 // FG_Altitude * SG_FEET_TO_METER);
345 // this is just a temporary hack, to make me understand Pui
346 // timerText -> setLabel (ctime (&t->cur_time));
349 // calculate our current position in cartesian space
350 scenery.center = scenery.next_center;
351 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
352 // scenery.center.y(), scenery.center.z());
354 FGViewerRPH *pilot_view =
355 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
357 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
358 cur_fdm_state->get_Lat_geocentric(),
359 cur_fdm_state->get_Altitude() *
361 pilot_view->set_sea_level_radius( cur_fdm_state->
362 get_Sea_level_radius() *
364 pilot_view->set_rph( cur_fdm_state->get_Phi(),
365 cur_fdm_state->get_Theta(),
366 cur_fdm_state->get_Psi() );
368 FGViewerLookAt *chase_view =
369 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
371 sgVec3 po; // chase view pilot_offset
372 sgVec3 wup; // chase view world up
373 sgSetVec3( po, 0.0, 0.0, 100.0 );
374 sgCopyVec3( wup, pilot_view->get_world_up() );
375 sgMat4 CXFM; // chase view + pilot offset xform
377 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
378 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
380 sgVec3 npo; // new pilot offset after rotation
381 sgVec3 *pPO = PilotOffsetGet();
382 sgXformVec3( po, *pPO, pilot_view->get_UP() );
383 sgXformVec3( npo, po, CXFM );
385 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
386 cur_fdm_state->get_Lat_geocentric(),
387 cur_fdm_state->get_Altitude() *
389 chase_view->set_sea_level_radius( cur_fdm_state->
390 get_Sea_level_radius() *
392 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
393 chase_view->set_view_forward( pilot_view->get_view_pos() );
394 chase_view->set_view_up( wup );
398 sgCopyMat4( rph, pilot_view->get_VIEW() );
399 cout << "RPH Matrix = " << endl;
401 for ( i = 0; i < 4; i++ ) {
402 for ( j = 0; j < 4; j++ ) {
403 printf("%10.4f ", rph[i][j]);
409 sgCopyMat4( la, chase_view->get_VIEW() );
410 cout << "LookAt Matrix = " << endl;
411 for ( i = 0; i < 4; i++ ) {
412 for ( j = 0; j < 4; j++ ) {
413 printf("%10.4f ", la[i][j]);
420 fgReshape( fgGetInt("/sim/startup/xsize"),
421 fgGetInt("/sim/startup/ysize") );
426 if ( ! fgPanelVisible() ) {
428 (GLint)(fgGetInt("/sim/startup/xsize")),
429 (GLint)(fgGetInt("/sim/startup/ysize")) );
432 int( (current_panel->getViewHeight() -
433 current_panel->getYOffset())
434 * (fgGetInt("/sim/startup/ysize") / 768.0) );
436 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
437 (GLint)(fgGetInt("/sim/startup/xsize")),
442 // set the sun position
443 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
445 clear_mask = GL_DEPTH_BUFFER_BIT;
446 if ( fgGetBool("/sim/rendering/wireframe") ) {
447 clear_mask |= GL_COLOR_BUFFER_BIT;
450 if ( fgGetBool("/sim/rendering/skyblend") ) {
451 if ( fgGetBool("/sim/rendering/textures") ) {
452 // glClearColor(black[0], black[1], black[2], black[3]);
453 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
454 l->adj_fog_color[2], l->adj_fog_color[3]);
455 clear_mask |= GL_COLOR_BUFFER_BIT;
458 glClearColor(l->sky_color[0], l->sky_color[1],
459 l->sky_color[2], l->sky_color[3]);
460 clear_mask |= GL_COLOR_BUFFER_BIT;
462 glClear( clear_mask );
464 // Tell GL we are switching to model view parameters
466 // I really should create a derived ssg node or use a call
467 // back or something so that I can draw the sky within the
468 // ssgCullAndDraw() function, but for now I just mimic what
469 // ssg does to set up the model view matrix
470 glMatrixMode(GL_MODELVIEW);
472 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
474 // set the opengl state to known default values
475 default_state->force();
477 // update fog params if visibility has changed
478 #ifndef FG_OLD_WEATHER
479 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
481 thesky->set_visibility( current_weather.get_visibility() );
484 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
485 ( global_multi_loop *
486 fgGetInt("/sim/speed-up") ) /
487 (double)fgGetInt("/sim/model-hz") );
489 double actual_visibility = thesky->get_visibility();
490 // cout << "actual visibility = " << actual_visibility << endl;
492 if ( actual_visibility != last_visibility ) {
493 last_visibility = actual_visibility;
495 // cout << "----> updating fog params" << endl;
498 fog_exp_density = -log(0.01) / actual_visibility;
501 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
502 fog_exp2_punch_through = sqrt( -log(0.01) ) /
503 ( actual_visibility * 1.5 );
506 // Set correct opengl fog density
507 glFogf (GL_FOG_DENSITY, fog_exp2_density);
509 // update the sky dome
510 if ( fgGetBool("/sim/rendering/skyblend") ) {
511 /* cout << "thesky->repaint() sky_color = "
512 << cur_light_params.sky_color[0] << " "
513 << cur_light_params.sky_color[1] << " "
514 << cur_light_params.sky_color[2] << " "
515 << cur_light_params.sky_color[3] << endl;
517 << cur_light_params.fog_color[0] << " "
518 << cur_light_params.fog_color[1] << " "
519 << cur_light_params.fog_color[2] << " "
520 << cur_light_params.fog_color[3] << endl;
521 cout << " sun_angle = " << cur_light_params.sun_angle
522 << " moon_angle = " << cur_light_params.moon_angle
524 thesky->repaint( cur_light_params.sky_color,
525 cur_light_params.adj_fog_color,
526 cur_light_params.sun_angle,
527 cur_light_params.moon_angle,
528 globals->get_ephem()->getNumPlanets(),
529 globals->get_ephem()->getPlanets(),
530 globals->get_ephem()->getNumStars(),
531 globals->get_ephem()->getStars() );
533 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
534 << view_pos[1] << " " << view_pos[2] << endl;
535 cout << " zero_elev = " << zero_elev[0] << " "
536 << zero_elev[1] << " " << zero_elev[2]
537 << " lon = " << cur_fdm_state->get_Longitude()
538 << " lat = " << cur_fdm_state->get_Latitude() << endl;
539 cout << " sun_rot = " << cur_light_params.sun_rotation
540 << " gst = " << SGTime::cur_time_params->getGst() << endl;
541 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
542 << " sun dec = " << globals->get_ephem()->getSunDeclination()
543 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
544 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
546 thesky->reposition( globals->get_current_view()->get_view_pos(),
547 globals->get_current_view()->get_zero_elev(),
548 globals->get_current_view()->get_world_up(),
549 cur_fdm_state->get_Longitude(),
550 cur_fdm_state->get_Latitude(),
551 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
552 cur_light_params.sun_rotation,
553 globals->get_time_params()->getGst(),
554 globals->get_ephem()->getSunRightAscension(),
555 globals->get_ephem()->getSunDeclination(),
557 globals->get_ephem()->getMoonRightAscension(),
558 globals->get_ephem()->getMoonDeclination(),
562 glEnable( GL_DEPTH_TEST );
563 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
565 glFogi( GL_FOG_MODE, GL_EXP2 );
566 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
569 // set sun/lighting parameters
570 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
572 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
573 // we only update GL_AMBIENT for our lights we will never get
574 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
575 // explicitely to black.
576 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
577 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
578 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
580 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
581 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
582 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
584 // texture parameters
585 // glEnable( GL_TEXTURE_2D );
586 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
587 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
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() * SG_FEET_TO_METER
597 // SG_LOG( SG_ALL, SG_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 if ( fgGetBool("/sim/rendering/skyblend") ) {
686 // draw the sky backdrop
688 // we need a white diffuse light for the phase of the moon
689 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
693 // return to the desired diffuse color
694 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
697 // draw the ssg scene
698 glEnable( GL_DEPTH_TEST );
699 ssgCullAndDraw( scene );
701 // change state for lighting here
704 // Set punch through fog density
705 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
707 ssgCullAndDraw( lighting );
709 if ( fgGetBool("/sim/rendering/skyblend") ) {
710 // draw the sky cloud layers
711 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
714 // display HUD && Panel
716 glDisable( GL_DEPTH_TEST );
717 // glDisable( GL_CULL_FACE );
718 // glDisable( GL_TEXTURE_2D );
720 // update the controls subsystem
723 hud_and_panel->apply();
726 // update the panel subsystem
727 if (current_panel != 0)
728 current_panel->update();
730 // We can do translucent menus, so why not. :-)
732 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
734 // glDisable ( GL_BLEND ) ;
736 // glEnable( GL_FOG );
743 // Update internal time dependent calculations (i.e. flight model)
744 void fgUpdateTimeDepCalcs() {
745 static bool inited = false;
747 fgLIGHT *l = &cur_light_params;
752 if ( !globals->get_freeze() && !initial_freeze ) {
753 // conceptually, this could be done for each fdm instance ...
756 cur_fdm_state->stamp();
762 long elapsed = current - cur_fdm_state->get_time_stamp();
763 cur_fdm_state->set_time_stamp( current );
764 elapsed += cur_fdm_state->get_remainder();
765 // cout << "elapsed = " << elapsed << endl;
766 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
767 multi_loop = (long)(((double)elapsed * 0.000001) /
768 cur_fdm_state->get_delta_t() );
769 cur_fdm_state->set_multi_loop( multi_loop );
770 long remainder = elapsed - (long)( (multi_loop*1000000) *
771 cur_fdm_state->get_delta_t() );
772 cur_fdm_state->set_remainder( remainder );
773 // cout << "remainder = " << remainder << endl;
775 // chop max interations to something reasonable if the sim was
776 // delayed for an excesive amount of time
777 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
778 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
779 cur_fdm_state->set_remainder( 0 );
782 // cout << "multi_loop = " << multi_loop << endl;
783 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
784 // run Autopilot system
785 current_autopilot->run();
788 cur_fdm_state->update( 1 );
790 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
792 cur_fdm_state->update( 0 );
793 FGSteam::update( 0 );
795 //if ( global_tile_mgr.queue_size() == 0 ) {
796 initial_freeze = false;
800 if ( fgGetString("/sim/view-mode") == "pilot" ) {
801 cur_view_fdm = *cur_fdm_state;
805 // update the view angle
806 FGViewer *v = globals->get_current_view();
807 for ( i = 0; i < multi_loop; i++ ) {
808 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
809 v->set_view_offset( v->get_goal_view_offset() );
812 // move current_view.view_offset towards
813 // current_view.goal_view_offset
814 if ( v->get_goal_view_offset() > v->get_view_offset() )
816 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
817 v->inc_view_offset( 0.01 );
819 v->inc_view_offset( -0.01 );
822 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
823 v->inc_view_offset( -0.01 );
825 v->inc_view_offset( 0.01 );
828 if ( v->get_view_offset() > SGD_2PI ) {
829 v->inc_view_offset( -SGD_2PI );
830 } else if ( v->get_view_offset() < 0 ) {
831 v->inc_view_offset( SGD_2PI );
836 double tmp = -(l->sun_rotation + SGD_PI)
837 - (cur_fdm_state->get_Psi() -
838 globals->get_current_view()->get_view_offset() );
839 while ( tmp < 0.0 ) {
842 while ( tmp > SGD_2PI ) {
845 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
846 FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES,
847 -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
850 // Update solar system
851 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
852 globals->get_time_params()->getLst(),
853 cur_fdm_state->get_Latitude() );
855 // Update radio stack model
856 current_radiostack->update();
860 void fgInitTimeDepCalcs( void ) {
863 // #ifdef HAVE_SETITIMER
864 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
865 // fgUpdateTimeDepCalcs );
866 // #endif HAVE_SETITIMER
870 static const double alt_adjust_ft = 3.758099;
871 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
874 // What should we do when we have nothing else to do? Let's get ready
875 // for the next move and update the display?
876 static void fgMainLoop( void ) {
877 static long remainder = 0;
879 #ifdef FANCY_FRAME_COUNTER
883 static time_t last_time = 0;
884 static int frames = 0;
885 #endif // FANCY_FRAME_COUNTER
887 SGTime *t = globals->get_time_params();
889 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
890 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
892 #ifdef FG_NETWORK_OLK
893 if ( fgGetBool("/sim/networking/network-olk") ) {
894 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
895 // printf("FGD: Netupdate\n");
896 fgd_send_com( "A", FGFS_host); // Send Mat4 data
897 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
902 #if defined( ENABLE_PLIB_JOYSTICK )
903 // Read joystick and update control settings
904 if ( fgGetString("/sim/control-mode") == "joystick" )
908 #elif defined( ENABLE_GLUT_JOYSTICK )
909 // Glut joystick support works by feeding a joystick handler
910 // function to glut. This is taken care of once in the joystick
911 // init routine and we don't have to worry about it again.
914 #ifdef FG_OLD_WEATHER
915 current_weather.Update();
918 // Fix elevation. I'm just sticking this here for now, it should
919 // probably move eventually
921 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
923 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
924 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
926 if ( scenery.cur_elev > -9990 ) {
927 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
928 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
929 // now set aircraft altitude above ground
930 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
931 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
932 scenery.cur_elev + alt_adjust_m - 3.0,
933 scenery.cur_elev + alt_adjust_m );
934 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
935 scenery.cur_elev + alt_adjust_m );
937 SG_LOG( SG_ALL, SG_DEBUG,
938 "<*> resetting altitude to "
939 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
944 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
946 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
947 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
950 if ( globals->get_warp_delta() != 0 ) {
951 globals->inc_warp( globals->get_warp_delta() );
954 t->update( cur_fdm_state->get_Longitude(),
955 cur_fdm_state->get_Latitude(),
956 globals->get_warp() );
958 if ( globals->get_warp_delta() != 0 ) {
959 fgUpdateSkyAndLightingParams();
962 // update magvar model
963 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
964 cur_fdm_state->get_Latitude(),
965 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
966 globals->get_time_params()->getJD() );
968 // Get elapsed time (in usec) for this past frame
969 elapsed = fgGetTimeInterval();
970 SG_LOG( SG_ALL, SG_DEBUG,
971 "Elapsed time interval is = " << elapsed
972 << ", previous remainder is = " << remainder );
974 // Calculate frame rate average
975 #ifdef FANCY_FRAME_COUNTER
976 /* old fps calculation */
980 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
981 tmp = general.get_frame(i);
983 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
984 general.set_frame(i+1,tmp);
986 tmp = 1000000.0 / (float)elapsed;
987 general.set_frame(0,tmp);
988 // printf("frame[0] = %.2f\n", general.frames[0]);
990 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
991 // printf("ave = %.2f\n", general.frame_rate);
994 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
995 general.set_frame_rate( frames );
996 SG_LOG( SG_ALL, SG_DEBUG,
997 "--> Frame rate is = " << general.get_frame_rate() );
1000 last_time = t->get_cur_time();
1006 // Calculate model iterations needed for next frame
1007 elapsed += remainder;
1009 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1010 fgGetInt("/sim/model-hz"));
1011 remainder = elapsed - ( (global_multi_loop*1000000) /
1012 fgGetInt("/sim/model-hz") );
1013 SG_LOG( SG_ALL, SG_DEBUG,
1014 "Model iterations needed = " << global_multi_loop
1015 << ", new remainder = " << remainder );
1017 // chop max interations to something reasonable if the sim was
1018 // delayed for an excesive amount of time
1019 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1020 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1025 if ( global_multi_loop > 0 ) {
1026 fgUpdateTimeDepCalcs();
1028 SG_LOG( SG_ALL, SG_DEBUG,
1029 "Elapsed time is zero ... we're zinging" );
1032 #if ! defined( macintosh )
1033 // Do any I/O channel work that might need to be done
1037 // see if we need to load any new scenery tiles
1038 global_tile_mgr.update( cur_fdm_state->get_Longitude()
1039 * SGD_RADIANS_TO_DEGREES,
1040 cur_fdm_state->get_Latitude()
1041 * SGD_RADIANS_TO_DEGREES );
1043 // see if we need to load any deferred-load textures
1044 material_lib.load_next_deferred();
1046 // Process/manage pending events
1047 global_events.Process();
1049 // Run audio scheduler
1050 #ifdef ENABLE_AUDIO_SUPPORT
1051 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1052 if ( fgGetString("/sim/aircraft") == "c172" ) {
1053 // pitch corresponds to rpm
1054 // volume corresponds to manifold pressure
1056 // cout << "AUDIO working = "
1057 // << globals->get_soundmgr()->is_working() << endl;
1060 if ( cur_fdm_state->get_engine(0) != NULL ) {
1061 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1065 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1068 double pitch = 0.3 + rpm_factor * 3.0;
1070 // don't run at absurdly slow rates -- not realistic
1071 // and sounds bad to boot. :-)
1072 if (pitch < 0.7) { pitch = 0.7; }
1073 if (pitch > 5.0) { pitch = 5.0; }
1076 if ( cur_fdm_state->get_engine(0) != NULL ) {
1078 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1083 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1086 double volume = 0.15 + mp_factor / 2.0;
1088 if ( volume < 0.15 ) { volume = 0.15; }
1089 if ( volume > 0.5 ) { volume = 0.5; }
1090 // cout << "volume = " << volume << endl;
1092 s1->set_pitch( pitch );
1093 s1->set_volume( volume );
1095 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1096 s1->set_pitch( param );
1097 s1->set_volume( param );
1100 globals->get_soundmgr()->update();
1107 SG_LOG( SG_ALL, SG_DEBUG, "" );
1111 // This is the top level master main function that is registered as
1112 // our idle funciton
1115 // The first few passes take care of initialization things (a couple
1116 // per pass) and once everything has been initialized fgMainLoop from
1119 static void fgIdleFunction ( void ) {
1120 // printf("idle state == %d\n", idle_state);
1122 if ( idle_state == 0 ) {
1123 // Initialize the splash screen right away
1124 if ( fgGetBool("/sim/startup/splash-screen") ) {
1129 } else if ( idle_state == 1 ) {
1130 // Start the intro music
1132 if ( fgGetBool("/sim/startup/intro-music") ) {
1133 string lockfile = "/tmp/mpg123.running";
1134 SGPath mp3file( globals->get_fg_root() );
1135 mp3file.append( "Sounds/intro.mp3" );
1137 string command = "(touch " + lockfile + "; mpg123 "
1138 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1140 SG_LOG( SG_GENERAL, SG_INFO,
1141 "Starting intro music: " << mp3file.str() );
1142 system ( command.c_str() );
1147 } else if ( idle_state == 2 ) {
1148 // These are a few miscellaneous things that aren't really
1149 // "subsystems" but still need to be initialized.
1152 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1153 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1158 } else if ( idle_state == 3 ) {
1159 // This is the top level init routine which calls all the
1160 // other subsystem initialization routines. If you are adding
1161 // a subsystem to flightgear, its initialization call should
1162 // located in this routine.
1163 if( !fgInitSubsystems()) {
1164 SG_LOG( SG_GENERAL, SG_ALERT,
1165 "Subsystem initializations failed ..." );
1170 } else if ( idle_state == 4 ) {
1171 // setup OpenGL view parameters
1175 } else if ( idle_state == 5 ) {
1178 } else if ( idle_state == 6 ) {
1179 // Initialize audio support
1180 #ifdef ENABLE_AUDIO_SUPPORT
1183 if ( fgGetBool("/sim/startup/intro-music") ) {
1184 // Let's wait for mpg123 to finish
1185 string lockfile = "/tmp/mpg123.running";
1186 struct stat stat_buf;
1188 SG_LOG( SG_GENERAL, SG_INFO,
1189 "Waiting for mpg123 player to finish ..." );
1190 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1191 // file exist, wait ...
1193 SG_LOG( SG_GENERAL, SG_INFO, ".");
1195 SG_LOG( SG_GENERAL, SG_INFO, "");
1199 if ( fgGetBool("/sim/sound") ) {
1200 globals->get_soundmgr()->init();
1202 s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1203 "Sounds/wasp.wav") );
1204 globals->get_soundmgr()->add( s1, "engine loop" );
1205 globals->get_soundmgr()->play_looped( "engine loop" );
1206 SG_LOG( SG_GENERAL, SG_INFO,
1207 "Rate = " << s1->get_sample()->getRate()
1208 << " Bps = " << s1->get_sample()->getBps()
1209 << " Stereo = " << s1->get_sample()->getStereo() );
1211 s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1214 // s2 = mmm.make_ident( "JLI" );
1215 s2->set_volume( 0.3 );
1216 globals->get_soundmgr()->add( s2, "flaps" );
1223 cout << "Panel visible = " << fgPanelVisible() << endl;
1224 fgReshape( fgGetInt("/sim/startup/xsize"),
1225 fgGetInt("/sim/startup/ysize") );
1228 if ( idle_state == 1000 ) {
1229 // We've finished all our initialization steps, from now on we
1230 // run the main loop.
1234 if ( fgGetBool("/sim/startup/splash-screen") ) {
1235 fgSplashUpdate(0.0);
1240 // options.cxx needs to see this for toggle_panel()
1241 // Handle new window size or exposure
1242 void fgReshape( int width, int height ) {
1244 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1245 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1246 globals->get_viewmgr()->get_view(i)->
1247 set_win_ratio( (float)height / (float)width );
1250 int((current_panel->getViewHeight() -
1251 current_panel->getYOffset())
1252 * (height / 768.0)) + 1;
1253 globals->get_viewmgr()->get_view(i)->
1254 set_win_ratio( (float)view_h / (float)width );
1258 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1259 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1262 int((current_panel->getViewHeight() - current_panel->getYOffset())
1263 * (height / 768.0)) + 1;
1264 glViewport(0, (GLint)(height - view_h),
1265 (GLint)(width), (GLint)(view_h) );
1268 fgSetInt("/sim/startup/xsize", width);
1269 fgSetInt("/sim/startup/ysize", height);
1271 float fov = globals->get_current_view()->get_fov();
1272 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1278 // Initialize GLUT and define a main window
1279 int fgGlutInit( int *argc, char **argv ) {
1281 #if !defined( macintosh )
1282 // GLUT will extract all glut specific options so later on we only
1283 // need wory about our own.
1284 glutInit(argc, argv);
1287 // Define Display Parameters
1288 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1290 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1291 fgGetInt("/sim/startup/xsize") << "x"
1292 << fgGetInt("/sim/startup/ysize") );
1294 // Define initial window size
1295 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1296 fgGetInt("/sim/startup/ysize") );
1298 // Initialize windows
1299 if ( !fgGetBool("/sim/startup/game-mode")) {
1300 // Open the regular window
1301 glutCreateWindow("FlightGear");
1302 #ifndef GLUT_WRONG_VERSION
1304 // Open the cool new 'game mode' window
1305 char game_mode_str[256];
1306 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1307 fgGetInt("/sim/startup/xsize"),
1308 fgGetInt("/sim/startup/ysize"),
1309 fgGetInt("/sim/rendering/bits-per-pixel"));
1311 SG_LOG( SG_GENERAL, SG_INFO,
1312 "game mode params = " << game_mode_str );
1313 glutGameModeString( game_mode_str );
1314 glutEnterGameMode();
1318 // This seems to be the absolute earliest in the init sequence
1319 // that these calls will return valid info. Too bad it's after
1320 // we've already created and sized out window. :-(
1321 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1322 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1323 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1324 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1327 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1328 general.set_glMaxTexSize( tmp );
1329 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1331 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1332 general.set_glDepthBits( tmp );
1333 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1339 // Initialize GLUT event handlers
1340 int fgGlutInitEvents( void ) {
1341 // call fgReshape() on window resizes
1342 glutReshapeFunc( fgReshape );
1344 // call GLUTkey() on keyboard event
1345 glutKeyboardFunc( GLUTkey );
1346 glutSpecialFunc( GLUTspecialkey );
1348 // call guiMouseFunc() whenever our little rodent is used
1349 glutMouseFunc ( guiMouseFunc );
1350 glutMotionFunc (guiMotionFunc );
1351 glutPassiveMotionFunc (guiMotionFunc );
1353 // call fgMainLoop() whenever there is
1354 // nothing else to do
1355 glutIdleFunc( fgIdleFunction );
1358 glutDisplayFunc( fgRenderFrame );
1365 int main( int argc, char **argv ) {
1367 #if defined( macintosh )
1368 freopen ("stdout.txt", "w", stdout );
1369 freopen ("stderr.txt", "w", stderr );
1370 argc = ccommand( &argv );
1374 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1377 // set default log levels
1378 sglog().setLogLevels( SG_ALL, SG_INFO );
1381 #ifdef FLIGHTGEAR_VERSION
1382 version = FLIGHTGEAR_VERSION;
1384 version = "unknown version";
1386 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1387 << version << endl );
1389 // Allocate global data structures. This needs to happen before
1390 // we parse command line options
1392 SGPropertyNode *props = new SGPropertyNode;
1393 globals = new FGGlobals;
1394 globals->set_props( props );
1396 // seed the random number generater
1399 SGRoute *route = new SGRoute;
1400 globals->set_route( route );
1402 #ifdef ENABLE_AUDIO_SUPPORT
1403 FGSoundMgr *soundmgr = new FGSoundMgr;
1404 globals->set_soundmgr( soundmgr );
1407 FGViewMgr *viewmgr = new FGViewMgr;
1408 globals->set_viewmgr( viewmgr );
1410 FGViewerRPH *pv = new FGViewerRPH;
1411 globals->get_viewmgr()->add_view( pv );
1413 FGViewerLookAt *chase = new FGViewerLookAt;
1414 globals->get_viewmgr()->add_view( chase );
1416 string_list *col = new string_list;
1417 globals->set_channel_options_list( col );
1419 // set current view to 0 (first) which is our main pilot view
1420 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1422 // Scan the config file(s) and command line options to see if
1423 // fg_root was specified (ignore all other options for now)
1424 fgInitFGRoot(argc, argv);
1426 // Initialize the Aircraft directory to "" (UIUC)
1429 // Load the configuration parameters
1430 if ( !fgInitConfig(argc, argv) ) {
1431 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1435 // Initialize the Window/Graphics environment.
1436 if( !fgGlutInit(&argc, argv) ) {
1437 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1441 // Initialize the various GLUT Event Handlers.
1442 if( !fgGlutInitEvents() ) {
1443 SG_LOG( SG_GENERAL, SG_ALERT,
1444 "GLUT event handler initialization failed ..." );
1448 // Initialize ssg (from plib). Needs to come before we do any
1449 // other ssg stuff, but after opengl/glut has been initialized.
1452 // Initialize the user interface (we need to do this before
1453 // passing off control to glut and before fgInitGeneral to get our
1457 #ifdef GL_EXT_texture_lod_bias
1458 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1462 #ifdef GL_EXT_texture_filter_anisotropic
1463 float max_anisotropy;
1464 glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1465 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1467 cout << "Max anisotropy = " << max_anisotropy << endl;
1471 // set current_options lon/lat if an airport id is specified
1472 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1473 if ( fgGetString("/sim/startup/airport-id").length() ) {
1474 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1475 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1476 fgGetDouble("/orientation/heading") );
1480 SGPath zone( globals->get_fg_root() );
1481 zone.append( "Timezone" );
1482 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * SGD_DEGREES_TO_RADIANS,
1483 fgGetDouble("/position/latitude") * SGD_DEGREES_TO_RADIANS,
1486 // Handle potential user specified time offsets
1487 time_t cur_time = t->get_cur_time();
1488 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1489 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1490 time_t aircraftLocalTime =
1491 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1493 // Okay, we now have six possible scenarios
1494 int offset = fgGetInt("/sim/startup/time-offset");
1495 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1496 if (offset_type == "system-offset") {
1497 globals->set_warp( offset );
1498 } else if (offset_type == "gmt-offset") {
1499 globals->set_warp( offset - (currGMT - systemLocalTime) );
1500 } else if (offset_type == "latitude-offset") {
1501 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1502 } else if (offset_type == "system") {
1503 globals->set_warp( offset - cur_time );
1504 } else if (offset_type == "gmt") {
1505 globals->set_warp( offset - currGMT );
1506 } else if (offset_type == "latitude") {
1507 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1510 SG_LOG( SG_GENERAL, SG_ALERT,
1511 "Unsupported offset type " << offset_type );
1515 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1516 << globals->get_warp() );
1518 globals->set_warp_delta( 0 );
1520 t->update( 0.0, 0.0, globals->get_warp() );
1522 globals->set_time_params( t );
1524 // Do some quick general initializations
1525 if( !fgInitGeneral()) {
1526 SG_LOG( SG_GENERAL, SG_ALERT,
1527 "General initializations failed ..." );
1531 SGPath modelpath( globals->get_fg_root() );
1532 ssgModelPath( (char *)modelpath.c_str() );
1535 scene = new ssgRoot;
1536 scene->setName( "Scene" );
1538 lighting = new ssgRoot;
1539 lighting->setName( "Lighting" );
1541 // Initialize the sky
1542 SGPath ephem_data_path( globals->get_fg_root() );
1543 ephem_data_path.append( "Astro" );
1544 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1545 ephem->update( globals->get_time_params()->getMjd(),
1546 globals->get_time_params()->getLst(),
1548 globals->set_ephem( ephem );
1552 SGPath sky_tex_path( globals->get_fg_root() );
1553 sky_tex_path.append( "Textures" );
1554 sky_tex_path.append( "Sky" );
1555 thesky->texture_path( sky_tex_path.str() );
1557 thesky->build( 550.0, 550.0,
1558 globals->get_ephem()->getNumPlanets(),
1559 globals->get_ephem()->getPlanets(), 60000.0,
1560 globals->get_ephem()->getNumStars(),
1561 globals->get_ephem()->getStars(), 60000.0 );
1563 if ( fgGetBool("/environment/clouds/status") ) {
1564 thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1565 SG_CLOUD_OVERCAST );
1566 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1567 SG_CLOUD_MOSTLY_CLOUDY );
1568 thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1569 SG_CLOUD_MOSTLY_SUNNY );
1570 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1574 // Initialize MagVar model
1575 SGMagVar *magvar = new SGMagVar();
1576 globals->set_mag( magvar );
1579 terrain = new ssgBranch;
1580 terrain->setName( "Terrain" );
1581 scene->addKid( terrain );
1584 ground = new ssgBranch;
1585 ground->setName( "Ground Lighting" );
1586 lighting->addKid( ground );
1588 airport = new ssgBranch;
1589 airport->setName( "Airport Lighting" );
1590 lighting->addKid( airport );
1592 // temporary visible aircraft "own ship"
1593 acmodel_selector = new ssgSelector;
1594 acmodel_pos = new ssgTransform;
1596 // Get the model location, and load textures from the same
1597 // directory. Use an absolute path for the model to avoid
1598 // incompatibilities in different versions of PLIB.
1599 string acmodel_path =
1600 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1601 SGPath full_model = globals->get_fg_root();
1602 full_model.append(acmodel_path);
1604 #if !defined( PLIB_1_2_X )
1605 // this should be redundant ... but it breaks for relative paths
1607 ssgModelPath( (char *)full_model.dir().c_str() );
1610 ssgTexturePath( (char *)full_model.dir().c_str() );
1611 ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1612 if( !acmodel_obj ) {
1613 // fall back to default
1614 acmodel_obj = ssgLoad( (char *)"glider.ac" );
1615 if( !acmodel_obj ) {
1616 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1621 // find moving parts (if this is an MDL model)
1622 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1623 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1625 acmodel_npropsettings = 0;
1626 if (prop_selector != NULL) {
1627 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1628 kid = prop_selector->getNextKid()) {
1629 int prop_low, prop_high;
1630 if ( sscanf(kid->getName(), "PROP_%d_%d",
1631 &prop_low, &prop_high) == 2 ) {
1632 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1633 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1634 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1635 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1636 acmodel_npropsettings++;
1638 SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1644 // align the model properly for FGFS
1645 ssgTransform *acmodel_align = new ssgTransform;
1646 acmodel_align->addKid(acmodel_obj);
1650 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1651 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1652 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1653 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1654 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1655 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1656 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1657 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1658 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1659 acmodel_align->setTransform(res_matrix);
1661 acmodel_pos->addKid( acmodel_align );
1662 acmodel_selector->addKid( acmodel_pos );
1663 //ssgFlatten( acmodel_obj );
1664 //ssgStripify( acmodel_selector );
1665 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1666 scene->addKid( acmodel_selector );
1668 // $$$ begin - added VS Renganthan 17 Oct 2K
1670 // $$$ end - added VS Renganthan 17 Oct 2K
1672 #ifdef FG_NETWORK_OLK
1673 // Do the network intialization
1674 if ( fgGetBool("/sim/networking/network-olk") ) {
1675 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1679 // build our custom render states
1680 fgBuildRenderStates();
1682 // pass control off to the master GLUT event handler
1685 // we never actually get here ... but to avoid compiler warnings,
1691 // $$$ end - added VS Renganathan, 15 Oct 2K
1692 // - added Venky , 12 Nov 2K
1694 void fgLoadDCS(void) {
1696 ssgEntity *ship_obj = NULL;
1699 char obj_filename[25];
1701 for ( int k = 0; k < 32; k++ ) {
1705 SGPath tile_path( globals->get_fg_root());
1706 tile_path.append( "Scenery" );
1707 tile_path.append( "Objects.txt" );
1708 sg_gzifstream in( tile_path.str() );
1709 if ( ! in.is_open() ) {
1710 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1713 SGPath modelpath( globals->get_fg_root() );
1714 modelpath.append( "Models" );
1715 modelpath.append( "Geometry" );
1717 SGPath texturepath( globals->get_fg_root() );
1718 texturepath.append( "Models" );
1719 texturepath.append( "Textures" );
1721 ssgModelPath( (char *)modelpath.c_str() );
1722 ssgTexturePath( (char *)texturepath.c_str() );
1724 ship_sel = new ssgSelector;
1727 while ( ! in.eof() ) {
1729 if ( in.get( c ) && c == '#' ) {
1733 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1734 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1735 int chj=getchar();*/
1737 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1738 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1740 ship_pos[objc] = new ssgTransform;
1742 // type "repeat" in objects.txt to load one more
1743 // instance of the last object.
1745 if ( strcmp(obj_filename,"repeat") != 0) {
1746 ship_obj = ssgLoadOBJ( obj_filename );
1749 if ( ship_obj != NULL ) {
1750 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1751 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1753 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1759 if (in.eof()) break;
1763 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1765 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1766 scene->addKid( ship_sel ); //add selector node to root node
1773 void fgUpdateDCS (void) {
1775 // double eye_lat,eye_lon,eye_alt;
1776 // static double obj_head;
1777 double sl_radius,obj_latgc;
1778 // float nresultmat[4][4];
1779 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1782 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1783 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1785 // Deck should be the first object in objects.txt in case of fdm=ada
1787 if (fgGetString("/sim/flight-model") == "ada") {
1788 obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1789 obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1790 obj_alt[0] = fdm->get_aux7();
1793 for ( int m = 0; m < objc; m++ ) {
1794 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1797 //Geodetic to Geocentric angles for rotation
1798 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1800 //moving object gbs-posn in cartesian coords
1801 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1802 Point3D obj_pos = sgGeodToCart( obj_posn );
1804 // Translate moving object w.r.t eye
1805 Point3D Objtrans = obj_pos-scenery.center;
1810 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1813 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1815 sgVec3 ship_fwd,ship_rt,ship_up;
1816 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1817 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1818 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1820 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1821 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1822 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1823 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1826 sgCopyMat4( sgTUX, sgROT_hdg );
1827 sgPostMultMat4( sgTUX, sgROT_lat );
1828 sgPostMultMat4( sgTUX, sgROT_lon );
1829 sgPostMultMat4( sgTUX, sgTRANS );
1832 sgSetCoord(&shippos, sgTUX );
1833 ship_pos[m]->setTransform( &shippos );
1835 if ( ship_sel != NULL ) {
1836 ship_sel->select(0xFFFFFFFF);
1840 // $$$ end - added VS Renganathan, 15 Oct 2K
1841 // added Venky , 12 Nov 2K