1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
45 #include <plib/netSocket.h>
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
58 #ifdef FG_USE_CLOUDS_3D
59 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
87 #include <GUI/new_gui.hxx>
90 #include <MultiPlayer/multiplaytxmgr.hxx>
91 #include <MultiPlayer/multiplayrxmgr.hxx>
95 #include "fg_commands.hxx"
99 float default_attenuation[3] = {1.0, 0.0, 0.0};
100 ssgSelector *ship_sel=NULL;
101 // upto 32 instances of a same object can be loaded.
102 ssgTransform *ship_pos[32];
103 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
105 ssgSelector *lightpoints_brightness = new ssgSelector;
106 ssgTransform *lightpoints_transform = new ssgTransform;
107 FGTileEntry *dummy_tile;
110 // Clip plane settings...
111 float scene_nearplane = 0.5f;
112 float scene_farplane = 120000.0f;
114 static double real_delta_time_sec = 0.0;
115 static double delta_time_sec = 0.0;
117 glPointParameterfProc glPointParameterfPtr = 0;
118 glPointParameterfvProc glPointParameterfvPtr = 0;
119 bool glPointParameterIsSupported = false;
123 # include <console.h> // -dw- for command line dialog
126 // This is a record containing a bit of global housekeeping information
129 // Specify our current idle function state. This is used to run all
130 // our initializations out of the idle callback so that we can get a
131 // splash screen up and running right away.
132 static int idle_state = 0;
133 static long global_multi_loop;
135 // fog constants. I'm a little nervous about putting actual code out
136 // here but it seems to work (?)
137 static const double m_log01 = -log( 0.01 );
138 static const double sqrt_m_log01 = sqrt( m_log01 );
139 static GLfloat fog_exp_density;
140 static GLfloat fog_exp2_density;
141 static GLfloat rwy_exp2_punch_through;
142 static GLfloat taxi_exp2_punch_through;
143 static GLfloat ground_exp2_punch_through;
148 #ifdef FG_USE_CLOUDS_3D
149 SkySceneLoader *sgClouds3d;
150 bool _bcloud_orig = true;
154 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
156 { 1.0f, 0.0f, 0.0f, 0.0f },
157 { 0.0f, 0.0f, -1.0f, 0.0f },
158 { 0.0f, 1.0f, 0.0f, 0.0f },
159 { 0.0f, 0.0f, 0.0f, 1.0f }
162 ssgSimpleState *cloud3d_imposter_state;
163 ssgSimpleState *default_state;
164 ssgSimpleState *hud_and_panel;
165 ssgSimpleState *menus;
167 SGTimeStamp last_time_stamp;
168 SGTimeStamp current_time_stamp;
171 void fgBuildRenderStates( void ) {
172 default_state = new ssgSimpleState;
173 default_state->ref();
174 default_state->disable( GL_TEXTURE_2D );
175 default_state->enable( GL_CULL_FACE );
176 default_state->enable( GL_COLOR_MATERIAL );
177 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
178 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
179 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
180 default_state->disable( GL_BLEND );
181 default_state->disable( GL_ALPHA_TEST );
182 default_state->disable( GL_LIGHTING );
184 cloud3d_imposter_state = new ssgSimpleState;
185 cloud3d_imposter_state->ref();
186 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
187 cloud3d_imposter_state->enable( GL_CULL_FACE );
188 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
189 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
190 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
191 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
192 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
193 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
194 cloud3d_imposter_state->enable( GL_BLEND );
195 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
196 cloud3d_imposter_state->disable( GL_LIGHTING );
198 hud_and_panel = new ssgSimpleState;
199 hud_and_panel->ref();
200 hud_and_panel->disable( GL_CULL_FACE );
201 hud_and_panel->disable( GL_TEXTURE_2D );
202 hud_and_panel->disable( GL_LIGHTING );
203 hud_and_panel->enable( GL_BLEND );
205 menus = new ssgSimpleState;
207 menus->disable( GL_CULL_FACE );
208 menus->disable( GL_TEXTURE_2D );
209 menus->enable( GL_BLEND );
213 // fgInitVisuals() -- Initialize various GL/view parameters
214 void fgInitVisuals( void ) {
216 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
218 // Go full screen if requested ...
219 if ( fgGetBool("/sim/startup/fullscreen") ) {
223 // If enabled, normal vectors specified with glNormal are scaled
224 // to unit length after transformation. Enabling this has
225 // performance implications. See the docs for glNormal.
226 // glEnable( GL_NORMALIZE );
228 glEnable( GL_LIGHTING );
229 glEnable( GL_LIGHT0 );
230 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
233 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
234 ssgGetLight( 0 ) -> setPosition( sunpos );
236 glFogi (GL_FOG_MODE, GL_EXP2);
237 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
238 (!fgGetBool("/sim/rendering/shading"))) {
239 // if fastest fog requested, or if flat shading force fastest
240 glHint ( GL_FOG_HINT, GL_FASTEST );
241 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
242 glHint ( GL_FOG_HINT, GL_NICEST );
244 if ( fgGetBool("/sim/rendering/wireframe") ) {
246 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
249 // This is the default anyways, but it can't hurt
250 glFrontFace ( GL_CCW );
253 // glEnable(GL_POINT_SMOOTH);
254 // glEnable(GL_LINE_SMOOTH);
255 // glEnable(GL_POLYGON_SMOOTH);
259 // For HiRes screen Dumps using Brian Pauls TR Library
260 void trRenderFrame( void ) {
261 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
262 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
263 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
265 bool multi_pass_clouds = false;
267 bool draw_clouds = fgGetBool("/environment/clouds/status");
269 if ( fgPanelVisible() ) {
270 GLfloat height = fgGetInt("/sim/startup/ysize");
272 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
273 * (height / 768.0) + 1;
274 glTranslatef( 0.0, view_h, 0.0 );
277 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
278 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
280 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
282 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
283 l->adj_fog_color()[2], l->adj_fog_color()[3]);
285 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
287 // set the opengl state to known default values
288 default_state->force();
291 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
292 glFogi ( GL_FOG_MODE, GL_EXP2 );
293 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
295 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
296 // we only update GL_AMBIENT for our lights we will never get
297 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
298 // explicitely to black.
299 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
300 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
302 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
304 // texture parameters
305 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
306 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
308 // we need a white diffuse light for the phase of the moon
309 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
310 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
313 // draw the ssg scene
314 // return to the desired diffuse color
315 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
316 glEnable( GL_DEPTH_TEST );
317 ssgSetNearFar( scene_nearplane, scene_farplane );
320 FGTileMgr::set_tile_filter( true );
321 sgSetModelFilter( false );
322 globals->get_aircraft_model()->select( false );
323 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
324 // Disable depth buffer update, draw the clouds
325 glDepthMask( GL_FALSE );
326 thesky->drawUpperClouds();
327 if ( multi_pass_clouds ) {
328 thesky->drawLowerClouds();
330 glDepthMask( GL_TRUE );
331 if ( multi_pass_clouds ) {
332 // Draw the objects except the aircraft
333 // and update the stencil buffer with 1
334 glEnable( GL_STENCIL_TEST );
335 glStencilFunc( GL_ALWAYS, 1, 1 );
336 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
338 FGTileMgr::set_tile_filter( false );
339 sgSetModelFilter( true );
340 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
342 FGTileMgr::set_tile_filter( true );
343 sgSetModelFilter( true );
344 globals->get_aircraft_model()->select( false );
345 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
349 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
350 ssgSetNearFar( scene_nearplane, scene_farplane );
351 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
352 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
354 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
357 if ( multi_pass_clouds ) {
358 // Disable depth buffer update, draw the clouds where the
359 // objects overwrite the already drawn clouds, by testing
360 // the stencil buffer against 1
361 glDepthMask( GL_FALSE );
362 glStencilFunc( GL_EQUAL, 1, 1 );
363 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
364 thesky->drawUpperClouds();
365 thesky->drawLowerClouds();
366 glDepthMask( GL_TRUE );
367 glDisable( GL_STENCIL_TEST );
369 glDepthMask( GL_FALSE );
370 thesky->drawLowerClouds();
371 glDepthMask( GL_TRUE );
375 globals->get_aircraft_model()->select( true );
376 globals->get_model_mgr()->draw();
377 globals->get_aircraft_model()->draw();
381 // Update all Visuals (redraws anything graphics related)
382 void fgRenderFrame() {
383 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
384 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
385 bool skyblend = fgGetBool("/sim/rendering/skyblend");
386 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
387 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
388 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
389 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
390 !SGCloudLayer::enable_bump_mapping; // ugly artefact now
392 bool multi_pass_clouds = false;
394 bool draw_clouds = fgGetBool("/environment/clouds/status");
396 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
397 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
399 // static const SGPropertyNode *longitude
400 // = fgGetNode("/position/longitude-deg");
401 // static const SGPropertyNode *latitude
402 // = fgGetNode("/position/latitude-deg");
403 // static const SGPropertyNode *altitude
404 // = fgGetNode("/position/altitude-ft");
405 static const SGPropertyNode *groundlevel_nearplane
406 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
408 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
409 static double last_visibility = -9999;
412 double actual_visibility;
413 if (fgGetBool("/environment/clouds/status"))
414 actual_visibility = thesky->get_visibility();
416 actual_visibility = fgGetDouble("/environment/visibility-m");
417 if ( actual_visibility != last_visibility ) {
418 last_visibility = actual_visibility;
420 fog_exp_density = m_log01 / actual_visibility;
421 fog_exp2_density = sqrt_m_log01 / actual_visibility;
422 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
423 if ( actual_visibility < 8000 ) {
424 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
425 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
427 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
428 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
433 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
434 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
435 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
436 // GLfloat mat_shininess[] = { 10.0 };
437 GLbitfield clear_mask;
439 if ( idle_state != 1000 || !scenery_loaded ) {
440 // still initializing, draw the splash screen
441 if ( fgGetBool("/sim/startup/splash-screen") ) {
442 fgSplashUpdate(0.0, 1.0);
444 // Keep resetting sim time while the sim is initializing
445 globals->set_sim_time_sec( 0.0 );
446 SGAnimation::set_sim_time_sec( 0.0 );
448 // idle_state is now 1000 meaning we've finished all our
449 // initializations and are running the main loop, so this will
450 // now work without seg faulting the system.
452 FGViewer *current__view = globals->get_current_view();
454 // calculate our current position in cartesian space
455 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
458 fgReshape( fgGetInt("/sim/startup/xsize"),
459 fgGetInt("/sim/startup/ysize") );
461 if ( fgGetBool("/sim/rendering/clouds3d") ) {
462 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
463 cloud3d_imposter_state->force();
465 glColor4f( 1.0, 1.0, 1.0, 1.0 );
466 glEnable(GL_DEPTH_TEST);
468 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
470 #ifdef FG_USE_CLOUDS_3D
471 if ( _bcloud_orig ) {
472 Point3D c = globals->get_scenery()->get_center();
473 sgClouds3d->Set_Cloud_Orig( &c );
474 _bcloud_orig = false;
476 sgClouds3d->Update( current__view->get_absolute_view_pos() );
478 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
479 glDisable(GL_DEPTH_TEST);
482 clear_mask = GL_DEPTH_BUFFER_BIT;
483 if ( fgGetBool("/sim/rendering/wireframe") ) {
484 clear_mask |= GL_COLOR_BUFFER_BIT;
488 if ( fgGetBool("/sim/rendering/textures") ) {
489 // glClearColor(black[0], black[1], black[2], black[3]);
490 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
491 l->adj_fog_color()[2], l->adj_fog_color()[3]);
492 clear_mask |= GL_COLOR_BUFFER_BIT;
495 glClearColor(l->sky_color()[0], l->sky_color()[1],
496 l->sky_color()[2], l->sky_color()[3]);
497 clear_mask |= GL_COLOR_BUFFER_BIT;
499 if ( multi_pass_clouds && draw_clouds ) {
501 clear_mask |= GL_STENCIL_BUFFER_BIT;
503 glClear( clear_mask );
505 // Tell GL we are switching to model view parameters
507 // I really should create a derived ssg node or use a call
508 // back or something so that I can draw the sky within the
509 // ssgCullAndDraw() function, but for now I just mimic what
510 // ssg does to set up the model view matrix
511 glMatrixMode(GL_MODELVIEW);
513 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
515 // set the opengl state to known default values
516 default_state->force();
518 // update fog params if visibility has changed
519 double visibility_meters = fgGetDouble("/environment/visibility-m");
520 thesky->set_visibility(visibility_meters);
522 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
523 ( global_multi_loop * fgGetInt("/sim/speed-up") )
524 / (double)fgGetInt("/sim/model-hz") );
526 // Set correct opengl fog density
527 glFogf (GL_FOG_DENSITY, fog_exp2_density);
529 // update the sky dome
532 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
533 << l->sky_color()[0] << " "
534 << l->sky_color()[1] << " "
535 << l->sky_color()[2] << " "
536 << l->sky_color()[3] );
537 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
538 << l->fog_color()[0] << " "
539 << l->fog_color()[1] << " "
540 << l->fog_color()[2] << " "
541 << l->fog_color()[3] );
542 SG_LOG( SG_GENERAL, SG_BULK,
543 " sun_angle = " << l->sun_angle
544 << " moon_angle = " << l->moon_angle );
547 static SGSkyColor scolor;
548 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
550 scolor.sky_color = l->sky_color();
551 scolor.fog_color = l->adj_fog_color();
552 scolor.cloud_color = l->cloud_color();
553 scolor.sun_angle = l->get_sun_angle();
554 scolor.moon_angle = l->get_moon_angle();
555 scolor.nplanets = globals->get_ephem()->getNumPlanets();
556 scolor.nstars = globals->get_ephem()->getNumStars();
557 scolor.planet_data = globals->get_ephem()->getPlanets();
558 scolor.star_data = globals->get_ephem()->getStars();
560 thesky->repaint( scolor );
563 SG_LOG( SG_GENERAL, SG_BULK,
564 "thesky->reposition( view_pos = " << view_pos[0] << " "
565 << view_pos[1] << " " << view_pos[2] );
566 SG_LOG( SG_GENERAL, SG_BULK,
567 " zero_elev = " << zero_elev[0] << " "
568 << zero_elev[1] << " " << zero_elev[2]
569 << " lon = " << cur_fdm_state->get_Longitude()
570 << " lat = " << cur_fdm_state->get_Latitude() );
571 SG_LOG( SG_GENERAL, SG_BULK,
572 " sun_rot = " << l->get_sun_rotation
573 << " gst = " << SGTime::cur_time_params->getGst() );
574 SG_LOG( SG_GENERAL, SG_BULK,
575 " sun ra = " << globals->get_ephem()->getSunRightAscension()
576 << " sun dec = " << globals->get_ephem()->getSunDeclination()
577 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
578 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
581 // The sun and moon distances are scaled down versions
582 // of the actual distance to get both the moon and the sun
583 // within the range of the far clip plane.
584 // Moon distance: 384,467 kilometers
585 // Sun distance: 150,000,000 kilometers
586 double sun_horiz_eff, moon_horiz_eff;
587 if (fgGetBool("/sim/rendering/horizon-effect")) {
588 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
589 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
591 sun_horiz_eff = moon_horiz_eff = 1.0;
594 static SGSkyState sstate;
596 sstate.view_pos = current__view->get_view_pos();
597 sstate.zero_elev = current__view->get_zero_elev();
598 sstate.view_up = current__view->get_world_up();
599 sstate.lon = current__view->getLongitude_deg()
600 * SGD_DEGREES_TO_RADIANS;
601 sstate.lat = current__view->getLatitude_deg()
602 * SGD_DEGREES_TO_RADIANS;
603 sstate.alt = current__view->getAltitudeASL_ft()
605 sstate.spin = l->get_sun_rotation();
606 sstate.gst = globals->get_time_params()->getGst();
607 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
608 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
609 sstate.sun_dist = 50000.0 * sun_horiz_eff;
610 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
611 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
612 sstate.moon_dist = 40000.0 * moon_horiz_eff;
614 thesky->reposition( sstate, delta_time_sec );
617 glEnable( GL_DEPTH_TEST );
618 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
620 glFogi( GL_FOG_MODE, GL_EXP2 );
621 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
624 // set sun/lighting parameters
625 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
627 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
628 // we only update GL_AMBIENT for our lights we will never get
629 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
630 // explicitely to black.
631 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
633 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
634 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
635 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
637 // texture parameters
638 // glEnable( GL_TEXTURE_2D );
639 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
640 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
642 // glMatrixMode( GL_PROJECTION );
644 ssgSetFOV( current__view->get_h_fov(),
645 current__view->get_v_fov() );
648 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
649 - globals->get_scenery()->get_cur_elev();
652 scene_nearplane = 10.0f;
653 scene_farplane = 120000.0f;
655 scene_nearplane = groundlevel_nearplane->getDoubleValue();
656 scene_farplane = 120000.0f;
659 ssgSetNearFar( scene_nearplane, scene_farplane );
662 // Update any multiplayer models
663 globals->get_multiplayer_rx_mgr()->Update();
666 if ( draw_otw && skyblend ) {
667 // draw the sky backdrop
669 // we need a white diffuse light for the phase of the moon
670 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
671 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
673 // return to the desired diffuse color
674 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
677 // draw the ssg scene
678 glEnable( GL_DEPTH_TEST );
680 ssgSetNearFar( scene_nearplane, scene_farplane );
682 if ( fgGetBool("/sim/rendering/wireframe") ) {
684 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
690 FGTileMgr::set_tile_filter( true );
691 sgSetModelFilter( false );
692 globals->get_aircraft_model()->select( false );
693 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
695 // Disable depth buffer update, draw the clouds
696 glDepthMask( GL_FALSE );
697 thesky->drawUpperClouds();
698 if ( multi_pass_clouds ) {
699 thesky->drawLowerClouds();
701 glDepthMask( GL_TRUE );
703 if ( multi_pass_clouds ) {
704 // Draw the objects except the aircraft
705 // and update the stencil buffer with 1
706 glEnable( GL_STENCIL_TEST );
707 glStencilFunc( GL_ALWAYS, 1, 1 );
708 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
710 FGTileMgr::set_tile_filter( false );
711 sgSetModelFilter( true );
712 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
714 FGTileMgr::set_tile_filter( true );
715 sgSetModelFilter( true );
716 globals->get_aircraft_model()->select( false );
717 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
721 // This is a bit kludgy. Every 200 frames, do an extra
722 // traversal of the scene graph without drawing anything, but
723 // with the field-of-view set to 360x360 degrees. This
724 // ensures that out-of-range random objects that are not in
725 // the current view frustum will still be freed properly.
726 static int counter = 0;
728 if (counter == 200) {
731 // No need to put the near plane too close;
732 // this way, at least the aircraft can be
734 f.setNearFar(1000, 1000000);
736 ssgGetModelviewMatrix(m);
737 FGTileMgr::set_tile_filter( true );
738 sgSetModelFilter( true );
739 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
743 // change state for lighting here
745 // draw runway lighting
746 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
747 ssgSetNearFar( scene_nearplane, scene_farplane );
749 if ( enhanced_lighting ) {
751 // Enable states for drawing points with GL_extension
752 glEnable(GL_POINT_SMOOTH);
754 if ( distance_attenuation && glPointParameterIsSupported )
756 // Enable states for drawing points with GL_extension
757 glEnable(GL_POINT_SMOOTH);
759 float quadratic[3] = {1.0, 0.001, 0.0000001};
760 // makes the points fade as they move away
761 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
762 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
767 // blending function for runway lights
768 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
771 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
772 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
773 glEnable(GL_TEXTURE_GEN_S);
774 glEnable(GL_TEXTURE_GEN_T);
775 glPolygonMode(GL_FRONT, GL_POINT);
777 // draw runway lighting
779 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
780 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
783 // change punch through and then draw taxi lighting
784 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
786 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
787 // glFogfv ( GL_FOG_COLOR, taxi_fog );
789 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
793 glPolygonMode(GL_FRONT, GL_FILL);
794 glDisable(GL_TEXTURE_GEN_S);
795 glDisable(GL_TEXTURE_GEN_T);
797 //static int _frame_count = 0;
798 //if (_frame_count % 30 == 0) {
799 // printf("SSG: %s\n", ssgShowStats());
807 if ( enhanced_lighting ) {
808 if ( distance_attenuation && glPointParameterIsSupported ) {
809 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
810 default_attenuation);
814 glDisable(GL_POINT_SMOOTH);
817 // draw ground lighting
818 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
820 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
823 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
825 glDisable( GL_LIGHTING );
826 // cout << "drawing new clouds" << endl;
828 glEnable(GL_DEPTH_TEST);
830 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
833 glEnable( GL_TEXTURE_2D );
834 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
835 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
836 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
837 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
840 #ifdef FG_USE_CLOUDS_3D
841 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
844 glEnable( GL_LIGHTING );
845 glEnable( GL_DEPTH_TEST );
846 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
849 if ( draw_otw && draw_clouds ) {
850 if ( multi_pass_clouds ) {
851 // Disable depth buffer update, draw the clouds where the
852 // objects overwrite the already drawn clouds, by testing
853 // the stencil buffer against 1
854 glDepthMask( GL_FALSE );
855 glStencilFunc( GL_EQUAL, 1, 1 );
856 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
857 thesky->drawUpperClouds();
858 thesky->drawLowerClouds();
859 glDepthMask( GL_TRUE );
860 glDisable( GL_STENCIL_TEST );
862 glDepthMask( GL_FALSE );
863 thesky->drawLowerClouds();
864 glDepthMask( GL_TRUE );
869 FGTileMgr::set_tile_filter( false );
870 sgSetModelFilter( false );
871 globals->get_aircraft_model()->select( true );
872 globals->get_model_mgr()->draw();
873 globals->get_aircraft_model()->draw();
874 // If the view is internal, the previous line draw the
875 // cockpit with modified near/far clip planes and deselect
876 // the aircraft in the global scenegraph
877 // Otherwise, it just enables the aircraft: The scenegraph
878 // must be drawn again to see the plane.
879 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
880 FGTileMgr::set_tile_filter( true );
881 sgSetModelFilter( true );
882 globals->get_aircraft_model()->select( true );
885 // display HUD && Panel
887 glDisable( GL_DEPTH_TEST );
888 // glDisable( GL_CULL_FACE );
889 // glDisable( GL_TEXTURE_2D );
891 // update the controls subsystem
892 globals->get_controls()->update(delta_time_sec);
894 hud_and_panel->apply();
897 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
898 // This only works properly if called before the panel call
899 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
900 globals->get_ATC_display()->update(delta_time_sec);
902 // update the panel subsystem
903 if ( globals->get_current_panel() != NULL ) {
904 globals->get_current_panel()->update(delta_time_sec);
908 // We can do translucent menus, so why not. :-)
910 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
912 // glDisable ( GL_BLEND ) ;
914 glEnable( GL_DEPTH_TEST );
917 // Fade out the splash screen over the first three seconds.
918 double t = globals->get_sim_time_sec();
920 fgSplashUpdate(0.0, 1.0);
921 } else if ( t <= 3.0) {
922 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
928 // Update internal time dependent calculations (i.e. flight model)
929 // FIXME: this distinction is obsolete; all subsystems now get delta
931 void fgUpdateTimeDepCalcs() {
932 static bool inited = false;
934 static const SGPropertyNode *replay_master
935 = fgGetNode( "/sim/freeze/replay", true );
936 static SGPropertyNode *replay_time
937 = fgGetNode( "/sim/replay/time", true );
938 // static const SGPropertyNode *replay_end_time
939 // = fgGetNode( "/sim/replay/end-time", true );
941 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
943 // Initialize the FDM here if it hasn't been and if we have a
944 // scenery elevation hit.
946 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
947 // << " cur_elev = " << scenery.get_cur_elev() << endl;
949 if ( !cur_fdm_state->get_inited() &&
950 globals->get_scenery()->get_cur_elev() > -9990 )
952 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
953 cur_fdm_state->init();
954 if ( cur_fdm_state->get_bound() ) {
955 cur_fdm_state->unbind();
957 cur_fdm_state->bind();
960 // conceptually, the following block could be done for each fdm
962 if ( cur_fdm_state->get_inited() ) {
963 // we have been inited, and we are good to go ...
969 if ( ! replay_master->getBoolValue() ) {
970 cur_fdm_state->update( delta_time_sec );
972 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
973 r->replay( replay_time->getDoubleValue() );
974 replay_time->setDoubleValue( replay_time->getDoubleValue()
976 * fgGetInt("/sim/speed-up") ) );
979 // do nothing, fdm isn't inited yet
982 globals->get_model_mgr()->update(delta_time_sec);
983 globals->get_aircraft_model()->update(delta_time_sec);
985 // update the view angle
986 globals->get_viewmgr()->update(delta_time_sec);
988 // Update solar system
989 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
990 globals->get_time_params()->getLst(),
991 cur_fdm_state->get_Latitude() );
993 // Update radio stack model
994 current_radiostack->update(delta_time_sec);
998 void fgInitTimeDepCalcs( void ) {
1003 static const double alt_adjust_ft = 3.758099;
1004 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1007 // What should we do when we have nothing else to do? Let's get ready
1008 // for the next move and update the display?
1009 static void fgMainLoop( void ) {
1010 int model_hz = fgGetInt("/sim/model-hz");
1012 static const SGPropertyNode *longitude
1013 = fgGetNode("/position/longitude-deg");
1014 static const SGPropertyNode *latitude
1015 = fgGetNode("/position/latitude-deg");
1016 static const SGPropertyNode *altitude
1017 = fgGetNode("/position/altitude-ft");
1018 static const SGPropertyNode *clock_freeze
1019 = fgGetNode("/sim/freeze/clock", true);
1020 static const SGPropertyNode *cur_time_override
1021 = fgGetNode("/sim/time/cur-time-override", true);
1022 // static const SGPropertyNode *replay_master
1023 // = fgGetNode("/sim/freeze/replay", true);
1025 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1027 // Update the elapsed time.
1028 static bool first_time = true;
1030 last_time_stamp.stamp();
1034 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1035 if ( throttle_hz > 0.0 ) {
1036 // simple frame rate throttle
1037 double dt = 1000000.0 / throttle_hz;
1038 current_time_stamp.stamp();
1039 while ( current_time_stamp - last_time_stamp < dt ) {
1040 current_time_stamp.stamp();
1043 // run as fast as the app will go
1044 current_time_stamp.stamp();
1048 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1049 if ( clock_freeze->getBoolValue() ) {
1052 delta_time_sec = real_delta_time_sec;
1054 last_time_stamp = current_time_stamp;
1055 globals->inc_sim_time_sec( delta_time_sec );
1056 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1058 // These are useful, especially for Nasal scripts.
1059 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1060 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1062 static long remainder = 0;
1064 #ifdef FANCY_FRAME_COUNTER
1068 static time_t last_time = 0;
1069 static int frames = 0;
1070 #endif // FANCY_FRAME_COUNTER
1072 SGTime *t = globals->get_time_params();
1074 globals->get_event_mgr()->update(delta_time_sec);
1076 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1077 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1079 #if defined( ENABLE_PLIB_JOYSTICK )
1080 // Read joystick and update control settings
1081 // if ( fgGetString("/sim/control-mode") == "joystick" )
1083 // fgJoystickRead();
1087 // Fix elevation. I'm just sticking this here for now, it should
1088 // probably move eventually
1090 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1091 scenery.get_cur_elev(),
1092 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1093 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1095 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1096 scenery.get_cur_elev(),
1097 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1098 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1100 // cout << "Warp = " << globals->get_warp() << endl;
1103 static bool last_clock_freeze = false;
1105 if ( clock_freeze->getBoolValue() ) {
1106 // clock freeze requested
1107 if ( cur_time_override->getLongValue() == 0 ) {
1108 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1109 globals->set_warp( 0 );
1112 // no clock freeze requested
1113 if ( last_clock_freeze == true ) {
1114 // clock just unfroze, let's set warp as the difference
1115 // between frozen time and current time so we don't get a
1116 // time jump (and corresponding sky object and lighting
1118 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1119 fgSetLong( "/sim/time/cur-time-override", 0 );
1121 if ( globals->get_warp_delta() != 0 ) {
1122 globals->inc_warp( globals->get_warp_delta() );
1126 last_clock_freeze = clock_freeze->getBoolValue();
1128 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1129 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1130 cur_time_override->getLongValue(),
1131 globals->get_warp() );
1133 if (globals->get_warp_delta() != 0) {
1134 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1138 // update magvar model
1139 globals->get_mag()->update( longitude->getDoubleValue()
1140 * SGD_DEGREES_TO_RADIANS,
1141 latitude->getDoubleValue()
1142 * SGD_DEGREES_TO_RADIANS,
1143 altitude->getDoubleValue() * SG_FEET_TO_METER,
1144 globals->get_time_params()->getJD() );
1146 // Get elapsed time (in usec) for this past frame
1147 elapsed = fgGetTimeInterval();
1148 SG_LOG( SG_ALL, SG_DEBUG,
1149 "Elapsed time interval is = " << elapsed
1150 << ", previous remainder is = " << remainder );
1152 // Calculate frame rate average
1153 #ifdef FANCY_FRAME_COUNTER
1154 /* old fps calculation */
1155 if ( elapsed > 0 ) {
1158 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1159 tmp = general.get_frame(i);
1161 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1162 general.set_frame(i+1,tmp);
1164 tmp = 1000000.0 / (float)elapsed;
1165 general.set_frame(0,tmp);
1166 // printf("frame[0] = %.2f\n", general.frames[0]);
1168 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1169 // printf("ave = %.2f\n", general.frame_rate);
1172 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1173 general.set_frame_rate( frames );
1174 fgSetInt("/sim/frame-rate", frames);
1175 SG_LOG( SG_ALL, SG_DEBUG,
1176 "--> Frame rate is = " << general.get_frame_rate() );
1179 last_time = t->get_cur_time();
1183 // Run ATC subsystem
1184 if (fgGetBool("/sim/ATC/enabled"))
1185 globals->get_ATC_mgr()->update(delta_time_sec);
1187 // Run the AI subsystem
1188 if (fgGetBool("/sim/ai-traffic/enabled"))
1189 globals->get_AI_mgr()->update(delta_time_sec);
1193 // Calculate model iterations needed for next frame
1194 elapsed += remainder;
1196 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1197 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1198 SG_LOG( SG_ALL, SG_DEBUG,
1199 "Model iterations needed = " << global_multi_loop
1200 << ", new remainder = " << remainder );
1202 // chop max interations to something reasonable if the sim was
1203 // delayed for an excesive amount of time
1204 if ( global_multi_loop > 2.0 * model_hz ) {
1205 global_multi_loop = (int)(2.0 * model_hz );
1209 bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
1212 if ( global_multi_loop > 0) {
1213 // first run the flight model each frame until it is intialized
1214 // then continue running each frame only after initial scenery load is complete.
1215 if (!cur_fdm_state->get_inited() || scenery_loaded) {
1216 fgUpdateTimeDepCalcs();
1219 SG_LOG( SG_ALL, SG_DEBUG,
1220 "Elapsed time is zero ... we're zinging" );
1223 // Do any I/O channel work that might need to be done
1224 globals->get_io()->update( real_delta_time_sec );
1226 // see if we need to load any deferred-load textures
1227 globals->get_matlib()->load_next_deferred();
1229 // Run audio scheduler
1230 #ifdef ENABLE_AUDIO_SUPPORT
1231 if ( globals->get_soundmgr()->is_working() ) {
1232 globals->get_soundmgr()->update( delta_time_sec );
1236 globals->get_subsystem_mgr()->update(delta_time_sec);
1239 // Tile Manager updates - see if we need to load any new scenery tiles.
1240 // this code ties together the fdm, viewer and scenery classes...
1241 // we may want to move this to it's own class at some point
1243 double visibility_meters = fgGetDouble("/environment/visibility-m");
1244 FGViewer *current_view = globals->get_current_view();
1246 // get the location data for the primary FDM (now hardcoded to ac model)...
1247 SGLocation *acmodel_loc = NULL;
1248 acmodel_loc = (SGLocation *)globals->
1249 get_aircraft_model()->get3DModel()->getSGLocation();
1251 // update tile manager for FDM...
1252 // ...only if location is different than the current-view location
1253 // (to avoid duplicating effort)
1254 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1255 if( acmodel_loc != NULL ) {
1256 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1257 visibility_meters );
1258 globals->get_tile_mgr()->
1259 update( acmodel_loc, visibility_meters,
1261 get_absolute_view_pos(globals->
1262 get_scenery()->get_center()) );
1263 // save results of update in SGLocation for fdm...
1264 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1266 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1267 fgSetDouble("/position/ground-elev-m",
1268 globals->get_scenery()->get_cur_elev());
1271 set_tile_center( globals->get_scenery()->get_next_center() );
1275 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1276 visibility_meters );
1277 // update tile manager for view...
1278 // IMPORTANT!!! the tilemgr update for view location _must_ be
1279 // done last after the FDM's until all of Flight Gear code
1280 // references the viewer's location for elevation instead of the
1281 // "scenery's" current elevation.
1282 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1283 globals->get_tile_mgr()->update( view_location, visibility_meters,
1284 current_view->get_absolute_view_pos() );
1285 // save results of update in SGLocation for fdm...
1286 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1287 current_view->getSGLocation()->
1288 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1290 current_view->getSGLocation()->
1291 set_tile_center( globals->get_scenery()->get_next_center() );
1293 #ifdef ENABLE_AUDIO_SUPPORT
1294 // Right now we make a simplifying assumption that the primary
1295 // aircraft is the source of all sounds and that all sounds are
1296 // positioned relative to the current view position.
1298 static sgVec3 last_pos_offset;
1300 // set positional offset for sources
1301 sgVec3 source_pos_offset;
1302 sgSubVec3( source_pos_offset,
1303 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1304 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1305 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1309 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1310 sgScaleVec3( source_vel, delta_time_sec );
1311 sgCopyVec3( last_pos_offset, source_pos_offset );
1312 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1313 globals->get_soundmgr()->set_source_vel_all( source_vel );
1315 // Right now we make a simplifying assumption that the listener is
1316 // always positioned at the origin.
1317 sgVec3 listener_pos;
1318 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1319 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1320 globals->get_soundmgr()->set_listener_pos( listener_pos );
1323 // If fdm location is same as viewer's then we didn't do the
1324 // update for fdm location above so we need to save the viewer
1325 // results in the fdm SGLocation as well...
1326 if( fgGetBool("/sim/current-view/config/from-model") ) {
1327 if( acmodel_loc != 0 ) {
1328 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1329 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1331 fgSetDouble("/position/ground-elev-m",
1332 globals->get_scenery()->get_cur_elev());
1334 acmodel_loc->set_tile_center( globals->get_scenery()->
1335 get_next_center() );
1339 // END Tile Manager udpates
1341 if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
1342 fgSetBool("sim/sceneryloaded",true);
1345 if (fgGetBool("/sim/rendering/specular-highlight")) {
1346 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1347 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1349 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1350 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1355 SG_LOG( SG_ALL, SG_DEBUG, "" );
1359 // This is the top level master main function that is registered as
1360 // our idle funciton
1362 // The first few passes take care of initialization things (a couple
1363 // per pass) and once everything has been initialized fgMainLoop from
1366 static void fgIdleFunction ( void ) {
1367 // printf("idle state == %d\n", idle_state);
1369 if ( idle_state == 0 ) {
1370 fgSetBool("sim/initialised", false);
1372 // Initialize the splash screen right away
1373 if ( fgGetBool("/sim/startup/splash-screen") ) {
1374 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1378 } else if ( idle_state == 1 ) {
1379 // Initialize audio support
1380 #ifdef ENABLE_AUDIO_SUPPORT
1382 // Start the intro music
1383 if ( fgGetBool("/sim/startup/intro-music") ) {
1384 SGPath mp3file( globals->get_fg_root() );
1385 mp3file.append( "Sounds/intro.mp3" );
1387 SG_LOG( SG_GENERAL, SG_INFO,
1388 "Starting intro music: " << mp3file.str() );
1390 #if defined( __CYGWIN__ )
1391 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1392 #elif defined( WIN32 )
1393 string command = "start /m " + mp3file.str();
1395 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1398 system ( command.c_str() );
1403 } else if ( idle_state == 2 ) {
1404 // These are a few miscellaneous things that aren't really
1405 // "subsystems" but still need to be initialized.
1408 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1409 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1414 } else if ( idle_state == 3 ) {
1415 // This is the top level init routine which calls all the
1416 // other subsystem initialization routines. If you are adding
1417 // a subsystem to flightgear, its initialization call should
1418 // located in this routine.
1419 if( !fgInitSubsystems()) {
1420 SG_LOG( SG_GENERAL, SG_ALERT,
1421 "Subsystem initializations failed ..." );
1426 } else if ( idle_state == 4 ) {
1427 // Initialize the time offset (warp) after fgInitSubsystem
1428 // (which initializes the lighting interpolation tables.)
1431 // setup OpenGL view parameters
1434 // Read the list of available aircrafts
1438 } else if ( idle_state == 5 ) {
1441 } else if ( idle_state == 6 ) {
1446 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1447 fgReshape( fgGetInt("/sim/startup/xsize"),
1448 fgGetInt("/sim/startup/ysize") );
1452 if ( idle_state == 1000 ) {
1453 // We've finished all our initialization steps, from now on we
1454 // run the main loop.
1455 fgSetBool("sim/initialised",true);
1456 fgSetBool("sim/sceneryloaded",false);
1458 fgRegisterIdleHandler(fgMainLoop);
1460 if ( fgGetBool("/sim/startup/splash-screen") ) {
1461 fgSplashUpdate(0.0, 1.0);
1466 // options.cxx needs to see this for toggle_panel()
1467 // Handle new window size or exposure
1468 void fgReshape( int width, int height ) {
1471 if ( (!fgGetBool("/sim/virtual-cockpit"))
1472 && fgPanelVisible() && idle_state == 1000 ) {
1473 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1474 globals->get_current_panel()->getYOffset()) / 768.0);
1479 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1481 fgSetInt("/sim/startup/xsize", width);
1482 fgSetInt("/sim/startup/ysize", height);
1483 guiInitMouse(width, height);
1486 FGViewMgr *viewmgr = globals->get_viewmgr();
1488 for ( int i = 0; i < viewmgr->size(); ++i ) {
1489 viewmgr->get_view(i)->
1490 set_aspect_ratio((float)view_h / (float)width);
1493 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1494 viewmgr->get_current_view()->get_v_fov() );
1496 #ifdef FG_USE_CLOUDS_3D
1497 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1498 viewmgr->get_current_view()->get_v_fov() );
1507 // do some clean up on exit. Specifically we want to call alutExit()
1508 // which happens in the sound manager destructor.
1509 void fgExitCleanup() {
1510 fgSetMouseCursor(MOUSE_CURSOR_POINTER);
1516 // Main top level initialization
1517 bool fgMainInit( int argc, char **argv ) {
1519 #if defined( macintosh )
1520 freopen ("stdout.txt", "w", stdout );
1521 freopen ("stderr.txt", "w", stderr );
1522 argc = ccommand( &argv );
1525 // set default log levels
1526 sglog().setLogLevels( SG_ALL, SG_ALERT );
1528 atexit(fgExitCleanup);
1531 #ifdef FLIGHTGEAR_VERSION
1532 version = FLIGHTGEAR_VERSION;
1534 version = "unknown version";
1536 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1538 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1540 // Allocate global data structures. This needs to happen before
1541 // we parse command line options
1543 globals = new FGGlobals;
1545 // seed the random number generater
1548 FGControls *controls = new FGControls;
1549 globals->set_controls( controls );
1551 string_list *col = new string_list;
1552 globals->set_channel_options_list( col );
1554 // Scan the config file(s) and command line options to see if
1555 // fg_root was specified (ignore all other options for now)
1556 fgInitFGRoot(argc, argv);
1558 // Check for the correct base package version
1559 static char required_version[] = "0.9.5";
1560 string base_version = fgBasePackageVersion();
1561 if ( !(base_version == required_version) ) {
1562 // tell the operator how to use this application
1564 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1565 cerr << endl << "Base package check failed ... " \
1566 << "Found version " << base_version << " at: " \
1567 << globals->get_fg_root() << endl;
1568 cerr << "Please upgrade to version: " << required_version << endl;
1570 cerr << "Hit a key to continue..." << endl;
1576 // Initialize the Aircraft directory to "" (UIUC)
1579 // Load the configuration parameters. (Command line options
1580 // overrides config file options. Config file options override
1582 if ( !fgInitConfig(argc, argv) ) {
1583 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1587 // Initialize the Window/Graphics environment.
1588 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1589 // Mac OS X command line ("non-bundle") applications call this
1590 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1591 // feel free to add comments...
1592 fgOSInit(&argc, argv);
1595 fgRegisterWindowResizeHandler( fgReshape );
1596 fgRegisterIdleHandler( fgIdleFunction );
1597 fgRegisterDrawHandler( fgRenderFrame );
1599 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1600 bool get_stencil_buffer = true;
1602 bool get_stencil_buffer = false;
1605 // Clouds3D requires an alpha channel
1606 // clouds may require stencil buffer
1607 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1608 fgGetInt("/sim/startup/ysize"),
1609 fgGetInt("/sim/rendering/bits-per-pixel"),
1610 fgGetBool("/sim/rendering/clouds3d"),
1612 fgGetBool("/sim/startup/fullscreen") );
1614 // This seems to be the absolute earliest in the init sequence
1615 // that these calls will return valid info. Too bad it's after
1616 // we've already created and sized out window. :-(
1617 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1618 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1619 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1620 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1623 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1624 general.set_glMaxTexSize( tmp );
1625 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1627 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1628 general.set_glDepthBits( tmp );
1629 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1631 // Initialize plib net interface
1632 netInit( &argc, argv );
1634 // Initialize ssg (from plib). Needs to come before we do any
1635 // other ssg stuff, but after opengl has been initialized.
1638 // Initialize the user interface (we need to do this before
1639 // passing off control to the OS main loop and before
1640 // fgInitGeneral to get our fonts !!!
1643 // Read the list of available aircrafts
1646 #ifdef GL_EXT_texture_lod_bias
1647 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1650 // get the address of our OpenGL extensions
1651 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1653 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1654 glPointParameterIsSupported = true;
1655 glPointParameterfPtr = (glPointParameterfProc)
1656 SGLookupFunction("glPointParameterfEXT");
1657 glPointParameterfvPtr = (glPointParameterfvProc)
1658 SGLookupFunction("glPointParameterfvEXT");
1660 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1661 glPointParameterIsSupported = true;
1662 glPointParameterfPtr = (glPointParameterfProc)
1663 SGLookupFunction("glPointParameterfARB");
1664 glPointParameterfvPtr = (glPointParameterfvProc)
1665 SGLookupFunction("glPointParameterfvARB");
1667 glPointParameterIsSupported = false;
1670 // based on the requested presets, calculate the true starting
1675 SGTime *t = fgInitTime();
1676 globals->set_time_params( t );
1678 // Do some quick general initializations
1679 if( !fgInitGeneral()) {
1680 SG_LOG( SG_GENERAL, SG_ALERT,
1681 "General initializations failed ..." );
1685 ////////////////////////////////////////////////////////////////////
1686 // Initialize the property-based built-in commands
1687 ////////////////////////////////////////////////////////////////////
1690 ////////////////////////////////////////////////////////////////////
1691 // Initialize the material manager
1692 ////////////////////////////////////////////////////////////////////
1693 globals->set_matlib( new SGMaterialLib );
1695 globals->set_model_lib(new SGModelLib);
1697 ////////////////////////////////////////////////////////////////////
1698 // Initialize the TG scenery subsystem.
1699 ////////////////////////////////////////////////////////////////////
1700 globals->set_scenery( new FGScenery );
1701 globals->get_scenery()->init();
1702 globals->get_scenery()->bind();
1703 globals->set_tile_mgr( new FGTileMgr );
1705 ////////////////////////////////////////////////////////////////////
1706 // Initialize the general model subsystem.
1707 ////////////////////////////////////////////////////////////////////
1708 globals->set_model_mgr(new FGModelMgr);
1709 globals->get_model_mgr()->init();
1710 globals->get_model_mgr()->bind();
1712 ////////////////////////////////////////////////////////////////////
1713 // Initialize the 3D aircraft model subsystem (has a dependency on
1714 // the scenery subsystem.)
1715 ////////////////////////////////////////////////////////////////////
1716 globals->set_aircraft_model(new FGAircraftModel);
1717 globals->get_aircraft_model()->init();
1718 globals->get_aircraft_model()->bind();
1720 ////////////////////////////////////////////////////////////////////
1721 // Initialize the view manager subsystem.
1722 ////////////////////////////////////////////////////////////////////
1723 FGViewMgr *viewmgr = new FGViewMgr;
1724 globals->set_viewmgr( viewmgr );
1729 // Initialize the sky
1730 SGPath ephem_data_path( globals->get_fg_root() );
1731 ephem_data_path.append( "Astro" );
1732 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1733 ephem->update( globals->get_time_params()->getMjd(),
1734 globals->get_time_params()->getLst(),
1736 globals->set_ephem( ephem );
1738 // TODO: move to environment mgr
1740 SGPath texture_path(globals->get_fg_root());
1741 texture_path.append("Textures");
1742 texture_path.append("Sky");
1743 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1744 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1745 thesky->add_cloud_layer(layer);
1748 SGPath sky_tex_path( globals->get_fg_root() );
1749 sky_tex_path.append( "Textures" );
1750 sky_tex_path.append( "Sky" );
1751 thesky->texture_path( sky_tex_path.str() );
1753 // The sun and moon diameters are scaled down numbers of the
1754 // actual diameters. This was needed to fit bot the sun and the
1755 // moon within the distance to the far clip plane.
1756 // Moon diameter: 3,476 kilometers
1757 // Sun diameter: 1,390,000 kilometers
1758 thesky->build( 80000.0, 80000.0,
1760 globals->get_ephem()->getNumPlanets(),
1761 globals->get_ephem()->getPlanets(),
1762 globals->get_ephem()->getNumStars(),
1763 globals->get_ephem()->getStars() );
1765 // Initialize MagVar model
1766 SGMagVar *magvar = new SGMagVar();
1767 globals->set_mag( magvar );
1770 // kludge to initialize mag compass
1771 // (should only be done for in-flight
1773 // update magvar model
1774 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1775 * SGD_DEGREES_TO_RADIANS,
1776 fgGetDouble("/position/latitude-deg")
1777 * SGD_DEGREES_TO_RADIANS,
1778 fgGetDouble("/position/altitude-ft")
1780 globals->get_time_params()->getJD() );
1781 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1782 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1784 // airport = new ssgBranch;
1785 // airport->setName( "Airport Lighting" );
1786 // lighting->addKid( airport );
1788 // build our custom render states
1789 fgBuildRenderStates();
1792 // pass control off to the master event handler
1795 SG_LOG( SG_ALL, SG_ALERT,
1796 "Unknown exception in the main loop. Aborting..." );
1799 // we never actually get here ... but to avoid compiler warnings,