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
51 #include <string.h> // for strcmp()
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;
140 // Clip plane settings...
141 float cockpit_nearplane = 0.1f;
142 float cockpit_farplane = 120000.0f;
143 float scene_nearplane = 0.5f;
144 float scene_farplane = 120000.0f;
147 #ifndef FG_NEW_ENVIRONMENT
148 # include <WeatherCM/FGLocalWeatherDatabase.h>
150 # include <Environment/environment_mgr.hxx>
155 #include "fg_init.hxx"
157 #include "fg_props.hxx"
158 #include "globals.hxx"
159 #include "splash.hxx"
160 #include "viewmgr.hxx"
161 #include "options.hxx"
162 #include "logger.hxx"
166 # include <console.h> // -dw- for command line dialog
170 // This is a record containing a bit of global housekeeping information
173 // Specify our current idle function state. This is used to run all
174 // our initializations out of the glutIdleLoop() so that we can get a
175 // splash screen up and running right away.
176 static int idle_state = 0;
177 static long global_multi_loop;
179 // forward declaration
180 void fgReshape( int width, int height );
183 ssgRoot *scene = NULL;
184 ssgRoot *cockpit = NULL;
185 ssgBranch *terrain_branch = NULL;
186 ssgBranch *gnd_lights_branch = NULL;
187 ssgBranch *rwy_lights_branch = NULL;
189 // fog constants. I'm a little nervous about putting actual code out
190 // here but it seems to work (?)
191 static const double m_log01 = -log( 0.01 );
192 static const double sqrt_m_log01 = sqrt( m_log01 );
193 static GLfloat fog_exp_density;
194 static GLfloat fog_exp2_density;
195 static GLfloat fog_exp2_punch_through;
197 ssgRoot *lighting = NULL;
198 // ssgBranch *airport = NULL;
200 #ifdef FG_NETWORK_OLK
201 ssgSelector *fgd_sel = NULL;
202 ssgTransform *fgd_pos = NULL;
205 // current fdm/position used for view
206 FGInterface cur_view_fdm;
212 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
214 { 1.0f, 0.0f, 0.0f, 0.0f },
215 { 0.0f, 0.0f, -1.0f, 0.0f },
216 { 0.0f, 1.0f, 0.0f, 0.0f },
217 { 0.0f, 0.0f, 0.0f, 1.0f }
220 // The following defines flightgear options. Because glutlib will also
221 // want to parse its own options, those options must not be included here
222 // or they will get parsed by the main program option parser. Hence case
223 // is significant for any option added that might be in conflict with
226 // glutlib parses for:
228 // -direct (invalid in Win32)
232 // -indirect (invalid in Win32)
235 // Note that glutlib depends upon strings while this program's
236 // option parser wants only initial characters followed by numbers
241 ssgSimpleState *default_state;
242 ssgSimpleState *hud_and_panel;
243 ssgSimpleState *menus;
245 SGTimeStamp start_time_stamp;
246 SGTimeStamp current_time_stamp;
248 void fgBuildRenderStates( void ) {
249 default_state = new ssgSimpleState;
250 default_state->ref();
251 default_state->disable( GL_TEXTURE_2D );
252 default_state->enable( GL_CULL_FACE );
253 default_state->enable( GL_COLOR_MATERIAL );
254 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
255 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
256 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
257 default_state->disable( GL_BLEND );
258 default_state->disable( GL_ALPHA_TEST );
259 default_state->disable( GL_LIGHTING );
261 hud_and_panel = new ssgSimpleState;
262 hud_and_panel->ref();
263 hud_and_panel->disable( GL_CULL_FACE );
264 hud_and_panel->disable( GL_TEXTURE_2D );
265 hud_and_panel->disable( GL_LIGHTING );
266 hud_and_panel->enable( GL_BLEND );
268 menus = new ssgSimpleState;
270 menus->disable( GL_CULL_FACE );
271 menus->disable( GL_TEXTURE_2D );
272 menus->enable( GL_BLEND );
275 // fgInitVisuals() -- Initialize various GL/view parameters
276 void fgInitVisuals( void ) {
279 l = &cur_light_params;
281 #ifndef GLUT_WRONG_VERSION
282 // Go full screen if requested ...
283 if ( fgGetBool("/sim/startup/fullscreen") ) {
288 // If enabled, normal vectors specified with glNormal are scaled
289 // to unit length after transformation. See glNormal.
290 // glEnable( GL_NORMALIZE );
292 glEnable( GL_LIGHTING );
293 glEnable( GL_LIGHT0 );
294 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
297 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
298 ssgGetLight( 0 ) -> setPosition( sunpos );
300 // glFogi (GL_FOG_MODE, GL_LINEAR);
301 glFogi (GL_FOG_MODE, GL_EXP2);
302 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
303 (!fgGetBool("/sim/rendering/shading"))) {
304 // if fastest fog requested, or if flat shading force fastest
305 glHint ( GL_FOG_HINT, GL_FASTEST );
306 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
307 glHint ( GL_FOG_HINT, GL_NICEST );
309 if ( fgGetBool("/sim/rendering/wireframe") ) {
311 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
314 // This is the default anyways, but it can't hurt
315 glFrontFace ( GL_CCW );
318 // glEnable(GL_POINT_SMOOTH);
319 // glEnable(GL_LINE_SMOOTH);
320 // glEnable(GL_POLYGON_SMOOTH);
324 // For HiRes screen Dumps using Brian Pauls TR Library
325 void trRenderFrame( void ) {
327 if ( fgPanelVisible() ) {
328 GLfloat height = fgGetInt("/sim/startup/ysize");
330 (current_panel->getViewHeight() - current_panel->getYOffset())
331 * (height / 768.0) + 1;
332 glTranslatef( 0.0, view_h, 0.0 );
335 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
336 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
338 fgLIGHT *l = &cur_light_params;
340 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
341 l->adj_fog_color[2], l->adj_fog_color[3]);
343 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
345 // set the opengl state to known default values
346 default_state->force();
349 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
350 glFogi ( GL_FOG_MODE, GL_EXP2 );
351 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
353 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
354 // we only update GL_AMBIENT for our lights we will never get
355 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
356 // explicitely to black.
357 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
359 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
361 // texture parameters
362 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
363 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
365 // we need a white diffuse light for the phase of the moon
366 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
369 // draw the ssg scene
370 // return to the desired diffuse color
371 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
372 glEnable( GL_DEPTH_TEST );
373 ssgSetNearFar( scene_nearplane, scene_farplane );
374 ssgCullAndDraw( scene );
376 // if in cockpit view adjust nearfar...
377 if (globals->get_current_view()->getType() == 0 )
378 ssgSetNearFar( cockpit_nearplane, cockpit_farplane );
379 ssgCullAndDraw( cockpit );
382 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
383 ssgSetNearFar( scene_nearplane, scene_farplane );
384 ssgCullAndDraw( lighting );
386 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
388 // need to do this here as hud_and_panel state is static to
389 // main.cxx and HUD and Panel routines have to be called with
390 // knowledge of the the TR struct < see gui.cxx::HighResDump()
391 hud_and_panel->apply();
395 // Update all Visuals (redraws anything graphics related)
396 void fgRenderFrame( void ) {
398 static long old_elapsed_ms = 0;
400 int dt_ms = int(globals->get_elapsed_time_ms() - old_elapsed_ms);
401 old_elapsed_ms = globals->get_elapsed_time_ms();
403 static const SGPropertyNode *longitude
404 = fgGetNode("/position/longitude-deg");
405 static const SGPropertyNode *latitude
406 = fgGetNode("/position/latitude-deg");
407 static const SGPropertyNode *altitude
408 = fgGetNode("/position/altitude-ft");
410 // Update the default (kludged) properties.
413 fgLIGHT *l = &cur_light_params;
414 static double last_visibility = -9999;
417 double actual_visibility = thesky->get_visibility();
418 if ( actual_visibility != last_visibility ) {
419 last_visibility = actual_visibility;
421 fog_exp_density = m_log01 / actual_visibility;
422 fog_exp2_density = sqrt_m_log01 / actual_visibility;
423 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
427 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
428 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
429 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
430 // GLfloat mat_shininess[] = { 10.0 };
431 GLbitfield clear_mask;
433 if ( idle_state != 1000 ) {
434 // still initializing, draw the splash screen
435 if ( fgGetBool("/sim/startup/splash-screen") ) {
438 start_time_stamp.stamp(); // Keep resetting the start time
440 // idle_state is now 1000 meaning we've finished all our
441 // initializations and are running the main loop, so this will
442 // now work without seg faulting the system.
444 // Update the elapsed time.
445 current_time_stamp.stamp();
446 globals->set_elapsed_time_ms((current_time_stamp - start_time_stamp)
449 // calculate our current position in cartesian space
450 scenery.set_center( scenery.get_next_center() );
453 fgReshape( fgGetInt("/sim/startup/xsize"),
454 fgGetInt("/sim/startup/ysize") );
456 // set the sun position
457 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
459 clear_mask = GL_DEPTH_BUFFER_BIT;
460 if ( fgGetBool("/sim/rendering/wireframe") ) {
461 clear_mask |= GL_COLOR_BUFFER_BIT;
464 if ( fgGetBool("/sim/rendering/skyblend") ) {
465 if ( fgGetBool("/sim/rendering/textures") ) {
466 // glClearColor(black[0], black[1], black[2], black[3]);
467 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
468 l->adj_fog_color[2], l->adj_fog_color[3]);
469 clear_mask |= GL_COLOR_BUFFER_BIT;
472 glClearColor(l->sky_color[0], l->sky_color[1],
473 l->sky_color[2], l->sky_color[3]);
474 clear_mask |= GL_COLOR_BUFFER_BIT;
476 glClear( clear_mask );
478 // Tell GL we are switching to model view parameters
480 // I really should create a derived ssg node or use a call
481 // back or something so that I can draw the sky within the
482 // ssgCullAndDraw() function, but for now I just mimic what
483 // ssg does to set up the model view matrix
484 glMatrixMode(GL_MODELVIEW);
486 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
488 // set the opengl state to known default values
489 default_state->force();
491 // update fog params if visibility has changed
492 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
494 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
495 ( global_multi_loop * fgGetInt("/sim/speed-up") )
496 / (double)fgGetInt("/sim/model-hz") );
498 // Set correct opengl fog density
499 glFogf (GL_FOG_DENSITY, fog_exp2_density);
501 // update the sky dome
502 if ( fgGetBool("/sim/rendering/skyblend") ) {
503 /* cout << "thesky->repaint() sky_color = "
504 << cur_light_params.sky_color[0] << " "
505 << cur_light_params.sky_color[1] << " "
506 << cur_light_params.sky_color[2] << " "
507 << cur_light_params.sky_color[3] << endl;
509 << cur_light_params.fog_color[0] << " "
510 << cur_light_params.fog_color[1] << " "
511 << cur_light_params.fog_color[2] << " "
512 << cur_light_params.fog_color[3] << endl;
513 cout << " sun_angle = " << cur_light_params.sun_angle
514 << " moon_angle = " << cur_light_params.moon_angle
516 thesky->repaint( cur_light_params.sky_color,
517 cur_light_params.adj_fog_color,
518 cur_light_params.sun_angle,
519 cur_light_params.moon_angle,
520 globals->get_ephem()->getNumPlanets(),
521 globals->get_ephem()->getPlanets(),
522 globals->get_ephem()->getNumStars(),
523 globals->get_ephem()->getStars() );
525 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
526 << view_pos[1] << " " << view_pos[2] << endl;
527 cout << " zero_elev = " << zero_elev[0] << " "
528 << zero_elev[1] << " " << zero_elev[2]
529 << " lon = " << cur_fdm_state->get_Longitude()
530 << " lat = " << cur_fdm_state->get_Latitude() << endl;
531 cout << " sun_rot = " << cur_light_params.sun_rotation
532 << " gst = " << SGTime::cur_time_params->getGst() << endl;
533 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
534 << " sun dec = " << globals->get_ephem()->getSunDeclination()
535 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
536 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
538 thesky->reposition( globals->get_current_view()->get_view_pos(),
539 globals->get_current_view()->get_zero_elev(),
540 globals->get_current_view()->get_world_up(),
541 longitude->getDoubleValue()
542 * SGD_DEGREES_TO_RADIANS,
543 latitude->getDoubleValue()
544 * SGD_DEGREES_TO_RADIANS,
545 altitude->getDoubleValue() * SG_FEET_TO_METER,
546 cur_light_params.sun_rotation,
547 globals->get_time_params()->getGst(),
548 globals->get_ephem()->getSunRightAscension(),
549 globals->get_ephem()->getSunDeclination(),
551 globals->get_ephem()->getMoonRightAscension(),
552 globals->get_ephem()->getMoonDeclination(),
556 glEnable( GL_DEPTH_TEST );
557 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
559 glFogi( GL_FOG_MODE, GL_EXP2 );
560 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
563 // set sun/lighting parameters
564 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
566 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
567 // we only update GL_AMBIENT for our lights we will never get
568 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
569 // explicitely to black.
570 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
571 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
572 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
574 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
575 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
576 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
578 // texture parameters
579 // glEnable( GL_TEXTURE_2D );
580 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
581 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
583 // glMatrixMode( GL_PROJECTION );
585 ssgSetFOV( globals->get_current_view()->get_h_fov(),
586 globals->get_current_view()->get_v_fov() );
588 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
589 - scenery.get_cur_elev();
591 // if (fgGetBool("/sim/view/internal"))
592 // ssgSetNearFar( 0.2f, 120000.0f );
593 // else if ( agl > 10.0)
596 scene_nearplane = 10.0f;
597 scene_farplane = 120000.0f;
599 scene_nearplane = 0.5f;
600 scene_farplane = 120000.0f;
603 ssgSetNearFar( scene_nearplane, scene_farplane );
605 current_model.update(dt_ms);
607 // $$$ begin - added VS Renganthan 17 Oct 2K
609 // $$$ end - added VS Renganthan 17 Oct 2K
611 # ifdef FG_NETWORK_OLK
612 if ( fgGetBool("/sim/networking/network-olk") ) {
614 other = head->next; /* put listpointer to start */
615 while ( other != tail) { /* display all except myself */
616 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
617 other->fgd_sel->select(1);
618 sgSetCoord( &fgdpos, other->sgFGD_COORD );
619 other->fgd_pos->setTransform( &fgdpos );
624 // fgd_sel->select(1);
625 // sgCopyMat4( sgTUX, current_view.sgVIEW);
627 // sgSetCoord( &fgdpos, sgFGD_VIEW );
628 // fgd_pos->setTransform( &fgdpos);
632 // position tile nodes and update range selectors
633 global_tile_mgr.prep_ssg_nodes();
635 if ( fgGetBool("/sim/rendering/skyblend") ) {
636 // draw the sky backdrop
638 // we need a white diffuse light for the phase of the moon
639 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
643 // return to the desired diffuse color
644 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
647 // draw the ssg scene
648 glEnable( GL_DEPTH_TEST );
650 ssgSetNearFar( scene_nearplane, scene_farplane );
651 ssgCullAndDraw( scene );
653 // change state for lighting here
656 // Set punch through fog density
657 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
659 #ifdef FG_EXPERIMENTAL_LIGHTING
660 // Enable states for drawing points with GL_extension
661 if (glutExtensionSupported("GL_EXT_point_parameters")) {
662 glEnable(GL_POINT_SMOOTH);
663 float quadratic[3] = {1.0, 0.01, 0.0001};
664 // get the address of our OpenGL extensions
666 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
667 wglGetProcAddress("glPointParameterfEXT");
668 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
669 wglGetProcAddress("glPointParameterfvEXT");
671 // makes the points fade as they move away
672 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
673 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
676 // Enable states for drawing runway lights with spherical mapping
677 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
678 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
679 glEnable(GL_TEXTURE_GEN_S);
680 glEnable(GL_TEXTURE_GEN_T);
682 //Maybe this is not the best way, but it works !!
683 glPolygonMode(GL_FRONT, GL_POINT);
685 glEnable(GL_CULL_FACE);
688 glDisable( GL_LIGHTING );
689 // blending function for runway lights
690 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
694 ssgSetNearFar( scene_nearplane, scene_farplane );
695 ssgCullAndDraw( lighting );
698 #ifdef FG_EXPERIMENTAL_LIGHTING
699 if (glutExtensionSupported("GL_EXT_point_parameters")) {
700 // Disable states used for runway lighting
701 glPolygonMode(GL_FRONT, GL_FILL);
703 glDisable(GL_TEXTURE_GEN_S);
704 glDisable(GL_TEXTURE_GEN_T);
705 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
706 default_attenuation);
712 if ( fgGetBool("/sim/rendering/skyblend") ) {
713 // draw the sky cloud layers
714 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
717 // if in cockpit view adjust nearfar...
718 if (globals->get_current_view()->getType() == 0 ) {
720 glClear(GL_DEPTH_BUFFER_BIT);
721 ssgSetNearFar( cockpit_nearplane, cockpit_farplane );
722 ssgCullAndDraw( cockpit );
724 ssgCullAndDraw( cockpit );
727 // display HUD && Panel
729 glDisable( GL_DEPTH_TEST );
730 // glDisable( GL_CULL_FACE );
731 // glDisable( GL_TEXTURE_2D );
733 // update the input subsystem
734 current_input.update(dt_ms);
736 // update the controls subsystem
737 globals->get_controls()->update(dt_ms);
739 hud_and_panel->apply();
742 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
743 // This only works properly if called before the panel call
744 globals->get_ATC_display()->update(dt_ms);
746 // update the panel subsystem
747 if ( current_panel != NULL ) {
748 current_panel->update(dt_ms);
751 // We can do translucent menus, so why not. :-)
753 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
755 // glDisable ( GL_BLEND ) ;
757 // glEnable( GL_FOG );
759 globals->get_logger()->update(dt_ms);
766 // Update internal time dependent calculations (i.e. flight model)
767 void fgUpdateTimeDepCalcs() {
768 static bool inited = false;
769 static const SGPropertyNode *master_freeze
770 = fgGetNode("/sim/freeze/master");
772 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
774 fgLIGHT *l = &cur_light_params;
779 // Initialize the FDM here if it hasn't been and if we have a
780 // scenery elevation hit.
782 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
783 // << " cur_elev = " << scenery.get_cur_elev() << endl;
785 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
786 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
788 cur_fdm_state->init();
789 if ( cur_fdm_state->get_bound() ) {
790 cur_fdm_state->unbind();
792 cur_fdm_state->bind();
795 // conceptually, the following block could be done for each fdm
797 if ( !cur_fdm_state->get_inited() ) {
798 // do nothing, fdm isn't inited yet
799 } else if ( master_freeze->getBoolValue() ) {
800 // we are frozen, run the fdm's with 0 time slices in case
801 // they want to do something with that.
803 cur_fdm_state->update( 0 );
804 FGSteam::update( 0 );
806 // we have been inited, and we are not frozen, we are good to go ...
809 cur_fdm_state->stamp();
815 long elapsed = current - cur_fdm_state->get_time_stamp();
816 cur_fdm_state->set_time_stamp( current );
817 elapsed += cur_fdm_state->get_remainder();
818 // cout << "elapsed = " << elapsed << endl;
819 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
820 multi_loop = (long)(((double)elapsed * 0.000001) /
821 cur_fdm_state->get_delta_t() );
822 cur_fdm_state->set_multi_loop( multi_loop );
823 long remainder = elapsed - (long)( (multi_loop*1000000) *
824 cur_fdm_state->get_delta_t() );
825 cur_fdm_state->set_remainder( remainder );
826 // cout << "remainder = " << remainder << endl;
828 // chop max interations to something reasonable if the sim was
829 // delayed for an excesive amount of time
830 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
831 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
832 cur_fdm_state->set_remainder( 0 );
835 // cout << "multi_loop = " << multi_loop << endl;
836 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
837 // run Autopilot system
838 globals->get_autopilot()->update(0); // FIXME: use real dt
841 cur_fdm_state->update( 1 );
843 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
846 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
847 cur_view_fdm = *cur_fdm_state;
851 // update the view angle
852 globals->get_viewmgr()->update(multi_loop);
856 // Update solar system
857 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
858 globals->get_time_params()->getLst(),
859 cur_fdm_state->get_Latitude() );
861 // Update radio stack model
862 current_radiostack->update(multi_loop);
866 void fgInitTimeDepCalcs( void ) {
869 // #ifdef HAVE_SETITIMER
870 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
871 // fgUpdateTimeDepCalcs );
872 // #endif HAVE_SETITIMER
876 static const double alt_adjust_ft = 3.758099;
877 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
880 // What should we do when we have nothing else to do? Let's get ready
881 // for the next move and update the display?
882 static void fgMainLoop( void ) {
883 static const SGPropertyNode *longitude
884 = fgGetNode("/position/longitude-deg");
885 static const SGPropertyNode *latitude
886 = fgGetNode("/position/latitude-deg");
887 static const SGPropertyNode *altitude
888 = fgGetNode("/position/altitude-ft");
889 static const SGPropertyNode *clock_freeze
890 = fgGetNode("/sim/freeze/clock", true);
891 static const SGPropertyNode *cur_time_override
892 = fgGetNode("/sim/time/cur-time-override", true);
894 static long remainder = 0;
896 #ifdef FANCY_FRAME_COUNTER
900 static time_t last_time = 0;
901 static int frames = 0;
902 #endif // FANCY_FRAME_COUNTER
904 SGTime *t = globals->get_time_params();
906 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
907 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
909 #ifdef FG_NETWORK_OLK
910 if ( fgGetBool("/sim/networking/network-olk") ) {
911 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
912 // printf("FGD: Netupdate\n");
913 fgd_send_com( "A", FGFS_host); // Send Mat4 data
914 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
919 #if defined( ENABLE_PLIB_JOYSTICK )
920 // Read joystick and update control settings
921 // if ( fgGetString("/sim/control-mode") == "joystick" )
925 #elif defined( ENABLE_GLUT_JOYSTICK )
926 // Glut joystick support works by feeding a joystick handler
927 // function to glut. This is taken care of once in the joystick
928 // init routine and we don't have to worry about it again.
931 #ifdef FG_NEW_ENVIRONMENT
932 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
935 // Fix elevation. I'm just sticking this here for now, it should
936 // probably move eventually
938 /* printf("Before - 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 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
944 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
945 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
946 // now set aircraft altitude above ground
947 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
948 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
949 scenery.get_cur_elev() + alt_adjust_m - 3.0,
950 scenery.get_cur_elev() + alt_adjust_m );
951 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
954 SG_LOG( SG_ALL, SG_DEBUG,
955 "<*> resetting altitude to "
956 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
961 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
962 scenery.get_cur_elev(),
963 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
964 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
966 // cout << "Warp = " << globals->get_warp() << endl;
969 static bool last_clock_freeze = false;
971 if ( clock_freeze->getBoolValue() ) {
972 // clock freeze requested
973 if ( cur_time_override->getLongValue() == 0 ) {
974 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
975 globals->set_warp( 0 );
978 // no clock freeze requested
979 if ( last_clock_freeze == true ) {
980 // clock just unfroze, let's set warp as the difference
981 // between frozen time and current time so we don't get a
982 // time jump (and corresponding sky object and lighting
984 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
985 fgSetLong( "/sim/time/cur-time-override", 0 );
987 if ( globals->get_warp_delta() != 0 ) {
988 globals->inc_warp( globals->get_warp_delta() );
992 last_clock_freeze = clock_freeze->getBoolValue();
994 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
995 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
996 cur_time_override->getLongValue(),
997 globals->get_warp() );
999 if ( globals->get_warp_delta() != 0 ) {
1000 fgUpdateSkyAndLightingParams();
1003 // update magvar model
1004 globals->get_mag()->update( longitude->getDoubleValue()
1005 * SGD_DEGREES_TO_RADIANS,
1006 latitude->getDoubleValue()
1007 * SGD_DEGREES_TO_RADIANS,
1008 altitude->getDoubleValue() * SG_FEET_TO_METER,
1009 globals->get_time_params()->getJD() );
1011 // Get elapsed time (in usec) for this past frame
1012 elapsed = fgGetTimeInterval();
1013 SG_LOG( SG_ALL, SG_DEBUG,
1014 "Elapsed time interval is = " << elapsed
1015 << ", previous remainder is = " << remainder );
1017 // Calculate frame rate average
1018 #ifdef FANCY_FRAME_COUNTER
1019 /* old fps calculation */
1020 if ( elapsed > 0 ) {
1023 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1024 tmp = general.get_frame(i);
1026 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1027 general.set_frame(i+1,tmp);
1029 tmp = 1000000.0 / (float)elapsed;
1030 general.set_frame(0,tmp);
1031 // printf("frame[0] = %.2f\n", general.frames[0]);
1033 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1034 // printf("ave = %.2f\n", general.frame_rate);
1037 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1038 general.set_frame_rate( frames );
1039 SG_LOG( SG_ALL, SG_DEBUG,
1040 "--> Frame rate is = " << general.get_frame_rate() );
1043 last_time = t->get_cur_time();
1047 // Run ATC subsystem
1048 globals->get_ATC_mgr()->update(1); // FIXME: use real dt
1052 // Calculate model iterations needed for next frame
1053 elapsed += remainder;
1055 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1056 fgGetInt("/sim/model-hz"));
1057 remainder = elapsed - ( (global_multi_loop*1000000) /
1058 fgGetInt("/sim/model-hz") );
1059 SG_LOG( SG_ALL, SG_DEBUG,
1060 "Model iterations needed = " << global_multi_loop
1061 << ", new remainder = " << remainder );
1063 // chop max interations to something reasonable if the sim was
1064 // delayed for an excesive amount of time
1065 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1066 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1071 if ( global_multi_loop > 0 ) {
1072 fgUpdateTimeDepCalcs();
1074 SG_LOG( SG_ALL, SG_DEBUG,
1075 "Elapsed time is zero ... we're zinging" );
1078 #if ! defined( macintosh )
1079 // Do any I/O channel work that might need to be done
1083 // see if we need to load any new scenery tiles
1084 global_tile_mgr.update( longitude->getDoubleValue(),
1085 latitude->getDoubleValue() );
1087 // see if we need to load any deferred-load textures
1088 material_lib.load_next_deferred();
1090 // Process/manage pending events
1091 global_events.Process();
1093 // Run audio scheduler
1094 #ifdef ENABLE_AUDIO_SUPPORT
1095 if ( fgGetBool("/sim/sound/audible")
1096 && globals->get_soundmgr()->is_working() ) {
1097 globals->get_fx()->update(1); // FIXME: use dt
1098 globals->get_soundmgr()->update(1); // FIXME: use dt
1105 SG_LOG( SG_ALL, SG_DEBUG, "" );
1109 // This is the top level master main function that is registered as
1110 // our idle funciton
1113 // The first few passes take care of initialization things (a couple
1114 // per pass) and once everything has been initialized fgMainLoop from
1117 static void fgIdleFunction ( void ) {
1118 // printf("idle state == %d\n", idle_state);
1120 if ( idle_state == 0 ) {
1121 // Initialize the splash screen right away
1122 if ( fgGetBool("/sim/startup/splash-screen") ) {
1127 } else if ( idle_state == 1 ) {
1128 // Initialize audio support
1129 #ifdef ENABLE_AUDIO_SUPPORT
1131 // Start the intro music
1132 if ( fgGetBool("/sim/startup/intro-music") ) {
1133 SGPath mp3file( globals->get_fg_root() );
1134 mp3file.append( "Sounds/intro.mp3" );
1136 SG_LOG( SG_GENERAL, SG_INFO,
1137 "Starting intro music: " << mp3file.str() );
1139 #if defined( __CYGWIN__ )
1140 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1141 #elif defined( WIN32 )
1142 string command = "start /m " + mp3file.str();
1144 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1147 system ( command.c_str() );
1153 } else if ( idle_state == 2 ) {
1154 // These are a few miscellaneous things that aren't really
1155 // "subsystems" but still need to be initialized.
1158 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1159 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1164 } else if ( idle_state == 3 ) {
1165 // This is the top level init routine which calls all the
1166 // other subsystem initialization routines. If you are adding
1167 // a subsystem to flightgear, its initialization call should
1168 // located in this routine.
1169 if( !fgInitSubsystems()) {
1170 SG_LOG( SG_GENERAL, SG_ALERT,
1171 "Subsystem initializations failed ..." );
1176 } else if ( idle_state == 4 ) {
1177 // setup OpenGL view parameters
1181 } else if ( idle_state == 5 ) {
1184 } else if ( idle_state == 6 ) {
1188 cout << "Panel visible = " << fgPanelVisible() << endl;
1189 fgReshape( fgGetInt("/sim/startup/xsize"),
1190 fgGetInt("/sim/startup/ysize") );
1193 if ( idle_state == 1000 ) {
1194 // We've finished all our initialization steps, from now on we
1195 // run the main loop.
1199 if ( fgGetBool("/sim/startup/splash-screen") ) {
1200 fgSplashUpdate(0.0);
1205 // options.cxx needs to see this for toggle_panel()
1206 // Handle new window size or exposure
1207 void fgReshape( int width, int height ) {
1210 if ( (!fgGetBool("/sim/virtual-cockpit"))
1211 && fgPanelVisible() && idle_state == 1000 ) {
1212 view_h = (int)(height * (current_panel->getViewHeight() -
1213 current_panel->getYOffset()) / 768.0);
1219 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1220 globals->get_viewmgr()->get_view(i)->
1221 set_aspect_ratio((float)view_h / (float)width);
1224 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1226 fgSetInt("/sim/startup/xsize", width);
1227 fgSetInt("/sim/startup/ysize", height);
1228 guiInitMouse(width, height);
1230 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1231 globals->get_current_view()->get_v_fov() );
1237 // Initialize GLUT and define a main window
1238 int fgGlutInit( int *argc, char **argv ) {
1240 #if !defined( macintosh )
1241 // GLUT will extract all glut specific options so later on we only
1242 // need wory about our own.
1243 glutInit(argc, argv);
1246 // Define Display Parameters
1247 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1249 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1250 fgGetInt("/sim/startup/xsize") << "x"
1251 << fgGetInt("/sim/startup/ysize") );
1253 // Define initial window size
1254 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1255 fgGetInt("/sim/startup/ysize") );
1257 // Initialize windows
1258 if ( !fgGetBool("/sim/startup/game-mode")) {
1259 // Open the regular window
1260 glutCreateWindow("FlightGear");
1261 #ifndef GLUT_WRONG_VERSION
1263 // Open the cool new 'game mode' window
1264 char game_mode_str[256];
1265 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1266 fgGetInt("/sim/startup/xsize"),
1267 fgGetInt("/sim/startup/ysize"),
1268 fgGetInt("/sim/rendering/bits-per-pixel"));
1270 SG_LOG( SG_GENERAL, SG_INFO,
1271 "game mode params = " << game_mode_str );
1272 glutGameModeString( game_mode_str );
1273 glutEnterGameMode();
1277 // This seems to be the absolute earliest in the init sequence
1278 // that these calls will return valid info. Too bad it's after
1279 // we've already created and sized out window. :-(
1280 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1281 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1282 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1283 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1286 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1287 general.set_glMaxTexSize( tmp );
1288 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1290 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1291 general.set_glDepthBits( tmp );
1292 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1298 // Initialize GLUT event handlers
1299 int fgGlutInitEvents( void ) {
1300 // call fgReshape() on window resizes
1301 glutReshapeFunc( fgReshape );
1303 // keyboard and mouse callbacks are set in FGInput::init
1305 #ifndef FG_NEW_MOUSE
1306 // call guiMouseFunc() whenever our little rodent is used
1307 glutMouseFunc ( guiMouseFunc );
1308 glutMotionFunc (guiMotionFunc );
1309 glutPassiveMotionFunc (guiMotionFunc );
1312 // call fgMainLoop() whenever there is
1313 // nothing else to do
1314 glutIdleFunc( fgIdleFunction );
1317 glutDisplayFunc( fgRenderFrame );
1324 int mainLoop( int argc, char **argv ) {
1326 #if defined( macintosh )
1327 freopen ("stdout.txt", "w", stdout );
1328 freopen ("stderr.txt", "w", stderr );
1329 argc = ccommand( &argv );
1332 // set default log levels
1333 sglog().setLogLevels( SG_ALL, SG_INFO );
1336 #ifdef FLIGHTGEAR_VERSION
1337 version = FLIGHTGEAR_VERSION;
1339 version = "unknown version";
1341 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1342 << version << endl );
1344 // Allocate global data structures. This needs to happen before
1345 // we parse command line options
1347 globals = new FGGlobals;
1349 #if defined(FG_NEW_ENVIRONMENT)
1350 globals->set_environment_mgr(new FGEnvironmentMgr);
1353 // seed the random number generater
1356 SGRoute *route = new SGRoute;
1357 globals->set_route( route );
1359 FGControls *controls = new FGControls;
1360 globals->set_controls( controls );
1362 FGViewMgr *viewmgr = new FGViewMgr;
1363 globals->set_viewmgr( viewmgr );
1367 string_list *col = new string_list;
1368 globals->set_channel_options_list( col );
1370 // Scan the config file(s) and command line options to see if
1371 // fg_root was specified (ignore all other options for now)
1372 fgInitFGRoot(argc, argv);
1374 // Check for the correct base package version
1375 string base_version = fgBasePackageVersion();
1376 if ( !(base_version == "0.7.9") ) {
1377 // tell the operator how to use this application
1380 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1381 << "Found version " << base_version );
1382 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1386 // Initialize the Aircraft directory to "" (UIUC)
1389 // Load the configuration parameters
1390 if ( !fgInitConfig(argc, argv) ) {
1391 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1395 // Initialize the Window/Graphics environment.
1396 if( !fgGlutInit(&argc, argv) ) {
1397 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1401 // Initialize the various GLUT Event Handlers.
1402 if( !fgGlutInitEvents() ) {
1403 SG_LOG( SG_GENERAL, SG_ALERT,
1404 "GLUT event handler initialization failed ..." );
1408 // Initialize plib net interface
1409 netInit( &argc, argv );
1411 // Initialize ssg (from plib). Needs to come before we do any
1412 // other ssg stuff, but after opengl/glut has been initialized.
1415 // Initialize the user interface (we need to do this before
1416 // passing off control to glut and before fgInitGeneral to get our
1420 #ifdef GL_EXT_texture_lod_bias
1421 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1424 // Set position relative to glide slope if requested
1425 fgSetPosFromGlideSlope();
1427 // set current_options lon/lat if an airport id is specified
1428 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1429 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1430 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1431 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1432 fgGetDouble("/orientation/heading-deg") );
1435 SGTime *t = fgInitTime();
1436 globals->set_time_params( t );
1438 // Do some quick general initializations
1439 if( !fgInitGeneral()) {
1440 SG_LOG( SG_GENERAL, SG_ALERT,
1441 "General initializations failed ..." );
1445 SGPath modelpath( globals->get_fg_root() );
1446 ssgModelPath( (char *)modelpath.c_str() );
1449 scene = new ssgRoot;
1450 scene->setName( "Scene" );
1452 // Scene graph root for cockpit
1453 cockpit = new ssgRoot;
1454 cockpit->setName( "Cockpit" );
1456 lighting = new ssgRoot;
1457 lighting->setName( "Lighting" );
1459 // Initialize the sky
1460 SGPath ephem_data_path( globals->get_fg_root() );
1461 ephem_data_path.append( "Astro" );
1462 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1463 ephem->update( globals->get_time_params()->getMjd(),
1464 globals->get_time_params()->getLst(),
1466 globals->set_ephem( ephem );
1470 SGPath sky_tex_path( globals->get_fg_root() );
1471 sky_tex_path.append( "Textures" );
1472 sky_tex_path.append( "Sky" );
1473 thesky->texture_path( sky_tex_path.str() );
1475 thesky->build( 550.0, 550.0,
1476 globals->get_ephem()->getNumPlanets(),
1477 globals->get_ephem()->getPlanets(), 60000.0,
1478 globals->get_ephem()->getNumStars(),
1479 globals->get_ephem()->getStars(), 60000.0 );
1481 if ( fgGetBool("/environment/clouds/status") ) {
1482 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1483 // SG_CLOUD_OVERCAST );
1484 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1486 200.0, 50.0, 40000.0,
1487 SG_CLOUD_MOSTLY_CLOUDY );
1488 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1489 // SG_CLOUD_MOSTLY_SUNNY );
1490 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1494 // Initialize MagVar model
1495 SGMagVar *magvar = new SGMagVar();
1496 globals->set_mag( magvar );
1499 terrain_branch = new ssgBranch;
1500 terrain_branch->setName( "Terrain" );
1501 scene->addKid( terrain_branch );
1504 gnd_lights_branch = new ssgBranch;
1505 gnd_lights_branch->setName( "Ground Lighting" );
1506 lighting->addKid( gnd_lights_branch );
1508 rwy_lights_branch = new ssgBranch;
1509 rwy_lights_branch->setName( "Runway Lighting" );
1510 lighting->addKid( rwy_lights_branch );
1512 // airport = new ssgBranch;
1513 // airport->setName( "Airport Lighting" );
1514 // lighting->addKid( airport );
1520 // temporary visible aircraft "own ship"
1521 current_model.init();
1523 #ifdef FG_NETWORK_OLK
1524 // Do the network intialization
1525 if ( fgGetBool("/sim/networking/network-olk") ) {
1526 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1530 // build our custom render states
1531 fgBuildRenderStates();
1533 // pass control off to the master GLUT event handler
1536 // we never actually get here ... but to avoid compiler warnings,
1542 // $$$ end - added VS Renganathan, 15 Oct 2K
1543 // - added Venky , 12 Nov 2K
1545 #if defined(__linux__) && defined(__i386__)
1547 static void handleFPE (int);
1552 fpu_control_t fpe_flags = 0;
1553 _FPU_GETCW(fpe_flags);
1554 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1555 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1556 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1557 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1558 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1559 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1560 _FPU_SETCW(fpe_flags);
1561 signal(SIGFPE, handleFPE);
1568 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1572 // Main entry point; catch any exceptions that have made it this far.
1573 int main ( int argc, char **argv ) {
1575 // Enable floating-point exceptions for Linux/x86
1576 #if defined(__linux__) && defined(__i386__)
1580 // Enable floating-point exceptions for Windows
1581 #if defined( _MSC_VER ) && defined( DEBUG )
1582 // Christian, we should document what this does
1583 _control87( _EM_INEXACT, _MCW_EM );
1586 #if defined( HAVE_BC5PLUS )
1587 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1590 // FIXME: add other, more specific
1593 mainLoop(argc, argv);
1594 } catch (sg_throwable &t) {
1595 SG_LOG(SG_GENERAL, SG_ALERT,
1596 "Fatal error: " << t.getFormattedMessage()
1597 << "\n (received from " << t.getOrigin() << ')');
1605 void fgLoadDCS(void) {
1607 ssgEntity *ship_obj = NULL;
1609 char obj_filename[25];
1611 for ( int k = 0; k < 32; k++ ) {
1615 SGPath tile_path( globals->get_fg_root());
1616 tile_path.append( "Scenery" );
1617 tile_path.append( "Objects.txt" );
1618 sg_gzifstream in( tile_path.str() );
1619 if ( ! in.is_open() ) {
1620 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1623 SGPath modelpath( globals->get_fg_root() );
1624 modelpath.append( "Models" );
1625 modelpath.append( "Geometry" );
1627 SGPath texturepath( globals->get_fg_root() );
1628 texturepath.append( "Models" );
1629 texturepath.append( "Textures" );
1631 ssgModelPath( (char *)modelpath.c_str() );
1632 ssgTexturePath( (char *)texturepath.c_str() );
1634 ship_sel = new ssgSelector;
1637 while ( ! in.eof() ) {
1639 if ( in.get( c ) && c == '#' ) {
1643 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1644 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1645 int chj=getchar();*/
1647 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1648 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1650 ship_pos[objc] = new ssgTransform;
1652 // type "repeat" in objects.txt to load one more
1653 // instance of the last object.
1655 if ( strcmp(obj_filename,"repeat") != 0) {
1656 ship_obj = ssgLoad( obj_filename );
1659 if ( ship_obj != NULL ) {
1660 ship_obj->setName(obj_filename);
1662 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1664 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1665 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1666 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1667 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1670 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1674 // temporary hack for deck lights - ultimately should move to PLib (when??)
1675 //const char *extn = file_extension ( obj_filename ) ;
1677 ssgVertexArray *lights = new ssgVertexArray( 100 );
1678 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1679 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1680 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1681 int ltype[500], light_type;
1682 static int ltcount = 0;
1684 sgVec3 rway_dir,rway_normal,lightpt;
1686 modelpath.append(obj_filename);
1687 sg_gzifstream in1( modelpath.str() );
1688 if ( ! in1.is_open() ) {
1689 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1691 while ( ! in1.eof() ) {
1693 if ( in1.get( c ) && c == '#' ) {
1698 //cout << token << endl;
1699 if ( token == "runway" ) {
1701 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1702 } else if ( token == "edgelight" ) {
1704 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1706 } else if ( token == "taxi" ) {
1708 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1710 } else if ( token == "vasi" ) {
1712 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1714 } else if ( token == "threshold" ) {
1716 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1718 } else if ( token == "rabbit" ) {
1720 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1722 } else if ( token == "ols" ) {
1724 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1726 } else if ( token == "red" ) {
1728 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1730 } else if ( token == "green" ) {
1732 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1734 } else if ( token == "lp" ) {
1736 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1737 lightpoints->add( lightpt );
1738 lightnormals->add( rway_normal );
1739 lightdir->add( rway_dir );
1740 ltype[ltcount]= light_type;
1743 if (in1.eof()) break;
1747 if ( lightpoints->getNum() ) {
1748 ssgBranch *lightpoints_branch;
1749 long int dummy = -999;
1750 dummy_tile = new FGTileEntry((SGBucket)dummy);
1751 dummy_tile->lightmaps_sequence = new ssgSelector;
1752 dummy_tile->ols_transform = new ssgTransform;
1754 // call function to generate the runway lights
1755 lightpoints_branch =
1756 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1758 lightpoints_brightness->addKid(lightpoints_branch);
1759 lightpoints_transform->addKid(lightpoints_brightness);
1760 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1761 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1762 lightpoints_transform->ref();
1763 gnd_lights_branch->addKid( lightpoints_transform );
1767 // end hack for deck lights
1771 if (in.eof()) break;
1775 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1777 terrain_branch->addKid( ship_sel ); //add selector node to root node
1784 void fgUpdateDCS (void) {
1786 // double eye_lat,eye_lon,eye_alt;
1787 // static double obj_head;
1788 double sl_radius,obj_latgc;
1789 // float nresultmat[4][4];
1790 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1793 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1794 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1796 // Deck should be the first object in objects.txt in case of fdm=ada
1798 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1799 if ((fdm->get_iaux(1))==1)
1801 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1802 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1803 obj_alt[1] = fdm->get_daux(3);
1804 obj_pitch[1] = fdm->get_faux(1);
1805 obj_roll[1] = fdm->get_faux(2);
1809 for ( int m = 0; m < objc; m++ ) {
1810 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1813 //Geodetic to Geocentric angles for rotation
1814 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1816 //moving object gbs-posn in cartesian coords
1817 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1818 Point3D obj_pos = sgGeodToCart( obj_posn );
1820 // Translate moving object w.r.t eye
1821 Point3D Objtrans = obj_pos-scenery.get_center();
1826 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1829 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1831 sgVec3 ship_fwd,ship_rt,ship_up;
1832 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1833 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1834 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1836 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1837 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1838 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1839 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1840 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1841 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1844 sgCopyMat4( sgTUX, sgROT_hdg );
1845 sgPostMultMat4( sgTUX, sgROT_pitch );
1846 sgPostMultMat4( sgTUX, sgROT_roll );
1847 sgPostMultMat4( sgTUX, sgROT_lat );
1848 sgPostMultMat4( sgTUX, sgROT_lon );
1849 sgPostMultMat4( sgTUX, sgTRANS );
1852 sgSetCoord(&shippos, sgTUX );
1853 ship_pos[m]->setTransform( &shippos );
1854 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1856 if (lightpoints_transform) {
1857 lightpoints_transform->setTransform( &shippos );
1858 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1859 if ( sun_angle > 89 ) {
1860 lightpoints_brightness->select(0x01);
1862 lightpoints_brightness->select(0x00);
1871 sgXformPnt3( rp, rway_ols, sgTUX );
1872 vp = globals->get_current_view()->get_view_pos();
1873 to[0] = rp[0]-vp[0];
1874 to[1] = rp[1]-vp[1];
1875 to[2] = rp[2]-vp[2];
1876 float dist = sgLengthVec3( to );
1877 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1879 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1881 ref_elev = elev - 3.75; // +ve above, -ve below
1885 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1886 // if (ref_elev > 0.51) sel = 0x21;
1887 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1888 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1889 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1890 // if (ref_elev < -0.51) sel = 0x30;
1891 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1892 dummy_tile->lightmaps_sequence->select(sel);
1895 sgCopyVec3 (up, ship_up);
1897 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1899 sgScaleVec3 (up, 4.0*ref_elev);
1900 dummy_tile->ols_transform->setTransform(up);
1901 //cout << "ref_elev " << ref_elev << endl;
1903 // end hack for deck lights
1906 if ( ship_sel != NULL ) {
1907 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1911 // $$$ end - added VS Renganathan, 15 Oct 2K
1912 // added Venky , 12 Nov 2K