]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
43bd1d3265492294d60b818cb35b4e661c649879
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
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.
11 //
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.
16 //
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.
20 //
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef FG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #include <GL/glut.h>
35 #include <simgear/xgl/xgl.h>
36
37 #include <stdio.h>
38 #include <stdlib.h>
39
40 // work around a stdc++ lib bug in some versions of linux, but doesn't
41 // seem to hurt to have this here for all versions of Linux.
42 #ifdef linux
43 #  define _G_NO_EXTERN_TEMPLATES
44 #endif
45
46 #include <simgear/compiler.h>
47
48 #include STL_STRING
49
50 #include <simgear/constants.h>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/math/point3d.hxx>
53 #include <simgear/math/polar3d.hxx>
54 #include <simgear/math/sg_geodesy.hxx>
55 #include <simgear/misc/fgpath.hxx>
56 #include <simgear/timing/sg_time.hxx>
57
58 #include <Aircraft/aircraft.hxx>
59 #include <Airports/runways.hxx>
60 #include <Airports/simple.hxx>
61 #include <Autopilot/auto_gui.hxx>
62 #include <Autopilot/newauto.hxx>
63 #include <Cockpit/cockpit.hxx>
64 #include <Cockpit/radiostack.hxx>
65 #include <Cockpit/panel.hxx>
66 #include <Cockpit/panel_io.hxx>
67 #include <FDM/ADA.hxx>
68 #include <FDM/Balloon.h>
69 #include <FDM/External.hxx>
70 #include <FDM/JSBSim.hxx>
71 #include <FDM/LaRCsim.hxx>
72 #include <FDM/MagicCarpet.hxx>
73 #include <Include/general.hxx>
74 #include <Joystick/joystick.hxx>
75 #include <Objects/matlib.hxx>
76 #include <Navaids/fixlist.hxx>
77 #include <Navaids/ilslist.hxx>
78 #include <Navaids/navlist.hxx>
79 #include <Scenery/scenery.hxx>
80 #include <Scenery/tilemgr.hxx>
81 #include <Time/event.hxx>
82 #include <Time/light.hxx>
83 #include <Time/sunpos.hxx>
84 #include <Time/moonpos.hxx>
85 #include <Time/tmp.hxx>
86
87 #ifndef FG_OLD_WEATHER
88 #  include <WeatherCM/FGLocalWeatherDatabase.h>
89 #else
90 #  include <Weather/weather.hxx>
91 #endif
92
93 #include "fg_init.hxx"
94 #include "fg_io.hxx"
95 #include "options.hxx"
96 #include "globals.hxx"
97 #include "bfi.hxx"
98
99 #if defined(FX) && defined(XMESA)
100 #include <GL/xmesa.h>
101 #endif
102
103 FG_USING_STD(string);
104
105 extern const char *default_root;
106
107
108 // Read in configuration (file and command line) and just set fg_root
109 bool fgInitFGRoot ( int argc, char **argv ) {
110     string root;
111     char* envp;
112
113     // First parse command line options looking for fg-root, this will
114     // override anything specified in a config file
115     root = fgScanForRoot(argc, argv);
116
117     // Next check home directory for .fgfsrc file
118     if ( root == "" ) {
119         envp = ::getenv( "HOME" );
120         if ( envp != NULL ) {
121             FGPath config( envp );
122             config.append( ".fgfsrc" );
123             root = fgScanForRoot(config.str());
124         }
125     }
126     
127     // Next check if fg-root is set as an env variable
128     if ( root == "" ) {
129         envp = ::getenv( "FG_ROOT" );
130         if ( envp != NULL ) {
131             root = envp;
132         }
133     }
134
135     // Otherwise, default to a random compiled-in location if we can't
136     // find fg-root any other way.
137     if ( root == "" ) {
138 #if defined( WIN32 )
139         root = "\\FlightGear";
140 #elif defined( macintosh )
141         root = "";
142 #else
143         root = PKGLIBDIR;
144 #endif
145     }
146
147     FG_LOG(FG_INPUT, FG_INFO, "fg_root = " << root );
148     globals->set_fg_root(root);
149
150     return true;
151 }
152
153
154 // Read in configuration (file and command line)
155 bool fgInitConfig ( int argc, char **argv ) {
156
157                                 // First, set some sane default values
158     fgSetDefaults();
159
160     // Read global preferences from $FG_ROOT/preferences.xml
161     FGPath props_path(globals->get_fg_root());
162     props_path.append("preferences.xml");
163     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
164     if (!readProperties(props_path.str(), globals->get_props())) {
165       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
166              << props_path.str());
167     } else {
168       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
169     }
170
171     // Attempt to locate and parse a config file
172     // First check fg_root
173     FGPath config( globals->get_fg_root() );
174     config.append( "system.fgfsrc" );
175     fgParseOptions(config.str());
176
177     // Next check home directory
178     char* envp = ::getenv( "HOME" );
179     if ( envp != NULL ) {
180         config.set( envp );
181         config.append( ".fgfsrc" );
182         fgParseOptions(config.str());
183     }
184
185     // Parse remaining command line options
186     // These will override anything specified in a config file
187     fgParseOptions(argc, argv);
188
189     return true;
190 }
191
192
193 // find basic airport location info from airport database
194 bool fgFindAirportID( const string& id, FGAirport *a ) {
195     if ( id.length() ) {
196         FGPath path( globals->get_fg_root() );
197         path.append( "Airports" );
198         path.append( "simple.mk4" );
199         FGAirports airports( path.c_str() );
200
201         FG_LOG( FG_GENERAL, FG_INFO, "Searching for airport code = " << id );
202
203         if ( ! airports.search( id, a ) ) {
204             FG_LOG( FG_GENERAL, FG_ALERT,
205                     "Failed to find " << id << " in " << path.str() );
206             return false;
207         }
208     } else {
209         return false;
210     }
211
212     FG_LOG( FG_GENERAL, FG_INFO,
213             "Position for " << id << " is ("
214             << a->longitude << ", "
215             << a->latitude << ")" );
216
217     return true;
218 }
219
220
221 // Set current_options lon/lat given an airport id
222 bool fgSetPosFromAirportID( const string& id ) {
223     FGAirport a;
224     // double lon, lat;
225
226     FG_LOG( FG_GENERAL, FG_INFO,
227             "Attempting to set starting position from airport code " << id );
228
229     if ( fgFindAirportID( id, &a ) ) {
230         fgSetDouble("/position/longitude",  a.longitude );
231         fgSetDouble("/position/latitude",  a.latitude );
232         FG_LOG( FG_GENERAL, FG_INFO,
233                 "Position for " << id << " is ("
234                 << a.longitude << ", "
235                 << a.latitude << ")" );
236
237         return true;
238     } else {
239         return false;
240     }
241
242 }
243
244
245 // Set current_options lon/lat given an airport id and heading (degrees)
246 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
247     FGRunway r;
248     FGRunway found_r;
249     double found_dir = 0.0;
250
251     if ( id.length() ) {
252         // set initial position from runway and heading
253
254         FGPath path( globals->get_fg_root() );
255         path.append( "Airports" );
256         path.append( "runways.mk4" );
257         FGRunways runways( path.c_str() );
258
259         FG_LOG( FG_GENERAL, FG_INFO,
260                 "Attempting to set starting position from runway code "
261                 << id << " heading " << tgt_hdg );
262
263         // FGPath inpath( globals->get_fg_root() );
264         // inpath.append( "Airports" );
265         // inpath.append( "apt_simple" );
266         // airports.load( inpath.c_str() );
267
268         // FGPath outpath( globals->get_fg_root() );
269         // outpath.append( "Airports" );
270         // outpath.append( "simple.gdbm" );
271         // airports.dump_gdbm( outpath.c_str() );
272
273         if ( ! runways.search( id, &r ) ) {
274             FG_LOG( FG_GENERAL, FG_ALERT,
275                     "Failed to find " << id << " in database." );
276             return false;
277         }
278
279         double diff;
280         double min_diff = 360.0;
281
282         while ( r.id == id ) {
283             // forward direction
284             diff = tgt_hdg - r.heading;
285             while ( diff < -180.0 ) { diff += 360.0; }
286             while ( diff >  180.0 ) { diff -= 360.0; }
287             diff = fabs(diff);
288             FG_LOG( FG_GENERAL, FG_INFO,
289                     "Runway " << r.rwy_no << " heading = " << r.heading <<
290                     " diff = " << diff );
291             if ( diff < min_diff ) {
292                 min_diff = diff;
293                 found_r = r;
294                 found_dir = 0;
295             }
296
297             // reverse direction
298             diff = tgt_hdg - r.heading - 180.0;
299             while ( diff < -180.0 ) { diff += 360.0; }
300             while ( diff >  180.0 ) { diff -= 360.0; }
301             diff = fabs(diff);
302             FG_LOG( FG_GENERAL, FG_INFO,
303                     "Runway -" << r.rwy_no << " heading = " <<
304                     r.heading + 180.0 <<
305                     " diff = " << diff );
306             if ( diff < min_diff ) {
307                 min_diff = diff;
308                 found_r = r;
309                 found_dir = 180.0;
310             }
311
312             runways.next( &r );
313         }
314
315         FG_LOG( FG_GENERAL, FG_INFO, "closest runway = " << found_r.rwy_no
316                 << " + " << found_dir );
317
318     } else {
319         return false;
320     }
321
322     double heading = found_r.heading + found_dir;
323     while ( heading >= 360.0 ) { heading -= 360.0; }
324
325     double lat2, lon2, az2;
326     double azimuth = found_r.heading + found_dir + 180.0;
327     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
328
329     FG_LOG( FG_GENERAL, FG_INFO,
330             "runway =  " << found_r.lon << ", " << found_r.lat
331             << " length = " << found_r.length * FEET_TO_METER * 0.5 
332             << " heading = " << azimuth );
333     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
334                         azimuth, found_r.length * FEET_TO_METER * 0.5 - 5.0,
335                         &lat2, &lon2, &az2 );
336     fgSetDouble("/position/longitude",  lon2 );
337     fgSetDouble("/position/latitude",  lat2 );
338     fgSetDouble("/orientation/heading", heading );
339
340     FG_LOG( FG_GENERAL, FG_INFO,
341             "Position for " << id << " is ("
342             << lon2 << ", "
343             << lat2 << ") new heading is "
344             << heading );
345
346     return true;
347 }
348
349
350 // Set initial position and orientation
351 bool fgInitPosition( void ) {
352     FGInterface *f = current_aircraft.fdm_state;
353     string id = fgGetString("/sim/startup/airport-id");
354
355     // set initial position from default or command line coordinates
356     f->set_Longitude( fgGetDouble("/position/longitude") * DEG_TO_RAD );
357     f->set_Latitude( fgGetDouble("/position/latitude") * DEG_TO_RAD );
358
359     if ( scenery.cur_elev > fgGetDouble("/position/altitude") - 1) {
360         fgSetDouble("/position/altitude", scenery.cur_elev + 1 );
361     }
362
363     FG_LOG( FG_GENERAL, FG_INFO,
364             "starting altitude is = " << fgGetDouble("/position/altitude") );
365
366     f->set_Altitude( fgGetDouble("/position/altitude") * METER_TO_FEET );
367     FG_LOG( FG_GENERAL, FG_INFO,
368             "Initial position is: ("
369             << (f->get_Longitude() * RAD_TO_DEG) << ", "
370             << (f->get_Latitude() * RAD_TO_DEG) << ", "
371             << (f->get_Altitude() * FEET_TO_METER) << ")" );
372
373     return true;
374 }
375
376
377 // General house keeping initializations
378 bool fgInitGeneral( void ) {
379     string root;
380
381 #if defined(FX) && defined(XMESA)
382     char *mesa_win_state;
383 #endif
384
385     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
386     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
387
388     root = globals->get_fg_root();
389     if ( ! root.length() ) {
390         // No root path set? Then bail ...
391         FG_LOG( FG_GENERAL, FG_ALERT,
392                 "Cannot continue without environment variable FG_ROOT"
393                 << "being defined." );
394         exit(-1);
395     }
396     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
397
398 #if defined(FX) && defined(XMESA)
399     // initialize full screen flag
400     global_fullscreen = false;
401     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
402         // Test for the MESA_GLX_FX env variable
403         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
404             // test if we are fullscreen mesa/glide
405             if ( (mesa_win_state[0] == 'f') ||
406                  (mesa_win_state[0] == 'F') ) {
407                 global_fullscreen = true;
408             }
409         }
410     }
411 #endif
412
413     return true;
414 }
415
416
417 // set initial aircraft speed
418 void
419 fgVelocityInit( void ) 
420 {
421   if (!fgHasValue("/sim/startup/speed-set")) {
422     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
423     return;
424   }
425
426   const string speedset = fgGetString("/sim/startup/speed-set");
427   if (speedset == "knots" || speedset == "KNOTS") {
428     current_aircraft.fdm_state
429       ->set_V_calibrated_kts(fgGetDouble("/velocities/airspeed"));
430   } else if (speedset == "mach" || speedset == "MACH") {
431     current_aircraft.fdm_state
432       ->set_Mach_number(fgGetDouble("/velocities/mach"));
433   } else if (speedset == "UVW" || speedset == "uvw") {
434     current_aircraft.fdm_state
435       ->set_Velocities_Wind_Body(fgGetDouble("/velocities/uBody"),
436                                  fgGetDouble("/velocities/vBody"),
437                                  fgGetDouble("/velocities/wBody"));
438   } else if (speedset == "NED" || speedset == "ned") {
439     current_aircraft.fdm_state
440       ->set_Velocities_Local(fgGetDouble("/velocities/speed-north"),
441                              fgGetDouble("/velocities/speed-east"),
442                              fgGetDouble("/velocities/speed-down"));
443   } else {
444     FG_LOG(FG_GENERAL, FG_ALERT,
445            "Unrecognized value for /sim/startup/speed-set: " << speedset);
446     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
447   }
448 }             
449
450         
451 // This is the top level init routine which calls all the other
452 // initialization routines.  If you are adding a subsystem to flight
453 // gear, its initialization call should located in this routine.
454 // Returns non-zero if a problem encountered.
455 bool fgInitSubsystems( void ) {
456     fgLIGHT *l = &cur_light_params;
457
458     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
459     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
460
461     // Initialize the material property lib
462     FGPath mpath( globals->get_fg_root() );
463     mpath.append( "materials" );
464     if ( material_lib.load( mpath.str() ) ) {
465     } else {
466         FG_LOG( FG_GENERAL, FG_ALERT, "Error loading material lib!" );
467         exit(-1);
468     }
469
470     // Initialize the Scenery Management subsystem
471     if ( fgSceneryInit() ) {
472         // Material lib initialized ok.
473     } else {
474         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
475         exit(-1);
476     }
477
478     if ( global_tile_mgr.init() ) {
479         // Load the local scenery data
480         global_tile_mgr.update( fgGetDouble("/position/longitude"),
481                                 fgGetDouble("/position/latitude") );
482     } else {
483         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
484         exit(-1);
485     }
486
487     FG_LOG( FG_GENERAL, FG_DEBUG,
488             "Current terrain elevation after tile mgr init " <<
489             scenery.cur_elev );
490
491     double dt = 1.0 / fgGetInt("/sim/model-hz");
492
493     const string &model = fgGetString("/sim/flight-model");
494     if (model == "larcsim") {
495         cur_fdm_state = new FGLaRCsim( dt );
496     } else if (model == "jsb") {
497         cur_fdm_state = new FGJSBsim( dt );
498     } else if (model == "ada") {
499         cur_fdm_state = new FGADA( dt );
500     } else if (model == "balloon") {
501         cur_fdm_state = new FGBalloonSim( dt );
502     } else if (model == "magic") {
503         cur_fdm_state = new FGMagicCarpet( dt );
504     } else if (model == "external") {
505         cur_fdm_state = new FGExternal( dt );
506     } else {
507         FG_LOG(FG_GENERAL, FG_ALERT,
508                "Unrecognized flight model '" << model
509                << ", can't init aircraft");
510         exit(-1);
511     }
512
513     // allocates structures so must happen before any of the flight
514     // model or control parameters are set
515     fgAircraftInit();   // In the future this might not be the case.
516
517     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"),
518                              scenery.cur_elev );
519     
520     // set the initial position
521     fgInitPosition();
522
523     // Calculate ground elevation at starting point (we didn't have
524     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
525     //
526     // calculalate a cartesian point somewhere along the line between
527     // the center of the earth and our view position.  Doesn't have to
528     // be the exact elevation (this is good because we don't know it
529     // yet :-)
530
531     // now handled inside of the fgTileMgrUpdate()
532
533     // Reset our altitude if we are below ground
534     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
535             << cur_fdm_state->get_Altitude() );
536     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
537             cur_fdm_state->get_Runway_altitude() );
538
539     if ( cur_fdm_state->get_Altitude() < cur_fdm_state->get_Runway_altitude() +
540          3.758099) {
541         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
542                                      3.758099 );
543     }
544
545     FG_LOG( FG_GENERAL, FG_INFO,
546             "Updated position (after elevation adj): ("
547             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
548             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
549             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
550
551     // We need to calculate a few sea_level_radius here so we can pass
552     // the correct value to the view class
553     double sea_level_radius_meters;
554     double lat_geoc;
555     sgGeodToGeoc( cur_fdm_state->get_Latitude(),
556                   cur_fdm_state->get_Altitude(),
557                   &sea_level_radius_meters, &lat_geoc);
558     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
559                                          METER_TO_FEET );
560
561     // The following section sets up the flight model EOM parameters
562     // and should really be read in from one or more files.
563
564     // Initial Velocity
565     fgVelocityInit();
566
567     // Initial Orientation
568 //     cur_fdm_state->
569 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
570 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
571 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
572
573     // Initialize the event manager
574     global_events.Init();
575
576     // Output event stats every 60 seconds
577     global_events.Register( "fgEVENT_MGR::PrintStats()",
578                             fgMethodCallback<fgEVENT_MGR>( &global_events,
579                                                    &fgEVENT_MGR::PrintStats),
580                             fgEVENT::FG_EVENT_READY, 60000 );
581
582     // Initialize win_ratio parameters
583     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
584         globals->get_viewmgr()->get_view(i)->
585             set_win_ratio( fgGetInt("/sim/startup/xsize") /
586                            fgGetInt("/sim/startup/ysize") );
587     }
588
589     // Initialize pilot view
590     FGViewerRPH *pilot_view =
591         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
592
593     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
594                                    cur_fdm_state->get_Lat_geocentric(), 
595                                    cur_fdm_state->get_Altitude() *
596                                    FEET_TO_METER );
597     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
598                                       FEET_TO_METER ); 
599     pilot_view->set_rph( cur_fdm_state->get_Phi(),
600                          cur_fdm_state->get_Theta(),
601                          cur_fdm_state->get_Psi() );
602
603     // set current view to 0 (first) which is our main pilot view
604     globals->set_current_view( pilot_view );
605
606     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
607             << globals->get_current_view()->get_abs_view_pos());
608
609     // fgUpdateSunPos() needs a few position and view parameters set
610     // so it can calculate local relative sun angle and a few other
611     // things for correctly orienting the sky.
612     fgUpdateSunPos();
613     fgUpdateMoonPos();
614     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
615                             fgEVENT::FG_EVENT_READY, 60000);
616     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
617                             fgEVENT::FG_EVENT_READY, 60000);
618
619     // Initialize Lighting interpolation tables
620     l->Init();
621
622     // update the lighting parameters (based on sun angle)
623     global_events.Register( "fgLight::Update()",
624                             fgMethodCallback<fgLIGHT>( &cur_light_params,
625                                                        &fgLIGHT::Update),
626                             fgEVENT::FG_EVENT_READY, 30000 );
627     // update the current timezone each 30 minutes
628     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
629                             fgEVENT::FG_EVENT_READY, 1800000);
630
631     // Initialize the weather modeling subsystem
632 #ifndef FG_OLD_WEATHER
633     // Initialize the WeatherDatabase
634     FG_LOG(FG_GENERAL, FG_INFO, "Creating LocalWeatherDatabase");
635     sgVec3 position;
636     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
637                current_aircraft.fdm_state->get_Longitude(),
638                current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER );
639     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
640         new FGLocalWeatherDatabase( position,
641                                     globals->get_fg_root() );
642     // cout << theFGLocalWeatherDatabase << endl;
643     // cout << "visibility = " 
644     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
645
646     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
647     
648     double init_vis = fgGetDouble("/environment/visibility");
649     if ( init_vis > 0 ) {
650         WeatherDatabase->setWeatherVisibility( init_vis );
651     }
652
653     // register the periodic update of the weather
654     global_events.Register( "weather update", fgUpdateWeatherDatabase,
655                             fgEVENT::FG_EVENT_READY, 30000);
656 #else
657     current_weather.Init();
658 #endif
659
660     // Initialize vor/ndb/ils/fix list management and query systems
661     FG_LOG(FG_GENERAL, FG_INFO, "Loading Navaids");
662
663     FG_LOG(FG_GENERAL, FG_INFO, "  VOR/NDB");
664     current_navlist = new FGNavList;
665     FGPath p_nav( globals->get_fg_root() );
666     p_nav.append( "Navaids/default.nav" );
667     current_navlist->init( p_nav );
668
669     FG_LOG(FG_GENERAL, FG_INFO, "  ILS");
670     current_ilslist = new FGILSList;
671     FGPath p_ils( globals->get_fg_root() );
672     p_ils.append( "Navaids/default.ils" );
673     current_ilslist->init( p_ils );
674
675     FG_LOG(FG_GENERAL, FG_INFO, "  Fixes");
676     current_fixlist = new FGFixList;
677     FGPath p_fix( globals->get_fg_root() );
678     p_fix.append( "Navaids/default.fix" );
679     current_fixlist->init( p_fix );
680
681     // Radio stack subsystem.
682     current_radiostack = new FGRadioStack;
683     current_radiostack->init();
684     current_radiostack->bind();
685
686     // Initialize the Cockpit subsystem
687     if( fgCockpitInit( &current_aircraft )) {
688         // Cockpit initialized ok.
689     } else {
690         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
691         exit(-1);
692     }
693
694     // Initialize the flight model subsystem data structures base on
695     // above values
696
697     cur_fdm_state->init();
698     cur_fdm_state->bind();
699 //     if ( cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") ) ) {
700 //      // fdm init successful
701 //     } else {
702 //      FG_LOG( FG_GENERAL, FG_ALERT, "FDM init() failed!  Cannot continue." );
703 //      exit(-1);
704 //     }
705
706     // *ABCD* I'm just sticking this here for now, it should probably
707     // move eventually
708     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
709
710     if ( cur_fdm_state->get_Altitude() <
711          cur_fdm_state->get_Runway_altitude() + 3.758099)
712     {
713         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
714                                      3.758099 );
715     }
716
717     FG_LOG( FG_GENERAL, FG_INFO,
718             "Updated position (after elevation adj): ("
719             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
720             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
721             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
722     // *ABCD* end of thing that I just stuck in that I should probably
723     // move
724
725     // Joystick support
726     if ( ! fgJoystickInit() ) {
727         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
728     }
729
730     // Autopilot init
731     current_autopilot = new FGAutopilot;
732     current_autopilot->init();
733
734     // initialize the gui parts of the autopilot
735     NewTgtAirportInit();
736     fgAPAdjustInit() ;
737     NewHeadingInit();
738     NewAltitudeInit();
739
740     // Initialize I/O channels
741 #if ! defined( macintosh )
742     fgIOInit();
743 #endif
744
745     // Initialize the 2D panel.
746     string panel_path = fgGetString("/sim/panel/path",
747                                     "Panels/Default/default.xml");
748     current_panel = fgReadPanel(panel_path);
749     if (current_panel == 0) {
750         FG_LOG( FG_INPUT, FG_ALERT, 
751                 "Error reading new panel from " << panel_path );
752     } else {
753         FG_LOG( FG_INPUT, FG_INFO, "Loaded new panel from " << panel_path );
754         current_panel->init();
755         current_panel->bind();
756     }
757
758     // Initialize the BFI
759     FGBFI::init();
760
761     controls.init();
762     controls.bind();
763
764     FG_LOG( FG_GENERAL, FG_INFO, endl);
765
766     return true;
767 }
768
769
770 void fgReInitSubsystems( void )
771 {
772     bool freeze = globals->get_freeze();
773     if( !freeze )
774         globals->set_freeze( true );
775     
776     if( global_tile_mgr.init() ) {
777         // Load the local scenery data
778         global_tile_mgr.update( fgGetDouble("/position/longitude"),
779                                 fgGetDouble("/position/latitude") );
780     } else {
781         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
782                 exit(-1);
783     }
784
785     // cout << "current scenery elev = " << scenery.cur_elev << endl;
786
787     fgInitPosition();
788     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"), 
789                              scenery.cur_elev );
790
791     // Reset our altitude if we are below ground
792     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
793             << cur_fdm_state->get_Altitude() );
794     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = "
795             << cur_fdm_state->get_Runway_altitude() );
796
797     if ( cur_fdm_state->get_Altitude() <
798          cur_fdm_state->get_Runway_altitude() + 3.758099)
799     {
800         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
801                                      3.758099 );
802     }
803     double sea_level_radius_meters;
804     double lat_geoc;
805     sgGeodToGeoc( cur_fdm_state->get_Latitude(), cur_fdm_state->get_Altitude(), 
806                   &sea_level_radius_meters, &lat_geoc);
807     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
808                                          METER_TO_FEET );
809         
810     // The following section sets up the flight model EOM parameters
811     // and should really be read in from one or more files.
812
813     // Initial Velocity
814     fgVelocityInit();
815
816     // Initial Orientation
817 //     cur_fdm_state->
818 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
819 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
820 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
821
822     // Initialize view parameters
823     FGViewerRPH *pilot_view =
824         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
825
826     pilot_view->set_view_offset( 0.0 );
827     pilot_view->set_goal_view_offset( 0.0 );
828
829     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
830                                    cur_fdm_state->get_Lat_geocentric(), 
831                                    cur_fdm_state->get_Altitude() *
832                                    FEET_TO_METER );
833     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
834                                       FEET_TO_METER ); 
835     pilot_view->set_rph( cur_fdm_state->get_Phi(),
836                          cur_fdm_state->get_Theta(),
837                          cur_fdm_state->get_Psi() );
838
839     // set current view to 0 (first) which is our main pilot view
840     globals->set_current_view( pilot_view );
841
842     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
843             << globals->get_current_view()->get_abs_view_pos());
844
845     cur_fdm_state->init();
846     cur_fdm_state->bind();
847 //     cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") );
848
849     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
850
851     if ( cur_fdm_state->get_Altitude() <
852          cur_fdm_state->get_Runway_altitude() + 3.758099)
853     {
854         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
855                                      3.758099 );
856     }
857
858     controls.reset_all();
859     current_autopilot->reset();
860
861     if( !freeze )
862         globals->set_freeze( false );
863 }