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>
87 #include <GUI/new_gui.hxx>
90 #include <MultiPlayer/multiplaytxmgr.hxx>
91 #include <MultiPlayer/multiplayrxmgr.hxx>
95 #include "fg_commands.hxx"
99 float default_attenuation[3] = {1.0, 0.0, 0.0};
100 ssgSelector *ship_sel=NULL;
101 // upto 32 instances of a same object can be loaded.
102 ssgTransform *ship_pos[32];
103 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
105 ssgSelector *lightpoints_brightness = new ssgSelector;
106 ssgTransform *lightpoints_transform = new ssgTransform;
107 FGTileEntry *dummy_tile;
110 // Clip plane settings...
111 float scene_nearplane = 0.5f;
112 float scene_farplane = 120000.0f;
114 static double real_delta_time_sec = 0.0;
115 static double delta_time_sec = 0.0;
117 glPointParameterfProc glPointParameterfPtr = 0;
118 glPointParameterfvProc glPointParameterfvPtr = 0;
119 bool glPointParameterIsSupported = false;
123 # include <console.h> // -dw- for command line dialog
126 // This is a record containing a bit of global housekeeping information
129 // Specify our current idle function state. This is used to run all
130 // our initializations out of the idle callback so that we can get a
131 // splash screen up and running right away.
132 static int idle_state = 0;
133 static long global_multi_loop;
135 // fog constants. I'm a little nervous about putting actual code out
136 // here but it seems to work (?)
137 static const double m_log01 = -log( 0.01 );
138 static const double sqrt_m_log01 = sqrt( m_log01 );
139 static GLfloat fog_exp_density;
140 static GLfloat fog_exp2_density;
141 static GLfloat rwy_exp2_punch_through;
142 static GLfloat taxi_exp2_punch_through;
143 static GLfloat ground_exp2_punch_through;
148 #ifdef FG_USE_CLOUDS_3D
149 SkySceneLoader *sgClouds3d;
150 bool _bcloud_orig = true;
154 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
156 { 1.0f, 0.0f, 0.0f, 0.0f },
157 { 0.0f, 0.0f, -1.0f, 0.0f },
158 { 0.0f, 1.0f, 0.0f, 0.0f },
159 { 0.0f, 0.0f, 0.0f, 1.0f }
162 ssgSimpleState *cloud3d_imposter_state;
163 ssgSimpleState *default_state;
164 ssgSimpleState *hud_and_panel;
165 ssgSimpleState *menus;
167 SGTimeStamp last_time_stamp;
168 SGTimeStamp current_time_stamp;
171 void fgBuildRenderStates( void ) {
172 default_state = new ssgSimpleState;
173 default_state->ref();
174 default_state->disable( GL_TEXTURE_2D );
175 default_state->enable( GL_CULL_FACE );
176 default_state->enable( GL_COLOR_MATERIAL );
177 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
178 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
179 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
180 default_state->disable( GL_BLEND );
181 default_state->disable( GL_ALPHA_TEST );
182 default_state->disable( GL_LIGHTING );
184 cloud3d_imposter_state = new ssgSimpleState;
185 cloud3d_imposter_state->ref();
186 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
187 cloud3d_imposter_state->enable( GL_CULL_FACE );
188 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
189 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
190 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
191 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
192 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
193 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
194 cloud3d_imposter_state->enable( GL_BLEND );
195 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
196 cloud3d_imposter_state->disable( GL_LIGHTING );
198 hud_and_panel = new ssgSimpleState;
199 hud_and_panel->ref();
200 hud_and_panel->disable( GL_CULL_FACE );
201 hud_and_panel->disable( GL_TEXTURE_2D );
202 hud_and_panel->disable( GL_LIGHTING );
203 hud_and_panel->enable( GL_BLEND );
205 menus = new ssgSimpleState;
207 menus->disable( GL_CULL_FACE );
208 menus->disable( GL_TEXTURE_2D );
209 menus->enable( GL_BLEND );
213 // fgInitVisuals() -- Initialize various GL/view parameters
214 void fgInitVisuals( void ) {
216 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
218 // Go full screen if requested ...
219 if ( fgGetBool("/sim/startup/fullscreen") ) {
223 // If enabled, normal vectors specified with glNormal are scaled
224 // to unit length after transformation. Enabling this has
225 // performance implications. See the docs for glNormal.
226 // glEnable( GL_NORMALIZE );
228 glEnable( GL_LIGHTING );
229 glEnable( GL_LIGHT0 );
230 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
233 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
234 ssgGetLight( 0 ) -> setPosition( sunpos );
236 glFogi (GL_FOG_MODE, GL_EXP2);
237 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
238 (!fgGetBool("/sim/rendering/shading"))) {
239 // if fastest fog requested, or if flat shading force fastest
240 glHint ( GL_FOG_HINT, GL_FASTEST );
241 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
242 glHint ( GL_FOG_HINT, GL_NICEST );
244 if ( fgGetBool("/sim/rendering/wireframe") ) {
246 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
249 // This is the default anyways, but it can't hurt
250 glFrontFace ( GL_CCW );
253 // glEnable(GL_POINT_SMOOTH);
254 // glEnable(GL_LINE_SMOOTH);
255 // glEnable(GL_POLYGON_SMOOTH);
259 // For HiRes screen Dumps using Brian Pauls TR Library
260 void trRenderFrame( void ) {
261 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
262 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
263 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
265 bool multi_pass_clouds = false;
267 bool draw_clouds = fgGetBool("/environment/clouds/status");
269 if ( fgPanelVisible() ) {
270 GLfloat height = fgGetInt("/sim/startup/ysize");
272 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
273 * (height / 768.0) + 1;
274 glTranslatef( 0.0, view_h, 0.0 );
277 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
278 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
280 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
282 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
283 l->adj_fog_color()[2], l->adj_fog_color()[3]);
285 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
287 // set the opengl state to known default values
288 default_state->force();
291 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
292 glFogi ( GL_FOG_MODE, GL_EXP2 );
293 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
295 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
296 // we only update GL_AMBIENT for our lights we will never get
297 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
298 // explicitely to black.
299 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
300 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
302 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
304 // texture parameters
305 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
306 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
308 // we need a white diffuse light for the phase of the moon
309 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
310 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
313 // draw the ssg scene
314 // return to the desired diffuse color
315 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
316 glEnable( GL_DEPTH_TEST );
317 ssgSetNearFar( scene_nearplane, scene_farplane );
320 FGTileMgr::set_tile_filter( true );
321 sgSetModelFilter( false );
322 globals->get_aircraft_model()->select( false );
323 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
324 // Disable depth buffer update, draw the clouds
325 glDepthMask( GL_FALSE );
326 thesky->drawUpperClouds();
327 if ( multi_pass_clouds ) {
328 thesky->drawLowerClouds();
330 glDepthMask( GL_TRUE );
331 if ( multi_pass_clouds ) {
332 // Draw the objects except the aircraft
333 // and update the stencil buffer with 1
334 glEnable( GL_STENCIL_TEST );
335 glStencilFunc( GL_ALWAYS, 1, 1 );
336 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
338 FGTileMgr::set_tile_filter( false );
339 sgSetModelFilter( true );
340 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
342 FGTileMgr::set_tile_filter( true );
343 sgSetModelFilter( true );
344 globals->get_aircraft_model()->select( false );
345 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
349 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
350 ssgSetNearFar( scene_nearplane, scene_farplane );
351 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
352 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
354 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
357 if ( multi_pass_clouds ) {
358 // Disable depth buffer update, draw the clouds where the
359 // objects overwrite the already drawn clouds, by testing
360 // the stencil buffer against 1
361 glDepthMask( GL_FALSE );
362 glStencilFunc( GL_EQUAL, 1, 1 );
363 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
364 thesky->drawUpperClouds();
365 thesky->drawLowerClouds();
366 glDepthMask( GL_TRUE );
367 glDisable( GL_STENCIL_TEST );
369 glDepthMask( GL_FALSE );
370 thesky->drawLowerClouds();
371 glDepthMask( GL_TRUE );
375 globals->get_aircraft_model()->select( true );
376 globals->get_model_mgr()->draw();
377 globals->get_aircraft_model()->draw();
381 // Update all Visuals (redraws anything graphics related)
382 void fgRenderFrame() {
383 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
384 bool skyblend = fgGetBool("/sim/rendering/skyblend");
385 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
386 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
387 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
388 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
389 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
391 bool multi_pass_clouds = false;
393 bool draw_clouds = fgGetBool("/environment/clouds/status");
395 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
396 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
398 // static const SGPropertyNode *longitude
399 // = fgGetNode("/position/longitude-deg");
400 // static const SGPropertyNode *latitude
401 // = fgGetNode("/position/latitude-deg");
402 // static const SGPropertyNode *altitude
403 // = fgGetNode("/position/altitude-ft");
404 static const SGPropertyNode *groundlevel_nearplane
405 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
407 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
408 static double last_visibility = -9999;
411 double actual_visibility;
412 if (fgGetBool("/environment/clouds/status"))
413 actual_visibility = thesky->get_visibility();
415 actual_visibility = fgGetDouble("/environment/visibility-m");
416 if ( actual_visibility != last_visibility ) {
417 last_visibility = actual_visibility;
419 fog_exp_density = m_log01 / actual_visibility;
420 fog_exp2_density = sqrt_m_log01 / actual_visibility;
421 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
422 if ( actual_visibility < 8000 ) {
423 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
424 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
426 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
427 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
432 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
433 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
434 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
435 // GLfloat mat_shininess[] = { 10.0 };
436 GLbitfield clear_mask;
438 if ( idle_state != 1000 ) {
439 // still initializing, draw the splash screen
440 if ( fgGetBool("/sim/startup/splash-screen") ) {
441 fgSplashUpdate(0.0, 1.0);
443 // Keep resetting sim time while the sim is initializing
444 globals->set_sim_time_sec( 0.0 );
445 SGAnimation::set_sim_time_sec( 0.0 );
447 // idle_state is now 1000 meaning we've finished all our
448 // initializations and are running the main loop, so this will
449 // now work without seg faulting the system.
451 FGViewer *current__view = globals->get_current_view();
453 // calculate our current position in cartesian space
454 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
457 fgReshape( fgGetInt("/sim/startup/xsize"),
458 fgGetInt("/sim/startup/ysize") );
460 if ( fgGetBool("/sim/rendering/clouds3d") ) {
461 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
462 cloud3d_imposter_state->force();
464 glColor4f( 1.0, 1.0, 1.0, 1.0 );
465 glEnable(GL_DEPTH_TEST);
467 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
469 #ifdef FG_USE_CLOUDS_3D
470 if ( _bcloud_orig ) {
471 Point3D c = globals->get_scenery()->get_center();
472 sgClouds3d->Set_Cloud_Orig( &c );
473 _bcloud_orig = false;
475 sgClouds3d->Update( current__view->get_absolute_view_pos() );
477 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
478 glDisable(GL_DEPTH_TEST);
481 clear_mask = GL_DEPTH_BUFFER_BIT;
482 if ( fgGetBool("/sim/rendering/wireframe") ) {
483 clear_mask |= GL_COLOR_BUFFER_BIT;
487 if ( fgGetBool("/sim/rendering/textures") ) {
488 // glClearColor(black[0], black[1], black[2], black[3]);
489 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
490 l->adj_fog_color()[2], l->adj_fog_color()[3]);
491 clear_mask |= GL_COLOR_BUFFER_BIT;
494 glClearColor(l->sky_color()[0], l->sky_color()[1],
495 l->sky_color()[2], l->sky_color()[3]);
496 clear_mask |= GL_COLOR_BUFFER_BIT;
498 if ( multi_pass_clouds && draw_clouds ) {
500 clear_mask |= GL_STENCIL_BUFFER_BIT;
502 glClear( clear_mask );
504 // Tell GL we are switching to model view parameters
506 // I really should create a derived ssg node or use a call
507 // back or something so that I can draw the sky within the
508 // ssgCullAndDraw() function, but for now I just mimic what
509 // ssg does to set up the model view matrix
510 glMatrixMode(GL_MODELVIEW);
512 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
514 // set the opengl state to known default values
515 default_state->force();
517 // update fog params if visibility has changed
518 double visibility_meters = fgGetDouble("/environment/visibility-m");
519 thesky->set_visibility(visibility_meters);
521 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
522 ( global_multi_loop * fgGetInt("/sim/speed-up") )
523 / (double)fgGetInt("/sim/model-hz") );
525 // Set correct opengl fog density
526 glFogf (GL_FOG_DENSITY, fog_exp2_density);
528 // update the sky dome
531 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
532 << l->sky_color()[0] << " "
533 << l->sky_color()[1] << " "
534 << l->sky_color()[2] << " "
535 << l->sky_color()[3] );
536 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
537 << l->fog_color()[0] << " "
538 << l->fog_color()[1] << " "
539 << l->fog_color()[2] << " "
540 << l->fog_color()[3] );
541 SG_LOG( SG_GENERAL, SG_BULK,
542 " sun_angle = " << l->sun_angle
543 << " moon_angle = " << l->moon_angle );
546 static SGSkyColor scolor;
547 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
549 scolor.sky_color = l->sky_color();
550 scolor.fog_color = l->adj_fog_color();
551 scolor.cloud_color = l->cloud_color();
552 scolor.sun_angle = l->get_sun_angle();
553 scolor.moon_angle = l->get_moon_angle();
554 scolor.nplanets = globals->get_ephem()->getNumPlanets();
555 scolor.nstars = globals->get_ephem()->getNumStars();
556 scolor.planet_data = globals->get_ephem()->getPlanets();
557 scolor.star_data = globals->get_ephem()->getStars();
559 thesky->repaint( scolor );
562 SG_LOG( SG_GENERAL, SG_BULK,
563 "thesky->reposition( view_pos = " << view_pos[0] << " "
564 << view_pos[1] << " " << view_pos[2] );
565 SG_LOG( SG_GENERAL, SG_BULK,
566 " zero_elev = " << zero_elev[0] << " "
567 << zero_elev[1] << " " << zero_elev[2]
568 << " lon = " << cur_fdm_state->get_Longitude()
569 << " lat = " << cur_fdm_state->get_Latitude() );
570 SG_LOG( SG_GENERAL, SG_BULK,
571 " sun_rot = " << l->get_sun_rotation
572 << " gst = " << SGTime::cur_time_params->getGst() );
573 SG_LOG( SG_GENERAL, SG_BULK,
574 " sun ra = " << globals->get_ephem()->getSunRightAscension()
575 << " sun dec = " << globals->get_ephem()->getSunDeclination()
576 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
577 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
580 // The sun and moon distances are scaled down versions
581 // of the actual distance to get both the moon and the sun
582 // within the range of the far clip plane.
583 // Moon distance: 384,467 kilometers
584 // Sun distance: 150,000,000 kilometers
585 double sun_horiz_eff, moon_horiz_eff;
586 if (fgGetBool("/sim/rendering/horizon-effect")) {
587 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
588 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
590 sun_horiz_eff = moon_horiz_eff = 1.0;
593 static SGSkyState sstate;
595 sstate.view_pos = current__view->get_view_pos();
596 sstate.zero_elev = current__view->get_zero_elev();
597 sstate.view_up = current__view->get_world_up();
598 sstate.lon = current__view->getLongitude_deg()
599 * SGD_DEGREES_TO_RADIANS;
600 sstate.lat = current__view->getLatitude_deg()
601 * SGD_DEGREES_TO_RADIANS;
602 sstate.alt = current__view->getAltitudeASL_ft()
604 sstate.spin = l->get_sun_rotation();
605 sstate.gst = globals->get_time_params()->getGst();
606 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
607 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
608 sstate.sun_dist = 50000.0 * sun_horiz_eff;
609 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
610 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
611 sstate.moon_dist = 40000.0 * moon_horiz_eff;
613 thesky->reposition( sstate, delta_time_sec );
616 glEnable( GL_DEPTH_TEST );
617 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
619 glFogi( GL_FOG_MODE, GL_EXP2 );
620 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
623 // set sun/lighting parameters
624 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
626 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
627 // we only update GL_AMBIENT for our lights we will never get
628 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
629 // explicitely to black.
630 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
632 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
633 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
634 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
636 // texture parameters
637 // glEnable( GL_TEXTURE_2D );
638 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
639 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
641 // glMatrixMode( GL_PROJECTION );
643 ssgSetFOV( current__view->get_h_fov(),
644 current__view->get_v_fov() );
647 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
648 - globals->get_scenery()->get_cur_elev();
651 scene_nearplane = 10.0f;
652 scene_farplane = 120000.0f;
654 scene_nearplane = groundlevel_nearplane->getDoubleValue();
655 scene_farplane = 120000.0f;
658 ssgSetNearFar( scene_nearplane, scene_farplane );
661 // Update any multiplayer models
662 globals->get_multiplayer_rx_mgr()->Update();
665 if ( draw_otw && skyblend ) {
666 // draw the sky backdrop
668 // we need a white diffuse light for the phase of the moon
669 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
670 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
672 // return to the desired diffuse color
673 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
676 // draw the ssg scene
677 glEnable( GL_DEPTH_TEST );
679 ssgSetNearFar( scene_nearplane, scene_farplane );
681 if ( fgGetBool("/sim/rendering/wireframe") ) {
683 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
689 FGTileMgr::set_tile_filter( true );
690 sgSetModelFilter( false );
691 globals->get_aircraft_model()->select( false );
692 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
694 // Disable depth buffer update, draw the clouds
695 glDepthMask( GL_FALSE );
696 thesky->drawUpperClouds();
697 if ( multi_pass_clouds ) {
698 thesky->drawLowerClouds();
700 glDepthMask( GL_TRUE );
702 if ( multi_pass_clouds ) {
703 // Draw the objects except the aircraft
704 // and update the stencil buffer with 1
705 glEnable( GL_STENCIL_TEST );
706 glStencilFunc( GL_ALWAYS, 1, 1 );
707 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
709 FGTileMgr::set_tile_filter( false );
710 sgSetModelFilter( true );
711 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
713 FGTileMgr::set_tile_filter( true );
714 sgSetModelFilter( true );
715 globals->get_aircraft_model()->select( false );
716 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
720 // This is a bit kludgy. Every 200 frames, do an extra
721 // traversal of the scene graph without drawing anything, but
722 // with the field-of-view set to 360x360 degrees. This
723 // ensures that out-of-range random objects that are not in
724 // the current view frustum will still be freed properly.
725 static int counter = 0;
727 if (counter == 200) {
730 // No need to put the near plane too close;
731 // this way, at least the aircraft can be
733 f.setNearFar(1000, 1000000);
735 ssgGetModelviewMatrix(m);
736 FGTileMgr::set_tile_filter( true );
737 sgSetModelFilter( true );
738 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
742 // change state for lighting here
744 // draw runway lighting
745 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
746 ssgSetNearFar( scene_nearplane, scene_farplane );
748 if ( enhanced_lighting ) {
750 // Enable states for drawing points with GL_extension
751 glEnable(GL_POINT_SMOOTH);
753 if ( distance_attenuation && glPointParameterIsSupported )
755 // Enable states for drawing points with GL_extension
756 glEnable(GL_POINT_SMOOTH);
758 float quadratic[3] = {1.0, 0.001, 0.0000001};
759 // makes the points fade as they move away
760 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
761 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
766 // blending function for runway lights
767 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
770 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
771 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
772 glEnable(GL_TEXTURE_GEN_S);
773 glEnable(GL_TEXTURE_GEN_T);
774 glPolygonMode(GL_FRONT, GL_POINT);
776 // draw runway lighting
778 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
779 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
782 // change punch through and then draw taxi lighting
783 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
785 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
786 // glFogfv ( GL_FOG_COLOR, taxi_fog );
788 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
792 glPolygonMode(GL_FRONT, GL_FILL);
793 glDisable(GL_TEXTURE_GEN_S);
794 glDisable(GL_TEXTURE_GEN_T);
796 //static int _frame_count = 0;
797 //if (_frame_count % 30 == 0) {
798 // printf("SSG: %s\n", ssgShowStats());
806 if ( enhanced_lighting ) {
807 if ( distance_attenuation && glPointParameterIsSupported ) {
808 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
809 default_attenuation);
813 glDisable(GL_POINT_SMOOTH);
816 // draw ground lighting
817 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
819 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
822 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
824 glDisable( GL_LIGHTING );
825 // cout << "drawing new clouds" << endl;
827 glEnable(GL_DEPTH_TEST);
829 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
832 glEnable( GL_TEXTURE_2D );
833 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
834 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
835 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
836 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
839 #ifdef FG_USE_CLOUDS_3D
840 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
843 glEnable( GL_LIGHTING );
844 glEnable( GL_DEPTH_TEST );
845 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
848 if ( draw_otw && draw_clouds ) {
849 if ( multi_pass_clouds ) {
850 // Disable depth buffer update, draw the clouds where the
851 // objects overwrite the already drawn clouds, by testing
852 // the stencil buffer against 1
853 glDepthMask( GL_FALSE );
854 glStencilFunc( GL_EQUAL, 1, 1 );
855 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
856 thesky->drawUpperClouds();
857 thesky->drawLowerClouds();
858 glDepthMask( GL_TRUE );
859 glDisable( GL_STENCIL_TEST );
861 glDepthMask( GL_FALSE );
862 thesky->drawLowerClouds();
863 glDepthMask( GL_TRUE );
868 FGTileMgr::set_tile_filter( false );
869 sgSetModelFilter( false );
870 globals->get_aircraft_model()->select( true );
871 globals->get_model_mgr()->draw();
872 globals->get_aircraft_model()->draw();
873 // If the view is internal, the previous line draw the
874 // cockpit with modified near/far clip planes and deselect
875 // the aircraft in the global scenegraph
876 // Otherwise, it just enables the aircraft: The scenegraph
877 // must be drawn again to see the plane.
878 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
879 FGTileMgr::set_tile_filter( true );
880 sgSetModelFilter( true );
881 globals->get_aircraft_model()->select( true );
884 // display HUD && Panel
886 glDisable( GL_DEPTH_TEST );
887 // glDisable( GL_CULL_FACE );
888 // glDisable( GL_TEXTURE_2D );
890 // update the controls subsystem
891 globals->get_controls()->update(delta_time_sec);
893 hud_and_panel->apply();
896 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
897 // This only works properly if called before the panel call
898 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
899 globals->get_ATC_display()->update(delta_time_sec);
901 // update the panel subsystem
902 if ( globals->get_current_panel() != NULL ) {
903 globals->get_current_panel()->update(delta_time_sec);
907 // We can do translucent menus, so why not. :-)
909 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
911 // glDisable ( GL_BLEND ) ;
913 glEnable( GL_DEPTH_TEST );
916 // Fade out the splash screen over the first three seconds.
917 double t = globals->get_sim_time_sec();
919 fgSplashUpdate(0.0, 1.0);
920 } else if ( t <= 3.0) {
921 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
927 // Update internal time dependent calculations (i.e. flight model)
928 // FIXME: this distinction is obsolete; all subsystems now get delta
930 void fgUpdateTimeDepCalcs() {
931 static bool inited = false;
933 static const SGPropertyNode *replay_master
934 = fgGetNode( "/sim/freeze/replay", true );
935 static SGPropertyNode *replay_time
936 = fgGetNode( "/sim/replay/time", true );
937 // static const SGPropertyNode *replay_end_time
938 // = fgGetNode( "/sim/replay/end-time", true );
940 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
942 // Initialize the FDM here if it hasn't been and if we have a
943 // scenery elevation hit.
945 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
946 // << " cur_elev = " << scenery.get_cur_elev() << endl;
948 if ( !cur_fdm_state->get_inited() &&
949 globals->get_scenery()->get_cur_elev() > -9990 )
951 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
952 cur_fdm_state->init();
953 if ( cur_fdm_state->get_bound() ) {
954 cur_fdm_state->unbind();
956 cur_fdm_state->bind();
959 // conceptually, the following block could be done for each fdm
961 if ( cur_fdm_state->get_inited() ) {
962 // we have been inited, and we are good to go ...
968 if ( ! replay_master->getBoolValue() ) {
969 cur_fdm_state->update( delta_time_sec );
971 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
972 r->replay( replay_time->getDoubleValue() );
973 replay_time->setDoubleValue( replay_time->getDoubleValue()
975 * fgGetInt("/sim/speed-up") ) );
978 // do nothing, fdm isn't inited yet
981 globals->get_model_mgr()->update(delta_time_sec);
982 globals->get_aircraft_model()->update(delta_time_sec);
984 // update the view angle
985 globals->get_viewmgr()->update(delta_time_sec);
987 // Update solar system
988 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
989 globals->get_time_params()->getLst(),
990 cur_fdm_state->get_Latitude() );
992 // Update radio stack model
993 current_radiostack->update(delta_time_sec);
997 void fgInitTimeDepCalcs( void ) {
1002 static const double alt_adjust_ft = 3.758099;
1003 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1006 // What should we do when we have nothing else to do? Let's get ready
1007 // for the next move and update the display?
1008 static void fgMainLoop( void ) {
1009 int model_hz = fgGetInt("/sim/model-hz");
1011 static const SGPropertyNode *longitude
1012 = fgGetNode("/position/longitude-deg");
1013 static const SGPropertyNode *latitude
1014 = fgGetNode("/position/latitude-deg");
1015 static const SGPropertyNode *altitude
1016 = fgGetNode("/position/altitude-ft");
1017 static const SGPropertyNode *clock_freeze
1018 = fgGetNode("/sim/freeze/clock", true);
1019 static const SGPropertyNode *cur_time_override
1020 = fgGetNode("/sim/time/cur-time-override", true);
1021 // static const SGPropertyNode *replay_master
1022 // = fgGetNode("/sim/freeze/replay", true);
1024 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1026 // Update the elapsed time.
1027 static bool first_time = true;
1029 last_time_stamp.stamp();
1033 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1034 if ( throttle_hz > 0.0 ) {
1035 // simple frame rate throttle
1036 double dt = 1000000.0 / throttle_hz;
1037 current_time_stamp.stamp();
1038 while ( current_time_stamp - last_time_stamp < dt ) {
1039 current_time_stamp.stamp();
1042 // run as fast as the app will go
1043 current_time_stamp.stamp();
1047 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1048 if ( clock_freeze->getBoolValue() ) {
1051 delta_time_sec = real_delta_time_sec;
1053 last_time_stamp = current_time_stamp;
1054 globals->inc_sim_time_sec( delta_time_sec );
1055 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1057 // These are useful, especially for Nasal scripts.
1058 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1059 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1061 static long remainder = 0;
1063 #ifdef FANCY_FRAME_COUNTER
1067 static time_t last_time = 0;
1068 static int frames = 0;
1069 #endif // FANCY_FRAME_COUNTER
1071 SGTime *t = globals->get_time_params();
1073 globals->get_event_mgr()->update(delta_time_sec);
1075 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1076 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1078 #if defined( ENABLE_PLIB_JOYSTICK )
1079 // Read joystick and update control settings
1080 // if ( fgGetString("/sim/control-mode") == "joystick" )
1082 // fgJoystickRead();
1086 // Fix elevation. I'm just sticking this here for now, it should
1087 // probably move eventually
1089 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1090 scenery.get_cur_elev(),
1091 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1092 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1094 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1095 scenery.get_cur_elev(),
1096 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1097 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1099 // cout << "Warp = " << globals->get_warp() << endl;
1102 static bool last_clock_freeze = false;
1104 if ( clock_freeze->getBoolValue() ) {
1105 // clock freeze requested
1106 if ( cur_time_override->getLongValue() == 0 ) {
1107 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1108 globals->set_warp( 0 );
1111 // no clock freeze requested
1112 if ( last_clock_freeze == true ) {
1113 // clock just unfroze, let's set warp as the difference
1114 // between frozen time and current time so we don't get a
1115 // time jump (and corresponding sky object and lighting
1117 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1118 fgSetLong( "/sim/time/cur-time-override", 0 );
1120 if ( globals->get_warp_delta() != 0 ) {
1121 globals->inc_warp( globals->get_warp_delta() );
1125 last_clock_freeze = clock_freeze->getBoolValue();
1127 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1128 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1129 cur_time_override->getLongValue(),
1130 globals->get_warp() );
1132 if (globals->get_warp_delta() != 0) {
1133 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1137 // update magvar model
1138 globals->get_mag()->update( longitude->getDoubleValue()
1139 * SGD_DEGREES_TO_RADIANS,
1140 latitude->getDoubleValue()
1141 * SGD_DEGREES_TO_RADIANS,
1142 altitude->getDoubleValue() * SG_FEET_TO_METER,
1143 globals->get_time_params()->getJD() );
1145 // Get elapsed time (in usec) for this past frame
1146 elapsed = fgGetTimeInterval();
1147 SG_LOG( SG_ALL, SG_DEBUG,
1148 "Elapsed time interval is = " << elapsed
1149 << ", previous remainder is = " << remainder );
1151 // Calculate frame rate average
1152 #ifdef FANCY_FRAME_COUNTER
1153 /* old fps calculation */
1154 if ( elapsed > 0 ) {
1157 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1158 tmp = general.get_frame(i);
1160 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1161 general.set_frame(i+1,tmp);
1163 tmp = 1000000.0 / (float)elapsed;
1164 general.set_frame(0,tmp);
1165 // printf("frame[0] = %.2f\n", general.frames[0]);
1167 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1168 // printf("ave = %.2f\n", general.frame_rate);
1171 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1172 general.set_frame_rate( frames );
1173 fgSetInt("/sim/frame-rate", frames);
1174 SG_LOG( SG_ALL, SG_DEBUG,
1175 "--> Frame rate is = " << general.get_frame_rate() );
1178 last_time = t->get_cur_time();
1182 // Run ATC subsystem
1183 if (fgGetBool("/sim/ATC/enabled"))
1184 globals->get_ATC_mgr()->update(delta_time_sec);
1186 // Run the AI subsystem
1187 if (fgGetBool("/sim/ai-traffic/enabled"))
1188 globals->get_AI_mgr()->update(delta_time_sec);
1192 // Calculate model iterations needed for next frame
1193 elapsed += remainder;
1195 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1196 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1197 SG_LOG( SG_ALL, SG_DEBUG,
1198 "Model iterations needed = " << global_multi_loop
1199 << ", new remainder = " << remainder );
1201 // chop max interations to something reasonable if the sim was
1202 // delayed for an excesive amount of time
1203 if ( global_multi_loop > 2.0 * model_hz ) {
1204 global_multi_loop = (int)(2.0 * model_hz );
1209 if ( global_multi_loop > 0) {
1210 // first run the flight model each frame until it is intialized
1211 // then continue running each frame only after initial scenery load is complete.
1212 if (!cur_fdm_state->get_inited() || fgGetBool("sim/sceneryloaded")) {
1213 fgUpdateTimeDepCalcs();
1215 // only during scenery load
1216 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1217 gui->showDialog("scenery_loading");
1220 SG_LOG( SG_ALL, SG_DEBUG,
1221 "Elapsed time is zero ... we're zinging" );
1224 // Do any I/O channel work that might need to be done
1225 globals->get_io()->update( real_delta_time_sec );
1227 // see if we need to load any deferred-load textures
1228 globals->get_matlib()->load_next_deferred();
1230 // Run audio scheduler
1231 #ifdef ENABLE_AUDIO_SUPPORT
1232 if ( globals->get_soundmgr()->is_working() ) {
1233 globals->get_soundmgr()->update( delta_time_sec );
1237 globals->get_subsystem_mgr()->update(delta_time_sec);
1240 // Tile Manager updates - see if we need to load any new scenery tiles.
1241 // this code ties together the fdm, viewer and scenery classes...
1242 // we may want to move this to it's own class at some point
1244 double visibility_meters = fgGetDouble("/environment/visibility-m");
1245 FGViewer *current_view = globals->get_current_view();
1247 // get the location data for the primary FDM (now hardcoded to ac model)...
1248 SGLocation *acmodel_loc = NULL;
1249 acmodel_loc = (SGLocation *)globals->
1250 get_aircraft_model()->get3DModel()->getSGLocation();
1252 // update tile manager for FDM...
1253 // ...only if location is different than the current-view location
1254 // (to avoid duplicating effort)
1255 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1256 if( acmodel_loc != NULL ) {
1257 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1258 visibility_meters );
1259 globals->get_tile_mgr()->
1260 update( acmodel_loc, visibility_meters,
1262 get_absolute_view_pos(globals->
1263 get_scenery()->get_center()) );
1264 // save results of update in SGLocation for fdm...
1265 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1267 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1268 fgSetDouble("/position/ground-elev-m",
1269 globals->get_scenery()->get_cur_elev());
1272 set_tile_center( globals->get_scenery()->get_next_center() );
1276 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1277 visibility_meters );
1278 // update tile manager for view...
1279 // IMPORTANT!!! the tilemgr update for view location _must_ be
1280 // done last after the FDM's until all of Flight Gear code
1281 // references the viewer's location for elevation instead of the
1282 // "scenery's" current elevation.
1283 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1284 globals->get_tile_mgr()->update( view_location, visibility_meters,
1285 current_view->get_absolute_view_pos() );
1286 // save results of update in SGLocation for fdm...
1287 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1288 current_view->getSGLocation()->
1289 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1291 current_view->getSGLocation()->
1292 set_tile_center( globals->get_scenery()->get_next_center() );
1294 #ifdef ENABLE_AUDIO_SUPPORT
1295 // Right now we make a simplifying assumption that the primary
1296 // aircraft is the source of all sounds and that all sounds are
1297 // positioned relative to the current view position.
1299 static sgVec3 last_pos_offset;
1301 // set positional offset for sources
1302 sgVec3 source_pos_offset;
1303 sgSubVec3( source_pos_offset,
1304 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1305 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1306 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1310 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1311 sgScaleVec3( source_vel, delta_time_sec );
1312 sgCopyVec3( last_pos_offset, source_pos_offset );
1313 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1314 globals->get_soundmgr()->set_source_vel_all( source_vel );
1316 // Right now we make a simplifying assumption that the listener is
1317 // always positioned at the origin.
1318 sgVec3 listener_pos;
1319 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1320 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1321 globals->get_soundmgr()->set_listener_pos( listener_pos );
1324 // If fdm location is same as viewer's then we didn't do the
1325 // update for fdm location above so we need to save the viewer
1326 // results in the fdm SGLocation as well...
1327 if( fgGetBool("/sim/current-view/config/from-model") ) {
1328 if( acmodel_loc != 0 ) {
1329 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1330 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1332 fgSetDouble("/position/ground-elev-m",
1333 globals->get_scenery()->get_cur_elev());
1335 acmodel_loc->set_tile_center( globals->get_scenery()->
1336 get_next_center() );
1340 // END Tile Manager udpates
1342 if (!fgGetBool("sim/sceneryloaded") && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
1343 fgSetBool("sim/sceneryloaded",true);
1344 // probably not efficient way to popup msg, but is done only during scenery load
1345 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1346 gui->closeDialog("scenery_loading");
1349 if (fgGetBool("/sim/rendering/specular-highlight")) {
1350 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1351 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1353 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1354 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1359 SG_LOG( SG_ALL, SG_DEBUG, "" );
1363 // This is the top level master main function that is registered as
1364 // our idle funciton
1366 // The first few passes take care of initialization things (a couple
1367 // per pass) and once everything has been initialized fgMainLoop from
1370 static void fgIdleFunction ( void ) {
1371 // printf("idle state == %d\n", idle_state);
1373 if ( idle_state == 0 ) {
1374 fgSetBool("sim/initialised", false);
1376 // Initialize the splash screen right away
1377 if ( fgGetBool("/sim/startup/splash-screen") ) {
1378 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1382 } else if ( idle_state == 1 ) {
1383 // Initialize audio support
1384 #ifdef ENABLE_AUDIO_SUPPORT
1386 // Start the intro music
1387 if ( fgGetBool("/sim/startup/intro-music") ) {
1388 SGPath mp3file( globals->get_fg_root() );
1389 mp3file.append( "Sounds/intro.mp3" );
1391 SG_LOG( SG_GENERAL, SG_INFO,
1392 "Starting intro music: " << mp3file.str() );
1394 #if defined( __CYGWIN__ )
1395 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1396 #elif defined( WIN32 )
1397 string command = "start /m " + mp3file.str();
1399 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1402 system ( command.c_str() );
1407 } else if ( idle_state == 2 ) {
1408 // These are a few miscellaneous things that aren't really
1409 // "subsystems" but still need to be initialized.
1412 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1413 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1418 } else if ( idle_state == 3 ) {
1419 // This is the top level init routine which calls all the
1420 // other subsystem initialization routines. If you are adding
1421 // a subsystem to flightgear, its initialization call should
1422 // located in this routine.
1423 if( !fgInitSubsystems()) {
1424 SG_LOG( SG_GENERAL, SG_ALERT,
1425 "Subsystem initializations failed ..." );
1430 } else if ( idle_state == 4 ) {
1431 // Initialize the time offset (warp) after fgInitSubsystem
1432 // (which initializes the lighting interpolation tables.)
1435 // setup OpenGL view parameters
1438 // Read the list of available aircrafts
1442 } else if ( idle_state == 5 ) {
1445 } else if ( idle_state == 6 ) {
1450 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1451 fgReshape( fgGetInt("/sim/startup/xsize"),
1452 fgGetInt("/sim/startup/ysize") );
1456 if ( idle_state == 1000 ) {
1457 // We've finished all our initialization steps, from now on we
1458 // run the main loop.
1459 fgSetBool("sim/initialised",true);
1460 fgSetBool("sim/sceneryloaded",false);
1462 fgRegisterIdleHandler(fgMainLoop);
1464 if ( fgGetBool("/sim/startup/splash-screen") ) {
1465 fgSplashUpdate(0.0, 1.0);
1470 // options.cxx needs to see this for toggle_panel()
1471 // Handle new window size or exposure
1472 void fgReshape( int width, int height ) {
1475 if ( (!fgGetBool("/sim/virtual-cockpit"))
1476 && fgPanelVisible() && idle_state == 1000 ) {
1477 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1478 globals->get_current_panel()->getYOffset()) / 768.0);
1483 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1485 fgSetInt("/sim/startup/xsize", width);
1486 fgSetInt("/sim/startup/ysize", height);
1487 guiInitMouse(width, height);
1490 FGViewMgr *viewmgr = globals->get_viewmgr();
1492 for ( int i = 0; i < viewmgr->size(); ++i ) {
1493 viewmgr->get_view(i)->
1494 set_aspect_ratio((float)view_h / (float)width);
1497 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1498 viewmgr->get_current_view()->get_v_fov() );
1500 #ifdef FG_USE_CLOUDS_3D
1501 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1502 viewmgr->get_current_view()->get_v_fov() );
1511 // do some clean up on exit. Specifically we want to call alutExit()
1512 // which happens in the sound manager destructor.
1513 void fgExitCleanup() {
1519 // Main top level initialization
1520 bool fgMainInit( int argc, char **argv ) {
1522 #if defined( macintosh )
1523 freopen ("stdout.txt", "w", stdout );
1524 freopen ("stderr.txt", "w", stderr );
1525 argc = ccommand( &argv );
1528 // set default log levels
1529 sglog().setLogLevels( SG_ALL, SG_ALERT );
1531 atexit(fgExitCleanup);
1534 #ifdef FLIGHTGEAR_VERSION
1535 version = FLIGHTGEAR_VERSION;
1537 version = "unknown version";
1539 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1541 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1543 // Allocate global data structures. This needs to happen before
1544 // we parse command line options
1546 globals = new FGGlobals;
1548 // seed the random number generater
1551 FGControls *controls = new FGControls;
1552 globals->set_controls( controls );
1554 string_list *col = new string_list;
1555 globals->set_channel_options_list( col );
1557 // Scan the config file(s) and command line options to see if
1558 // fg_root was specified (ignore all other options for now)
1559 fgInitFGRoot(argc, argv);
1561 // Check for the correct base package version
1562 static char required_version[] = "0.9.5";
1563 string base_version = fgBasePackageVersion();
1564 if ( !(base_version == required_version) ) {
1565 // tell the operator how to use this application
1567 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1568 cerr << endl << "Base package check failed ... " \
1569 << "Found version " << base_version << " at: " \
1570 << globals->get_fg_root() << endl;
1571 cerr << "Please upgrade to version: " << required_version << endl;
1573 cerr << "Hit a key to continue..." << endl;
1579 // Initialize the Aircraft directory to "" (UIUC)
1582 // Load the configuration parameters. (Command line options
1583 // overrides config file options. Config file options override
1585 if ( !fgInitConfig(argc, argv) ) {
1586 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1590 // Initialize the Window/Graphics environment.
1591 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1592 // Mac OS X command line ("non-bundle") applications call this
1593 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1594 // feel free to add comments...
1595 fgOSInit(&argc, argv);
1598 fgRegisterWindowResizeHandler( fgReshape );
1599 fgRegisterIdleHandler( fgIdleFunction );
1600 fgRegisterDrawHandler( fgRenderFrame );
1602 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1603 bool get_stencil_buffer = true;
1605 bool get_stencil_buffer = false;
1608 // Clouds3D requires an alpha channel
1609 // clouds may require stencil buffer
1610 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1611 fgGetInt("/sim/startup/ysize"),
1612 fgGetInt("/sim/rendering/bits-per-pixel"),
1613 fgGetBool("/sim/rendering/clouds3d"),
1615 fgGetBool("/sim/startup/fullscreen") );
1617 // This seems to be the absolute earliest in the init sequence
1618 // that these calls will return valid info. Too bad it's after
1619 // we've already created and sized out window. :-(
1620 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1621 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1622 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1623 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1626 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1627 general.set_glMaxTexSize( tmp );
1628 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1630 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1631 general.set_glDepthBits( tmp );
1632 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1634 // Initialize plib net interface
1635 netInit( &argc, argv );
1637 // Initialize ssg (from plib). Needs to come before we do any
1638 // other ssg stuff, but after opengl has been initialized.
1641 // Initialize the user interface (we need to do this before
1642 // passing off control to the OS main loop and before
1643 // fgInitGeneral to get our fonts !!!
1646 // Read the list of available aircrafts
1649 #ifdef GL_EXT_texture_lod_bias
1650 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1653 // get the address of our OpenGL extensions
1654 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1656 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1657 glPointParameterIsSupported = true;
1658 glPointParameterfPtr = (glPointParameterfProc)
1659 SGLookupFunction("glPointParameterfEXT");
1660 glPointParameterfvPtr = (glPointParameterfvProc)
1661 SGLookupFunction("glPointParameterfvEXT");
1663 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1664 glPointParameterIsSupported = true;
1665 glPointParameterfPtr = (glPointParameterfProc)
1666 SGLookupFunction("glPointParameterfARB");
1667 glPointParameterfvPtr = (glPointParameterfvProc)
1668 SGLookupFunction("glPointParameterfvARB");
1670 glPointParameterIsSupported = false;
1673 // based on the requested presets, calculate the true starting
1678 SGTime *t = fgInitTime();
1679 globals->set_time_params( t );
1681 // Do some quick general initializations
1682 if( !fgInitGeneral()) {
1683 SG_LOG( SG_GENERAL, SG_ALERT,
1684 "General initializations failed ..." );
1688 ////////////////////////////////////////////////////////////////////
1689 // Initialize the property-based built-in commands
1690 ////////////////////////////////////////////////////////////////////
1693 ////////////////////////////////////////////////////////////////////
1694 // Initialize the material manager
1695 ////////////////////////////////////////////////////////////////////
1696 globals->set_matlib( new SGMaterialLib );
1698 globals->set_model_lib(new SGModelLib);
1700 ////////////////////////////////////////////////////////////////////
1701 // Initialize the TG scenery subsystem.
1702 ////////////////////////////////////////////////////////////////////
1703 globals->set_scenery( new FGScenery );
1704 globals->get_scenery()->init();
1705 globals->get_scenery()->bind();
1706 globals->set_tile_mgr( new FGTileMgr );
1708 ////////////////////////////////////////////////////////////////////
1709 // Initialize the general model subsystem.
1710 ////////////////////////////////////////////////////////////////////
1711 globals->set_model_mgr(new FGModelMgr);
1712 globals->get_model_mgr()->init();
1713 globals->get_model_mgr()->bind();
1715 ////////////////////////////////////////////////////////////////////
1716 // Initialize the 3D aircraft model subsystem (has a dependency on
1717 // the scenery subsystem.)
1718 ////////////////////////////////////////////////////////////////////
1719 globals->set_aircraft_model(new FGAircraftModel);
1720 globals->get_aircraft_model()->init();
1721 globals->get_aircraft_model()->bind();
1723 ////////////////////////////////////////////////////////////////////
1724 // Initialize the view manager subsystem.
1725 ////////////////////////////////////////////////////////////////////
1726 FGViewMgr *viewmgr = new FGViewMgr;
1727 globals->set_viewmgr( viewmgr );
1732 // Initialize the sky
1733 SGPath ephem_data_path( globals->get_fg_root() );
1734 ephem_data_path.append( "Astro" );
1735 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1736 ephem->update( globals->get_time_params()->getMjd(),
1737 globals->get_time_params()->getLst(),
1739 globals->set_ephem( ephem );
1741 // TODO: move to environment mgr
1743 SGPath texture_path(globals->get_fg_root());
1744 texture_path.append("Textures");
1745 texture_path.append("Sky");
1746 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1747 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1748 thesky->add_cloud_layer(layer);
1751 SGPath sky_tex_path( globals->get_fg_root() );
1752 sky_tex_path.append( "Textures" );
1753 sky_tex_path.append( "Sky" );
1754 thesky->texture_path( sky_tex_path.str() );
1756 // The sun and moon diameters are scaled down numbers of the
1757 // actual diameters. This was needed to fit bot the sun and the
1758 // moon within the distance to the far clip plane.
1759 // Moon diameter: 3,476 kilometers
1760 // Sun diameter: 1,390,000 kilometers
1761 thesky->build( 80000.0, 80000.0,
1763 globals->get_ephem()->getNumPlanets(),
1764 globals->get_ephem()->getPlanets(),
1765 globals->get_ephem()->getNumStars(),
1766 globals->get_ephem()->getStars() );
1768 // Initialize MagVar model
1769 SGMagVar *magvar = new SGMagVar();
1770 globals->set_mag( magvar );
1773 // kludge to initialize mag compass
1774 // (should only be done for in-flight
1776 // update magvar model
1777 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1778 * SGD_DEGREES_TO_RADIANS,
1779 fgGetDouble("/position/latitude-deg")
1780 * SGD_DEGREES_TO_RADIANS,
1781 fgGetDouble("/position/altitude-ft")
1783 globals->get_time_params()->getJD() );
1784 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1785 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1787 // airport = new ssgBranch;
1788 // airport->setName( "Airport Lighting" );
1789 // lighting->addKid( airport );
1791 // build our custom render states
1792 fgBuildRenderStates();
1795 // pass control off to the master event handler
1798 SG_LOG( SG_ALL, SG_ALERT,
1799 "Unknown exception in the main loop. Aborting..." );
1802 // we never actually get here ... but to avoid compiler warnings,