]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Return to glider model ...
[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( current_options.get_uBody(),
318                              current_options.get_vBody(),
319                              current_options.get_wBody());
320
321     // Initial Orientation
322     f->set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
323                          current_options.get_pitch() * DEG_TO_RAD,
324                          current_options.get_heading() * DEG_TO_RAD );
325
326     // Initial Angular Body rates
327     f->set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
328
329     f->set_Earth_position_angle( 0.0 );
330
331     // Mass properties and geometry values
332     f->set_Inertias( 8.547270E+01,
333                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
334
335     // CG position w.r.t. ref. point
336     f->set_CG_Position( 0.0, 0.0, 0.0 );
337
338     // Initialize the event manager
339     global_events.Init();
340
341     // Output event stats every 60 seconds
342     global_events.Register( "fgEVENT_MGR::PrintStats()",
343                             fgMethodCallback<fgEVENT_MGR>( &global_events,
344                                                    &fgEVENT_MGR::PrintStats),
345                             fgEVENT::FG_EVENT_READY, 60000 );
346
347     // Initialize the time dependent variables
348     t->init();
349     t->update(f);
350
351     // Initialize view parameters
352     FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
353     v->Init();
354     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
355     v->UpdateViewMath(f);
356     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
357     v->UpdateWorldToEye(f);
358
359     // Build the solar system
360     //fgSolarSystemInit(*t);
361     FG_LOG(FG_GENERAL, FG_INFO, "Building SolarSystem");
362     SolarSystem::theSolarSystem = new SolarSystem(t);
363
364     // Initialize the Stars subsystem
365     if( fgStarsInit() ) {
366         // Stars initialized ok.
367     } else {
368         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Stars initialization!" );
369         exit(-1);
370     }
371
372     // Initialize the planetary subsystem
373     // global_events.Register( "fgPlanetsInit()", fgPlanetsInit,
374     //                      fgEVENT::FG_EVENT_READY, 600000);
375
376     // Initialize the sun's position
377     // global_events.Register( "fgSunInit()", fgSunInit,
378     //                      fgEVENT::FG_EVENT_READY, 30000 );
379
380     // Intialize the moon's position
381     // global_events.Register( "fgMoonInit()", fgMoonInit,
382     //                      fgEVENT::FG_EVENT_READY, 600000 );
383
384     // register the periodic update of Sun, moon, and planets
385     global_events.Register( "ssolsysUpdate", solarSystemRebuild,
386                             fgEVENT::FG_EVENT_READY, 600000);
387
388     // fgUpdateSunPos() needs a few position and view parameters set
389     // so it can calculate local relative sun angle and a few other
390     // things for correctly orienting the sky.
391     fgUpdateSunPos();
392     fgUpdateMoonPos();
393     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
394                             fgEVENT::FG_EVENT_READY, 60000);
395     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
396                             fgEVENT::FG_EVENT_READY, 60000);
397
398     // Initialize Lighting interpolation tables
399     l->Init();
400
401     // update the lighting parameters (based on sun angle)
402     global_events.Register( "fgLight::Update()",
403                             fgMethodCallback<fgLIGHT>( &cur_light_params,
404                                                        &fgLIGHT::Update),
405                             fgEVENT::FG_EVENT_READY, 30000 );
406
407     // Initialize the weather modeling subsystem
408     current_weather.Init();
409
410     // Initialize the Cockpit subsystem
411     if( fgCockpitInit( &current_aircraft )) {
412         // Cockpit initialized ok.
413     } else {
414         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
415         exit(-1);
416     }
417
418     // Initialize the "sky"
419     fgSkyInit();
420
421     // Initialize the flight model subsystem data structures base on
422     // above values
423
424     fgFDMInit( current_options.get_flight_model(), cur_fdm_state,
425                1.0 / DEFAULT_MODEL_HZ );
426
427     // I'm just sticking this here for now, it should probably move
428     // eventually
429     scenery.cur_elev = f->get_Runway_altitude() * FEET_TO_METER;
430
431     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
432         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
433     }
434
435     FG_LOG( FG_GENERAL, FG_INFO,
436             "Updated position (after elevation adj): ("
437             << (f->get_Latitude() * RAD_TO_DEG) << ", "
438             << (f->get_Longitude() * RAD_TO_DEG) << ", "
439             << (f->get_Altitude() * FEET_TO_METER) << ")" );
440     // end of thing that I just stuck in that I should probably move
441
442     // Joystick support
443     if ( fgJoystickInit() ) {
444         // Joystick initialized ok.
445     } else {
446         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
447     }
448
449     // Autopilot init added here, by Jeff Goeke-Smith
450     fgAPInit(&current_aircraft);
451
452     // Initialize serial ports
453 #if ! defined( MACOS )
454     fgSerialInit();
455 #endif
456
457     FG_LOG( FG_GENERAL, FG_INFO, endl);
458
459     return true;
460 }
461
462
463 void fgReInitSubsystems( void )
464 {
465     FGInterface *f = current_aircraft.fdm_state;
466     FGView *v = &current_view;
467     FGTime *t = FGTime::cur_time_params;
468     
469     int toggle_pause = t->getPause();
470     
471     if( !toggle_pause )
472         t->togglePauseMode();
473     
474     fgInitPosition();
475     if( global_tile_mgr.init() ) {
476         // Load the local scenery data
477         global_tile_mgr.update();
478     } else {
479         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
480                 exit(-1);
481     }
482     fgFDMSetGroundElevation( current_options.get_flight_model(), 
483                              scenery.cur_elev );
484
485     // Reset our altitude if we are below ground
486     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = " << f->get_Altitude() );
487     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " << 
488             f->get_Runway_altitude() );
489
490     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
491         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
492     }
493     double sea_level_radius_meters;
494     double lat_geoc;
495     // Set the FG variables first
496     fgGeodToGeoc( f->get_Latitude(), f->get_Altitude(), 
497                   &sea_level_radius_meters, &lat_geoc);
498     f->set_Geocentric_Position( lat_geoc, f->get_Longitude(), 
499                                 f->get_Altitude() + 
500                                 (sea_level_radius_meters * METER_TO_FEET) );
501     f->set_Sea_level_radius( sea_level_radius_meters * METER_TO_FEET );
502         
503     f->set_sin_cos_longitude(f->get_Longitude());
504     f->set_sin_cos_latitude(f->get_Latitude());
505         
506     f->set_sin_lat_geocentric(sin(lat_geoc));
507     f->set_cos_lat_geocentric(cos(lat_geoc));
508
509     // The following section sets up the flight model EOM parameters
510     // and should really be read in from one or more files.
511
512     // Initial Velocity
513     f->set_Velocities_Local( current_options.get_uBody(),
514                              current_options.get_vBody(),
515                              current_options.get_wBody());
516
517     // Initial Orientation
518     f->set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
519                          current_options.get_pitch() * DEG_TO_RAD,
520                          current_options.get_heading() * DEG_TO_RAD );
521
522     // Initial Angular Body rates
523     f->set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
524
525     f->set_Earth_position_angle( 0.0 );
526
527     // Mass properties and geometry values
528     f->set_Inertias( 8.547270E+01, 
529                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
530
531     // CG position w.r.t. ref. point
532     f->set_CG_Position( 0.0, 0.0, 0.0 );
533
534     // Initialize view parameters
535     FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
536     v->Init();
537     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
538     v->UpdateViewMath(f);
539     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
540     v->UpdateWorldToEye(f);
541
542     fgFDMInit( current_options.get_flight_model(), cur_fdm_state, 
543                1.0 / DEFAULT_MODEL_HZ );
544
545     scenery.cur_elev = f->get_Runway_altitude() * FEET_TO_METER;
546
547     if ( f->get_Altitude() < f->get_Runway_altitude() + 3.758099) {
548         f->set_Altitude( f->get_Runway_altitude() + 3.758099 );
549     }
550
551     controls.reset_all();
552     fgAPReset();
553
554     if( !toggle_pause )
555         t->togglePauseMode();
556 }