1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 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>
43 #ifdef SG_MATH_EXCEPTION_CLASH
56 #include <string.h> // for strcmp()
63 #ifdef HAVE_SYS_STAT_H
64 # include <sys/stat.h> // for stat()
68 # include <unistd.h> // for stat()
71 #include <plib/netChat.h>
75 #include <simgear/constants.h> // for VERSION
76 #include <simgear/debug/logstream.hxx>
77 #include <simgear/math/polar3d.hxx>
78 #include <simgear/math/sg_random.h>
79 #include <simgear/misc/sg_path.hxx>
80 #include <simgear/sky/sky.hxx>
81 #include <simgear/timing/sg_time.hxx>
83 #include <Include/general.hxx>
85 #include <Aircraft/aircraft.hxx>
87 #include <ATC/ATCmgr.hxx>
88 #include <ATC/ATCdisplay.hxx>
89 #include <ATC/AIMgr.hxx>
91 #include <Autopilot/newauto.hxx>
93 #include <Cockpit/cockpit.hxx>
94 #include <Cockpit/radiostack.hxx>
95 #include <Cockpit/steam.hxx>
97 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
99 // #include <Joystick/joystick.hxx>
100 #ifdef FG_NETWORK_OLK
101 #include <NetworkOLK/network.h>
103 #include <Objects/matlib.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #ifdef ENABLE_AUDIO_SUPPORT
107 # include <Sound/soundmgr.hxx>
108 # include <Sound/fg_fx.hxx>
109 # include <Sound/morse.hxx>
111 #include <Time/event.hxx>
112 #include <Time/fg_timer.hxx>
113 #include <Time/light.hxx>
114 #include <Time/sunpos.hxx>
115 #include <Time/tmp.hxx>
117 #include <Input/input.hxx>
120 #include <simgear/misc/sgstream.hxx>
121 #include <simgear/math/point3d.hxx>
122 #include <FDM/flight.hxx>
123 #include <FDM/ADA.hxx>
124 #include <Scenery/tileentry.hxx>
126 // Should already be inlcluded by gl.h if needed by your platform so
127 // we shouldn't include this here.
128 // #include <GL/glext.h>
130 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
131 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
133 float default_attenuation[3] = {1.0, 0.0, 0.0};
134 //Required for using GL_extensions
135 void fgLoadDCS (void);
136 void fgUpdateDCS (void);
137 ssgSelector *ship_sel=NULL;
138 // upto 32 instances of a same object can be loaded.
139 ssgTransform *ship_pos[32];
140 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
142 ssgSelector *lightpoints_brightness = new ssgSelector;
143 ssgTransform *lightpoints_transform = new ssgTransform;
144 FGTileEntry *dummy_tile;
147 // Clip plane settings...
148 float cockpit_nearplane = 0.01f;
149 float cockpit_farplane = 100.0f;
150 float scene_nearplane = 0.5f;
151 float scene_farplane = 120000.0f;
154 #ifndef FG_NEW_ENVIRONMENT
155 # include <WeatherCM/FGLocalWeatherDatabase.h>
157 # include <Environment/environment_mgr.hxx>
162 #include "fg_init.hxx"
164 #include "fg_props.hxx"
165 #include "globals.hxx"
166 #include "splash.hxx"
167 #include "viewmgr.hxx"
168 #include "options.hxx"
169 #include "logger.hxx"
173 # include <console.h> // -dw- for command line dialog
177 // This is a record containing a bit of global housekeeping information
180 // Specify our current idle function state. This is used to run all
181 // our initializations out of the glutIdleLoop() so that we can get a
182 // splash screen up and running right away.
183 static int idle_state = 0;
184 static long global_multi_loop;
186 // forward declaration
187 void fgReshape( int width, int height );
190 ssgRoot *scene = NULL;
191 ssgRoot *cockpit = NULL;
192 ssgBranch *terrain_branch = NULL;
193 ssgBranch *gnd_lights_branch = NULL;
194 ssgBranch *rwy_lights_branch = NULL;
196 // fog constants. I'm a little nervous about putting actual code out
197 // here but it seems to work (?)
198 static const double m_log01 = -log( 0.01 );
199 static const double sqrt_m_log01 = sqrt( m_log01 );
200 static GLfloat fog_exp_density;
201 static GLfloat fog_exp2_density;
202 static GLfloat fog_exp2_punch_through;
204 ssgRoot *lighting = NULL;
205 // ssgBranch *airport = NULL;
207 #ifdef FG_NETWORK_OLK
208 ssgSelector *fgd_sel = NULL;
209 ssgTransform *fgd_pos = NULL;
212 // current fdm/position used for view
213 FGInterface cur_view_fdm;
219 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
221 { 1.0f, 0.0f, 0.0f, 0.0f },
222 { 0.0f, 0.0f, -1.0f, 0.0f },
223 { 0.0f, 1.0f, 0.0f, 0.0f },
224 { 0.0f, 0.0f, 0.0f, 1.0f }
227 // The following defines flightgear options. Because glutlib will also
228 // want to parse its own options, those options must not be included here
229 // or they will get parsed by the main program option parser. Hence case
230 // is significant for any option added that might be in conflict with
233 // glutlib parses for:
235 // -direct (invalid in Win32)
239 // -indirect (invalid in Win32)
242 // Note that glutlib depends upon strings while this program's
243 // option parser wants only initial characters followed by numbers
248 ssgSimpleState *default_state;
249 ssgSimpleState *hud_and_panel;
250 ssgSimpleState *menus;
252 SGTimeStamp start_time_stamp;
253 SGTimeStamp current_time_stamp;
255 void fgBuildRenderStates( void ) {
256 default_state = new ssgSimpleState;
257 default_state->ref();
258 default_state->disable( GL_TEXTURE_2D );
259 default_state->enable( GL_CULL_FACE );
260 default_state->enable( GL_COLOR_MATERIAL );
261 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
262 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
263 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
264 default_state->disable( GL_BLEND );
265 default_state->disable( GL_ALPHA_TEST );
266 default_state->disable( GL_LIGHTING );
268 hud_and_panel = new ssgSimpleState;
269 hud_and_panel->ref();
270 hud_and_panel->disable( GL_CULL_FACE );
271 hud_and_panel->disable( GL_TEXTURE_2D );
272 hud_and_panel->disable( GL_LIGHTING );
273 hud_and_panel->enable( GL_BLEND );
275 menus = new ssgSimpleState;
277 menus->disable( GL_CULL_FACE );
278 menus->disable( GL_TEXTURE_2D );
279 menus->enable( GL_BLEND );
282 // fgInitVisuals() -- Initialize various GL/view parameters
283 void fgInitVisuals( void ) {
286 l = &cur_light_params;
288 #ifndef GLUT_WRONG_VERSION
289 // Go full screen if requested ...
290 if ( fgGetBool("/sim/startup/fullscreen") ) {
295 // If enabled, normal vectors specified with glNormal are scaled
296 // to unit length after transformation. See glNormal.
297 // glEnable( GL_NORMALIZE );
299 glEnable( GL_LIGHTING );
300 glEnable( GL_LIGHT0 );
301 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
304 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
305 ssgGetLight( 0 ) -> setPosition( sunpos );
307 // glFogi (GL_FOG_MODE, GL_LINEAR);
308 glFogi (GL_FOG_MODE, GL_EXP2);
309 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
310 (!fgGetBool("/sim/rendering/shading"))) {
311 // if fastest fog requested, or if flat shading force fastest
312 glHint ( GL_FOG_HINT, GL_FASTEST );
313 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
314 glHint ( GL_FOG_HINT, GL_NICEST );
316 if ( fgGetBool("/sim/rendering/wireframe") ) {
318 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
321 // This is the default anyways, but it can't hurt
322 glFrontFace ( GL_CCW );
325 // glEnable(GL_POINT_SMOOTH);
326 // glEnable(GL_LINE_SMOOTH);
327 // glEnable(GL_POLYGON_SMOOTH);
331 // For HiRes screen Dumps using Brian Pauls TR Library
332 void trRenderFrame( void ) {
334 if ( fgPanelVisible() ) {
335 GLfloat height = fgGetInt("/sim/startup/ysize");
337 (current_panel->getViewHeight() - current_panel->getYOffset())
338 * (height / 768.0) + 1;
339 glTranslatef( 0.0, view_h, 0.0 );
342 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
343 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
345 fgLIGHT *l = &cur_light_params;
347 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
348 l->adj_fog_color[2], l->adj_fog_color[3]);
350 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
352 // set the opengl state to known default values
353 default_state->force();
356 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
357 glFogi ( GL_FOG_MODE, GL_EXP2 );
358 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
360 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
361 // we only update GL_AMBIENT for our lights we will never get
362 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
363 // explicitely to black.
364 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
366 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
368 // texture parameters
369 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
370 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
372 // we need a white diffuse light for the phase of the moon
373 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
376 // draw the ssg scene
377 // return to the desired diffuse color
378 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
379 glEnable( GL_DEPTH_TEST );
380 ssgSetNearFar( scene_nearplane, scene_farplane );
381 ssgCullAndDraw( scene );
383 // if in cockpit view adjust nearfar...
384 if (globals->get_current_view()->getType() == 0 )
385 ssgSetNearFar( cockpit_nearplane, cockpit_farplane );
386 ssgCullAndDraw( cockpit );
389 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
390 ssgSetNearFar( scene_nearplane, scene_farplane );
391 ssgCullAndDraw( lighting );
393 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
395 // need to do this here as hud_and_panel state is static to
396 // main.cxx and HUD and Panel routines have to be called with
397 // knowledge of the the TR struct < see gui.cxx::HighResDump()
398 hud_and_panel->apply();
402 // Update all Visuals (redraws anything graphics related)
403 void fgRenderFrame( void ) {
405 static long old_elapsed_ms = 0;
407 int dt_ms = int(globals->get_elapsed_time_ms() - old_elapsed_ms);
408 old_elapsed_ms = globals->get_elapsed_time_ms();
410 static const SGPropertyNode *longitude
411 = fgGetNode("/position/longitude-deg");
412 static const SGPropertyNode *latitude
413 = fgGetNode("/position/latitude-deg");
414 static const SGPropertyNode *altitude
415 = fgGetNode("/position/altitude-ft");
417 // Update the default (kludged) properties.
420 fgLIGHT *l = &cur_light_params;
421 static double last_visibility = -9999;
424 double actual_visibility = thesky->get_visibility();
425 if ( actual_visibility != last_visibility ) {
426 last_visibility = actual_visibility;
428 fog_exp_density = m_log01 / actual_visibility;
429 fog_exp2_density = sqrt_m_log01 / actual_visibility;
430 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
434 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
435 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
436 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
437 // GLfloat mat_shininess[] = { 10.0 };
438 GLbitfield clear_mask;
440 if ( idle_state != 1000 ) {
441 // still initializing, draw the splash screen
442 if ( fgGetBool("/sim/startup/splash-screen") ) {
445 start_time_stamp.stamp(); // Keep resetting the start time
447 // idle_state is now 1000 meaning we've finished all our
448 // initializations and are running the main loop, so this will
449 // now work without seg faulting the system.
451 // Update the elapsed time.
452 current_time_stamp.stamp();
453 globals->set_elapsed_time_ms((current_time_stamp - start_time_stamp)
456 // calculate our current position in cartesian space
457 scenery.set_center( scenery.get_next_center() );
460 fgReshape( fgGetInt("/sim/startup/xsize"),
461 fgGetInt("/sim/startup/ysize") );
463 // set the sun position
464 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
466 clear_mask = GL_DEPTH_BUFFER_BIT;
467 if ( fgGetBool("/sim/rendering/wireframe") ) {
468 clear_mask |= GL_COLOR_BUFFER_BIT;
471 if ( fgGetBool("/sim/rendering/skyblend") ) {
472 if ( fgGetBool("/sim/rendering/textures") ) {
473 // glClearColor(black[0], black[1], black[2], black[3]);
474 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
475 l->adj_fog_color[2], l->adj_fog_color[3]);
476 clear_mask |= GL_COLOR_BUFFER_BIT;
479 glClearColor(l->sky_color[0], l->sky_color[1],
480 l->sky_color[2], l->sky_color[3]);
481 clear_mask |= GL_COLOR_BUFFER_BIT;
483 glClear( clear_mask );
485 // Tell GL we are switching to model view parameters
487 // I really should create a derived ssg node or use a call
488 // back or something so that I can draw the sky within the
489 // ssgCullAndDraw() function, but for now I just mimic what
490 // ssg does to set up the model view matrix
491 glMatrixMode(GL_MODELVIEW);
493 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
495 // set the opengl state to known default values
496 default_state->force();
498 // update fog params if visibility has changed
499 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
501 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
502 ( global_multi_loop * fgGetInt("/sim/speed-up") )
503 / (double)fgGetInt("/sim/model-hz") );
505 // Set correct opengl fog density
506 glFogf (GL_FOG_DENSITY, fog_exp2_density);
508 // update the sky dome
509 if ( fgGetBool("/sim/rendering/skyblend") ) {
510 /* cout << "thesky->repaint() sky_color = "
511 << cur_light_params.sky_color[0] << " "
512 << cur_light_params.sky_color[1] << " "
513 << cur_light_params.sky_color[2] << " "
514 << cur_light_params.sky_color[3] << endl;
516 << cur_light_params.fog_color[0] << " "
517 << cur_light_params.fog_color[1] << " "
518 << cur_light_params.fog_color[2] << " "
519 << cur_light_params.fog_color[3] << endl;
520 cout << " sun_angle = " << cur_light_params.sun_angle
521 << " moon_angle = " << cur_light_params.moon_angle
523 thesky->repaint( cur_light_params.sky_color,
524 cur_light_params.adj_fog_color,
525 cur_light_params.sun_angle,
526 cur_light_params.moon_angle,
527 globals->get_ephem()->getNumPlanets(),
528 globals->get_ephem()->getPlanets(),
529 globals->get_ephem()->getNumStars(),
530 globals->get_ephem()->getStars() );
532 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
533 << view_pos[1] << " " << view_pos[2] << endl;
534 cout << " zero_elev = " << zero_elev[0] << " "
535 << zero_elev[1] << " " << zero_elev[2]
536 << " lon = " << cur_fdm_state->get_Longitude()
537 << " lat = " << cur_fdm_state->get_Latitude() << endl;
538 cout << " sun_rot = " << cur_light_params.sun_rotation
539 << " gst = " << SGTime::cur_time_params->getGst() << endl;
540 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
541 << " sun dec = " << globals->get_ephem()->getSunDeclination()
542 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
543 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
545 thesky->reposition( globals->get_current_view()->get_view_pos(),
546 globals->get_current_view()->get_zero_elev(),
547 globals->get_current_view()->get_world_up(),
548 longitude->getDoubleValue()
549 * SGD_DEGREES_TO_RADIANS,
550 latitude->getDoubleValue()
551 * SGD_DEGREES_TO_RADIANS,
552 altitude->getDoubleValue() * SG_FEET_TO_METER,
553 cur_light_params.sun_rotation,
554 globals->get_time_params()->getGst(),
555 globals->get_ephem()->getSunRightAscension(),
556 globals->get_ephem()->getSunDeclination(),
558 globals->get_ephem()->getMoonRightAscension(),
559 globals->get_ephem()->getMoonDeclination(),
563 glEnable( GL_DEPTH_TEST );
564 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
566 glFogi( GL_FOG_MODE, GL_EXP2 );
567 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
570 // set sun/lighting parameters
571 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
573 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
574 // we only update GL_AMBIENT for our lights we will never get
575 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
576 // explicitely to black.
577 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
578 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
579 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
581 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
582 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
583 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
585 // texture parameters
586 // glEnable( GL_TEXTURE_2D );
587 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
588 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
590 // glMatrixMode( GL_PROJECTION );
592 ssgSetFOV( globals->get_current_view()->get_h_fov(),
593 globals->get_current_view()->get_v_fov() );
595 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
596 - scenery.get_cur_elev();
598 // if (fgGetBool("/sim/view/internal"))
599 // ssgSetNearFar( 0.2f, 120000.0f );
600 // else if ( agl > 10.0)
603 scene_nearplane = 10.0f;
604 scene_farplane = 120000.0f;
606 scene_nearplane = 0.5f;
607 scene_farplane = 120000.0f;
610 ssgSetNearFar( scene_nearplane, scene_farplane );
612 current_model.update(dt_ms);
614 // $$$ begin - added VS Renganthan 17 Oct 2K
616 // $$$ end - added VS Renganthan 17 Oct 2K
618 # ifdef FG_NETWORK_OLK
619 if ( fgGetBool("/sim/networking/network-olk") ) {
621 other = head->next; /* put listpointer to start */
622 while ( other != tail) { /* display all except myself */
623 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
624 other->fgd_sel->select(1);
625 sgSetCoord( &fgdpos, other->sgFGD_COORD );
626 other->fgd_pos->setTransform( &fgdpos );
631 // fgd_sel->select(1);
632 // sgCopyMat4( sgTUX, current_view.sgVIEW);
634 // sgSetCoord( &fgdpos, sgFGD_VIEW );
635 // fgd_pos->setTransform( &fgdpos);
639 // position tile nodes and update range selectors
640 global_tile_mgr.prep_ssg_nodes();
642 if ( fgGetBool("/sim/rendering/skyblend") ) {
643 // draw the sky backdrop
645 // we need a white diffuse light for the phase of the moon
646 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
650 // return to the desired diffuse color
651 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
654 // draw the ssg scene
655 glEnable( GL_DEPTH_TEST );
657 ssgSetNearFar( scene_nearplane, scene_farplane );
658 ssgCullAndDraw( scene );
660 // change state for lighting here
663 // Set punch through fog density
664 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
666 #ifdef FG_EXPERIMENTAL_LIGHTING
667 // Enable states for drawing points with GL_extension
668 if (glutExtensionSupported("GL_EXT_point_parameters")) {
669 glEnable(GL_POINT_SMOOTH);
670 float quadratic[3] = {1.0, 0.01, 0.0001};
671 // get the address of our OpenGL extensions
673 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
674 wglGetProcAddress("glPointParameterfEXT");
675 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
676 wglGetProcAddress("glPointParameterfvEXT");
678 // makes the points fade as they move away
679 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
680 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
683 // Enable states for drawing runway lights with spherical mapping
684 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
685 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
686 glEnable(GL_TEXTURE_GEN_S);
687 glEnable(GL_TEXTURE_GEN_T);
689 //Maybe this is not the best way, but it works !!
690 glPolygonMode(GL_FRONT, GL_POINT);
692 glEnable(GL_CULL_FACE);
695 glDisable( GL_LIGHTING );
696 // blending function for runway lights
697 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
701 ssgSetNearFar( scene_nearplane, scene_farplane );
702 ssgCullAndDraw( lighting );
705 #ifdef FG_EXPERIMENTAL_LIGHTING
706 if (glutExtensionSupported("GL_EXT_point_parameters")) {
707 // Disable states used for runway lighting
708 glPolygonMode(GL_FRONT, GL_FILL);
710 glDisable(GL_TEXTURE_GEN_S);
711 glDisable(GL_TEXTURE_GEN_T);
712 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
713 default_attenuation);
719 if ( fgGetBool("/sim/rendering/skyblend") ) {
720 // draw the sky cloud layers
721 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
724 // if in cockpit view adjust nearfar...
725 if (globals->get_current_view()->getType() == 0 ) {
727 glClear(GL_DEPTH_BUFFER_BIT);
728 ssgSetNearFar( cockpit_nearplane, cockpit_farplane );
729 ssgCullAndDraw( cockpit );
731 ssgCullAndDraw( cockpit );
734 // display HUD && Panel
736 glDisable( GL_DEPTH_TEST );
737 // glDisable( GL_CULL_FACE );
738 // glDisable( GL_TEXTURE_2D );
740 // update the input subsystem
741 current_input.update(dt_ms);
743 // update the controls subsystem
744 globals->get_controls()->update(dt_ms);
746 hud_and_panel->apply();
749 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
750 // This only works properly if called before the panel call
751 globals->get_ATC_display()->update(dt_ms);
753 // update the panel subsystem
754 if ( current_panel != NULL ) {
755 current_panel->update(dt_ms);
758 // We can do translucent menus, so why not. :-)
760 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
762 // glDisable ( GL_BLEND ) ;
764 // glEnable( GL_FOG );
766 globals->get_logger()->update(dt_ms);
773 // Update internal time dependent calculations (i.e. flight model)
774 void fgUpdateTimeDepCalcs() {
775 static bool inited = false;
776 static const SGPropertyNode *master_freeze
777 = fgGetNode("/sim/freeze/master");
779 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
781 fgLIGHT *l = &cur_light_params;
786 // Initialize the FDM here if it hasn't been and if we have a
787 // scenery elevation hit.
789 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
790 // << " cur_elev = " << scenery.get_cur_elev() << endl;
792 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
793 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
795 cur_fdm_state->init();
796 if ( cur_fdm_state->get_bound() ) {
797 cur_fdm_state->unbind();
799 cur_fdm_state->bind();
802 // conceptually, the following block could be done for each fdm
804 if ( !cur_fdm_state->get_inited() ) {
805 // do nothing, fdm isn't inited yet
806 } else if ( master_freeze->getBoolValue() ) {
807 // we are frozen, run the fdm's with 0 time slices in case
808 // they want to do something with that.
810 cur_fdm_state->update( 0 );
811 FGSteam::update( 0 );
813 // we have been inited, and we are not frozen, we are good to go ...
816 cur_fdm_state->stamp();
822 long elapsed = current - cur_fdm_state->get_time_stamp();
823 cur_fdm_state->set_time_stamp( current );
824 elapsed += cur_fdm_state->get_remainder();
825 // cout << "elapsed = " << elapsed << endl;
826 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
827 multi_loop = (long)(((double)elapsed * 0.000001) /
828 cur_fdm_state->get_delta_t() );
829 cur_fdm_state->set_multi_loop( multi_loop );
830 long remainder = elapsed - (long)( (multi_loop*1000000) *
831 cur_fdm_state->get_delta_t() );
832 cur_fdm_state->set_remainder( remainder );
833 // cout << "remainder = " << remainder << endl;
835 // chop max interations to something reasonable if the sim was
836 // delayed for an excesive amount of time
837 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
838 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
839 cur_fdm_state->set_remainder( 0 );
842 // cout << "multi_loop = " << multi_loop << endl;
843 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
844 // run Autopilot system
845 globals->get_autopilot()->update(0); // FIXME: use real dt
848 cur_fdm_state->update( 1 );
850 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
853 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
854 cur_view_fdm = *cur_fdm_state;
858 // update the view angle
859 globals->get_viewmgr()->update(multi_loop);
863 // Update solar system
864 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
865 globals->get_time_params()->getLst(),
866 cur_fdm_state->get_Latitude() );
868 // Update radio stack model
869 current_radiostack->update(multi_loop);
873 void fgInitTimeDepCalcs( void ) {
876 // #ifdef HAVE_SETITIMER
877 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
878 // fgUpdateTimeDepCalcs );
879 // #endif HAVE_SETITIMER
883 static const double alt_adjust_ft = 3.758099;
884 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
887 // What should we do when we have nothing else to do? Let's get ready
888 // for the next move and update the display?
889 static void fgMainLoop( void ) {
890 static const SGPropertyNode *longitude
891 = fgGetNode("/position/longitude-deg");
892 static const SGPropertyNode *latitude
893 = fgGetNode("/position/latitude-deg");
894 static const SGPropertyNode *altitude
895 = fgGetNode("/position/altitude-ft");
896 static const SGPropertyNode *clock_freeze
897 = fgGetNode("/sim/freeze/clock", true);
898 static const SGPropertyNode *cur_time_override
899 = fgGetNode("/sim/time/cur-time-override", true);
901 static long remainder = 0;
903 #ifdef FANCY_FRAME_COUNTER
907 static time_t last_time = 0;
908 static int frames = 0;
909 #endif // FANCY_FRAME_COUNTER
911 SGTime *t = globals->get_time_params();
913 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
914 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
916 #ifdef FG_NETWORK_OLK
917 if ( fgGetBool("/sim/networking/network-olk") ) {
918 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
919 // printf("FGD: Netupdate\n");
920 fgd_send_com( "A", FGFS_host); // Send Mat4 data
921 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
926 #if defined( ENABLE_PLIB_JOYSTICK )
927 // Read joystick and update control settings
928 // if ( fgGetString("/sim/control-mode") == "joystick" )
932 #elif defined( ENABLE_GLUT_JOYSTICK )
933 // Glut joystick support works by feeding a joystick handler
934 // function to glut. This is taken care of once in the joystick
935 // init routine and we don't have to worry about it again.
938 #ifdef FG_NEW_ENVIRONMENT
939 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
942 // Fix elevation. I'm just sticking this here for now, it should
943 // probably move eventually
945 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
946 scenery.get_cur_elev(),
947 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
948 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
950 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
951 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
952 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
953 // now set aircraft altitude above ground
954 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
955 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
956 scenery.get_cur_elev() + alt_adjust_m - 3.0,
957 scenery.get_cur_elev() + alt_adjust_m );
958 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
961 SG_LOG( SG_ALL, SG_DEBUG,
962 "<*> resetting altitude to "
963 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
968 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
969 scenery.get_cur_elev(),
970 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
971 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
973 // cout << "Warp = " << globals->get_warp() << endl;
976 static bool last_clock_freeze = false;
978 if ( clock_freeze->getBoolValue() ) {
979 // clock freeze requested
980 if ( cur_time_override->getLongValue() == 0 ) {
981 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
982 globals->set_warp( 0 );
985 // no clock freeze requested
986 if ( last_clock_freeze == true ) {
987 // clock just unfroze, let's set warp as the difference
988 // between frozen time and current time so we don't get a
989 // time jump (and corresponding sky object and lighting
991 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
992 fgSetLong( "/sim/time/cur-time-override", 0 );
994 if ( globals->get_warp_delta() != 0 ) {
995 globals->inc_warp( globals->get_warp_delta() );
999 last_clock_freeze = clock_freeze->getBoolValue();
1001 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1002 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1003 cur_time_override->getLongValue(),
1004 globals->get_warp() );
1006 if ( globals->get_warp_delta() != 0 ) {
1007 fgUpdateSkyAndLightingParams();
1010 // update magvar model
1011 globals->get_mag()->update( longitude->getDoubleValue()
1012 * SGD_DEGREES_TO_RADIANS,
1013 latitude->getDoubleValue()
1014 * SGD_DEGREES_TO_RADIANS,
1015 altitude->getDoubleValue() * SG_FEET_TO_METER,
1016 globals->get_time_params()->getJD() );
1018 // Get elapsed time (in usec) for this past frame
1019 elapsed = fgGetTimeInterval();
1020 SG_LOG( SG_ALL, SG_DEBUG,
1021 "Elapsed time interval is = " << elapsed
1022 << ", previous remainder is = " << remainder );
1024 // Calculate frame rate average
1025 #ifdef FANCY_FRAME_COUNTER
1026 /* old fps calculation */
1027 if ( elapsed > 0 ) {
1030 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1031 tmp = general.get_frame(i);
1033 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1034 general.set_frame(i+1,tmp);
1036 tmp = 1000000.0 / (float)elapsed;
1037 general.set_frame(0,tmp);
1038 // printf("frame[0] = %.2f\n", general.frames[0]);
1040 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1041 // printf("ave = %.2f\n", general.frame_rate);
1044 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1045 general.set_frame_rate( frames );
1046 SG_LOG( SG_ALL, SG_DEBUG,
1047 "--> Frame rate is = " << general.get_frame_rate() );
1050 last_time = t->get_cur_time();
1054 // Run ATC subsystem
1055 globals->get_ATC_mgr()->update(1); // FIXME - use real dt.
1057 // Run the AI subsystem
1058 globals->get_AI_mgr()->update(1); // FIXME - use real dt.
1062 // Calculate model iterations needed for next frame
1063 elapsed += remainder;
1065 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1066 fgGetInt("/sim/model-hz"));
1067 remainder = elapsed - ( (global_multi_loop*1000000) /
1068 fgGetInt("/sim/model-hz") );
1069 SG_LOG( SG_ALL, SG_DEBUG,
1070 "Model iterations needed = " << global_multi_loop
1071 << ", new remainder = " << remainder );
1073 // chop max interations to something reasonable if the sim was
1074 // delayed for an excesive amount of time
1075 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1076 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1081 if ( global_multi_loop > 0 ) {
1082 fgUpdateTimeDepCalcs();
1084 SG_LOG( SG_ALL, SG_DEBUG,
1085 "Elapsed time is zero ... we're zinging" );
1088 #if ! defined( macintosh )
1089 // Do any I/O channel work that might need to be done
1093 // see if we need to load any new scenery tiles
1094 global_tile_mgr.update( longitude->getDoubleValue(),
1095 latitude->getDoubleValue() );
1097 // see if we need to load any deferred-load textures
1098 material_lib.load_next_deferred();
1100 // Process/manage pending events
1101 global_events.Process();
1103 // Run audio scheduler
1104 #ifdef ENABLE_AUDIO_SUPPORT
1105 if ( fgGetBool("/sim/sound/audible")
1106 && globals->get_soundmgr()->is_working() ) {
1107 globals->get_fx()->update(1); // FIXME: use dt
1108 globals->get_soundmgr()->update(1); // FIXME: use dt
1115 SG_LOG( SG_ALL, SG_DEBUG, "" );
1119 // This is the top level master main function that is registered as
1120 // our idle funciton
1123 // The first few passes take care of initialization things (a couple
1124 // per pass) and once everything has been initialized fgMainLoop from
1127 static void fgIdleFunction ( void ) {
1128 // printf("idle state == %d\n", idle_state);
1130 if ( idle_state == 0 ) {
1131 // Initialize the splash screen right away
1132 if ( fgGetBool("/sim/startup/splash-screen") ) {
1137 } else if ( idle_state == 1 ) {
1138 // Initialize audio support
1139 #ifdef ENABLE_AUDIO_SUPPORT
1141 // Start the intro music
1142 if ( fgGetBool("/sim/startup/intro-music") ) {
1143 SGPath mp3file( globals->get_fg_root() );
1144 mp3file.append( "Sounds/intro.mp3" );
1146 SG_LOG( SG_GENERAL, SG_INFO,
1147 "Starting intro music: " << mp3file.str() );
1149 #if defined( __CYGWIN__ )
1150 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1151 #elif defined( WIN32 )
1152 string command = "start /m " + mp3file.str();
1154 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1157 system ( command.c_str() );
1163 } else if ( idle_state == 2 ) {
1164 // These are a few miscellaneous things that aren't really
1165 // "subsystems" but still need to be initialized.
1168 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1169 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1174 } else if ( idle_state == 3 ) {
1175 // This is the top level init routine which calls all the
1176 // other subsystem initialization routines. If you are adding
1177 // a subsystem to flightgear, its initialization call should
1178 // located in this routine.
1179 if( !fgInitSubsystems()) {
1180 SG_LOG( SG_GENERAL, SG_ALERT,
1181 "Subsystem initializations failed ..." );
1186 } else if ( idle_state == 4 ) {
1187 // setup OpenGL view parameters
1191 } else if ( idle_state == 5 ) {
1194 } else if ( idle_state == 6 ) {
1198 cout << "Panel visible = " << fgPanelVisible() << endl;
1199 fgReshape( fgGetInt("/sim/startup/xsize"),
1200 fgGetInt("/sim/startup/ysize") );
1203 if ( idle_state == 1000 ) {
1204 // We've finished all our initialization steps, from now on we
1205 // run the main loop.
1209 if ( fgGetBool("/sim/startup/splash-screen") ) {
1210 fgSplashUpdate(0.0);
1215 // options.cxx needs to see this for toggle_panel()
1216 // Handle new window size or exposure
1217 void fgReshape( int width, int height ) {
1220 if ( (!fgGetBool("/sim/virtual-cockpit"))
1221 && fgPanelVisible() && idle_state == 1000 ) {
1222 view_h = (int)(height * (current_panel->getViewHeight() -
1223 current_panel->getYOffset()) / 768.0);
1229 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1230 globals->get_viewmgr()->get_view(i)->
1231 set_aspect_ratio((float)view_h / (float)width);
1234 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1236 fgSetInt("/sim/startup/xsize", width);
1237 fgSetInt("/sim/startup/ysize", height);
1238 guiInitMouse(width, height);
1240 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1241 globals->get_current_view()->get_v_fov() );
1247 // Initialize GLUT and define a main window
1248 int fgGlutInit( int *argc, char **argv ) {
1250 #if !defined( macintosh )
1251 // GLUT will extract all glut specific options so later on we only
1252 // need wory about our own.
1253 glutInit(argc, argv);
1256 // Define Display Parameters
1257 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1259 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1260 fgGetInt("/sim/startup/xsize") << "x"
1261 << fgGetInt("/sim/startup/ysize") );
1263 // Define initial window size
1264 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1265 fgGetInt("/sim/startup/ysize") );
1267 // Initialize windows
1268 if ( !fgGetBool("/sim/startup/game-mode")) {
1269 // Open the regular window
1270 glutCreateWindow("FlightGear");
1271 #ifndef GLUT_WRONG_VERSION
1273 // Open the cool new 'game mode' window
1274 char game_mode_str[256];
1275 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1276 fgGetInt("/sim/startup/xsize"),
1277 fgGetInt("/sim/startup/ysize"),
1278 fgGetInt("/sim/rendering/bits-per-pixel"));
1280 SG_LOG( SG_GENERAL, SG_INFO,
1281 "game mode params = " << game_mode_str );
1282 glutGameModeString( game_mode_str );
1283 glutEnterGameMode();
1287 // This seems to be the absolute earliest in the init sequence
1288 // that these calls will return valid info. Too bad it's after
1289 // we've already created and sized out window. :-(
1290 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1291 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1292 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1293 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1296 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1297 general.set_glMaxTexSize( tmp );
1298 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1300 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1301 general.set_glDepthBits( tmp );
1302 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1308 // Initialize GLUT event handlers
1309 int fgGlutInitEvents( void ) {
1310 // call fgReshape() on window resizes
1311 glutReshapeFunc( fgReshape );
1313 // keyboard and mouse callbacks are set in FGInput::init
1315 #ifndef FG_NEW_MOUSE
1316 // call guiMouseFunc() whenever our little rodent is used
1317 glutMouseFunc ( guiMouseFunc );
1318 glutMotionFunc (guiMotionFunc );
1319 glutPassiveMotionFunc (guiMotionFunc );
1322 // call fgMainLoop() whenever there is
1323 // nothing else to do
1324 glutIdleFunc( fgIdleFunction );
1327 glutDisplayFunc( fgRenderFrame );
1334 int mainLoop( int argc, char **argv ) {
1336 #if defined( macintosh )
1337 freopen ("stdout.txt", "w", stdout );
1338 freopen ("stderr.txt", "w", stderr );
1339 argc = ccommand( &argv );
1342 // set default log levels
1343 sglog().setLogLevels( SG_ALL, SG_INFO );
1346 #ifdef FLIGHTGEAR_VERSION
1347 version = FLIGHTGEAR_VERSION;
1349 version = "unknown version";
1351 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1352 << version << endl );
1354 // Allocate global data structures. This needs to happen before
1355 // we parse command line options
1357 globals = new FGGlobals;
1359 #if defined(FG_NEW_ENVIRONMENT)
1360 globals->set_environment_mgr(new FGEnvironmentMgr);
1363 // seed the random number generater
1366 SGRoute *route = new SGRoute;
1367 globals->set_route( route );
1369 FGControls *controls = new FGControls;
1370 globals->set_controls( controls );
1372 FGViewMgr *viewmgr = new FGViewMgr;
1373 globals->set_viewmgr( viewmgr );
1377 string_list *col = new string_list;
1378 globals->set_channel_options_list( col );
1380 // Scan the config file(s) and command line options to see if
1381 // fg_root was specified (ignore all other options for now)
1382 fgInitFGRoot(argc, argv);
1384 // Check for the correct base package version
1385 string base_version = fgBasePackageVersion();
1386 if ( !(base_version == "0.7.9") ) {
1387 // tell the operator how to use this application
1390 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1391 << "Found version " << base_version << " at: "
1392 << globals->get_fg_root() );
1393 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1397 // Initialize the Aircraft directory to "" (UIUC)
1400 // Load the configuration parameters
1401 if ( !fgInitConfig(argc, argv) ) {
1402 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1406 // Initialize the Window/Graphics environment.
1407 if( !fgGlutInit(&argc, argv) ) {
1408 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1412 // Initialize the various GLUT Event Handlers.
1413 if( !fgGlutInitEvents() ) {
1414 SG_LOG( SG_GENERAL, SG_ALERT,
1415 "GLUT event handler initialization failed ..." );
1419 // Initialize plib net interface
1420 netInit( &argc, argv );
1422 // Initialize ssg (from plib). Needs to come before we do any
1423 // other ssg stuff, but after opengl/glut has been initialized.
1426 // Initialize the user interface (we need to do this before
1427 // passing off control to glut and before fgInitGeneral to get our
1431 #ifdef GL_EXT_texture_lod_bias
1432 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1435 // Set position relative to glide slope if requested
1436 fgSetPosFromGlideSlope();
1438 // set current_options lon/lat if an airport id is specified
1439 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1440 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1441 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1442 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1443 fgGetDouble("/orientation/heading-deg") );
1446 SGTime *t = fgInitTime();
1447 globals->set_time_params( t );
1449 // Do some quick general initializations
1450 if( !fgInitGeneral()) {
1451 SG_LOG( SG_GENERAL, SG_ALERT,
1452 "General initializations failed ..." );
1456 SGPath modelpath( globals->get_fg_root() );
1457 ssgModelPath( (char *)modelpath.c_str() );
1460 scene = new ssgRoot;
1461 scene->setName( "Scene" );
1463 // Scene graph root for cockpit
1464 cockpit = new ssgRoot;
1465 cockpit->setName( "Cockpit" );
1467 lighting = new ssgRoot;
1468 lighting->setName( "Lighting" );
1470 // Initialize the sky
1471 SGPath ephem_data_path( globals->get_fg_root() );
1472 ephem_data_path.append( "Astro" );
1473 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1474 ephem->update( globals->get_time_params()->getMjd(),
1475 globals->get_time_params()->getLst(),
1477 globals->set_ephem( ephem );
1481 SGPath sky_tex_path( globals->get_fg_root() );
1482 sky_tex_path.append( "Textures" );
1483 sky_tex_path.append( "Sky" );
1484 thesky->texture_path( sky_tex_path.str() );
1486 thesky->build( 550.0, 550.0,
1487 globals->get_ephem()->getNumPlanets(),
1488 globals->get_ephem()->getPlanets(), 60000.0,
1489 globals->get_ephem()->getNumStars(),
1490 globals->get_ephem()->getStars(), 60000.0 );
1492 if ( fgGetBool("/environment/clouds/status") ) {
1493 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1494 // SG_CLOUD_OVERCAST );
1495 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1497 200.0, 50.0, 40000.0,
1498 SG_CLOUD_MOSTLY_CLOUDY );
1499 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1500 // SG_CLOUD_MOSTLY_SUNNY );
1501 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1505 // Initialize MagVar model
1506 SGMagVar *magvar = new SGMagVar();
1507 globals->set_mag( magvar );
1510 terrain_branch = new ssgBranch;
1511 terrain_branch->setName( "Terrain" );
1512 scene->addKid( terrain_branch );
1515 gnd_lights_branch = new ssgBranch;
1516 gnd_lights_branch->setName( "Ground Lighting" );
1517 lighting->addKid( gnd_lights_branch );
1519 rwy_lights_branch = new ssgBranch;
1520 rwy_lights_branch->setName( "Runway Lighting" );
1521 lighting->addKid( rwy_lights_branch );
1523 // airport = new ssgBranch;
1524 // airport->setName( "Airport Lighting" );
1525 // lighting->addKid( airport );
1531 // temporary visible aircraft "own ship"
1532 current_model.init();
1534 #ifdef FG_NETWORK_OLK
1535 // Do the network intialization
1536 if ( fgGetBool("/sim/networking/network-olk") ) {
1537 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1541 // build our custom render states
1542 fgBuildRenderStates();
1544 // pass control off to the master GLUT event handler
1547 // we never actually get here ... but to avoid compiler warnings,
1553 // $$$ end - added VS Renganathan, 15 Oct 2K
1554 // - added Venky , 12 Nov 2K
1556 #if defined(__linux__) && defined(__i386__)
1558 static void handleFPE (int);
1563 fpu_control_t fpe_flags = 0;
1564 _FPU_GETCW(fpe_flags);
1565 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1566 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1567 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1568 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1569 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1570 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1571 _FPU_SETCW(fpe_flags);
1572 signal(SIGFPE, handleFPE);
1579 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1583 // Main entry point; catch any exceptions that have made it this far.
1584 int main ( int argc, char **argv ) {
1586 // Enable floating-point exceptions for Linux/x86
1587 #if defined(__linux__) && defined(__i386__)
1591 // Enable floating-point exceptions for Windows
1592 #if defined( _MSC_VER ) && defined( DEBUG )
1593 // Christian, we should document what this does
1594 _control87( _EM_INEXACT, _MCW_EM );
1597 #if defined( HAVE_BC5PLUS )
1598 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1601 // FIXME: add other, more specific
1604 mainLoop(argc, argv);
1605 } catch (sg_throwable &t) {
1606 // We must use cerr rather than
1607 // logging, since logging may be
1609 cerr << "Fatal error: " << t.getFormattedMessage()
1610 << "\n (received from " << t.getOrigin() << ')' << endl;
1618 void fgLoadDCS(void) {
1620 ssgEntity *ship_obj = NULL;
1622 char obj_filename[25];
1624 for ( int k = 0; k < 32; k++ ) {
1628 SGPath tile_path( globals->get_fg_root());
1629 tile_path.append( "Scenery" );
1630 tile_path.append( "Objects.txt" );
1631 sg_gzifstream in( tile_path.str() );
1632 if ( ! in.is_open() ) {
1633 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1636 SGPath modelpath( globals->get_fg_root() );
1637 modelpath.append( "Models" );
1638 modelpath.append( "Geometry" );
1640 SGPath texturepath( globals->get_fg_root() );
1641 texturepath.append( "Models" );
1642 texturepath.append( "Textures" );
1644 ssgModelPath( (char *)modelpath.c_str() );
1645 ssgTexturePath( (char *)texturepath.c_str() );
1647 ship_sel = new ssgSelector;
1650 while ( ! in.eof() ) {
1652 if ( in.get( c ) && c == '#' ) {
1656 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1657 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1658 int chj=getchar();*/
1660 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1661 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1663 ship_pos[objc] = new ssgTransform;
1665 // type "repeat" in objects.txt to load one more
1666 // instance of the last object.
1668 if ( strcmp(obj_filename,"repeat") != 0) {
1669 ship_obj = ssgLoad( obj_filename );
1672 if ( ship_obj != NULL ) {
1673 ship_obj->setName(obj_filename);
1675 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1677 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1678 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1679 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1680 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1683 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1687 // temporary hack for deck lights - ultimately should move to PLib (when??)
1688 //const char *extn = file_extension ( obj_filename ) ;
1690 ssgVertexArray *lights = new ssgVertexArray( 100 );
1691 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1692 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1693 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1694 int ltype[500], light_type;
1695 static int ltcount = 0;
1697 sgVec3 rway_dir,rway_normal,lightpt;
1699 modelpath.append(obj_filename);
1700 sg_gzifstream in1( modelpath.str() );
1701 if ( ! in1.is_open() ) {
1702 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1704 while ( ! in1.eof() ) {
1706 if ( in1.get( c ) && c == '#' ) {
1711 //cout << token << endl;
1712 if ( token == "runway" ) {
1714 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1715 } else if ( token == "edgelight" ) {
1717 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1719 } else if ( token == "taxi" ) {
1721 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1723 } else if ( token == "vasi" ) {
1725 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1727 } else if ( token == "threshold" ) {
1729 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1731 } else if ( token == "rabbit" ) {
1733 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1735 } else if ( token == "ols" ) {
1737 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1739 } else if ( token == "red" ) {
1741 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1743 } else if ( token == "green" ) {
1745 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1747 } else if ( token == "lp" ) {
1749 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1750 lightpoints->add( lightpt );
1751 lightnormals->add( rway_normal );
1752 lightdir->add( rway_dir );
1753 ltype[ltcount]= light_type;
1756 if (in1.eof()) break;
1760 if ( lightpoints->getNum() ) {
1761 ssgBranch *lightpoints_branch;
1762 long int dummy = -999;
1763 dummy_tile = new FGTileEntry((SGBucket)dummy);
1764 dummy_tile->lightmaps_sequence = new ssgSelector;
1765 dummy_tile->ols_transform = new ssgTransform;
1767 // call function to generate the runway lights
1768 lightpoints_branch =
1769 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1771 lightpoints_brightness->addKid(lightpoints_branch);
1772 lightpoints_transform->addKid(lightpoints_brightness);
1773 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1774 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1775 lightpoints_transform->ref();
1776 gnd_lights_branch->addKid( lightpoints_transform );
1780 // end hack for deck lights
1784 if (in.eof()) break;
1788 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1790 terrain_branch->addKid( ship_sel ); //add selector node to root node
1797 void fgUpdateDCS (void) {
1799 // double eye_lat,eye_lon,eye_alt;
1800 // static double obj_head;
1801 double sl_radius,obj_latgc;
1802 // float nresultmat[4][4];
1803 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1806 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1807 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1809 // Deck should be the first object in objects.txt in case of fdm=ada
1811 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1812 if ((fdm->get_iaux(1))==1)
1814 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1815 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1816 obj_alt[1] = fdm->get_daux(3);
1817 obj_pitch[1] = fdm->get_faux(1);
1818 obj_roll[1] = fdm->get_faux(2);
1822 for ( int m = 0; m < objc; m++ ) {
1823 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1826 //Geodetic to Geocentric angles for rotation
1827 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1829 //moving object gbs-posn in cartesian coords
1830 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1831 Point3D obj_pos = sgGeodToCart( obj_posn );
1833 // Translate moving object w.r.t eye
1834 Point3D Objtrans = obj_pos-scenery.get_center();
1839 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1842 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1844 sgVec3 ship_fwd,ship_rt,ship_up;
1845 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1846 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1847 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1849 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1850 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1851 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1852 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1853 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1854 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1857 sgCopyMat4( sgTUX, sgROT_hdg );
1858 sgPostMultMat4( sgTUX, sgROT_pitch );
1859 sgPostMultMat4( sgTUX, sgROT_roll );
1860 sgPostMultMat4( sgTUX, sgROT_lat );
1861 sgPostMultMat4( sgTUX, sgROT_lon );
1862 sgPostMultMat4( sgTUX, sgTRANS );
1865 sgSetCoord(&shippos, sgTUX );
1866 ship_pos[m]->setTransform( &shippos );
1867 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1869 if (lightpoints_transform) {
1870 lightpoints_transform->setTransform( &shippos );
1871 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1872 if ( sun_angle > 89 ) {
1873 lightpoints_brightness->select(0x01);
1875 lightpoints_brightness->select(0x00);
1884 sgXformPnt3( rp, rway_ols, sgTUX );
1885 vp = globals->get_current_view()->get_view_pos();
1886 to[0] = rp[0]-vp[0];
1887 to[1] = rp[1]-vp[1];
1888 to[2] = rp[2]-vp[2];
1889 float dist = sgLengthVec3( to );
1890 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1892 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1894 ref_elev = elev - 3.75; // +ve above, -ve below
1898 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1899 // if (ref_elev > 0.51) sel = 0x21;
1900 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1901 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1902 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1903 // if (ref_elev < -0.51) sel = 0x30;
1904 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1905 dummy_tile->lightmaps_sequence->select(sel);
1908 sgCopyVec3 (up, ship_up);
1910 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1912 sgScaleVec3 (up, 4.0*ref_elev);
1913 dummy_tile->ols_transform->setTransform(up);
1914 //cout << "ref_elev " << ref_elev << endl;
1916 // end hack for deck lights
1919 if ( ship_sel != NULL ) {
1920 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1924 // $$$ end - added VS Renganathan, 15 Oct 2K
1925 // added Venky , 12 Nov 2K