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_rwy_lights_root() );
346 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
348 if (fgGetBool("/environment/clouds/status"))
349 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
351 globals->get_model_mgr()->draw();
352 globals->get_aircraft_model()->draw();
356 // Update all Visuals (redraws anything graphics related)
357 void fgRenderFrame() {
358 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
359 bool skyblend = fgGetBool("/sim/rendering/skyblend");
360 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
361 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
363 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
364 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
366 // static const SGPropertyNode *longitude
367 // = fgGetNode("/position/longitude-deg");
368 // static const SGPropertyNode *latitude
369 // = fgGetNode("/position/latitude-deg");
370 // static const SGPropertyNode *altitude
371 // = fgGetNode("/position/altitude-ft");
372 static const SGPropertyNode *groundlevel_nearplane
373 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
375 // Update the default (kludged) properties.
378 FGViewer *current__view = globals->get_current_view();
380 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
381 static double last_visibility = -9999;
384 double actual_visibility;
385 if (fgGetBool("/environment/clouds/status"))
386 actual_visibility = thesky->get_visibility();
388 actual_visibility = fgGetDouble("/environment/visibility-m");
389 if ( actual_visibility != last_visibility ) {
390 last_visibility = actual_visibility;
392 fog_exp_density = m_log01 / actual_visibility;
393 fog_exp2_density = sqrt_m_log01 / actual_visibility;
394 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
395 if ( actual_visibility < 8000 ) {
396 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
397 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
399 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
400 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
405 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
406 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
407 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
408 // GLfloat mat_shininess[] = { 10.0 };
409 GLbitfield clear_mask;
411 if ( idle_state != 1000 ) {
412 // still initializing, draw the splash screen
413 if ( fgGetBool("/sim/startup/splash-screen") ) {
414 fgSplashUpdate(0.0, 1.0);
416 // Keep resetting sim time while the sim is initializing
417 globals->set_sim_time_sec( 0.0 );
418 SGAnimation::set_sim_time_sec( 0.0 );
420 // idle_state is now 1000 meaning we've finished all our
421 // initializations and are running the main loop, so this will
422 // now work without seg faulting the system.
424 // calculate our current position in cartesian space
425 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
428 fgReshape( fgGetInt("/sim/startup/xsize"),
429 fgGetInt("/sim/startup/ysize") );
431 if ( fgGetBool("/sim/rendering/clouds3d") ) {
432 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
433 cloud3d_imposter_state->force();
435 glColor4f( 1.0, 1.0, 1.0, 1.0 );
436 glEnable(GL_DEPTH_TEST);
438 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
440 #ifdef FG_USE_CLOUDS_3D
441 if ( _bcloud_orig ) {
442 Point3D c = globals->get_scenery()->get_center();
443 sgClouds3d->Set_Cloud_Orig( &c );
444 _bcloud_orig = false;
446 sgClouds3d->Update( current__view->get_absolute_view_pos() );
448 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
449 glDisable(GL_DEPTH_TEST);
452 clear_mask = GL_DEPTH_BUFFER_BIT;
453 if ( fgGetBool("/sim/rendering/wireframe") ) {
454 clear_mask |= GL_COLOR_BUFFER_BIT;
458 if ( fgGetBool("/sim/rendering/textures") ) {
459 // glClearColor(black[0], black[1], black[2], black[3]);
460 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
461 l->adj_fog_color()[2], l->adj_fog_color()[3]);
462 clear_mask |= GL_COLOR_BUFFER_BIT;
465 glClearColor(l->sky_color()[0], l->sky_color()[1],
466 l->sky_color()[2], l->sky_color()[3]);
467 clear_mask |= GL_COLOR_BUFFER_BIT;
469 glClear( clear_mask );
471 // Tell GL we are switching to model view parameters
473 // I really should create a derived ssg node or use a call
474 // back or something so that I can draw the sky within the
475 // ssgCullAndDraw() function, but for now I just mimic what
476 // ssg does to set up the model view matrix
477 glMatrixMode(GL_MODELVIEW);
479 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
481 // set the opengl state to known default values
482 default_state->force();
484 // update fog params if visibility has changed
485 double visibility_meters = fgGetDouble("/environment/visibility-m");
486 thesky->set_visibility(visibility_meters);
488 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
489 ( global_multi_loop * fgGetInt("/sim/speed-up") )
490 / (double)fgGetInt("/sim/model-hz") );
492 // Set correct opengl fog density
493 glFogf (GL_FOG_DENSITY, fog_exp2_density);
495 // update the sky dome
498 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
499 << l->sky_color()[0] << " "
500 << l->sky_color()[1] << " "
501 << l->sky_color()[2] << " "
502 << l->sky_color()[3] );
503 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
504 << l->fog_color()[0] << " "
505 << l->fog_color()[1] << " "
506 << l->fog_color()[2] << " "
507 << l->fog_color()[3] );
508 SG_LOG( SG_GENERAL, SG_BULK,
509 " sun_angle = " << l->sun_angle
510 << " moon_angle = " << l->moon_angle );
513 static SGSkyColor scolor;
514 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
516 scolor.sky_color = l->sky_color();
517 scolor.fog_color = l->adj_fog_color();
518 scolor.cloud_color = l->cloud_color();
519 scolor.sun_angle = l->get_sun_angle();
520 scolor.moon_angle = l->get_moon_angle();
521 scolor.nplanets = globals->get_ephem()->getNumPlanets();
522 scolor.nstars = globals->get_ephem()->getNumStars();
523 scolor.planet_data = globals->get_ephem()->getPlanets();
524 scolor.star_data = globals->get_ephem()->getStars();
526 thesky->repaint( scolor );
529 SG_LOG( SG_GENERAL, SG_BULK,
530 "thesky->reposition( view_pos = " << view_pos[0] << " "
531 << view_pos[1] << " " << view_pos[2] );
532 SG_LOG( SG_GENERAL, SG_BULK,
533 " zero_elev = " << zero_elev[0] << " "
534 << zero_elev[1] << " " << zero_elev[2]
535 << " lon = " << cur_fdm_state->get_Longitude()
536 << " lat = " << cur_fdm_state->get_Latitude() );
537 SG_LOG( SG_GENERAL, SG_BULK,
538 " sun_rot = " << l->get_sun_rotation
539 << " gst = " << SGTime::cur_time_params->getGst() );
540 SG_LOG( SG_GENERAL, SG_BULK,
541 " sun ra = " << globals->get_ephem()->getSunRightAscension()
542 << " sun dec = " << globals->get_ephem()->getSunDeclination()
543 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
544 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
547 // The sun and moon distances are scaled down versions
548 // of the actual distance to get both the moon and the sun
549 // within the range of the far clip plane.
550 // Moon distance: 384,467 kilometers
551 // Sun distance: 150,000,000 kilometers
552 double sun_horiz_eff, moon_horiz_eff;
553 if (fgGetBool("/sim/rendering/horizon-effect")) {
554 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
555 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
557 sun_horiz_eff = moon_horiz_eff = 1.0;
560 static SGSkyState sstate;
562 sstate.view_pos = current__view->get_view_pos();
563 sstate.zero_elev = current__view->get_zero_elev();
564 sstate.view_up = current__view->get_world_up();
565 sstate.lon = current__view->getLongitude_deg()
566 * SGD_DEGREES_TO_RADIANS;
567 sstate.lat = current__view->getLatitude_deg()
568 * SGD_DEGREES_TO_RADIANS;
569 sstate.alt = current__view->getAltitudeASL_ft()
571 sstate.spin = l->get_sun_rotation();
572 sstate.gst = globals->get_time_params()->getGst();
573 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
574 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
575 sstate.sun_dist = 50000.0 * sun_horiz_eff;
576 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
577 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
578 sstate.moon_dist = 40000.0 * moon_horiz_eff;
580 thesky->reposition( sstate, delta_time_sec );
583 glEnable( GL_DEPTH_TEST );
584 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
586 glFogi( GL_FOG_MODE, GL_EXP2 );
587 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
590 // set sun/lighting parameters
591 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
593 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
594 // we only update GL_AMBIENT for our lights we will never get
595 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
596 // explicitely to black.
597 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
599 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
600 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
601 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
603 // texture parameters
604 // glEnable( GL_TEXTURE_2D );
605 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
606 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
608 // glMatrixMode( GL_PROJECTION );
610 ssgSetFOV( current__view->get_h_fov(),
611 current__view->get_v_fov() );
614 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
615 - globals->get_scenery()->get_cur_elev();
618 scene_nearplane = 10.0f;
619 scene_farplane = 120000.0f;
621 scene_nearplane = groundlevel_nearplane->getDoubleValue();
622 scene_farplane = 120000.0f;
625 ssgSetNearFar( scene_nearplane, scene_farplane );
628 // Update any multiplayer models
629 globals->get_multiplayer_rx_mgr()->Update();
632 if ( draw_otw && skyblend )
634 // draw the sky backdrop
636 // we need a white diffuse light for the phase of the moon
637 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
639 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
641 // return to the desired diffuse color
642 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
645 // draw the ssg scene
646 glEnable( GL_DEPTH_TEST );
648 ssgSetNearFar( scene_nearplane, scene_farplane );
650 if ( fgGetBool("/sim/rendering/wireframe") ) {
652 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
655 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
658 // This is a bit kludgy. Every 200 frames, do an extra
659 // traversal of the scene graph without drawing anything, but
660 // with the field-of-view set to 360x360 degrees. This
661 // ensures that out-of-range random objects that are not in
662 // the current view frustum will still be freed properly.
663 static int counter = 0;
665 if (counter == 200) {
668 // No need to put the near plane too close;
669 // this way, at least the aircraft can be
671 f.setNearFar(1000, 1000000);
673 ssgGetModelviewMatrix(m);
674 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
678 // change state for lighting here
680 // draw runway lighting
681 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
682 ssgSetNearFar( scene_nearplane, scene_farplane );
684 if ( enhanced_lighting ) {
686 // Enable states for drawing points with GL_extension
687 glEnable(GL_POINT_SMOOTH);
689 if ( distance_attenuation && glPointParameterIsSupported )
691 // Enable states for drawing points with GL_extension
692 glEnable(GL_POINT_SMOOTH);
694 float quadratic[3] = {1.0, 0.001, 0.0000001};
695 // makes the points fade as they move away
696 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
697 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
702 // blending function for runway lights
703 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
706 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
707 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
708 glEnable(GL_TEXTURE_GEN_S);
709 glEnable(GL_TEXTURE_GEN_T);
710 glPolygonMode(GL_FRONT, GL_POINT);
712 // draw runway lighting
714 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
717 // change punch through and then draw taxi lighting
718 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
720 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
721 // glFogfv ( GL_FOG_COLOR, taxi_fog );
723 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
727 glPolygonMode(GL_FRONT, GL_FILL);
728 glDisable(GL_TEXTURE_GEN_S);
729 glDisable(GL_TEXTURE_GEN_T);
731 //static int _frame_count = 0;
732 //if (_frame_count % 30 == 0) {
733 // printf("SSG: %s\n", ssgShowStats());
741 if ( enhanced_lighting ) {
742 if ( distance_attenuation && glPointParameterIsSupported )
744 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
745 default_attenuation);
749 glDisable(GL_POINT_SMOOTH);
752 // draw ground lighting
753 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
755 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
759 // draw the sky cloud layers
760 if ( draw_otw && fgGetBool("/environment/clouds/status") )
762 thesky->postDraw( cur_fdm_state->get_Altitude()
763 * SG_FEET_TO_METER );
767 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
770 glDisable( GL_LIGHTING );
771 // cout << "drawing new clouds" << endl;
773 glEnable(GL_DEPTH_TEST);
775 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
778 glEnable( GL_TEXTURE_2D );
779 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
780 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
781 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
782 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
785 #ifdef FG_USE_CLOUDS_3D
786 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
789 glEnable( GL_LIGHTING );
790 glEnable( GL_DEPTH_TEST );
791 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
795 globals->get_model_mgr()->draw();
796 globals->get_aircraft_model()->draw();
799 // display HUD && Panel
801 glDisable( GL_DEPTH_TEST );
802 // glDisable( GL_CULL_FACE );
803 // glDisable( GL_TEXTURE_2D );
805 // update the controls subsystem
806 globals->get_controls()->update(delta_time_sec);
808 hud_and_panel->apply();
811 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
812 // This only works properly if called before the panel call
813 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
814 globals->get_ATC_display()->update(delta_time_sec);
816 // update the panel subsystem
817 if ( globals->get_current_panel() != NULL ) {
818 globals->get_current_panel()->update(delta_time_sec);
822 // We can do translucent menus, so why not. :-)
824 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
826 // glDisable ( GL_BLEND ) ;
828 glEnable( GL_DEPTH_TEST );
831 // Fade out the splash screen over the first three seconds.
832 double t = globals->get_sim_time_sec();
834 fgSplashUpdate(0.0, 1.0);
835 } else if ( t <= 3.0) {
836 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
844 // Update internal time dependent calculations (i.e. flight model)
845 // FIXME: this distinction is obsolete; all subsystems now get delta
847 void fgUpdateTimeDepCalcs() {
848 static bool inited = false;
850 static const SGPropertyNode *replay_master
851 = fgGetNode( "/sim/freeze/replay", true );
852 static SGPropertyNode *replay_time
853 = fgGetNode( "/sim/replay/time", true );
854 static const SGPropertyNode *replay_end_time
855 = fgGetNode( "/sim/replay/end-time", true );
857 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
859 // Initialize the FDM here if it hasn't been and if we have a
860 // scenery elevation hit.
862 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
863 // << " cur_elev = " << scenery.get_cur_elev() << endl;
865 if ( !cur_fdm_state->get_inited() &&
866 globals->get_scenery()->get_cur_elev() > -9990 )
868 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
869 cur_fdm_state->init();
870 if ( cur_fdm_state->get_bound() ) {
871 cur_fdm_state->unbind();
873 cur_fdm_state->bind();
876 // conceptually, the following block could be done for each fdm
878 if ( cur_fdm_state->get_inited() ) {
879 // we have been inited, and we are good to go ...
885 if ( ! replay_master->getBoolValue() ) {
886 globals->get_autopilot()->update( delta_time_sec );
887 cur_fdm_state->update( delta_time_sec );
889 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
890 r->replay( replay_time->getDoubleValue() );
891 replay_time->setDoubleValue( replay_time->getDoubleValue()
893 * fgGetInt("/sim/speed-up") ) );
896 // do nothing, fdm isn't inited yet
899 globals->get_model_mgr()->update(delta_time_sec);
900 globals->get_aircraft_model()->update(delta_time_sec);
902 // update the view angle
903 globals->get_viewmgr()->update(delta_time_sec);
905 // Update solar system
906 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
907 globals->get_time_params()->getLst(),
908 cur_fdm_state->get_Latitude() );
910 // Update radio stack model
911 current_radiostack->update(delta_time_sec);
915 void fgInitTimeDepCalcs( void ) {
920 static const double alt_adjust_ft = 3.758099;
921 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
924 // What should we do when we have nothing else to do? Let's get ready
925 // for the next move and update the display?
926 static void fgMainLoop( void ) {
927 int model_hz = fgGetInt("/sim/model-hz");
929 static const SGPropertyNode *longitude
930 = fgGetNode("/position/longitude-deg");
931 static const SGPropertyNode *latitude
932 = fgGetNode("/position/latitude-deg");
933 static const SGPropertyNode *altitude
934 = fgGetNode("/position/altitude-ft");
935 static const SGPropertyNode *clock_freeze
936 = fgGetNode("/sim/freeze/clock", true);
937 static const SGPropertyNode *cur_time_override
938 = fgGetNode("/sim/time/cur-time-override", true);
939 static const SGPropertyNode *replay_master
940 = fgGetNode("/sim/freeze/replay", true);
942 // Update the elapsed time.
943 static bool first_time = true;
945 last_time_stamp.stamp();
949 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
950 if ( throttle_hz > 0.0 ) {
951 // simple frame rate throttle
952 double dt = 1000000.0 / throttle_hz;
953 current_time_stamp.stamp();
954 while ( current_time_stamp - last_time_stamp < dt ) {
955 current_time_stamp.stamp();
958 // run as fast as the app will go
959 current_time_stamp.stamp();
963 = double(current_time_stamp - last_time_stamp) / 1000000.0;
964 if ( clock_freeze->getBoolValue() ) {
967 delta_time_sec = real_delta_time_sec;
969 last_time_stamp = current_time_stamp;
970 globals->inc_sim_time_sec( delta_time_sec );
971 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
973 static long remainder = 0;
975 #ifdef FANCY_FRAME_COUNTER
979 static time_t last_time = 0;
980 static int frames = 0;
981 #endif // FANCY_FRAME_COUNTER
983 SGTime *t = globals->get_time_params();
985 globals->get_event_mgr()->update(delta_time_sec);
987 SGLocation * acmodel_location = 0;
988 if(cur_fdm_state->getACModel() != 0) {
989 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
992 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
993 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
995 #if defined( ENABLE_PLIB_JOYSTICK )
996 // Read joystick and update control settings
997 // if ( fgGetString("/sim/control-mode") == "joystick" )
1001 #elif defined( ENABLE_GLUT_JOYSTICK )
1002 // Glut joystick support works by feeding a joystick handler
1003 // function to glut. This is taken care of once in the joystick
1004 // init routine and we don't have to worry about it again.
1007 // Fix elevation. I'm just sticking this here for now, it should
1008 // probably move eventually
1010 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1011 scenery.get_cur_elev(),
1012 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1013 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1015 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1016 scenery.get_cur_elev(),
1017 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1018 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1020 // cout << "Warp = " << globals->get_warp() << endl;
1023 static bool last_clock_freeze = false;
1025 if ( clock_freeze->getBoolValue() ) {
1026 // clock freeze requested
1027 if ( cur_time_override->getLongValue() == 0 ) {
1028 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1029 globals->set_warp( 0 );
1032 // no clock freeze requested
1033 if ( last_clock_freeze == true ) {
1034 // clock just unfroze, let's set warp as the difference
1035 // between frozen time and current time so we don't get a
1036 // time jump (and corresponding sky object and lighting
1038 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1039 fgSetLong( "/sim/time/cur-time-override", 0 );
1041 if ( globals->get_warp_delta() != 0 ) {
1042 globals->inc_warp( globals->get_warp_delta() );
1046 last_clock_freeze = clock_freeze->getBoolValue();
1048 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1049 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1050 cur_time_override->getLongValue(),
1051 globals->get_warp() );
1053 if (globals->get_warp_delta() != 0) {
1054 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1058 // update magvar model
1059 globals->get_mag()->update( longitude->getDoubleValue()
1060 * SGD_DEGREES_TO_RADIANS,
1061 latitude->getDoubleValue()
1062 * SGD_DEGREES_TO_RADIANS,
1063 altitude->getDoubleValue() * SG_FEET_TO_METER,
1064 globals->get_time_params()->getJD() );
1066 // Get elapsed time (in usec) for this past frame
1067 elapsed = fgGetTimeInterval();
1068 SG_LOG( SG_ALL, SG_DEBUG,
1069 "Elapsed time interval is = " << elapsed
1070 << ", previous remainder is = " << remainder );
1072 // Calculate frame rate average
1073 #ifdef FANCY_FRAME_COUNTER
1074 /* old fps calculation */
1075 if ( elapsed > 0 ) {
1078 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1079 tmp = general.get_frame(i);
1081 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1082 general.set_frame(i+1,tmp);
1084 tmp = 1000000.0 / (float)elapsed;
1085 general.set_frame(0,tmp);
1086 // printf("frame[0] = %.2f\n", general.frames[0]);
1088 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1089 // printf("ave = %.2f\n", general.frame_rate);
1092 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1093 general.set_frame_rate( frames );
1094 fgSetInt("/sim/frame-rate", frames);
1095 SG_LOG( SG_ALL, SG_DEBUG,
1096 "--> Frame rate is = " << general.get_frame_rate() );
1099 last_time = t->get_cur_time();
1103 // Run ATC subsystem
1104 if (fgGetBool("/sim/ATC/enabled"))
1105 globals->get_ATC_mgr()->update(delta_time_sec);
1107 // Run the AI subsystem
1108 if (fgGetBool("/sim/ai-traffic/enabled"))
1109 globals->get_AI_mgr()->update(delta_time_sec);
1113 // Calculate model iterations needed for next frame
1114 elapsed += remainder;
1116 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1117 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1118 SG_LOG( SG_ALL, SG_DEBUG,
1119 "Model iterations needed = " << global_multi_loop
1120 << ", new remainder = " << remainder );
1122 // chop max interations to something reasonable if the sim was
1123 // delayed for an excesive amount of time
1124 if ( global_multi_loop > 2.0 * model_hz ) {
1125 global_multi_loop = (int)(2.0 * model_hz );
1130 if ( global_multi_loop > 0 ) {
1131 fgUpdateTimeDepCalcs();
1133 SG_LOG( SG_ALL, SG_DEBUG,
1134 "Elapsed time is zero ... we're zinging" );
1137 // Do any I/O channel work that might need to be done
1138 globals->get_io()->update( real_delta_time_sec );
1140 // see if we need to load any deferred-load textures
1141 globals->get_matlib()->load_next_deferred();
1143 // Run audio scheduler
1144 #ifdef ENABLE_AUDIO_SUPPORT
1145 if ( fgGetBool("/sim/sound/audible")
1146 && globals->get_soundmgr()->is_working() ) {
1147 globals->get_soundmgr()->update( delta_time_sec );
1151 globals->get_subsystem_mgr()->update(delta_time_sec);
1154 // Tile Manager updates - see if we need to load any new scenery tiles.
1155 // this code ties together the fdm, viewer and scenery classes...
1156 // we may want to move this to it's own class at some point
1158 double visibility_meters = fgGetDouble("/environment/visibility-m");
1159 FGViewer *current_view = globals->get_current_view();
1161 // update tile manager for FDM...
1162 // ...only if location is different than the viewer (to avoid duplicating effort)
1163 if( acmodel_location != current_view->getSGLocation() ) {
1164 if( acmodel_location != 0 ) {
1165 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1166 visibility_meters );
1167 globals->get_tile_mgr()->
1168 update( acmodel_location, visibility_meters,
1169 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1170 // save results of update in SGLocation for fdm...
1171 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1173 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1176 set_tile_center( globals->get_scenery()->get_next_center() );
1180 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1181 visibility_meters );
1182 // update tile manager for view...
1183 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1184 // after the FDM's until all of Flight Gear code references the viewer's location
1185 // for elevation instead of the "scenery's" current elevation.
1186 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1187 globals->get_tile_mgr()->update( view_location, visibility_meters,
1188 current_view->get_absolute_view_pos() );
1189 // save results of update in SGLocation for fdm...
1190 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1191 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1193 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1195 // If fdm location is same as viewer's then we didn't do the update for fdm location
1196 // above so we need to save the viewer results in the fdm SGLocation as well...
1197 if( acmodel_location == current_view->getSGLocation() ) {
1198 if( acmodel_location != 0 ) {
1199 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1200 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1202 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1206 // END Tile Manager udpates
1208 if (fgGetBool("/sim/rendering/specular-highlight")) {
1209 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1210 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1212 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1213 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1219 SG_LOG( SG_ALL, SG_DEBUG, "" );
1223 // This is the top level master main function that is registered as
1224 // our idle funciton
1226 // The first few passes take care of initialization things (a couple
1227 // per pass) and once everything has been initialized fgMainLoop from
1230 static void fgIdleFunction ( void ) {
1231 // printf("idle state == %d\n", idle_state);
1233 if ( idle_state == 0 ) {
1234 // Initialize the splash screen right away
1235 if ( fgGetBool("/sim/startup/splash-screen") ) {
1240 } else if ( idle_state == 1 ) {
1241 // Initialize audio support
1242 #ifdef ENABLE_AUDIO_SUPPORT
1244 // Start the intro music
1245 if ( fgGetBool("/sim/startup/intro-music") ) {
1246 SGPath mp3file( globals->get_fg_root() );
1247 mp3file.append( "Sounds/intro.mp3" );
1249 SG_LOG( SG_GENERAL, SG_INFO,
1250 "Starting intro music: " << mp3file.str() );
1252 #if defined( __CYGWIN__ )
1253 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1254 #elif defined( WIN32 )
1255 string command = "start /m " + mp3file.str();
1257 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1260 system ( command.c_str() );
1265 } else if ( idle_state == 2 ) {
1266 // These are a few miscellaneous things that aren't really
1267 // "subsystems" but still need to be initialized.
1270 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1271 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1276 } else if ( idle_state == 3 ) {
1277 // This is the top level init routine which calls all the
1278 // other subsystem initialization routines. If you are adding
1279 // a subsystem to flightgear, its initialization call should
1280 // located in this routine.
1281 if( !fgInitSubsystems()) {
1282 SG_LOG( SG_GENERAL, SG_ALERT,
1283 "Subsystem initializations failed ..." );
1288 } else if ( idle_state == 4 ) {
1289 // Initialize the time offset (warp) after fgInitSubsystem
1290 // (which initializes the lighting interpolation tables.)
1293 // setup OpenGL view parameters
1296 // Read the list of available aircrafts
1300 } else if ( idle_state == 5 ) {
1303 } else if ( idle_state == 6 ) {
1308 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1309 fgReshape( fgGetInt("/sim/startup/xsize"),
1310 fgGetInt("/sim/startup/ysize") );
1314 if ( idle_state == 1000 ) {
1315 // We've finished all our initialization steps, from now on we
1316 // run the main loop.
1318 glutIdleFunc(fgMainLoop);
1320 if ( fgGetBool("/sim/startup/splash-screen") ) {
1321 fgSplashUpdate(0.0, 1.0);
1326 // options.cxx needs to see this for toggle_panel()
1327 // Handle new window size or exposure
1328 void fgReshape( int width, int height ) {
1331 if ( (!fgGetBool("/sim/virtual-cockpit"))
1332 && fgPanelVisible() && idle_state == 1000 ) {
1333 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1334 globals->get_current_panel()->getYOffset()) / 768.0);
1340 FGViewMgr *viewmgr = globals->get_viewmgr();
1341 for ( int i = 0; i < viewmgr->size(); ++i ) {
1342 viewmgr->get_view(i)->
1343 set_aspect_ratio((float)view_h / (float)width);
1346 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1348 fgSetInt("/sim/startup/xsize", width);
1349 fgSetInt("/sim/startup/ysize", height);
1350 guiInitMouse(width, height);
1352 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1353 viewmgr->get_current_view()->get_v_fov() );
1357 #ifdef FG_USE_CLOUDS_3D
1358 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1359 viewmgr->get_current_view()->get_v_fov() );
1364 // Initialize GLUT and define a main window
1365 static bool fgGlutInit( int *argc, char **argv ) {
1367 #if !defined( macintosh )
1368 // GLUT will extract all glut specific options so later on we only
1369 // need wory about our own.
1370 glutInit(argc, argv);
1373 // Define Display Parameters. Clouds3d works best with --bpp32 option
1374 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1375 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1377 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1380 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1381 fgGetInt("/sim/startup/xsize") << "x"
1382 << fgGetInt("/sim/startup/ysize") );
1384 // Define initial window size
1385 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1386 fgGetInt("/sim/startup/ysize") );
1388 // Initialize windows
1389 if ( !fgGetBool("/sim/startup/game-mode")) {
1390 // Open the regular window
1391 glutCreateWindow("FlightGear");
1392 #ifndef GLUT_WRONG_VERSION
1394 // Open the cool new 'game mode' window
1395 char game_mode_str[256];
1396 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1397 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1398 #ifndef ENUM_CURRENT_SETTINGS
1399 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1400 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1404 dm.dmSize = sizeof(DEVMODE);
1405 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1406 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1407 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1408 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1409 fgGetInt("/sim/startup/ysize") );
1410 sprintf( game_mode_str, "%dx%d:%d@%d",
1414 dm.dmDisplayFrequency );
1416 // Open the cool new 'game mode' window
1417 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1418 fgGetInt("/sim/startup/xsize"),
1419 fgGetInt("/sim/startup/ysize"),
1420 fgGetInt("/sim/rendering/bits-per-pixel"));
1422 #endif // HAVE_WINDOWS_H
1423 SG_LOG( SG_GENERAL, SG_INFO,
1424 "game mode params = " << game_mode_str );
1425 glutGameModeString( game_mode_str );
1426 glutEnterGameMode();
1427 #endif // GLUT_WRONG_VERSION
1430 // This seems to be the absolute earliest in the init sequence
1431 // that these calls will return valid info. Too bad it's after
1432 // we've already created and sized out window. :-(
1433 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1434 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1435 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1436 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1439 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1440 general.set_glMaxTexSize( tmp );
1441 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1443 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1444 general.set_glDepthBits( tmp );
1445 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1451 // Initialize GLUT event handlers
1452 static bool fgGlutInitEvents( void ) {
1453 // call fgReshape() on window resizes
1454 glutReshapeFunc( fgReshape );
1456 // keyboard and mouse callbacks are set in FGInput::init
1458 // call fgMainLoop() whenever there is
1459 // nothing else to do
1460 glutIdleFunc( fgIdleFunction );
1463 glutDisplayFunc( fgRenderFrame );
1468 // Main top level initialization
1469 bool fgMainInit( int argc, char **argv ) {
1471 #if defined( macintosh )
1472 freopen ("stdout.txt", "w", stdout );
1473 freopen ("stderr.txt", "w", stderr );
1474 argc = ccommand( &argv );
1477 // set default log levels
1478 sglog().setLogLevels( SG_ALL, SG_ALERT );
1481 #ifdef FLIGHTGEAR_VERSION
1482 version = FLIGHTGEAR_VERSION;
1484 version = "unknown version";
1486 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1488 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1490 // Allocate global data structures. This needs to happen before
1491 // we parse command line options
1493 globals = new FGGlobals;
1495 // seed the random number generater
1498 SGRoute *route = new SGRoute;
1499 globals->set_route( route );
1501 FGControls *controls = new FGControls;
1502 globals->set_controls( controls );
1504 string_list *col = new string_list;
1505 globals->set_channel_options_list( col );
1507 // Scan the config file(s) and command line options to see if
1508 // fg_root was specified (ignore all other options for now)
1509 fgInitFGRoot(argc, argv);
1511 // Check for the correct base package version
1512 static char required_version[] = "0.9.3";
1513 string base_version = fgBasePackageVersion();
1514 if ( !(base_version == required_version) ) {
1515 // tell the operator how to use this application
1517 cerr << endl << "Base package check failed ... " \
1518 << "Found version " << base_version << " at: " \
1519 << globals->get_fg_root() << endl;
1520 cerr << "Please upgrade to version: " << required_version << endl;
1524 // Initialize the Aircraft directory to "" (UIUC)
1527 // Load the configuration parameters. (Command line options
1528 // overrides config file options. Config file options override
1530 if ( !fgInitConfig(argc, argv) ) {
1531 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1535 // Initialize the Window/Graphics environment.
1536 if( !fgGlutInit(&argc, argv) ) {
1537 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1541 // Initialize the various GLUT Event Handlers.
1542 if( !fgGlutInitEvents() ) {
1543 SG_LOG( SG_GENERAL, SG_ALERT,
1544 "GLUT event handler initialization failed ..." );
1548 // Initialize plib net interface
1549 netInit( &argc, argv );
1551 // Initialize ssg (from plib). Needs to come before we do any
1552 // other ssg stuff, but after opengl/glut has been initialized.
1555 // Initialize the user interface (we need to do this before
1556 // passing off control to glut and before fgInitGeneral to get our
1560 // Read the list of available aircrafts
1563 #ifdef GL_EXT_texture_lod_bias
1564 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1567 // get the address of our OpenGL extensions
1568 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1570 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1571 glPointParameterIsSupported = true;
1572 glPointParameterfPtr = (glPointParameterfProc)
1573 SGLookupFunction("glPointParameterfEXT");
1574 glPointParameterfvPtr = (glPointParameterfvProc)
1575 SGLookupFunction("glPointParameterfvEXT");
1577 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1578 glPointParameterIsSupported = true;
1579 glPointParameterfPtr = (glPointParameterfProc)
1580 SGLookupFunction("glPointParameterfARB");
1581 glPointParameterfvPtr = (glPointParameterfvProc)
1582 SGLookupFunction("glPointParameterfvARB");
1584 glPointParameterIsSupported = false;
1587 // based on the requested presets, calculate the true starting
1592 SGTime *t = fgInitTime();
1593 globals->set_time_params( t );
1595 // Do some quick general initializations
1596 if( !fgInitGeneral()) {
1597 SG_LOG( SG_GENERAL, SG_ALERT,
1598 "General initializations failed ..." );
1602 ////////////////////////////////////////////////////////////////////
1603 // Initialize the property-based built-in commands
1604 ////////////////////////////////////////////////////////////////////
1607 ////////////////////////////////////////////////////////////////////
1608 // Initialize the material manager
1609 ////////////////////////////////////////////////////////////////////
1610 globals->set_matlib( new SGMaterialLib );
1612 globals->set_model_lib(new SGModelLib);
1614 ////////////////////////////////////////////////////////////////////
1615 // Initialize the TG scenery subsystem.
1616 ////////////////////////////////////////////////////////////////////
1617 globals->set_scenery( new FGScenery );
1618 globals->get_scenery()->init();
1619 globals->get_scenery()->bind();
1620 globals->set_tile_mgr( new FGTileMgr );
1622 ////////////////////////////////////////////////////////////////////
1623 // Initialize the general model subsystem.
1624 ////////////////////////////////////////////////////////////////////
1625 globals->set_model_mgr(new FGModelMgr);
1626 globals->get_model_mgr()->init();
1627 globals->get_model_mgr()->bind();
1629 ////////////////////////////////////////////////////////////////////
1630 // Initialize the 3D aircraft model subsystem (has a dependency on
1631 // the scenery subsystem.)
1632 ////////////////////////////////////////////////////////////////////
1633 globals->set_aircraft_model(new FGAircraftModel);
1634 globals->get_aircraft_model()->init();
1635 globals->get_aircraft_model()->bind();
1637 ////////////////////////////////////////////////////////////////////
1638 // Initialize the view manager subsystem.
1639 ////////////////////////////////////////////////////////////////////
1640 FGViewMgr *viewmgr = new FGViewMgr;
1641 globals->set_viewmgr( viewmgr );
1646 // Initialize the sky
1647 SGPath ephem_data_path( globals->get_fg_root() );
1648 ephem_data_path.append( "Astro" );
1649 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1650 ephem->update( globals->get_time_params()->getMjd(),
1651 globals->get_time_params()->getLst(),
1653 globals->set_ephem( ephem );
1655 // TODO: move to environment mgr
1657 SGPath texture_path(globals->get_fg_root());
1658 texture_path.append("Textures");
1659 texture_path.append("Sky");
1660 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1661 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1662 thesky->add_cloud_layer(layer);
1665 SGPath sky_tex_path( globals->get_fg_root() );
1666 sky_tex_path.append( "Textures" );
1667 sky_tex_path.append( "Sky" );
1668 thesky->texture_path( sky_tex_path.str() );
1670 // The sun and moon diameters are scaled down numbers of the
1671 // actual diameters. This was needed to fit bot the sun and the
1672 // moon within the distance to the far clip plane.
1673 // Moon diameter: 3,476 kilometers
1674 // Sun diameter: 1,390,000 kilometers
1675 thesky->build( 80000.0, 80000.0,
1677 globals->get_ephem()->getNumPlanets(),
1678 globals->get_ephem()->getPlanets(),
1679 globals->get_ephem()->getNumStars(),
1680 globals->get_ephem()->getStars() );
1682 // Initialize MagVar model
1683 SGMagVar *magvar = new SGMagVar();
1684 globals->set_mag( magvar );
1687 // kludge to initialize mag compass
1688 // (should only be done for in-flight
1690 // update magvar model
1691 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1692 * SGD_DEGREES_TO_RADIANS,
1693 fgGetDouble("/position/latitude-deg")
1694 * SGD_DEGREES_TO_RADIANS,
1695 fgGetDouble("/position/altitude-ft")
1697 globals->get_time_params()->getJD() );
1698 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1699 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1701 // airport = new ssgBranch;
1702 // airport->setName( "Airport Lighting" );
1703 // lighting->addKid( airport );
1705 // build our custom render states
1706 fgBuildRenderStates();
1708 // pass control off to the master GLUT event handler
1711 // we never actually get here ... but to avoid compiler warnings,