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