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