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");
263 bool multi_pass_clouds = false;
265 bool draw_clouds = fgGetBool("/environment/clouds/status");
267 if ( fgPanelVisible() ) {
268 GLfloat height = fgGetInt("/sim/startup/ysize");
270 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
271 * (height / 768.0) + 1;
272 glTranslatef( 0.0, view_h, 0.0 );
275 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
276 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
278 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
280 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
281 l->adj_fog_color()[2], l->adj_fog_color()[3]);
283 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
285 // set the opengl state to known default values
286 default_state->force();
289 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
290 glFogi ( GL_FOG_MODE, GL_EXP2 );
291 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
293 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
294 // we only update GL_AMBIENT for our lights we will never get
295 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
296 // explicitely to black.
297 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
298 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
300 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
302 // texture parameters
303 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
304 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
306 // we need a white diffuse light for the phase of the moon
307 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
308 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
311 // draw the ssg scene
312 // return to the desired diffuse color
313 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
314 glEnable( GL_DEPTH_TEST );
315 ssgSetNearFar( scene_nearplane, scene_farplane );
318 FGTileMgr::set_tile_filter( true );
319 sgSetModelFilter( false );
320 globals->get_aircraft_model()->select( false );
321 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
322 // Disable depth buffer update, draw the clouds
323 glDepthMask( GL_FALSE );
324 thesky->drawUpperClouds();
325 if ( multi_pass_clouds ) {
326 thesky->drawLowerClouds();
328 glDepthMask( GL_TRUE );
329 if ( multi_pass_clouds ) {
330 // Draw the objects except the aircraft
331 // and update the stencil buffer with 1
332 glEnable( GL_STENCIL_TEST );
333 glStencilFunc( GL_ALWAYS, 1, 1 );
334 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
336 FGTileMgr::set_tile_filter( false );
337 sgSetModelFilter( true );
338 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
340 FGTileMgr::set_tile_filter( true );
341 sgSetModelFilter( true );
342 globals->get_aircraft_model()->select( false );
343 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
347 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
348 ssgSetNearFar( scene_nearplane, scene_farplane );
349 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
350 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
352 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
355 if ( multi_pass_clouds ) {
356 // Disable depth buffer update, draw the clouds where the
357 // objects overwrite the already drawn clouds, by testing
358 // the stencil buffer against 1
359 glDepthMask( GL_FALSE );
360 glStencilFunc( GL_EQUAL, 1, 1 );
361 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
362 thesky->drawUpperClouds();
363 thesky->drawLowerClouds();
364 glDepthMask( GL_TRUE );
365 glDisable( GL_STENCIL_TEST );
367 glDepthMask( GL_FALSE );
368 thesky->drawLowerClouds();
369 glDepthMask( GL_TRUE );
373 globals->get_aircraft_model()->select( true );
374 globals->get_model_mgr()->draw();
375 globals->get_aircraft_model()->draw();
379 // Update all Visuals (redraws anything graphics related)
380 void fgRenderFrame() {
381 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
382 bool skyblend = fgGetBool("/sim/rendering/skyblend");
383 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
384 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
385 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
386 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
388 bool multi_pass_clouds = false;
390 bool draw_clouds = fgGetBool("/environment/clouds/status");
392 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
393 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
395 // static const SGPropertyNode *longitude
396 // = fgGetNode("/position/longitude-deg");
397 // static const SGPropertyNode *latitude
398 // = fgGetNode("/position/latitude-deg");
399 // static const SGPropertyNode *altitude
400 // = fgGetNode("/position/altitude-ft");
401 static const SGPropertyNode *groundlevel_nearplane
402 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
404 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
405 static double last_visibility = -9999;
408 double actual_visibility;
409 if (fgGetBool("/environment/clouds/status"))
410 actual_visibility = thesky->get_visibility();
412 actual_visibility = fgGetDouble("/environment/visibility-m");
413 if ( actual_visibility != last_visibility ) {
414 last_visibility = actual_visibility;
416 fog_exp_density = m_log01 / actual_visibility;
417 fog_exp2_density = sqrt_m_log01 / actual_visibility;
418 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
419 if ( actual_visibility < 8000 ) {
420 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
421 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
423 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
424 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
429 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
430 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
431 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
432 // GLfloat mat_shininess[] = { 10.0 };
433 GLbitfield clear_mask;
435 if ( idle_state != 1000 ) {
436 // still initializing, draw the splash screen
437 if ( fgGetBool("/sim/startup/splash-screen") ) {
438 fgSplashUpdate(0.0, 1.0);
440 // Keep resetting sim time while the sim is initializing
441 globals->set_sim_time_sec( 0.0 );
442 SGAnimation::set_sim_time_sec( 0.0 );
444 // idle_state is now 1000 meaning we've finished all our
445 // initializations and are running the main loop, so this will
446 // now work without seg faulting the system.
448 FGViewer *current__view = globals->get_current_view();
450 // calculate our current position in cartesian space
451 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
454 fgReshape( fgGetInt("/sim/startup/xsize"),
455 fgGetInt("/sim/startup/ysize") );
457 if ( fgGetBool("/sim/rendering/clouds3d") ) {
458 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
459 cloud3d_imposter_state->force();
461 glColor4f( 1.0, 1.0, 1.0, 1.0 );
462 glEnable(GL_DEPTH_TEST);
464 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
466 #ifdef FG_USE_CLOUDS_3D
467 if ( _bcloud_orig ) {
468 Point3D c = globals->get_scenery()->get_center();
469 sgClouds3d->Set_Cloud_Orig( &c );
470 _bcloud_orig = false;
472 sgClouds3d->Update( current__view->get_absolute_view_pos() );
474 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
475 glDisable(GL_DEPTH_TEST);
478 clear_mask = GL_DEPTH_BUFFER_BIT;
479 if ( fgGetBool("/sim/rendering/wireframe") ) {
480 clear_mask |= GL_COLOR_BUFFER_BIT;
484 if ( fgGetBool("/sim/rendering/textures") ) {
485 // glClearColor(black[0], black[1], black[2], black[3]);
486 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
487 l->adj_fog_color()[2], l->adj_fog_color()[3]);
488 clear_mask |= GL_COLOR_BUFFER_BIT;
491 glClearColor(l->sky_color()[0], l->sky_color()[1],
492 l->sky_color()[2], l->sky_color()[3]);
493 clear_mask |= GL_COLOR_BUFFER_BIT;
495 if ( multi_pass_clouds && draw_clouds ) {
497 clear_mask |= GL_STENCIL_BUFFER_BIT;
499 glClear( clear_mask );
501 // Tell GL we are switching to model view parameters
503 // I really should create a derived ssg node or use a call
504 // back or something so that I can draw the sky within the
505 // ssgCullAndDraw() function, but for now I just mimic what
506 // ssg does to set up the model view matrix
507 glMatrixMode(GL_MODELVIEW);
509 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
511 // set the opengl state to known default values
512 default_state->force();
514 // update fog params if visibility has changed
515 double visibility_meters = fgGetDouble("/environment/visibility-m");
516 thesky->set_visibility(visibility_meters);
518 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
519 ( global_multi_loop * fgGetInt("/sim/speed-up") )
520 / (double)fgGetInt("/sim/model-hz") );
522 // Set correct opengl fog density
523 glFogf (GL_FOG_DENSITY, fog_exp2_density);
525 // update the sky dome
528 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
529 << l->sky_color()[0] << " "
530 << l->sky_color()[1] << " "
531 << l->sky_color()[2] << " "
532 << l->sky_color()[3] );
533 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
534 << l->fog_color()[0] << " "
535 << l->fog_color()[1] << " "
536 << l->fog_color()[2] << " "
537 << l->fog_color()[3] );
538 SG_LOG( SG_GENERAL, SG_BULK,
539 " sun_angle = " << l->sun_angle
540 << " moon_angle = " << l->moon_angle );
543 static SGSkyColor scolor;
544 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
546 scolor.sky_color = l->sky_color();
547 scolor.fog_color = l->adj_fog_color();
548 scolor.cloud_color = l->cloud_color();
549 scolor.sun_angle = l->get_sun_angle();
550 scolor.moon_angle = l->get_moon_angle();
551 scolor.nplanets = globals->get_ephem()->getNumPlanets();
552 scolor.nstars = globals->get_ephem()->getNumStars();
553 scolor.planet_data = globals->get_ephem()->getPlanets();
554 scolor.star_data = globals->get_ephem()->getStars();
556 thesky->repaint( scolor );
559 SG_LOG( SG_GENERAL, SG_BULK,
560 "thesky->reposition( view_pos = " << view_pos[0] << " "
561 << view_pos[1] << " " << view_pos[2] );
562 SG_LOG( SG_GENERAL, SG_BULK,
563 " zero_elev = " << zero_elev[0] << " "
564 << zero_elev[1] << " " << zero_elev[2]
565 << " lon = " << cur_fdm_state->get_Longitude()
566 << " lat = " << cur_fdm_state->get_Latitude() );
567 SG_LOG( SG_GENERAL, SG_BULK,
568 " sun_rot = " << l->get_sun_rotation
569 << " gst = " << SGTime::cur_time_params->getGst() );
570 SG_LOG( SG_GENERAL, SG_BULK,
571 " sun ra = " << globals->get_ephem()->getSunRightAscension()
572 << " sun dec = " << globals->get_ephem()->getSunDeclination()
573 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
574 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
577 // The sun and moon distances are scaled down versions
578 // of the actual distance to get both the moon and the sun
579 // within the range of the far clip plane.
580 // Moon distance: 384,467 kilometers
581 // Sun distance: 150,000,000 kilometers
582 double sun_horiz_eff, moon_horiz_eff;
583 if (fgGetBool("/sim/rendering/horizon-effect")) {
584 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
585 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
587 sun_horiz_eff = moon_horiz_eff = 1.0;
590 static SGSkyState sstate;
592 sstate.view_pos = current__view->get_view_pos();
593 sstate.zero_elev = current__view->get_zero_elev();
594 sstate.view_up = current__view->get_world_up();
595 sstate.lon = current__view->getLongitude_deg()
596 * SGD_DEGREES_TO_RADIANS;
597 sstate.lat = current__view->getLatitude_deg()
598 * SGD_DEGREES_TO_RADIANS;
599 sstate.alt = current__view->getAltitudeASL_ft()
601 sstate.spin = l->get_sun_rotation();
602 sstate.gst = globals->get_time_params()->getGst();
603 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
604 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
605 sstate.sun_dist = 50000.0 * sun_horiz_eff;
606 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
607 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
608 sstate.moon_dist = 40000.0 * moon_horiz_eff;
610 thesky->reposition( sstate, delta_time_sec );
613 glEnable( GL_DEPTH_TEST );
614 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
616 glFogi( GL_FOG_MODE, GL_EXP2 );
617 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
620 // set sun/lighting parameters
621 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
623 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
624 // we only update GL_AMBIENT for our lights we will never get
625 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
626 // explicitely to black.
627 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
629 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
630 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
631 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
633 // texture parameters
634 // glEnable( GL_TEXTURE_2D );
635 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
636 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
638 // glMatrixMode( GL_PROJECTION );
640 ssgSetFOV( current__view->get_h_fov(),
641 current__view->get_v_fov() );
644 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
645 - globals->get_scenery()->get_cur_elev();
648 scene_nearplane = 10.0f;
649 scene_farplane = 120000.0f;
651 scene_nearplane = groundlevel_nearplane->getDoubleValue();
652 scene_farplane = 120000.0f;
655 ssgSetNearFar( scene_nearplane, scene_farplane );
658 // Update any multiplayer models
659 globals->get_multiplayer_rx_mgr()->Update();
662 if ( draw_otw && skyblend ) {
663 // draw the sky backdrop
665 // we need a white diffuse light for the phase of the moon
666 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
667 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
669 // return to the desired diffuse color
670 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
673 // draw the ssg scene
674 glEnable( GL_DEPTH_TEST );
676 ssgSetNearFar( scene_nearplane, scene_farplane );
678 if ( fgGetBool("/sim/rendering/wireframe") ) {
680 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
686 FGTileMgr::set_tile_filter( true );
687 sgSetModelFilter( false );
688 globals->get_aircraft_model()->select( false );
689 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
691 // Disable depth buffer update, draw the clouds
692 glDepthMask( GL_FALSE );
693 thesky->drawUpperClouds();
694 if ( multi_pass_clouds ) {
695 thesky->drawLowerClouds();
697 glDepthMask( GL_TRUE );
699 if ( multi_pass_clouds ) {
700 // Draw the objects except the aircraft
701 // and update the stencil buffer with 1
702 glEnable( GL_STENCIL_TEST );
703 glStencilFunc( GL_ALWAYS, 1, 1 );
704 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
706 FGTileMgr::set_tile_filter( false );
707 sgSetModelFilter( true );
708 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
710 FGTileMgr::set_tile_filter( true );
711 sgSetModelFilter( true );
712 globals->get_aircraft_model()->select( false );
713 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
717 // This is a bit kludgy. Every 200 frames, do an extra
718 // traversal of the scene graph without drawing anything, but
719 // with the field-of-view set to 360x360 degrees. This
720 // ensures that out-of-range random objects that are not in
721 // the current view frustum will still be freed properly.
722 static int counter = 0;
724 if (counter == 200) {
727 // No need to put the near plane too close;
728 // this way, at least the aircraft can be
730 f.setNearFar(1000, 1000000);
732 ssgGetModelviewMatrix(m);
733 FGTileMgr::set_tile_filter( true );
734 sgSetModelFilter( true );
735 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
739 // change state for lighting here
741 // draw runway lighting
742 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
743 ssgSetNearFar( scene_nearplane, scene_farplane );
745 if ( enhanced_lighting ) {
747 // Enable states for drawing points with GL_extension
748 glEnable(GL_POINT_SMOOTH);
750 if ( distance_attenuation && glPointParameterIsSupported )
752 // Enable states for drawing points with GL_extension
753 glEnable(GL_POINT_SMOOTH);
755 float quadratic[3] = {1.0, 0.001, 0.0000001};
756 // makes the points fade as they move away
757 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
758 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
763 // blending function for runway lights
764 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
767 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
768 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
769 glEnable(GL_TEXTURE_GEN_S);
770 glEnable(GL_TEXTURE_GEN_T);
771 glPolygonMode(GL_FRONT, GL_POINT);
773 // draw runway lighting
775 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
776 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
779 // change punch through and then draw taxi lighting
780 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
782 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
783 // glFogfv ( GL_FOG_COLOR, taxi_fog );
785 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
789 glPolygonMode(GL_FRONT, GL_FILL);
790 glDisable(GL_TEXTURE_GEN_S);
791 glDisable(GL_TEXTURE_GEN_T);
793 //static int _frame_count = 0;
794 //if (_frame_count % 30 == 0) {
795 // printf("SSG: %s\n", ssgShowStats());
803 if ( enhanced_lighting ) {
804 if ( distance_attenuation && glPointParameterIsSupported ) {
805 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
806 default_attenuation);
810 glDisable(GL_POINT_SMOOTH);
813 // draw ground lighting
814 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
816 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
819 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
821 glDisable( GL_LIGHTING );
822 // cout << "drawing new clouds" << endl;
824 glEnable(GL_DEPTH_TEST);
826 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
829 glEnable( GL_TEXTURE_2D );
830 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
831 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
832 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
833 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
836 #ifdef FG_USE_CLOUDS_3D
837 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
840 glEnable( GL_LIGHTING );
841 glEnable( GL_DEPTH_TEST );
842 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
845 if ( draw_otw && draw_clouds ) {
846 if ( multi_pass_clouds ) {
847 // Disable depth buffer update, draw the clouds where the
848 // objects overwrite the already drawn clouds, by testing
849 // the stencil buffer against 1
850 glDepthMask( GL_FALSE );
851 glStencilFunc( GL_EQUAL, 1, 1 );
852 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
853 thesky->drawUpperClouds();
854 thesky->drawLowerClouds();
855 glDepthMask( GL_TRUE );
856 glDisable( GL_STENCIL_TEST );
858 glDepthMask( GL_FALSE );
859 thesky->drawLowerClouds();
860 glDepthMask( GL_TRUE );
865 FGTileMgr::set_tile_filter( false );
866 sgSetModelFilter( false );
867 globals->get_aircraft_model()->select( true );
868 globals->get_model_mgr()->draw();
869 globals->get_aircraft_model()->draw();
870 // If the view is internal, the previous line draw the
871 // cockpit with modified near/far clip planes and deselect
872 // the aircraft in the global scenegraph
873 // Otherwise, it just enables the aircraft: The scenegraph
874 // must be drawn again to see the plane.
875 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
876 FGTileMgr::set_tile_filter( true );
877 sgSetModelFilter( true );
878 globals->get_aircraft_model()->select( true );
881 // display HUD && Panel
883 glDisable( GL_DEPTH_TEST );
884 // glDisable( GL_CULL_FACE );
885 // glDisable( GL_TEXTURE_2D );
887 // update the controls subsystem
888 globals->get_controls()->update(delta_time_sec);
890 hud_and_panel->apply();
893 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
894 // This only works properly if called before the panel call
895 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
896 globals->get_ATC_display()->update(delta_time_sec);
898 // update the panel subsystem
899 if ( globals->get_current_panel() != NULL ) {
900 globals->get_current_panel()->update(delta_time_sec);
904 // We can do translucent menus, so why not. :-)
906 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
908 // glDisable ( GL_BLEND ) ;
910 glEnable( GL_DEPTH_TEST );
913 // Fade out the splash screen over the first three seconds.
914 double t = globals->get_sim_time_sec();
916 fgSplashUpdate(0.0, 1.0);
917 } else if ( t <= 3.0) {
918 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
924 // Update internal time dependent calculations (i.e. flight model)
925 // FIXME: this distinction is obsolete; all subsystems now get delta
927 void fgUpdateTimeDepCalcs() {
928 static bool inited = false;
930 static const SGPropertyNode *replay_master
931 = fgGetNode( "/sim/freeze/replay", true );
932 static SGPropertyNode *replay_time
933 = fgGetNode( "/sim/replay/time", true );
934 // static const SGPropertyNode *replay_end_time
935 // = fgGetNode( "/sim/replay/end-time", true );
937 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
939 // Initialize the FDM here if it hasn't been and if we have a
940 // scenery elevation hit.
942 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
943 // << " cur_elev = " << scenery.get_cur_elev() << endl;
945 if ( !cur_fdm_state->get_inited() &&
946 globals->get_scenery()->get_cur_elev() > -9990 )
948 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
949 cur_fdm_state->init();
950 if ( cur_fdm_state->get_bound() ) {
951 cur_fdm_state->unbind();
953 cur_fdm_state->bind();
956 // conceptually, the following block could be done for each fdm
958 if ( cur_fdm_state->get_inited() ) {
959 // we have been inited, and we are good to go ...
965 if ( ! replay_master->getBoolValue() ) {
966 cur_fdm_state->update( delta_time_sec );
968 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
969 r->replay( replay_time->getDoubleValue() );
970 replay_time->setDoubleValue( replay_time->getDoubleValue()
972 * fgGetInt("/sim/speed-up") ) );
975 // do nothing, fdm isn't inited yet
978 globals->get_model_mgr()->update(delta_time_sec);
979 globals->get_aircraft_model()->update(delta_time_sec);
981 // update the view angle
982 globals->get_viewmgr()->update(delta_time_sec);
984 // Update solar system
985 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
986 globals->get_time_params()->getLst(),
987 cur_fdm_state->get_Latitude() );
989 // Update radio stack model
990 current_radiostack->update(delta_time_sec);
994 void fgInitTimeDepCalcs( void ) {
999 static const double alt_adjust_ft = 3.758099;
1000 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1003 // What should we do when we have nothing else to do? Let's get ready
1004 // for the next move and update the display?
1005 static void fgMainLoop( void ) {
1006 int model_hz = fgGetInt("/sim/model-hz");
1008 static const SGPropertyNode *longitude
1009 = fgGetNode("/position/longitude-deg");
1010 static const SGPropertyNode *latitude
1011 = fgGetNode("/position/latitude-deg");
1012 static const SGPropertyNode *altitude
1013 = fgGetNode("/position/altitude-ft");
1014 static const SGPropertyNode *clock_freeze
1015 = fgGetNode("/sim/freeze/clock", true);
1016 static const SGPropertyNode *cur_time_override
1017 = fgGetNode("/sim/time/cur-time-override", true);
1018 // static const SGPropertyNode *replay_master
1019 // = fgGetNode("/sim/freeze/replay", true);
1021 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1023 // Update the elapsed time.
1024 static bool first_time = true;
1026 last_time_stamp.stamp();
1030 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1031 if ( throttle_hz > 0.0 ) {
1032 // simple frame rate throttle
1033 double dt = 1000000.0 / throttle_hz;
1034 current_time_stamp.stamp();
1035 while ( current_time_stamp - last_time_stamp < dt ) {
1036 current_time_stamp.stamp();
1039 // run as fast as the app will go
1040 current_time_stamp.stamp();
1044 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1045 if ( clock_freeze->getBoolValue() ) {
1048 delta_time_sec = real_delta_time_sec;
1050 last_time_stamp = current_time_stamp;
1051 globals->inc_sim_time_sec( delta_time_sec );
1052 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1054 // These are useful, especially for Nasal scripts.
1055 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1056 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1058 static long remainder = 0;
1060 #ifdef FANCY_FRAME_COUNTER
1064 static time_t last_time = 0;
1065 static int frames = 0;
1066 #endif // FANCY_FRAME_COUNTER
1068 SGTime *t = globals->get_time_params();
1070 globals->get_event_mgr()->update(delta_time_sec);
1072 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1073 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1075 #if defined( ENABLE_PLIB_JOYSTICK )
1076 // Read joystick and update control settings
1077 // if ( fgGetString("/sim/control-mode") == "joystick" )
1079 // fgJoystickRead();
1083 // Fix elevation. I'm just sticking this here for now, it should
1084 // probably move eventually
1086 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1087 scenery.get_cur_elev(),
1088 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1089 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1091 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1092 scenery.get_cur_elev(),
1093 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1094 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1096 // cout << "Warp = " << globals->get_warp() << endl;
1099 static bool last_clock_freeze = false;
1101 if ( clock_freeze->getBoolValue() ) {
1102 // clock freeze requested
1103 if ( cur_time_override->getLongValue() == 0 ) {
1104 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1105 globals->set_warp( 0 );
1108 // no clock freeze requested
1109 if ( last_clock_freeze == true ) {
1110 // clock just unfroze, let's set warp as the difference
1111 // between frozen time and current time so we don't get a
1112 // time jump (and corresponding sky object and lighting
1114 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1115 fgSetLong( "/sim/time/cur-time-override", 0 );
1117 if ( globals->get_warp_delta() != 0 ) {
1118 globals->inc_warp( globals->get_warp_delta() );
1122 last_clock_freeze = clock_freeze->getBoolValue();
1124 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1125 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1126 cur_time_override->getLongValue(),
1127 globals->get_warp() );
1129 if (globals->get_warp_delta() != 0) {
1130 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1134 // update magvar model
1135 globals->get_mag()->update( longitude->getDoubleValue()
1136 * SGD_DEGREES_TO_RADIANS,
1137 latitude->getDoubleValue()
1138 * SGD_DEGREES_TO_RADIANS,
1139 altitude->getDoubleValue() * SG_FEET_TO_METER,
1140 globals->get_time_params()->getJD() );
1142 // Get elapsed time (in usec) for this past frame
1143 elapsed = fgGetTimeInterval();
1144 SG_LOG( SG_ALL, SG_DEBUG,
1145 "Elapsed time interval is = " << elapsed
1146 << ", previous remainder is = " << remainder );
1148 // Calculate frame rate average
1149 #ifdef FANCY_FRAME_COUNTER
1150 /* old fps calculation */
1151 if ( elapsed > 0 ) {
1154 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1155 tmp = general.get_frame(i);
1157 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1158 general.set_frame(i+1,tmp);
1160 tmp = 1000000.0 / (float)elapsed;
1161 general.set_frame(0,tmp);
1162 // printf("frame[0] = %.2f\n", general.frames[0]);
1164 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1165 // printf("ave = %.2f\n", general.frame_rate);
1168 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1169 general.set_frame_rate( frames );
1170 fgSetInt("/sim/frame-rate", frames);
1171 SG_LOG( SG_ALL, SG_DEBUG,
1172 "--> Frame rate is = " << general.get_frame_rate() );
1175 last_time = t->get_cur_time();
1179 // Run ATC subsystem
1180 if (fgGetBool("/sim/ATC/enabled"))
1181 globals->get_ATC_mgr()->update(delta_time_sec);
1183 // Run the AI subsystem
1184 if (fgGetBool("/sim/ai-traffic/enabled"))
1185 globals->get_AI_mgr()->update(delta_time_sec);
1189 // Calculate model iterations needed for next frame
1190 elapsed += remainder;
1192 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1193 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1194 SG_LOG( SG_ALL, SG_DEBUG,
1195 "Model iterations needed = " << global_multi_loop
1196 << ", new remainder = " << remainder );
1198 // chop max interations to something reasonable if the sim was
1199 // delayed for an excesive amount of time
1200 if ( global_multi_loop > 2.0 * model_hz ) {
1201 global_multi_loop = (int)(2.0 * model_hz );
1206 if ( global_multi_loop > 0 ) {
1207 fgUpdateTimeDepCalcs();
1209 SG_LOG( SG_ALL, SG_DEBUG,
1210 "Elapsed time is zero ... we're zinging" );
1213 // Do any I/O channel work that might need to be done
1214 globals->get_io()->update( real_delta_time_sec );
1216 // see if we need to load any deferred-load textures
1217 globals->get_matlib()->load_next_deferred();
1219 // Run audio scheduler
1220 #ifdef ENABLE_AUDIO_SUPPORT
1221 if ( globals->get_soundmgr()->is_working() ) {
1222 globals->get_soundmgr()->update( delta_time_sec );
1226 globals->get_subsystem_mgr()->update(delta_time_sec);
1229 // Tile Manager updates - see if we need to load any new scenery tiles.
1230 // this code ties together the fdm, viewer and scenery classes...
1231 // we may want to move this to it's own class at some point
1233 double visibility_meters = fgGetDouble("/environment/visibility-m");
1234 FGViewer *current_view = globals->get_current_view();
1236 // get the location data for the primary FDM (now hardcoded to ac model)...
1237 SGLocation *acmodel_loc = NULL;
1238 acmodel_loc = (SGLocation *)globals->
1239 get_aircraft_model()->get3DModel()->getSGLocation();
1241 // update tile manager for FDM...
1242 // ...only if location is different than the current-view location
1243 // (to avoid duplicating effort)
1244 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1245 if( acmodel_loc != NULL ) {
1246 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1247 visibility_meters );
1248 globals->get_tile_mgr()->
1249 update( acmodel_loc, visibility_meters,
1251 get_absolute_view_pos(globals->
1252 get_scenery()->get_center()) );
1253 // save results of update in SGLocation for fdm...
1254 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1256 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1257 fgSetDouble("/position/ground-elev-m",
1258 globals->get_scenery()->get_cur_elev());
1261 set_tile_center( globals->get_scenery()->get_next_center() );
1265 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1266 visibility_meters );
1267 // update tile manager for view...
1268 // IMPORTANT!!! the tilemgr update for view location _must_ be
1269 // done last after the FDM's until all of Flight Gear code
1270 // references the viewer's location for elevation instead of the
1271 // "scenery's" current elevation.
1272 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1273 globals->get_tile_mgr()->update( view_location, visibility_meters,
1274 current_view->get_absolute_view_pos() );
1275 // save results of update in SGLocation for fdm...
1276 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1277 current_view->getSGLocation()->
1278 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1280 current_view->getSGLocation()->
1281 set_tile_center( globals->get_scenery()->get_next_center() );
1283 #ifdef ENABLE_AUDIO_SUPPORT
1284 // Right now we make a simplifying assumption that the primary
1285 // aircraft is the source of all sounds and that all sounds are
1286 // positioned relative to the current view position.
1288 static sgVec3 last_pos_offset;
1290 // set positional offset for sources
1291 sgVec3 source_pos_offset;
1292 sgSubVec3( source_pos_offset,
1293 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1294 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1295 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1299 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1300 sgScaleVec3( source_vel, delta_time_sec );
1301 sgCopyVec3( last_pos_offset, source_pos_offset );
1302 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1303 globals->get_soundmgr()->set_source_vel_all( source_vel );
1305 // Right now we make a simplifying assumption that the listener is
1306 // always positioned at the origin.
1307 sgVec3 listener_pos;
1308 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1309 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1310 globals->get_soundmgr()->set_listener_pos( listener_pos );
1313 // If fdm location is same as viewer's then we didn't do the
1314 // update for fdm location above so we need to save the viewer
1315 // results in the fdm SGLocation as well...
1316 if( fgGetBool("/sim/current-view/config/from-model") ) {
1317 if( acmodel_loc != 0 ) {
1318 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1319 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1321 fgSetDouble("/position/ground-elev-m",
1322 globals->get_scenery()->get_cur_elev());
1324 acmodel_loc->set_tile_center( globals->get_scenery()->
1325 get_next_center() );
1329 // END Tile Manager udpates
1331 if (fgGetBool("/sim/rendering/specular-highlight")) {
1332 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1333 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1335 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1336 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1341 SG_LOG( SG_ALL, SG_DEBUG, "" );
1345 // This is the top level master main function that is registered as
1346 // our idle funciton
1348 // The first few passes take care of initialization things (a couple
1349 // per pass) and once everything has been initialized fgMainLoop from
1352 static void fgIdleFunction ( void ) {
1353 // printf("idle state == %d\n", idle_state);
1355 if ( idle_state == 0 ) {
1356 fgSetBool("sim/initialised", false);
1358 // Initialize the splash screen right away
1359 if ( fgGetBool("/sim/startup/splash-screen") ) {
1360 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1364 } else if ( idle_state == 1 ) {
1365 // Initialize audio support
1366 #ifdef ENABLE_AUDIO_SUPPORT
1368 // Start the intro music
1369 if ( fgGetBool("/sim/startup/intro-music") ) {
1370 SGPath mp3file( globals->get_fg_root() );
1371 mp3file.append( "Sounds/intro.mp3" );
1373 SG_LOG( SG_GENERAL, SG_INFO,
1374 "Starting intro music: " << mp3file.str() );
1376 #if defined( __CYGWIN__ )
1377 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1378 #elif defined( WIN32 )
1379 string command = "start /m " + mp3file.str();
1381 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1384 system ( command.c_str() );
1389 } else if ( idle_state == 2 ) {
1390 // These are a few miscellaneous things that aren't really
1391 // "subsystems" but still need to be initialized.
1394 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1395 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1400 } else if ( idle_state == 3 ) {
1401 // This is the top level init routine which calls all the
1402 // other subsystem initialization routines. If you are adding
1403 // a subsystem to flightgear, its initialization call should
1404 // located in this routine.
1405 if( !fgInitSubsystems()) {
1406 SG_LOG( SG_GENERAL, SG_ALERT,
1407 "Subsystem initializations failed ..." );
1412 } else if ( idle_state == 4 ) {
1413 // Initialize the time offset (warp) after fgInitSubsystem
1414 // (which initializes the lighting interpolation tables.)
1417 // setup OpenGL view parameters
1420 // Read the list of available aircrafts
1424 } else if ( idle_state == 5 ) {
1427 } else if ( idle_state == 6 ) {
1432 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1433 fgReshape( fgGetInt("/sim/startup/xsize"),
1434 fgGetInt("/sim/startup/ysize") );
1438 if ( idle_state == 1000 ) {
1439 // We've finished all our initialization steps, from now on we
1440 // run the main loop.
1441 fgSetBool("sim/initialised",true);
1443 fgRegisterIdleHandler(fgMainLoop);
1445 if ( fgGetBool("/sim/startup/splash-screen") ) {
1446 fgSplashUpdate(0.0, 1.0);
1451 // options.cxx needs to see this for toggle_panel()
1452 // Handle new window size or exposure
1453 void fgReshape( int width, int height ) {
1456 if ( (!fgGetBool("/sim/virtual-cockpit"))
1457 && fgPanelVisible() && idle_state == 1000 ) {
1458 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1459 globals->get_current_panel()->getYOffset()) / 768.0);
1464 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1466 fgSetInt("/sim/startup/xsize", width);
1467 fgSetInt("/sim/startup/ysize", height);
1468 guiInitMouse(width, height);
1471 FGViewMgr *viewmgr = globals->get_viewmgr();
1473 for ( int i = 0; i < viewmgr->size(); ++i ) {
1474 viewmgr->get_view(i)->
1475 set_aspect_ratio((float)view_h / (float)width);
1478 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1479 viewmgr->get_current_view()->get_v_fov() );
1481 #ifdef FG_USE_CLOUDS_3D
1482 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1483 viewmgr->get_current_view()->get_v_fov() );
1492 // do some clean up on exit. Specifically we want to call alutExit()
1493 // which happens in the sound manager destructor.
1494 void fgExitCleanup() {
1500 // Main top level initialization
1501 bool fgMainInit( int argc, char **argv ) {
1503 #if defined( macintosh )
1504 freopen ("stdout.txt", "w", stdout );
1505 freopen ("stderr.txt", "w", stderr );
1506 argc = ccommand( &argv );
1509 // set default log levels
1510 sglog().setLogLevels( SG_ALL, SG_ALERT );
1512 atexit(fgExitCleanup);
1515 #ifdef FLIGHTGEAR_VERSION
1516 version = FLIGHTGEAR_VERSION;
1518 version = "unknown version";
1520 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1522 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1524 // Allocate global data structures. This needs to happen before
1525 // we parse command line options
1527 globals = new FGGlobals;
1529 // seed the random number generater
1532 FGControls *controls = new FGControls;
1533 globals->set_controls( controls );
1535 string_list *col = new string_list;
1536 globals->set_channel_options_list( col );
1538 // Scan the config file(s) and command line options to see if
1539 // fg_root was specified (ignore all other options for now)
1540 fgInitFGRoot(argc, argv);
1542 // Check for the correct base package version
1543 static char required_version[] = "0.9.4";
1544 string base_version = fgBasePackageVersion();
1545 if ( !(base_version == required_version) ) {
1546 // tell the operator how to use this application
1548 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1549 cerr << endl << "Base package check failed ... " \
1550 << "Found version " << base_version << " at: " \
1551 << globals->get_fg_root() << endl;
1552 cerr << "Please upgrade to version: " << required_version << endl;
1554 cerr << "Hit a key to continue..." << endl;
1560 // Initialize the Aircraft directory to "" (UIUC)
1563 // Load the configuration parameters. (Command line options
1564 // overrides config file options. Config file options override
1566 if ( !fgInitConfig(argc, argv) ) {
1567 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1571 // Initialize the Window/Graphics environment.
1572 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1573 // Mac OS X command line ("non-bundle") applications call this
1574 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1575 // feel free to add comments...
1576 fgOSInit(&argc, argv);
1579 fgRegisterWindowResizeHandler( fgReshape );
1580 fgRegisterIdleHandler( fgIdleFunction );
1581 fgRegisterDrawHandler( fgRenderFrame );
1583 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1584 bool get_stencil_buffer = true;
1586 bool get_stencil_buffer = false;
1589 // Clouds3D requires an alpha channel
1590 // clouds may require stencil buffer
1591 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1592 fgGetInt("/sim/startup/ysize"),
1593 fgGetInt("/sim/rendering/bits-per-pixel"),
1594 fgGetBool("/sim/rendering/clouds3d"),
1596 fgGetBool("/sim/startup/fullscreen") );
1598 // This seems to be the absolute earliest in the init sequence
1599 // that these calls will return valid info. Too bad it's after
1600 // we've already created and sized out window. :-(
1601 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1602 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1603 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1604 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1607 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1608 general.set_glMaxTexSize( tmp );
1609 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1611 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1612 general.set_glDepthBits( tmp );
1613 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1615 // Initialize plib net interface
1616 netInit( &argc, argv );
1618 // Initialize ssg (from plib). Needs to come before we do any
1619 // other ssg stuff, but after opengl has been initialized.
1622 // Initialize the user interface (we need to do this before
1623 // passing off control to the OS main loop and before
1624 // fgInitGeneral to get our fonts !!!
1627 // Read the list of available aircrafts
1630 #ifdef GL_EXT_texture_lod_bias
1631 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1634 // get the address of our OpenGL extensions
1635 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1637 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1638 glPointParameterIsSupported = true;
1639 glPointParameterfPtr = (glPointParameterfProc)
1640 SGLookupFunction("glPointParameterfEXT");
1641 glPointParameterfvPtr = (glPointParameterfvProc)
1642 SGLookupFunction("glPointParameterfvEXT");
1644 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1645 glPointParameterIsSupported = true;
1646 glPointParameterfPtr = (glPointParameterfProc)
1647 SGLookupFunction("glPointParameterfARB");
1648 glPointParameterfvPtr = (glPointParameterfvProc)
1649 SGLookupFunction("glPointParameterfvARB");
1651 glPointParameterIsSupported = false;
1654 // based on the requested presets, calculate the true starting
1659 SGTime *t = fgInitTime();
1660 globals->set_time_params( t );
1662 // Do some quick general initializations
1663 if( !fgInitGeneral()) {
1664 SG_LOG( SG_GENERAL, SG_ALERT,
1665 "General initializations failed ..." );
1669 ////////////////////////////////////////////////////////////////////
1670 // Initialize the property-based built-in commands
1671 ////////////////////////////////////////////////////////////////////
1674 ////////////////////////////////////////////////////////////////////
1675 // Initialize the material manager
1676 ////////////////////////////////////////////////////////////////////
1677 globals->set_matlib( new SGMaterialLib );
1679 globals->set_model_lib(new SGModelLib);
1681 ////////////////////////////////////////////////////////////////////
1682 // Initialize the TG scenery subsystem.
1683 ////////////////////////////////////////////////////////////////////
1684 globals->set_scenery( new FGScenery );
1685 globals->get_scenery()->init();
1686 globals->get_scenery()->bind();
1687 globals->set_tile_mgr( new FGTileMgr );
1689 ////////////////////////////////////////////////////////////////////
1690 // Initialize the general model subsystem.
1691 ////////////////////////////////////////////////////////////////////
1692 globals->set_model_mgr(new FGModelMgr);
1693 globals->get_model_mgr()->init();
1694 globals->get_model_mgr()->bind();
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the 3D aircraft model subsystem (has a dependency on
1698 // the scenery subsystem.)
1699 ////////////////////////////////////////////////////////////////////
1700 globals->set_aircraft_model(new FGAircraftModel);
1701 globals->get_aircraft_model()->init();
1702 globals->get_aircraft_model()->bind();
1704 ////////////////////////////////////////////////////////////////////
1705 // Initialize the view manager subsystem.
1706 ////////////////////////////////////////////////////////////////////
1707 FGViewMgr *viewmgr = new FGViewMgr;
1708 globals->set_viewmgr( viewmgr );
1713 // Initialize the sky
1714 SGPath ephem_data_path( globals->get_fg_root() );
1715 ephem_data_path.append( "Astro" );
1716 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1717 ephem->update( globals->get_time_params()->getMjd(),
1718 globals->get_time_params()->getLst(),
1720 globals->set_ephem( ephem );
1722 // TODO: move to environment mgr
1724 SGPath texture_path(globals->get_fg_root());
1725 texture_path.append("Textures");
1726 texture_path.append("Sky");
1727 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1728 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1729 thesky->add_cloud_layer(layer);
1732 SGPath sky_tex_path( globals->get_fg_root() );
1733 sky_tex_path.append( "Textures" );
1734 sky_tex_path.append( "Sky" );
1735 thesky->texture_path( sky_tex_path.str() );
1737 // The sun and moon diameters are scaled down numbers of the
1738 // actual diameters. This was needed to fit bot the sun and the
1739 // moon within the distance to the far clip plane.
1740 // Moon diameter: 3,476 kilometers
1741 // Sun diameter: 1,390,000 kilometers
1742 thesky->build( 80000.0, 80000.0,
1744 globals->get_ephem()->getNumPlanets(),
1745 globals->get_ephem()->getPlanets(),
1746 globals->get_ephem()->getNumStars(),
1747 globals->get_ephem()->getStars() );
1749 // Initialize MagVar model
1750 SGMagVar *magvar = new SGMagVar();
1751 globals->set_mag( magvar );
1754 // kludge to initialize mag compass
1755 // (should only be done for in-flight
1757 // update magvar model
1758 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1759 * SGD_DEGREES_TO_RADIANS,
1760 fgGetDouble("/position/latitude-deg")
1761 * SGD_DEGREES_TO_RADIANS,
1762 fgGetDouble("/position/altitude-ft")
1764 globals->get_time_params()->getJD() );
1765 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1766 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1768 // airport = new ssgBranch;
1769 // airport->setName( "Airport Lighting" );
1770 // lighting->addKid( airport );
1772 // build our custom render states
1773 fgBuildRenderStates();
1776 // pass control off to the master event handler
1779 SG_LOG( SG_ALL, SG_ALERT,
1780 "Unknown exception in the main loop. Aborting..." );
1783 // we never actually get here ... but to avoid compiler warnings,