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
46 #include <plib/netSocket.h>
48 #include <simgear/screen/extensions.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/scene/sky/sky.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/scene/model/animation.hxx>
54 #include <simgear/ephemeris/ephemeris.hxx>
55 #include <simgear/scene/model/placement.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/route/route.hxx>
58 #include <simgear/scene/model/modellib.hxx>
60 #ifdef FG_USE_CLOUDS_3D
61 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
62 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
65 #include <Include/general.hxx>
66 #include <Scenery/tileentry.hxx>
67 #include <Time/light.hxx>
68 #include <Time/light.hxx>
69 #include <Aircraft/aircraft.hxx>
70 #include <Cockpit/panel.hxx>
71 #include <Cockpit/cockpit.hxx>
72 #include <Cockpit/radiostack.hxx>
73 #include <Cockpit/hud.hxx>
74 #include <Model/panelnode.hxx>
75 #include <Model/modelmgr.hxx>
76 #include <Model/acmodel.hxx>
77 #include <Scenery/scenery.hxx>
78 #include <Scenery/tilemgr.hxx>
79 #include <FDM/flight.hxx>
80 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
81 #include <FDM/ADA.hxx>
82 #include <ATC/ATCdisplay.hxx>
83 #include <ATC/ATCmgr.hxx>
84 #include <ATC/AIMgr.hxx>
85 #include <Autopilot/newauto.hxx>
86 #include <Replay/replay.hxx>
87 #include <Time/tmp.hxx>
88 #include <Time/fg_timer.hxx>
89 #include <Environment/environment_mgr.hxx>
92 #include <MultiPlayer/multiplaytxmgr.hxx>
93 #include <MultiPlayer/multiplayrxmgr.hxx>
97 #include "fg_commands.hxx"
101 float default_attenuation[3] = {1.0, 0.0, 0.0};
102 ssgSelector *ship_sel=NULL;
103 // upto 32 instances of a same object can be loaded.
104 ssgTransform *ship_pos[32];
105 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
107 ssgSelector *lightpoints_brightness = new ssgSelector;
108 ssgTransform *lightpoints_transform = new ssgTransform;
109 FGTileEntry *dummy_tile;
112 // Clip plane settings...
113 float scene_nearplane = 0.5f;
114 float scene_farplane = 120000.0f;
116 static double real_delta_time_sec = 0.0;
117 static double delta_time_sec = 0.0;
119 glPointParameterfProc glPointParameterfPtr = 0;
120 glPointParameterfvProc glPointParameterfvPtr = 0;
121 bool glPointParameterIsSupported = false;
125 # include <WeatherCM/FGLocalWeatherDatabase.h>
129 # include <console.h> // -dw- for command line dialog
132 // This is a record containing a bit of global housekeeping information
135 // Specify our current idle function state. This is used to run all
136 // our initializations out of the glutIdleLoop() so that we can get a
137 // splash screen up and running right away.
138 static int idle_state = 0;
139 static long global_multi_loop;
141 // fog constants. I'm a little nervous about putting actual code out
142 // here but it seems to work (?)
143 static const double m_log01 = -log( 0.01 );
144 static const double sqrt_m_log01 = sqrt( m_log01 );
145 static GLfloat fog_exp_density;
146 static GLfloat fog_exp2_density;
147 static GLfloat rwy_exp2_punch_through;
148 static GLfloat taxi_exp2_punch_through;
149 static GLfloat ground_exp2_punch_through;
154 #ifdef FG_USE_CLOUDS_3D
155 SkySceneLoader *sgClouds3d;
156 bool _bcloud_orig = true;
160 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
162 { 1.0f, 0.0f, 0.0f, 0.0f },
163 { 0.0f, 0.0f, -1.0f, 0.0f },
164 { 0.0f, 1.0f, 0.0f, 0.0f },
165 { 0.0f, 0.0f, 0.0f, 1.0f }
168 // The following defines flightgear options. Because glutlib will also
169 // want to parse its own options, those options must not be included here
170 // or they will get parsed by the main program option parser. Hence case
171 // is significant for any option added that might be in conflict with
174 // glutlib parses for:
176 // -direct (invalid in Win32)
180 // -indirect (invalid in Win32)
183 // Note that glutlib depends upon strings while this program's
184 // option parser wants only initial characters followed by numbers
189 ssgSimpleState *cloud3d_imposter_state;
190 ssgSimpleState *default_state;
191 ssgSimpleState *hud_and_panel;
192 ssgSimpleState *menus;
194 SGTimeStamp last_time_stamp;
195 SGTimeStamp current_time_stamp;
198 void fgBuildRenderStates( void ) {
199 default_state = new ssgSimpleState;
200 default_state->ref();
201 default_state->disable( GL_TEXTURE_2D );
202 default_state->enable( GL_CULL_FACE );
203 default_state->enable( GL_COLOR_MATERIAL );
204 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
205 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
206 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
207 default_state->disable( GL_BLEND );
208 default_state->disable( GL_ALPHA_TEST );
209 default_state->disable( GL_LIGHTING );
211 cloud3d_imposter_state = new ssgSimpleState;
212 cloud3d_imposter_state->ref();
213 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
214 cloud3d_imposter_state->enable( GL_CULL_FACE );
215 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
216 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
217 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
218 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
219 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
220 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
221 cloud3d_imposter_state->enable( GL_BLEND );
222 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
223 cloud3d_imposter_state->disable( GL_LIGHTING );
225 hud_and_panel = new ssgSimpleState;
226 hud_and_panel->ref();
227 hud_and_panel->disable( GL_CULL_FACE );
228 hud_and_panel->disable( GL_TEXTURE_2D );
229 hud_and_panel->disable( GL_LIGHTING );
230 hud_and_panel->enable( GL_BLEND );
232 menus = new ssgSimpleState;
234 menus->disable( GL_CULL_FACE );
235 menus->disable( GL_TEXTURE_2D );
236 menus->enable( GL_BLEND );
240 // fgInitVisuals() -- Initialize various GL/view parameters
241 void fgInitVisuals( void ) {
243 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
245 #ifndef GLUT_WRONG_VERSION
246 // Go full screen if requested ...
247 if ( fgGetBool("/sim/startup/fullscreen") ) {
252 // If enabled, normal vectors specified with glNormal are scaled
253 // to unit length after transformation. Enabling this has
254 // performance implications. See the docs for glNormal.
255 // glEnable( GL_NORMALIZE );
257 glEnable( GL_LIGHTING );
258 glEnable( GL_LIGHT0 );
259 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
262 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
263 ssgGetLight( 0 ) -> setPosition( sunpos );
265 glFogi (GL_FOG_MODE, GL_EXP2);
266 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
267 (!fgGetBool("/sim/rendering/shading"))) {
268 // if fastest fog requested, or if flat shading force fastest
269 glHint ( GL_FOG_HINT, GL_FASTEST );
270 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
271 glHint ( GL_FOG_HINT, GL_NICEST );
273 if ( fgGetBool("/sim/rendering/wireframe") ) {
275 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
278 // This is the default anyways, but it can't hurt
279 glFrontFace ( GL_CCW );
282 // glEnable(GL_POINT_SMOOTH);
283 // glEnable(GL_LINE_SMOOTH);
284 // glEnable(GL_POLYGON_SMOOTH);
288 // For HiRes screen Dumps using Brian Pauls TR Library
289 void trRenderFrame( void ) {
291 if ( fgPanelVisible() ) {
292 GLfloat height = fgGetInt("/sim/startup/ysize");
294 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
295 * (height / 768.0) + 1;
296 glTranslatef( 0.0, view_h, 0.0 );
299 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
300 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
302 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
304 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
305 l->adj_fog_color()[2], l->adj_fog_color()[3]);
307 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
309 // set the opengl state to known default values
310 default_state->force();
313 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
314 glFogi ( GL_FOG_MODE, GL_EXP2 );
315 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
317 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
318 // we only update GL_AMBIENT for our lights we will never get
319 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
320 // explicitely to black.
321 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
322 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
324 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
326 // texture parameters
327 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
328 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
330 // we need a white diffuse light for the phase of the moon
331 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
332 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
334 // draw the ssg scene
335 // return to the desired diffuse color
336 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
337 glEnable( GL_DEPTH_TEST );
338 ssgSetNearFar( scene_nearplane, scene_farplane );
339 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
342 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
343 ssgSetNearFar( scene_nearplane, scene_farplane );
344 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
345 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
347 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
349 if (fgGetBool("/environment/clouds/status"))
350 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
352 globals->get_model_mgr()->draw();
353 globals->get_aircraft_model()->draw();
357 // Update all Visuals (redraws anything graphics related)
358 void fgRenderFrame() {
359 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
360 bool skyblend = fgGetBool("/sim/rendering/skyblend");
361 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
362 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
364 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
365 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
367 // static const SGPropertyNode *longitude
368 // = fgGetNode("/position/longitude-deg");
369 // static const SGPropertyNode *latitude
370 // = fgGetNode("/position/latitude-deg");
371 // static const SGPropertyNode *altitude
372 // = fgGetNode("/position/altitude-ft");
373 static const SGPropertyNode *groundlevel_nearplane
374 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
376 // Update the default (kludged) properties.
379 FGViewer *current__view = globals->get_current_view();
381 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
382 static double last_visibility = -9999;
385 double actual_visibility;
386 if (fgGetBool("/environment/clouds/status"))
387 actual_visibility = thesky->get_visibility();
389 actual_visibility = fgGetDouble("/environment/visibility-m");
390 if ( actual_visibility != last_visibility ) {
391 last_visibility = actual_visibility;
393 fog_exp_density = m_log01 / actual_visibility;
394 fog_exp2_density = sqrt_m_log01 / actual_visibility;
395 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
396 if ( actual_visibility < 8000 ) {
397 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
398 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
400 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
401 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
406 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
407 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
408 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
409 // GLfloat mat_shininess[] = { 10.0 };
410 GLbitfield clear_mask;
412 if ( idle_state != 1000 ) {
413 // still initializing, draw the splash screen
414 if ( fgGetBool("/sim/startup/splash-screen") ) {
415 fgSplashUpdate(0.0, 1.0);
417 // Keep resetting sim time while the sim is initializing
418 globals->set_sim_time_sec( 0.0 );
419 SGAnimation::set_sim_time_sec( 0.0 );
421 // idle_state is now 1000 meaning we've finished all our
422 // initializations and are running the main loop, so this will
423 // now work without seg faulting the system.
425 // calculate our current position in cartesian space
426 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
429 fgReshape( fgGetInt("/sim/startup/xsize"),
430 fgGetInt("/sim/startup/ysize") );
432 if ( fgGetBool("/sim/rendering/clouds3d") ) {
433 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
434 cloud3d_imposter_state->force();
436 glColor4f( 1.0, 1.0, 1.0, 1.0 );
437 glEnable(GL_DEPTH_TEST);
439 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
441 #ifdef FG_USE_CLOUDS_3D
442 if ( _bcloud_orig ) {
443 Point3D c = globals->get_scenery()->get_center();
444 sgClouds3d->Set_Cloud_Orig( &c );
445 _bcloud_orig = false;
447 sgClouds3d->Update( current__view->get_absolute_view_pos() );
449 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
450 glDisable(GL_DEPTH_TEST);
453 clear_mask = GL_DEPTH_BUFFER_BIT;
454 if ( fgGetBool("/sim/rendering/wireframe") ) {
455 clear_mask |= GL_COLOR_BUFFER_BIT;
459 if ( fgGetBool("/sim/rendering/textures") ) {
460 // glClearColor(black[0], black[1], black[2], black[3]);
461 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
462 l->adj_fog_color()[2], l->adj_fog_color()[3]);
463 clear_mask |= GL_COLOR_BUFFER_BIT;
466 glClearColor(l->sky_color()[0], l->sky_color()[1],
467 l->sky_color()[2], l->sky_color()[3]);
468 clear_mask |= GL_COLOR_BUFFER_BIT;
470 glClear( clear_mask );
472 // Tell GL we are switching to model view parameters
474 // I really should create a derived ssg node or use a call
475 // back or something so that I can draw the sky within the
476 // ssgCullAndDraw() function, but for now I just mimic what
477 // ssg does to set up the model view matrix
478 glMatrixMode(GL_MODELVIEW);
480 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
482 // set the opengl state to known default values
483 default_state->force();
485 // update fog params if visibility has changed
486 double visibility_meters = fgGetDouble("/environment/visibility-m");
487 thesky->set_visibility(visibility_meters);
489 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
490 ( global_multi_loop * fgGetInt("/sim/speed-up") )
491 / (double)fgGetInt("/sim/model-hz") );
493 // Set correct opengl fog density
494 glFogf (GL_FOG_DENSITY, fog_exp2_density);
496 // update the sky dome
499 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
500 << l->sky_color()[0] << " "
501 << l->sky_color()[1] << " "
502 << l->sky_color()[2] << " "
503 << l->sky_color()[3] );
504 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
505 << l->fog_color()[0] << " "
506 << l->fog_color()[1] << " "
507 << l->fog_color()[2] << " "
508 << l->fog_color()[3] );
509 SG_LOG( SG_GENERAL, SG_BULK,
510 " sun_angle = " << l->sun_angle
511 << " moon_angle = " << l->moon_angle );
514 static SGSkyColor scolor;
515 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
517 scolor.sky_color = l->sky_color();
518 scolor.fog_color = l->adj_fog_color();
519 scolor.cloud_color = l->cloud_color();
520 scolor.sun_angle = l->get_sun_angle();
521 scolor.moon_angle = l->get_moon_angle();
522 scolor.nplanets = globals->get_ephem()->getNumPlanets();
523 scolor.nstars = globals->get_ephem()->getNumStars();
524 scolor.planet_data = globals->get_ephem()->getPlanets();
525 scolor.star_data = globals->get_ephem()->getStars();
527 thesky->repaint( scolor );
530 SG_LOG( SG_GENERAL, SG_BULK,
531 "thesky->reposition( view_pos = " << view_pos[0] << " "
532 << view_pos[1] << " " << view_pos[2] );
533 SG_LOG( SG_GENERAL, SG_BULK,
534 " zero_elev = " << zero_elev[0] << " "
535 << zero_elev[1] << " " << zero_elev[2]
536 << " lon = " << cur_fdm_state->get_Longitude()
537 << " lat = " << cur_fdm_state->get_Latitude() );
538 SG_LOG( SG_GENERAL, SG_BULK,
539 " sun_rot = " << l->get_sun_rotation
540 << " gst = " << SGTime::cur_time_params->getGst() );
541 SG_LOG( SG_GENERAL, SG_BULK,
542 " sun ra = " << globals->get_ephem()->getSunRightAscension()
543 << " sun dec = " << globals->get_ephem()->getSunDeclination()
544 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
545 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
548 // The sun and moon distances are scaled down versions
549 // of the actual distance to get both the moon and the sun
550 // within the range of the far clip plane.
551 // Moon distance: 384,467 kilometers
552 // Sun distance: 150,000,000 kilometers
553 double sun_horiz_eff, moon_horiz_eff;
554 if (fgGetBool("/sim/rendering/horizon-effect")) {
555 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
556 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
558 sun_horiz_eff = moon_horiz_eff = 1.0;
561 static SGSkyState sstate;
563 sstate.view_pos = current__view->get_view_pos();
564 sstate.zero_elev = current__view->get_zero_elev();
565 sstate.view_up = current__view->get_world_up();
566 sstate.lon = current__view->getLongitude_deg()
567 * SGD_DEGREES_TO_RADIANS;
568 sstate.lat = current__view->getLatitude_deg()
569 * SGD_DEGREES_TO_RADIANS;
570 sstate.alt = current__view->getAltitudeASL_ft()
572 sstate.spin = l->get_sun_rotation();
573 sstate.gst = globals->get_time_params()->getGst();
574 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
575 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
576 sstate.sun_dist = 50000.0 * sun_horiz_eff;
577 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
578 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
579 sstate.moon_dist = 40000.0 * moon_horiz_eff;
581 thesky->reposition( sstate, delta_time_sec );
584 glEnable( GL_DEPTH_TEST );
585 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
587 glFogi( GL_FOG_MODE, GL_EXP2 );
588 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
591 // set sun/lighting parameters
592 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
594 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
595 // we only update GL_AMBIENT for our lights we will never get
596 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
597 // explicitely to black.
598 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
600 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
601 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
602 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
604 // texture parameters
605 // glEnable( GL_TEXTURE_2D );
606 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
607 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
609 // glMatrixMode( GL_PROJECTION );
611 ssgSetFOV( current__view->get_h_fov(),
612 current__view->get_v_fov() );
615 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
616 - globals->get_scenery()->get_cur_elev();
619 scene_nearplane = 10.0f;
620 scene_farplane = 120000.0f;
622 scene_nearplane = groundlevel_nearplane->getDoubleValue();
623 scene_farplane = 120000.0f;
626 ssgSetNearFar( scene_nearplane, scene_farplane );
629 // Update any multiplayer models
630 globals->get_multiplayer_rx_mgr()->Update();
633 if ( draw_otw && skyblend )
635 // draw the sky backdrop
637 // we need a white diffuse light for the phase of the moon
638 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
640 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
642 // return to the desired diffuse color
643 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
646 // draw the ssg scene
647 glEnable( GL_DEPTH_TEST );
649 ssgSetNearFar( scene_nearplane, scene_farplane );
651 if ( fgGetBool("/sim/rendering/wireframe") ) {
653 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
656 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
659 // This is a bit kludgy. Every 200 frames, do an extra
660 // traversal of the scene graph without drawing anything, but
661 // with the field-of-view set to 360x360 degrees. This
662 // ensures that out-of-range random objects that are not in
663 // the current view frustum will still be freed properly.
664 static int counter = 0;
666 if (counter == 200) {
669 // No need to put the near plane too close;
670 // this way, at least the aircraft can be
672 f.setNearFar(1000, 1000000);
674 ssgGetModelviewMatrix(m);
675 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
679 // change state for lighting here
681 // draw runway lighting
682 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
683 ssgSetNearFar( scene_nearplane, scene_farplane );
685 if ( enhanced_lighting ) {
687 // Enable states for drawing points with GL_extension
688 glEnable(GL_POINT_SMOOTH);
690 if ( distance_attenuation && glPointParameterIsSupported )
692 // Enable states for drawing points with GL_extension
693 glEnable(GL_POINT_SMOOTH);
695 float quadratic[3] = {1.0, 0.001, 0.0000001};
696 // makes the points fade as they move away
697 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
698 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
703 // blending function for runway lights
704 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
707 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
708 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
709 glEnable(GL_TEXTURE_GEN_S);
710 glEnable(GL_TEXTURE_GEN_T);
711 glPolygonMode(GL_FRONT, GL_POINT);
713 // draw runway lighting
715 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
716 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
719 // change punch through and then draw taxi lighting
720 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
722 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
723 // glFogfv ( GL_FOG_COLOR, taxi_fog );
725 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
729 glPolygonMode(GL_FRONT, GL_FILL);
730 glDisable(GL_TEXTURE_GEN_S);
731 glDisable(GL_TEXTURE_GEN_T);
733 //static int _frame_count = 0;
734 //if (_frame_count % 30 == 0) {
735 // printf("SSG: %s\n", ssgShowStats());
743 if ( enhanced_lighting ) {
744 if ( distance_attenuation && glPointParameterIsSupported )
746 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
747 default_attenuation);
751 glDisable(GL_POINT_SMOOTH);
754 // draw ground lighting
755 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
757 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
761 // draw the sky cloud layers
762 if ( draw_otw && fgGetBool("/environment/clouds/status") )
764 thesky->postDraw( cur_fdm_state->get_Altitude()
765 * SG_FEET_TO_METER );
769 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
772 glDisable( GL_LIGHTING );
773 // cout << "drawing new clouds" << endl;
775 glEnable(GL_DEPTH_TEST);
777 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
780 glEnable( GL_TEXTURE_2D );
781 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
782 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
783 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
784 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
787 #ifdef FG_USE_CLOUDS_3D
788 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
791 glEnable( GL_LIGHTING );
792 glEnable( GL_DEPTH_TEST );
793 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
797 globals->get_model_mgr()->draw();
798 globals->get_aircraft_model()->draw();
801 // display HUD && Panel
803 glDisable( GL_DEPTH_TEST );
804 // glDisable( GL_CULL_FACE );
805 // glDisable( GL_TEXTURE_2D );
807 // update the controls subsystem
808 globals->get_controls()->update(delta_time_sec);
810 hud_and_panel->apply();
813 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
814 // This only works properly if called before the panel call
815 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
816 globals->get_ATC_display()->update(delta_time_sec);
818 // update the panel subsystem
819 if ( globals->get_current_panel() != NULL ) {
820 globals->get_current_panel()->update(delta_time_sec);
824 // We can do translucent menus, so why not. :-)
826 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
828 // glDisable ( GL_BLEND ) ;
830 glEnable( GL_DEPTH_TEST );
833 // Fade out the splash screen over the first three seconds.
834 double t = globals->get_sim_time_sec();
836 fgSplashUpdate(0.0, 1.0);
837 } else if ( t <= 3.0) {
838 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
846 // Update internal time dependent calculations (i.e. flight model)
847 // FIXME: this distinction is obsolete; all subsystems now get delta
849 void fgUpdateTimeDepCalcs() {
850 static bool inited = false;
852 static const SGPropertyNode *replay_master
853 = fgGetNode( "/sim/freeze/replay", true );
854 static SGPropertyNode *replay_time
855 = fgGetNode( "/sim/replay/time", true );
856 static const SGPropertyNode *replay_end_time
857 = fgGetNode( "/sim/replay/end-time", true );
859 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
861 // Initialize the FDM here if it hasn't been and if we have a
862 // scenery elevation hit.
864 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
865 // << " cur_elev = " << scenery.get_cur_elev() << endl;
867 if ( !cur_fdm_state->get_inited() &&
868 globals->get_scenery()->get_cur_elev() > -9990 )
870 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
871 cur_fdm_state->init();
872 if ( cur_fdm_state->get_bound() ) {
873 cur_fdm_state->unbind();
875 cur_fdm_state->bind();
878 // conceptually, the following block could be done for each fdm
880 if ( cur_fdm_state->get_inited() ) {
881 // we have been inited, and we are good to go ...
887 if ( ! replay_master->getBoolValue() ) {
888 globals->get_autopilot()->update( delta_time_sec );
889 cur_fdm_state->update( delta_time_sec );
891 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
892 r->replay( replay_time->getDoubleValue() );
893 replay_time->setDoubleValue( replay_time->getDoubleValue()
895 * fgGetInt("/sim/speed-up") ) );
898 // do nothing, fdm isn't inited yet
901 globals->get_model_mgr()->update(delta_time_sec);
902 globals->get_aircraft_model()->update(delta_time_sec);
904 // update the view angle
905 globals->get_viewmgr()->update(delta_time_sec);
907 // Update solar system
908 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
909 globals->get_time_params()->getLst(),
910 cur_fdm_state->get_Latitude() );
912 // Update radio stack model
913 current_radiostack->update(delta_time_sec);
917 void fgInitTimeDepCalcs( void ) {
922 static const double alt_adjust_ft = 3.758099;
923 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
926 // What should we do when we have nothing else to do? Let's get ready
927 // for the next move and update the display?
928 static void fgMainLoop( void ) {
929 int model_hz = fgGetInt("/sim/model-hz");
931 static const SGPropertyNode *longitude
932 = fgGetNode("/position/longitude-deg");
933 static const SGPropertyNode *latitude
934 = fgGetNode("/position/latitude-deg");
935 static const SGPropertyNode *altitude
936 = fgGetNode("/position/altitude-ft");
937 static const SGPropertyNode *clock_freeze
938 = fgGetNode("/sim/freeze/clock", true);
939 static const SGPropertyNode *cur_time_override
940 = fgGetNode("/sim/time/cur-time-override", true);
941 static const SGPropertyNode *replay_master
942 = fgGetNode("/sim/freeze/replay", true);
944 // Update the elapsed time.
945 static bool first_time = true;
947 last_time_stamp.stamp();
951 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
952 if ( throttle_hz > 0.0 ) {
953 // simple frame rate throttle
954 double dt = 1000000.0 / throttle_hz;
955 current_time_stamp.stamp();
956 while ( current_time_stamp - last_time_stamp < dt ) {
957 current_time_stamp.stamp();
960 // run as fast as the app will go
961 current_time_stamp.stamp();
965 = double(current_time_stamp - last_time_stamp) / 1000000.0;
966 if ( clock_freeze->getBoolValue() ) {
969 delta_time_sec = real_delta_time_sec;
971 last_time_stamp = current_time_stamp;
972 globals->inc_sim_time_sec( delta_time_sec );
973 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
975 // These are useful, especially for Nasal scripts.
976 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
977 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
979 static long remainder = 0;
981 #ifdef FANCY_FRAME_COUNTER
985 static time_t last_time = 0;
986 static int frames = 0;
987 #endif // FANCY_FRAME_COUNTER
989 SGTime *t = globals->get_time_params();
991 globals->get_event_mgr()->update(delta_time_sec);
993 SGLocation * acmodel_location = 0;
994 if(cur_fdm_state->getACModel() != 0) {
995 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
998 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
999 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1001 #if defined( ENABLE_PLIB_JOYSTICK )
1002 // Read joystick and update control settings
1003 // if ( fgGetString("/sim/control-mode") == "joystick" )
1005 // fgJoystickRead();
1007 #elif defined( ENABLE_GLUT_JOYSTICK )
1008 // Glut joystick support works by feeding a joystick handler
1009 // function to glut. This is taken care of once in the joystick
1010 // init routine and we don't have to worry about it again.
1013 // Fix elevation. I'm just sticking this here for now, it should
1014 // probably move eventually
1016 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1017 scenery.get_cur_elev(),
1018 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1019 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1021 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1022 scenery.get_cur_elev(),
1023 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1024 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1026 // cout << "Warp = " << globals->get_warp() << endl;
1029 static bool last_clock_freeze = false;
1031 if ( clock_freeze->getBoolValue() ) {
1032 // clock freeze requested
1033 if ( cur_time_override->getLongValue() == 0 ) {
1034 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1035 globals->set_warp( 0 );
1038 // no clock freeze requested
1039 if ( last_clock_freeze == true ) {
1040 // clock just unfroze, let's set warp as the difference
1041 // between frozen time and current time so we don't get a
1042 // time jump (and corresponding sky object and lighting
1044 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1045 fgSetLong( "/sim/time/cur-time-override", 0 );
1047 if ( globals->get_warp_delta() != 0 ) {
1048 globals->inc_warp( globals->get_warp_delta() );
1052 last_clock_freeze = clock_freeze->getBoolValue();
1054 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1055 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1056 cur_time_override->getLongValue(),
1057 globals->get_warp() );
1059 if (globals->get_warp_delta() != 0) {
1060 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1064 // update magvar model
1065 globals->get_mag()->update( longitude->getDoubleValue()
1066 * SGD_DEGREES_TO_RADIANS,
1067 latitude->getDoubleValue()
1068 * SGD_DEGREES_TO_RADIANS,
1069 altitude->getDoubleValue() * SG_FEET_TO_METER,
1070 globals->get_time_params()->getJD() );
1072 // Get elapsed time (in usec) for this past frame
1073 elapsed = fgGetTimeInterval();
1074 SG_LOG( SG_ALL, SG_DEBUG,
1075 "Elapsed time interval is = " << elapsed
1076 << ", previous remainder is = " << remainder );
1078 // Calculate frame rate average
1079 #ifdef FANCY_FRAME_COUNTER
1080 /* old fps calculation */
1081 if ( elapsed > 0 ) {
1084 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1085 tmp = general.get_frame(i);
1087 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1088 general.set_frame(i+1,tmp);
1090 tmp = 1000000.0 / (float)elapsed;
1091 general.set_frame(0,tmp);
1092 // printf("frame[0] = %.2f\n", general.frames[0]);
1094 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1095 // printf("ave = %.2f\n", general.frame_rate);
1098 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1099 general.set_frame_rate( frames );
1100 fgSetInt("/sim/frame-rate", frames);
1101 SG_LOG( SG_ALL, SG_DEBUG,
1102 "--> Frame rate is = " << general.get_frame_rate() );
1105 last_time = t->get_cur_time();
1109 // Run ATC subsystem
1110 if (fgGetBool("/sim/ATC/enabled"))
1111 globals->get_ATC_mgr()->update(delta_time_sec);
1113 // Run the AI subsystem
1114 if (fgGetBool("/sim/ai-traffic/enabled"))
1115 globals->get_AI_mgr()->update(delta_time_sec);
1119 // Calculate model iterations needed for next frame
1120 elapsed += remainder;
1122 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1123 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1124 SG_LOG( SG_ALL, SG_DEBUG,
1125 "Model iterations needed = " << global_multi_loop
1126 << ", new remainder = " << remainder );
1128 // chop max interations to something reasonable if the sim was
1129 // delayed for an excesive amount of time
1130 if ( global_multi_loop > 2.0 * model_hz ) {
1131 global_multi_loop = (int)(2.0 * model_hz );
1136 if ( global_multi_loop > 0 ) {
1137 fgUpdateTimeDepCalcs();
1139 SG_LOG( SG_ALL, SG_DEBUG,
1140 "Elapsed time is zero ... we're zinging" );
1143 // Do any I/O channel work that might need to be done
1144 globals->get_io()->update( real_delta_time_sec );
1146 // see if we need to load any deferred-load textures
1147 globals->get_matlib()->load_next_deferred();
1149 // Run audio scheduler
1150 #ifdef ENABLE_AUDIO_SUPPORT
1151 if ( fgGetBool("/sim/sound/audible")
1152 && globals->get_soundmgr()->is_working() ) {
1153 globals->get_soundmgr()->update( delta_time_sec );
1157 globals->get_subsystem_mgr()->update(delta_time_sec);
1160 // Tile Manager updates - see if we need to load any new scenery tiles.
1161 // this code ties together the fdm, viewer and scenery classes...
1162 // we may want to move this to it's own class at some point
1164 double visibility_meters = fgGetDouble("/environment/visibility-m");
1165 FGViewer *current_view = globals->get_current_view();
1167 // update tile manager for FDM...
1168 // ...only if location is different than the viewer (to avoid duplicating effort)
1169 if( acmodel_location != current_view->getSGLocation() ) {
1170 if( acmodel_location != 0 ) {
1171 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1172 visibility_meters );
1173 globals->get_tile_mgr()->
1174 update( acmodel_location, visibility_meters,
1175 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1176 // save results of update in SGLocation for fdm...
1177 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1179 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1182 set_tile_center( globals->get_scenery()->get_next_center() );
1186 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1187 visibility_meters );
1188 // update tile manager for view...
1189 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1190 // after the FDM's until all of Flight Gear code references the viewer's location
1191 // for elevation instead of the "scenery's" current elevation.
1192 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1193 globals->get_tile_mgr()->update( view_location, visibility_meters,
1194 current_view->get_absolute_view_pos() );
1195 // save results of update in SGLocation for fdm...
1196 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1197 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1199 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1201 // If fdm location is same as viewer's then we didn't do the update for fdm location
1202 // above so we need to save the viewer results in the fdm SGLocation as well...
1203 if( acmodel_location == current_view->getSGLocation() ) {
1204 if( acmodel_location != 0 ) {
1205 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1206 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1208 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1212 // END Tile Manager udpates
1214 if (fgGetBool("/sim/rendering/specular-highlight")) {
1215 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1216 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1218 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1219 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1225 SG_LOG( SG_ALL, SG_DEBUG, "" );
1229 // This is the top level master main function that is registered as
1230 // our idle funciton
1232 // The first few passes take care of initialization things (a couple
1233 // per pass) and once everything has been initialized fgMainLoop from
1236 static void fgIdleFunction ( void ) {
1237 // printf("idle state == %d\n", idle_state);
1239 if ( idle_state == 0 ) {
1240 // Initialize the splash screen right away
1241 if ( fgGetBool("/sim/startup/splash-screen") ) {
1242 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1246 } else if ( idle_state == 1 ) {
1247 // Initialize audio support
1248 #ifdef ENABLE_AUDIO_SUPPORT
1250 // Start the intro music
1251 if ( fgGetBool("/sim/startup/intro-music") ) {
1252 SGPath mp3file( globals->get_fg_root() );
1253 mp3file.append( "Sounds/intro.mp3" );
1255 SG_LOG( SG_GENERAL, SG_INFO,
1256 "Starting intro music: " << mp3file.str() );
1258 #if defined( __CYGWIN__ )
1259 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1260 #elif defined( WIN32 )
1261 string command = "start /m " + mp3file.str();
1263 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1266 system ( command.c_str() );
1271 } else if ( idle_state == 2 ) {
1272 // These are a few miscellaneous things that aren't really
1273 // "subsystems" but still need to be initialized.
1276 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1277 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1282 } else if ( idle_state == 3 ) {
1283 // This is the top level init routine which calls all the
1284 // other subsystem initialization routines. If you are adding
1285 // a subsystem to flightgear, its initialization call should
1286 // located in this routine.
1287 if( !fgInitSubsystems()) {
1288 SG_LOG( SG_GENERAL, SG_ALERT,
1289 "Subsystem initializations failed ..." );
1294 } else if ( idle_state == 4 ) {
1295 // Initialize the time offset (warp) after fgInitSubsystem
1296 // (which initializes the lighting interpolation tables.)
1299 // setup OpenGL view parameters
1302 // Read the list of available aircrafts
1306 } else if ( idle_state == 5 ) {
1309 } else if ( idle_state == 6 ) {
1314 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1315 fgReshape( fgGetInt("/sim/startup/xsize"),
1316 fgGetInt("/sim/startup/ysize") );
1320 if ( idle_state == 1000 ) {
1321 // We've finished all our initialization steps, from now on we
1322 // run the main loop.
1324 glutIdleFunc(fgMainLoop);
1326 if ( fgGetBool("/sim/startup/splash-screen") ) {
1327 fgSplashUpdate(0.0, 1.0);
1332 // options.cxx needs to see this for toggle_panel()
1333 // Handle new window size or exposure
1334 void fgReshape( int width, int height ) {
1337 if ( (!fgGetBool("/sim/virtual-cockpit"))
1338 && fgPanelVisible() && idle_state == 1000 ) {
1339 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1340 globals->get_current_panel()->getYOffset()) / 768.0);
1346 FGViewMgr *viewmgr = globals->get_viewmgr();
1347 for ( int i = 0; i < viewmgr->size(); ++i ) {
1348 viewmgr->get_view(i)->
1349 set_aspect_ratio((float)view_h / (float)width);
1352 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1354 fgSetInt("/sim/startup/xsize", width);
1355 fgSetInt("/sim/startup/ysize", height);
1356 guiInitMouse(width, height);
1358 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1359 viewmgr->get_current_view()->get_v_fov() );
1363 #ifdef FG_USE_CLOUDS_3D
1364 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1365 viewmgr->get_current_view()->get_v_fov() );
1370 // Initialize GLUT and define a main window
1371 static bool fgGlutInit( int *argc, char **argv ) {
1373 #if !defined( macintosh )
1374 // GLUT will extract all glut specific options so later on we only
1375 // need wory about our own.
1376 glutInit(argc, argv);
1379 // Define Display Parameters. Clouds3d works best with --bpp32 option
1380 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1381 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1383 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1386 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1387 fgGetInt("/sim/startup/xsize") << "x"
1388 << fgGetInt("/sim/startup/ysize") );
1390 // Define initial window size
1391 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1392 fgGetInt("/sim/startup/ysize") );
1394 // Initialize windows
1395 if ( !fgGetBool("/sim/startup/game-mode")) {
1396 // Open the regular window
1397 glutCreateWindow("FlightGear");
1398 #ifndef GLUT_WRONG_VERSION
1400 // Open the cool new 'game mode' window
1401 char game_mode_str[256];
1402 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1403 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1404 #ifndef ENUM_CURRENT_SETTINGS
1405 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1406 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1410 dm.dmSize = sizeof(DEVMODE);
1411 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1412 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1413 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1414 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1415 fgGetInt("/sim/startup/ysize") );
1416 sprintf( game_mode_str, "%dx%d:%d@%d",
1420 dm.dmDisplayFrequency );
1422 // Open the cool new 'game mode' window
1423 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1424 fgGetInt("/sim/startup/xsize"),
1425 fgGetInt("/sim/startup/ysize"),
1426 fgGetInt("/sim/rendering/bits-per-pixel"));
1428 #endif // HAVE_WINDOWS_H
1429 SG_LOG( SG_GENERAL, SG_INFO,
1430 "game mode params = " << game_mode_str );
1431 glutGameModeString( game_mode_str );
1432 glutEnterGameMode();
1433 #endif // GLUT_WRONG_VERSION
1436 // This seems to be the absolute earliest in the init sequence
1437 // that these calls will return valid info. Too bad it's after
1438 // we've already created and sized out window. :-(
1439 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1440 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1441 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1442 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1445 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1446 general.set_glMaxTexSize( tmp );
1447 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1449 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1450 general.set_glDepthBits( tmp );
1451 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1457 // Initialize GLUT event handlers
1458 static bool fgGlutInitEvents( void ) {
1459 // call fgReshape() on window resizes
1460 glutReshapeFunc( fgReshape );
1462 // keyboard and mouse callbacks are set in FGInput::init
1464 // call fgMainLoop() whenever there is
1465 // nothing else to do
1466 glutIdleFunc( fgIdleFunction );
1469 glutDisplayFunc( fgRenderFrame );
1474 // Main top level initialization
1475 bool fgMainInit( int argc, char **argv ) {
1477 #if defined( macintosh )
1478 freopen ("stdout.txt", "w", stdout );
1479 freopen ("stderr.txt", "w", stderr );
1480 argc = ccommand( &argv );
1483 // set default log levels
1484 sglog().setLogLevels( SG_ALL, SG_ALERT );
1487 #ifdef FLIGHTGEAR_VERSION
1488 version = FLIGHTGEAR_VERSION;
1490 version = "unknown version";
1492 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1494 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1496 // Allocate global data structures. This needs to happen before
1497 // we parse command line options
1499 globals = new FGGlobals;
1501 // seed the random number generater
1504 SGRoute *route = new SGRoute;
1505 globals->set_route( route );
1507 FGControls *controls = new FGControls;
1508 globals->set_controls( controls );
1510 string_list *col = new string_list;
1511 globals->set_channel_options_list( col );
1513 // Scan the config file(s) and command line options to see if
1514 // fg_root was specified (ignore all other options for now)
1515 fgInitFGRoot(argc, argv);
1517 // Check for the correct base package version
1518 static char required_version[] = "0.9.3";
1519 string base_version = fgBasePackageVersion();
1520 if ( !(base_version == required_version) ) {
1521 // tell the operator how to use this application
1523 cerr << endl << "Base package check failed ... " \
1524 << "Found version " << base_version << " at: " \
1525 << globals->get_fg_root() << endl;
1526 cerr << "Please upgrade to version: " << required_version << endl;
1530 // Initialize the Aircraft directory to "" (UIUC)
1533 // Load the configuration parameters. (Command line options
1534 // overrides config file options. Config file options override
1536 if ( !fgInitConfig(argc, argv) ) {
1537 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1541 // Initialize the Window/Graphics environment.
1542 if( !fgGlutInit(&argc, argv) ) {
1543 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1547 // Initialize the various GLUT Event Handlers.
1548 if( !fgGlutInitEvents() ) {
1549 SG_LOG( SG_GENERAL, SG_ALERT,
1550 "GLUT event handler initialization failed ..." );
1554 // Initialize plib net interface
1555 netInit( &argc, argv );
1557 // Initialize ssg (from plib). Needs to come before we do any
1558 // other ssg stuff, but after opengl/glut has been initialized.
1561 // Initialize the user interface (we need to do this before
1562 // passing off control to glut and before fgInitGeneral to get our
1566 // Read the list of available aircrafts
1569 #ifdef GL_EXT_texture_lod_bias
1570 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1573 // get the address of our OpenGL extensions
1574 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1576 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1577 glPointParameterIsSupported = true;
1578 glPointParameterfPtr = (glPointParameterfProc)
1579 SGLookupFunction("glPointParameterfEXT");
1580 glPointParameterfvPtr = (glPointParameterfvProc)
1581 SGLookupFunction("glPointParameterfvEXT");
1583 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1584 glPointParameterIsSupported = true;
1585 glPointParameterfPtr = (glPointParameterfProc)
1586 SGLookupFunction("glPointParameterfARB");
1587 glPointParameterfvPtr = (glPointParameterfvProc)
1588 SGLookupFunction("glPointParameterfvARB");
1590 glPointParameterIsSupported = false;
1593 // based on the requested presets, calculate the true starting
1598 SGTime *t = fgInitTime();
1599 globals->set_time_params( t );
1601 // Do some quick general initializations
1602 if( !fgInitGeneral()) {
1603 SG_LOG( SG_GENERAL, SG_ALERT,
1604 "General initializations failed ..." );
1608 ////////////////////////////////////////////////////////////////////
1609 // Initialize the property-based built-in commands
1610 ////////////////////////////////////////////////////////////////////
1613 ////////////////////////////////////////////////////////////////////
1614 // Initialize the material manager
1615 ////////////////////////////////////////////////////////////////////
1616 globals->set_matlib( new SGMaterialLib );
1618 globals->set_model_lib(new SGModelLib);
1620 ////////////////////////////////////////////////////////////////////
1621 // Initialize the TG scenery subsystem.
1622 ////////////////////////////////////////////////////////////////////
1623 globals->set_scenery( new FGScenery );
1624 globals->get_scenery()->init();
1625 globals->get_scenery()->bind();
1626 globals->set_tile_mgr( new FGTileMgr );
1628 ////////////////////////////////////////////////////////////////////
1629 // Initialize the general model subsystem.
1630 ////////////////////////////////////////////////////////////////////
1631 globals->set_model_mgr(new FGModelMgr);
1632 globals->get_model_mgr()->init();
1633 globals->get_model_mgr()->bind();
1635 ////////////////////////////////////////////////////////////////////
1636 // Initialize the 3D aircraft model subsystem (has a dependency on
1637 // the scenery subsystem.)
1638 ////////////////////////////////////////////////////////////////////
1639 globals->set_aircraft_model(new FGAircraftModel);
1640 globals->get_aircraft_model()->init();
1641 globals->get_aircraft_model()->bind();
1643 ////////////////////////////////////////////////////////////////////
1644 // Initialize the view manager subsystem.
1645 ////////////////////////////////////////////////////////////////////
1646 FGViewMgr *viewmgr = new FGViewMgr;
1647 globals->set_viewmgr( viewmgr );
1652 // Initialize the sky
1653 SGPath ephem_data_path( globals->get_fg_root() );
1654 ephem_data_path.append( "Astro" );
1655 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1656 ephem->update( globals->get_time_params()->getMjd(),
1657 globals->get_time_params()->getLst(),
1659 globals->set_ephem( ephem );
1661 // TODO: move to environment mgr
1663 SGPath texture_path(globals->get_fg_root());
1664 texture_path.append("Textures");
1665 texture_path.append("Sky");
1666 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1667 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1668 thesky->add_cloud_layer(layer);
1671 SGPath sky_tex_path( globals->get_fg_root() );
1672 sky_tex_path.append( "Textures" );
1673 sky_tex_path.append( "Sky" );
1674 thesky->texture_path( sky_tex_path.str() );
1676 // The sun and moon diameters are scaled down numbers of the
1677 // actual diameters. This was needed to fit bot the sun and the
1678 // moon within the distance to the far clip plane.
1679 // Moon diameter: 3,476 kilometers
1680 // Sun diameter: 1,390,000 kilometers
1681 thesky->build( 80000.0, 80000.0,
1683 globals->get_ephem()->getNumPlanets(),
1684 globals->get_ephem()->getPlanets(),
1685 globals->get_ephem()->getNumStars(),
1686 globals->get_ephem()->getStars() );
1688 // Initialize MagVar model
1689 SGMagVar *magvar = new SGMagVar();
1690 globals->set_mag( magvar );
1693 // kludge to initialize mag compass
1694 // (should only be done for in-flight
1696 // update magvar model
1697 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1698 * SGD_DEGREES_TO_RADIANS,
1699 fgGetDouble("/position/latitude-deg")
1700 * SGD_DEGREES_TO_RADIANS,
1701 fgGetDouble("/position/altitude-ft")
1703 globals->get_time_params()->getJD() );
1704 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1705 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1707 // airport = new ssgBranch;
1708 // airport->setName( "Airport Lighting" );
1709 // lighting->addKid( airport );
1711 // build our custom render states
1712 fgBuildRenderStates();
1714 // pass control off to the master GLUT event handler
1717 // we never actually get here ... but to avoid compiler warnings,