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>
36 #ifndef SG_HAVE_NATIVE_SGI_COMPILERS
41 #include <simgear/misc/exception.hxx>
42 #include <simgear/ephemeris/ephemeris.hxx>
43 #include <simgear/route/route.hxx>
45 #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>
77 #include <simgear/constants.h> // for VERSION
78 #include <simgear/debug/logstream.hxx>
79 #include <simgear/math/polar3d.hxx>
80 #include <simgear/math/sg_random.h>
81 #include <simgear/misc/sg_path.hxx>
82 #include <simgear/sky/sky.hxx>
83 #include <simgear/timing/sg_time.hxx>
85 #include <Include/general.hxx>
87 #include <Aircraft/aircraft.hxx>
89 #include <ATC/ATCmgr.hxx>
90 #include <ATC/ATCdisplay.hxx>
91 #include <ATC/AIMgr.hxx>
93 #include <Autopilot/newauto.hxx>
95 #include <Cockpit/cockpit.hxx>
96 #include <Cockpit/radiostack.hxx>
97 #include <Cockpit/steam.hxx>
99 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
101 #include <Model/acmodel.hxx>
102 #include <Model/modelmgr.hxx>
103 #include <Model/model.hxx>
104 #include <Main/location.hxx>
105 #ifdef FG_NETWORK_OLK
106 #include <NetworkOLK/network.h>
108 #include <Objects/matlib.hxx>
109 #include <Scenery/scenery.hxx>
110 #include <Scenery/tilemgr.hxx>
111 #ifdef ENABLE_AUDIO_SUPPORT
112 # include <Sound/soundmgr.hxx>
113 # include <Sound/fg_fx.hxx>
114 # include <Sound/morse.hxx>
116 #include <Time/FGEventMgr.hxx>
117 #include <Time/fg_timer.hxx>
118 #include <Time/light.hxx>
119 #include <Time/sunpos.hxx>
120 #include <Time/tmp.hxx>
122 #include <Input/input.hxx>
125 #include <simgear/misc/sgstream.hxx>
126 #include <simgear/math/point3d.hxx>
127 #include <FDM/flight.hxx>
128 #include <FDM/ADA.hxx>
129 #include <Scenery/tileentry.hxx>
132 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
133 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
135 float default_attenuation[3] = {1.0, 0.0, 0.0};
136 //Required for using GL_extensions
137 void fgLoadDCS (void);
138 void fgUpdateDCS (void);
139 ssgSelector *ship_sel=NULL;
140 // upto 32 instances of a same object can be loaded.
141 ssgTransform *ship_pos[32];
142 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
144 ssgSelector *lightpoints_brightness = new ssgSelector;
145 ssgTransform *lightpoints_transform = new ssgTransform;
146 FGTileEntry *dummy_tile;
149 // Clip plane settings...
150 float scene_nearplane = 0.5f;
151 float scene_farplane = 120000.0f;
153 static double delta_time_sec = 0;
157 # include <WeatherCM/FGLocalWeatherDatabase.h>
159 # include <Environment/environment_mgr.hxx>
164 #include "fg_init.hxx"
166 #include "fg_props.hxx"
167 #include "globals.hxx"
168 #include "splash.hxx"
169 #include "viewmgr.hxx"
170 #include "options.hxx"
171 #include "logger.hxx"
174 # include <console.h> // -dw- for command line dialog
178 FGEventMgr global_events;
180 // This is a record containing a bit of global housekeeping information
183 // Specify our current idle function state. This is used to run all
184 // our initializations out of the glutIdleLoop() so that we can get a
185 // splash screen up and running right away.
186 static int idle_state = 0;
187 static long global_multi_loop;
189 // forward declaration
190 void fgReshape( int width, int height );
192 // fog constants. I'm a little nervous about putting actual code out
193 // here but it seems to work (?)
194 static const double m_log01 = -log( 0.01 );
195 static const double sqrt_m_log01 = sqrt( m_log01 );
196 static GLfloat fog_exp_density;
197 static GLfloat fog_exp2_density;
198 static GLfloat fog_exp2_punch_through;
200 #ifdef FG_NETWORK_OLK
201 ssgSelector *fgd_sel = NULL;
202 ssgTransform *fgd_pos = NULL;
205 // current fdm/position used for view
206 FGInterface cur_view_fdm;
212 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
214 { 1.0f, 0.0f, 0.0f, 0.0f },
215 { 0.0f, 0.0f, -1.0f, 0.0f },
216 { 0.0f, 1.0f, 0.0f, 0.0f },
217 { 0.0f, 0.0f, 0.0f, 1.0f }
220 // The following defines flightgear options. Because glutlib will also
221 // want to parse its own options, those options must not be included here
222 // or they will get parsed by the main program option parser. Hence case
223 // is significant for any option added that might be in conflict with
226 // glutlib parses for:
228 // -direct (invalid in Win32)
232 // -indirect (invalid in Win32)
235 // Note that glutlib depends upon strings while this program's
236 // option parser wants only initial characters followed by numbers
241 ssgSimpleState *default_state;
242 ssgSimpleState *hud_and_panel;
243 ssgSimpleState *menus;
245 SGTimeStamp last_time_stamp;
246 SGTimeStamp current_time_stamp;
248 void fgBuildRenderStates( void ) {
249 default_state = new ssgSimpleState;
250 default_state->ref();
251 default_state->disable( GL_TEXTURE_2D );
252 default_state->enable( GL_CULL_FACE );
253 default_state->enable( GL_COLOR_MATERIAL );
254 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
255 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
256 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
257 default_state->disable( GL_BLEND );
258 default_state->disable( GL_ALPHA_TEST );
259 default_state->disable( GL_LIGHTING );
261 hud_and_panel = new ssgSimpleState;
262 hud_and_panel->ref();
263 hud_and_panel->disable( GL_CULL_FACE );
264 hud_and_panel->disable( GL_TEXTURE_2D );
265 hud_and_panel->disable( GL_LIGHTING );
266 hud_and_panel->enable( GL_BLEND );
268 menus = new ssgSimpleState;
270 menus->disable( GL_CULL_FACE );
271 menus->disable( GL_TEXTURE_2D );
272 menus->enable( GL_BLEND );
276 // fgInitVisuals() -- Initialize various GL/view parameters
277 void fgInitVisuals( void ) {
280 l = &cur_light_params;
282 #ifndef GLUT_WRONG_VERSION
283 // Go full screen if requested ...
284 if ( fgGetBool("/sim/startup/fullscreen") ) {
289 // If enabled, normal vectors specified with glNormal are scaled
290 // to unit length after transformation. Enabling this has
291 // performance implications. See the docs for glNormal.
292 // glEnable( GL_NORMALIZE );
294 glEnable( GL_LIGHTING );
295 glEnable( GL_LIGHT0 );
296 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
299 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
300 ssgGetLight( 0 ) -> setPosition( sunpos );
302 glFogi (GL_FOG_MODE, GL_EXP2);
303 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
304 (!fgGetBool("/sim/rendering/shading"))) {
305 // if fastest fog requested, or if flat shading force fastest
306 glHint ( GL_FOG_HINT, GL_FASTEST );
307 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
308 glHint ( GL_FOG_HINT, GL_NICEST );
310 if ( fgGetBool("/sim/rendering/wireframe") ) {
312 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
315 // This is the default anyways, but it can't hurt
316 glFrontFace ( GL_CCW );
319 // glEnable(GL_POINT_SMOOTH);
320 // glEnable(GL_LINE_SMOOTH);
321 // glEnable(GL_POLYGON_SMOOTH);
325 // For HiRes screen Dumps using Brian Pauls TR Library
326 void trRenderFrame( void ) {
328 if ( fgPanelVisible() ) {
329 GLfloat height = fgGetInt("/sim/startup/ysize");
331 (current_panel->getViewHeight() - current_panel->getYOffset())
332 * (height / 768.0) + 1;
333 glTranslatef( 0.0, view_h, 0.0 );
336 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
337 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
339 fgLIGHT *l = &cur_light_params;
341 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
342 l->adj_fog_color[2], l->adj_fog_color[3]);
344 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
346 // set the opengl state to known default values
347 default_state->force();
350 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
351 glFogi ( GL_FOG_MODE, GL_EXP2 );
352 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
354 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
355 // we only update GL_AMBIENT for our lights we will never get
356 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
357 // explicitely to black.
358 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
360 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
362 // texture parameters
363 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
364 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
366 // we need a white diffuse light for the phase of the moon
367 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
370 // draw the ssg scene
371 // return to the desired diffuse color
372 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
373 glEnable( GL_DEPTH_TEST );
374 ssgSetNearFar( scene_nearplane, scene_farplane );
375 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
378 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
379 ssgSetNearFar( scene_nearplane, scene_farplane );
380 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
382 if (fgGetBool("/environment/clouds/status"))
383 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
385 globals->get_model_mgr()->draw();
386 globals->get_aircraft_model()->draw();
388 // need to do this here as hud_and_panel state is static to
389 // main.cxx and HUD and Panel routines have to be called with
390 // knowledge of the the TR struct < see gui.cxx::HighResDump()
391 hud_and_panel->apply();
395 // Update all Visuals (redraws anything graphics related)
396 void fgRenderFrame() {
398 // Process/manage pending events
399 global_events.update( delta_time_sec );
401 static const SGPropertyNode *longitude
402 = fgGetNode("/position/longitude-deg");
403 static const SGPropertyNode *latitude
404 = fgGetNode("/position/latitude-deg");
405 static const SGPropertyNode *altitude
406 = fgGetNode("/position/altitude-ft");
407 static const SGPropertyNode *groundlevel_nearplane
408 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
410 // Update the default (kludged) properties.
413 FGViewer *current__view = globals->get_current_view();
415 fgLIGHT *l = &cur_light_params;
416 static double last_visibility = -9999;
419 double actual_visibility = thesky->get_visibility();
420 if ( actual_visibility != last_visibility ) {
421 last_visibility = actual_visibility;
423 fog_exp_density = m_log01 / actual_visibility;
424 fog_exp2_density = sqrt_m_log01 / actual_visibility;
425 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
429 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
430 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
431 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
432 // GLfloat mat_shininess[] = { 10.0 };
433 GLbitfield clear_mask;
435 if ( idle_state != 1000 ) {
436 // still initializing, draw the splash screen
437 if ( fgGetBool("/sim/startup/splash-screen") ) {
440 // Keep resetting sim time while the sim is initializing
441 globals->set_sim_time_sec( 0.0 );
443 // idle_state is now 1000 meaning we've finished all our
444 // initializations and are running the main loop, so this will
445 // now work without seg faulting the system.
447 // calculate our current position in cartesian space
448 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
451 fgReshape( fgGetInt("/sim/startup/xsize"),
452 fgGetInt("/sim/startup/ysize") );
454 // set the sun position
455 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
457 clear_mask = GL_DEPTH_BUFFER_BIT;
458 if ( fgGetBool("/sim/rendering/wireframe") ) {
459 clear_mask |= GL_COLOR_BUFFER_BIT;
462 if ( fgGetBool("/sim/rendering/skyblend") ) {
463 if ( fgGetBool("/sim/rendering/textures") ) {
464 // glClearColor(black[0], black[1], black[2], black[3]);
465 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
466 l->adj_fog_color[2], l->adj_fog_color[3]);
467 clear_mask |= GL_COLOR_BUFFER_BIT;
470 glClearColor(l->sky_color[0], l->sky_color[1],
471 l->sky_color[2], l->sky_color[3]);
472 clear_mask |= GL_COLOR_BUFFER_BIT;
474 glClear( clear_mask );
476 // Tell GL we are switching to model view parameters
478 // I really should create a derived ssg node or use a call
479 // back or something so that I can draw the sky within the
480 // ssgCullAndDraw() function, but for now I just mimic what
481 // ssg does to set up the model view matrix
482 glMatrixMode(GL_MODELVIEW);
484 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
486 // set the opengl state to known default values
487 default_state->force();
489 // update fog params if visibility has changed
490 double visibility_meters = fgGetDouble("/environment/visibility-m");
491 thesky->set_visibility(visibility_meters);
493 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
494 ( global_multi_loop * fgGetInt("/sim/speed-up") )
495 / (double)fgGetInt("/sim/model-hz") );
497 // Set correct opengl fog density
498 glFogf (GL_FOG_DENSITY, fog_exp2_density);
500 // update the sky dome
501 if ( fgGetBool("/sim/rendering/skyblend") ) {
502 /* cout << "thesky->repaint() sky_color = "
503 << cur_light_params.sky_color[0] << " "
504 << cur_light_params.sky_color[1] << " "
505 << cur_light_params.sky_color[2] << " "
506 << cur_light_params.sky_color[3] << endl;
508 << cur_light_params.fog_color[0] << " "
509 << cur_light_params.fog_color[1] << " "
510 << cur_light_params.fog_color[2] << " "
511 << cur_light_params.fog_color[3] << endl;
512 cout << " sun_angle = " << cur_light_params.sun_angle
513 << " moon_angle = " << cur_light_params.moon_angle
515 thesky->repaint( cur_light_params.sky_color,
516 cur_light_params.adj_fog_color,
517 cur_light_params.sun_angle,
518 cur_light_params.moon_angle,
519 globals->get_ephem()->getNumPlanets(),
520 globals->get_ephem()->getPlanets(),
521 globals->get_ephem()->getNumStars(),
522 globals->get_ephem()->getStars() );
524 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
525 << view_pos[1] << " " << view_pos[2] << endl;
526 cout << " zero_elev = " << zero_elev[0] << " "
527 << zero_elev[1] << " " << zero_elev[2]
528 << " lon = " << cur_fdm_state->get_Longitude()
529 << " lat = " << cur_fdm_state->get_Latitude() << endl;
530 cout << " sun_rot = " << cur_light_params.sun_rotation
531 << " gst = " << SGTime::cur_time_params->getGst() << endl;
532 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
533 << " sun dec = " << globals->get_ephem()->getSunDeclination()
534 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
535 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
537 thesky->reposition( current__view->get_view_pos(),
538 current__view->get_zero_elev(),
539 current__view->get_world_up(),
540 current__view->getLongitude_deg()
541 * SGD_DEGREES_TO_RADIANS,
542 current__view->getLatitude_deg()
543 * SGD_DEGREES_TO_RADIANS,
544 current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
545 cur_light_params.sun_rotation,
546 globals->get_time_params()->getGst(),
547 globals->get_ephem()->getSunRightAscension(),
548 globals->get_ephem()->getSunDeclination(),
550 globals->get_ephem()->getMoonRightAscension(),
551 globals->get_ephem()->getMoonDeclination(),
555 glEnable( GL_DEPTH_TEST );
556 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
558 glFogi( GL_FOG_MODE, GL_EXP2 );
559 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
562 // set sun/lighting parameters
563 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
565 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
566 // we only update GL_AMBIENT for our lights we will never get
567 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
568 // explicitely to black.
569 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
570 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
571 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
573 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
574 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
575 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
577 // texture parameters
578 // glEnable( GL_TEXTURE_2D );
579 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
580 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
582 // glMatrixMode( GL_PROJECTION );
584 ssgSetFOV( current__view->get_h_fov(),
585 current__view->get_v_fov() );
588 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
589 - globals->get_scenery()->get_cur_elev();
592 scene_nearplane = 10.0f;
593 scene_farplane = 120000.0f;
595 scene_nearplane = groundlevel_nearplane->getDoubleValue();
596 scene_farplane = 120000.0f;
599 ssgSetNearFar( scene_nearplane, scene_farplane );
601 // $$$ begin - added VS Renganthan 17 Oct 2K
604 // $$$ end - added VS Renganthan 17 Oct 2K
606 # ifdef FG_NETWORK_OLK
607 if ( fgGetBool("/sim/networking/network-olk") ) {
609 other = head->next; /* put listpointer to start */
610 while ( other != tail) { /* display all except myself */
611 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
612 other->fgd_sel->select(1);
613 sgSetCoord( &fgdpos, other->sgFGD_COORD );
614 other->fgd_pos->setTransform( &fgdpos );
619 // fgd_sel->select(1);
620 // sgCopyMat4( sgTUX, current_view.sgVIEW);
622 // sgSetCoord( &fgdpos, sgFGD_VIEW );
623 // fgd_pos->setTransform( &fgdpos);
627 // position tile nodes and update range selectors
629 // this is done in the main loop now...
630 // global_tile_mgr.prep_ssg_nodes(visibility_meters);
632 if ( fgGetBool("/sim/rendering/skyblend") ) {
633 // draw the sky backdrop
635 // we need a white diffuse light for the phase of the moon
636 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
640 // return to the desired diffuse color
641 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
644 // draw the ssg scene
645 glEnable( GL_DEPTH_TEST );
647 ssgSetNearFar( scene_nearplane, scene_farplane );
648 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
650 // change state for lighting here
653 // Set punch through fog density
654 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
656 #ifdef FG_EXPERIMENTAL_LIGHTING
657 // Enable states for drawing points with GL_extension
658 if (glutExtensionSupported("GL_EXT_point_parameters")) {
659 glEnable(GL_POINT_SMOOTH);
660 float quadratic[3] = {1.0, 0.01, 0.0001};
661 // get the address of our OpenGL extensions
663 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
664 wglGetProcAddress("glPointParameterfEXT");
665 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
666 wglGetProcAddress("glPointParameterfvEXT");
668 // makes the points fade as they move away
669 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
670 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
673 // Enable states for drawing runway lights with spherical mapping
674 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
675 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
676 glEnable(GL_TEXTURE_GEN_S);
677 glEnable(GL_TEXTURE_GEN_T);
679 //Maybe this is not the best way, but it works !!
680 glPolygonMode(GL_FRONT, GL_POINT);
682 glEnable(GL_CULL_FACE);
685 glDisable( GL_LIGHTING );
686 // blending function for runway lights
687 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
691 ssgSetNearFar( scene_nearplane, scene_farplane );
692 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
695 #ifdef FG_EXPERIMENTAL_LIGHTING
696 if (glutExtensionSupported("GL_EXT_point_parameters")) {
697 // Disable states used for runway lighting
698 glPolygonMode(GL_FRONT, GL_FILL);
700 glDisable(GL_TEXTURE_GEN_S);
701 glDisable(GL_TEXTURE_GEN_T);
702 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
703 default_attenuation);
709 if ( fgGetBool("/sim/rendering/skyblend") ) {
710 // draw the sky cloud layers
711 if (fgGetBool("/environment/clouds/status"))
712 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
715 globals->get_model_mgr()->draw();
716 globals->get_aircraft_model()->draw();
718 // display HUD && Panel
720 glDisable( GL_DEPTH_TEST );
721 // glDisable( GL_CULL_FACE );
722 // glDisable( GL_TEXTURE_2D );
724 // update the input subsystem
725 current_input.update(delta_time_sec);
727 // update the controls subsystem
728 globals->get_controls()->update(delta_time_sec);
730 hud_and_panel->apply();
733 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
734 // This only works properly if called before the panel call
735 globals->get_ATC_display()->update(delta_time_sec);
737 // update the panel subsystem
738 if ( current_panel != NULL ) {
739 current_panel->update(delta_time_sec);
742 // We can do translucent menus, so why not. :-)
744 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
746 // glDisable ( GL_BLEND ) ;
748 // glEnable( GL_FOG );
750 globals->get_logger()->update(delta_time_sec);
757 // Update internal time dependent calculations (i.e. flight model)
758 // FIXME: this distinction is obsolete; all subsystems now get delta
760 void fgUpdateTimeDepCalcs() {
761 static bool inited = false;
763 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
765 fgLIGHT *l = &cur_light_params;
770 // Initialize the FDM here if it hasn't been and if we have a
771 // scenery elevation hit.
773 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
774 // << " cur_elev = " << scenery.get_cur_elev() << endl;
776 if ( !cur_fdm_state->get_inited() &&
777 globals->get_scenery()->get_cur_elev() > -9990 )
779 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
781 cur_fdm_state->init();
782 if ( cur_fdm_state->get_bound() ) {
783 cur_fdm_state->unbind();
785 cur_fdm_state->bind();
788 // conceptually, the following block could be done for each fdm
790 if ( !cur_fdm_state->get_inited() ) {
791 // do nothing, fdm isn't inited yet
793 // we have been inited, and we are good to go ...
799 globals->get_autopilot()->update(delta_time_sec);
800 cur_fdm_state->update(delta_time_sec);
801 FGSteam::update(delta_time_sec);
804 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
805 cur_view_fdm = *cur_fdm_state;
809 globals->get_model_mgr()->update(delta_time_sec);
810 globals->get_aircraft_model()->update(delta_time_sec);
812 // update the view angle
813 globals->get_viewmgr()->update(delta_time_sec);
817 // Update solar system
818 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
819 globals->get_time_params()->getLst(),
820 cur_fdm_state->get_Latitude() );
822 // Update radio stack model
823 current_radiostack->update(delta_time_sec);
827 void fgInitTimeDepCalcs( void ) {
832 static const double alt_adjust_ft = 3.758099;
833 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
836 // What should we do when we have nothing else to do? Let's get ready
837 // for the next move and update the display?
838 static void fgMainLoop( void ) {
840 // Update the elapsed time.
841 current_time_stamp.stamp();
842 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
843 last_time_stamp = current_time_stamp;
844 globals->inc_sim_time_sec( delta_time_sec );
846 static const SGPropertyNode *longitude
847 = fgGetNode("/position/longitude-deg");
848 static const SGPropertyNode *latitude
849 = fgGetNode("/position/latitude-deg");
850 static const SGPropertyNode *altitude
851 = fgGetNode("/position/altitude-ft");
852 static const SGPropertyNode *clock_freeze
853 = fgGetNode("/sim/freeze/clock", true);
854 static const SGPropertyNode *cur_time_override
855 = fgGetNode("/sim/time/cur-time-override", true);
857 static long remainder = 0;
859 #ifdef FANCY_FRAME_COUNTER
863 static time_t last_time = 0;
864 static int frames = 0;
865 #endif // FANCY_FRAME_COUNTER
867 SGTime *t = globals->get_time_params();
869 FGLocation * acmodel_location = 0;
870 if(cur_fdm_state->getACModel() != 0) {
871 acmodel_location = (FGLocation *) cur_fdm_state->getACModel()->get3DModel()->getFGLocation();
874 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
875 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
877 #ifdef FG_NETWORK_OLK
878 if ( fgGetBool("/sim/networking/network-olk") ) {
879 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
880 // printf("FGD: Netupdate\n");
881 fgd_send_com( "A", FGFS_host); // Send Mat4 data
882 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
887 #if defined( ENABLE_PLIB_JOYSTICK )
888 // Read joystick and update control settings
889 // if ( fgGetString("/sim/control-mode") == "joystick" )
893 #elif defined( ENABLE_GLUT_JOYSTICK )
894 // Glut joystick support works by feeding a joystick handler
895 // function to glut. This is taken care of once in the joystick
896 // init routine and we don't have to worry about it again.
900 globals->get_environment_mgr()->update(delta_time_sec);
903 // Fix elevation. I'm just sticking this here for now, it should
904 // probably move eventually
906 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
907 scenery.get_cur_elev(),
908 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
909 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
911 // Curt is this code used? I don't see any problems when I comment it out.
912 if ( acmodel_location != 0 ) {
913 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
914 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
915 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
916 // now set aircraft altitude above ground
917 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
918 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
919 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
920 acmodel_location->get_cur_elev_m() + alt_adjust_m );
921 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
922 + alt_adjust_m) * SG_METER_TO_FEET );
923 SG_LOG( SG_ALL, SG_DEBUG,
924 "<*> resetting altitude to "
925 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
930 // End of code in question. (see Curt is this code used? above)
932 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
933 scenery.get_cur_elev(),
934 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
935 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
937 // cout << "Warp = " << globals->get_warp() << endl;
940 static bool last_clock_freeze = false;
942 if ( clock_freeze->getBoolValue() ) {
943 // clock freeze requested
944 if ( cur_time_override->getLongValue() == 0 ) {
945 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
946 globals->set_warp( 0 );
949 // no clock freeze requested
950 if ( last_clock_freeze == true ) {
951 // clock just unfroze, let's set warp as the difference
952 // between frozen time and current time so we don't get a
953 // time jump (and corresponding sky object and lighting
955 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
956 fgSetLong( "/sim/time/cur-time-override", 0 );
958 if ( globals->get_warp_delta() != 0 ) {
959 globals->inc_warp( globals->get_warp_delta() );
963 last_clock_freeze = clock_freeze->getBoolValue();
965 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
966 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
967 cur_time_override->getLongValue(),
968 globals->get_warp() );
970 if ( globals->get_warp_delta() != 0 ) {
971 fgUpdateSkyAndLightingParams();
974 // update magvar model
975 globals->get_mag()->update( longitude->getDoubleValue()
976 * SGD_DEGREES_TO_RADIANS,
977 latitude->getDoubleValue()
978 * SGD_DEGREES_TO_RADIANS,
979 altitude->getDoubleValue() * SG_FEET_TO_METER,
980 globals->get_time_params()->getJD() );
982 // Get elapsed time (in usec) for this past frame
983 elapsed = fgGetTimeInterval();
984 SG_LOG( SG_ALL, SG_DEBUG,
985 "Elapsed time interval is = " << elapsed
986 << ", previous remainder is = " << remainder );
988 // Calculate frame rate average
989 #ifdef FANCY_FRAME_COUNTER
990 /* old fps calculation */
994 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
995 tmp = general.get_frame(i);
997 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
998 general.set_frame(i+1,tmp);
1000 tmp = 1000000.0 / (float)elapsed;
1001 general.set_frame(0,tmp);
1002 // printf("frame[0] = %.2f\n", general.frames[0]);
1004 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1005 // printf("ave = %.2f\n", general.frame_rate);
1008 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1009 general.set_frame_rate( frames );
1010 SG_LOG( SG_ALL, SG_DEBUG,
1011 "--> Frame rate is = " << general.get_frame_rate() );
1014 last_time = t->get_cur_time();
1018 // Run ATC subsystem
1019 globals->get_ATC_mgr()->update(delta_time_sec);
1021 // Run the AI subsystem
1022 // globals->get_AI_mgr()->update(delta_time_sec);
1026 // Calculate model iterations needed for next frame
1027 elapsed += remainder;
1029 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1030 fgGetInt("/sim/model-hz"));
1031 remainder = elapsed - ( (global_multi_loop*1000000) /
1032 fgGetInt("/sim/model-hz") );
1033 SG_LOG( SG_ALL, SG_DEBUG,
1034 "Model iterations needed = " << global_multi_loop
1035 << ", new remainder = " << remainder );
1037 // chop max interations to something reasonable if the sim was
1038 // delayed for an excesive amount of time
1039 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1040 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1045 if ( global_multi_loop > 0 ) {
1046 fgUpdateTimeDepCalcs();
1048 SG_LOG( SG_ALL, SG_DEBUG,
1049 "Elapsed time is zero ... we're zinging" );
1052 #if ! defined( macintosh )
1053 // Do any I/O channel work that might need to be done
1057 // see if we need to load any deferred-load textures
1058 material_lib.load_next_deferred();
1060 // Run audio scheduler
1061 #ifdef ENABLE_AUDIO_SUPPORT
1062 if ( fgGetBool("/sim/sound/audible")
1063 && globals->get_soundmgr()->is_working() ) {
1064 globals->get_fx()->update(1); // FIXME: use dt
1065 globals->get_soundmgr()->update(1); // FIXME: use dt
1070 // Tile Manager updates - see if we need to load any new scenery tiles.
1071 // this code ties together the fdm, viewer and scenery classes...
1072 // we may want to move this to it's own class at some point
1074 double visibility_meters = fgGetDouble("/environment/visibility-m");
1075 FGViewer *current_view = globals->get_current_view();
1077 // update tile manager for FDM...
1078 // ...only if location is different than the viewer (to avoid duplicating effort)
1079 if( acmodel_location != current_view->getFGLocation() ) {
1080 if( acmodel_location != 0 ) {
1081 global_tile_mgr.prep_ssg_nodes(visibility_meters,
1082 acmodel_location->get_world_up(),
1083 acmodel_location->get_tile_center());
1084 global_tile_mgr.update( acmodel_location->getLongitude_deg(),
1085 acmodel_location->getLatitude_deg(),
1087 acmodel_location->get_absolute_view_pos(),
1088 acmodel_location->get_current_bucket(),
1089 acmodel_location->get_previous_bucket(),
1090 acmodel_location->get_tile_center()
1092 // save results of update in FGLocation for fdm...
1093 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1094 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1096 acmodel_location->set_current_bucket( global_tile_mgr.get_current_bucket() );
1097 acmodel_location->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1098 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1102 global_tile_mgr.prep_ssg_nodes(visibility_meters,
1103 current_view->getFGLocation()->get_world_up(),
1104 current_view->getFGLocation()->get_tile_center());
1105 // update tile manager for view...
1106 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1107 // after the FDM's until all of Flight Gear code references the viewer's location
1108 // for elevation instead of the "scenery's" current elevation.
1109 global_tile_mgr.update( current_view->getLongitude_deg(),
1110 current_view->getLatitude_deg(),
1112 current_view->get_absolute_view_pos(),
1113 current_view->getFGLocation()->get_current_bucket(),
1114 current_view->getFGLocation()->get_previous_bucket(),
1115 current_view->getFGLocation()->get_tile_center()
1117 // save results of update in FGLocation for fdm...
1118 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1119 current_view->getFGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1121 current_view->getFGLocation()->set_current_bucket( global_tile_mgr.get_current_bucket() );
1122 current_view->getFGLocation()->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1123 current_view->getFGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1125 // If fdm location is same as viewer's then we didn't do the update for fdm location
1126 // above so we need to save the viewer results in the fdm FGLocation as well...
1127 if( acmodel_location == current_view->getFGLocation() ) {
1128 if( acmodel_location != 0 ) {
1129 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1130 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1132 acmodel_location->set_current_bucket( global_tile_mgr.get_current_bucket() );
1133 acmodel_location->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1134 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1138 // END Tile Manager udpates
1143 SG_LOG( SG_ALL, SG_DEBUG, "" );
1147 // This is the top level master main function that is registered as
1148 // our idle funciton
1150 // The first few passes take care of initialization things (a couple
1151 // per pass) and once everything has been initialized fgMainLoop from
1154 static void fgIdleFunction ( void ) {
1155 // printf("idle state == %d\n", idle_state);
1157 if ( idle_state == 0 ) {
1158 // Initialize the splash screen right away
1159 if ( fgGetBool("/sim/startup/splash-screen") ) {
1164 } else if ( idle_state == 1 ) {
1165 // Initialize audio support
1166 #ifdef ENABLE_AUDIO_SUPPORT
1168 // Start the intro music
1169 if ( fgGetBool("/sim/startup/intro-music") ) {
1170 SGPath mp3file( globals->get_fg_root() );
1171 mp3file.append( "Sounds/intro.mp3" );
1173 SG_LOG( SG_GENERAL, SG_INFO,
1174 "Starting intro music: " << mp3file.str() );
1176 #if defined( __CYGWIN__ )
1177 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1178 #elif defined( WIN32 )
1179 string command = "start /m " + mp3file.str();
1181 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1184 system ( command.c_str() );
1189 } else if ( idle_state == 2 ) {
1190 // These are a few miscellaneous things that aren't really
1191 // "subsystems" but still need to be initialized.
1194 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1195 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1200 } else if ( idle_state == 3 ) {
1201 // This is the top level init routine which calls all the
1202 // other subsystem initialization routines. If you are adding
1203 // a subsystem to flightgear, its initialization call should
1204 // located in this routine.
1205 if( !fgInitSubsystems()) {
1206 SG_LOG( SG_GENERAL, SG_ALERT,
1207 "Subsystem initializations failed ..." );
1212 } else if ( idle_state == 4 ) {
1213 // setup OpenGL view parameters
1217 } else if ( idle_state == 5 ) {
1220 } else if ( idle_state == 6 ) {
1224 cout << "Panel visible = " << fgPanelVisible() << endl;
1225 fgReshape( fgGetInt("/sim/startup/xsize"),
1226 fgGetInt("/sim/startup/ysize") );
1229 if ( idle_state == 1000 ) {
1230 // We've finished all our initialization steps, from now on we
1231 // run the main loop.
1233 glutIdleFunc(fgMainLoop);
1235 if ( fgGetBool("/sim/startup/splash-screen") ) {
1236 fgSplashUpdate(0.0);
1241 // options.cxx needs to see this for toggle_panel()
1242 // Handle new window size or exposure
1243 void fgReshape( int width, int height ) {
1246 if ( (!fgGetBool("/sim/virtual-cockpit"))
1247 && fgPanelVisible() && idle_state == 1000 ) {
1248 view_h = (int)(height * (current_panel->getViewHeight() -
1249 current_panel->getYOffset()) / 768.0);
1255 FGViewMgr *viewmgr = globals->get_viewmgr();
1256 for ( int i = 0; i < viewmgr->size(); ++i ) {
1257 viewmgr->get_view(i)->
1258 set_aspect_ratio((float)view_h / (float)width);
1261 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1263 fgSetInt("/sim/startup/xsize", width);
1264 fgSetInt("/sim/startup/ysize", height);
1265 guiInitMouse(width, height);
1267 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1268 viewmgr->get_current_view()->get_v_fov() );
1273 // Initialize GLUT and define a main window
1274 int fgGlutInit( int *argc, char **argv ) {
1276 #if !defined( macintosh )
1277 // GLUT will extract all glut specific options so later on we only
1278 // need wory about our own.
1279 glutInit(argc, argv);
1282 // Define Display Parameters
1283 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1285 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1286 fgGetInt("/sim/startup/xsize") << "x"
1287 << fgGetInt("/sim/startup/ysize") );
1289 // Define initial window size
1290 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1291 fgGetInt("/sim/startup/ysize") );
1293 // Initialize windows
1294 if ( !fgGetBool("/sim/startup/game-mode")) {
1295 // Open the regular window
1296 glutCreateWindow("FlightGear");
1297 #ifndef GLUT_WRONG_VERSION
1299 // Open the cool new 'game mode' window
1300 char game_mode_str[256];
1301 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1302 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1303 #ifndef ENUM_CURRENT_SETTINGS
1304 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1305 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1309 dm.dmSize = sizeof(DEVMODE);
1310 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1311 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1312 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1313 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1314 fgGetInt("/sim/startup/ysize") );
1315 sprintf( game_mode_str, "%dx%d:%d@%d",
1319 dm.dmDisplayFrequency );
1321 // Open the cool new 'game mode' window
1322 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1323 fgGetInt("/sim/startup/xsize"),
1324 fgGetInt("/sim/startup/ysize"),
1325 fgGetInt("/sim/rendering/bits-per-pixel"));
1327 #endif // HAVE_WINDOWS_H
1328 SG_LOG( SG_GENERAL, SG_INFO,
1329 "game mode params = " << game_mode_str );
1330 glutGameModeString( game_mode_str );
1331 glutEnterGameMode();
1332 #endif // GLUT_WRONG_VERSION
1335 // This seems to be the absolute earliest in the init sequence
1336 // that these calls will return valid info. Too bad it's after
1337 // we've already created and sized out window. :-(
1338 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1339 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1340 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1341 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1344 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1345 general.set_glMaxTexSize( tmp );
1346 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1348 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1349 general.set_glDepthBits( tmp );
1350 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1356 // Initialize GLUT event handlers
1357 int fgGlutInitEvents( void ) {
1358 // call fgReshape() on window resizes
1359 glutReshapeFunc( fgReshape );
1361 // keyboard and mouse callbacks are set in FGInput::init
1363 // call fgMainLoop() whenever there is
1364 // nothing else to do
1365 glutIdleFunc( fgIdleFunction );
1368 glutDisplayFunc( fgRenderFrame );
1375 int mainLoop( int argc, char **argv ) {
1377 #if defined( macintosh )
1378 freopen ("stdout.txt", "w", stdout );
1379 freopen ("stderr.txt", "w", stderr );
1380 argc = ccommand( &argv );
1383 // set default log levels
1384 sglog().setLogLevels( SG_ALL, SG_INFO );
1387 #ifdef FLIGHTGEAR_VERSION
1388 version = FLIGHTGEAR_VERSION;
1390 version = "unknown version";
1392 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1394 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1396 // Allocate global data structures. This needs to happen before
1397 // we parse command line options
1399 globals = new FGGlobals;
1401 #ifndef FG_WEATHERCM
1402 globals->set_environment_mgr(new FGEnvironmentMgr);
1405 // seed the random number generater
1408 SGRoute *route = new SGRoute;
1409 globals->set_route( route );
1411 FGControls *controls = new FGControls;
1412 globals->set_controls( controls );
1414 string_list *col = new string_list;
1415 globals->set_channel_options_list( col );
1417 // Scan the config file(s) and command line options to see if
1418 // fg_root was specified (ignore all other options for now)
1419 fgInitFGRoot(argc, argv);
1421 // Check for the correct base package version
1422 string base_version = fgBasePackageVersion();
1423 if ( !(base_version == "0.7.11pre1") ) {
1424 // tell the operator how to use this application
1427 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1428 << "Found version " << base_version << " at: "
1429 << globals->get_fg_root() );
1430 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1434 // Initialize the Aircraft directory to "" (UIUC)
1437 // Load the configuration parameters
1438 if ( !fgInitConfig(argc, argv) ) {
1439 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1443 // Initialize the Window/Graphics environment.
1444 if( !fgGlutInit(&argc, argv) ) {
1445 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1449 // Initialize the various GLUT Event Handlers.
1450 if( !fgGlutInitEvents() ) {
1451 SG_LOG( SG_GENERAL, SG_ALERT,
1452 "GLUT event handler initialization failed ..." );
1456 // Initialize plib net interface
1457 netInit( &argc, argv );
1459 // Initialize ssg (from plib). Needs to come before we do any
1460 // other ssg stuff, but after opengl/glut has been initialized.
1463 // Initialize the user interface (we need to do this before
1464 // passing off control to glut and before fgInitGeneral to get our
1468 #ifdef GL_EXT_texture_lod_bias
1469 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1472 // Set position relative to glide slope if requested
1473 fgSetPosFromGlideSlope();
1475 // If we have an explicit, in-range lon/lat, use it.
1476 // If not, check for an airport-id and use that.
1477 // If not, default to the middle of the KSFO field.
1478 // The default values for lon/lat are deliberately out of range
1479 // so that the airport-id can take effect; valid lon/lat will
1480 // override airport-id, however.
1481 double lon_deg = fgGetDouble("/position/longitude-deg");
1482 double lat_deg = fgGetDouble("/position/latitude-deg");
1483 if (lon_deg < -180 || lon_deg > 180 || lat_deg < -90 || lat_deg > 90) {
1484 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1485 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1486 fgGetDouble("/orientation/heading-deg") );
1487 // set tower position (a little off the heading for single
1489 fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"),
1490 fgGetDouble("orientation/heading") );
1492 // Default to middle of KSFO field
1493 fgSetDouble("/position/longitude-deg", -122.374843);
1494 fgSetDouble("/position/latitude-deg", 37.619002);
1498 SGTime *t = fgInitTime();
1499 globals->set_time_params( t );
1501 // Do some quick general initializations
1502 if( !fgInitGeneral()) {
1503 SG_LOG( SG_GENERAL, SG_ALERT,
1504 "General initializations failed ..." );
1508 SGPath modelpath( globals->get_fg_root() );
1509 ssgModelPath( (char *)modelpath.c_str() );
1511 // Initialize the global scenery manager
1512 globals->set_scenery( new FGScenery );
1513 globals->get_scenery()->init();
1514 globals->get_scenery()->bind();
1516 ////////////////////////////////////////////////////////////////////
1517 // Initialize the general model subsystem.
1518 ////////////////////////////////////////////////////////////////////
1520 globals->set_model_mgr(new FGModelMgr);
1521 globals->get_model_mgr()->init();
1522 globals->get_model_mgr()->bind();
1524 ////////////////////////////////////////////////////////////////////
1525 // Initialize the 3D aircraft model subsystem.
1526 ////////////////////////////////////////////////////////////////////
1528 globals->set_aircraft_model(new FGAircraftModel);
1529 globals->get_aircraft_model()->init();
1530 globals->get_aircraft_model()->bind();
1532 ////////////////////////////////////////////////////////////////////
1533 // Initialize the view manager subsystem.
1534 ////////////////////////////////////////////////////////////////////
1536 FGViewMgr *viewmgr = new FGViewMgr;
1537 globals->set_viewmgr( viewmgr );
1542 // Initialize the sky
1543 SGPath ephem_data_path( globals->get_fg_root() );
1544 ephem_data_path.append( "Astro" );
1545 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1546 ephem->update( globals->get_time_params()->getMjd(),
1547 globals->get_time_params()->getLst(),
1549 globals->set_ephem( ephem );
1553 SGPath sky_tex_path( globals->get_fg_root() );
1554 sky_tex_path.append( "Textures" );
1555 sky_tex_path.append( "Sky" );
1556 thesky->texture_path( sky_tex_path.str() );
1558 thesky->build( 550.0, 550.0,
1559 globals->get_ephem()->getNumPlanets(),
1560 globals->get_ephem()->getPlanets(), 60000.0,
1561 globals->get_ephem()->getNumStars(),
1562 globals->get_ephem()->getStars(), 60000.0 );
1564 // Initialize MagVar model
1565 SGMagVar *magvar = new SGMagVar();
1566 globals->set_mag( magvar );
1568 // airport = new ssgBranch;
1569 // airport->setName( "Airport Lighting" );
1570 // lighting->addKid( airport );
1576 #ifdef FG_NETWORK_OLK
1577 // Do the network intialization
1578 if ( fgGetBool("/sim/networking/network-olk") ) {
1579 printf("Multipilot mode %s\n",
1580 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1584 // build our custom render states
1585 fgBuildRenderStates();
1587 // pass control off to the master GLUT event handler
1590 // we never actually get here ... but to avoid compiler warnings,
1596 // $$$ end - added VS Renganathan, 15 Oct 2K
1597 // - added Venky , 12 Nov 2K
1599 #if defined(__linux__) && defined(__i386__)
1601 static void handleFPE (int);
1606 fpu_control_t fpe_flags = 0;
1607 _FPU_GETCW(fpe_flags);
1608 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1609 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1610 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1611 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1612 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1613 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1614 _FPU_SETCW(fpe_flags);
1615 signal(SIGFPE, handleFPE);
1622 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1626 // Main entry point; catch any exceptions that have made it this far.
1627 int main ( int argc, char **argv ) {
1629 // Enable floating-point exceptions for Linux/x86
1630 #if defined(__linux__) && defined(__i386__)
1634 // Enable floating-point exceptions for Windows
1635 #if defined( _MSC_VER ) && defined( DEBUG )
1636 // Christian, we should document what this does
1637 _control87( _EM_INEXACT, _MCW_EM );
1640 #if defined( HAVE_BC5PLUS )
1641 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1644 // FIXME: add other, more specific
1647 mainLoop(argc, argv);
1648 } catch (sg_throwable &t) {
1649 // We must use cerr rather than
1650 // logging, since logging may be
1652 cerr << "Fatal error: " << t.getFormattedMessage()
1653 << "\n (received from " << t.getOrigin() << ')' << endl;
1661 void fgLoadDCS(void) {
1663 ssgEntity *ship_obj = NULL;
1665 char obj_filename[25];
1667 for ( int k = 0; k < 32; k++ ) {
1671 SGPath tile_path( globals->get_fg_root());
1672 tile_path.append( "Scenery" );
1673 tile_path.append( "Objects.txt" );
1674 sg_gzifstream in( tile_path.str() );
1675 if ( ! in.is_open() ) {
1676 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1679 SGPath modelpath( globals->get_fg_root() );
1680 modelpath.append( "Models" );
1681 modelpath.append( "Geometry" );
1683 SGPath texturepath( globals->get_fg_root() );
1684 texturepath.append( "Models" );
1685 texturepath.append( "Textures" );
1687 ssgModelPath( (char *)modelpath.c_str() );
1688 ssgTexturePath( (char *)texturepath.c_str() );
1690 ship_sel = new ssgSelector;
1693 while ( ! in.eof() ) {
1695 if ( in.get( c ) && c == '#' ) {
1699 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1700 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1701 int chj=getchar();*/
1703 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1704 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1706 ship_pos[objc] = new ssgTransform;
1708 // type "repeat" in objects.txt to load one more
1709 // instance of the last object.
1711 if ( strcmp(obj_filename,"repeat") != 0) {
1712 ship_obj = ssgLoad( obj_filename );
1715 if ( ship_obj != NULL ) {
1716 ship_obj->setName(obj_filename);
1718 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1720 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1721 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1722 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1723 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1726 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1730 // temporary hack for deck lights - ultimately should move to PLib (when??)
1731 //const char *extn = file_extension ( obj_filename ) ;
1733 ssgVertexArray *lights = new ssgVertexArray( 100 );
1734 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1735 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1736 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1737 int ltype[500], light_type;
1738 static int ltcount = 0;
1740 sgVec3 rway_dir,rway_normal,lightpt;
1742 modelpath.append(obj_filename);
1743 sg_gzifstream in1( modelpath.str() );
1744 if ( ! in1.is_open() ) {
1745 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1747 while ( ! in1.eof() ) {
1749 if ( in1.get( c ) && c == '#' ) {
1754 //cout << token << endl;
1755 if ( token == "runway" ) {
1757 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1758 } else if ( token == "edgelight" ) {
1760 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1762 } else if ( token == "taxi" ) {
1764 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1766 } else if ( token == "vasi" ) {
1768 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1770 } else if ( token == "threshold" ) {
1772 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1774 } else if ( token == "rabbit" ) {
1776 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1778 } else if ( token == "ols" ) {
1780 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1782 } else if ( token == "red" ) {
1784 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1786 } else if ( token == "green" ) {
1788 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1790 } else if ( token == "lp" ) {
1792 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1793 lightpoints->add( lightpt );
1794 lightnormals->add( rway_normal );
1795 lightdir->add( rway_dir );
1796 ltype[ltcount]= light_type;
1799 if (in1.eof()) break;
1803 if ( lightpoints->getNum() ) {
1804 ssgBranch *lightpoints_branch;
1805 long int dummy = -999;
1806 dummy_tile = new FGTileEntry((SGBucket)dummy);
1807 dummy_tile->lightmaps_sequence = new ssgSelector;
1808 dummy_tile->ols_transform = new ssgTransform;
1810 // call function to generate the runway lights
1811 lightpoints_branch =
1812 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1814 lightpoints_brightness->addKid(lightpoints_branch);
1815 lightpoints_transform->addKid(lightpoints_brightness);
1816 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1817 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1818 lightpoints_transform->ref();
1819 globals->get_scenery()->get_gnd_lights_branch()->addKid( lightpoints_transform );
1823 // end hack for deck lights
1827 if (in.eof()) break;
1831 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1833 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
1840 void fgUpdateDCS (void) {
1842 // double eye_lat,eye_lon,eye_alt;
1843 // static double obj_head;
1844 double sl_radius,obj_latgc;
1845 // float nresultmat[4][4];
1846 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1849 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1850 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1852 // Deck should be the first object in objects.txt in case of fdm=ada
1854 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1855 if ((fdm->get_iaux(1))==1)
1857 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1858 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1859 obj_alt[1] = fdm->get_daux(3);
1860 obj_pitch[1] = fdm->get_faux(1);
1861 obj_roll[1] = fdm->get_faux(2);
1865 for ( int m = 0; m < objc; m++ ) {
1866 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1869 //Geodetic to Geocentric angles for rotation
1870 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1872 //moving object gbs-posn in cartesian coords
1873 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1874 Point3D obj_pos = sgGeodToCart( obj_posn );
1876 // Translate moving object w.r.t eye
1877 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
1882 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1885 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1887 sgVec3 ship_fwd,ship_rt,ship_up;
1888 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1889 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1890 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1892 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1893 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1894 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1895 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1896 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1897 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1900 sgCopyMat4( sgTUX, sgROT_hdg );
1901 sgPostMultMat4( sgTUX, sgROT_pitch );
1902 sgPostMultMat4( sgTUX, sgROT_roll );
1903 sgPostMultMat4( sgTUX, sgROT_lat );
1904 sgPostMultMat4( sgTUX, sgROT_lon );
1905 sgPostMultMat4( sgTUX, sgTRANS );
1908 sgSetCoord(&shippos, sgTUX );
1909 ship_pos[m]->setTransform( &shippos );
1910 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1912 if (lightpoints_transform) {
1913 lightpoints_transform->setTransform( &shippos );
1914 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1915 if ( sun_angle > 89 ) {
1916 lightpoints_brightness->select(0x01);
1918 lightpoints_brightness->select(0x00);
1927 sgXformPnt3( rp, rway_ols, sgTUX );
1928 vp = globals->get_current_view()->get_view_pos();
1929 to[0] = rp[0]-vp[0];
1930 to[1] = rp[1]-vp[1];
1931 to[2] = rp[2]-vp[2];
1932 float dist = sgLengthVec3( to );
1933 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1935 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1937 ref_elev = elev - 3.75; // +ve above, -ve below
1941 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1942 // if (ref_elev > 0.51) sel = 0x21;
1943 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1944 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1945 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1946 // if (ref_elev < -0.51) sel = 0x30;
1947 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1948 dummy_tile->lightmaps_sequence->select(sel);
1951 sgCopyVec3 (up, ship_up);
1953 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1955 sgScaleVec3 (up, 4.0*ref_elev);
1956 dummy_tile->ols_transform->setTransform(up);
1957 //cout << "ref_elev " << ref_elev << endl;
1959 // end hack for deck lights
1962 if ( ship_sel != NULL ) {
1963 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1967 // $$$ end - added VS Renganathan, 15 Oct 2K
1968 // added Venky , 12 Nov 2K