]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
d7a384760461cc2b9b754f8b93efddc3ae36dc73
[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     
334     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
335                         azimuth, found_r.length * FEET_TO_METER * 0.5 - 5.0,
336                         &lat2, &lon2, &az2 );
337
338     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > FG_EPSILON ) {
339         double olat, olon;
340         double odist = fgGetDouble("/sim/startup/offset-distance");
341         odist *= NM_TO_METER;
342         double oaz = azimuth;
343         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > FG_EPSILON ) {
344             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
345         }
346         while ( oaz >= 360.0 ) { oaz -= 360.0; }
347         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
348         lat2=olat;
349         lon2=olon;
350     }
351     fgSetDouble("/position/longitude",  lon2 );
352     fgSetDouble("/position/latitude",  lat2 );
353     fgSetDouble("/orientation/heading", heading );
354
355     FG_LOG( FG_GENERAL, FG_INFO,
356             "Position for " << id << " is ("
357             << lon2 << ", "
358             << lat2 << ") new heading is "
359             << heading );
360
361     return true;
362 }
363
364
365 // Set initial position and orientation
366 bool fgInitPosition( void ) {
367     FGInterface *f = current_aircraft.fdm_state;
368     string id = fgGetString("/sim/startup/airport-id");
369
370     // set initial position from default or command line coordinates
371     f->set_Longitude( fgGetDouble("/position/longitude") * DEG_TO_RAD );
372     f->set_Latitude( fgGetDouble("/position/latitude") * DEG_TO_RAD );
373
374     FG_LOG( FG_GENERAL, FG_INFO,
375             "scenery.cur_elev = " << scenery.cur_elev );
376     FG_LOG( FG_GENERAL, FG_INFO,
377             "/position/altitude = " << fgGetDouble("/position/altitude") );
378
379     // if we requested on ground startups
380     if ( fgGetBool( "/sim/startup/onground" ) ) {
381         fgSetDouble("/position/altitude", scenery.cur_elev + 1 );
382     }
383
384     // if requested altitude is below ground level
385     if ( scenery.cur_elev > fgGetDouble("/position/altitude") - 1) {
386         fgSetDouble("/position/altitude", scenery.cur_elev + 1 );
387     }
388
389     FG_LOG( FG_GENERAL, FG_INFO,
390             "starting altitude is = " <<
391             fgGetDouble("/position/altitude") );
392
393     f->set_Altitude( fgGetDouble("/position/altitude") );
394     FG_LOG( FG_GENERAL, FG_INFO,
395             "Initial position is: ("
396             << (f->get_Longitude() * RAD_TO_DEG) << ", "
397             << (f->get_Latitude() * RAD_TO_DEG) << ", "
398             << (f->get_Altitude() * FEET_TO_METER) << ")" );
399
400     return true;
401 }
402
403
404 // General house keeping initializations
405 bool fgInitGeneral( void ) {
406     string root;
407
408 #if defined(FX) && defined(XMESA)
409     char *mesa_win_state;
410 #endif
411
412     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
413     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
414
415     root = globals->get_fg_root();
416     if ( ! root.length() ) {
417         // No root path set? Then bail ...
418         FG_LOG( FG_GENERAL, FG_ALERT,
419                 "Cannot continue without environment variable FG_ROOT"
420                 << "being defined." );
421         exit(-1);
422     }
423     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
424
425 #if defined(FX) && defined(XMESA)
426     // initialize full screen flag
427     global_fullscreen = false;
428     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
429         // Test for the MESA_GLX_FX env variable
430         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
431             // test if we are fullscreen mesa/glide
432             if ( (mesa_win_state[0] == 'f') ||
433                  (mesa_win_state[0] == 'F') ) {
434                 global_fullscreen = true;
435             }
436         }
437     }
438 #endif
439
440     return true;
441 }
442
443
444 // set initial aircraft speed
445 void
446 fgVelocityInit( void ) 
447 {
448   if (!fgHasValue("/sim/startup/speed-set")) {
449     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
450     return;
451   }
452
453   const string speedset = fgGetString("/sim/startup/speed-set");
454   if (speedset == "knots" || speedset == "KNOTS") {
455     current_aircraft.fdm_state
456       ->set_V_calibrated_kts(fgGetDouble("/velocities/airspeed"));
457   } else if (speedset == "mach" || speedset == "MACH") {
458     current_aircraft.fdm_state
459       ->set_Mach_number(fgGetDouble("/velocities/mach"));
460   } else if (speedset == "UVW" || speedset == "uvw") {
461     current_aircraft.fdm_state
462       ->set_Velocities_Wind_Body(fgGetDouble("/velocities/uBody"),
463                                  fgGetDouble("/velocities/vBody"),
464                                  fgGetDouble("/velocities/wBody"));
465   } else if (speedset == "NED" || speedset == "ned") {
466     current_aircraft.fdm_state
467       ->set_Velocities_Local(fgGetDouble("/velocities/speed-north"),
468                              fgGetDouble("/velocities/speed-east"),
469                              fgGetDouble("/velocities/speed-down"));
470   } else {
471     FG_LOG(FG_GENERAL, FG_ALERT,
472            "Unrecognized value for /sim/startup/speed-set: " << speedset);
473     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
474   }
475 }             
476
477         
478 // This is the top level init routine which calls all the other
479 // initialization routines.  If you are adding a subsystem to flight
480 // gear, its initialization call should located in this routine.
481 // Returns non-zero if a problem encountered.
482 bool fgInitSubsystems( void ) {
483     fgLIGHT *l = &cur_light_params;
484
485     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
486     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
487
488     // Initialize the material property lib
489     FGPath mpath( globals->get_fg_root() );
490     mpath.append( "materials" );
491     if ( material_lib.load( mpath.str() ) ) {
492     } else {
493         FG_LOG( FG_GENERAL, FG_ALERT, "Error loading material lib!" );
494         exit(-1);
495     }
496
497     // Initialize the Scenery Management subsystem
498     if ( fgSceneryInit() ) {
499         // Material lib initialized ok.
500     } else {
501         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
502         exit(-1);
503     }
504
505     if ( global_tile_mgr.init() ) {
506         // Load the local scenery data
507         global_tile_mgr.update( fgGetDouble("/position/longitude"),
508                                 fgGetDouble("/position/latitude") );
509     } else {
510         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
511         exit(-1);
512     }
513
514     FG_LOG( FG_GENERAL, FG_DEBUG,
515             "Current terrain elevation after tile mgr init " <<
516             scenery.cur_elev );
517
518     double dt = 1.0 / fgGetInt("/sim/model-hz");
519     // cout << "dt = " << dt << endl;
520
521     const string &model = fgGetString("/sim/flight-model");
522     if (model == "larcsim") {
523         cur_fdm_state = new FGLaRCsim( dt );
524     } else if (model == "jsb") {
525         cur_fdm_state = new FGJSBsim( dt );
526     } else if (model == "ada") {
527         cur_fdm_state = new FGADA( dt );
528     } else if (model == "balloon") {
529         cur_fdm_state = new FGBalloonSim( dt );
530     } else if (model == "magic") {
531         cur_fdm_state = new FGMagicCarpet( dt );
532     } else if (model == "external") {
533         cur_fdm_state = new FGExternal( dt );
534     } else {
535         FG_LOG(FG_GENERAL, FG_ALERT,
536                "Unrecognized flight model '" << model
537                << ", can't init aircraft");
538         exit(-1);
539     }
540     cur_fdm_state->stamp();
541     cur_fdm_state->set_remainder( 0 );
542
543     // allocates structures so must happen before any of the flight
544     // model or control parameters are set
545     fgAircraftInit();   // In the future this might not be the case.
546
547     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"),
548                              scenery.cur_elev );
549     
550     // set the initial position
551     fgInitPosition();
552
553     // Calculate ground elevation at starting point (we didn't have
554     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
555     //
556     // calculalate a cartesian point somewhere along the line between
557     // the center of the earth and our view position.  Doesn't have to
558     // be the exact elevation (this is good because we don't know it
559     // yet :-)
560
561     // now handled inside of the fgTileMgrUpdate()
562
563     // Reset our altitude if we are below ground
564     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
565             << cur_fdm_state->get_Altitude() );
566     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
567             cur_fdm_state->get_Runway_altitude() );
568
569     if ( cur_fdm_state->get_Altitude() < cur_fdm_state->get_Runway_altitude() +
570          3.758099) {
571         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
572                                      3.758099 );
573     }
574
575     FG_LOG( FG_GENERAL, FG_INFO,
576             "Updated position (after elevation adj): ("
577             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
578             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
579             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
580
581     // We need to calculate a few sea_level_radius here so we can pass
582     // the correct value to the view class
583     double sea_level_radius_meters;
584     double lat_geoc;
585     sgGeodToGeoc( cur_fdm_state->get_Latitude(),
586                   cur_fdm_state->get_Altitude(),
587                   &sea_level_radius_meters, &lat_geoc);
588     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
589                                          METER_TO_FEET );
590
591     // The following section sets up the flight model EOM parameters
592     // and should really be read in from one or more files.
593
594     // Initial Velocity
595     fgVelocityInit();
596
597     // Initial Orientation
598 //     cur_fdm_state->
599 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
600 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
601 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
602
603     // Initialize the event manager
604     global_events.Init();
605
606     // Output event stats every 60 seconds
607     global_events.Register( "fgEVENT_MGR::PrintStats()",
608                             fgMethodCallback<fgEVENT_MGR>( &global_events,
609                                                    &fgEVENT_MGR::PrintStats),
610                             fgEVENT::FG_EVENT_READY, 60000 );
611
612     // Initialize win_ratio parameters
613     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
614         globals->get_viewmgr()->get_view(i)->
615             set_win_ratio( fgGetInt("/sim/startup/xsize") /
616                            fgGetInt("/sim/startup/ysize") );
617     }
618
619     // Initialize pilot view
620     FGViewerRPH *pilot_view =
621         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
622
623     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
624                                    cur_fdm_state->get_Lat_geocentric(), 
625                                    cur_fdm_state->get_Altitude() *
626                                    FEET_TO_METER );
627     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
628                                       FEET_TO_METER ); 
629     pilot_view->set_rph( cur_fdm_state->get_Phi(),
630                          cur_fdm_state->get_Theta(),
631                          cur_fdm_state->get_Psi() );
632
633     // set current view to 0 (first) which is our main pilot view
634     globals->set_current_view( pilot_view );
635
636     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
637             << globals->get_current_view()->get_abs_view_pos());
638
639     // fgUpdateSunPos() needs a few position and view parameters set
640     // so it can calculate local relative sun angle and a few other
641     // things for correctly orienting the sky.
642     fgUpdateSunPos();
643     fgUpdateMoonPos();
644     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
645                             fgEVENT::FG_EVENT_READY, 60000);
646     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
647                             fgEVENT::FG_EVENT_READY, 60000);
648
649     // Initialize Lighting interpolation tables
650     l->Init();
651
652     // update the lighting parameters (based on sun angle)
653     global_events.Register( "fgLight::Update()",
654                             fgMethodCallback<fgLIGHT>( &cur_light_params,
655                                                        &fgLIGHT::Update),
656                             fgEVENT::FG_EVENT_READY, 30000 );
657     // update the current timezone each 30 minutes
658     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
659                             fgEVENT::FG_EVENT_READY, 1800000);
660
661     // Initialize the weather modeling subsystem
662 #ifndef FG_OLD_WEATHER
663     // Initialize the WeatherDatabase
664     FG_LOG(FG_GENERAL, FG_INFO, "Creating LocalWeatherDatabase");
665     sgVec3 position;
666     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
667                current_aircraft.fdm_state->get_Longitude(),
668                current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER );
669     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
670         new FGLocalWeatherDatabase( position,
671                                     globals->get_fg_root() );
672     // cout << theFGLocalWeatherDatabase << endl;
673     // cout << "visibility = " 
674     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
675
676     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
677     
678     double init_vis = fgGetDouble("/environment/visibility");
679     if ( init_vis > 0 ) {
680         WeatherDatabase->setWeatherVisibility( init_vis );
681     }
682
683     // register the periodic update of the weather
684     global_events.Register( "weather update", fgUpdateWeatherDatabase,
685                             fgEVENT::FG_EVENT_READY, 30000);
686 #else
687     current_weather.Init();
688 #endif
689
690     // Initialize vor/ndb/ils/fix list management and query systems
691     FG_LOG(FG_GENERAL, FG_INFO, "Loading Navaids");
692
693     FG_LOG(FG_GENERAL, FG_INFO, "  VOR/NDB");
694     current_navlist = new FGNavList;
695     FGPath p_nav( globals->get_fg_root() );
696     p_nav.append( "Navaids/default.nav" );
697     current_navlist->init( p_nav );
698
699     FG_LOG(FG_GENERAL, FG_INFO, "  ILS");
700     current_ilslist = new FGILSList;
701     FGPath p_ils( globals->get_fg_root() );
702     p_ils.append( "Navaids/default.ils" );
703     current_ilslist->init( p_ils );
704
705     FG_LOG(FG_GENERAL, FG_INFO, "  Fixes");
706     current_fixlist = new FGFixList;
707     FGPath p_fix( globals->get_fg_root() );
708     p_fix.append( "Navaids/default.fix" );
709     current_fixlist->init( p_fix );
710
711     // Radio stack subsystem.
712     current_radiostack = new FGRadioStack;
713     current_radiostack->init();
714     current_radiostack->bind();
715
716     // Initialize the Cockpit subsystem
717     if( fgCockpitInit( &current_aircraft )) {
718         // Cockpit initialized ok.
719     } else {
720         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
721         exit(-1);
722     }
723
724     // Initialize the flight model subsystem data structures base on
725     // above values
726
727     cur_fdm_state->init();
728     cur_fdm_state->bind();
729 //     if ( cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") ) ) {
730 //      // fdm init successful
731 //     } else {
732 //      FG_LOG( FG_GENERAL, FG_ALERT, "FDM init() failed!  Cannot continue." );
733 //      exit(-1);
734 //     }
735
736     // *ABCD* I'm just sticking this here for now, it should probably
737     // move eventually
738     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
739
740     if ( cur_fdm_state->get_Altitude() <
741          cur_fdm_state->get_Runway_altitude() + 3.758099)
742     {
743         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
744                                      3.758099 );
745     }
746
747     FG_LOG( FG_GENERAL, FG_INFO,
748             "Updated position (after elevation adj): ("
749             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
750             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
751             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
752     // *ABCD* end of thing that I just stuck in that I should probably
753     // move
754
755     // Joystick support
756     if ( ! fgJoystickInit() ) {
757         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
758     }
759
760     // Autopilot init
761     current_autopilot = new FGAutopilot;
762     current_autopilot->init();
763
764     // initialize the gui parts of the autopilot
765     NewTgtAirportInit();
766     fgAPAdjustInit() ;
767     NewHeadingInit();
768     NewAltitudeInit();
769
770     // Initialize I/O channels
771 #if ! defined( macintosh )
772     fgIOInit();
773 #endif
774
775     // Initialize the 2D panel.
776     string panel_path = fgGetString("/sim/panel/path",
777                                     "Panels/Default/default.xml");
778     current_panel = fgReadPanel(panel_path);
779     if (current_panel == 0) {
780         FG_LOG( FG_INPUT, FG_ALERT, 
781                 "Error reading new panel from " << panel_path );
782     } else {
783         FG_LOG( FG_INPUT, FG_INFO, "Loaded new panel from " << panel_path );
784         current_panel->init();
785         current_panel->bind();
786     }
787
788     // Initialize the BFI
789     FGBFI::init();
790
791     controls.init();
792     controls.bind();
793
794     FG_LOG( FG_GENERAL, FG_INFO, endl);
795
796                                 // Save the initial state for future
797                                 // reference.
798     globals->saveInitialState();
799
800     return true;
801 }
802
803
804 void fgReInitSubsystems( void )
805 {
806     FG_LOG( FG_GENERAL, FG_INFO,
807             "/position/altitude = " << fgGetDouble("/position/altitude") );
808
809     bool freeze = globals->get_freeze();
810     if( !freeze )
811         globals->set_freeze( true );
812     
813     // Initialize the Scenery Management subsystem
814     if ( ! fgSceneryInit() ) {
815         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
816         exit(-1);
817     }
818
819     if( global_tile_mgr.init() ) {
820         // Load the local scenery data
821         global_tile_mgr.update( fgGetDouble("/position/longitude"),
822                                 fgGetDouble("/position/latitude") );
823     } else {
824         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
825                 exit(-1);
826     }
827
828     // cout << "current scenery elev = " << scenery.cur_elev << endl;
829
830     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"), 
831                              scenery.cur_elev );
832     fgInitPosition();
833
834     // Reset our altitude if we are below ground
835     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
836             << cur_fdm_state->get_Altitude() );
837     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = "
838             << cur_fdm_state->get_Runway_altitude() );
839
840     if ( cur_fdm_state->get_Altitude() <
841          cur_fdm_state->get_Runway_altitude() + 3.758099)
842     {
843         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
844                                      3.758099 );
845     }
846     double sea_level_radius_meters;
847     double lat_geoc;
848     sgGeodToGeoc( cur_fdm_state->get_Latitude(), cur_fdm_state->get_Altitude(), 
849                   &sea_level_radius_meters, &lat_geoc);
850     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
851                                          METER_TO_FEET );
852         
853     // The following section sets up the flight model EOM parameters
854     // and should really be read in from one or more files.
855
856     // Initial Velocity
857     fgVelocityInit();
858
859     // Initial Orientation
860 //     cur_fdm_state->
861 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
862 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
863 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
864
865     // Initialize view parameters
866     FGViewerRPH *pilot_view =
867         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
868
869     pilot_view->set_view_offset( 0.0 );
870     pilot_view->set_goal_view_offset( 0.0 );
871
872     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
873                                    cur_fdm_state->get_Lat_geocentric(), 
874                                    cur_fdm_state->get_Altitude() *
875                                    FEET_TO_METER );
876     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
877                                       FEET_TO_METER ); 
878     pilot_view->set_rph( cur_fdm_state->get_Phi(),
879                          cur_fdm_state->get_Theta(),
880                          cur_fdm_state->get_Psi() );
881
882     // set current view to 0 (first) which is our main pilot view
883     globals->set_current_view( pilot_view );
884
885     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
886             << globals->get_current_view()->get_abs_view_pos());
887
888     cur_fdm_state->init();
889 //     cur_fdm_state->bind();
890 //     cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") );
891
892     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
893
894     if ( cur_fdm_state->get_Altitude() <
895          cur_fdm_state->get_Runway_altitude() + 3.758099)
896     {
897         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
898                                      3.758099 );
899     }
900
901     controls.reset_all();
902     current_autopilot->reset();
903
904     if( !freeze )
905         globals->set_freeze( false );
906 }