]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Integrated FGOptions with the property manager (by David Megginson)
[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 "globals.hxx"
96 #include "bfi.hxx"
97
98 #if defined(FX) && defined(XMESA)
99 #include <GL/xmesa.h>
100 #endif
101
102 FG_USING_STD(string);
103
104 extern const char *default_root;
105
106
107 // Read in configuration (file and command line) and just set fg_root
108 bool fgInitFGRoot ( int argc, char **argv ) {
109     // Attempt to locate and parse a config file
110     // First check fg_root
111     FGPath config( globals->get_options()->get_fg_root() );
112     config.append( "system.fgfsrc" );
113     globals->get_options()->scan_config_file_for_root( config.str() );
114
115     // Next check home directory
116     char* envp = ::getenv( "HOME" );
117     if ( envp != NULL ) {
118         config.set( envp );
119         config.append( ".fgfsrc" );
120         globals->get_options()->scan_config_file_for_root( config.str() );
121     }
122
123     // Parse remaining command line options
124     // These will override anything specified in a config file
125     globals->get_options()->scan_command_line_for_root(argc, argv);
126
127     return true;
128 }
129
130
131 // Read in configuration (file and command line)
132 bool fgInitConfig ( int argc, char **argv ) {
133
134                                 // First, set some sane default values
135     globals->get_options()->set_default_props();
136
137     // Read global preferences from $FG_ROOT/preferences.xml
138     FGPath props_path(globals->get_options()->get_fg_root());
139     props_path.append("preferences.xml");
140     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
141     if (!readProperties(props_path.str(), globals->get_props())) {
142       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
143              << props_path.str());
144     } else {
145       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
146     }
147
148     // Attempt to locate and parse a config file
149     // First check fg_root
150     FGPath config( globals->get_options()->get_fg_root() );
151     config.append( "system.fgfsrc" );
152     globals->get_options()->parse_config_file( config.str() );
153
154     // Next check home directory
155     char* envp = ::getenv( "HOME" );
156     if ( envp != NULL ) {
157         config.set( envp );
158         config.append( ".fgfsrc" );
159         globals->get_options()->parse_config_file( config.str() );
160     }
161
162     // Parse remaining command line options
163     // These will override anything specified in a config file
164     if ( globals->get_options()->parse_command_line(argc, argv) !=
165          FGOptions::FG_OPTIONS_OK )
166     {
167         // Something must have gone horribly wrong with the command
168         // line parsing or maybe the user just requested help ... :-)
169         globals->get_options()->usage();
170         FG_LOG( FG_GENERAL, FG_ALERT, "\nExiting ...");
171         return false;
172     }
173
174     return true;
175 }
176
177
178 // find basic airport location info from airport database
179 bool fgFindAirportID( const string& id, FGAirport *a ) {
180     if ( id.length() ) {
181         FGPath path( globals->get_options()->get_fg_root() );
182         path.append( "Airports" );
183         path.append( "simple.mk4" );
184         FGAirports airports( path.c_str() );
185
186         FG_LOG( FG_GENERAL, FG_INFO, "Searching for airport code = " << id );
187
188         if ( ! airports.search( id, a ) ) {
189             FG_LOG( FG_GENERAL, FG_ALERT,
190                     "Failed to find " << id << " in " << path.str() );
191             return false;
192         }
193     } else {
194         return false;
195     }
196
197     FG_LOG( FG_GENERAL, FG_INFO,
198             "Position for " << id << " is ("
199             << a->longitude << ", "
200             << a->latitude << ")" );
201
202     return true;
203 }
204
205
206 // Set current_options lon/lat given an airport id
207 bool fgSetPosFromAirportID( const string& id ) {
208     FGAirport a;
209     // double lon, lat;
210
211     FG_LOG( FG_GENERAL, FG_INFO,
212             "Attempting to set starting position from airport code " << id );
213
214     if ( fgFindAirportID( id, &a ) ) {
215         globals->get_options()->set_lon( a.longitude );
216         globals->get_options()->set_lat( a.latitude );
217         globals->get_props()->setDoubleValue("/position/longitude",
218                                           a.longitude);
219         globals->get_props()->setDoubleValue("/position/latitude",
220                                           a.latitude);
221
222         FG_LOG( FG_GENERAL, FG_INFO,
223                 "Position for " << id << " is ("
224                 << a.longitude << ", "
225                 << a.latitude << ")" );
226
227         return true;
228     } else {
229         return false;
230     }
231
232 }
233
234
235 // Set current_options lon/lat given an airport id and heading (degrees)
236 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
237     FGRunway r;
238     FGRunway found_r;
239     double found_dir = 0.0;
240
241     if ( id.length() ) {
242         // set initial position from runway and heading
243
244         FGPath path( globals->get_options()->get_fg_root() );
245         path.append( "Airports" );
246         path.append( "runways.mk4" );
247         FGRunways runways( path.c_str() );
248
249         FG_LOG( FG_GENERAL, FG_INFO,
250                 "Attempting to set starting position from runway code "
251                 << id << " heading " << tgt_hdg );
252
253         // FGPath inpath( globals->get_options()->get_fg_root() );
254         // inpath.append( "Airports" );
255         // inpath.append( "apt_simple" );
256         // airports.load( inpath.c_str() );
257
258         // FGPath outpath( globals->get_options()->get_fg_root() );
259         // outpath.append( "Airports" );
260         // outpath.append( "simple.gdbm" );
261         // airports.dump_gdbm( outpath.c_str() );
262
263         if ( ! runways.search( id, &r ) ) {
264             FG_LOG( FG_GENERAL, FG_ALERT,
265                     "Failed to find " << id << " in database." );
266             return false;
267         }
268
269         double diff;
270         double min_diff = 360.0;
271
272         while ( r.id == id ) {
273             // forward direction
274             diff = tgt_hdg - r.heading;
275             while ( diff < -180.0 ) { diff += 360.0; }
276             while ( diff >  180.0 ) { diff -= 360.0; }
277             diff = fabs(diff);
278             FG_LOG( FG_GENERAL, FG_INFO,
279                     "Runway " << r.rwy_no << " heading = " << r.heading <<
280                     " diff = " << diff );
281             if ( diff < min_diff ) {
282                 min_diff = diff;
283                 found_r = r;
284                 found_dir = 0;
285             }
286
287             // reverse direction
288             diff = tgt_hdg - r.heading - 180.0;
289             while ( diff < -180.0 ) { diff += 360.0; }
290             while ( diff >  180.0 ) { diff -= 360.0; }
291             diff = fabs(diff);
292             FG_LOG( FG_GENERAL, FG_INFO,
293                     "Runway -" << r.rwy_no << " heading = " <<
294                     r.heading + 180.0 <<
295                     " diff = " << diff );
296             if ( diff < min_diff ) {
297                 min_diff = diff;
298                 found_r = r;
299                 found_dir = 180.0;
300             }
301
302             runways.next( &r );
303         }
304
305         FG_LOG( FG_GENERAL, FG_INFO, "closest runway = " << found_r.rwy_no
306                 << " + " << found_dir );
307
308     } else {
309         return false;
310     }
311
312     double heading = found_r.heading + found_dir;
313     while ( heading >= 360.0 ) { heading -= 360.0; }
314
315     double lat2, lon2, az2;
316     double azimuth = found_r.heading + found_dir + 180.0;
317     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
318
319     FG_LOG( FG_GENERAL, FG_INFO,
320             "runway =  " << found_r.lon << ", " << found_r.lat
321             << " length = " << found_r.length * FEET_TO_METER * 0.5 
322             << " heading = " << azimuth );
323     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
324                         azimuth, found_r.length * FEET_TO_METER * 0.5 - 5.0,
325                         &lat2, &lon2, &az2 );
326     globals->get_options()->set_lon( lon2 );
327     globals->get_options()->set_lat( lat2 );
328     globals->get_options()->set_heading( heading );
329     globals->get_props()->setDoubleValue("/position/longitude", lon2);
330     globals->get_props()->setDoubleValue("/position/latitude", lat2);
331     globals->get_props()->setDoubleValue("/orientation/heading", heading);
332
333     FG_LOG( FG_GENERAL, FG_INFO,
334             "Position for " << id << " is ("
335             << lon2 << ", "
336             << lat2 << ") new heading is "
337             << heading );
338
339     return true;
340 }
341
342
343 // Set initial position and orientation
344 bool fgInitPosition( void ) {
345     FGInterface *f = current_aircraft.fdm_state;
346     string id = globals->get_options()->get_airport_id();
347
348     // set initial position from default or command line coordinates
349     f->set_Longitude( globals->get_options()->get_lon() * DEG_TO_RAD );
350     f->set_Latitude( globals->get_options()->get_lat() * DEG_TO_RAD );
351
352     if ( scenery.cur_elev > globals->get_options()->get_altitude() - 1) {
353         globals->get_options()->set_altitude( scenery.cur_elev + 1 );
354     }
355
356     FG_LOG( FG_GENERAL, FG_INFO,
357             "starting altitude is = " << globals->get_options()->get_altitude() );
358
359     f->set_Altitude( globals->get_options()->get_altitude() * METER_TO_FEET );
360     // fgFDMSetGroundElevation( globals->get_options()->get_flight_model(),
361     //                          f->get_Altitude() * FEET_TO_METER );
362
363 #if 0
364     globals->get_props()->setDoubleValue("/position/longitude",
365                                       f->get_Longitude() * RAD_TO_DEG);
366     globals->get_props()->setDoubleValue("/position/latitude",
367                                       f->get_Latitude() * RAD_TO_DEG);
368     globals->get_props()->setDoubleValue("/position/altitude",
369                                       f->get_Altitude() * RAD_TO_DEG);
370 #endif
371
372     FG_LOG( FG_GENERAL, FG_INFO,
373             "Initial position is: ("
374             << (f->get_Longitude() * RAD_TO_DEG) << ", "
375             << (f->get_Latitude() * RAD_TO_DEG) << ", "
376             << (f->get_Altitude() * FEET_TO_METER) << ")" );
377
378     return true;
379 }
380
381
382 // General house keeping initializations
383 bool fgInitGeneral( void ) {
384     string root;
385
386 #if defined(FX) && defined(XMESA)
387     char *mesa_win_state;
388 #endif
389
390     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
391     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
392
393     root = globals->get_options()->get_fg_root();
394     if ( ! root.length() ) {
395         // No root path set? Then bail ...
396         FG_LOG( FG_GENERAL, FG_ALERT,
397                 "Cannot continue without environment variable FG_ROOT"
398                 << "being defined." );
399         exit(-1);
400     }
401     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
402
403 #if defined(FX) && defined(XMESA)
404     // initialize full screen flag
405     global_fullscreen = false;
406     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
407         // Test for the MESA_GLX_FX env variable
408         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
409             // test if we are fullscreen mesa/glide
410             if ( (mesa_win_state[0] == 'f') ||
411                  (mesa_win_state[0] == 'F') ) {
412                 global_fullscreen = true;
413             }
414         }
415     }
416 #endif
417
418     return true;
419 }
420
421
422 // set initial aircraft speed
423 bool fgVelocityInit( void ) {
424   switch(globals->get_options()->get_speedset()) {
425     case FGOptions::FG_VC:
426       current_aircraft.fdm_state->set_V_calibrated_kts( 
427                                     globals->get_options()->get_vc() );
428       break;
429     case FGOptions::FG_MACH:
430       current_aircraft.fdm_state->set_Mach_number(
431                                     globals->get_options()->get_mach() );
432       break;
433     case FGOptions::FG_VTUVW:
434       current_aircraft.fdm_state->set_Velocities_Wind_Body(
435                                     globals->get_options()->get_uBody(),
436                                     globals->get_options()->get_vBody(),
437                                     globals->get_options()->get_wBody() );
438       break;
439     case FGOptions::FG_VTNED:
440       current_aircraft.fdm_state->set_Velocities_Local(
441                                     globals->get_options()->get_vNorth(),
442                                     globals->get_options()->get_vEast(),
443                                     globals->get_options()->get_vDown() );
444       break;
445     default:
446       current_aircraft.fdm_state->set_V_calibrated_kts( 0.0 );
447     }
448     return true;  
449 }             
450
451         
452 // This is the top level init routine which calls all the other
453 // initialization routines.  If you are adding a subsystem to flight
454 // gear, its initialization call should located in this routine.
455 // Returns non-zero if a problem encountered.
456 bool fgInitSubsystems( void ) {
457     fgLIGHT *l = &cur_light_params;
458
459     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
460     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
461
462     // Initialize the material property lib
463     FGPath mpath( globals->get_options()->get_fg_root() );
464     mpath.append( "materials" );
465     if ( material_lib.load( mpath.str() ) ) {
466     } else {
467         FG_LOG( FG_GENERAL, FG_ALERT, "Error loading material lib!" );
468         exit(-1);
469     }
470
471     // Initialize the Scenery Management subsystem
472     if ( fgSceneryInit() ) {
473         // Material lib initialized ok.
474     } else {
475         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
476         exit(-1);
477     }
478
479     if ( global_tile_mgr.init() ) {
480         // Load the local scenery data
481         global_tile_mgr.update( globals->get_options()->get_lon(),
482                                 globals->get_options()->get_lat() );
483     } else {
484         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
485         exit(-1);
486     }
487
488     FG_LOG( FG_GENERAL, FG_DEBUG,
489             "Current terrain elevation after tile mgr init " <<
490             scenery.cur_elev );
491
492     if ( globals->get_options()->get_flight_model() == FGInterface::FG_LARCSIM ) {
493         cur_fdm_state = new FGLaRCsim;
494     } else if ( globals->get_options()->get_flight_model() == FGInterface::FG_JSBSIM ) {
495         cur_fdm_state = new FGJSBsim;
496     } else if ( globals->get_options()->get_flight_model() == FGInterface::FG_ADA ) {
497         cur_fdm_state = new FGADA;
498     } else if ( globals->get_options()->get_flight_model() == 
499                 FGInterface::FG_BALLOONSIM ) {
500         cur_fdm_state = new FGBalloonSim;
501     } else if ( globals->get_options()->get_flight_model() == 
502                 FGInterface::FG_MAGICCARPET ) {
503         cur_fdm_state = new FGMagicCarpet;
504     } else if ( globals->get_options()->get_flight_model() == 
505                 FGInterface::FG_EXTERNAL ) {
506         cur_fdm_state = new FGExternal;
507     } else {
508         FG_LOG( FG_GENERAL, FG_ALERT,
509                 "No flight model, 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( globals->get_options()->get_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( globals->get_options()->get_roll() * DEG_TO_RAD,
570                           globals->get_options()->get_pitch() * DEG_TO_RAD,
571                           globals->get_options()->get_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( globals->get_options()->get_xsize() /
586                            globals->get_options()->get_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_options()->get_fg_root() );
642     // cout << theFGLocalWeatherDatabase << endl;
643     // cout << "visibility = " 
644     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
645
646     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
647     
648     double init_vis = globals->get_options()->get_default_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_options()->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_options()->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_options()->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     if ( cur_fdm_state->init( 1.0 / globals->get_options()->get_model_hz() ) ) {
698         // fdm init successful
699     } else {
700         FG_LOG( FG_GENERAL, FG_ALERT, "FDM init() failed!  Cannot continue." );
701         exit(-1);
702     }
703
704     // *ABCD* I'm just sticking this here for now, it should probably
705     // move eventually
706     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
707
708     if ( cur_fdm_state->get_Altitude() <
709          cur_fdm_state->get_Runway_altitude() + 3.758099)
710     {
711         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
712                                      3.758099 );
713     }
714
715     FG_LOG( FG_GENERAL, FG_INFO,
716             "Updated position (after elevation adj): ("
717             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
718             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
719             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
720     // *ABCD* end of thing that I just stuck in that I should probably
721     // move
722
723     // Joystick support
724     if ( ! fgJoystickInit() ) {
725         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
726     }
727
728     // Autopilot init
729     current_autopilot = new FGAutopilot;
730     current_autopilot->init();
731
732     // initialize the gui parts of the autopilot
733     NewTgtAirportInit();
734     fgAPAdjustInit() ;
735     NewHeadingInit();
736     NewAltitudeInit();
737
738     // Initialize I/O channels
739 #if ! defined( macintosh )
740     fgIOInit();
741 #endif
742
743     // Initialize the 2D panel.
744     string panel_path =
745         globals->get_props()->getStringValue("/sim/panel/path",
746                                             "Panels/Default/default.xml");
747     current_panel = fgReadPanel(panel_path);
748     if (current_panel == 0) {
749         FG_LOG( FG_INPUT, FG_ALERT, 
750                 "Error reading new panel from " << panel_path );
751     } else {
752         FG_LOG( FG_INPUT, FG_INFO, "Loaded new panel from " << panel_path );
753         current_panel->init();
754         current_panel->bind();
755     }
756
757     // Initialize the BFI
758     FGBFI::init();
759
760     controls.init();
761     controls.bind();
762
763     FG_LOG( FG_GENERAL, FG_INFO, endl);
764
765     return true;
766 }
767
768
769 void fgReInitSubsystems( void )
770 {
771     bool freeze = globals->get_freeze();
772     if( !freeze )
773         globals->set_freeze( true );
774     
775     if( global_tile_mgr.init() ) {
776         // Load the local scenery data
777         global_tile_mgr.update( globals->get_options()->get_lon(),
778                                 globals->get_options()->get_lat() );
779     } else {
780         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
781                 exit(-1);
782     }
783
784     // cout << "current scenery elev = " << scenery.cur_elev << endl;
785
786     fgInitPosition();
787     fgFDMSetGroundElevation( globals->get_options()->get_flight_model(), 
788                              scenery.cur_elev );
789
790     // Reset our altitude if we are below ground
791     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
792             << cur_fdm_state->get_Altitude() );
793     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = "
794             << cur_fdm_state->get_Runway_altitude() );
795
796     if ( cur_fdm_state->get_Altitude() <
797          cur_fdm_state->get_Runway_altitude() + 3.758099)
798     {
799         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
800                                      3.758099 );
801     }
802     double sea_level_radius_meters;
803     double lat_geoc;
804     sgGeodToGeoc( cur_fdm_state->get_Latitude(), cur_fdm_state->get_Altitude(), 
805                   &sea_level_radius_meters, &lat_geoc);
806     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
807                                          METER_TO_FEET );
808         
809     // The following section sets up the flight model EOM parameters
810     // and should really be read in from one or more files.
811
812     // Initial Velocity
813     fgVelocityInit();
814
815     // Initial Orientation
816     cur_fdm_state->
817         set_Euler_Angles( globals->get_options()->get_roll() * DEG_TO_RAD,
818                           globals->get_options()->get_pitch() * DEG_TO_RAD,
819                           globals->get_options()->get_heading() * DEG_TO_RAD );
820
821     // Initialize view parameters
822     FGViewerRPH *pilot_view =
823         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
824
825     pilot_view->set_view_offset( 0.0 );
826     pilot_view->set_goal_view_offset( 0.0 );
827
828     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
829                                    cur_fdm_state->get_Lat_geocentric(), 
830                                    cur_fdm_state->get_Altitude() *
831                                    FEET_TO_METER );
832     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
833                                       FEET_TO_METER ); 
834     pilot_view->set_rph( cur_fdm_state->get_Phi(),
835                          cur_fdm_state->get_Theta(),
836                          cur_fdm_state->get_Psi() );
837
838     // set current view to 0 (first) which is our main pilot view
839     globals->set_current_view( pilot_view );
840
841     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
842             << globals->get_current_view()->get_abs_view_pos());
843
844     cur_fdm_state->init( 1.0 / globals->get_options()->get_model_hz() );
845
846     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
847
848     if ( cur_fdm_state->get_Altitude() <
849          cur_fdm_state->get_Runway_altitude() + 3.758099)
850     {
851         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
852                                      3.758099 );
853     }
854
855     controls.reset_all();
856     current_autopilot->reset();
857
858     if( !freeze )
859         globals->set_freeze( false );
860 }