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 #ifdef FG_MATH_EXCEPTION_CLASH
38 #include <simgear/xgl/xgl.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> /* for stat() */
53 # include <unistd.h> /* for stat() */
56 #include <plib/pu.h> // plib include
57 #include <plib/ssg.h> // plib include
59 #ifdef ENABLE_AUDIO_SUPPORT
60 # include <plib/sl.h> // plib include
61 # include <plib/sm.h> // plib include
64 #include <simgear/constants.h> // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/fg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
73 #include <Include/general.hxx>
75 #include <Aircraft/aircraft.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/sunpos.hxx>
93 #include <Time/tmp.hxx>
95 // $$$ begin - added VS Renganathan
96 #include <simgear/misc/fgstream.hxx>
97 #include <FDM/flight.hxx>
98 void fgLoadDCS (void);
99 void fgUpdateDCS (void);
100 ssgSelector *ship_sel = NULL;
101 ssgTransform *ship_pos = NULL;
102 //int totalDCSobj = 0;
103 // $$$ end - added VS Renganathan
105 #ifndef FG_OLD_WEATHER
106 # include <WeatherCM/FGLocalWeatherDatabase.h>
108 # include <Weather/weather.hxx>
114 #include "fg_init.hxx"
116 #include "globals.hxx"
117 #include "keyboard.hxx"
118 #include "options.hxx"
119 #include "splash.hxx"
122 // -dw- use custom sioux settings so I can see output window
125 # include <sioux.h> // settings for output window
127 # include <console.h>
131 // This is a record containing a bit of global housekeeping information
134 // Specify our current idle function state. This is used to run all
135 // our initializations out of the glutIdleLoop() so that we can get a
136 // splash screen up and running right away.
137 static int idle_state = 0;
138 static int global_multi_loop;
140 // attempt to avoid a large bounce at startup
141 static bool initial_freeze = true;
146 // Global structures for the Audio library
147 #ifdef ENABLE_AUDIO_SUPPORT
148 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
149 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
150 slScheduler *audio_sched;
151 smMixer *audio_mixer;
158 ssgRoot *scene = NULL;
159 ssgBranch *terrain = NULL;
160 ssgSelector *penguin_sel = NULL;
161 ssgTransform *penguin_pos = NULL;
163 #ifdef FG_NETWORK_OLK
164 ssgSelector *fgd_sel = NULL;
165 ssgTransform *fgd_pos = NULL;
169 // current fdm/position used for view
170 FGInterface cur_view_fdm;
176 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
178 { 1.0f, 0.0f, 0.0f, 0.0f },
179 { 0.0f, 0.0f, -1.0f, 0.0f },
180 { 0.0f, 1.0f, 0.0f, 0.0f },
181 { 0.0f, 0.0f, 0.0f, 1.0f }
184 // The following defines flightgear options. Because glutlib will also
185 // want to parse its own options, those options must not be included here
186 // or they will get parsed by the main program option parser. Hence case
187 // is significant for any option added that might be in conflict with
190 // glutlib parses for:
192 // -direct (invalid in Win32)
196 // -indirect (invalid in Win32)
199 // Note that glutlib depends upon strings while this program's
200 // option parser wants only initial characters followed by numbers
205 ssgSimpleState *default_state;
206 ssgSimpleState *hud_and_panel;
207 ssgSimpleState *menus;
209 void fgBuildRenderStates( void ) {
210 default_state = new ssgSimpleState;
211 default_state->ref();
212 default_state->disable( GL_TEXTURE_2D );
213 default_state->enable( GL_CULL_FACE );
214 default_state->enable( GL_COLOR_MATERIAL );
215 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
216 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
217 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
218 default_state->disable( GL_BLEND );
219 default_state->disable( GL_ALPHA_TEST );
220 default_state->disable( GL_LIGHTING );
222 hud_and_panel = new ssgSimpleState;
223 hud_and_panel->ref();
224 hud_and_panel->disable( GL_CULL_FACE );
225 hud_and_panel->disable( GL_TEXTURE_2D );
226 hud_and_panel->disable( GL_LIGHTING );
227 hud_and_panel->enable( GL_BLEND );
229 menus = new ssgSimpleState;
231 menus->disable( GL_CULL_FACE );
232 menus->disable( GL_TEXTURE_2D );
233 menus->enable( GL_BLEND );
237 // fgInitVisuals() -- Initialize various GL/view parameters
238 void fgInitVisuals( void ) {
241 l = &cur_light_params;
243 #ifndef GLUT_WRONG_VERSION
244 // Go full screen if requested ...
245 if ( globals->get_options()->get_fullscreen() ) {
250 // If enabled, normal vectors specified with glNormal are scaled
251 // to unit length after transformation. See glNormal.
252 // glEnable( GL_NORMALIZE );
254 glEnable( GL_LIGHTING );
255 glEnable( GL_LIGHT0 );
256 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
259 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
260 ssgGetLight( 0 ) -> setPosition( sunpos );
262 // glFogi (GL_FOG_MODE, GL_LINEAR);
263 glFogi (GL_FOG_MODE, GL_EXP2);
264 if ( (globals->get_options()->get_fog() == 1) ||
265 (globals->get_options()->get_shading() == 0) ) {
266 // if fastest fog requested, or if flat shading force fastest
267 glHint ( GL_FOG_HINT, GL_FASTEST );
268 } else if ( globals->get_options()->get_fog() == 2 ) {
269 glHint ( GL_FOG_HINT, GL_NICEST );
271 if ( globals->get_options()->get_wireframe() ) {
273 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
276 // This is the default anyways, but it can't hurt
277 glFrontFace ( GL_CCW );
280 // glEnable(GL_POINT_SMOOTH);
281 // glEnable(GL_LINE_SMOOTH);
282 // glEnable(GL_POLYGON_SMOOTH);
286 // Update all Visuals (redraws anything graphics related)
287 void fgRenderFrame( void ) {
291 fgLIGHT *l = &cur_light_params;
292 static double last_visibility = -9999;
295 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
296 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
297 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
298 // GLfloat mat_shininess[] = { 10.0 };
299 GLbitfield clear_mask;
301 if ( idle_state != 1000 ) {
302 // still initializing, draw the splash screen
303 if ( globals->get_options()->get_splash_screen() == 1 ) {
307 // idle_state is now 1000 meaning we've finished all our
308 // initializations and are running the main loop, so this will
309 // now work without seg faulting the system.
311 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
312 // FG_Altitude * FEET_TO_METER);
314 // this is just a temporary hack, to make me understand Pui
315 // timerText -> setLabel (ctime (&t->cur_time));
318 // update view volume parameters
319 // cout << "before pilot_view update" << endl;
320 if ( globals->get_options()->get_view_mode()
321 == FGOptions::FG_VIEW_FOLLOW )
323 float * offset = globals->get_pilot_view()->get_pilot_offset();
324 globals->get_current_view()->set_pilot_offset( offset[0],
328 globals->get_current_view()->set_pilot_offset(0.0, 0.0, 0.0);
330 globals->get_pilot_view()->UpdateViewParams(*cur_fdm_state);
331 // cout << "after pilot_view update" << endl;
332 globals->get_current_view()->UpdateViewParams(cur_view_fdm);
334 // set the sun position
335 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
337 clear_mask = GL_DEPTH_BUFFER_BIT;
338 if ( globals->get_options()->get_wireframe() ) {
339 clear_mask |= GL_COLOR_BUFFER_BIT;
342 if ( globals->get_options()->get_skyblend() ) {
343 if ( globals->get_options()->get_textures() ) {
344 // glClearColor(black[0], black[1], black[2], black[3]);
345 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
346 l->adj_fog_color[2], l->adj_fog_color[3]);
347 clear_mask |= GL_COLOR_BUFFER_BIT;
350 glClearColor(l->sky_color[0], l->sky_color[1],
351 l->sky_color[2], l->sky_color[3]);
352 clear_mask |= GL_COLOR_BUFFER_BIT;
354 glClear( clear_mask );
356 // Tell GL we are switching to model view parameters
358 // I really should create a derived ssg node or use a call
359 // back or something so that I can draw the sky within the
360 // ssgCullAndDraw() function, but for now I just mimic what
361 // ssg does to set up the model view matrix
362 glMatrixMode(GL_MODELVIEW);
364 ssgSetCamera( (sgMat4)globals->get_current_view()->get_VIEW() );
367 sgMat4 vm_tmp, view_mat;
368 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
369 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
370 sgPreMultMat4( view_mat, vm_tmp ) ;
371 glLoadMatrixf( (float *)view_mat );
374 // set the opengl state to known default values
375 default_state->force();
377 // update fog params if visibility has changed
378 #ifndef FG_OLD_WEATHER
379 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
381 thesky->set_visibility( current_weather.get_visibility() );
384 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
386 ( global_multi_loop *
387 globals->get_options()->get_speed_up() ) /
388 (double)globals->get_options()->get_model_hz() );
390 double actual_visibility = thesky->get_visibility();
391 // cout << "actual visibility = " << actual_visibility << endl;
393 if ( actual_visibility != last_visibility ) {
394 last_visibility = actual_visibility;
396 // cout << "----> updating fog params" << endl;
398 GLfloat fog_exp_density;
399 GLfloat fog_exp2_density;
402 fog_exp_density = -log(0.01 / actual_visibility);
405 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
407 // Set correct opengl fog density
408 glFogf (GL_FOG_DENSITY, fog_exp2_density);
411 // update the sky dome
412 if ( globals->get_options()->get_skyblend() ) {
415 globals->get_current_view()->get_view_pos().x(),
416 globals->get_current_view()->get_view_pos().y(),
417 globals->get_current_view()->get_view_pos().z() );
420 sgSetVec3( zero_elev,
421 globals->get_current_view()->get_cur_zero_elev().x(),
422 globals->get_current_view()->get_cur_zero_elev().y(),
423 globals->get_current_view()->get_cur_zero_elev().z() );
425 /* cout << "thesky->repaint() sky_color = "
426 << cur_light_params.sky_color[0] << " "
427 << cur_light_params.sky_color[1] << " "
428 << cur_light_params.sky_color[2] << " "
429 << cur_light_params.sky_color[3] << endl;
431 << cur_light_params.fog_color[0] << " "
432 << cur_light_params.fog_color[1] << " "
433 << cur_light_params.fog_color[2] << " "
434 << cur_light_params.fog_color[3] << endl;
435 cout << " sun_angle = " << cur_light_params.sun_angle
436 << " moon_angle = " << cur_light_params.moon_angle
438 thesky->repaint( cur_light_params.sky_color,
439 cur_light_params.adj_fog_color,
440 cur_light_params.sun_angle,
441 cur_light_params.moon_angle,
442 globals->get_ephem()->getNumPlanets(),
443 globals->get_ephem()->getPlanets(),
444 globals->get_ephem()->getNumStars(),
445 globals->get_ephem()->getStars() );
447 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
448 << view_pos[1] << " " << view_pos[2] << endl;
449 cout << " zero_elev = " << zero_elev[0] << " "
450 << zero_elev[1] << " " << zero_elev[2]
451 << " lon = " << cur_fdm_state->get_Longitude()
452 << " lat = " << cur_fdm_state->get_Latitude() << endl;
453 cout << " sun_rot = " << cur_light_params.sun_rotation
454 << " gst = " << SGTime::cur_time_params->getGst() << endl;
455 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
456 << " sun dec = " << globals->get_ephem()->getSunDeclination()
457 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
458 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
460 thesky->reposition( view_pos, zero_elev,
461 globals->get_current_view()->get_local_up(),
462 cur_fdm_state->get_Longitude(),
463 cur_fdm_state->get_Latitude(),
464 cur_fdm_state->get_Altitude() * FEET_TO_METER,
465 cur_light_params.sun_rotation,
466 globals->get_time_params()->getGst(),
467 globals->get_ephem()->getSunRightAscension(),
468 globals->get_ephem()->getSunDeclination(),
470 globals->get_ephem()->getMoonRightAscension(),
471 globals->get_ephem()->getMoonDeclination(),
475 glEnable( GL_DEPTH_TEST );
476 if ( globals->get_options()->get_fog() > 0 ) {
478 glFogi( GL_FOG_MODE, GL_EXP2 );
479 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
482 // set lighting parameters
483 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
484 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
485 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
486 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
487 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
489 // texture parameters
490 // glEnable( GL_TEXTURE_2D );
491 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
492 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
493 // set base color (I don't think this is doing anything here)
494 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
495 // (GL_FRONT, GL_DIFFUSE, white);
496 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
497 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
500 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
501 ssgGetLight( 0 ) -> setPosition( sunpos );
503 // glMatrixMode( GL_PROJECTION );
505 float fov = globals->get_options()->get_fov();
506 // ssgSetFOV(fov * current_view.get_win_ratio(), fov);
507 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
509 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
512 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
513 // << current_weather.get_visibility() );
516 ssgSetNearFar( 10.0f, 120000.0f );
518 ssgSetNearFar( 0.5f, 120000.0f );
521 if ( globals->get_options()->get_view_mode() ==
522 FGOptions::FG_VIEW_PILOT )
525 penguin_sel->select(0);
526 } else if ( globals->get_options()->get_view_mode() ==
527 FGOptions::FG_VIEW_FOLLOW )
529 // select view matrix from front of view matrix queue
530 // FGMat4Wrapper tmp = current_view.follow.front();
531 // sgCopyMat4( sgVIEW, tmp.m );
533 // enable TuX and set up his position and orientation
534 penguin_sel->select(1);
537 sgMakeTransMat4( sgTRANS,
538 globals->get_pilot_view()->get_view_pos().x(),
539 globals->get_pilot_view()->get_view_pos().y(),
540 globals->get_pilot_view()->get_view_pos().z() );
543 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
546 sgMakeRotMat4( sgROT, -90.0, ownship_up );
550 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
551 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
553 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
555 sgCopyMat4( sgTUX, sgROT );
556 sgPostMultMat4( sgTUX, globals->get_pilot_view()->get_VIEW_ROT() );
557 sgPostMultMat4( sgTUX, sgTRANS );
560 sgSetCoord( &tuxpos, sgTUX );
561 penguin_pos->setTransform( &tuxpos );
564 // $$$ begin - added VS Renganthan 17 Oct 2K
566 // $$$ end - added VS Renganthan 17 Oct 2K
568 # ifdef FG_NETWORK_OLK
569 if ( globals->get_options()->get_network_olk() ) {
571 other = head->next; /* put listpointer to start */
572 while ( other != tail) { /* display all except myself */
573 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
574 other->fgd_sel->select(1);
575 sgSetCoord( &fgdpos, other->sgFGD_COORD );
576 other->fgd_pos->setTransform( &fgdpos );
581 // fgd_sel->select(1);
582 // sgCopyMat4( sgTUX, current_view.sgVIEW);
584 // sgSetCoord( &fgdpos, sgFGD_VIEW );
585 // fgd_pos->setTransform( &fgdpos);
589 // ssgSetCamera( current_view.VIEW );
591 // position tile nodes and update range selectors
592 global_tile_mgr.prep_ssg_nodes();
594 // force the default state so ssg can get back on track if
595 // we've changed things elsewhere (this is now handled
598 // FGMaterialSlot m_slot;
599 // FGMaterialSlot *m_ptr = &m_slot;
600 // if ( material_mgr.find( "Default", m_ptr ) ) {
601 // m_ptr->get_state()->force();
604 // draw the sky backdrop
607 // draw the ssg scene
608 glEnable( GL_DEPTH_TEST );
609 ssgCullAndDraw( scene );
611 // draw the sky cloud layers
612 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
614 // display HUD && Panel
616 glDisable( GL_DEPTH_TEST );
617 // glDisable( GL_CULL_FACE );
618 // glDisable( GL_TEXTURE_2D );
619 hud_and_panel->apply();
622 // We can do translucent menus, so why not. :-)
623 // glEnable ( GL_BLEND ) ;
625 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
627 // glDisable ( GL_BLEND ) ;
629 // glEnable( GL_FOG );
636 // Update internal time dependent calculations (i.e. flight model)
637 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
638 static fdm_state_list fdm_list;
639 fgLIGHT *l = &cur_light_params;
642 // update the flight model
643 if ( multi_loop < 0 ) {
647 if ( !globals->get_freeze() && !initial_freeze ) {
648 // run Autopilot system
649 current_autopilot->run();
651 // printf("updating flight model x %d\n", multi_loop);
652 /* fgFDMUpdate( globals->get_options()->get_flight_model(),
654 multi_loop * globals->get_options()->get_speed_up(),
656 cur_fdm_state->update( multi_loop *
657 globals->get_options()->get_speed_up() );
658 FGSteam::update( multi_loop * globals->get_options()->get_speed_up() );
660 // fgFDMUpdate( globals->get_options()->get_flight_model(),
661 // fdm_state, 0, remainder );
662 cur_fdm_state->update( 0 );
663 FGSteam::update( 0 );
665 if ( global_tile_mgr.queue_size() == 0 ) {
666 initial_freeze = false;
670 fdm_list.push_back( *cur_fdm_state );
671 while ( fdm_list.size() > 15 ) {
672 fdm_list.pop_front();
675 if ( globals->get_options()->get_view_mode() == FGOptions::FG_VIEW_PILOT ) {
676 cur_view_fdm = *cur_fdm_state;
678 } else if ( globals->get_options()->get_view_mode()
679 == FGOptions::FG_VIEW_FOLLOW )
681 cur_view_fdm = fdm_list.front();
684 // update the view angle
685 for ( i = 0; i < multi_loop; i++ ) {
686 if ( fabs(globals->get_current_view()->get_goal_view_offset() -
687 globals->get_current_view()->get_view_offset()) < 0.05 )
689 globals->get_current_view()->set_view_offset( globals->get_current_view()->get_goal_view_offset() );
692 // move current_view.view_offset towards
693 // current_view.goal_view_offset
694 if ( globals->get_current_view()->get_goal_view_offset() >
695 globals->get_current_view()->get_view_offset() )
697 if ( globals->get_current_view()->get_goal_view_offset() -
698 globals->get_current_view()->get_view_offset() < FG_PI )
700 globals->get_current_view()->inc_view_offset( 0.01 );
702 globals->get_current_view()->inc_view_offset( -0.01 );
705 if ( globals->get_current_view()->get_view_offset() -
706 globals->get_current_view()->get_goal_view_offset() <
709 globals->get_current_view()->inc_view_offset( -0.01 );
711 globals->get_current_view()->inc_view_offset( 0.01 );
714 if ( globals->get_current_view()->get_view_offset() > FG_2PI ) {
715 globals->get_current_view()->inc_view_offset( -FG_2PI );
716 } else if ( globals->get_current_view()->get_view_offset() < 0 ) {
717 globals->get_current_view()->inc_view_offset( FG_2PI );
722 double tmp = -(l->sun_rotation + FG_PI)
723 - (cur_fdm_state->get_Psi() -
724 globals->get_current_view()->get_view_offset() );
725 while ( tmp < 0.0 ) {
728 while ( tmp > FG_2PI ) {
731 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
732 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
733 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
736 // Update solar system
737 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
738 globals->get_time_params()->getLst(),
739 cur_fdm_state->get_Latitude() );
741 // Update radio stack model
742 current_radiostack->update( cur_fdm_state->get_Longitude(),
743 cur_fdm_state->get_Latitude(),
744 cur_fdm_state->get_Altitude() * FEET_TO_METER );
748 void fgInitTimeDepCalcs( void ) {
751 // #ifdef HAVE_SETITIMER
752 // fgTimerInit( 1.0 / globals->get_options()->get_model_hz(),
753 // fgUpdateTimeDepCalcs );
754 // #endif HAVE_SETITIMER
758 static const double alt_adjust_ft = 3.758099;
759 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
762 // What should we do when we have nothing else to do? Let's get ready
763 // for the next move and update the display?
764 static void fgMainLoop( void ) {
765 static long remainder = 0;
767 #ifdef FANCY_FRAME_COUNTER
771 static time_t last_time = 0;
772 static int frames = 0;
773 #endif // FANCY_FRAME_COUNTER
775 SGTime *t = globals->get_time_params();
777 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
778 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
780 #ifdef FG_NETWORK_OLK
781 if ( globals->get_options()->get_network_olk() ) {
782 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
783 // printf("FGD: Netupdate\n");
784 fgd_send_com( "A", FGFS_host); // Send Mat4 data
785 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
790 #if defined( ENABLE_PLIB_JOYSTICK )
791 // Read joystick and update control settings
792 if ( globals->get_options()->get_control_mode() == FGOptions::FG_JOYSTICK )
796 #elif defined( ENABLE_GLUT_JOYSTICK )
797 // Glut joystick support works by feeding a joystick handler
798 // function to glut. This is taken care of once in the joystick
799 // init routine and we don't have to worry about it again.
802 #ifdef FG_OLD_WEATHER
803 current_weather.Update();
806 // Fix elevation. I'm just sticking this here for now, it should
807 // probably move eventually
809 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
811 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
812 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
814 if ( scenery.cur_elev > -9990 ) {
815 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
816 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
817 // now set aircraft altitude above ground
818 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
819 cur_fdm_state->get_Altitude() * FEET_TO_METER,
820 scenery.cur_elev + alt_adjust_m - 3.0,
821 scenery.cur_elev + alt_adjust_m );
822 fgFDMForceAltitude( globals->get_options()->get_flight_model(),
823 scenery.cur_elev + alt_adjust_m );
825 FG_LOG( FG_ALL, FG_DEBUG,
826 "<*> resetting altitude to "
827 << cur_fdm_state->get_Altitude() * FEET_TO_METER
830 fgFDMSetGroundElevation( globals->get_options()->get_flight_model(),
831 scenery.cur_elev ); // meters
834 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
836 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
837 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
840 if ( globals->get_warp_delta() != 0 ) {
841 globals->inc_warp( globals->get_warp_delta() );
844 t->update( cur_fdm_state->get_Longitude(),
845 cur_fdm_state->get_Latitude(),
846 globals->get_warp() );
848 if ( globals->get_warp_delta() != 0 ) {
849 fgUpdateSkyAndLightingParams();
852 // update magvar model
853 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
854 cur_fdm_state->get_Latitude(),
855 cur_fdm_state->get_Altitude()* FEET_TO_METER,
856 globals->get_time_params()->getJD() );
858 // Get elapsed time (in usec) for this past frame
859 elapsed = fgGetTimeInterval();
860 FG_LOG( FG_ALL, FG_DEBUG,
861 "Elapsed time interval is = " << elapsed
862 << ", previous remainder is = " << remainder );
864 // Calculate frame rate average
865 #ifdef FANCY_FRAME_COUNTER
866 /* old fps calculation */
870 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
871 tmp = general.get_frame(i);
873 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
874 general.set_frame(i+1,tmp);
876 tmp = 1000000.0 / (float)elapsed;
877 general.set_frame(0,tmp);
878 // printf("frame[0] = %.2f\n", general.frames[0]);
880 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
881 // printf("ave = %.2f\n", general.frame_rate);
884 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
885 general.set_frame_rate( frames );
886 FG_LOG( FG_ALL, FG_DEBUG,
887 "--> Frame rate is = " << general.get_frame_rate() );
890 last_time = t->get_cur_time();
895 if ( ! use_signals ) {
896 // Calculate model iterations needed for next frame
897 elapsed += remainder;
899 global_multi_loop = (int)(((double)elapsed * 0.000001) *
900 globals->get_options()->get_model_hz());
901 remainder = elapsed - ( (global_multi_loop*1000000) /
902 globals->get_options()->get_model_hz() );
903 FG_LOG( FG_ALL, FG_DEBUG,
904 "Model iterations needed = " << global_multi_loop
905 << ", new remainder = " << remainder );
908 if ( global_multi_loop > 0 ) {
909 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
911 FG_LOG( FG_ALL, FG_DEBUG,
912 "Elapsed time is zero ... we're zinging" );
916 #if ! defined( macintosh )
917 // Do any I/O channel work that might need to be done
921 // see if we need to load any new scenery tiles
922 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
923 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
925 // Process/manage pending events
926 global_events.Process();
928 // Run audio scheduler
929 #ifdef ENABLE_AUDIO_SUPPORT
930 if ( globals->get_options()->get_sound() && !audio_sched->not_working() ) {
932 if ( globals->get_options()->get_aircraft() == "c172" ) {
933 // pitch corresponds to rpm
934 // volume corresponds to manifold pressure
937 if ( cur_fdm_state->get_engine(0) != NULL ) {
938 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
942 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
945 double pitch = 0.3 + rpm_factor * 3.0;
947 // don't run at absurdly slow rates -- not realistic
948 // and sounds bad to boot. :-)
949 if (pitch < 0.7) { pitch = 0.7; }
950 if (pitch > 5.0) { pitch = 5.0; }
951 // cout << "pitch = " << pitch << endl;
954 if ( cur_fdm_state->get_engine(0) != NULL ) {
956 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
961 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
964 double volume = mp_factor;
966 if ( volume < 0.3 ) { volume = 0.3; }
967 if ( volume > 2.0 ) { volume = 2.0; }
968 // cout << "volume = " << volume << endl;
970 pitch_envelope.setStep ( 0, 0.01, pitch );
971 volume_envelope.setStep ( 0, 0.01, volume );
973 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
974 pitch_envelope.setStep ( 0, 0.01, param );
975 volume_envelope.setStep ( 0, 0.01, param );
978 audio_sched -> update();
985 FG_LOG( FG_ALL, FG_DEBUG, "" );
989 // This is the top level master main function that is registered as
993 // The first few passes take care of initialization things (a couple
994 // per pass) and once everything has been initialized fgMainLoop from
997 static void fgIdleFunction ( void ) {
998 // printf("idle state == %d\n", idle_state);
1000 if ( idle_state == 0 ) {
1001 // Initialize the splash screen right away
1002 if ( globals->get_options()->get_splash_screen() ) {
1007 } else if ( idle_state == 1 ) {
1008 // Start the intro music
1010 if ( globals->get_options()->get_intro_music() ) {
1011 string lockfile = "/tmp/mpg123.running";
1012 FGPath mp3file( globals->get_options()->get_fg_root() );
1013 mp3file.append( "Sounds/intro.mp3" );
1015 string command = "(touch " + lockfile + "; mpg123 "
1016 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1018 FG_LOG( FG_GENERAL, FG_INFO,
1019 "Starting intro music: " << mp3file.str() );
1020 system ( command.c_str() );
1025 } else if ( idle_state == 2 ) {
1026 // These are a few miscellaneous things that aren't really
1027 // "subsystems" but still need to be initialized.
1030 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1031 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1036 } else if ( idle_state == 3 ) {
1037 // This is the top level init routine which calls all the
1038 // other subsystem initialization routines. If you are adding
1039 // a subsystem to flightgear, its initialization call should
1040 // located in this routine.
1041 if( !fgInitSubsystems()) {
1042 FG_LOG( FG_GENERAL, FG_ALERT,
1043 "Subsystem initializations failed ..." );
1048 } else if ( idle_state == 4 ) {
1049 // setup OpenGL view parameters
1052 if ( use_signals ) {
1053 // init timer routines, signals, etc. Arrange for an alarm
1054 // signal to be generated, etc.
1055 fgInitTimeDepCalcs();
1059 } else if ( idle_state == 5 ) {
1062 } else if ( idle_state == 6 ) {
1063 // Initialize audio support
1064 #ifdef ENABLE_AUDIO_SUPPORT
1067 if ( globals->get_options()->get_intro_music() ) {
1068 // Let's wait for mpg123 to finish
1069 string lockfile = "/tmp/mpg123.running";
1070 struct stat stat_buf;
1072 FG_LOG( FG_GENERAL, FG_INFO,
1073 "Waiting for mpg123 player to finish ..." );
1074 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1075 // file exist, wait ...
1077 FG_LOG( FG_GENERAL, FG_INFO, ".");
1079 FG_LOG( FG_GENERAL, FG_INFO, "");
1083 if ( globals->get_options()->get_sound() ) {
1084 audio_sched = new slScheduler ( 8000 );
1085 audio_mixer = new smMixer;
1086 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1087 audio_sched -> setSafetyMargin ( 1.0 ) ;
1089 FGPath slfile( globals->get_options()->get_fg_root() );
1090 slfile.append( "Sounds/wasp.wav" );
1092 s1 = new slSample ( (char *)slfile.c_str() );
1093 FG_LOG( FG_GENERAL, FG_INFO,
1094 "Rate = " << s1 -> getRate()
1095 << " Bps = " << s1 -> getBps()
1096 << " Stereo = " << s1 -> getStereo() );
1097 audio_sched -> loopSample ( s1 );
1099 if ( audio_sched->not_working() ) {
1102 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1103 volume_envelope.setStep ( 0, 0.01, 0.6 );
1105 audio_sched -> addSampleEnvelope( s1, 0, 0,
1107 SL_PITCH_ENVELOPE );
1108 audio_sched -> addSampleEnvelope( s1, 0, 1,
1110 SL_VOLUME_ENVELOPE );
1113 // strcpy(slfile, path);
1114 // strcat(slfile, "thunder.wav");
1115 // s2 -> loadFile ( slfile );
1116 // s2 -> adjustVolume(0.5);
1117 // audio_sched -> playSample ( s2 );
1125 if ( idle_state == 1000 ) {
1126 // We've finished all our initialization steps, from now on we
1127 // run the main loop.
1131 if ( globals->get_options()->get_splash_screen() == 1 ) {
1132 fgSplashUpdate(0.0);
1137 // options.cxx needs to see this for toggle_panel()
1138 // Handle new window size or exposure
1139 void fgReshape( int width, int height ) {
1140 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1141 globals->get_current_view()->set_win_ratio( (float)height /
1143 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1146 int((current_panel->getViewHeight() - current_panel->getYOffset())
1147 * (height / 768.0)) + 1;
1148 globals->get_current_view()->set_win_ratio( (float)view_h /
1150 glViewport(0, (GLint)(height - view_h),
1151 (GLint)(width), (GLint)(view_h) );
1154 globals->get_current_view()->set_winWidth( width );
1155 globals->get_current_view()->set_winHeight( height );
1156 globals->get_current_view()->force_update_fov_math();
1158 // set these fov to be the same as in fgRenderFrame()
1159 // float x_fov = globals->get_options()->get_fov();
1160 // float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1161 // ssgSetFOV( x_fov, y_fov );
1163 // glViewport ( 0, 0, width, height );
1164 float fov = globals->get_options()->get_fov();
1165 // ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1166 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1170 if ( idle_state == 1000 ) {
1171 // yes we've finished all our initializations and are running
1172 // the main loop, so this will now work without seg faulting
1174 globals->get_current_view()->UpdateViewParams(cur_view_fdm);
1179 // Initialize GLUT and define a main window
1180 int fgGlutInit( int *argc, char **argv ) {
1182 #if !defined( macintosh )
1183 // GLUT will extract all glut specific options so later on we only
1184 // need wory about our own.
1185 glutInit(argc, argv);
1188 // Define Display Parameters
1189 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1191 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1192 globals->get_options()->get_xsize() << "x"
1193 << globals->get_options()->get_ysize() );
1195 // Define initial window size
1196 glutInitWindowSize( globals->get_options()->get_xsize(),
1197 globals->get_options()->get_ysize() );
1199 // Initialize windows
1200 if ( globals->get_options()->get_game_mode() == 0 ) {
1201 // Open the regular window
1202 glutCreateWindow("FlightGear");
1203 #ifndef GLUT_WRONG_VERSION
1205 // Open the cool new 'game mode' window
1206 char game_mode_str[256];
1207 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1208 globals->get_options()->get_xsize(),
1209 globals->get_options()->get_ysize(),
1210 globals->get_options()->get_bpp());
1212 FG_LOG( FG_GENERAL, FG_INFO,
1213 "game mode params = " << game_mode_str );
1214 glutGameModeString( game_mode_str );
1215 glutEnterGameMode();
1219 // This seems to be the absolute earliest in the init sequence
1220 // that these calls will return valid info. Too bad it's after
1221 // we've already created and sized out window. :-(
1222 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1223 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1224 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1226 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1227 general.set_glMaxTexSize( tmp );
1228 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1229 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1232 // try to determine if we should adjust the initial default
1233 // display resolution. The options class defaults (is
1234 // initialized) to 640x480.
1235 string renderer = general.glRenderer;
1237 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1238 if ( renderer.find( "Glide" ) != string::npos ) {
1239 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1240 if ( renderer.find( "FB/8" ) != string::npos ) {
1241 // probably a voodoo-2
1242 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1243 // probably two SLI'd Voodoo-2's
1244 globals->get_options()->set_xsize( 1024 );
1245 globals->get_options()->set_ysize( 768 );
1246 FG_LOG( FG_GENERAL, FG_INFO,
1247 "It looks like you have two sli'd voodoo-2's." << endl
1248 << "upgrading your win resolution to 1024 x 768" );
1249 glutReshapeWindow(1024, 768);
1251 // probably a single non-SLI'd Voodoo-2
1252 globals->get_options()->set_xsize( 800 );
1253 globals->get_options()->set_ysize( 600 );
1254 FG_LOG( FG_GENERAL, FG_INFO,
1255 "It looks like you have a voodoo-2." << endl
1256 << "upgrading your win resolution to 800 x 600" );
1257 glutReshapeWindow(800, 600);
1259 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1260 // probably a voodoo-1, stick with the default
1263 // we have no special knowledge of this card, stick with the default
1271 // Initialize GLUT event handlers
1272 int fgGlutInitEvents( void ) {
1273 // call fgReshape() on window resizes
1274 glutReshapeFunc( fgReshape );
1276 // call GLUTkey() on keyboard event
1277 glutKeyboardFunc( GLUTkey );
1278 glutSpecialFunc( GLUTspecialkey );
1280 // call guiMouseFunc() whenever our little rodent is used
1281 glutMouseFunc ( guiMouseFunc );
1282 glutMotionFunc (guiMotionFunc );
1283 glutPassiveMotionFunc (guiMotionFunc );
1285 // call fgMainLoop() whenever there is
1286 // nothing else to do
1287 glutIdleFunc( fgIdleFunction );
1290 glutDisplayFunc( fgRenderFrame );
1297 int main( int argc, char **argv ) {
1299 #if defined( macintosh )
1300 freopen ("stdout.txt", "w", stdout );
1301 freopen ("stderr.txt", "w", stderr );
1302 argc = ccommand( &argv );
1306 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1309 // set default log levels
1310 fglog().setLogLevels( FG_ALL, FG_INFO );
1312 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1313 << FLIGHTGEAR_VERSION << endl );
1315 // seed the random number generater
1318 // needs to happen before we parse command line options
1319 globals = new FGGlobals;
1321 SGRoute *route = new SGRoute;
1322 globals->set_route( route );
1324 FGOptions *options = new FGOptions;
1325 globals->set_options( options );
1327 FGViewer *pv = new FGViewer;
1328 globals->set_pilot_view( pv );
1329 FGViewer *cv = new FGViewer;
1330 globals->set_current_view( cv );
1332 // Scan the config file(s) and command line options to see if
1333 // fg_root was specified (ignore all other options for now)
1334 fgInitFGRoot(argc, argv);
1336 // cout << "1. airport_id = " << globals->get_options()->get_airport_id() << endl;
1338 // Read global preferences from $FG_ROOT/preferences.xml
1339 FGPath props_path(globals->get_options()->get_fg_root());
1340 props_path.append("preferences.xml");
1341 FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
1342 if (!readPropertyList(props_path.str(), ¤t_properties)) {
1343 FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
1344 << props_path.str());
1346 FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
1349 // cout << "2. airport_id = " << globals->get_options()->get_airport_id() << endl;
1351 // Initialize the Aircraft directory to "" (UIUC)
1354 // Load the configuration parameters
1355 if ( !fgInitConfig(argc, argv) ) {
1356 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1360 // Initialize the Window/Graphics environment.
1361 if( !fgGlutInit(&argc, argv) ) {
1362 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1366 // Initialize the various GLUT Event Handlers.
1367 if( !fgGlutInitEvents() ) {
1368 FG_LOG( FG_GENERAL, FG_ALERT,
1369 "GLUT event handler initialization failed ..." );
1373 // Initialize ssg (from plib). Needs to come before we do any
1374 // other ssg stuff, but after opengl/glut has been initialized.
1377 // Initialize the user interface (we need to do this before
1378 // passing off control to glut and before fgInitGeneral to get our
1382 // set current_options lon/lat if an airport id is specified
1383 // cout << "3. airport_id = " << globals->get_options()->get_airport_id() << endl;
1384 if ( globals->get_options()->get_airport_id().length() ) {
1385 // fgSetPosFromAirportID( globals->get_options()->get_airport_id() );
1386 fgSetPosFromAirportIDandHdg( globals->get_options()->get_airport_id(),
1387 globals->get_options()->get_heading() );
1391 FGPath zone( globals->get_options()->get_fg_root() );
1392 zone.append( "Timezone" );
1393 SGTime *t = new SGTime( globals->get_options()->get_lon() * DEG_TO_RAD,
1394 globals->get_options()->get_lat() * DEG_TO_RAD,
1397 // Handle potential user specified time offsets
1398 time_t cur_time = t->get_cur_time();
1399 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1400 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1401 time_t aircraftLocalTime =
1402 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1404 // Okay, we now have six possible scenarios
1405 switch ( globals->get_options()->get_time_offset_type() ) {
1406 case FGOptions::FG_TIME_SYS_OFFSET:
1407 globals->set_warp( globals->get_options()->get_time_offset() );
1409 case FGOptions::FG_TIME_GMT_OFFSET:
1410 globals->set_warp( globals->get_options()->get_time_offset() -
1411 (currGMT - systemLocalTime) );
1413 case FGOptions::FG_TIME_LAT_OFFSET:
1414 globals->set_warp( globals->get_options()->get_time_offset() -
1415 (aircraftLocalTime - systemLocalTime) );
1417 case FGOptions::FG_TIME_SYS_ABSOLUTE:
1418 globals->set_warp( globals->get_options()->get_time_offset() -
1420 //printf("warp = %d\n", warp);
1422 case FGOptions::FG_TIME_GMT_ABSOLUTE:
1423 globals->set_warp( globals->get_options()->get_time_offset() -
1426 case FGOptions::FG_TIME_LAT_ABSOLUTE:
1427 globals->set_warp( globals->get_options()->get_time_offset() -
1428 (aircraftLocalTime - systemLocalTime) -
1432 FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1436 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1437 << globals->get_warp() );
1439 globals->set_warp_delta( 0 );
1441 t->update( 0.0, 0.0, globals->get_warp() );
1443 globals->set_time_params( t );
1445 // Do some quick general initializations
1446 if( !fgInitGeneral()) {
1447 FG_LOG( FG_GENERAL, FG_ALERT,
1448 "General initializations failed ..." );
1453 // some ssg test stuff (requires data from the plib source
1454 // distribution) specifically from the ssg tux example
1457 FGPath modelpath( globals->get_options()->get_fg_root() );
1458 // modelpath.append( "Models" );
1459 // modelpath.append( "Geometry" );
1461 FGPath texturepath( globals->get_options()->get_fg_root() );
1462 texturepath.append( "Models" );
1463 texturepath.append( "Textures" );
1465 ssgModelPath( (char *)modelpath.c_str() );
1466 ssgTexturePath( (char *)texturepath.c_str() );
1469 scene = new ssgRoot;
1470 scene->setName( "Scene" );
1472 // Initialize the sky
1473 FGPath ephem_data_path( globals->get_options()->get_fg_root() );
1474 ephem_data_path.append( "Astro" );
1475 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1476 ephem->update( globals->get_time_params()->getMjd(),
1477 globals->get_time_params()->getLst(),
1479 globals->set_ephem( ephem );
1481 FGPath sky_tex_path( globals->get_options()->get_fg_root() );
1482 sky_tex_path.append( "Textures" );
1483 sky_tex_path.append( "Sky" );
1485 thesky->texture_path( sky_tex_path.str() );
1487 thesky->build( 550.0, 550.0,
1488 globals->get_ephem()->getNumPlanets(),
1489 globals->get_ephem()->getPlanets(), 60000.0,
1490 globals->get_ephem()->getNumStars(),
1491 globals->get_ephem()->getStars(), 60000.0 );
1493 if ( globals->get_options()->get_clouds() == true ) {
1494 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1495 SG_CLOUD_MOSTLY_SUNNY );
1496 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1498 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1499 // SG_CLOUD_MOSTLY_SUNNY );
1500 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1501 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1504 // Initialize MagVar model
1505 SGMagVar *magvar = new SGMagVar();
1506 globals->set_mag( magvar );
1509 terrain = new ssgBranch;
1510 terrain->setName( "Terrain" );
1511 scene->addKid( terrain );
1513 // temporary visible aircraft "own ship"
1514 penguin_sel = new ssgSelector;
1515 penguin_pos = new ssgTransform;
1517 current_properties.getStringValue("/sim/model/path",
1518 "Models/Geometry/glider.ac");
1519 ssgEntity *tux_obj = ssgLoad((char *)(tux_path.c_str()));
1521 // align the model properly for FGFS
1522 ssgTransform *tux_align = new ssgTransform;
1523 tux_align->addKid(tux_obj);
1526 current_properties.getFloatValue("/sim/model/h-rotation", 0.0);
1528 current_properties.getFloatValue("/sim/model/p-rotation", 0.0);
1530 current_properties.getFloatValue("/sim/model/r-rotation", 0.0);
1531 sgMakeRotMat4(tux_matrix, h_rot, h_rot, r_rot);
1532 tux_align->setTransform(tux_matrix);
1534 penguin_pos->addKid( tux_align );
1535 penguin_sel->addKid( penguin_pos );
1536 ssgFlatten( tux_obj );
1537 ssgStripify( penguin_sel );
1538 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1539 scene->addKid( penguin_sel );
1541 // $$$ begin - added VS Renganthan 17 Oct 2K
1543 // $$$ end - added VS Renganthan 17 Oct 2K
1545 #ifdef FG_NETWORK_OLK
1546 // Do the network intialization
1547 if ( globals->get_options()->get_network_olk() ) {
1548 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1552 // build our custom render states
1553 fgBuildRenderStates();
1555 // pass control off to the master GLUT event handler
1558 // we never actually get here ... but to avoid compiler warnings,
1564 // $$$ end - added VS Renganathan, 15 Oct 2K
1565 void fgLoadDCS(void) {
1567 double obj_lat,obj_lon,obj_alt;
1569 string obj_filename;
1571 FGPath tile_path( globals->get_options()->get_fg_root());
1572 tile_path.append( "Scenery" );
1573 tile_path.append( "Objects.txt" );
1574 fg_gzifstream in( tile_path.str() );
1575 if ( ! in.is_open() ) {
1576 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1579 FGPath modelpath( globals->get_options()->get_fg_root() );
1580 modelpath.append( "Models" );
1581 modelpath.append( "Geometry" );
1583 FGPath texturepath( globals->get_options()->get_fg_root() );
1584 texturepath.append( "Models" );
1585 texturepath.append( "Textures" );
1587 ssgModelPath( (char *)modelpath.c_str() );
1588 ssgTexturePath( (char *)texturepath.c_str() );
1590 // while ( ! in.eof() ) {
1591 // in >> obj_filename >> obj_lat >> obj_lon >> obj_alt;
1592 // totalDCSobj = totalDCSobj+1;
1594 ship_sel = new ssgSelector;
1595 ship_pos = new ssgTransform;
1596 ssgEntity *ship_obj = ssgLoadOBJ( "saratoga.obj" );
1597 if ( ship_obj != NULL ) {
1598 ship_pos->addKid( ship_obj ); // add object to transform node
1599 ship_sel->addKid( ship_pos ); // add transform node to selector
1600 // ssgFlatten( ship_obj );
1601 // ssgStripify( ship_sel );
1602 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1603 scene->addKid( ship_sel ); //add selector node to root node
1605 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << "saratoga.obj" );
1608 // if (in.eof()) break;
1615 void fgUpdateDCS (void) {
1617 double eye_lat,eye_lon,eye_alt;
1618 static double obj_lat=15.377603*DEG_TO_RAD;
1619 static double obj_lon= 73.816436*DEG_TO_RAD;
1620 static double obj_alt=0.15;
1621 static double obj_head;
1622 double sl_radius,obj_latgc;
1623 float nresultmat[4][4];
1624 sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1627 obj_lat = obj_lat + 0.0000001;
1629 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1630 // obj_lon = current_aircraft.fdm_state->get_aux5()*DEG_TO_RAD;
1631 // obj_lat = current_aircraft.fdm_state->get_aux6()*DEG_TO_RAD;
1632 // obj_alt = current_aircraft.fdm_state->get_aux7();
1634 // Geodetic to Geocentric angles for rotation
1635 sgGeodToGeoc(obj_lat,obj_alt,&sl_radius,&obj_latgc);
1637 // moving object gbs-posn in cartesian coords
1638 Point3D obj_posn = Point3D( obj_lon,obj_lat,obj_alt);
1639 Point3D obj_pos = sgGeodToCart( obj_posn );
1641 // Translate moving object w.r.t eye
1642 Point3D Objtrans = obj_pos-scenery.center;
1647 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1648 if ( ship_sel != NULL ) {
1649 ship_sel->select(1);
1652 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1654 sgVec3 ship_fwd,ship_rt,ship_up;
1655 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1656 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1657 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1659 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1660 sgMakeRotMat4( sgROT_lon, obj_lon*RAD_TO_DEG, ship_up );
1661 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1662 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1665 sgCopyMat4( sgTUX, sgROT_hdg );
1666 sgPostMultMat4( sgTUX, sgROT_lat );
1667 sgPostMultMat4( sgTUX, sgROT_lon );
1668 sgPostMultMat4( sgTUX, sgTRANS );
1671 sgSetCoord( &shippos, sgTUX );
1672 ship_pos->setTransform( &shippos );
1676 // $$$ end - added VS Renganathan, 15 Oct 2K