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 #if defined(__linux__) && defined(__i386__)
29 # include <fpu_control.h>
33 #include <simgear/compiler.h>
34 #include <simgear/misc/exception.hxx>
35 #include <simgear/ephemeris/ephemeris.hxx>
36 #include <simgear/route/route.hxx>
38 #ifdef SG_MATH_EXCEPTION_CLASH
58 #ifdef HAVE_SYS_STAT_H
59 # include <sys/stat.h> // for stat()
63 # include <unistd.h> // for stat()
66 #include <plib/netChat.h>
70 #include <simgear/constants.h> // for VERSION
71 #include <simgear/debug/logstream.hxx>
72 #include <simgear/math/polar3d.hxx>
73 #include <simgear/math/sg_random.h>
74 #include <simgear/misc/sg_path.hxx>
75 #include <simgear/sky/sky.hxx>
76 #include <simgear/timing/sg_time.hxx>
78 #include <Include/general.hxx>
80 #include <Aircraft/aircraft.hxx>
82 #include <ATC/ATCmgr.hxx>
83 #include <ATC/ATCdisplay.hxx>
84 #include <Autopilot/newauto.hxx>
86 #include <Cockpit/cockpit.hxx>
87 #include <Cockpit/radiostack.hxx>
88 #include <Cockpit/steam.hxx>
90 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
92 // #include <Joystick/joystick.hxx>
94 #include <NetworkOLK/network.h>
96 #include <Objects/matlib.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #ifdef ENABLE_AUDIO_SUPPORT
100 # include <Sound/soundmgr.hxx>
101 # include <Sound/fg_fx.hxx>
102 # include <Sound/morse.hxx>
104 #include <Time/event.hxx>
105 #include <Time/fg_timer.hxx>
106 #include <Time/light.hxx>
107 #include <Time/sunpos.hxx>
108 #include <Time/tmp.hxx>
110 #include <Input/input.hxx>
113 #include <simgear/misc/sgstream.hxx>
114 #include <simgear/math/point3d.hxx>
115 #include <FDM/flight.hxx>
116 #include <FDM/ADA.hxx>
117 #include <Scenery/tileentry.hxx>
119 // Should already be inlcluded by gl.h if needed by your platform so
120 // we shouldn't include this here.
121 // #include <GL/glext.h>
123 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
124 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
126 float default_attenuation[3] = {1.0, 0.0, 0.0};
127 //Required for using GL_extensions
128 void fgLoadDCS (void);
129 void fgUpdateDCS (void);
130 ssgSelector *ship_sel=NULL;
131 // upto 32 instances of a same object can be loaded.
132 ssgTransform *ship_pos[32];
133 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
135 ssgSelector *lightpoints_brightness = new ssgSelector;
136 ssgTransform *lightpoints_transform = new ssgTransform;
137 FGTileEntry *dummy_tile;
141 #ifndef FG_NEW_ENVIRONMENT
142 # include <WeatherCM/FGLocalWeatherDatabase.h>
144 # include <Environment/environment_mgr.hxx>
149 #include "fg_init.hxx"
151 #include "fg_props.hxx"
152 #include "globals.hxx"
153 #include "splash.hxx"
154 #include "viewmgr.hxx"
155 #include "options.hxx"
156 #include "logger.hxx"
160 # include <console.h> // -dw- for command line dialog
164 // This is a record containing a bit of global housekeeping information
167 // Specify our current idle function state. This is used to run all
168 // our initializations out of the glutIdleLoop() so that we can get a
169 // splash screen up and running right away.
170 static int idle_state = 0;
171 static long global_multi_loop;
173 // forward declaration
174 void fgReshape( int width, int height );
177 ssgRoot *scene = NULL;
178 ssgBranch *terrain_branch = NULL;
179 ssgBranch *gnd_lights_branch = NULL;
180 ssgBranch *rwy_lights_branch = NULL;
182 // fog constants. I'm a little nervous about putting actual code out
183 // here but it seems to work (?)
184 static const double m_log01 = -log( 0.01 );
185 static const double sqrt_m_log01 = sqrt( m_log01 );
186 static GLfloat fog_exp_density;
187 static GLfloat fog_exp2_density;
188 static GLfloat fog_exp2_punch_through;
190 ssgRoot *lighting = NULL;
191 // ssgBranch *airport = NULL;
193 #ifdef FG_NETWORK_OLK
194 ssgSelector *fgd_sel = NULL;
195 ssgTransform *fgd_pos = NULL;
198 // current fdm/position used for view
199 FGInterface cur_view_fdm;
205 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
207 { 1.0f, 0.0f, 0.0f, 0.0f },
208 { 0.0f, 0.0f, -1.0f, 0.0f },
209 { 0.0f, 1.0f, 0.0f, 0.0f },
210 { 0.0f, 0.0f, 0.0f, 1.0f }
213 // The following defines flightgear options. Because glutlib will also
214 // want to parse its own options, those options must not be included here
215 // or they will get parsed by the main program option parser. Hence case
216 // is significant for any option added that might be in conflict with
219 // glutlib parses for:
221 // -direct (invalid in Win32)
225 // -indirect (invalid in Win32)
228 // Note that glutlib depends upon strings while this program's
229 // option parser wants only initial characters followed by numbers
234 ssgSimpleState *default_state;
235 ssgSimpleState *hud_and_panel;
236 ssgSimpleState *menus;
238 SGTimeStamp start_time_stamp;
239 SGTimeStamp current_time_stamp;
241 void fgBuildRenderStates( void ) {
242 default_state = new ssgSimpleState;
243 default_state->ref();
244 default_state->disable( GL_TEXTURE_2D );
245 default_state->enable( GL_CULL_FACE );
246 default_state->enable( GL_COLOR_MATERIAL );
247 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
248 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
249 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
250 default_state->disable( GL_BLEND );
251 default_state->disable( GL_ALPHA_TEST );
252 default_state->disable( GL_LIGHTING );
254 hud_and_panel = new ssgSimpleState;
255 hud_and_panel->ref();
256 hud_and_panel->disable( GL_CULL_FACE );
257 hud_and_panel->disable( GL_TEXTURE_2D );
258 hud_and_panel->disable( GL_LIGHTING );
259 hud_and_panel->enable( GL_BLEND );
261 menus = new ssgSimpleState;
263 menus->disable( GL_CULL_FACE );
264 menus->disable( GL_TEXTURE_2D );
265 menus->enable( GL_BLEND );
268 // fgFindNode -- a function that finds a named node in an ssg graph
269 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
270 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
272 } else if ( node->isAKindOf(ssgTypeBranch()) ) {
273 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
274 while ( kid != NULL ) {
275 ssgEntity *n = fgFindNode(kid, name);
279 kid = ((ssgBranch*)node)->getNextKid();
286 // fgInitVisuals() -- Initialize various GL/view parameters
287 void fgInitVisuals( void ) {
290 l = &cur_light_params;
292 #ifndef GLUT_WRONG_VERSION
293 // Go full screen if requested ...
294 if ( fgGetBool("/sim/startup/fullscreen") ) {
299 // If enabled, normal vectors specified with glNormal are scaled
300 // to unit length after transformation. See glNormal.
301 // glEnable( GL_NORMALIZE );
303 glEnable( GL_LIGHTING );
304 glEnable( GL_LIGHT0 );
305 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
308 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
309 ssgGetLight( 0 ) -> setPosition( sunpos );
311 // glFogi (GL_FOG_MODE, GL_LINEAR);
312 glFogi (GL_FOG_MODE, GL_EXP2);
313 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
314 (!fgGetBool("/sim/rendering/shading"))) {
315 // if fastest fog requested, or if flat shading force fastest
316 glHint ( GL_FOG_HINT, GL_FASTEST );
317 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
318 glHint ( GL_FOG_HINT, GL_NICEST );
320 if ( fgGetBool("/sim/rendering/wireframe") ) {
322 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
325 // This is the default anyways, but it can't hurt
326 glFrontFace ( GL_CCW );
329 // glEnable(GL_POINT_SMOOTH);
330 // glEnable(GL_LINE_SMOOTH);
331 // glEnable(GL_POLYGON_SMOOTH);
335 // For HiRes screen Dumps using Brian Pauls TR Library
336 void trRenderFrame( void ) {
338 if ( fgPanelVisible() ) {
339 GLfloat height = fgGetInt("/sim/startup/ysize");
341 (current_panel->getViewHeight() - current_panel->getYOffset())
342 * (height / 768.0) + 1;
343 glTranslatef( 0.0, view_h, 0.0 );
346 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
347 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
349 fgLIGHT *l = &cur_light_params;
351 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
352 l->adj_fog_color[2], l->adj_fog_color[3]);
354 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
356 // set the opengl state to known default values
357 default_state->force();
360 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
361 glFogi ( GL_FOG_MODE, GL_EXP2 );
362 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
364 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
365 // we only update GL_AMBIENT for our lights we will never get
366 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
367 // explicitely to black.
368 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
370 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
372 // texture parameters
373 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
374 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
376 // we need a white diffuse light for the phase of the moon
377 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
380 // draw the ssg scene
381 // return to the desired diffuse color
382 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
383 glEnable( GL_DEPTH_TEST );
384 ssgCullAndDraw( scene );
387 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
388 ssgCullAndDraw( lighting );
390 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
392 // need to do this here as hud_and_panel state is static to
393 // main.cxx and HUD and Panel routines have to be called with
394 // knowledge of the the TR struct < see gui.cxx::HighResDump()
395 hud_and_panel->apply();
399 // Update all Visuals (redraws anything graphics related)
400 void fgRenderFrame( void ) {
401 static const SGPropertyNode *longitude
402 = fgGetNode("/position/longitude-deg");
403 static const SGPropertyNode *latitude
404 = fgGetNode("/position/latitude-deg");
405 static const SGPropertyNode *altitude
406 = fgGetNode("/position/altitude-ft");
408 // Update the default (kludged) properties.
411 fgLIGHT *l = &cur_light_params;
412 static double last_visibility = -9999;
415 double actual_visibility = thesky->get_visibility();
416 if ( actual_visibility != last_visibility ) {
417 last_visibility = actual_visibility;
419 fog_exp_density = m_log01 / actual_visibility;
420 fog_exp2_density = sqrt_m_log01 / actual_visibility;
421 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
425 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
426 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
427 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
428 // GLfloat mat_shininess[] = { 10.0 };
429 GLbitfield clear_mask;
431 if ( idle_state != 1000 ) {
432 // still initializing, draw the splash screen
433 if ( fgGetBool("/sim/startup/splash-screen") ) {
436 start_time_stamp.stamp(); // Keep resetting the start time
438 // idle_state is now 1000 meaning we've finished all our
439 // initializations and are running the main loop, so this will
440 // now work without seg faulting the system.
442 // Update the elapsed time.
443 current_time_stamp.stamp();
444 globals->set_elapsed_time_ms((current_time_stamp - start_time_stamp)
447 // calculate our current position in cartesian space
448 scenery.set_center( scenery.get_next_center() );
451 fgReshape( fgGetInt("/sim/startup/xsize"),
452 fgGetInt("/sim/startup/ysize") );
454 // set the sun position
455 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
457 clear_mask = GL_DEPTH_BUFFER_BIT;
458 if ( fgGetBool("/sim/rendering/wireframe") ) {
459 clear_mask |= GL_COLOR_BUFFER_BIT;
462 if ( fgGetBool("/sim/rendering/skyblend") ) {
463 if ( fgGetBool("/sim/rendering/textures") ) {
464 // glClearColor(black[0], black[1], black[2], black[3]);
465 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
466 l->adj_fog_color[2], l->adj_fog_color[3]);
467 clear_mask |= GL_COLOR_BUFFER_BIT;
470 glClearColor(l->sky_color[0], l->sky_color[1],
471 l->sky_color[2], l->sky_color[3]);
472 clear_mask |= GL_COLOR_BUFFER_BIT;
474 glClear( clear_mask );
476 // Tell GL we are switching to model view parameters
478 // I really should create a derived ssg node or use a call
479 // back or something so that I can draw the sky within the
480 // ssgCullAndDraw() function, but for now I just mimic what
481 // ssg does to set up the model view matrix
482 glMatrixMode(GL_MODELVIEW);
484 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
486 // set the opengl state to known default values
487 default_state->force();
489 // update fog params if visibility has changed
490 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
492 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
493 ( global_multi_loop * fgGetInt("/sim/speed-up") )
494 / (double)fgGetInt("/sim/model-hz") );
496 // Set correct opengl fog density
497 glFogf (GL_FOG_DENSITY, fog_exp2_density);
499 // update the sky dome
500 if ( fgGetBool("/sim/rendering/skyblend") ) {
501 /* cout << "thesky->repaint() sky_color = "
502 << cur_light_params.sky_color[0] << " "
503 << cur_light_params.sky_color[1] << " "
504 << cur_light_params.sky_color[2] << " "
505 << cur_light_params.sky_color[3] << endl;
507 << cur_light_params.fog_color[0] << " "
508 << cur_light_params.fog_color[1] << " "
509 << cur_light_params.fog_color[2] << " "
510 << cur_light_params.fog_color[3] << endl;
511 cout << " sun_angle = " << cur_light_params.sun_angle
512 << " moon_angle = " << cur_light_params.moon_angle
514 thesky->repaint( cur_light_params.sky_color,
515 cur_light_params.adj_fog_color,
516 cur_light_params.sun_angle,
517 cur_light_params.moon_angle,
518 globals->get_ephem()->getNumPlanets(),
519 globals->get_ephem()->getPlanets(),
520 globals->get_ephem()->getNumStars(),
521 globals->get_ephem()->getStars() );
523 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
524 << view_pos[1] << " " << view_pos[2] << endl;
525 cout << " zero_elev = " << zero_elev[0] << " "
526 << zero_elev[1] << " " << zero_elev[2]
527 << " lon = " << cur_fdm_state->get_Longitude()
528 << " lat = " << cur_fdm_state->get_Latitude() << endl;
529 cout << " sun_rot = " << cur_light_params.sun_rotation
530 << " gst = " << SGTime::cur_time_params->getGst() << endl;
531 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
532 << " sun dec = " << globals->get_ephem()->getSunDeclination()
533 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
534 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
536 thesky->reposition( globals->get_current_view()->get_view_pos(),
537 globals->get_current_view()->get_zero_elev(),
538 globals->get_current_view()->get_world_up(),
539 longitude->getDoubleValue()
540 * SGD_DEGREES_TO_RADIANS,
541 latitude->getDoubleValue()
542 * SGD_DEGREES_TO_RADIANS,
543 altitude->getDoubleValue() * SG_FEET_TO_METER,
544 cur_light_params.sun_rotation,
545 globals->get_time_params()->getGst(),
546 globals->get_ephem()->getSunRightAscension(),
547 globals->get_ephem()->getSunDeclination(),
549 globals->get_ephem()->getMoonRightAscension(),
550 globals->get_ephem()->getMoonDeclination(),
554 glEnable( GL_DEPTH_TEST );
555 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
557 glFogi( GL_FOG_MODE, GL_EXP2 );
558 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
561 // set sun/lighting parameters
562 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
564 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
565 // we only update GL_AMBIENT for our lights we will never get
566 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
567 // explicitely to black.
568 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
569 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
570 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
572 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
573 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
574 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
576 // texture parameters
577 // glEnable( GL_TEXTURE_2D );
578 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
579 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
581 // glMatrixMode( GL_PROJECTION );
583 ssgSetFOV( globals->get_current_view()->get_h_fov(),
584 globals->get_current_view()->get_v_fov() );
586 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
587 - scenery.get_cur_elev();
589 if (fgGetBool("/sim/view/internal"))
590 ssgSetNearFar( 0.2f, 120000.0f );
591 else if ( agl > 10.0)
592 ssgSetNearFar( 10.0f, 120000.0f );
594 ssgSetNearFar( 0.5f, 120000.0f );
596 current_model.update(0); // FIXME: use real delta time
598 // $$$ begin - added VS Renganthan 17 Oct 2K
600 // $$$ end - added VS Renganthan 17 Oct 2K
602 # ifdef FG_NETWORK_OLK
603 if ( fgGetBool("/sim/networking/network-olk") ) {
605 other = head->next; /* put listpointer to start */
606 while ( other != tail) { /* display all except myself */
607 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
608 other->fgd_sel->select(1);
609 sgSetCoord( &fgdpos, other->sgFGD_COORD );
610 other->fgd_pos->setTransform( &fgdpos );
615 // fgd_sel->select(1);
616 // sgCopyMat4( sgTUX, current_view.sgVIEW);
618 // sgSetCoord( &fgdpos, sgFGD_VIEW );
619 // fgd_pos->setTransform( &fgdpos);
623 // position tile nodes and update range selectors
624 global_tile_mgr.prep_ssg_nodes();
626 if ( fgGetBool("/sim/rendering/skyblend") ) {
627 // draw the sky backdrop
629 // we need a white diffuse light for the phase of the moon
630 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
634 // return to the desired diffuse color
635 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
638 // draw the ssg scene
639 glEnable( GL_DEPTH_TEST );
640 ssgCullAndDraw( scene );
642 // change state for lighting here
645 // Set punch through fog density
646 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
648 #ifdef FG_EXPERIMENTAL_LIGHTING
649 // Enable states for drawing points with GL_extension
650 if (glutExtensionSupported("GL_EXT_point_parameters")) {
651 glEnable(GL_POINT_SMOOTH);
652 float quadratic[3] = {1.0, 0.01, 0.0001};
653 // get the address of our OpenGL extensions
655 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
656 wglGetProcAddress("glPointParameterfEXT");
657 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
658 wglGetProcAddress("glPointParameterfvEXT");
660 // makes the points fade as they move away
661 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
662 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
665 // Enable states for drawing runway lights with spherical mapping
666 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
667 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
668 glEnable(GL_TEXTURE_GEN_S);
669 glEnable(GL_TEXTURE_GEN_T);
671 //Maybe this is not the best way, but it works !!
672 glPolygonMode(GL_FRONT, GL_POINT);
674 glEnable(GL_CULL_FACE);
677 glDisable( GL_LIGHTING );
678 // blending function for runway lights
679 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
683 ssgCullAndDraw( lighting );
685 #ifdef FG_EXPERIMENTAL_LIGHTING
686 if (glutExtensionSupported("GL_EXT_point_parameters")) {
687 // Disable states used for runway lighting
688 glPolygonMode(GL_FRONT, GL_FILL);
690 glDisable(GL_TEXTURE_GEN_S);
691 glDisable(GL_TEXTURE_GEN_T);
692 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
693 default_attenuation);
699 if ( fgGetBool("/sim/rendering/skyblend") ) {
700 // draw the sky cloud layers
701 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
704 // display HUD && Panel
706 glDisable( GL_DEPTH_TEST );
707 // glDisable( GL_CULL_FACE );
708 // glDisable( GL_TEXTURE_2D );
710 // update the input subsystem
711 current_input.update(1); // FIXME: use real dt
713 // update the controls subsystem
714 globals->get_controls()->update(1); // FIXME: use real dt
716 hud_and_panel->apply();
719 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
720 // This only works properly if called before the panel call
721 globals->get_ATC_display()->update(1); // FIXME: use real dt
723 // update the panel subsystem
724 if ( current_panel != NULL ) {
725 current_panel->update(1); // FIXME: use real dt
728 // We can do translucent menus, so why not. :-)
730 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
732 // glDisable ( GL_BLEND ) ;
734 // glEnable( GL_FOG );
736 globals->get_logger()->update(0); // FIXME: use real dt
743 // Update internal time dependent calculations (i.e. flight model)
744 void fgUpdateTimeDepCalcs() {
745 static bool inited = false;
746 static const SGPropertyNode *master_freeze
747 = fgGetNode("/sim/freeze/master");
749 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
751 fgLIGHT *l = &cur_light_params;
756 // Initialize the FDM here if it hasn't been and if we have a
757 // scenery elevation hit.
759 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
760 // << " cur_elev = " << scenery.get_cur_elev() << endl;
762 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
763 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
765 cur_fdm_state->init();
766 if ( cur_fdm_state->get_bound() ) {
767 cur_fdm_state->unbind();
769 cur_fdm_state->bind();
772 // conceptually, the following block could be done for each fdm
774 if ( !cur_fdm_state->get_inited() ) {
775 // do nothing, fdm isn't inited yet
776 } else if ( master_freeze->getBoolValue() ) {
777 // we are frozen, run the fdm's with 0 time slices in case
778 // they want to do something with that.
780 cur_fdm_state->update( 0 );
781 FGSteam::update( 0 );
783 // we have been inited, and we are not frozen, we are good to go ...
786 cur_fdm_state->stamp();
792 long elapsed = current - cur_fdm_state->get_time_stamp();
793 cur_fdm_state->set_time_stamp( current );
794 elapsed += cur_fdm_state->get_remainder();
795 // cout << "elapsed = " << elapsed << endl;
796 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
797 multi_loop = (long)(((double)elapsed * 0.000001) /
798 cur_fdm_state->get_delta_t() );
799 cur_fdm_state->set_multi_loop( multi_loop );
800 long remainder = elapsed - (long)( (multi_loop*1000000) *
801 cur_fdm_state->get_delta_t() );
802 cur_fdm_state->set_remainder( remainder );
803 // cout << "remainder = " << remainder << endl;
805 // chop max interations to something reasonable if the sim was
806 // delayed for an excesive amount of time
807 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
808 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
809 cur_fdm_state->set_remainder( 0 );
812 // cout << "multi_loop = " << multi_loop << endl;
813 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
814 // run Autopilot system
815 globals->get_autopilot()->update(0); // FIXME: use real dt
818 cur_fdm_state->update( 1 );
820 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
823 if ( fgGetString("/sim/view-mode") == "pilot" ) {
824 cur_view_fdm = *cur_fdm_state;
828 // update the view angle
829 globals->get_viewmgr()->update(multi_loop);
833 // Update solar system
834 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
835 globals->get_time_params()->getLst(),
836 cur_fdm_state->get_Latitude() );
838 // Update radio stack model
839 current_radiostack->update(multi_loop);
843 void fgInitTimeDepCalcs( void ) {
846 // #ifdef HAVE_SETITIMER
847 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
848 // fgUpdateTimeDepCalcs );
849 // #endif HAVE_SETITIMER
853 static const double alt_adjust_ft = 3.758099;
854 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
857 // What should we do when we have nothing else to do? Let's get ready
858 // for the next move and update the display?
859 static void fgMainLoop( void ) {
860 static const SGPropertyNode *longitude
861 = fgGetNode("/position/longitude-deg");
862 static const SGPropertyNode *latitude
863 = fgGetNode("/position/latitude-deg");
864 static const SGPropertyNode *altitude
865 = fgGetNode("/position/altitude-ft");
866 static const SGPropertyNode *clock_freeze
867 = fgGetNode("/sim/freeze/clock", true);
868 static const SGPropertyNode *cur_time_override
869 = fgGetNode("/sim/time/cur-time-override", true);
871 static long remainder = 0;
873 #ifdef FANCY_FRAME_COUNTER
877 static time_t last_time = 0;
878 static int frames = 0;
879 #endif // FANCY_FRAME_COUNTER
881 SGTime *t = globals->get_time_params();
883 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
884 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
886 #ifdef FG_NETWORK_OLK
887 if ( fgGetBool("/sim/networking/network-olk") ) {
888 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
889 // printf("FGD: Netupdate\n");
890 fgd_send_com( "A", FGFS_host); // Send Mat4 data
891 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
896 #if defined( ENABLE_PLIB_JOYSTICK )
897 // Read joystick and update control settings
898 // if ( fgGetString("/sim/control-mode") == "joystick" )
902 #elif defined( ENABLE_GLUT_JOYSTICK )
903 // Glut joystick support works by feeding a joystick handler
904 // function to glut. This is taken care of once in the joystick
905 // init routine and we don't have to worry about it again.
908 #ifdef FG_NEW_ENVIRONMENT
909 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
912 // Fix elevation. I'm just sticking this here for now, it should
913 // probably move eventually
915 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
916 scenery.get_cur_elev(),
917 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
918 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
920 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
921 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
922 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
923 // now set aircraft altitude above ground
924 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
925 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
926 scenery.get_cur_elev() + alt_adjust_m - 3.0,
927 scenery.get_cur_elev() + alt_adjust_m );
928 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
931 SG_LOG( SG_ALL, SG_DEBUG,
932 "<*> resetting altitude to "
933 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
938 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
939 scenery.get_cur_elev(),
940 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
941 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
943 // cout << "Warp = " << globals->get_warp() << endl;
946 static bool last_clock_freeze = false;
948 if ( clock_freeze->getBoolValue() ) {
949 // clock freeze requested
950 if ( cur_time_override->getLongValue() == 0 ) {
951 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
952 globals->set_warp( 0 );
955 // no clock freeze requested
956 if ( last_clock_freeze == true ) {
957 // clock just unfroze, let's set warp as the difference
958 // between frozen time and current time so we don't get a
959 // time jump (and corresponding sky object and lighting
961 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
962 fgSetLong( "/sim/time/cur-time-override", 0 );
964 if ( globals->get_warp_delta() != 0 ) {
965 globals->inc_warp( globals->get_warp_delta() );
969 last_clock_freeze = clock_freeze->getBoolValue();
971 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
972 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
973 cur_time_override->getLongValue(),
974 globals->get_warp() );
976 if ( globals->get_warp_delta() != 0 ) {
977 fgUpdateSkyAndLightingParams();
980 // update magvar model
981 globals->get_mag()->update( longitude->getDoubleValue()
982 * SGD_DEGREES_TO_RADIANS,
983 latitude->getDoubleValue()
984 * SGD_DEGREES_TO_RADIANS,
985 altitude->getDoubleValue() * SG_FEET_TO_METER,
986 globals->get_time_params()->getJD() );
988 // Get elapsed time (in usec) for this past frame
989 elapsed = fgGetTimeInterval();
990 SG_LOG( SG_ALL, SG_DEBUG,
991 "Elapsed time interval is = " << elapsed
992 << ", previous remainder is = " << remainder );
994 // Calculate frame rate average
995 #ifdef FANCY_FRAME_COUNTER
996 /* old fps calculation */
1000 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1001 tmp = general.get_frame(i);
1003 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1004 general.set_frame(i+1,tmp);
1006 tmp = 1000000.0 / (float)elapsed;
1007 general.set_frame(0,tmp);
1008 // printf("frame[0] = %.2f\n", general.frames[0]);
1010 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1011 // printf("ave = %.2f\n", general.frame_rate);
1014 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1015 general.set_frame_rate( frames );
1016 SG_LOG( SG_ALL, SG_DEBUG,
1017 "--> Frame rate is = " << general.get_frame_rate() );
1020 last_time = t->get_cur_time();
1024 // Run ATC subsystem
1025 globals->get_ATC_mgr()->update(1); // FIXME: use real dt
1029 // Calculate model iterations needed for next frame
1030 elapsed += remainder;
1032 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1033 fgGetInt("/sim/model-hz"));
1034 remainder = elapsed - ( (global_multi_loop*1000000) /
1035 fgGetInt("/sim/model-hz") );
1036 SG_LOG( SG_ALL, SG_DEBUG,
1037 "Model iterations needed = " << global_multi_loop
1038 << ", new remainder = " << remainder );
1040 // chop max interations to something reasonable if the sim was
1041 // delayed for an excesive amount of time
1042 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1043 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1048 if ( global_multi_loop > 0 ) {
1049 fgUpdateTimeDepCalcs();
1051 SG_LOG( SG_ALL, SG_DEBUG,
1052 "Elapsed time is zero ... we're zinging" );
1055 #if ! defined( macintosh )
1056 // Do any I/O channel work that might need to be done
1060 // see if we need to load any new scenery tiles
1061 global_tile_mgr.update( longitude->getDoubleValue(),
1062 latitude->getDoubleValue() );
1064 // see if we need to load any deferred-load textures
1065 material_lib.load_next_deferred();
1067 // Process/manage pending events
1068 global_events.Process();
1070 // Run audio scheduler
1071 #ifdef ENABLE_AUDIO_SUPPORT
1072 if ( fgGetBool("/sim/sound/audible")
1073 && globals->get_soundmgr()->is_working() ) {
1074 globals->get_fx()->update(1); // FIXME: use dt
1075 globals->get_soundmgr()->update(1); // FIXME: use dt
1082 SG_LOG( SG_ALL, SG_DEBUG, "" );
1086 // This is the top level master main function that is registered as
1087 // our idle funciton
1090 // The first few passes take care of initialization things (a couple
1091 // per pass) and once everything has been initialized fgMainLoop from
1094 static void fgIdleFunction ( void ) {
1095 // printf("idle state == %d\n", idle_state);
1097 if ( idle_state == 0 ) {
1098 // Initialize the splash screen right away
1099 if ( fgGetBool("/sim/startup/splash-screen") ) {
1104 } else if ( idle_state == 1 ) {
1105 // Initialize audio support
1106 #ifdef ENABLE_AUDIO_SUPPORT
1108 // Start the intro music
1109 if ( fgGetBool("/sim/startup/intro-music") ) {
1110 SGPath mp3file( globals->get_fg_root() );
1111 mp3file.append( "Sounds/intro.mp3" );
1113 SG_LOG( SG_GENERAL, SG_INFO,
1114 "Starting intro music: " << mp3file.str() );
1116 #if defined( __CYGWIN__ )
1117 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1118 #elif defined( WIN32 )
1119 string command = "start /m " + mp3file.str();
1121 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1124 system ( command.c_str() );
1130 } else if ( idle_state == 2 ) {
1131 // These are a few miscellaneous things that aren't really
1132 // "subsystems" but still need to be initialized.
1135 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1136 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1141 } else if ( idle_state == 3 ) {
1142 // This is the top level init routine which calls all the
1143 // other subsystem initialization routines. If you are adding
1144 // a subsystem to flightgear, its initialization call should
1145 // located in this routine.
1146 if( !fgInitSubsystems()) {
1147 SG_LOG( SG_GENERAL, SG_ALERT,
1148 "Subsystem initializations failed ..." );
1153 } else if ( idle_state == 4 ) {
1154 // setup OpenGL view parameters
1158 } else if ( idle_state == 5 ) {
1161 } else if ( idle_state == 6 ) {
1165 cout << "Panel visible = " << fgPanelVisible() << endl;
1166 fgReshape( fgGetInt("/sim/startup/xsize"),
1167 fgGetInt("/sim/startup/ysize") );
1170 if ( idle_state == 1000 ) {
1171 // We've finished all our initialization steps, from now on we
1172 // run the main loop.
1176 if ( fgGetBool("/sim/startup/splash-screen") ) {
1177 fgSplashUpdate(0.0);
1182 // options.cxx needs to see this for toggle_panel()
1183 // Handle new window size or exposure
1184 void fgReshape( int width, int height ) {
1187 if ( (!fgGetBool("/sim/virtual-cockpit"))
1188 && fgPanelVisible() && idle_state == 1000 ) {
1189 view_h = (int)(height * (current_panel->getViewHeight() -
1190 current_panel->getYOffset()) / 768.0);
1196 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1197 globals->get_viewmgr()->get_view(i)->
1198 set_aspect_ratio((float)view_h / (float)width);
1201 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1203 fgSetInt("/sim/startup/xsize", width);
1204 fgSetInt("/sim/startup/ysize", height);
1205 guiInitMouse(width, height);
1207 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1208 globals->get_current_view()->get_v_fov() );
1214 // Initialize GLUT and define a main window
1215 int fgGlutInit( int *argc, char **argv ) {
1217 #if !defined( macintosh )
1218 // GLUT will extract all glut specific options so later on we only
1219 // need wory about our own.
1220 glutInit(argc, argv);
1223 // Define Display Parameters
1224 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1226 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1227 fgGetInt("/sim/startup/xsize") << "x"
1228 << fgGetInt("/sim/startup/ysize") );
1230 // Define initial window size
1231 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1232 fgGetInt("/sim/startup/ysize") );
1234 // Initialize windows
1235 if ( !fgGetBool("/sim/startup/game-mode")) {
1236 // Open the regular window
1237 glutCreateWindow("FlightGear");
1238 #ifndef GLUT_WRONG_VERSION
1240 // Open the cool new 'game mode' window
1241 char game_mode_str[256];
1242 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1243 fgGetInt("/sim/startup/xsize"),
1244 fgGetInt("/sim/startup/ysize"),
1245 fgGetInt("/sim/rendering/bits-per-pixel"));
1247 SG_LOG( SG_GENERAL, SG_INFO,
1248 "game mode params = " << game_mode_str );
1249 glutGameModeString( game_mode_str );
1250 glutEnterGameMode();
1254 // This seems to be the absolute earliest in the init sequence
1255 // that these calls will return valid info. Too bad it's after
1256 // we've already created and sized out window. :-(
1257 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1258 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1259 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1260 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1263 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1264 general.set_glMaxTexSize( tmp );
1265 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1267 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1268 general.set_glDepthBits( tmp );
1269 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1275 // Initialize GLUT event handlers
1276 int fgGlutInitEvents( void ) {
1277 // call fgReshape() on window resizes
1278 glutReshapeFunc( fgReshape );
1280 // call GLUTkey() on keyboard event
1281 glutKeyboardFunc(GLUTkey);
1282 glutKeyboardUpFunc(GLUTkeyup);
1283 glutSpecialFunc(GLUTspecialkey);
1284 glutSpecialUpFunc(GLUTspecialkeyup);
1286 // call guiMouseFunc() whenever our little rodent is used
1287 glutMouseFunc ( guiMouseFunc );
1288 glutMotionFunc (guiMotionFunc );
1289 glutPassiveMotionFunc (guiMotionFunc );
1291 // call fgMainLoop() whenever there is
1292 // nothing else to do
1293 glutIdleFunc( fgIdleFunction );
1296 glutDisplayFunc( fgRenderFrame );
1303 int mainLoop( int argc, char **argv ) {
1305 #if defined( macintosh )
1306 freopen ("stdout.txt", "w", stdout );
1307 freopen ("stderr.txt", "w", stderr );
1308 argc = ccommand( &argv );
1311 // set default log levels
1312 sglog().setLogLevels( SG_ALL, SG_INFO );
1315 #ifdef FLIGHTGEAR_VERSION
1316 version = FLIGHTGEAR_VERSION;
1318 version = "unknown version";
1320 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1321 << version << endl );
1323 // Allocate global data structures. This needs to happen before
1324 // we parse command line options
1326 globals = new FGGlobals;
1328 #if defined(FG_NEW_ENVIRONMENT)
1329 globals->set_environment_mgr(new FGEnvironmentMgr);
1332 // seed the random number generater
1335 SGRoute *route = new SGRoute;
1336 globals->set_route( route );
1338 FGControls *controls = new FGControls;
1339 globals->set_controls( controls );
1341 FGViewMgr *viewmgr = new FGViewMgr;
1342 globals->set_viewmgr( viewmgr );
1346 string_list *col = new string_list;
1347 globals->set_channel_options_list( col );
1349 // Scan the config file(s) and command line options to see if
1350 // fg_root was specified (ignore all other options for now)
1351 fgInitFGRoot(argc, argv);
1353 // Check for the correct base package version
1354 string base_version = fgBasePackageVersion();
1355 if ( !(base_version == "0.7.9") ) {
1356 // tell the operator how to use this application
1359 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1360 << "Found version " << base_version );
1361 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1365 // Initialize the Aircraft directory to "" (UIUC)
1368 // Load the configuration parameters
1369 if ( !fgInitConfig(argc, argv) ) {
1370 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1374 // Initialize the Window/Graphics environment.
1375 if( !fgGlutInit(&argc, argv) ) {
1376 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1380 // Initialize the various GLUT Event Handlers.
1381 if( !fgGlutInitEvents() ) {
1382 SG_LOG( SG_GENERAL, SG_ALERT,
1383 "GLUT event handler initialization failed ..." );
1387 // Initialize plib net interface
1388 netInit( &argc, argv );
1390 // Initialize ssg (from plib). Needs to come before we do any
1391 // other ssg stuff, but after opengl/glut has been initialized.
1394 // Initialize the user interface (we need to do this before
1395 // passing off control to glut and before fgInitGeneral to get our
1399 #ifdef GL_EXT_texture_lod_bias
1400 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1403 // Set position relative to glide slope if requested
1404 fgSetPosFromGlideSlope();
1406 // set current_options lon/lat if an airport id is specified
1407 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1408 if ( fgGetString("/sim/startup/airport-id").length() ) {
1409 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1410 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1411 fgGetDouble("/orientation/heading-deg") );
1414 SGTime *t = fgInitTime();
1415 globals->set_time_params( t );
1417 // Do some quick general initializations
1418 if( !fgInitGeneral()) {
1419 SG_LOG( SG_GENERAL, SG_ALERT,
1420 "General initializations failed ..." );
1424 SGPath modelpath( globals->get_fg_root() );
1425 ssgModelPath( (char *)modelpath.c_str() );
1428 scene = new ssgRoot;
1429 scene->setName( "Scene" );
1431 lighting = new ssgRoot;
1432 lighting->setName( "Lighting" );
1434 // Initialize the sky
1435 SGPath ephem_data_path( globals->get_fg_root() );
1436 ephem_data_path.append( "Astro" );
1437 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1438 ephem->update( globals->get_time_params()->getMjd(),
1439 globals->get_time_params()->getLst(),
1441 globals->set_ephem( ephem );
1445 SGPath sky_tex_path( globals->get_fg_root() );
1446 sky_tex_path.append( "Textures" );
1447 sky_tex_path.append( "Sky" );
1448 thesky->texture_path( sky_tex_path.str() );
1450 thesky->build( 550.0, 550.0,
1451 globals->get_ephem()->getNumPlanets(),
1452 globals->get_ephem()->getPlanets(), 60000.0,
1453 globals->get_ephem()->getNumStars(),
1454 globals->get_ephem()->getStars(), 60000.0 );
1456 if ( fgGetBool("/environment/clouds/status") ) {
1457 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1458 // SG_CLOUD_OVERCAST );
1459 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1461 200.0, 50.0, 40000.0,
1462 SG_CLOUD_MOSTLY_CLOUDY );
1463 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1464 // SG_CLOUD_MOSTLY_SUNNY );
1465 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1469 // Initialize MagVar model
1470 SGMagVar *magvar = new SGMagVar();
1471 globals->set_mag( magvar );
1474 terrain_branch = new ssgBranch;
1475 terrain_branch->setName( "Terrain" );
1476 scene->addKid( terrain_branch );
1479 gnd_lights_branch = new ssgBranch;
1480 gnd_lights_branch->setName( "Ground Lighting" );
1481 lighting->addKid( gnd_lights_branch );
1483 rwy_lights_branch = new ssgBranch;
1484 rwy_lights_branch->setName( "Runway Lighting" );
1485 lighting->addKid( rwy_lights_branch );
1487 // airport = new ssgBranch;
1488 // airport->setName( "Airport Lighting" );
1489 // lighting->addKid( airport );
1495 // temporary visible aircraft "own ship"
1496 current_model.init();
1498 #ifdef FG_NETWORK_OLK
1499 // Do the network intialization
1500 if ( fgGetBool("/sim/networking/network-olk") ) {
1501 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1505 // build our custom render states
1506 fgBuildRenderStates();
1508 // pass control off to the master GLUT event handler
1511 // we never actually get here ... but to avoid compiler warnings,
1517 // $$$ end - added VS Renganathan, 15 Oct 2K
1518 // - added Venky , 12 Nov 2K
1520 #if defined(__linux__) && defined(__i386__)
1522 static void handleFPE (int);
1527 fpu_control_t fpe_flags = 0;
1528 _FPU_GETCW(fpe_flags);
1529 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1530 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1531 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1532 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1533 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1534 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1535 _FPU_SETCW(fpe_flags);
1536 signal(SIGFPE, handleFPE);
1543 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1547 // Main entry point; catch any exceptions that have made it this far.
1548 int main ( int argc, char **argv ) {
1550 // Enable floating-point exceptions for Linux/x86
1551 #if defined(__linux__) && defined(__i386__)
1555 // Enable floating-point exceptions for Windows
1556 #if defined( _MSC_VER ) && defined( DEBUG )
1557 // Christian, we should document what this does
1558 _control87( _EM_INEXACT, _MCW_EM );
1561 #if defined( HAVE_BC5PLUS )
1562 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1565 // FIXME: add other, more specific
1568 mainLoop(argc, argv);
1569 } catch (sg_throwable &t) {
1570 SG_LOG(SG_GENERAL, SG_ALERT,
1571 "Fatal error: " << t.getFormattedMessage()
1572 << "\n (received from " << t.getOrigin() << ')');
1580 void fgLoadDCS(void) {
1582 ssgEntity *ship_obj = NULL;
1584 char obj_filename[25];
1586 for ( int k = 0; k < 32; k++ ) {
1590 SGPath tile_path( globals->get_fg_root());
1591 tile_path.append( "Scenery" );
1592 tile_path.append( "Objects.txt" );
1593 sg_gzifstream in( tile_path.str() );
1594 if ( ! in.is_open() ) {
1595 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1598 SGPath modelpath( globals->get_fg_root() );
1599 modelpath.append( "Models" );
1600 modelpath.append( "Geometry" );
1602 SGPath texturepath( globals->get_fg_root() );
1603 texturepath.append( "Models" );
1604 texturepath.append( "Textures" );
1606 ssgModelPath( (char *)modelpath.c_str() );
1607 ssgTexturePath( (char *)texturepath.c_str() );
1609 ship_sel = new ssgSelector;
1612 while ( ! in.eof() ) {
1614 if ( in.get( c ) && c == '#' ) {
1618 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1619 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1620 int chj=getchar();*/
1622 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1623 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1625 ship_pos[objc] = new ssgTransform;
1627 // type "repeat" in objects.txt to load one more
1628 // instance of the last object.
1630 if ( strcmp(obj_filename,"repeat") != 0) {
1631 ship_obj = ssgLoad( obj_filename );
1634 if ( ship_obj != NULL ) {
1635 ship_obj->setName(obj_filename);
1637 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1639 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1640 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1641 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1642 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1645 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1649 // temporary hack for deck lights - ultimately should move to PLib (when??)
1650 //const char *extn = file_extension ( obj_filename ) ;
1652 ssgVertexArray *lights = new ssgVertexArray( 100 );
1653 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1654 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1655 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1656 int ltype[500], light_type;
1657 static int ltcount = 0;
1659 sgVec3 rway_dir,rway_normal,lightpt;
1661 modelpath.append(obj_filename);
1662 sg_gzifstream in1( modelpath.str() );
1663 if ( ! in1.is_open() ) {
1664 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1666 while ( ! in1.eof() ) {
1668 if ( in1.get( c ) && c == '#' ) {
1673 //cout << token << endl;
1674 if ( token == "runway" ) {
1676 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1677 } else if ( token == "edgelight" ) {
1679 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1681 } else if ( token == "taxi" ) {
1683 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1685 } else if ( token == "vasi" ) {
1687 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1689 } else if ( token == "threshold" ) {
1691 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1693 } else if ( token == "rabbit" ) {
1695 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1697 } else if ( token == "ols" ) {
1699 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1701 } else if ( token == "red" ) {
1703 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1705 } else if ( token == "green" ) {
1707 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1709 } else if ( token == "lp" ) {
1711 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1712 lightpoints->add( lightpt );
1713 lightnormals->add( rway_normal );
1714 lightdir->add( rway_dir );
1715 ltype[ltcount]= light_type;
1718 if (in1.eof()) break;
1722 if ( lightpoints->getNum() ) {
1723 ssgBranch *lightpoints_branch;
1724 long int dummy = -999;
1725 dummy_tile = new FGTileEntry((SGBucket)dummy);
1726 dummy_tile->lightmaps_sequence = new ssgSelector;
1727 dummy_tile->ols_transform = new ssgTransform;
1729 // call function to generate the runway lights
1730 lightpoints_branch =
1731 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1733 lightpoints_brightness->addKid(lightpoints_branch);
1734 lightpoints_transform->addKid(lightpoints_brightness);
1735 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1736 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1737 lightpoints_transform->ref();
1738 gnd_lights_branch->addKid( lightpoints_transform );
1742 // end hack for deck lights
1746 if (in.eof()) break;
1750 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1752 terrain_branch->addKid( ship_sel ); //add selector node to root node
1759 void fgUpdateDCS (void) {
1761 // double eye_lat,eye_lon,eye_alt;
1762 // static double obj_head;
1763 double sl_radius,obj_latgc;
1764 // float nresultmat[4][4];
1765 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1768 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1769 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1771 // Deck should be the first object in objects.txt in case of fdm=ada
1773 if (fgGetString("/sim/flight-model") == "ada") {
1774 if ((fdm->get_iaux(1))==1)
1776 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1777 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1778 obj_alt[1] = fdm->get_daux(3);
1779 obj_pitch[1] = fdm->get_faux(1);
1780 obj_roll[1] = fdm->get_faux(2);
1784 for ( int m = 0; m < objc; m++ ) {
1785 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1788 //Geodetic to Geocentric angles for rotation
1789 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1791 //moving object gbs-posn in cartesian coords
1792 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1793 Point3D obj_pos = sgGeodToCart( obj_posn );
1795 // Translate moving object w.r.t eye
1796 Point3D Objtrans = obj_pos-scenery.get_center();
1801 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1804 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1806 sgVec3 ship_fwd,ship_rt,ship_up;
1807 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1808 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1809 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1811 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1812 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1813 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1814 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1815 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1816 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1819 sgCopyMat4( sgTUX, sgROT_hdg );
1820 sgPostMultMat4( sgTUX, sgROT_pitch );
1821 sgPostMultMat4( sgTUX, sgROT_roll );
1822 sgPostMultMat4( sgTUX, sgROT_lat );
1823 sgPostMultMat4( sgTUX, sgROT_lon );
1824 sgPostMultMat4( sgTUX, sgTRANS );
1827 sgSetCoord(&shippos, sgTUX );
1828 ship_pos[m]->setTransform( &shippos );
1829 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1831 if (lightpoints_transform) {
1832 lightpoints_transform->setTransform( &shippos );
1833 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1834 if ( sun_angle > 89 ) {
1835 lightpoints_brightness->select(0x01);
1837 lightpoints_brightness->select(0x00);
1846 sgXformPnt3( rp, rway_ols, sgTUX );
1847 vp = globals->get_current_view()->get_view_pos();
1848 to[0] = rp[0]-vp[0];
1849 to[1] = rp[1]-vp[1];
1850 to[2] = rp[2]-vp[2];
1851 float dist = sgLengthVec3( to );
1852 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1854 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1856 ref_elev = elev - 3.75; // +ve above, -ve below
1860 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1861 // if (ref_elev > 0.51) sel = 0x21;
1862 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1863 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1864 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1865 // if (ref_elev < -0.51) sel = 0x30;
1866 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1867 dummy_tile->lightmaps_sequence->select(sel);
1870 sgCopyVec3 (up, ship_up);
1872 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1874 sgScaleVec3 (up, 4.0*ref_elev);
1875 dummy_tile->ols_transform->setTransform(up);
1876 //cout << "ref_elev " << ref_elev << endl;
1878 // end hack for deck lights
1881 if ( ship_sel != NULL ) {
1882 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1886 // $$$ end - added VS Renganathan, 15 Oct 2K
1887 // added Venky , 12 Nov 2K