1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 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 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
45 #include <plib/netSocket.h>
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
58 #ifdef FG_USE_CLOUDS_3D
59 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
89 #include <MultiPlayer/multiplaytxmgr.hxx>
90 #include <MultiPlayer/multiplayrxmgr.hxx>
94 #include "fg_commands.hxx"
98 float default_attenuation[3] = {1.0, 0.0, 0.0};
99 ssgSelector *ship_sel=NULL;
100 // upto 32 instances of a same object can be loaded.
101 ssgTransform *ship_pos[32];
102 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
104 ssgSelector *lightpoints_brightness = new ssgSelector;
105 ssgTransform *lightpoints_transform = new ssgTransform;
106 FGTileEntry *dummy_tile;
109 // Clip plane settings...
110 float scene_nearplane = 0.5f;
111 float scene_farplane = 120000.0f;
113 static double real_delta_time_sec = 0.0;
114 static double delta_time_sec = 0.0;
116 glPointParameterfProc glPointParameterfPtr = 0;
117 glPointParameterfvProc glPointParameterfvPtr = 0;
118 bool glPointParameterIsSupported = false;
122 # include <console.h> // -dw- for command line dialog
125 // This is a record containing a bit of global housekeeping information
128 // Specify our current idle function state. This is used to run all
129 // our initializations out of the idle callback so that we can get a
130 // splash screen up and running right away.
131 static int idle_state = 0;
132 static long global_multi_loop;
134 // fog constants. I'm a little nervous about putting actual code out
135 // here but it seems to work (?)
136 static const double m_log01 = -log( 0.01 );
137 static const double sqrt_m_log01 = sqrt( m_log01 );
138 static GLfloat fog_exp_density;
139 static GLfloat fog_exp2_density;
140 static GLfloat rwy_exp2_punch_through;
141 static GLfloat taxi_exp2_punch_through;
142 static GLfloat ground_exp2_punch_through;
147 #ifdef FG_USE_CLOUDS_3D
148 SkySceneLoader *sgClouds3d;
149 bool _bcloud_orig = true;
153 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
155 { 1.0f, 0.0f, 0.0f, 0.0f },
156 { 0.0f, 0.0f, -1.0f, 0.0f },
157 { 0.0f, 1.0f, 0.0f, 0.0f },
158 { 0.0f, 0.0f, 0.0f, 1.0f }
161 ssgSimpleState *cloud3d_imposter_state;
162 ssgSimpleState *default_state;
163 ssgSimpleState *hud_and_panel;
164 ssgSimpleState *menus;
166 SGTimeStamp last_time_stamp;
167 SGTimeStamp current_time_stamp;
170 void fgBuildRenderStates( void ) {
171 default_state = new ssgSimpleState;
172 default_state->ref();
173 default_state->disable( GL_TEXTURE_2D );
174 default_state->enable( GL_CULL_FACE );
175 default_state->enable( GL_COLOR_MATERIAL );
176 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
177 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
178 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
179 default_state->disable( GL_BLEND );
180 default_state->disable( GL_ALPHA_TEST );
181 default_state->disable( GL_LIGHTING );
183 cloud3d_imposter_state = new ssgSimpleState;
184 cloud3d_imposter_state->ref();
185 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
186 cloud3d_imposter_state->enable( GL_CULL_FACE );
187 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
188 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
189 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
190 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
191 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
192 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
193 cloud3d_imposter_state->enable( GL_BLEND );
194 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
195 cloud3d_imposter_state->disable( GL_LIGHTING );
197 hud_and_panel = new ssgSimpleState;
198 hud_and_panel->ref();
199 hud_and_panel->disable( GL_CULL_FACE );
200 hud_and_panel->disable( GL_TEXTURE_2D );
201 hud_and_panel->disable( GL_LIGHTING );
202 hud_and_panel->enable( GL_BLEND );
204 menus = new ssgSimpleState;
206 menus->disable( GL_CULL_FACE );
207 menus->disable( GL_TEXTURE_2D );
208 menus->enable( GL_BLEND );
212 // fgInitVisuals() -- Initialize various GL/view parameters
213 void fgInitVisuals( void ) {
215 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
217 // Go full screen if requested ...
218 if ( fgGetBool("/sim/startup/fullscreen") ) {
222 // If enabled, normal vectors specified with glNormal are scaled
223 // to unit length after transformation. Enabling this has
224 // performance implications. See the docs for glNormal.
225 // glEnable( GL_NORMALIZE );
227 glEnable( GL_LIGHTING );
228 glEnable( GL_LIGHT0 );
229 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
232 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
233 ssgGetLight( 0 ) -> setPosition( sunpos );
235 glFogi (GL_FOG_MODE, GL_EXP2);
236 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
237 (!fgGetBool("/sim/rendering/shading"))) {
238 // if fastest fog requested, or if flat shading force fastest
239 glHint ( GL_FOG_HINT, GL_FASTEST );
240 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
241 glHint ( GL_FOG_HINT, GL_NICEST );
243 if ( fgGetBool("/sim/rendering/wireframe") ) {
245 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
248 // This is the default anyways, but it can't hurt
249 glFrontFace ( GL_CCW );
252 // glEnable(GL_POINT_SMOOTH);
253 // glEnable(GL_LINE_SMOOTH);
254 // glEnable(GL_POLYGON_SMOOTH);
258 // For HiRes screen Dumps using Brian Pauls TR Library
259 void trRenderFrame( void ) {
260 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
261 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
262 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
264 bool multi_pass_clouds = false;
266 bool draw_clouds = fgGetBool("/environment/clouds/status");
268 if ( fgPanelVisible() ) {
269 GLfloat height = fgGetInt("/sim/startup/ysize");
271 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
272 * (height / 768.0) + 1;
273 glTranslatef( 0.0, view_h, 0.0 );
276 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
277 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
279 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
281 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
282 l->adj_fog_color()[2], l->adj_fog_color()[3]);
284 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
286 // set the opengl state to known default values
287 default_state->force();
290 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
291 glFogi ( GL_FOG_MODE, GL_EXP2 );
292 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
294 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
295 // we only update GL_AMBIENT for our lights we will never get
296 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
297 // explicitely to black.
298 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
299 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
301 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
303 // texture parameters
304 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
305 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
307 // we need a white diffuse light for the phase of the moon
308 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
309 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
312 // draw the ssg scene
313 // return to the desired diffuse color
314 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
315 glEnable( GL_DEPTH_TEST );
316 ssgSetNearFar( scene_nearplane, scene_farplane );
319 FGTileMgr::set_tile_filter( true );
320 sgSetModelFilter( false );
321 globals->get_aircraft_model()->select( false );
322 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
323 // Disable depth buffer update, draw the clouds
324 glDepthMask( GL_FALSE );
325 thesky->drawUpperClouds();
326 if ( multi_pass_clouds ) {
327 thesky->drawLowerClouds();
329 glDepthMask( GL_TRUE );
330 if ( multi_pass_clouds ) {
331 // Draw the objects except the aircraft
332 // and update the stencil buffer with 1
333 glEnable( GL_STENCIL_TEST );
334 glStencilFunc( GL_ALWAYS, 1, 1 );
335 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
337 FGTileMgr::set_tile_filter( false );
338 sgSetModelFilter( true );
339 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
341 FGTileMgr::set_tile_filter( true );
342 sgSetModelFilter( true );
343 globals->get_aircraft_model()->select( false );
344 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
348 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
349 ssgSetNearFar( scene_nearplane, scene_farplane );
350 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
351 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
353 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
356 if ( multi_pass_clouds ) {
357 // Disable depth buffer update, draw the clouds where the
358 // objects overwrite the already drawn clouds, by testing
359 // the stencil buffer against 1
360 glDepthMask( GL_FALSE );
361 glStencilFunc( GL_EQUAL, 1, 1 );
362 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
363 thesky->drawUpperClouds();
364 thesky->drawLowerClouds();
365 glDepthMask( GL_TRUE );
366 glDisable( GL_STENCIL_TEST );
368 glDepthMask( GL_FALSE );
369 thesky->drawLowerClouds();
370 glDepthMask( GL_TRUE );
374 globals->get_aircraft_model()->select( true );
375 globals->get_model_mgr()->draw();
376 globals->get_aircraft_model()->draw();
380 // Update all Visuals (redraws anything graphics related)
381 void fgRenderFrame() {
382 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
383 bool skyblend = fgGetBool("/sim/rendering/skyblend");
384 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
385 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
386 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
387 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
388 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
390 bool multi_pass_clouds = false;
392 bool draw_clouds = fgGetBool("/environment/clouds/status");
394 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
395 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
397 // static const SGPropertyNode *longitude
398 // = fgGetNode("/position/longitude-deg");
399 // static const SGPropertyNode *latitude
400 // = fgGetNode("/position/latitude-deg");
401 // static const SGPropertyNode *altitude
402 // = fgGetNode("/position/altitude-ft");
403 static const SGPropertyNode *groundlevel_nearplane
404 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
406 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
407 static double last_visibility = -9999;
410 double actual_visibility;
411 if (fgGetBool("/environment/clouds/status"))
412 actual_visibility = thesky->get_visibility();
414 actual_visibility = fgGetDouble("/environment/visibility-m");
415 if ( actual_visibility != last_visibility ) {
416 last_visibility = actual_visibility;
418 fog_exp_density = m_log01 / actual_visibility;
419 fog_exp2_density = sqrt_m_log01 / actual_visibility;
420 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
421 if ( actual_visibility < 8000 ) {
422 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
423 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
425 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
426 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
431 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
432 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
433 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
434 // GLfloat mat_shininess[] = { 10.0 };
435 GLbitfield clear_mask;
437 if ( idle_state != 1000 ) {
438 // still initializing, draw the splash screen
439 if ( fgGetBool("/sim/startup/splash-screen") ) {
440 fgSplashUpdate(0.0, 1.0);
442 // Keep resetting sim time while the sim is initializing
443 globals->set_sim_time_sec( 0.0 );
444 SGAnimation::set_sim_time_sec( 0.0 );
446 // idle_state is now 1000 meaning we've finished all our
447 // initializations and are running the main loop, so this will
448 // now work without seg faulting the system.
450 FGViewer *current__view = globals->get_current_view();
452 // calculate our current position in cartesian space
453 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
456 fgReshape( fgGetInt("/sim/startup/xsize"),
457 fgGetInt("/sim/startup/ysize") );
459 if ( fgGetBool("/sim/rendering/clouds3d") ) {
460 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
461 cloud3d_imposter_state->force();
463 glColor4f( 1.0, 1.0, 1.0, 1.0 );
464 glEnable(GL_DEPTH_TEST);
466 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
468 #ifdef FG_USE_CLOUDS_3D
469 if ( _bcloud_orig ) {
470 Point3D c = globals->get_scenery()->get_center();
471 sgClouds3d->Set_Cloud_Orig( &c );
472 _bcloud_orig = false;
474 sgClouds3d->Update( current__view->get_absolute_view_pos() );
476 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
477 glDisable(GL_DEPTH_TEST);
480 clear_mask = GL_DEPTH_BUFFER_BIT;
481 if ( fgGetBool("/sim/rendering/wireframe") ) {
482 clear_mask |= GL_COLOR_BUFFER_BIT;
486 if ( fgGetBool("/sim/rendering/textures") ) {
487 // glClearColor(black[0], black[1], black[2], black[3]);
488 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
489 l->adj_fog_color()[2], l->adj_fog_color()[3]);
490 clear_mask |= GL_COLOR_BUFFER_BIT;
493 glClearColor(l->sky_color()[0], l->sky_color()[1],
494 l->sky_color()[2], l->sky_color()[3]);
495 clear_mask |= GL_COLOR_BUFFER_BIT;
497 if ( multi_pass_clouds && draw_clouds ) {
499 clear_mask |= GL_STENCIL_BUFFER_BIT;
501 glClear( clear_mask );
503 // Tell GL we are switching to model view parameters
505 // I really should create a derived ssg node or use a call
506 // back or something so that I can draw the sky within the
507 // ssgCullAndDraw() function, but for now I just mimic what
508 // ssg does to set up the model view matrix
509 glMatrixMode(GL_MODELVIEW);
511 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
513 // set the opengl state to known default values
514 default_state->force();
516 // update fog params if visibility has changed
517 double visibility_meters = fgGetDouble("/environment/visibility-m");
518 thesky->set_visibility(visibility_meters);
520 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
521 ( global_multi_loop * fgGetInt("/sim/speed-up") )
522 / (double)fgGetInt("/sim/model-hz") );
524 // Set correct opengl fog density
525 glFogf (GL_FOG_DENSITY, fog_exp2_density);
527 // update the sky dome
530 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
531 << l->sky_color()[0] << " "
532 << l->sky_color()[1] << " "
533 << l->sky_color()[2] << " "
534 << l->sky_color()[3] );
535 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
536 << l->fog_color()[0] << " "
537 << l->fog_color()[1] << " "
538 << l->fog_color()[2] << " "
539 << l->fog_color()[3] );
540 SG_LOG( SG_GENERAL, SG_BULK,
541 " sun_angle = " << l->sun_angle
542 << " moon_angle = " << l->moon_angle );
545 static SGSkyColor scolor;
546 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
548 scolor.sky_color = l->sky_color();
549 scolor.fog_color = l->adj_fog_color();
550 scolor.cloud_color = l->cloud_color();
551 scolor.sun_angle = l->get_sun_angle();
552 scolor.moon_angle = l->get_moon_angle();
553 scolor.nplanets = globals->get_ephem()->getNumPlanets();
554 scolor.nstars = globals->get_ephem()->getNumStars();
555 scolor.planet_data = globals->get_ephem()->getPlanets();
556 scolor.star_data = globals->get_ephem()->getStars();
558 thesky->repaint( scolor );
561 SG_LOG( SG_GENERAL, SG_BULK,
562 "thesky->reposition( view_pos = " << view_pos[0] << " "
563 << view_pos[1] << " " << view_pos[2] );
564 SG_LOG( SG_GENERAL, SG_BULK,
565 " zero_elev = " << zero_elev[0] << " "
566 << zero_elev[1] << " " << zero_elev[2]
567 << " lon = " << cur_fdm_state->get_Longitude()
568 << " lat = " << cur_fdm_state->get_Latitude() );
569 SG_LOG( SG_GENERAL, SG_BULK,
570 " sun_rot = " << l->get_sun_rotation
571 << " gst = " << SGTime::cur_time_params->getGst() );
572 SG_LOG( SG_GENERAL, SG_BULK,
573 " sun ra = " << globals->get_ephem()->getSunRightAscension()
574 << " sun dec = " << globals->get_ephem()->getSunDeclination()
575 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
576 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
579 // The sun and moon distances are scaled down versions
580 // of the actual distance to get both the moon and the sun
581 // within the range of the far clip plane.
582 // Moon distance: 384,467 kilometers
583 // Sun distance: 150,000,000 kilometers
584 double sun_horiz_eff, moon_horiz_eff;
585 if (fgGetBool("/sim/rendering/horizon-effect")) {
586 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
587 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
589 sun_horiz_eff = moon_horiz_eff = 1.0;
592 static SGSkyState sstate;
594 sstate.view_pos = current__view->get_view_pos();
595 sstate.zero_elev = current__view->get_zero_elev();
596 sstate.view_up = current__view->get_world_up();
597 sstate.lon = current__view->getLongitude_deg()
598 * SGD_DEGREES_TO_RADIANS;
599 sstate.lat = current__view->getLatitude_deg()
600 * SGD_DEGREES_TO_RADIANS;
601 sstate.alt = current__view->getAltitudeASL_ft()
603 sstate.spin = l->get_sun_rotation();
604 sstate.gst = globals->get_time_params()->getGst();
605 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
606 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
607 sstate.sun_dist = 50000.0 * sun_horiz_eff;
608 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
609 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
610 sstate.moon_dist = 40000.0 * moon_horiz_eff;
612 thesky->reposition( sstate, delta_time_sec );
615 glEnable( GL_DEPTH_TEST );
616 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
618 glFogi( GL_FOG_MODE, GL_EXP2 );
619 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
622 // set sun/lighting parameters
623 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
625 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
626 // we only update GL_AMBIENT for our lights we will never get
627 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
628 // explicitely to black.
629 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
631 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
632 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
633 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
635 // texture parameters
636 // glEnable( GL_TEXTURE_2D );
637 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
638 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
640 // glMatrixMode( GL_PROJECTION );
642 ssgSetFOV( current__view->get_h_fov(),
643 current__view->get_v_fov() );
646 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
647 - globals->get_scenery()->get_cur_elev();
650 scene_nearplane = 10.0f;
651 scene_farplane = 120000.0f;
653 scene_nearplane = groundlevel_nearplane->getDoubleValue();
654 scene_farplane = 120000.0f;
657 ssgSetNearFar( scene_nearplane, scene_farplane );
660 // Update any multiplayer models
661 globals->get_multiplayer_rx_mgr()->Update();
664 if ( draw_otw && skyblend ) {
665 // draw the sky backdrop
667 // we need a white diffuse light for the phase of the moon
668 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
669 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
671 // return to the desired diffuse color
672 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
675 // draw the ssg scene
676 glEnable( GL_DEPTH_TEST );
678 ssgSetNearFar( scene_nearplane, scene_farplane );
680 if ( fgGetBool("/sim/rendering/wireframe") ) {
682 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
688 FGTileMgr::set_tile_filter( true );
689 sgSetModelFilter( false );
690 globals->get_aircraft_model()->select( false );
691 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
693 // Disable depth buffer update, draw the clouds
694 glDepthMask( GL_FALSE );
695 thesky->drawUpperClouds();
696 if ( multi_pass_clouds ) {
697 thesky->drawLowerClouds();
699 glDepthMask( GL_TRUE );
701 if ( multi_pass_clouds ) {
702 // Draw the objects except the aircraft
703 // and update the stencil buffer with 1
704 glEnable( GL_STENCIL_TEST );
705 glStencilFunc( GL_ALWAYS, 1, 1 );
706 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
708 FGTileMgr::set_tile_filter( false );
709 sgSetModelFilter( true );
710 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
712 FGTileMgr::set_tile_filter( true );
713 sgSetModelFilter( true );
714 globals->get_aircraft_model()->select( false );
715 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
719 // This is a bit kludgy. Every 200 frames, do an extra
720 // traversal of the scene graph without drawing anything, but
721 // with the field-of-view set to 360x360 degrees. This
722 // ensures that out-of-range random objects that are not in
723 // the current view frustum will still be freed properly.
724 static int counter = 0;
726 if (counter == 200) {
729 // No need to put the near plane too close;
730 // this way, at least the aircraft can be
732 f.setNearFar(1000, 1000000);
734 ssgGetModelviewMatrix(m);
735 FGTileMgr::set_tile_filter( true );
736 sgSetModelFilter( true );
737 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
741 // change state for lighting here
743 // draw runway lighting
744 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
745 ssgSetNearFar( scene_nearplane, scene_farplane );
747 if ( enhanced_lighting ) {
749 // Enable states for drawing points with GL_extension
750 glEnable(GL_POINT_SMOOTH);
752 if ( distance_attenuation && glPointParameterIsSupported )
754 // Enable states for drawing points with GL_extension
755 glEnable(GL_POINT_SMOOTH);
757 float quadratic[3] = {1.0, 0.001, 0.0000001};
758 // makes the points fade as they move away
759 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
760 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
765 // blending function for runway lights
766 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
769 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
770 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
771 glEnable(GL_TEXTURE_GEN_S);
772 glEnable(GL_TEXTURE_GEN_T);
773 glPolygonMode(GL_FRONT, GL_POINT);
775 // draw runway lighting
777 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
778 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
781 // change punch through and then draw taxi lighting
782 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
784 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
785 // glFogfv ( GL_FOG_COLOR, taxi_fog );
787 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
791 glPolygonMode(GL_FRONT, GL_FILL);
792 glDisable(GL_TEXTURE_GEN_S);
793 glDisable(GL_TEXTURE_GEN_T);
795 //static int _frame_count = 0;
796 //if (_frame_count % 30 == 0) {
797 // printf("SSG: %s\n", ssgShowStats());
805 if ( enhanced_lighting ) {
806 if ( distance_attenuation && glPointParameterIsSupported ) {
807 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
808 default_attenuation);
812 glDisable(GL_POINT_SMOOTH);
815 // draw ground lighting
816 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
818 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
821 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
823 glDisable( GL_LIGHTING );
824 // cout << "drawing new clouds" << endl;
826 glEnable(GL_DEPTH_TEST);
828 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
831 glEnable( GL_TEXTURE_2D );
832 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
833 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
834 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
835 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
838 #ifdef FG_USE_CLOUDS_3D
839 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
842 glEnable( GL_LIGHTING );
843 glEnable( GL_DEPTH_TEST );
844 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
847 if ( draw_otw && draw_clouds ) {
848 if ( multi_pass_clouds ) {
849 // Disable depth buffer update, draw the clouds where the
850 // objects overwrite the already drawn clouds, by testing
851 // the stencil buffer against 1
852 glDepthMask( GL_FALSE );
853 glStencilFunc( GL_EQUAL, 1, 1 );
854 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
855 thesky->drawUpperClouds();
856 thesky->drawLowerClouds();
857 glDepthMask( GL_TRUE );
858 glDisable( GL_STENCIL_TEST );
860 glDepthMask( GL_FALSE );
861 thesky->drawLowerClouds();
862 glDepthMask( GL_TRUE );
867 FGTileMgr::set_tile_filter( false );
868 sgSetModelFilter( false );
869 globals->get_aircraft_model()->select( true );
870 globals->get_model_mgr()->draw();
871 globals->get_aircraft_model()->draw();
872 // If the view is internal, the previous line draw the
873 // cockpit with modified near/far clip planes and deselect
874 // the aircraft in the global scenegraph
875 // Otherwise, it just enables the aircraft: The scenegraph
876 // must be drawn again to see the plane.
877 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
878 FGTileMgr::set_tile_filter( true );
879 sgSetModelFilter( true );
880 globals->get_aircraft_model()->select( true );
883 // display HUD && Panel
885 glDisable( GL_DEPTH_TEST );
886 // glDisable( GL_CULL_FACE );
887 // glDisable( GL_TEXTURE_2D );
889 // update the controls subsystem
890 globals->get_controls()->update(delta_time_sec);
892 hud_and_panel->apply();
895 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
896 // This only works properly if called before the panel call
897 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
898 globals->get_ATC_display()->update(delta_time_sec);
900 // update the panel subsystem
901 if ( globals->get_current_panel() != NULL ) {
902 globals->get_current_panel()->update(delta_time_sec);
906 // We can do translucent menus, so why not. :-)
908 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
910 // glDisable ( GL_BLEND ) ;
912 glEnable( GL_DEPTH_TEST );
915 // Fade out the splash screen over the first three seconds.
916 double t = globals->get_sim_time_sec();
918 fgSplashUpdate(0.0, 1.0);
919 } else if ( t <= 3.0) {
920 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
926 // Update internal time dependent calculations (i.e. flight model)
927 // FIXME: this distinction is obsolete; all subsystems now get delta
929 void fgUpdateTimeDepCalcs() {
930 static bool inited = false;
932 static const SGPropertyNode *replay_master
933 = fgGetNode( "/sim/freeze/replay", true );
934 static SGPropertyNode *replay_time
935 = fgGetNode( "/sim/replay/time", true );
936 // static const SGPropertyNode *replay_end_time
937 // = fgGetNode( "/sim/replay/end-time", true );
939 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
941 // Initialize the FDM here if it hasn't been and if we have a
942 // scenery elevation hit.
944 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
945 // << " cur_elev = " << scenery.get_cur_elev() << endl;
947 if ( !cur_fdm_state->get_inited() &&
948 globals->get_scenery()->get_cur_elev() > -9990 )
950 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
951 cur_fdm_state->init();
952 if ( cur_fdm_state->get_bound() ) {
953 cur_fdm_state->unbind();
955 cur_fdm_state->bind();
958 // conceptually, the following block could be done for each fdm
960 if ( cur_fdm_state->get_inited() ) {
961 // we have been inited, and we are good to go ...
967 if ( ! replay_master->getBoolValue() ) {
968 cur_fdm_state->update( delta_time_sec );
970 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
971 r->replay( replay_time->getDoubleValue() );
972 replay_time->setDoubleValue( replay_time->getDoubleValue()
974 * fgGetInt("/sim/speed-up") ) );
977 // do nothing, fdm isn't inited yet
980 globals->get_model_mgr()->update(delta_time_sec);
981 globals->get_aircraft_model()->update(delta_time_sec);
983 // update the view angle
984 globals->get_viewmgr()->update(delta_time_sec);
986 // Update solar system
987 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
988 globals->get_time_params()->getLst(),
989 cur_fdm_state->get_Latitude() );
991 // Update radio stack model
992 current_radiostack->update(delta_time_sec);
996 void fgInitTimeDepCalcs( void ) {
1001 static const double alt_adjust_ft = 3.758099;
1002 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1005 // What should we do when we have nothing else to do? Let's get ready
1006 // for the next move and update the display?
1007 static void fgMainLoop( void ) {
1008 int model_hz = fgGetInt("/sim/model-hz");
1010 static const SGPropertyNode *longitude
1011 = fgGetNode("/position/longitude-deg");
1012 static const SGPropertyNode *latitude
1013 = fgGetNode("/position/latitude-deg");
1014 static const SGPropertyNode *altitude
1015 = fgGetNode("/position/altitude-ft");
1016 static const SGPropertyNode *clock_freeze
1017 = fgGetNode("/sim/freeze/clock", true);
1018 static const SGPropertyNode *cur_time_override
1019 = fgGetNode("/sim/time/cur-time-override", true);
1020 // static const SGPropertyNode *replay_master
1021 // = fgGetNode("/sim/freeze/replay", true);
1023 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1025 // Update the elapsed time.
1026 static bool first_time = true;
1028 last_time_stamp.stamp();
1032 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1033 if ( throttle_hz > 0.0 ) {
1034 // simple frame rate throttle
1035 double dt = 1000000.0 / throttle_hz;
1036 current_time_stamp.stamp();
1037 while ( current_time_stamp - last_time_stamp < dt ) {
1038 current_time_stamp.stamp();
1041 // run as fast as the app will go
1042 current_time_stamp.stamp();
1046 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1047 if ( clock_freeze->getBoolValue() ) {
1050 delta_time_sec = real_delta_time_sec;
1052 last_time_stamp = current_time_stamp;
1053 globals->inc_sim_time_sec( delta_time_sec );
1054 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1056 // These are useful, especially for Nasal scripts.
1057 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1058 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1060 static long remainder = 0;
1062 #ifdef FANCY_FRAME_COUNTER
1066 static time_t last_time = 0;
1067 static int frames = 0;
1068 #endif // FANCY_FRAME_COUNTER
1070 SGTime *t = globals->get_time_params();
1072 globals->get_event_mgr()->update(delta_time_sec);
1074 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1075 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1077 #if defined( ENABLE_PLIB_JOYSTICK )
1078 // Read joystick and update control settings
1079 // if ( fgGetString("/sim/control-mode") == "joystick" )
1081 // fgJoystickRead();
1085 // Fix elevation. I'm just sticking this here for now, it should
1086 // probably move eventually
1088 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1089 scenery.get_cur_elev(),
1090 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1091 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1093 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1094 scenery.get_cur_elev(),
1095 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1096 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1098 // cout << "Warp = " << globals->get_warp() << endl;
1101 static bool last_clock_freeze = false;
1103 if ( clock_freeze->getBoolValue() ) {
1104 // clock freeze requested
1105 if ( cur_time_override->getLongValue() == 0 ) {
1106 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1107 globals->set_warp( 0 );
1110 // no clock freeze requested
1111 if ( last_clock_freeze == true ) {
1112 // clock just unfroze, let's set warp as the difference
1113 // between frozen time and current time so we don't get a
1114 // time jump (and corresponding sky object and lighting
1116 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1117 fgSetLong( "/sim/time/cur-time-override", 0 );
1119 if ( globals->get_warp_delta() != 0 ) {
1120 globals->inc_warp( globals->get_warp_delta() );
1124 last_clock_freeze = clock_freeze->getBoolValue();
1126 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1127 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1128 cur_time_override->getLongValue(),
1129 globals->get_warp() );
1131 if (globals->get_warp_delta() != 0) {
1132 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1136 // update magvar model
1137 globals->get_mag()->update( longitude->getDoubleValue()
1138 * SGD_DEGREES_TO_RADIANS,
1139 latitude->getDoubleValue()
1140 * SGD_DEGREES_TO_RADIANS,
1141 altitude->getDoubleValue() * SG_FEET_TO_METER,
1142 globals->get_time_params()->getJD() );
1144 // Get elapsed time (in usec) for this past frame
1145 elapsed = fgGetTimeInterval();
1146 SG_LOG( SG_ALL, SG_DEBUG,
1147 "Elapsed time interval is = " << elapsed
1148 << ", previous remainder is = " << remainder );
1150 // Calculate frame rate average
1151 #ifdef FANCY_FRAME_COUNTER
1152 /* old fps calculation */
1153 if ( elapsed > 0 ) {
1156 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1157 tmp = general.get_frame(i);
1159 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1160 general.set_frame(i+1,tmp);
1162 tmp = 1000000.0 / (float)elapsed;
1163 general.set_frame(0,tmp);
1164 // printf("frame[0] = %.2f\n", general.frames[0]);
1166 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1167 // printf("ave = %.2f\n", general.frame_rate);
1170 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1171 general.set_frame_rate( frames );
1172 fgSetInt("/sim/frame-rate", frames);
1173 SG_LOG( SG_ALL, SG_DEBUG,
1174 "--> Frame rate is = " << general.get_frame_rate() );
1177 last_time = t->get_cur_time();
1181 // Run ATC subsystem
1182 if (fgGetBool("/sim/ATC/enabled"))
1183 globals->get_ATC_mgr()->update(delta_time_sec);
1185 // Run the AI subsystem
1186 if (fgGetBool("/sim/ai-traffic/enabled"))
1187 globals->get_AI_mgr()->update(delta_time_sec);
1191 // Calculate model iterations needed for next frame
1192 elapsed += remainder;
1194 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1195 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1196 SG_LOG( SG_ALL, SG_DEBUG,
1197 "Model iterations needed = " << global_multi_loop
1198 << ", new remainder = " << remainder );
1200 // chop max interations to something reasonable if the sim was
1201 // delayed for an excesive amount of time
1202 if ( global_multi_loop > 2.0 * model_hz ) {
1203 global_multi_loop = (int)(2.0 * model_hz );
1208 if ( global_multi_loop > 0 ) {
1209 fgUpdateTimeDepCalcs();
1211 SG_LOG( SG_ALL, SG_DEBUG,
1212 "Elapsed time is zero ... we're zinging" );
1215 // Do any I/O channel work that might need to be done
1216 globals->get_io()->update( real_delta_time_sec );
1218 // see if we need to load any deferred-load textures
1219 globals->get_matlib()->load_next_deferred();
1221 // Run audio scheduler
1222 #ifdef ENABLE_AUDIO_SUPPORT
1223 if ( globals->get_soundmgr()->is_working() ) {
1224 globals->get_soundmgr()->update( delta_time_sec );
1228 globals->get_subsystem_mgr()->update(delta_time_sec);
1231 // Tile Manager updates - see if we need to load any new scenery tiles.
1232 // this code ties together the fdm, viewer and scenery classes...
1233 // we may want to move this to it's own class at some point
1235 double visibility_meters = fgGetDouble("/environment/visibility-m");
1236 FGViewer *current_view = globals->get_current_view();
1238 // get the location data for the primary FDM (now hardcoded to ac model)...
1239 SGLocation *acmodel_loc = NULL;
1240 acmodel_loc = (SGLocation *)globals->
1241 get_aircraft_model()->get3DModel()->getSGLocation();
1243 // update tile manager for FDM...
1244 // ...only if location is different than the current-view location
1245 // (to avoid duplicating effort)
1246 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1247 if( acmodel_loc != NULL ) {
1248 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1249 visibility_meters );
1250 globals->get_tile_mgr()->
1251 update( acmodel_loc, visibility_meters,
1253 get_absolute_view_pos(globals->
1254 get_scenery()->get_center()) );
1255 // save results of update in SGLocation for fdm...
1256 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1258 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1259 fgSetDouble("/position/ground-elev-m",
1260 globals->get_scenery()->get_cur_elev());
1263 set_tile_center( globals->get_scenery()->get_next_center() );
1267 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1268 visibility_meters );
1269 // update tile manager for view...
1270 // IMPORTANT!!! the tilemgr update for view location _must_ be
1271 // done last after the FDM's until all of Flight Gear code
1272 // references the viewer's location for elevation instead of the
1273 // "scenery's" current elevation.
1274 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1275 globals->get_tile_mgr()->update( view_location, visibility_meters,
1276 current_view->get_absolute_view_pos() );
1277 // save results of update in SGLocation for fdm...
1278 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1279 current_view->getSGLocation()->
1280 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1282 current_view->getSGLocation()->
1283 set_tile_center( globals->get_scenery()->get_next_center() );
1285 #ifdef ENABLE_AUDIO_SUPPORT
1286 // Right now we make a simplifying assumption that the primary
1287 // aircraft is the source of all sounds and that all sounds are
1288 // positioned relative to the current view position.
1290 static sgVec3 last_pos_offset;
1292 // set positional offset for sources
1293 sgVec3 source_pos_offset;
1294 sgSubVec3( source_pos_offset,
1295 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1296 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1297 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1301 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1302 sgScaleVec3( source_vel, delta_time_sec );
1303 sgCopyVec3( last_pos_offset, source_pos_offset );
1304 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1305 globals->get_soundmgr()->set_source_vel_all( source_vel );
1307 // Right now we make a simplifying assumption that the listener is
1308 // always positioned at the origin.
1309 sgVec3 listener_pos;
1310 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1311 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1312 globals->get_soundmgr()->set_listener_pos( listener_pos );
1315 // If fdm location is same as viewer's then we didn't do the
1316 // update for fdm location above so we need to save the viewer
1317 // results in the fdm SGLocation as well...
1318 if( fgGetBool("/sim/current-view/config/from-model") ) {
1319 if( acmodel_loc != 0 ) {
1320 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1321 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1323 fgSetDouble("/position/ground-elev-m",
1324 globals->get_scenery()->get_cur_elev());
1326 acmodel_loc->set_tile_center( globals->get_scenery()->
1327 get_next_center() );
1331 // END Tile Manager udpates
1333 if (fgGetBool("/sim/rendering/specular-highlight")) {
1334 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1335 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1337 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1338 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1343 SG_LOG( SG_ALL, SG_DEBUG, "" );
1347 // This is the top level master main function that is registered as
1348 // our idle funciton
1350 // The first few passes take care of initialization things (a couple
1351 // per pass) and once everything has been initialized fgMainLoop from
1354 static void fgIdleFunction ( void ) {
1355 // printf("idle state == %d\n", idle_state);
1357 if ( idle_state == 0 ) {
1358 fgSetBool("sim/initialised", false);
1360 // Initialize the splash screen right away
1361 if ( fgGetBool("/sim/startup/splash-screen") ) {
1362 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1366 } else if ( idle_state == 1 ) {
1367 // Initialize audio support
1368 #ifdef ENABLE_AUDIO_SUPPORT
1370 // Start the intro music
1371 if ( fgGetBool("/sim/startup/intro-music") ) {
1372 SGPath mp3file( globals->get_fg_root() );
1373 mp3file.append( "Sounds/intro.mp3" );
1375 SG_LOG( SG_GENERAL, SG_INFO,
1376 "Starting intro music: " << mp3file.str() );
1378 #if defined( __CYGWIN__ )
1379 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1380 #elif defined( WIN32 )
1381 string command = "start /m " + mp3file.str();
1383 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1386 system ( command.c_str() );
1391 } else if ( idle_state == 2 ) {
1392 // These are a few miscellaneous things that aren't really
1393 // "subsystems" but still need to be initialized.
1396 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1397 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1402 } else if ( idle_state == 3 ) {
1403 // This is the top level init routine which calls all the
1404 // other subsystem initialization routines. If you are adding
1405 // a subsystem to flightgear, its initialization call should
1406 // located in this routine.
1407 if( !fgInitSubsystems()) {
1408 SG_LOG( SG_GENERAL, SG_ALERT,
1409 "Subsystem initializations failed ..." );
1414 } else if ( idle_state == 4 ) {
1415 // Initialize the time offset (warp) after fgInitSubsystem
1416 // (which initializes the lighting interpolation tables.)
1419 // setup OpenGL view parameters
1422 // Read the list of available aircrafts
1426 } else if ( idle_state == 5 ) {
1429 } else if ( idle_state == 6 ) {
1434 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1435 fgReshape( fgGetInt("/sim/startup/xsize"),
1436 fgGetInt("/sim/startup/ysize") );
1440 if ( idle_state == 1000 ) {
1441 // We've finished all our initialization steps, from now on we
1442 // run the main loop.
1443 fgSetBool("sim/initialised",true);
1445 fgRegisterIdleHandler(fgMainLoop);
1447 if ( fgGetBool("/sim/startup/splash-screen") ) {
1448 fgSplashUpdate(0.0, 1.0);
1453 // options.cxx needs to see this for toggle_panel()
1454 // Handle new window size or exposure
1455 void fgReshape( int width, int height ) {
1458 if ( (!fgGetBool("/sim/virtual-cockpit"))
1459 && fgPanelVisible() && idle_state == 1000 ) {
1460 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1461 globals->get_current_panel()->getYOffset()) / 768.0);
1466 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1468 fgSetInt("/sim/startup/xsize", width);
1469 fgSetInt("/sim/startup/ysize", height);
1470 guiInitMouse(width, height);
1473 FGViewMgr *viewmgr = globals->get_viewmgr();
1475 for ( int i = 0; i < viewmgr->size(); ++i ) {
1476 viewmgr->get_view(i)->
1477 set_aspect_ratio((float)view_h / (float)width);
1480 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1481 viewmgr->get_current_view()->get_v_fov() );
1483 #ifdef FG_USE_CLOUDS_3D
1484 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1485 viewmgr->get_current_view()->get_v_fov() );
1494 // do some clean up on exit. Specifically we want to call alutExit()
1495 // which happens in the sound manager destructor.
1496 void fgExitCleanup() {
1502 // Main top level initialization
1503 bool fgMainInit( int argc, char **argv ) {
1505 #if defined( macintosh )
1506 freopen ("stdout.txt", "w", stdout );
1507 freopen ("stderr.txt", "w", stderr );
1508 argc = ccommand( &argv );
1511 // set default log levels
1512 sglog().setLogLevels( SG_ALL, SG_ALERT );
1514 atexit(fgExitCleanup);
1517 #ifdef FLIGHTGEAR_VERSION
1518 version = FLIGHTGEAR_VERSION;
1520 version = "unknown version";
1522 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1524 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1526 // Allocate global data structures. This needs to happen before
1527 // we parse command line options
1529 globals = new FGGlobals;
1531 // seed the random number generater
1534 FGControls *controls = new FGControls;
1535 globals->set_controls( controls );
1537 string_list *col = new string_list;
1538 globals->set_channel_options_list( col );
1540 // Scan the config file(s) and command line options to see if
1541 // fg_root was specified (ignore all other options for now)
1542 fgInitFGRoot(argc, argv);
1544 // Check for the correct base package version
1545 static char required_version[] = "0.9.5-pre1";
1546 string base_version = fgBasePackageVersion();
1547 if ( !(base_version == required_version) ) {
1548 // tell the operator how to use this application
1550 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1551 cerr << endl << "Base package check failed ... " \
1552 << "Found version " << base_version << " at: " \
1553 << globals->get_fg_root() << endl;
1554 cerr << "Please upgrade to version: " << required_version << endl;
1556 cerr << "Hit a key to continue..." << endl;
1562 // Initialize the Aircraft directory to "" (UIUC)
1565 // Load the configuration parameters. (Command line options
1566 // overrides config file options. Config file options override
1568 if ( !fgInitConfig(argc, argv) ) {
1569 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1573 // Initialize the Window/Graphics environment.
1574 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1575 // Mac OS X command line ("non-bundle") applications call this
1576 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1577 // feel free to add comments...
1578 fgOSInit(&argc, argv);
1581 fgRegisterWindowResizeHandler( fgReshape );
1582 fgRegisterIdleHandler( fgIdleFunction );
1583 fgRegisterDrawHandler( fgRenderFrame );
1585 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1586 bool get_stencil_buffer = true;
1588 bool get_stencil_buffer = false;
1591 // Clouds3D requires an alpha channel
1592 // clouds may require stencil buffer
1593 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1594 fgGetInt("/sim/startup/ysize"),
1595 fgGetInt("/sim/rendering/bits-per-pixel"),
1596 fgGetBool("/sim/rendering/clouds3d"),
1598 fgGetBool("/sim/startup/fullscreen") );
1600 // This seems to be the absolute earliest in the init sequence
1601 // that these calls will return valid info. Too bad it's after
1602 // we've already created and sized out window. :-(
1603 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1604 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1605 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1606 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1609 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1610 general.set_glMaxTexSize( tmp );
1611 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1613 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1614 general.set_glDepthBits( tmp );
1615 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1617 // Initialize plib net interface
1618 netInit( &argc, argv );
1620 // Initialize ssg (from plib). Needs to come before we do any
1621 // other ssg stuff, but after opengl has been initialized.
1624 // Initialize the user interface (we need to do this before
1625 // passing off control to the OS main loop and before
1626 // fgInitGeneral to get our fonts !!!
1629 // Read the list of available aircrafts
1632 #ifdef GL_EXT_texture_lod_bias
1633 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1636 // get the address of our OpenGL extensions
1637 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1639 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1640 glPointParameterIsSupported = true;
1641 glPointParameterfPtr = (glPointParameterfProc)
1642 SGLookupFunction("glPointParameterfEXT");
1643 glPointParameterfvPtr = (glPointParameterfvProc)
1644 SGLookupFunction("glPointParameterfvEXT");
1646 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1647 glPointParameterIsSupported = true;
1648 glPointParameterfPtr = (glPointParameterfProc)
1649 SGLookupFunction("glPointParameterfARB");
1650 glPointParameterfvPtr = (glPointParameterfvProc)
1651 SGLookupFunction("glPointParameterfvARB");
1653 glPointParameterIsSupported = false;
1656 // based on the requested presets, calculate the true starting
1661 SGTime *t = fgInitTime();
1662 globals->set_time_params( t );
1664 // Do some quick general initializations
1665 if( !fgInitGeneral()) {
1666 SG_LOG( SG_GENERAL, SG_ALERT,
1667 "General initializations failed ..." );
1671 ////////////////////////////////////////////////////////////////////
1672 // Initialize the property-based built-in commands
1673 ////////////////////////////////////////////////////////////////////
1676 ////////////////////////////////////////////////////////////////////
1677 // Initialize the material manager
1678 ////////////////////////////////////////////////////////////////////
1679 globals->set_matlib( new SGMaterialLib );
1681 globals->set_model_lib(new SGModelLib);
1683 ////////////////////////////////////////////////////////////////////
1684 // Initialize the TG scenery subsystem.
1685 ////////////////////////////////////////////////////////////////////
1686 globals->set_scenery( new FGScenery );
1687 globals->get_scenery()->init();
1688 globals->get_scenery()->bind();
1689 globals->set_tile_mgr( new FGTileMgr );
1691 ////////////////////////////////////////////////////////////////////
1692 // Initialize the general model subsystem.
1693 ////////////////////////////////////////////////////////////////////
1694 globals->set_model_mgr(new FGModelMgr);
1695 globals->get_model_mgr()->init();
1696 globals->get_model_mgr()->bind();
1698 ////////////////////////////////////////////////////////////////////
1699 // Initialize the 3D aircraft model subsystem (has a dependency on
1700 // the scenery subsystem.)
1701 ////////////////////////////////////////////////////////////////////
1702 globals->set_aircraft_model(new FGAircraftModel);
1703 globals->get_aircraft_model()->init();
1704 globals->get_aircraft_model()->bind();
1706 ////////////////////////////////////////////////////////////////////
1707 // Initialize the view manager subsystem.
1708 ////////////////////////////////////////////////////////////////////
1709 FGViewMgr *viewmgr = new FGViewMgr;
1710 globals->set_viewmgr( viewmgr );
1715 // Initialize the sky
1716 SGPath ephem_data_path( globals->get_fg_root() );
1717 ephem_data_path.append( "Astro" );
1718 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1719 ephem->update( globals->get_time_params()->getMjd(),
1720 globals->get_time_params()->getLst(),
1722 globals->set_ephem( ephem );
1724 // TODO: move to environment mgr
1726 SGPath texture_path(globals->get_fg_root());
1727 texture_path.append("Textures");
1728 texture_path.append("Sky");
1729 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1730 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1731 thesky->add_cloud_layer(layer);
1734 SGPath sky_tex_path( globals->get_fg_root() );
1735 sky_tex_path.append( "Textures" );
1736 sky_tex_path.append( "Sky" );
1737 thesky->texture_path( sky_tex_path.str() );
1739 // The sun and moon diameters are scaled down numbers of the
1740 // actual diameters. This was needed to fit bot the sun and the
1741 // moon within the distance to the far clip plane.
1742 // Moon diameter: 3,476 kilometers
1743 // Sun diameter: 1,390,000 kilometers
1744 thesky->build( 80000.0, 80000.0,
1746 globals->get_ephem()->getNumPlanets(),
1747 globals->get_ephem()->getPlanets(),
1748 globals->get_ephem()->getNumStars(),
1749 globals->get_ephem()->getStars() );
1751 // Initialize MagVar model
1752 SGMagVar *magvar = new SGMagVar();
1753 globals->set_mag( magvar );
1756 // kludge to initialize mag compass
1757 // (should only be done for in-flight
1759 // update magvar model
1760 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1761 * SGD_DEGREES_TO_RADIANS,
1762 fgGetDouble("/position/latitude-deg")
1763 * SGD_DEGREES_TO_RADIANS,
1764 fgGetDouble("/position/altitude-ft")
1766 globals->get_time_params()->getJD() );
1767 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1768 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1770 // airport = new ssgBranch;
1771 // airport->setName( "Airport Lighting" );
1772 // lighting->addKid( airport );
1774 // build our custom render states
1775 fgBuildRenderStates();
1778 // pass control off to the master event handler
1781 SG_LOG( SG_ALL, SG_ALERT,
1782 "Unknown exception in the main loop. Aborting..." );
1785 // we never actually get here ... but to avoid compiler warnings,