]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Added some early support for a cheezy external view of TuX.
[flightgear.git] / src / Main / fg_init.cxx
1 //
2 // fg_init.cxx -- Flight Gear top level initialization routines
3 //
4 // Written by Curtis Olson, started August 1997.
5 //
6 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 //
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 // For BC 5.01 this must be included before OpenGL includes.
31 #ifdef FG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #include <GL/glut.h>
36 #include <XGL/xgl.h>
37
38 #include <stdio.h>
39 #include <stdlib.h>
40
41 // work around a stdc++ lib bug in some versions of linux, but doesn't
42 // seem to hurt to have this here for all versions of Linux.
43 #ifdef linux
44 #  define _G_NO_EXTERN_TEMPLATES
45 #endif
46
47 #include <Include/compiler.h>
48
49 #include STL_STRING
50
51 #include <Debug/logstream.hxx>
52 #include <Aircraft/aircraft.hxx>
53 #include <Airports/simple.hxx>
54 #include <Astro/sky.hxx>
55 #include <Astro/stars.hxx>
56 #include <Astro/solarsystem.hxx>
57 #include <Autopilot/autopilot.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Include/fg_constants.h>
60 #include <Include/general.hxx>
61 #include <Joystick/joystick.hxx>
62 #include <Math/fg_geodesy.hxx>
63 #include <Math/point3d.hxx>
64 #include <Math/polar3d.hxx>
65 #include <Misc/fgpath.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Scenery/tilemgr.hxx>
68 #include <Time/event.hxx>
69 #include <Time/fg_time.hxx>
70 #include <Time/light.hxx>
71 #include <Time/sunpos.hxx>
72 #include <Time/moonpos.hxx>
73 #include <Weather/weather.hxx>
74
75 #include "fg_init.hxx"
76 #include "options.hxx"
77 #include "views.hxx"
78 #include "fg_serial.hxx"
79
80 #if defined(FX) && defined(XMESA)
81 #include <GL/xmesa.h>
82 #endif
83
84 FG_USING_STD(string);
85
86 extern const char *default_root;
87
88
89 // Read in configuration (file and command line)
90 bool fgInitConfig ( int argc, char **argv ) {
91     // Attempt to locate and parse a config file
92     // First check fg_root
93     FGPath config( current_options.get_fg_root() );
94     config.append( "system.fgfsrc" );
95     current_options.parse_config_file( config.str() );
96
97     // Next check home directory
98     char* envp = ::getenv( "HOME" );
99     if ( envp != NULL ) {
100         config.set( envp );
101         config.append( ".fgfsrc" );
102         current_options.parse_config_file( config.str() );
103     }
104
105     // Parse remaining command line options
106     // These will override anything specified in a config file
107     if ( current_options.parse_command_line(argc, argv) !=
108          fgOPTIONS::FG_OPTIONS_OK )
109     {
110         // Something must have gone horribly wrong with the command
111         // line parsing or maybe the user just requested help ... :-)
112         current_options.usage();
113         FG_LOG( FG_GENERAL, FG_ALERT, "\nExiting ...");
114         return false;
115     }
116
117     return true;
118 }
119
120
121 // Set initial position and orientation
122 bool fgInitPosition( void ) {
123     string id;
124     FGInterface *f;
125
126     f = current_aircraft.fdm_state;
127
128     id = current_options.get_airport_id();
129     if ( id.length() ) {
130         // set initial position from airport id
131
132         fgAIRPORTS airports;
133         fgAIRPORT a;
134
135         FG_LOG( FG_GENERAL, FG_INFO,
136                 "Attempting to set starting position from airport code "
137                 << id );
138
139         airports.load("apt_simple");
140         if ( ! airports.search( id, &a ) ) {
141             FG_LOG( FG_GENERAL, FG_ALERT,
142                     "Failed to find " << id << " in database." );
143             exit(-1);
144         } else {
145             f->set_Longitude( a.longitude * DEG_TO_RAD );
146             f->set_Latitude( a.latitude * DEG_TO_RAD );
147         }
148     } else {
149         // set initial position from default or command line coordinates
150
151         f->set_Longitude( current_options.get_lon() * DEG_TO_RAD );
152         f->set_Latitude( current_options.get_lat() * DEG_TO_RAD );
153     }
154
155     FG_LOG( FG_GENERAL, FG_INFO,
156             "starting altitude is = " << current_options.get_altitude() );
157
158     f->set_Altitude( current_options.get_altitude() * METER_TO_FEET );
159     fgFDMSetGroundElevation( current_options.get_flight_model(),
160                              (f->get_Altitude() - 3.758099) * FEET_TO_METER );
161
162     FG_LOG( FG_GENERAL, FG_INFO,
163             "Initial position is: ("
164             << (f->get_Longitude() * RAD_TO_DEG) << ", "
165             << (f->get_Latitude() * RAD_TO_DEG) << ", "
166             << (f->get_Altitude() * FEET_TO_METER) << ")" );
167
168     return true;
169 }
170
171
172 // General house keeping initializations
173 bool fgInitGeneral( void ) {
174     string root;
175     char *mesa_win_state;
176
177     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
178     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
179
180     root = current_options.get_fg_root();
181     if ( ! root.length() ) {
182         // No root path set? Then bail ...
183         FG_LOG( FG_GENERAL, FG_ALERT,
184                 "Cannot continue without environment variable FG_ROOT"
185                 << "being defined." );
186         exit(-1);
187     }
188     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << root << endl );
189
190 #if defined(FX) && defined(XMESA)
191     // initialize full screen flag
192     global_fullscreen = false;
193     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
194         // Test for the MESA_GLX_FX env variable
195         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
196             // test if we are fullscreen mesa/glide
197             if ( (mesa_win_state[0] == 'f') ||
198                  (mesa_win_state[0] == 'F') ) {
199                 global_fullscreen = true;
200             }
201         }
202     }
203 #endif
204
205     return true;
206 }
207
208
209 // This is the top level init routine which calls all the other
210 // initialization routines.  If you are adding a subsystem to flight
211 // gear, its initialization call should located in this routine.
212 // Returns non-zero if a problem encountered.
213 bool fgInitSubsystems( void ) {
214     FGTime::cur_time_params = new FGTime();
215
216     FGInterface *f; // assigned later
217     fgLIGHT *l = &cur_light_params;
218     FGTime *t = FGTime::cur_time_params;
219     FGView *v = &current_view;
220
221     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
222     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
223
224     // allocates structures so must happen before any of the flight
225     // model or control parameters are set
226     fgAircraftInit();   // In the future this might not be the case.
227     f = current_aircraft.fdm_state;
228
229     // set the initial position
230     fgInitPosition();
231
232     // Initialize the Scenery Management subsystem
233     if ( fgSceneryInit() ) {
234         // Scenery initialized ok.
235     } else {
236         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
237         exit(-1);
238     }
239
240     if( global_tile_mgr.init() ) {
241         // Load the local scenery data
242         global_tile_mgr.update();
243     } else {
244         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
245         exit(-1);
246     }
247
248     FG_LOG( FG_GENERAL, FG_DEBUG,
249             "Current terrain elevation after tile mgr init " <<
250             scenery.cur_elev );
251
252     // Calculate ground elevation at starting point (we didn't have
253     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
254     //
255     // calculalate a cartesian point somewhere along the line between
256     // the center of the earth and our view position.  Doesn't have to
257     // be the exact elevation (this is good because we don't know it
258     // yet :-)
259
260     // now handled inside of the fgTileMgrUpdate()
261
262     /*
263     geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
264     tmp_abs_view_pos = fgGeodToCart(geod_pos);
265
266     FG_LOG( FG_GENERAL, FG_DEBUG,
267             "Initial abs_view_pos = " << tmp_abs_view_pos );
268     scenery.cur_elev =
269         fgTileMgrCurElev( f->get_Longitude(), f->get_Latitude(),
270                           tmp_abs_view_pos );
271     FG_LOG( FG_GENERAL, FG_DEBUG,
272             "Altitude after update " << scenery.cur_elev );
273     */
274
275     fgFDMSetGroundElevation( current_options.get_flight_model(),
276                              scenery.cur_elev );
277
278     // Reset our altitude if we are below ground
279     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = " << f->get_Altitude() );
280     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
281             f->get_Runway_altitude() );
282
283     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
284         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
285     }
286
287     FG_LOG( FG_GENERAL, FG_INFO,
288             "Updated position (after elevation adj): ("
289             << (f->get_Latitude() * RAD_TO_DEG) << ", "
290             << (f->get_Longitude() * RAD_TO_DEG) << ", "
291             << (f->get_Altitude() * FEET_TO_METER) << ")" );
292
293     // We need to calculate a few more values here that would normally
294     // be calculated by the FDM so that the v->UpdateViewMath()
295     // routine doesn't get hosed.
296
297     double sea_level_radius_meters;
298     double lat_geoc;
299     // Set the FG variables first
300     fgGeodToGeoc( f->get_Latitude(), f->get_Altitude(),
301                   &sea_level_radius_meters, &lat_geoc);
302     f->set_Geocentric_Position( lat_geoc, f->get_Longitude(),
303                                 f->get_Altitude() +
304                                 (sea_level_radius_meters * METER_TO_FEET) );
305     f->set_Sea_level_radius( sea_level_radius_meters * METER_TO_FEET );
306
307     f->set_sin_cos_longitude(f->get_Longitude());
308     f->set_sin_cos_latitude(f->get_Latitude());
309         
310     f->set_sin_lat_geocentric(sin(lat_geoc));
311     f->set_cos_lat_geocentric(cos(lat_geoc));
312
313     // The following section sets up the flight model EOM parameters
314     // and should really be read in from one or more files.
315
316     // Initial Velocity
317     f->set_Velocities_Local( 0.0, 0.0, 0.0 );
318
319     // Initial Orientation
320     f->set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
321                          current_options.get_pitch() * DEG_TO_RAD,
322                          current_options.get_heading() * DEG_TO_RAD );
323
324     // Initial Angular Body rates
325     f->set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
326
327     f->set_Earth_position_angle( 0.0 );
328
329     // Mass properties and geometry values
330     f->set_Inertias( 8.547270E+01,
331                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
332
333     // CG position w.r.t. ref. point
334     f->set_CG_Position( 0.0, 0.0, 0.0 );
335
336     // Initialize the event manager
337     global_events.Init();
338
339     // Output event stats every 60 seconds
340     global_events.Register( "fgEVENT_MGR::PrintStats()",
341                             fgMethodCallback<fgEVENT_MGR>( &global_events,
342                                                    &fgEVENT_MGR::PrintStats),
343                             fgEVENT::FG_EVENT_READY, 60000 );
344
345     // Initialize the time dependent variables
346     t->init();
347     t->update(f);
348
349     // Initialize view parameters
350     FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
351     v->Init();
352     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
353     v->UpdateViewMath(f);
354     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
355     v->UpdateWorldToEye(f);
356
357     // Build the solar system
358     //fgSolarSystemInit(*t);
359     FG_LOG(FG_GENERAL, FG_INFO, "Building SolarSystem");
360     SolarSystem::theSolarSystem = new SolarSystem(t);
361
362     // Initialize the Stars subsystem
363     if( fgStarsInit() ) {
364         // Stars initialized ok.
365     } else {
366         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Stars initialization!" );
367         exit(-1);
368     }
369
370     // Initialize the planetary subsystem
371     // global_events.Register( "fgPlanetsInit()", fgPlanetsInit,
372     //                      fgEVENT::FG_EVENT_READY, 600000);
373
374     // Initialize the sun's position
375     // global_events.Register( "fgSunInit()", fgSunInit,
376     //                      fgEVENT::FG_EVENT_READY, 30000 );
377
378     // Intialize the moon's position
379     // global_events.Register( "fgMoonInit()", fgMoonInit,
380     //                      fgEVENT::FG_EVENT_READY, 600000 );
381
382     // register the periodic update of Sun, moon, and planets
383     global_events.Register( "ssolsysUpdate", solarSystemRebuild,
384                             fgEVENT::FG_EVENT_READY, 600000);
385
386     // fgUpdateSunPos() needs a few position and view parameters set
387     // so it can calculate local relative sun angle and a few other
388     // things for correctly orienting the sky.
389     fgUpdateSunPos();
390     fgUpdateMoonPos();
391     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
392                             fgEVENT::FG_EVENT_READY, 60000);
393     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
394                             fgEVENT::FG_EVENT_READY, 60000);
395
396     // Initialize Lighting interpolation tables
397     l->Init();
398
399     // update the lighting parameters (based on sun angle)
400     global_events.Register( "fgLight::Update()",
401                             fgMethodCallback<fgLIGHT>( &cur_light_params,
402                                                        &fgLIGHT::Update),
403                             fgEVENT::FG_EVENT_READY, 30000 );
404
405     // Initialize the weather modeling subsystem
406     current_weather.Init();
407
408     // Initialize the Cockpit subsystem
409     if( fgCockpitInit( &current_aircraft )) {
410         // Cockpit initialized ok.
411     } else {
412         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
413         exit(-1);
414     }
415
416     // Initialize the "sky"
417     fgSkyInit();
418
419     // Initialize the flight model subsystem data structures base on
420     // above values
421
422     fgFDMInit( current_options.get_flight_model(), cur_fdm_state,
423                1.0 / DEFAULT_MODEL_HZ );
424
425     // I'm just sticking this here for now, it should probably move
426     // eventually
427     scenery.cur_elev = f->get_Runway_altitude() * FEET_TO_METER;
428
429     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
430         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
431     }
432
433     FG_LOG( FG_GENERAL, FG_INFO,
434             "Updated position (after elevation adj): ("
435             << (f->get_Latitude() * RAD_TO_DEG) << ", "
436             << (f->get_Longitude() * RAD_TO_DEG) << ", "
437             << (f->get_Altitude() * FEET_TO_METER) << ")" );
438     // end of thing that I just stuck in that I should probably move
439
440     // Joystick support
441     if ( fgJoystickInit() ) {
442         // Joystick initialized ok.
443     } else {
444         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
445     }
446
447     // Autopilot init added here, by Jeff Goeke-Smith
448     fgAPInit(&current_aircraft);
449
450     // Initialize serial ports
451 #if ! defined( MACOS )
452     fgSerialInit();
453 #endif
454
455     FG_LOG( FG_GENERAL, FG_INFO, endl);
456
457     return true;
458 }
459
460
461 void fgReInitSubsystems( void )
462 {
463     FGInterface *f = current_aircraft.fdm_state;
464     FGView *v = &current_view;
465     FGTime *t = FGTime::cur_time_params;
466     
467     int toggle_pause = t->getPause();
468     
469     if( !toggle_pause )
470         t->togglePauseMode();
471     
472     fgInitPosition();
473     if( global_tile_mgr.init() ) {
474         // Load the local scenery data
475         global_tile_mgr.update();
476     } else {
477         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
478                 exit(-1);
479     }
480     fgFDMSetGroundElevation( current_options.get_flight_model(), 
481                              scenery.cur_elev );
482
483     // Reset our altitude if we are below ground
484     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = " << f->get_Altitude() );
485     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " << 
486             f->get_Runway_altitude() );
487
488     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
489         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
490     }
491     double sea_level_radius_meters;
492     double lat_geoc;
493     // Set the FG variables first
494     fgGeodToGeoc( f->get_Latitude(), f->get_Altitude(), 
495                   &sea_level_radius_meters, &lat_geoc);
496     f->set_Geocentric_Position( lat_geoc, f->get_Longitude(), 
497                                 f->get_Altitude() + 
498                                 (sea_level_radius_meters * METER_TO_FEET) );
499     f->set_Sea_level_radius( sea_level_radius_meters * METER_TO_FEET );
500         
501     f->set_sin_cos_longitude(f->get_Longitude());
502     f->set_sin_cos_latitude(f->get_Latitude());
503         
504     f->set_sin_lat_geocentric(sin(lat_geoc));
505     f->set_cos_lat_geocentric(cos(lat_geoc));
506
507     // The following section sets up the flight model EOM parameters
508     // and should really be read in from one or more files.
509
510     // Initial Velocity
511     f->set_Velocities_Local( 0.0, 0.0, 0.0 );
512
513     // Initial Orientation
514     f->set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
515                          current_options.get_pitch() * DEG_TO_RAD,
516                          current_options.get_heading() * DEG_TO_RAD );
517
518     // Initial Angular Body rates
519     f->set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
520
521     f->set_Earth_position_angle( 0.0 );
522
523     // Mass properties and geometry values
524     f->set_Inertias( 8.547270E+01, 
525                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
526
527     // CG position w.r.t. ref. point
528     f->set_CG_Position( 0.0, 0.0, 0.0 );
529
530     // Initialize view parameters
531     FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
532     v->Init();
533     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
534     v->UpdateViewMath(f);
535     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
536     v->UpdateWorldToEye(f);
537
538     fgFDMInit( current_options.get_flight_model(), cur_fdm_state, 
539                1.0 / DEFAULT_MODEL_HZ );
540
541     scenery.cur_elev = f->get_Runway_altitude() * FEET_TO_METER;
542
543     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
544         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
545     }
546
547     controls.reset_all();
548     fgAPReset();
549
550     if( !toggle_pause )
551         t->togglePauseMode();
552 }