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 #if defined(__linux__) && defined(__i386__)
29 # include <fpu_control.h>
33 #include <simgear/compiler.h>
39 #include <simgear/misc/exception.hxx>
40 #include <simgear/ephemeris/ephemeris.hxx>
41 #include <simgear/route/route.hxx>
42 #include <simgear/screen/extensions.hxx>
44 #include <Environment/environment_mgr.hxx>
46 #ifdef SG_MATH_EXCEPTION_CLASH
58 #include <string.h> // for strcmp()
65 #ifdef HAVE_SYS_STAT_H
66 # include <sys/stat.h> // for stat()
70 # include <unistd.h> // for stat()
73 #include <plib/netChat.h>
78 #include <simgear/constants.h> // for VERSION
79 #include <simgear/debug/logstream.hxx>
80 #include <simgear/math/polar3d.hxx>
81 #include <simgear/math/sg_random.h>
82 #include <simgear/misc/sg_path.hxx>
83 #include <simgear/scene/material/matlib.hxx>
84 #include <simgear/scene/model/animation.hxx>
85 #include <simgear/scene/model/location.hxx>
86 #include <simgear/scene/model/model.hxx>
87 #include <simgear/scene/model/modellib.hxx>
88 #ifdef FG_USE_CLOUDS_3D
89 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
90 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
92 #include <simgear/scene/sky/sky.hxx>
93 #include <simgear/timing/sg_time.hxx>
95 #include <Include/general.hxx>
97 #include <Aircraft/aircraft.hxx>
99 #include <ATC/ATCmgr.hxx>
100 #include <ATC/ATCdisplay.hxx>
101 #include <ATC/AIMgr.hxx>
103 #include <Autopilot/newauto.hxx>
105 #include <Cockpit/hud.hxx>
106 #include <Cockpit/cockpit.hxx>
107 #include <Cockpit/radiostack.hxx>
109 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
111 #include <Model/acmodel.hxx>
112 #include <Model/modelmgr.hxx>
113 #include <Model/panelnode.hxx>
114 #ifdef FG_NETWORK_OLK
115 #include <NetworkOLK/network.h>
119 #include <MultiPlayer/multiplaytxmgr.hxx>
120 #include <MultiPlayer/multiplayrxmgr.hxx>
123 #include <Scenery/scenery.hxx>
124 #include <Scenery/tilemgr.hxx>
125 #ifdef ENABLE_AUDIO_SUPPORT
126 # include <Sound/fg_fx.hxx>
127 # include <Sound/morse.hxx>
129 #include <Systems/system_mgr.hxx>
130 #include <Instrumentation/instrument_mgr.hxx>
131 #include <Time/FGEventMgr.hxx>
132 #include <Time/fg_timer.hxx>
133 #include <Time/light.hxx>
134 #include <Time/sunpos.hxx>
135 #include <Time/tmp.hxx>
138 #include <simgear/misc/sgstream.hxx>
139 #include <simgear/math/point3d.hxx>
140 #include <FDM/flight.hxx>
141 #include <FDM/ADA.hxx>
142 #include <Scenery/tileentry.hxx>
144 #include "fg_commands.hxx"
146 glPointParameterfProc glPointParameterfPtr = 0;
147 glPointParameterfvProc glPointParameterfvPtr = 0;
149 float default_attenuation[3] = {1.0, 0.0, 0.0};
150 //Required for using GL_extensions
151 void fgLoadDCS (void);
152 void fgUpdateDCS (void);
153 ssgSelector *ship_sel=NULL;
154 // upto 32 instances of a same object can be loaded.
155 ssgTransform *ship_pos[32];
156 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
158 ssgSelector *lightpoints_brightness = new ssgSelector;
159 ssgTransform *lightpoints_transform = new ssgTransform;
160 FGTileEntry *dummy_tile;
163 // Clip plane settings...
164 float scene_nearplane = 0.5f;
165 float scene_farplane = 120000.0f;
167 static double delta_time_sec = 0;
171 # include <WeatherCM/FGLocalWeatherDatabase.h>
176 #include "fg_init.hxx"
178 #include "fg_props.hxx"
179 #include "globals.hxx"
180 #include "splash.hxx"
181 #include "viewmgr.hxx"
182 #include "options.hxx"
183 #include "logger.hxx"
186 # include <console.h> // -dw- for command line dialog
190 FGEventMgr global_events;
192 // This is a record containing a bit of global housekeeping information
195 // Specify our current idle function state. This is used to run all
196 // our initializations out of the glutIdleLoop() so that we can get a
197 // splash screen up and running right away.
198 static int idle_state = 0;
199 static long global_multi_loop;
201 // fog constants. I'm a little nervous about putting actual code out
202 // here but it seems to work (?)
203 static const double m_log01 = -log( 0.01 );
204 static const double sqrt_m_log01 = sqrt( m_log01 );
205 static GLfloat fog_exp_density;
206 static GLfloat fog_exp2_density;
207 static GLfloat rwy_exp2_punch_through;
208 static GLfloat taxi_exp2_punch_through;
209 static GLfloat ground_exp2_punch_through;
211 #ifdef FG_NETWORK_OLK
212 ssgSelector *fgd_sel = NULL;
213 ssgTransform *fgd_pos = NULL;
219 #ifdef FG_USE_CLOUDS_3D
220 SkySceneLoader *sgClouds3d;
221 bool _bcloud_orig = true;
225 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
227 { 1.0f, 0.0f, 0.0f, 0.0f },
228 { 0.0f, 0.0f, -1.0f, 0.0f },
229 { 0.0f, 1.0f, 0.0f, 0.0f },
230 { 0.0f, 0.0f, 0.0f, 1.0f }
233 // The following defines flightgear options. Because glutlib will also
234 // want to parse its own options, those options must not be included here
235 // or they will get parsed by the main program option parser. Hence case
236 // is significant for any option added that might be in conflict with
239 // glutlib parses for:
241 // -direct (invalid in Win32)
245 // -indirect (invalid in Win32)
248 // Note that glutlib depends upon strings while this program's
249 // option parser wants only initial characters followed by numbers
254 ssgSimpleState *cloud3d_imposter_state;
255 ssgSimpleState *default_state;
256 ssgSimpleState *hud_and_panel;
257 ssgSimpleState *menus;
259 SGTimeStamp last_time_stamp;
260 SGTimeStamp current_time_stamp;
263 void fgBuildRenderStates( void ) {
264 default_state = new ssgSimpleState;
265 default_state->ref();
266 default_state->disable( GL_TEXTURE_2D );
267 default_state->enable( GL_CULL_FACE );
268 default_state->enable( GL_COLOR_MATERIAL );
269 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
270 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
271 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
272 default_state->disable( GL_BLEND );
273 default_state->disable( GL_ALPHA_TEST );
274 default_state->disable( GL_LIGHTING );
276 cloud3d_imposter_state = new ssgSimpleState;
277 cloud3d_imposter_state->ref();
278 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
279 cloud3d_imposter_state->enable( GL_CULL_FACE );
280 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
281 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
282 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
283 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
284 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
285 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
286 cloud3d_imposter_state->enable( GL_BLEND );
287 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
288 cloud3d_imposter_state->disable( GL_LIGHTING );
290 hud_and_panel = new ssgSimpleState;
291 hud_and_panel->ref();
292 hud_and_panel->disable( GL_CULL_FACE );
293 hud_and_panel->disable( GL_TEXTURE_2D );
294 hud_and_panel->disable( GL_LIGHTING );
295 hud_and_panel->enable( GL_BLEND );
297 menus = new ssgSimpleState;
299 menus->disable( GL_CULL_FACE );
300 menus->disable( GL_TEXTURE_2D );
301 menus->enable( GL_BLEND );
305 // fgInitVisuals() -- Initialize various GL/view parameters
306 void fgInitVisuals( void ) {
309 l = &cur_light_params;
311 #ifndef GLUT_WRONG_VERSION
312 // Go full screen if requested ...
313 if ( fgGetBool("/sim/startup/fullscreen") ) {
318 // If enabled, normal vectors specified with glNormal are scaled
319 // to unit length after transformation. Enabling this has
320 // performance implications. See the docs for glNormal.
321 // glEnable( GL_NORMALIZE );
323 glEnable( GL_LIGHTING );
324 glEnable( GL_LIGHT0 );
325 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
328 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
329 ssgGetLight( 0 ) -> setPosition( sunpos );
331 glFogi (GL_FOG_MODE, GL_EXP2);
332 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
333 (!fgGetBool("/sim/rendering/shading"))) {
334 // if fastest fog requested, or if flat shading force fastest
335 glHint ( GL_FOG_HINT, GL_FASTEST );
336 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
337 glHint ( GL_FOG_HINT, GL_NICEST );
339 if ( fgGetBool("/sim/rendering/wireframe") ) {
341 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
344 // This is the default anyways, but it can't hurt
345 glFrontFace ( GL_CCW );
348 // glEnable(GL_POINT_SMOOTH);
349 // glEnable(GL_LINE_SMOOTH);
350 // glEnable(GL_POLYGON_SMOOTH);
354 // For HiRes screen Dumps using Brian Pauls TR Library
355 void trRenderFrame( void ) {
357 if ( fgPanelVisible() ) {
358 GLfloat height = fgGetInt("/sim/startup/ysize");
360 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
361 * (height / 768.0) + 1;
362 glTranslatef( 0.0, view_h, 0.0 );
365 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
366 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
368 fgLIGHT *l = &cur_light_params;
370 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
371 l->adj_fog_color[2], l->adj_fog_color[3]);
373 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
375 // set the opengl state to known default values
376 default_state->force();
379 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
380 glFogi ( GL_FOG_MODE, GL_EXP2 );
381 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
383 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
384 // we only update GL_AMBIENT for our lights we will never get
385 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
386 // explicitely to black.
387 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
388 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
390 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
392 // texture parameters
393 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
394 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
396 // we need a white diffuse light for the phase of the moon
397 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
400 // draw the ssg scene
401 // return to the desired diffuse color
402 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
403 glEnable( GL_DEPTH_TEST );
404 ssgSetNearFar( scene_nearplane, scene_farplane );
405 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
408 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
409 ssgSetNearFar( scene_nearplane, scene_farplane );
410 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
412 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
414 if (fgGetBool("/environment/clouds/status"))
415 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
417 globals->get_model_mgr()->draw();
418 globals->get_aircraft_model()->draw();
422 // Update all Visuals (redraws anything graphics related)
423 void fgRenderFrame() {
425 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
426 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
428 // Process/manage pending events
429 global_events.update( delta_time_sec );
431 // static const SGPropertyNode *longitude
432 // = fgGetNode("/position/longitude-deg");
433 // static const SGPropertyNode *latitude
434 // = fgGetNode("/position/latitude-deg");
435 // static const SGPropertyNode *altitude
436 // = fgGetNode("/position/altitude-ft");
437 static const SGPropertyNode *groundlevel_nearplane
438 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
440 // Update the default (kludged) properties.
443 FGViewer *current__view = globals->get_current_view();
445 fgLIGHT *l = &cur_light_params;
446 static double last_visibility = -9999;
449 double actual_visibility;
450 if (fgGetBool("/environment/clouds/status"))
451 actual_visibility = thesky->get_visibility();
453 actual_visibility = fgGetDouble("/environment/visibility-m");
454 if ( actual_visibility != last_visibility ) {
455 last_visibility = actual_visibility;
457 fog_exp_density = m_log01 / actual_visibility;
458 fog_exp2_density = sqrt_m_log01 / actual_visibility;
459 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
460 if ( actual_visibility < 8000 ) {
461 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
462 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
464 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
465 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
470 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
471 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
472 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
473 // GLfloat mat_shininess[] = { 10.0 };
474 GLbitfield clear_mask;
476 if ( idle_state != 1000 ) {
477 // still initializing, draw the splash screen
478 if ( fgGetBool("/sim/startup/splash-screen") ) {
479 fgSplashUpdate(0.0, 1.0);
481 // Keep resetting sim time while the sim is initializing
482 globals->set_sim_time_sec( 0.0 );
483 SGAnimation::set_sim_time_sec( 0.0 );
485 // idle_state is now 1000 meaning we've finished all our
486 // initializations and are running the main loop, so this will
487 // now work without seg faulting the system.
489 // calculate our current position in cartesian space
490 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
493 fgReshape( fgGetInt("/sim/startup/xsize"),
494 fgGetInt("/sim/startup/ysize") );
496 if ( fgGetBool("/sim/rendering/clouds3d") ) {
497 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
498 cloud3d_imposter_state->force();
500 glColor4f( 1.0, 1.0, 1.0, 1.0 );
501 glEnable(GL_DEPTH_TEST);
503 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
505 #ifdef FG_USE_CLOUDS_3D
506 if ( _bcloud_orig ) {
507 Point3D c = globals->get_scenery()->get_center();
508 sgClouds3d->Set_Cloud_Orig( &c );
509 _bcloud_orig = false;
511 sgClouds3d->Update( current__view->get_absolute_view_pos() );
513 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
514 glDisable(GL_DEPTH_TEST);
517 clear_mask = GL_DEPTH_BUFFER_BIT;
518 if ( fgGetBool("/sim/rendering/wireframe") ) {
519 clear_mask |= GL_COLOR_BUFFER_BIT;
522 if ( fgGetBool("/sim/rendering/skyblend") ) {
523 if ( fgGetBool("/sim/rendering/textures") ) {
524 // glClearColor(black[0], black[1], black[2], black[3]);
525 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
526 l->adj_fog_color[2], l->adj_fog_color[3]);
527 clear_mask |= GL_COLOR_BUFFER_BIT;
530 glClearColor(l->sky_color[0], l->sky_color[1],
531 l->sky_color[2], l->sky_color[3]);
532 clear_mask |= GL_COLOR_BUFFER_BIT;
534 glClear( clear_mask );
536 // Tell GL we are switching to model view parameters
538 // I really should create a derived ssg node or use a call
539 // back or something so that I can draw the sky within the
540 // ssgCullAndDraw() function, but for now I just mimic what
541 // ssg does to set up the model view matrix
542 glMatrixMode(GL_MODELVIEW);
544 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
546 // set the opengl state to known default values
547 default_state->force();
549 // update fog params if visibility has changed
550 double visibility_meters = fgGetDouble("/environment/visibility-m");
551 thesky->set_visibility(visibility_meters);
553 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
554 ( global_multi_loop * fgGetInt("/sim/speed-up") )
555 / (double)fgGetInt("/sim/model-hz") );
557 // Set correct opengl fog density
558 glFogf (GL_FOG_DENSITY, fog_exp2_density);
560 // update the sky dome
561 if ( fgGetBool("/sim/rendering/skyblend") ) {
563 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
564 << cur_light_params.sky_color[0] << " "
565 << cur_light_params.sky_color[1] << " "
566 << cur_light_params.sky_color[2] << " "
567 << cur_light_params.sky_color[3] );
568 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
569 << cur_light_params.fog_color[0] << " "
570 << cur_light_params.fog_color[1] << " "
571 << cur_light_params.fog_color[2] << " "
572 << cur_light_params.fog_color[3] );
573 SG_LOG( SG_GENERAL, SG_BULK,
574 " sun_angle = " << cur_light_params.sun_angle
575 << " moon_angle = " << cur_light_params.moon_angle );
577 thesky->repaint( cur_light_params.sky_color,
578 cur_light_params.adj_fog_color,
579 cur_light_params.cloud_color,
580 cur_light_params.sun_angle,
581 cur_light_params.moon_angle,
582 globals->get_ephem()->getNumPlanets(),
583 globals->get_ephem()->getPlanets(),
584 globals->get_ephem()->getNumStars(),
585 globals->get_ephem()->getStars() );
588 SG_LOG( SG_GENERAL, SG_BULK,
589 "thesky->reposition( view_pos = " << view_pos[0] << " "
590 << view_pos[1] << " " << view_pos[2] );
591 SG_LOG( SG_GENERAL, SG_BULK,
592 " zero_elev = " << zero_elev[0] << " "
593 << zero_elev[1] << " " << zero_elev[2]
594 << " lon = " << cur_fdm_state->get_Longitude()
595 << " lat = " << cur_fdm_state->get_Latitude() );
596 SG_LOG( SG_GENERAL, SG_BULK,
597 " sun_rot = " << cur_light_params.sun_rotation
598 << " gst = " << SGTime::cur_time_params->getGst() );
599 SG_LOG( SG_GENERAL, SG_BULK,
600 " sun ra = " << globals->get_ephem()->getSunRightAscension()
601 << " sun dec = " << globals->get_ephem()->getSunDeclination()
602 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
603 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
606 // The sun and moon distances are scaled down versions
607 // of the actual distance to get both the moon and the sun
608 // within the range of the far clip plane.
609 // Moon distance: 384,467 kilometers
610 // Sun distance: 150,000,000 kilometers
611 double sun_horiz_eff, moon_horiz_eff;
612 if (fgGetBool("/sim/rendering/horizon-effect")) {
613 sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
614 moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
616 sun_horiz_eff = moon_horiz_eff = 1.0;
618 thesky->reposition( current__view->get_view_pos(),
619 current__view->get_zero_elev(),
620 current__view->get_world_up(),
621 current__view->getLongitude_deg()
622 * SGD_DEGREES_TO_RADIANS,
623 current__view->getLatitude_deg()
624 * SGD_DEGREES_TO_RADIANS,
625 current__view->getAltitudeASL_ft()
627 cur_light_params.sun_rotation,
628 globals->get_time_params()->getGst(),
629 globals->get_ephem()->getSunRightAscension(),
630 globals->get_ephem()->getSunDeclination(),
631 50000.0 * sun_horiz_eff,
632 globals->get_ephem()->getMoonRightAscension(),
633 globals->get_ephem()->getMoonDeclination(),
634 40000.0 * moon_horiz_eff );
637 glEnable( GL_DEPTH_TEST );
638 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
640 glFogi( GL_FOG_MODE, GL_EXP2 );
641 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
644 // set sun/lighting parameters
645 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
647 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
648 // we only update GL_AMBIENT for our lights we will never get
649 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
650 // explicitely to black.
651 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
653 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
654 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
655 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
657 // texture parameters
658 // glEnable( GL_TEXTURE_2D );
659 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
660 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
662 // glMatrixMode( GL_PROJECTION );
664 ssgSetFOV( current__view->get_h_fov(),
665 current__view->get_v_fov() );
668 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
669 - globals->get_scenery()->get_cur_elev();
672 scene_nearplane = 10.0f;
673 scene_farplane = 120000.0f;
675 scene_nearplane = groundlevel_nearplane->getDoubleValue();
676 scene_farplane = 120000.0f;
679 ssgSetNearFar( scene_nearplane, scene_farplane );
681 // $$$ begin - added VS Renganthan 17 Oct 2K
684 // $$$ end - added VS Renganthan 17 Oct 2K
686 # ifdef FG_NETWORK_OLK
687 if ( fgGetBool("/sim/networking/network-olk") ) {
689 other = head->next; /* put listpointer to start */
690 while ( other != tail) { /* display all except myself */
691 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
692 other->fgd_sel->select(1);
693 sgSetCoord( &fgdpos, other->sgFGD_COORD );
694 other->fgd_pos->setTransform( &fgdpos );
699 // fgd_sel->select(1);
700 // sgCopyMat4( sgTUX, current_view.sgVIEW);
702 // sgSetCoord( &fgdpos, sgFGD_VIEW );
703 // fgd_pos->setTransform( &fgdpos);
708 // Update any multiplayer models
709 globals->get_multiplayer_rx_mgr()->Update();
712 if ( fgGetBool("/sim/rendering/skyblend") &&
713 fgGetBool("/sim/rendering/draw-otw") )
715 // draw the sky backdrop
717 // we need a white diffuse light for the phase of the moon
718 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
722 // return to the desired diffuse color
723 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
726 // draw the ssg scene
727 glEnable( GL_DEPTH_TEST );
729 ssgSetNearFar( scene_nearplane, scene_farplane );
731 if ( fgGetBool("/sim/rendering/wireframe") ) {
733 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
735 if ( fgGetBool("/sim/rendering/draw-otw") ) {
736 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
739 // This is a bit kludgy. Every 200 frames, do an extra
740 // traversal of the scene graph without drawing anything, but
741 // with the field-of-view set to 360x360 degrees. This
742 // ensures that out-of-range random objects that are not in
743 // the current view frustum will still be freed properly.
744 static int counter = 0;
746 if (counter == 200) {
749 // No need to put the near plane too close;
750 // this way, at least the aircraft can be
752 f.setNearFar(1000, 1000000);
754 ssgGetModelviewMatrix(m);
755 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
759 // change state for lighting here
761 // draw runway lighting
762 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
763 ssgSetNearFar( scene_nearplane, scene_farplane );
765 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
767 // Enable states for drawing points with GL_extension
768 glEnable(GL_POINT_SMOOTH);
770 if ( fgGetBool("/sim/rendering/distance-attenuation") &&
771 ( SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ||
772 SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) )
774 // Enable states for drawing points with GL_extension
775 glEnable(GL_POINT_SMOOTH);
777 float quadratic[3] = {1.0, 0.001, 0.0000001};
778 // makes the points fade as they move away
779 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
780 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
785 // blending function for runway lights
786 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
789 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
790 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
791 glEnable(GL_TEXTURE_GEN_S);
792 glEnable(GL_TEXTURE_GEN_T);
793 glPolygonMode(GL_FRONT, GL_POINT);
795 // draw runway lighting
796 if ( fgGetBool("/sim/rendering/draw-otw") ) {
797 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
800 // change punch through and then draw taxi lighting
801 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
803 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
804 // glFogfv ( GL_FOG_COLOR, taxi_fog );
805 if ( fgGetBool("/sim/rendering/draw-otw") ) {
806 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
810 glPolygonMode(GL_FRONT, GL_FILL);
811 glDisable(GL_TEXTURE_GEN_S);
812 glDisable(GL_TEXTURE_GEN_T);
814 //static int _frame_count = 0;
815 //if (_frame_count % 30 == 0) {
816 // printf("SSG: %s\n", ssgShowStats());
824 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
825 if ( fgGetBool("/sim/rendering/distance-attenuation") &&
826 ( SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ||
827 SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) )
829 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
830 default_attenuation);
834 glDisable(GL_POINT_SMOOTH);
837 // draw ground lighting
838 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
839 if ( fgGetBool("/sim/rendering/draw-otw") ) {
840 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
843 if ( fgGetBool("/sim/rendering/skyblend") ) {
844 // draw the sky cloud layers
845 if ( fgGetBool("/environment/clouds/status") &&
846 fgGetBool("/sim/rendering/draw-otw") )
848 thesky->postDraw( cur_fdm_state->get_Altitude()
849 * SG_FEET_TO_METER );
853 if ( fgGetBool("/sim/rendering/clouds3d") &&
854 fgGetBool("/sim/rendering/draw-otw") )
857 glDisable( GL_LIGHTING );
858 // cout << "drawing new clouds" << endl;
860 glEnable(GL_DEPTH_TEST);
862 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
865 glEnable( GL_TEXTURE_2D );
866 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
867 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
868 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
869 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
872 #ifdef FG_USE_CLOUDS_3D
873 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
876 glEnable( GL_LIGHTING );
877 glEnable( GL_DEPTH_TEST );
878 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
881 if ( fgGetBool("/sim/rendering/draw-otw") ) {
882 globals->get_model_mgr()->draw();
883 globals->get_aircraft_model()->draw();
886 // display HUD && Panel
888 glDisable( GL_DEPTH_TEST );
889 // glDisable( GL_CULL_FACE );
890 // glDisable( GL_TEXTURE_2D );
892 // update the controls subsystem
893 globals->get_controls()->update(delta_time_sec);
895 hud_and_panel->apply();
898 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
899 // This only works properly if called before the panel call
900 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
901 globals->get_ATC_display()->update(delta_time_sec);
903 // update the panel subsystem
904 if ( globals->get_current_panel() != NULL ) {
905 globals->get_current_panel()->update(delta_time_sec);
909 // We can do translucent menus, so why not. :-)
911 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
913 // glDisable ( GL_BLEND ) ;
915 glEnable( GL_DEPTH_TEST );
918 // Fade out the splash screen over the first three seconds.
919 double t = globals->get_sim_time_sec();
921 fgSplashUpdate(0.0, 1.0);
922 } else if ( t <= 3.0) {
923 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
931 // Update internal time dependent calculations (i.e. flight model)
932 // FIXME: this distinction is obsolete; all subsystems now get delta
934 void fgUpdateTimeDepCalcs() {
935 static bool inited = false;
937 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
939 fgLIGHT *l = &cur_light_params;
941 // Initialize the FDM here if it hasn't been and if we have a
942 // scenery elevation hit.
944 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
945 // << " cur_elev = " << scenery.get_cur_elev() << endl;
947 if ( !cur_fdm_state->get_inited() &&
948 globals->get_scenery()->get_cur_elev() > -9990 )
950 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
951 cur_fdm_state->init();
952 if ( cur_fdm_state->get_bound() ) {
953 cur_fdm_state->unbind();
955 cur_fdm_state->bind();
958 // conceptually, the following block could be done for each fdm
960 if ( !cur_fdm_state->get_inited() ) {
961 // do nothing, fdm isn't inited yet
963 // we have been inited, and we are good to go ...
969 globals->get_autopilot()->update(delta_time_sec);
970 cur_fdm_state->update(delta_time_sec);
973 globals->get_model_mgr()->update(delta_time_sec);
974 globals->get_aircraft_model()->update(delta_time_sec);
976 // update the view angle
977 globals->get_viewmgr()->update(delta_time_sec);
981 // Update solar system
982 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
983 globals->get_time_params()->getLst(),
984 cur_fdm_state->get_Latitude() );
986 // Update radio stack model
987 current_radiostack->update(delta_time_sec);
991 void fgInitTimeDepCalcs( void ) {
996 static const double alt_adjust_ft = 3.758099;
997 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1000 // What should we do when we have nothing else to do? Let's get ready
1001 // for the next move and update the display?
1002 static void fgMainLoop( void ) {
1004 static const SGPropertyNode *longitude
1005 = fgGetNode("/position/longitude-deg");
1006 static const SGPropertyNode *latitude
1007 = fgGetNode("/position/latitude-deg");
1008 static const SGPropertyNode *altitude
1009 = fgGetNode("/position/altitude-ft");
1010 static const SGPropertyNode *clock_freeze
1011 = fgGetNode("/sim/freeze/clock", true);
1012 static const SGPropertyNode *cur_time_override
1013 = fgGetNode("/sim/time/cur-time-override", true);
1015 // Update the elapsed time.
1016 static bool first_time = true;
1018 last_time_stamp.stamp();
1022 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1023 if ( throttle_hz > 0.0 ) {
1024 // simple frame rate throttle
1025 double dt = 1000000.0 / throttle_hz;
1026 current_time_stamp.stamp();
1027 while ( current_time_stamp - last_time_stamp < dt ) {
1028 current_time_stamp.stamp();
1031 // run as fast as the app will go
1032 current_time_stamp.stamp();
1035 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1036 if ( clock_freeze->getBoolValue() ) {
1039 last_time_stamp = current_time_stamp;
1040 globals->inc_sim_time_sec( delta_time_sec );
1041 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1043 static long remainder = 0;
1045 #ifdef FANCY_FRAME_COUNTER
1049 static time_t last_time = 0;
1050 static int frames = 0;
1051 #endif // FANCY_FRAME_COUNTER
1053 SGTime *t = globals->get_time_params();
1055 sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1056 sglog().setLogLevels( SG_ALL, SG_INFO );
1058 SGLocation * acmodel_location = 0;
1059 if(cur_fdm_state->getACModel() != 0) {
1060 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1063 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1064 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1066 #ifdef FG_NETWORK_OLK
1067 if ( fgGetBool("/sim/networking/network-olk") ) {
1068 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
1069 // printf("FGD: Netupdate\n");
1070 fgd_send_com( "A", FGFS_host); // Send Mat4 data
1071 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
1076 #if defined( ENABLE_PLIB_JOYSTICK )
1077 // Read joystick and update control settings
1078 // if ( fgGetString("/sim/control-mode") == "joystick" )
1080 // fgJoystickRead();
1082 #elif defined( ENABLE_GLUT_JOYSTICK )
1083 // Glut joystick support works by feeding a joystick handler
1084 // function to glut. This is taken care of once in the joystick
1085 // init routine and we don't have to worry about it again.
1088 // Fix elevation. I'm just sticking this here for now, it should
1089 // probably move eventually
1091 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1092 scenery.get_cur_elev(),
1093 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1094 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1096 // Curt is this code used? I don't see any problems when I comment it out.
1097 if ( acmodel_location != 0 ) {
1098 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1099 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1100 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1101 // now set aircraft altitude above ground
1102 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1103 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1104 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1105 acmodel_location->get_cur_elev_m() + alt_adjust_m );
1106 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
1107 + alt_adjust_m) * SG_METER_TO_FEET );
1108 SG_LOG( SG_ALL, SG_DEBUG,
1109 "<*> resetting altitude to "
1110 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1115 // End of code in question. (see Curt is this code used? above)
1117 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1118 scenery.get_cur_elev(),
1119 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1120 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1122 // cout << "Warp = " << globals->get_warp() << endl;
1125 static bool last_clock_freeze = false;
1127 if ( clock_freeze->getBoolValue() ) {
1128 // clock freeze requested
1129 if ( cur_time_override->getLongValue() == 0 ) {
1130 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1131 globals->set_warp( 0 );
1134 // no clock freeze requested
1135 if ( last_clock_freeze == true ) {
1136 // clock just unfroze, let's set warp as the difference
1137 // between frozen time and current time so we don't get a
1138 // time jump (and corresponding sky object and lighting
1140 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1141 fgSetLong( "/sim/time/cur-time-override", 0 );
1143 if ( globals->get_warp_delta() != 0 ) {
1144 globals->inc_warp( globals->get_warp_delta() );
1148 last_clock_freeze = clock_freeze->getBoolValue();
1150 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1151 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1152 cur_time_override->getLongValue(),
1153 globals->get_warp() );
1155 if ( globals->get_warp_delta() != 0 ) {
1156 fgUpdateSkyAndLightingParams();
1159 // update magvar model
1160 globals->get_mag()->update( longitude->getDoubleValue()
1161 * SGD_DEGREES_TO_RADIANS,
1162 latitude->getDoubleValue()
1163 * SGD_DEGREES_TO_RADIANS,
1164 altitude->getDoubleValue() * SG_FEET_TO_METER,
1165 globals->get_time_params()->getJD() );
1167 // Get elapsed time (in usec) for this past frame
1168 elapsed = fgGetTimeInterval();
1169 SG_LOG( SG_ALL, SG_DEBUG,
1170 "Elapsed time interval is = " << elapsed
1171 << ", previous remainder is = " << remainder );
1173 // Calculate frame rate average
1174 #ifdef FANCY_FRAME_COUNTER
1175 /* old fps calculation */
1176 if ( elapsed > 0 ) {
1179 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1180 tmp = general.get_frame(i);
1182 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1183 general.set_frame(i+1,tmp);
1185 tmp = 1000000.0 / (float)elapsed;
1186 general.set_frame(0,tmp);
1187 // printf("frame[0] = %.2f\n", general.frames[0]);
1189 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1190 // printf("ave = %.2f\n", general.frame_rate);
1193 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1194 general.set_frame_rate( frames );
1195 fgSetInt("/sim/frame-rate", frames);
1196 SG_LOG( SG_ALL, SG_DEBUG,
1197 "--> Frame rate is = " << general.get_frame_rate() );
1200 last_time = t->get_cur_time();
1204 // Run ATC subsystem
1205 if (fgGetBool("/sim/ATC/enabled"))
1206 globals->get_ATC_mgr()->update(delta_time_sec);
1208 // Run the AI subsystem
1209 if (fgGetBool("/sim/ai-traffic/enabled"))
1210 globals->get_AI_mgr()->update(delta_time_sec);
1214 // Calculate model iterations needed for next frame
1215 elapsed += remainder;
1217 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1218 fgGetInt("/sim/model-hz"));
1219 remainder = elapsed - ( (global_multi_loop*1000000) /
1220 fgGetInt("/sim/model-hz") );
1221 SG_LOG( SG_ALL, SG_DEBUG,
1222 "Model iterations needed = " << global_multi_loop
1223 << ", new remainder = " << remainder );
1225 // chop max interations to something reasonable if the sim was
1226 // delayed for an excesive amount of time
1227 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1228 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1233 if ( global_multi_loop > 0 ) {
1234 fgUpdateTimeDepCalcs();
1236 SG_LOG( SG_ALL, SG_DEBUG,
1237 "Elapsed time is zero ... we're zinging" );
1240 // Do any I/O channel work that might need to be done
1241 globals->get_io()->update( delta_time_sec );
1243 // see if we need to load any deferred-load textures
1244 globals->get_matlib()->load_next_deferred();
1246 // Run audio scheduler
1247 #ifdef ENABLE_AUDIO_SUPPORT
1248 if ( fgGetBool("/sim/sound/audible")
1249 && globals->get_soundmgr()->is_working() ) {
1250 globals->get_soundmgr()->update( delta_time_sec );
1254 globals->get_subsystem_mgr()->update(delta_time_sec);
1257 // Tile Manager updates - see if we need to load any new scenery tiles.
1258 // this code ties together the fdm, viewer and scenery classes...
1259 // we may want to move this to it's own class at some point
1261 double visibility_meters = fgGetDouble("/environment/visibility-m");
1262 FGViewer *current_view = globals->get_current_view();
1264 // update tile manager for FDM...
1265 // ...only if location is different than the viewer (to avoid duplicating effort)
1266 if( acmodel_location != current_view->getSGLocation() ) {
1267 if( acmodel_location != 0 ) {
1268 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1269 visibility_meters );
1270 globals->get_tile_mgr()->
1271 update( acmodel_location, visibility_meters,
1272 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1273 // save results of update in SGLocation for fdm...
1274 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1276 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1279 set_tile_center( globals->get_scenery()->get_next_center() );
1283 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1284 visibility_meters );
1285 // update tile manager for view...
1286 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1287 // after the FDM's until all of Flight Gear code references the viewer's location
1288 // for elevation instead of the "scenery's" current elevation.
1289 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1290 globals->get_tile_mgr()->update( view_location, visibility_meters,
1291 current_view->get_absolute_view_pos() );
1292 // save results of update in SGLocation for fdm...
1293 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1294 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1296 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1298 // If fdm location is same as viewer's then we didn't do the update for fdm location
1299 // above so we need to save the viewer results in the fdm SGLocation as well...
1300 if( acmodel_location == current_view->getSGLocation() ) {
1301 if( acmodel_location != 0 ) {
1302 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1303 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1305 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1309 // END Tile Manager udpates
1314 SG_LOG( SG_ALL, SG_DEBUG, "" );
1318 // This is the top level master main function that is registered as
1319 // our idle funciton
1321 // The first few passes take care of initialization things (a couple
1322 // per pass) and once everything has been initialized fgMainLoop from
1325 static void fgIdleFunction ( void ) {
1326 // printf("idle state == %d\n", idle_state);
1328 if ( idle_state == 0 ) {
1329 // Initialize the splash screen right away
1330 if ( fgGetBool("/sim/startup/splash-screen") ) {
1335 } else if ( idle_state == 1 ) {
1336 // Initialize audio support
1337 #ifdef ENABLE_AUDIO_SUPPORT
1339 // Start the intro music
1340 if ( fgGetBool("/sim/startup/intro-music") ) {
1341 SGPath mp3file( globals->get_fg_root() );
1342 mp3file.append( "Sounds/intro.mp3" );
1344 SG_LOG( SG_GENERAL, SG_INFO,
1345 "Starting intro music: " << mp3file.str() );
1347 #if defined( __CYGWIN__ )
1348 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1349 #elif defined( WIN32 )
1350 string command = "start /m " + mp3file.str();
1352 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1355 system ( command.c_str() );
1360 } else if ( idle_state == 2 ) {
1361 // These are a few miscellaneous things that aren't really
1362 // "subsystems" but still need to be initialized.
1365 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1366 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1371 } else if ( idle_state == 3 ) {
1372 // This is the top level init routine which calls all the
1373 // other subsystem initialization routines. If you are adding
1374 // a subsystem to flightgear, its initialization call should
1375 // located in this routine.
1376 if( !fgInitSubsystems()) {
1377 SG_LOG( SG_GENERAL, SG_ALERT,
1378 "Subsystem initializations failed ..." );
1383 } else if ( idle_state == 4 ) {
1384 // setup OpenGL view parameters
1387 // Read the list of available aircrafts
1391 } else if ( idle_state == 5 ) {
1394 } else if ( idle_state == 6 ) {
1398 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1399 fgReshape( fgGetInt("/sim/startup/xsize"),
1400 fgGetInt("/sim/startup/ysize") );
1403 if ( idle_state == 1000 ) {
1404 // We've finished all our initialization steps, from now on we
1405 // run the main loop.
1407 glutIdleFunc(fgMainLoop);
1409 if ( fgGetBool("/sim/startup/splash-screen") ) {
1410 fgSplashUpdate(0.0, 1.0);
1415 // options.cxx needs to see this for toggle_panel()
1416 // Handle new window size or exposure
1417 void fgReshape( int width, int height ) {
1420 if ( (!fgGetBool("/sim/virtual-cockpit"))
1421 && fgPanelVisible() && idle_state == 1000 ) {
1422 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1423 globals->get_current_panel()->getYOffset()) / 768.0);
1429 FGViewMgr *viewmgr = globals->get_viewmgr();
1430 for ( int i = 0; i < viewmgr->size(); ++i ) {
1431 viewmgr->get_view(i)->
1432 set_aspect_ratio((float)view_h / (float)width);
1435 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1437 fgSetInt("/sim/startup/xsize", width);
1438 fgSetInt("/sim/startup/ysize", height);
1439 guiInitMouse(width, height);
1441 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1442 viewmgr->get_current_view()->get_v_fov() );
1446 #ifdef FG_USE_CLOUDS_3D
1447 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1448 viewmgr->get_current_view()->get_v_fov() );
1453 // Initialize GLUT and define a main window
1454 static bool fgGlutInit( int *argc, char **argv ) {
1456 #if !defined( macintosh )
1457 // GLUT will extract all glut specific options so later on we only
1458 // need wory about our own.
1459 glutInit(argc, argv);
1462 // Define Display Parameters. Clouds3d works best with --bpp32 option
1463 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1464 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1466 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1469 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1470 fgGetInt("/sim/startup/xsize") << "x"
1471 << fgGetInt("/sim/startup/ysize") );
1473 // Define initial window size
1474 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1475 fgGetInt("/sim/startup/ysize") );
1477 // Initialize windows
1478 if ( !fgGetBool("/sim/startup/game-mode")) {
1479 // Open the regular window
1480 glutCreateWindow("FlightGear");
1481 #ifndef GLUT_WRONG_VERSION
1483 // Open the cool new 'game mode' window
1484 char game_mode_str[256];
1485 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1486 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1487 #ifndef ENUM_CURRENT_SETTINGS
1488 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1489 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1493 dm.dmSize = sizeof(DEVMODE);
1494 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1495 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1496 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1497 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1498 fgGetInt("/sim/startup/ysize") );
1499 sprintf( game_mode_str, "%dx%d:%d@%d",
1503 dm.dmDisplayFrequency );
1505 // Open the cool new 'game mode' window
1506 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1507 fgGetInt("/sim/startup/xsize"),
1508 fgGetInt("/sim/startup/ysize"),
1509 fgGetInt("/sim/rendering/bits-per-pixel"));
1511 #endif // HAVE_WINDOWS_H
1512 SG_LOG( SG_GENERAL, SG_INFO,
1513 "game mode params = " << game_mode_str );
1514 glutGameModeString( game_mode_str );
1515 glutEnterGameMode();
1516 #endif // GLUT_WRONG_VERSION
1519 // This seems to be the absolute earliest in the init sequence
1520 // that these calls will return valid info. Too bad it's after
1521 // we've already created and sized out window. :-(
1522 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1523 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1524 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1525 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1528 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1529 general.set_glMaxTexSize( tmp );
1530 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1532 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1533 general.set_glDepthBits( tmp );
1534 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1540 // Initialize GLUT event handlers
1541 static bool fgGlutInitEvents( void ) {
1542 // call fgReshape() on window resizes
1543 glutReshapeFunc( fgReshape );
1545 // keyboard and mouse callbacks are set in FGInput::init
1547 // call fgMainLoop() whenever there is
1548 // nothing else to do
1549 glutIdleFunc( fgIdleFunction );
1552 glutDisplayFunc( fgRenderFrame );
1557 // Main top level initialization
1558 static bool fgMainInit( int argc, char **argv ) {
1560 #if defined( macintosh )
1561 freopen ("stdout.txt", "w", stdout );
1562 freopen ("stderr.txt", "w", stderr );
1563 argc = ccommand( &argv );
1566 // set default log levels
1567 sglog().setLogLevels( SG_ALL, SG_INFO );
1570 #ifdef FLIGHTGEAR_VERSION
1571 version = FLIGHTGEAR_VERSION;
1573 version = "unknown version";
1575 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1577 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1579 // Allocate global data structures. This needs to happen before
1580 // we parse command line options
1582 globals = new FGGlobals;
1584 // seed the random number generater
1587 SGRoute *route = new SGRoute;
1588 globals->set_route( route );
1590 FGControls *controls = new FGControls;
1591 globals->set_controls( controls );
1593 string_list *col = new string_list;
1594 globals->set_channel_options_list( col );
1596 // Scan the config file(s) and command line options to see if
1597 // fg_root was specified (ignore all other options for now)
1598 fgInitFGRoot(argc, argv);
1600 // Check for the correct base package version
1601 static char required_version[] = "0.9.2";
1602 string base_version = fgBasePackageVersion();
1603 if ( !(base_version == required_version) ) {
1604 // tell the operator how to use this application
1606 cerr << endl << "Base package check failed ... " \
1607 << "Found version " << base_version << " at: " \
1608 << globals->get_fg_root() << endl;
1609 cerr << "Please upgrade to version: " << required_version << endl;
1613 // Initialize the Aircraft directory to "" (UIUC)
1616 // Load the configuration parameters. (Command line options
1617 // overrides config file options. Config file options override
1619 if ( !fgInitConfig(argc, argv) ) {
1620 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1624 // Initialize the Window/Graphics environment.
1625 if( !fgGlutInit(&argc, argv) ) {
1626 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1630 // Initialize the various GLUT Event Handlers.
1631 if( !fgGlutInitEvents() ) {
1632 SG_LOG( SG_GENERAL, SG_ALERT,
1633 "GLUT event handler initialization failed ..." );
1637 // Initialize plib net interface
1638 netInit( &argc, argv );
1640 // Initialize ssg (from plib). Needs to come before we do any
1641 // other ssg stuff, but after opengl/glut has been initialized.
1644 // Initialize the user interface (we need to do this before
1645 // passing off control to glut and before fgInitGeneral to get our
1649 // Read the list of available aircrafts
1652 #ifdef GL_EXT_texture_lod_bias
1653 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1656 // get the address of our OpenGL extensions
1657 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1659 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1660 glPointParameterfPtr = (glPointParameterfProc)
1661 SGLookupFunction("glPointParameterfEXT");
1662 glPointParameterfvPtr = (glPointParameterfvProc)
1663 SGLookupFunction("glPointParameterfvEXT");
1665 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1666 glPointParameterfPtr = (glPointParameterfProc)
1667 SGLookupFunction("glPointParameterfARB");
1668 glPointParameterfvPtr = (glPointParameterfvProc)
1669 SGLookupFunction("glPointParameterfvARB");
1673 // based on the requested presets, calculate the true starting
1678 SGTime *t = fgInitTime();
1679 globals->set_time_params( t );
1681 // Do some quick general initializations
1682 if( !fgInitGeneral()) {
1683 SG_LOG( SG_GENERAL, SG_ALERT,
1684 "General initializations failed ..." );
1688 SGPath modelpath( globals->get_fg_root() );
1689 ssgModelPath( (char *)modelpath.c_str() );
1691 ////////////////////////////////////////////////////////////////////
1692 // Initialize the property-based built-in commands
1693 ////////////////////////////////////////////////////////////////////
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the material manager
1698 ////////////////////////////////////////////////////////////////////
1699 globals->set_matlib( new SGMaterialLib );
1701 globals->set_model_lib(new SGModelLib);
1703 ////////////////////////////////////////////////////////////////////
1704 // Initialize the TG scenery subsystem.
1705 ////////////////////////////////////////////////////////////////////
1706 globals->set_scenery( new FGScenery );
1707 globals->get_scenery()->init();
1708 globals->get_scenery()->bind();
1709 globals->set_tile_mgr( new FGTileMgr );
1711 ////////////////////////////////////////////////////////////////////
1712 // Initialize the general model subsystem.
1713 ////////////////////////////////////////////////////////////////////
1714 globals->set_model_mgr(new FGModelMgr);
1715 globals->get_model_mgr()->init();
1716 globals->get_model_mgr()->bind();
1718 ////////////////////////////////////////////////////////////////////
1719 // Initialize the 3D aircraft model subsystem (has a dependency on
1720 // the scenery subsystem.)
1721 ////////////////////////////////////////////////////////////////////
1722 globals->set_aircraft_model(new FGAircraftModel);
1723 globals->get_aircraft_model()->init();
1724 globals->get_aircraft_model()->bind();
1726 ////////////////////////////////////////////////////////////////////
1727 // Initialize the view manager subsystem.
1728 ////////////////////////////////////////////////////////////////////
1730 FGViewMgr *viewmgr = new FGViewMgr;
1731 globals->set_viewmgr( viewmgr );
1736 // Initialize the sky
1737 SGPath ephem_data_path( globals->get_fg_root() );
1738 ephem_data_path.append( "Astro" );
1739 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1740 ephem->update( globals->get_time_params()->getMjd(),
1741 globals->get_time_params()->getLst(),
1743 globals->set_ephem( ephem );
1745 // TODO: move to environment mgr
1747 SGPath texture_path(globals->get_fg_root());
1748 texture_path.append("Textures");
1749 texture_path.append("Sky");
1750 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1751 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1752 thesky->add_cloud_layer(layer);
1756 SGPath sky_tex_path( globals->get_fg_root() );
1757 sky_tex_path.append( "Textures" );
1758 sky_tex_path.append( "Sky" );
1759 thesky->texture_path( sky_tex_path.str() );
1761 // The sun and moon diameters are scaled down numbers of the
1762 // actual diameters. This was needed to fit bot the sun and the
1763 // moon within the distance to the far clip plane.
1764 // Moon diameter: 3,476 kilometers
1765 // Sun diameter: 1,390,000 kilometers
1766 thesky->build( 80000.0, 80000.0,
1768 globals->get_ephem()->getNumPlanets(),
1769 globals->get_ephem()->getPlanets(),
1770 globals->get_ephem()->getNumStars(),
1771 globals->get_ephem()->getStars() );
1773 // Initialize MagVar model
1774 SGMagVar *magvar = new SGMagVar();
1775 globals->set_mag( magvar );
1777 // airport = new ssgBranch;
1778 // airport->setName( "Airport Lighting" );
1779 // lighting->addKid( airport );
1785 #ifdef FG_NETWORK_OLK
1786 // Do the network intialization
1787 if ( fgGetBool("/sim/networking/network-olk") ) {
1788 printf("Multipilot mode %s\n",
1789 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1793 // build our custom render states
1794 fgBuildRenderStates();
1796 // pass control off to the master GLUT event handler
1799 // we never actually get here ... but to avoid compiler warnings,
1805 // $$$ end - added VS Renganathan, 15 Oct 2K
1806 // - added Venky , 12 Nov 2K
1808 #if defined(__linux__) && defined(__i386__)
1810 static void handleFPE (int);
1815 fpu_control_t fpe_flags = 0;
1816 _FPU_GETCW(fpe_flags);
1817 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1818 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1819 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1820 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1821 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1822 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1823 _FPU_SETCW(fpe_flags);
1824 signal(SIGFPE, handleFPE);
1831 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1844 short CPSGetCurrentProcess(PSN *psn);
1845 short CPSSetProcessName (PSN *psn, char *processname);
1846 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1847 short CPSSetFrontProcess(PSN *psn);
1850 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1854 // Main entry point; catch any exceptions that have made it this far.
1855 int main ( int argc, char **argv ) {
1857 // Enable floating-point exceptions for Linux/x86
1858 #if defined(__linux__) && defined(__i386__)
1862 // Enable floating-point exceptions for Windows
1863 #if defined( _MSC_VER ) && defined( DEBUG )
1864 // Christian, we should document what this does
1865 _control87( _EM_INEXACT, _MCW_EM );
1868 #if defined( HAVE_BC5PLUS )
1869 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1872 // Keyboard focus hack
1877 glutInit (&argc, argv);
1879 CPSGetCurrentProcess(&psn);
1880 CPSSetProcessName(&psn, "FlightGear");
1882 CPSSetFrontProcess(&psn);
1886 // FIXME: add other, more specific
1889 fgMainInit(argc, argv);
1890 } catch (sg_throwable &t) {
1891 // We must use cerr rather than
1892 // logging, since logging may be
1894 cerr << "Fatal error: " << t.getFormattedMessage()
1895 << "\n (received from " << t.getOrigin() << ')' << endl;
1903 void fgLoadDCS(void) {
1905 ssgEntity *ship_obj = NULL;
1907 char obj_filename[25];
1909 for ( int k = 0; k < 32; k++ ) {
1913 SGPath tile_path( globals->get_fg_root());
1914 tile_path.append( "Scenery" );
1915 tile_path.append( "Objects.txt" );
1916 sg_gzifstream in( tile_path.str() );
1917 if ( ! in.is_open() ) {
1918 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1921 SGPath modelpath( globals->get_fg_root() );
1922 modelpath.append( "Models" );
1923 modelpath.append( "Geometry" );
1925 SGPath texturepath( globals->get_fg_root() );
1926 texturepath.append( "Models" );
1927 texturepath.append( "Textures" );
1929 ssgModelPath( (char *)modelpath.c_str() );
1930 ssgTexturePath( (char *)texturepath.c_str() );
1932 ship_sel = new ssgSelector;
1935 while ( ! in.eof() ) {
1937 if ( in.get( c ) && c == '#' ) {
1941 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1942 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1943 int chj=getchar();*/
1945 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1946 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1948 ship_pos[objc] = new ssgTransform;
1950 // type "repeat" in objects.txt to load one more
1951 // instance of the last object.
1953 if ( strcmp(obj_filename,"repeat") != 0) {
1955 globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1958 if ( ship_obj != NULL ) {
1959 ship_obj->setName(obj_filename);
1961 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1963 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1964 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1965 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1966 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1969 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1973 // temporary hack for deck lights - ultimately should move to PLib (when??)
1974 //const char *extn = file_extension ( obj_filename ) ;
1976 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1977 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1978 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1979 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1980 int ltype[500], light_type = 0;
1981 static int ltcount = 0;
1983 sgVec3 rway_dir,rway_normal,lightpt;
1985 modelpath.append(obj_filename);
1986 sg_gzifstream in1( modelpath.str() );
1987 if ( ! in1.is_open() ) {
1988 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1990 while ( ! in1.eof() ) {
1992 if ( in1.get( c ) && c == '#' ) {
1997 //cout << token << endl;
1998 if ( token == "runway" ) {
2000 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
2001 } else if ( token == "edgelight" ) {
2003 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2005 } else if ( token == "taxi" ) {
2007 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2009 } else if ( token == "vasi" ) {
2011 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2013 } else if ( token == "threshold" ) {
2015 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2017 } else if ( token == "rabbit" ) {
2019 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2021 } else if ( token == "ols" ) {
2023 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2025 } else if ( token == "red" ) {
2027 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2029 } else if ( token == "green" ) {
2031 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2033 } else if ( token == "lp" ) {
2035 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2036 lightpoints->add( lightpt );
2037 lightnormals->add( rway_normal );
2038 lightdir->add( rway_dir );
2039 ltype[ltcount]= light_type;
2042 if (in1.eof()) break;
2047 if ( lightpoints->getNum() ) {
2048 ssgBranch *lightpoints_branch;
2049 long int dummy = -999;
2050 dummy_tile = new FGTileEntry((SGBucket)dummy);
2051 dummy_tile->lightmaps_sequence = new ssgSelector;
2052 dummy_tile->ols_transform = new ssgTransform;
2054 // call function to generate the runway lights
2055 lightpoints_branch =
2056 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2058 lightpoints_brightness->addKid(lightpoints_branch);
2059 lightpoints_transform->addKid(lightpoints_brightness);
2060 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2061 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2062 lightpoints_transform->ref();
2063 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2068 // end hack for deck lights
2072 if (in.eof()) break;
2076 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2078 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
2085 void fgUpdateDCS (void) {
2087 // double eye_lat,eye_lon,eye_alt;
2088 // static double obj_head;
2089 double sl_radius,obj_latgc;
2090 // float nresultmat[4][4];
2091 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2094 // Instantaneous Geodetic Lat/Lon/Alt of moving object
2095 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2097 // Deck should be the first object in objects.txt in case of fdm=ada
2099 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2100 if ((fdm->get_iaux(1))==1)
2102 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2103 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2104 obj_alt[1] = fdm->get_daux(3);
2105 obj_pitch[1] = fdm->get_faux(1);
2106 obj_roll[1] = fdm->get_faux(2);
2110 for ( int m = 0; m < objc; m++ ) {
2111 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2114 //Geodetic to Geocentric angles for rotation
2115 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2117 //moving object gbs-posn in cartesian coords
2118 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2119 Point3D obj_pos = sgGeodToCart( obj_posn );
2121 // Translate moving object w.r.t eye
2122 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2127 // rotate dynamic objects for lat,lon & alt and other motion about its axes
2130 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2132 sgVec3 ship_fwd,ship_rt,ship_up;
2133 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2134 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2135 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2137 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2138 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2139 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2140 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2141 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2142 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2145 sgCopyMat4( sgTUX, sgROT_hdg );
2146 sgPostMultMat4( sgTUX, sgROT_pitch );
2147 sgPostMultMat4( sgTUX, sgROT_roll );
2148 sgPostMultMat4( sgTUX, sgROT_lat );
2149 sgPostMultMat4( sgTUX, sgROT_lon );
2150 sgPostMultMat4( sgTUX, sgTRANS );
2153 sgSetCoord(&shippos, sgTUX );
2154 ship_pos[m]->setTransform( &shippos );
2155 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2157 if (lightpoints_transform) {
2158 lightpoints_transform->setTransform( &shippos );
2159 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2160 if ( sun_angle > 89 ) {
2161 lightpoints_brightness->select(0x01);
2163 lightpoints_brightness->select(0x00);
2172 sgXformPnt3( rp, rway_ols, sgTUX );
2173 vp = globals->get_current_view()->get_view_pos();
2174 to[0] = rp[0]-vp[0];
2175 to[1] = rp[1]-vp[1];
2176 to[2] = rp[2]-vp[2];
2177 float dist = sgLengthVec3( to );
2178 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2180 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2182 ref_elev = elev - 3.75; // +ve above, -ve below
2186 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2187 // if (ref_elev > 0.51) sel = 0x21;
2188 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2189 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2190 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2191 // if (ref_elev < -0.51) sel = 0x30;
2192 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2193 // dummy_tile->lightmaps_sequence->select(sel);
2196 sgCopyVec3 (up, ship_up);
2198 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2200 sgScaleVec3 (up, 4.0*ref_elev);
2201 // dummy_tile->ols_transform->setTransform(up);
2202 //cout << "ref_elev " << ref_elev << endl;
2204 // end hack for deck lights
2207 if ( ship_sel != NULL ) {
2208 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2212 // $$$ end - added VS Renganathan, 15 Oct 2K
2213 // added Venky , 12 Nov 2K