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;
170 // The atexit() functio handler should know when the graphical subsystem
172 extern int _bootstrap_OSInit;
175 void fgBuildRenderStates( void ) {
176 default_state = new ssgSimpleState;
177 default_state->ref();
178 default_state->disable( GL_TEXTURE_2D );
179 default_state->enable( GL_CULL_FACE );
180 default_state->enable( GL_COLOR_MATERIAL );
181 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
182 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
183 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
184 default_state->disable( GL_BLEND );
185 default_state->disable( GL_ALPHA_TEST );
186 default_state->disable( GL_LIGHTING );
188 cloud3d_imposter_state = new ssgSimpleState;
189 cloud3d_imposter_state->ref();
190 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
191 cloud3d_imposter_state->enable( GL_CULL_FACE );
192 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
193 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
194 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
195 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
196 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
197 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
198 cloud3d_imposter_state->enable( GL_BLEND );
199 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
200 cloud3d_imposter_state->disable( GL_LIGHTING );
202 hud_and_panel = new ssgSimpleState;
203 hud_and_panel->ref();
204 hud_and_panel->disable( GL_CULL_FACE );
205 hud_and_panel->disable( GL_TEXTURE_2D );
206 hud_and_panel->disable( GL_LIGHTING );
207 hud_and_panel->enable( GL_BLEND );
209 menus = new ssgSimpleState;
211 menus->disable( GL_CULL_FACE );
212 menus->disable( GL_TEXTURE_2D );
213 menus->enable( GL_BLEND );
217 // fgInitVisuals() -- Initialize various GL/view parameters
218 void fgInitVisuals( void ) {
220 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
222 // Go full screen if requested ...
223 if ( fgGetBool("/sim/startup/fullscreen") ) {
227 // If enabled, normal vectors specified with glNormal are scaled
228 // to unit length after transformation. Enabling this has
229 // performance implications. See the docs for glNormal.
230 // glEnable( GL_NORMALIZE );
232 glEnable( GL_LIGHTING );
233 glEnable( GL_LIGHT0 );
234 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
237 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
238 ssgGetLight( 0 ) -> setPosition( sunpos );
240 glFogi (GL_FOG_MODE, GL_EXP2);
241 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
242 (!fgGetBool("/sim/rendering/shading"))) {
243 // if fastest fog requested, or if flat shading force fastest
244 glHint ( GL_FOG_HINT, GL_FASTEST );
245 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
246 glHint ( GL_FOG_HINT, GL_NICEST );
248 if ( fgGetBool("/sim/rendering/wireframe") ) {
250 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
253 // This is the default anyways, but it can't hurt
254 glFrontFace ( GL_CCW );
257 // glEnable(GL_POINT_SMOOTH);
258 // glEnable(GL_LINE_SMOOTH);
259 // glEnable(GL_POLYGON_SMOOTH);
263 // For HiRes screen Dumps using Brian Pauls TR Library
264 void trRenderFrame( void ) {
265 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
266 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
267 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
269 bool multi_pass_clouds = false;
271 bool draw_clouds = fgGetBool("/environment/clouds/status");
273 if ( fgPanelVisible() ) {
274 GLfloat height = fgGetInt("/sim/startup/ysize");
276 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
277 * (height / 768.0) + 1;
278 glTranslatef( 0.0, view_h, 0.0 );
281 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
282 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
284 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
286 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
287 l->adj_fog_color()[2], l->adj_fog_color()[3]);
289 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
291 // set the opengl state to known default values
292 default_state->force();
295 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
296 glFogi ( GL_FOG_MODE, GL_EXP2 );
297 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
299 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
300 // we only update GL_AMBIENT for our lights we will never get
301 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
302 // explicitely to black.
303 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
304 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
306 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
308 // texture parameters
309 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
310 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
312 // we need a white diffuse light for the phase of the moon
313 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
314 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
317 // draw the ssg scene
318 // return to the desired diffuse color
319 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
320 glEnable( GL_DEPTH_TEST );
321 ssgSetNearFar( scene_nearplane, scene_farplane );
324 FGTileMgr::set_tile_filter( true );
325 sgSetModelFilter( false );
326 globals->get_aircraft_model()->select( false );
327 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
328 // Disable depth buffer update, draw the clouds
329 glDepthMask( GL_FALSE );
330 thesky->drawUpperClouds();
331 if ( multi_pass_clouds ) {
332 thesky->drawLowerClouds();
334 glDepthMask( GL_TRUE );
335 if ( multi_pass_clouds ) {
336 // Draw the objects except the aircraft
337 // and update the stencil buffer with 1
338 glEnable( GL_STENCIL_TEST );
339 glStencilFunc( GL_ALWAYS, 1, 1 );
340 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
342 FGTileMgr::set_tile_filter( false );
343 sgSetModelFilter( true );
344 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
346 FGTileMgr::set_tile_filter( true );
347 sgSetModelFilter( true );
348 globals->get_aircraft_model()->select( false );
349 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
353 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
354 ssgSetNearFar( scene_nearplane, scene_farplane );
355 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
356 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
358 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
361 if ( multi_pass_clouds ) {
362 // Disable depth buffer update, draw the clouds where the
363 // objects overwrite the already drawn clouds, by testing
364 // the stencil buffer against 1
365 glDepthMask( GL_FALSE );
366 glStencilFunc( GL_EQUAL, 1, 1 );
367 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
368 thesky->drawUpperClouds();
369 thesky->drawLowerClouds();
370 glDepthMask( GL_TRUE );
371 glDisable( GL_STENCIL_TEST );
373 glDepthMask( GL_FALSE );
374 thesky->drawLowerClouds();
375 glDepthMask( GL_TRUE );
379 globals->get_aircraft_model()->select( true );
380 globals->get_model_mgr()->draw();
381 globals->get_aircraft_model()->draw();
385 // Update all Visuals (redraws anything graphics related)
386 void fgRenderFrame() {
387 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
388 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
389 bool skyblend = fgGetBool("/sim/rendering/skyblend");
390 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
391 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
392 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
393 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
394 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
396 bool multi_pass_clouds = false;
398 bool draw_clouds = fgGetBool("/environment/clouds/status");
400 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
401 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
403 // static const SGPropertyNode *longitude
404 // = fgGetNode("/position/longitude-deg");
405 // static const SGPropertyNode *latitude
406 // = fgGetNode("/position/latitude-deg");
407 // static const SGPropertyNode *altitude
408 // = fgGetNode("/position/altitude-ft");
409 static const SGPropertyNode *groundlevel_nearplane
410 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
412 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
413 static double last_visibility = -9999;
416 double actual_visibility;
417 if (fgGetBool("/environment/clouds/status"))
418 actual_visibility = thesky->get_visibility();
420 actual_visibility = fgGetDouble("/environment/visibility-m");
421 if ( actual_visibility != last_visibility ) {
422 last_visibility = actual_visibility;
424 fog_exp_density = m_log01 / actual_visibility;
425 fog_exp2_density = sqrt_m_log01 / actual_visibility;
426 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
427 if ( actual_visibility < 8000 ) {
428 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
429 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
431 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
432 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
437 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
438 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
439 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
440 // GLfloat mat_shininess[] = { 10.0 };
441 GLbitfield clear_mask;
443 if ( idle_state != 1000 || !scenery_loaded ) {
444 // still initializing, draw the splash screen
445 if ( fgGetBool("/sim/startup/splash-screen") ) {
446 fgSplashUpdate(0.0, 1.0);
448 // Keep resetting sim time while the sim is initializing
449 globals->set_sim_time_sec( 0.0 );
450 SGAnimation::set_sim_time_sec( 0.0 );
452 // idle_state is now 1000 meaning we've finished all our
453 // initializations and are running the main loop, so this will
454 // now work without seg faulting the system.
456 FGViewer *current__view = globals->get_current_view();
458 // calculate our current position in cartesian space
459 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
462 fgReshape( fgGetInt("/sim/startup/xsize"),
463 fgGetInt("/sim/startup/ysize") );
465 if ( fgGetBool("/sim/rendering/clouds3d") ) {
466 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
467 cloud3d_imposter_state->force();
469 glColor4f( 1.0, 1.0, 1.0, 1.0 );
470 glEnable(GL_DEPTH_TEST);
472 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
474 #ifdef FG_USE_CLOUDS_3D
475 if ( _bcloud_orig ) {
476 Point3D c = globals->get_scenery()->get_center();
477 sgClouds3d->Set_Cloud_Orig( &c );
478 _bcloud_orig = false;
480 sgClouds3d->Update( current__view->get_absolute_view_pos() );
482 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
483 glDisable(GL_DEPTH_TEST);
486 clear_mask = GL_DEPTH_BUFFER_BIT;
487 if ( fgGetBool("/sim/rendering/wireframe") ) {
488 clear_mask |= GL_COLOR_BUFFER_BIT;
492 if ( fgGetBool("/sim/rendering/textures") ) {
493 // glClearColor(black[0], black[1], black[2], black[3]);
494 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
495 l->adj_fog_color()[2], l->adj_fog_color()[3]);
496 clear_mask |= GL_COLOR_BUFFER_BIT;
499 glClearColor(l->sky_color()[0], l->sky_color()[1],
500 l->sky_color()[2], l->sky_color()[3]);
501 clear_mask |= GL_COLOR_BUFFER_BIT;
503 if ( multi_pass_clouds && draw_clouds ) {
505 clear_mask |= GL_STENCIL_BUFFER_BIT;
507 glClear( clear_mask );
509 // Tell GL we are switching to model view parameters
511 // I really should create a derived ssg node or use a call
512 // back or something so that I can draw the sky within the
513 // ssgCullAndDraw() function, but for now I just mimic what
514 // ssg does to set up the model view matrix
515 glMatrixMode(GL_MODELVIEW);
517 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
519 // set the opengl state to known default values
520 default_state->force();
522 // update fog params if visibility has changed
523 double visibility_meters = fgGetDouble("/environment/visibility-m");
524 thesky->set_visibility(visibility_meters);
526 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
527 ( global_multi_loop * fgGetInt("/sim/speed-up") )
528 / (double)fgGetInt("/sim/model-hz") );
530 // Set correct opengl fog density
531 glFogf (GL_FOG_DENSITY, fog_exp2_density);
533 // update the sky dome
536 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
537 << l->sky_color()[0] << " "
538 << l->sky_color()[1] << " "
539 << l->sky_color()[2] << " "
540 << l->sky_color()[3] );
541 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
542 << l->fog_color()[0] << " "
543 << l->fog_color()[1] << " "
544 << l->fog_color()[2] << " "
545 << l->fog_color()[3] );
546 SG_LOG( SG_GENERAL, SG_BULK,
547 " sun_angle = " << l->sun_angle
548 << " moon_angle = " << l->moon_angle );
551 static SGSkyColor scolor;
552 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
554 scolor.sky_color = l->sky_color();
555 scolor.fog_color = l->adj_fog_color();
556 scolor.cloud_color = l->cloud_color();
557 scolor.sun_angle = l->get_sun_angle();
558 scolor.moon_angle = l->get_moon_angle();
559 scolor.nplanets = globals->get_ephem()->getNumPlanets();
560 scolor.nstars = globals->get_ephem()->getNumStars();
561 scolor.planet_data = globals->get_ephem()->getPlanets();
562 scolor.star_data = globals->get_ephem()->getStars();
564 thesky->repaint( scolor );
567 SG_LOG( SG_GENERAL, SG_BULK,
568 "thesky->reposition( view_pos = " << view_pos[0] << " "
569 << view_pos[1] << " " << view_pos[2] );
570 SG_LOG( SG_GENERAL, SG_BULK,
571 " zero_elev = " << zero_elev[0] << " "
572 << zero_elev[1] << " " << zero_elev[2]
573 << " lon = " << cur_fdm_state->get_Longitude()
574 << " lat = " << cur_fdm_state->get_Latitude() );
575 SG_LOG( SG_GENERAL, SG_BULK,
576 " sun_rot = " << l->get_sun_rotation
577 << " gst = " << SGTime::cur_time_params->getGst() );
578 SG_LOG( SG_GENERAL, SG_BULK,
579 " sun ra = " << globals->get_ephem()->getSunRightAscension()
580 << " sun dec = " << globals->get_ephem()->getSunDeclination()
581 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
582 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
585 // The sun and moon distances are scaled down versions
586 // of the actual distance to get both the moon and the sun
587 // within the range of the far clip plane.
588 // Moon distance: 384,467 kilometers
589 // Sun distance: 150,000,000 kilometers
590 double sun_horiz_eff, moon_horiz_eff;
591 if (fgGetBool("/sim/rendering/horizon-effect")) {
592 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
593 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
595 sun_horiz_eff = moon_horiz_eff = 1.0;
598 static SGSkyState sstate;
600 sstate.view_pos = current__view->get_view_pos();
601 sstate.zero_elev = current__view->get_zero_elev();
602 sstate.view_up = current__view->get_world_up();
603 sstate.lon = current__view->getLongitude_deg()
604 * SGD_DEGREES_TO_RADIANS;
605 sstate.lat = current__view->getLatitude_deg()
606 * SGD_DEGREES_TO_RADIANS;
607 sstate.alt = current__view->getAltitudeASL_ft()
609 sstate.spin = l->get_sun_rotation();
610 sstate.gst = globals->get_time_params()->getGst();
611 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
612 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
613 sstate.sun_dist = 50000.0 * sun_horiz_eff;
614 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
615 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
616 sstate.moon_dist = 40000.0 * moon_horiz_eff;
618 thesky->reposition( sstate, delta_time_sec );
621 glEnable( GL_DEPTH_TEST );
622 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
624 glFogi( GL_FOG_MODE, GL_EXP2 );
625 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
628 // set sun/lighting parameters
629 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
631 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
632 // we only update GL_AMBIENT for our lights we will never get
633 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
634 // explicitely to black.
635 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
637 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
638 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
639 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
641 // texture parameters
642 // glEnable( GL_TEXTURE_2D );
643 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
644 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
646 // glMatrixMode( GL_PROJECTION );
648 ssgSetFOV( current__view->get_h_fov(),
649 current__view->get_v_fov() );
652 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
653 - globals->get_scenery()->get_cur_elev();
656 scene_nearplane = 10.0f;
657 scene_farplane = 120000.0f;
659 scene_nearplane = groundlevel_nearplane->getDoubleValue();
660 scene_farplane = 120000.0f;
663 ssgSetNearFar( scene_nearplane, scene_farplane );
666 // Update any multiplayer models
667 globals->get_multiplayer_rx_mgr()->Update();
670 if ( draw_otw && skyblend ) {
671 // draw the sky backdrop
673 // we need a white diffuse light for the phase of the moon
674 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
675 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
677 // return to the desired diffuse color
678 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
681 // draw the ssg scene
682 glEnable( GL_DEPTH_TEST );
684 ssgSetNearFar( scene_nearplane, scene_farplane );
686 if ( fgGetBool("/sim/rendering/wireframe") ) {
688 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
694 FGTileMgr::set_tile_filter( true );
695 sgSetModelFilter( false );
696 globals->get_aircraft_model()->select( false );
697 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
699 // Disable depth buffer update, draw the clouds
700 glDepthMask( GL_FALSE );
701 thesky->drawUpperClouds();
702 if ( multi_pass_clouds ) {
703 thesky->drawLowerClouds();
705 glDepthMask( GL_TRUE );
707 if ( multi_pass_clouds ) {
708 // Draw the objects except the aircraft
709 // and update the stencil buffer with 1
710 glEnable( GL_STENCIL_TEST );
711 glStencilFunc( GL_ALWAYS, 1, 1 );
712 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
714 FGTileMgr::set_tile_filter( false );
715 sgSetModelFilter( true );
716 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
718 FGTileMgr::set_tile_filter( true );
719 sgSetModelFilter( true );
720 globals->get_aircraft_model()->select( false );
721 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
725 // This is a bit kludgy. Every 200 frames, do an extra
726 // traversal of the scene graph without drawing anything, but
727 // with the field-of-view set to 360x360 degrees. This
728 // ensures that out-of-range random objects that are not in
729 // the current view frustum will still be freed properly.
730 static int counter = 0;
732 if (counter == 200) {
735 // No need to put the near plane too close;
736 // this way, at least the aircraft can be
738 f.setNearFar(1000, 1000000);
740 ssgGetModelviewMatrix(m);
741 FGTileMgr::set_tile_filter( true );
742 sgSetModelFilter( true );
743 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
747 // change state for lighting here
749 // draw runway lighting
750 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
751 ssgSetNearFar( scene_nearplane, scene_farplane );
753 if ( enhanced_lighting ) {
755 // Enable states for drawing points with GL_extension
756 glEnable(GL_POINT_SMOOTH);
758 if ( distance_attenuation && glPointParameterIsSupported )
760 // Enable states for drawing points with GL_extension
761 glEnable(GL_POINT_SMOOTH);
763 float quadratic[3] = {1.0, 0.001, 0.0000001};
764 // makes the points fade as they move away
765 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
766 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
771 // blending function for runway lights
772 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
775 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
776 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
777 glEnable(GL_TEXTURE_GEN_S);
778 glEnable(GL_TEXTURE_GEN_T);
779 glPolygonMode(GL_FRONT, GL_POINT);
781 // draw runway lighting
783 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
784 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
787 // change punch through and then draw taxi lighting
788 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
790 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
791 // glFogfv ( GL_FOG_COLOR, taxi_fog );
793 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
797 glPolygonMode(GL_FRONT, GL_FILL);
798 glDisable(GL_TEXTURE_GEN_S);
799 glDisable(GL_TEXTURE_GEN_T);
801 //static int _frame_count = 0;
802 //if (_frame_count % 30 == 0) {
803 // printf("SSG: %s\n", ssgShowStats());
811 if ( enhanced_lighting ) {
812 if ( distance_attenuation && glPointParameterIsSupported ) {
813 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
814 default_attenuation);
818 glDisable(GL_POINT_SMOOTH);
821 // draw ground lighting
822 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
824 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
827 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
829 glDisable( GL_LIGHTING );
830 // cout << "drawing new clouds" << endl;
832 glEnable(GL_DEPTH_TEST);
834 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
837 glEnable( GL_TEXTURE_2D );
838 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
839 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
840 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
841 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
844 #ifdef FG_USE_CLOUDS_3D
845 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
848 glEnable( GL_LIGHTING );
849 glEnable( GL_DEPTH_TEST );
850 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
853 if ( draw_otw && draw_clouds ) {
854 if ( multi_pass_clouds ) {
855 // Disable depth buffer update, draw the clouds where the
856 // objects overwrite the already drawn clouds, by testing
857 // the stencil buffer against 1
858 glDepthMask( GL_FALSE );
859 glStencilFunc( GL_EQUAL, 1, 1 );
860 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
861 thesky->drawUpperClouds();
862 thesky->drawLowerClouds();
863 glDepthMask( GL_TRUE );
864 glDisable( GL_STENCIL_TEST );
866 glDepthMask( GL_FALSE );
867 thesky->drawLowerClouds();
868 glDepthMask( GL_TRUE );
873 FGTileMgr::set_tile_filter( false );
874 sgSetModelFilter( false );
875 globals->get_aircraft_model()->select( true );
876 globals->get_model_mgr()->draw();
877 globals->get_aircraft_model()->draw();
878 // If the view is internal, the previous line draw the
879 // cockpit with modified near/far clip planes and deselect
880 // the aircraft in the global scenegraph
881 // Otherwise, it just enables the aircraft: The scenegraph
882 // must be drawn again to see the plane.
883 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
884 FGTileMgr::set_tile_filter( true );
885 sgSetModelFilter( true );
886 globals->get_aircraft_model()->select( true );
889 // display HUD && Panel
891 glDisable( GL_DEPTH_TEST );
892 // glDisable( GL_CULL_FACE );
893 // glDisable( GL_TEXTURE_2D );
895 // update the controls subsystem
896 globals->get_controls()->update(delta_time_sec);
898 hud_and_panel->apply();
901 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
902 // This only works properly if called before the panel call
903 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
904 globals->get_ATC_display()->update(delta_time_sec);
906 // update the panel subsystem
907 if ( globals->get_current_panel() != NULL ) {
908 globals->get_current_panel()->update(delta_time_sec);
912 // We can do translucent menus, so why not. :-)
914 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
916 // glDisable ( GL_BLEND ) ;
918 glEnable( GL_DEPTH_TEST );
921 // Fade out the splash screen over the first three seconds.
922 double t = globals->get_sim_time_sec();
924 fgSplashUpdate(0.0, 1.0);
925 } else if ( t <= 3.0) {
926 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
932 // Update internal time dependent calculations (i.e. flight model)
933 // FIXME: this distinction is obsolete; all subsystems now get delta
935 void fgUpdateTimeDepCalcs() {
936 static bool inited = false;
938 static const SGPropertyNode *replay_master
939 = fgGetNode( "/sim/freeze/replay", true );
940 static SGPropertyNode *replay_time
941 = fgGetNode( "/sim/replay/time", true );
942 // static const SGPropertyNode *replay_end_time
943 // = fgGetNode( "/sim/replay/end-time", true );
945 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
947 // Initialize the FDM here if it hasn't been and if we have a
948 // scenery elevation hit.
950 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
951 // << " cur_elev = " << scenery.get_cur_elev() << endl;
953 if ( !cur_fdm_state->get_inited() &&
954 globals->get_scenery()->get_cur_elev() > -9990 )
956 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
957 cur_fdm_state->init();
958 if ( cur_fdm_state->get_bound() ) {
959 cur_fdm_state->unbind();
961 cur_fdm_state->bind();
964 // conceptually, the following block could be done for each fdm
966 if ( cur_fdm_state->get_inited() ) {
967 // we have been inited, and we are good to go ...
973 if ( ! replay_master->getBoolValue() ) {
974 cur_fdm_state->update( delta_time_sec );
976 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
977 r->replay( replay_time->getDoubleValue() );
978 replay_time->setDoubleValue( replay_time->getDoubleValue()
980 * fgGetInt("/sim/speed-up") ) );
983 // do nothing, fdm isn't inited yet
986 globals->get_model_mgr()->update(delta_time_sec);
987 globals->get_aircraft_model()->update(delta_time_sec);
989 // update the view angle
990 globals->get_viewmgr()->update(delta_time_sec);
992 // Update solar system
993 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
994 globals->get_time_params()->getLst(),
995 cur_fdm_state->get_Latitude() );
997 // Update radio stack model
998 current_radiostack->update(delta_time_sec);
1002 void fgInitTimeDepCalcs( void ) {
1007 static const double alt_adjust_ft = 3.758099;
1008 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1011 // What should we do when we have nothing else to do? Let's get ready
1012 // for the next move and update the display?
1013 static void fgMainLoop( void ) {
1014 int model_hz = fgGetInt("/sim/model-hz");
1016 static const SGPropertyNode *longitude
1017 = fgGetNode("/position/longitude-deg");
1018 static const SGPropertyNode *latitude
1019 = fgGetNode("/position/latitude-deg");
1020 static const SGPropertyNode *altitude
1021 = fgGetNode("/position/altitude-ft");
1022 static const SGPropertyNode *clock_freeze
1023 = fgGetNode("/sim/freeze/clock", true);
1024 static const SGPropertyNode *cur_time_override
1025 = fgGetNode("/sim/time/cur-time-override", true);
1026 // static const SGPropertyNode *replay_master
1027 // = fgGetNode("/sim/freeze/replay", true);
1029 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1031 // Update the elapsed time.
1032 static bool first_time = true;
1034 last_time_stamp.stamp();
1038 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1039 if ( throttle_hz > 0.0 ) {
1040 // simple frame rate throttle
1041 double dt = 1000000.0 / throttle_hz;
1042 current_time_stamp.stamp();
1043 while ( current_time_stamp - last_time_stamp < dt ) {
1044 current_time_stamp.stamp();
1047 // run as fast as the app will go
1048 current_time_stamp.stamp();
1052 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1053 if ( clock_freeze->getBoolValue() ) {
1056 delta_time_sec = real_delta_time_sec;
1058 last_time_stamp = current_time_stamp;
1059 globals->inc_sim_time_sec( delta_time_sec );
1060 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1062 // These are useful, especially for Nasal scripts.
1063 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1064 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1066 static long remainder = 0;
1068 #ifdef FANCY_FRAME_COUNTER
1072 static time_t last_time = 0;
1073 static int frames = 0;
1074 #endif // FANCY_FRAME_COUNTER
1076 SGTime *t = globals->get_time_params();
1078 globals->get_event_mgr()->update(delta_time_sec);
1080 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1081 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1083 #if defined( ENABLE_PLIB_JOYSTICK )
1084 // Read joystick and update control settings
1085 // if ( fgGetString("/sim/control-mode") == "joystick" )
1087 // fgJoystickRead();
1091 // Fix elevation. I'm just sticking this here for now, it should
1092 // probably move eventually
1094 /* printf("Before - 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 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1100 scenery.get_cur_elev(),
1101 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1102 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1104 // cout << "Warp = " << globals->get_warp() << endl;
1107 static bool last_clock_freeze = false;
1109 if ( clock_freeze->getBoolValue() ) {
1110 // clock freeze requested
1111 if ( cur_time_override->getLongValue() == 0 ) {
1112 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1113 globals->set_warp( 0 );
1116 // no clock freeze requested
1117 if ( last_clock_freeze == true ) {
1118 // clock just unfroze, let's set warp as the difference
1119 // between frozen time and current time so we don't get a
1120 // time jump (and corresponding sky object and lighting
1122 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1123 fgSetLong( "/sim/time/cur-time-override", 0 );
1125 if ( globals->get_warp_delta() != 0 ) {
1126 globals->inc_warp( globals->get_warp_delta() );
1130 last_clock_freeze = clock_freeze->getBoolValue();
1132 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1133 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1134 cur_time_override->getLongValue(),
1135 globals->get_warp() );
1137 if (globals->get_warp_delta() != 0) {
1138 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1142 // update magvar model
1143 globals->get_mag()->update( longitude->getDoubleValue()
1144 * SGD_DEGREES_TO_RADIANS,
1145 latitude->getDoubleValue()
1146 * SGD_DEGREES_TO_RADIANS,
1147 altitude->getDoubleValue() * SG_FEET_TO_METER,
1148 globals->get_time_params()->getJD() );
1150 // Get elapsed time (in usec) for this past frame
1151 elapsed = fgGetTimeInterval();
1152 SG_LOG( SG_ALL, SG_DEBUG,
1153 "Elapsed time interval is = " << elapsed
1154 << ", previous remainder is = " << remainder );
1156 // Calculate frame rate average
1157 #ifdef FANCY_FRAME_COUNTER
1158 /* old fps calculation */
1159 if ( elapsed > 0 ) {
1162 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1163 tmp = general.get_frame(i);
1165 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1166 general.set_frame(i+1,tmp);
1168 tmp = 1000000.0 / (float)elapsed;
1169 general.set_frame(0,tmp);
1170 // printf("frame[0] = %.2f\n", general.frames[0]);
1172 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1173 // printf("ave = %.2f\n", general.frame_rate);
1176 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1177 general.set_frame_rate( frames );
1178 fgSetInt("/sim/frame-rate", frames);
1179 SG_LOG( SG_ALL, SG_DEBUG,
1180 "--> Frame rate is = " << general.get_frame_rate() );
1183 last_time = t->get_cur_time();
1187 // Run ATC subsystem
1188 if (fgGetBool("/sim/ATC/enabled"))
1189 globals->get_ATC_mgr()->update(delta_time_sec);
1191 // Run the AI subsystem
1192 if (fgGetBool("/sim/ai-traffic/enabled"))
1193 globals->get_AI_mgr()->update(delta_time_sec);
1197 // Calculate model iterations needed for next frame
1198 elapsed += remainder;
1200 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1201 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1202 SG_LOG( SG_ALL, SG_DEBUG,
1203 "Model iterations needed = " << global_multi_loop
1204 << ", new remainder = " << remainder );
1206 // chop max interations to something reasonable if the sim was
1207 // delayed for an excesive amount of time
1208 if ( global_multi_loop > 2.0 * model_hz ) {
1209 global_multi_loop = (int)(2.0 * model_hz );
1213 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
1216 if ( global_multi_loop > 0) {
1217 // first run the flight model each frame until it is intialized
1218 // then continue running each frame only after initial scenery load is complete.
1219 if (!cur_fdm_state->get_inited() || scenery_loaded) {
1220 fgUpdateTimeDepCalcs();
1223 SG_LOG( SG_ALL, SG_DEBUG,
1224 "Elapsed time is zero ... we're zinging" );
1227 // Do any I/O channel work that might need to be done
1228 globals->get_io()->update( real_delta_time_sec );
1230 // see if we need to load any deferred-load textures
1231 globals->get_matlib()->load_next_deferred();
1233 // Run audio scheduler
1234 #ifdef ENABLE_AUDIO_SUPPORT
1235 if ( globals->get_soundmgr()->is_working() ) {
1236 globals->get_soundmgr()->update( delta_time_sec );
1240 globals->get_subsystem_mgr()->update(delta_time_sec);
1243 // Tile Manager updates - see if we need to load any new scenery tiles.
1244 // this code ties together the fdm, viewer and scenery classes...
1245 // we may want to move this to it's own class at some point
1247 double visibility_meters = fgGetDouble("/environment/visibility-m");
1248 FGViewer *current_view = globals->get_current_view();
1250 // get the location data for the primary FDM (now hardcoded to ac model)...
1251 SGLocation *acmodel_loc = NULL;
1252 acmodel_loc = (SGLocation *)globals->
1253 get_aircraft_model()->get3DModel()->getSGLocation();
1255 // update tile manager for FDM...
1256 // ...only if location is different than the current-view location
1257 // (to avoid duplicating effort)
1258 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1259 if( acmodel_loc != NULL ) {
1260 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1261 visibility_meters );
1262 globals->get_tile_mgr()->
1263 update( acmodel_loc, visibility_meters,
1265 get_absolute_view_pos(globals->
1266 get_scenery()->get_center()) );
1267 // save results of update in SGLocation for fdm...
1268 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1270 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1271 fgSetDouble("/position/ground-elev-m",
1272 globals->get_scenery()->get_cur_elev());
1275 set_tile_center( globals->get_scenery()->get_next_center() );
1279 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1280 visibility_meters );
1281 // update tile manager for view...
1282 // IMPORTANT!!! the tilemgr update for view location _must_ be
1283 // done last after the FDM's until all of Flight Gear code
1284 // references the viewer's location for elevation instead of the
1285 // "scenery's" current elevation.
1286 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1287 globals->get_tile_mgr()->update( view_location, visibility_meters,
1288 current_view->get_absolute_view_pos() );
1289 // save results of update in SGLocation for fdm...
1290 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1291 current_view->getSGLocation()->
1292 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1294 current_view->getSGLocation()->
1295 set_tile_center( globals->get_scenery()->get_next_center() );
1297 #ifdef ENABLE_AUDIO_SUPPORT
1298 // Right now we make a simplifying assumption that the primary
1299 // aircraft is the source of all sounds and that all sounds are
1300 // positioned relative to the current view position.
1302 static sgVec3 last_pos_offset;
1304 // set positional offset for sources
1305 sgVec3 source_pos_offset;
1306 sgSubVec3( source_pos_offset,
1307 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1308 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1309 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1313 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1314 sgScaleVec3( source_vel, delta_time_sec );
1315 sgCopyVec3( last_pos_offset, source_pos_offset );
1316 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1317 globals->get_soundmgr()->set_source_vel_all( source_vel );
1319 // Right now we make a simplifying assumption that the listener is
1320 // always positioned at the origin.
1321 sgVec3 listener_pos;
1322 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1323 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1324 globals->get_soundmgr()->set_listener_pos( listener_pos );
1327 // If fdm location is same as viewer's then we didn't do the
1328 // update for fdm location above so we need to save the viewer
1329 // results in the fdm SGLocation as well...
1330 if( fgGetBool("/sim/current-view/config/from-model") ) {
1331 if( acmodel_loc != 0 ) {
1332 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1333 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1335 fgSetDouble("/position/ground-elev-m",
1336 globals->get_scenery()->get_cur_elev());
1338 acmodel_loc->set_tile_center( globals->get_scenery()->
1339 get_next_center() );
1343 // END Tile Manager udpates
1345 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
1346 fgSetBool("sim/sceneryloaded",true);
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 // Main top level initialization
1512 bool fgMainInit( int argc, char **argv ) {
1514 #if defined( macintosh )
1515 freopen ("stdout.txt", "w", stdout );
1516 freopen ("stderr.txt", "w", stderr );
1517 argc = ccommand( &argv );
1520 // set default log levels
1521 sglog().setLogLevels( SG_ALL, SG_ALERT );
1524 #ifdef FLIGHTGEAR_VERSION
1525 version = FLIGHTGEAR_VERSION;
1527 version = "unknown version";
1529 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1531 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1533 // Allocate global data structures. This needs to happen before
1534 // we parse command line options
1536 globals = new FGGlobals;
1538 // seed the random number generater
1541 FGControls *controls = new FGControls;
1542 globals->set_controls( controls );
1544 string_list *col = new string_list;
1545 globals->set_channel_options_list( col );
1547 // Scan the config file(s) and command line options to see if
1548 // fg_root was specified (ignore all other options for now)
1549 fgInitFGRoot(argc, argv);
1551 // Check for the correct base package version
1552 static char required_version[] = "0.9.6";
1553 string base_version = fgBasePackageVersion();
1554 if ( !(base_version == required_version) ) {
1555 // tell the operator how to use this application
1557 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1558 cerr << endl << "Base package check failed ... " \
1559 << "Found version " << base_version << " at: " \
1560 << globals->get_fg_root() << endl;
1561 cerr << "Please upgrade to version: " << required_version << endl;
1563 cerr << "Hit a key to continue..." << endl;
1569 // Initialize the Aircraft directory to "" (UIUC)
1572 // Load the configuration parameters. (Command line options
1573 // overrides config file options. Config file options override
1575 if ( !fgInitConfig(argc, argv) ) {
1576 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1580 // Initialize the Window/Graphics environment.
1581 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1582 // Mac OS X command line ("non-bundle") applications call this
1583 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1584 // feel free to add comments...
1585 fgOSInit(&argc, argv);
1586 _bootstrap_OSInit++;
1589 fgRegisterWindowResizeHandler( fgReshape );
1590 fgRegisterIdleHandler( fgIdleFunction );
1591 fgRegisterDrawHandler( fgRenderFrame );
1593 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1594 bool get_stencil_buffer = true;
1596 bool get_stencil_buffer = false;
1599 // Clouds3D requires an alpha channel
1600 // clouds may require stencil buffer
1601 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1602 fgGetInt("/sim/startup/ysize"),
1603 fgGetInt("/sim/rendering/bits-per-pixel"),
1604 fgGetBool("/sim/rendering/clouds3d"),
1606 fgGetBool("/sim/startup/fullscreen") );
1608 // This seems to be the absolute earliest in the init sequence
1609 // that these calls will return valid info. Too bad it's after
1610 // we've already created and sized out window. :-(
1611 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1612 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1613 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1614 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1617 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1618 general.set_glMaxTexSize( tmp );
1619 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1621 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1622 general.set_glDepthBits( tmp );
1623 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1625 // Initialize plib net interface
1626 netInit( &argc, argv );
1628 // Initialize ssg (from plib). Needs to come before we do any
1629 // other ssg stuff, but after opengl has been initialized.
1632 // Initialize the user interface (we need to do this before
1633 // passing off control to the OS main loop and before
1634 // fgInitGeneral to get our fonts !!!
1637 // Read the list of available aircrafts
1640 #ifdef GL_EXT_texture_lod_bias
1641 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1644 // get the address of our OpenGL extensions
1645 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1647 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1648 glPointParameterIsSupported = true;
1649 glPointParameterfPtr = (glPointParameterfProc)
1650 SGLookupFunction("glPointParameterfEXT");
1651 glPointParameterfvPtr = (glPointParameterfvProc)
1652 SGLookupFunction("glPointParameterfvEXT");
1654 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1655 glPointParameterIsSupported = true;
1656 glPointParameterfPtr = (glPointParameterfProc)
1657 SGLookupFunction("glPointParameterfARB");
1658 glPointParameterfvPtr = (glPointParameterfvProc)
1659 SGLookupFunction("glPointParameterfvARB");
1661 glPointParameterIsSupported = false;
1664 // based on the requested presets, calculate the true starting
1669 SGTime *t = fgInitTime();
1670 globals->set_time_params( t );
1672 // Do some quick general initializations
1673 if( !fgInitGeneral()) {
1674 SG_LOG( SG_GENERAL, SG_ALERT,
1675 "General initializations failed ..." );
1679 ////////////////////////////////////////////////////////////////////
1680 // Initialize the property-based built-in commands
1681 ////////////////////////////////////////////////////////////////////
1684 ////////////////////////////////////////////////////////////////////
1685 // Initialize the material manager
1686 ////////////////////////////////////////////////////////////////////
1687 globals->set_matlib( new SGMaterialLib );
1689 globals->set_model_lib(new SGModelLib);
1691 ////////////////////////////////////////////////////////////////////
1692 // Initialize the TG scenery subsystem.
1693 ////////////////////////////////////////////////////////////////////
1694 globals->set_scenery( new FGScenery );
1695 globals->get_scenery()->init();
1696 globals->get_scenery()->bind();
1697 globals->set_tile_mgr( new FGTileMgr );
1699 ////////////////////////////////////////////////////////////////////
1700 // Initialize the general model subsystem.
1701 ////////////////////////////////////////////////////////////////////
1702 globals->set_model_mgr(new FGModelMgr);
1703 globals->get_model_mgr()->init();
1704 globals->get_model_mgr()->bind();
1706 ////////////////////////////////////////////////////////////////////
1707 // Initialize the 3D aircraft model subsystem (has a dependency on
1708 // the scenery subsystem.)
1709 ////////////////////////////////////////////////////////////////////
1710 globals->set_aircraft_model(new FGAircraftModel);
1711 globals->get_aircraft_model()->init();
1712 globals->get_aircraft_model()->bind();
1714 ////////////////////////////////////////////////////////////////////
1715 // Initialize the view manager subsystem.
1716 ////////////////////////////////////////////////////////////////////
1717 FGViewMgr *viewmgr = new FGViewMgr;
1718 globals->set_viewmgr( viewmgr );
1723 // Initialize the sky
1724 SGPath ephem_data_path( globals->get_fg_root() );
1725 ephem_data_path.append( "Astro" );
1726 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1727 ephem->update( globals->get_time_params()->getMjd(),
1728 globals->get_time_params()->getLst(),
1730 globals->set_ephem( ephem );
1732 // TODO: move to environment mgr
1734 SGPath texture_path(globals->get_fg_root());
1735 texture_path.append("Textures");
1736 texture_path.append("Sky");
1737 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1738 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1739 thesky->add_cloud_layer(layer);
1742 SGPath sky_tex_path( globals->get_fg_root() );
1743 sky_tex_path.append( "Textures" );
1744 sky_tex_path.append( "Sky" );
1745 thesky->texture_path( sky_tex_path.str() );
1747 // The sun and moon diameters are scaled down numbers of the
1748 // actual diameters. This was needed to fit bot the sun and the
1749 // moon within the distance to the far clip plane.
1750 // Moon diameter: 3,476 kilometers
1751 // Sun diameter: 1,390,000 kilometers
1752 thesky->build( 80000.0, 80000.0,
1754 globals->get_ephem()->getNumPlanets(),
1755 globals->get_ephem()->getPlanets(),
1756 globals->get_ephem()->getNumStars(),
1757 globals->get_ephem()->getStars() );
1759 // Initialize MagVar model
1760 SGMagVar *magvar = new SGMagVar();
1761 globals->set_mag( magvar );
1764 // kludge to initialize mag compass
1765 // (should only be done for in-flight
1767 // update magvar model
1768 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1769 * SGD_DEGREES_TO_RADIANS,
1770 fgGetDouble("/position/latitude-deg")
1771 * SGD_DEGREES_TO_RADIANS,
1772 fgGetDouble("/position/altitude-ft")
1774 globals->get_time_params()->getJD() );
1775 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1776 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1778 // airport = new ssgBranch;
1779 // airport->setName( "Airport Lighting" );
1780 // lighting->addKid( airport );
1782 // build our custom render states
1783 fgBuildRenderStates();
1786 // pass control off to the master event handler
1789 SG_LOG( SG_ALL, SG_ALERT,
1790 "Unknown exception in the main loop. Aborting..." );
1793 // we never actually get here ... but to avoid compiler warnings,