]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
801ce3be41b6b5d7bdc3e090f70f2ed343d5aa2c
[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/sg_path.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             SGPath 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             SGPath 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( __CYGWIN__ )
162         root = "/FlightGear";
163 #elif defined( WIN32 )
164         root = "\\FlightGear";
165 #elif defined( macintosh )
166         root = "";
167 #else
168         root = PKGLIBDIR;
169 #endif
170     }
171
172     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
173     globals->set_fg_root(root);
174
175     return true;
176 }
177
178
179 // Read in configuration (file and command line)
180 bool fgInitConfig ( int argc, char **argv ) {
181
182                                 // First, set some sane default values
183     fgSetDefaults();
184
185     // Read global preferences from $FG_ROOT/preferences.xml
186     SGPath props_path(globals->get_fg_root());
187     props_path.append("preferences.xml");
188     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
189     if (!readProperties(props_path.str(), globals->get_props())) {
190       SG_LOG(SG_INPUT, SG_ALERT, "Failed to read global preferences from "
191              << props_path.str());
192     } else {
193       SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
194     }
195
196     // Attempt to locate and parse the various config files in order
197     // from least precidence to greatest precidence
198
199     // Check for $fg_root/system.fgfsrc
200     SGPath config( globals->get_fg_root() );
201     config.append( "system.fgfsrc" );
202     fgParseOptions(config.str());
203
204     char name[256];
205 #if defined( unix ) || defined( __CYGWIN__ )
206     // Check for $fg_root/system.fgfsrc.hostname
207     gethostname( name, 256 );
208     config.concat( "." );
209     config.concat( name );
210     fgParseOptions(config.str());
211 #endif
212
213     // Check for ~/.fgfsrc
214     char* envp = ::getenv( "HOME" );
215     if ( envp != NULL ) {
216         config.set( envp );
217         config.append( ".fgfsrc" );
218         fgParseOptions(config.str());
219     }
220
221 #if defined( unix ) || defined( __CYGWIN__ )
222     // Check for ~/.fgfsrc.hostname
223     gethostname( name, 256 );
224     config.concat( "." );
225     config.concat( name );
226     fgParseOptions(config.str());
227 #endif
228
229     // Parse remaining command line options
230     // These will override anything specified in a config file
231     fgParseOptions(argc, argv);
232
233     return true;
234 }
235
236
237 // find basic airport location info from airport database
238 bool fgFindAirportID( const string& id, FGAirport *a ) {
239     if ( id.length() ) {
240         SGPath path( globals->get_fg_root() );
241         path.append( "Airports" );
242         path.append( "simple.mk4" );
243         FGAirports airports( path.c_str() );
244
245         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
246
247         if ( ! airports.search( id, a ) ) {
248             SG_LOG( SG_GENERAL, SG_ALERT,
249                     "Failed to find " << id << " in " << path.str() );
250             return false;
251         }
252     } else {
253         return false;
254     }
255
256     SG_LOG( SG_GENERAL, SG_INFO,
257             "Position for " << id << " is ("
258             << a->longitude << ", "
259             << a->latitude << ")" );
260
261     return true;
262 }
263
264
265 // Set current_options lon/lat given an airport id
266 bool fgSetPosFromAirportID( const string& id ) {
267     FGAirport a;
268     // double lon, lat;
269
270     SG_LOG( SG_GENERAL, SG_INFO,
271             "Attempting to set starting position from airport code " << id );
272
273     if ( fgFindAirportID( id, &a ) ) {
274         fgSetDouble("/position/longitude",  a.longitude );
275         fgSetDouble("/position/latitude",  a.latitude );
276         SG_LOG( SG_GENERAL, SG_INFO,
277                 "Position for " << id << " is ("
278                 << a.longitude << ", "
279                 << a.latitude << ")" );
280
281         return true;
282     } else {
283         return false;
284     }
285
286 }
287
288
289 // Set current_options lon/lat given an airport id and heading (degrees)
290 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
291     FGRunway r;
292     FGRunway found_r;
293     double found_dir = 0.0;
294
295     if ( id.length() ) {
296         // set initial position from runway and heading
297
298         SGPath path( globals->get_fg_root() );
299         path.append( "Airports" );
300         path.append( "runways.mk4" );
301         FGRunways runways( path.c_str() );
302
303         SG_LOG( SG_GENERAL, SG_INFO,
304                 "Attempting to set starting position from runway code "
305                 << id << " heading " << tgt_hdg );
306
307         // SGPath inpath( globals->get_fg_root() );
308         // inpath.append( "Airports" );
309         // inpath.append( "apt_simple" );
310         // airports.load( inpath.c_str() );
311
312         // SGPath outpath( globals->get_fg_root() );
313         // outpath.append( "Airports" );
314         // outpath.append( "simple.gdbm" );
315         // airports.dump_gdbm( outpath.c_str() );
316
317         if ( ! runways.search( id, &r ) ) {
318             SG_LOG( SG_GENERAL, SG_ALERT,
319                     "Failed to find " << id << " in database." );
320             return false;
321         }
322
323         double diff;
324         double min_diff = 360.0;
325
326         while ( r.id == id ) {
327             // forward direction
328             diff = tgt_hdg - r.heading;
329             while ( diff < -180.0 ) { diff += 360.0; }
330             while ( diff >  180.0 ) { diff -= 360.0; }
331             diff = fabs(diff);
332             SG_LOG( SG_GENERAL, SG_INFO,
333                     "Runway " << r.rwy_no << " heading = " << r.heading <<
334                     " diff = " << diff );
335             if ( diff < min_diff ) {
336                 min_diff = diff;
337                 found_r = r;
338                 found_dir = 0;
339             }
340
341             // reverse direction
342             diff = tgt_hdg - r.heading - 180.0;
343             while ( diff < -180.0 ) { diff += 360.0; }
344             while ( diff >  180.0 ) { diff -= 360.0; }
345             diff = fabs(diff);
346             SG_LOG( SG_GENERAL, SG_INFO,
347                     "Runway -" << r.rwy_no << " heading = " <<
348                     r.heading + 180.0 <<
349                     " diff = " << diff );
350             if ( diff < min_diff ) {
351                 min_diff = diff;
352                 found_r = r;
353                 found_dir = 180.0;
354             }
355
356             runways.next( &r );
357         }
358
359         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
360                 << " + " << found_dir );
361
362     } else {
363         return false;
364     }
365
366     double heading = found_r.heading + found_dir;
367     while ( heading >= 360.0 ) { heading -= 360.0; }
368
369     double lat2, lon2, az2;
370     double azimuth = found_r.heading + found_dir + 180.0;
371     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
372
373     SG_LOG( SG_GENERAL, SG_INFO,
374             "runway =  " << found_r.lon << ", " << found_r.lat
375             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
376             << " heading = " << azimuth );
377     
378     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
379                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
380                         &lat2, &lon2, &az2 );
381
382     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > SG_EPSILON ) {
383         double olat, olon;
384         double odist = fgGetDouble("/sim/startup/offset-distance");
385         odist *= SG_NM_TO_METER;
386         double oaz = azimuth;
387         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > SG_EPSILON ) {
388             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
389         }
390         while ( oaz >= 360.0 ) { oaz -= 360.0; }
391         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
392         lat2=olat;
393         lon2=olon;
394     }
395     fgSetDouble("/position/longitude",  lon2 );
396     fgSetDouble("/position/latitude",  lat2 );
397     fgSetDouble("/orientation/heading", heading );
398
399     SG_LOG( SG_GENERAL, SG_INFO,
400             "Position for " << id << " is ("
401             << lon2 << ", "
402             << lat2 << ") new heading is "
403             << heading );
404
405     return true;
406 }
407
408
409 // General house keeping initializations
410 bool fgInitGeneral( void ) {
411     string root;
412
413 #if defined(FX) && defined(XMESA)
414     char *mesa_win_state;
415 #endif
416
417     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
418     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
419
420     root = globals->get_fg_root();
421     if ( ! root.length() ) {
422         // No root path set? Then bail ...
423         SG_LOG( SG_GENERAL, SG_ALERT,
424                 "Cannot continue without environment variable FG_ROOT"
425                 << "being defined." );
426         exit(-1);
427     }
428     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
429
430 #if defined(FX) && defined(XMESA)
431     // initialize full screen flag
432     global_fullscreen = false;
433     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
434         // Test for the MESA_GLX_FX env variable
435         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
436             // test if we are fullscreen mesa/glide
437             if ( (mesa_win_state[0] == 'f') ||
438                  (mesa_win_state[0] == 'F') ) {
439                 global_fullscreen = true;
440             }
441         }
442     }
443 #endif
444
445     return true;
446 }
447
448
449 // This is the top level init routine which calls all the other
450 // initialization routines.  If you are adding a subsystem to flight
451 // gear, its initialization call should located in this routine.
452 // Returns non-zero if a problem encountered.
453 bool fgInitSubsystems( void ) {
454     fgLIGHT *l = &cur_light_params;
455
456     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
457     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
458
459
460     ////////////////////////////////////////////////////////////////////
461     // Initialize the material property subsystem.
462     ////////////////////////////////////////////////////////////////////
463
464     SGPath mpath( globals->get_fg_root() );
465     mpath.append( "materials" );
466     if ( material_lib.load( mpath.str() ) ) {
467     } else {
468         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
469         exit(-1);
470     }
471
472
473     ////////////////////////////////////////////////////////////////////
474     // Initialize the scenery management subsystem.
475     ////////////////////////////////////////////////////////////////////
476
477     if ( fgSceneryInit() ) {
478         // Material lib initialized ok.
479     } else {
480         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Scenery initialization!" );
481         exit(-1);
482     }
483
484     if ( global_tile_mgr.init() ) {
485         // Load the local scenery data
486         global_tile_mgr.update( fgGetDouble("/position/longitude"),
487                                 fgGetDouble("/position/latitude") );
488     } else {
489         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
490         exit(-1);
491     }
492
493     SG_LOG( SG_GENERAL, SG_DEBUG,
494             "Current terrain elevation after tile mgr init " <<
495             scenery.cur_elev );
496
497
498     ////////////////////////////////////////////////////////////////////
499     // Initialize the flight model subsystem.
500     ////////////////////////////////////////////////////////////////////
501
502     double dt = 1.0 / fgGetInt("/sim/model-hz");
503     // cout << "dt = " << dt << endl;
504
505     aircraft_dir = fgGetString("/sim/aircraft-dir");
506     const string &model = fgGetString("/sim/flight-model");
507     if (model == "larcsim") {
508         cur_fdm_state = new FGLaRCsim( dt );
509     } else if (model == "jsb") {
510         cur_fdm_state = new FGJSBsim( dt );
511     } else if (model == "ada") {
512         cur_fdm_state = new FGADA( dt );
513     } else if (model == "balloon") {
514         cur_fdm_state = new FGBalloonSim( dt );
515     } else if (model == "magic") {
516         cur_fdm_state = new FGMagicCarpet( dt );
517     } else if (model == "external") {
518         cur_fdm_state = new FGExternal( dt );
519     } else {
520         SG_LOG(SG_GENERAL, SG_ALERT,
521                "Unrecognized flight model '" << model
522                << ", can't init aircraft");
523         exit(-1);
524     }
525     cur_fdm_state->init();
526     cur_fdm_state->bind();
527     
528     // allocates structures so must happen before any of the flight
529     // model or control parameters are set
530     fgAircraftInit();   // In the future this might not be the case.
531
532
533     ////////////////////////////////////////////////////////////////////
534     // Initialize the event manager subsystem.
535     ////////////////////////////////////////////////////////////////////
536
537     global_events.Init();
538
539     // Output event stats every 60 seconds
540     global_events.Register( "fgEVENT_MGR::PrintStats()",
541                             fgMethodCallback<fgEVENT_MGR>( &global_events,
542                                                    &fgEVENT_MGR::PrintStats),
543                             fgEVENT::FG_EVENT_READY, 60000 );
544
545
546     ////////////////////////////////////////////////////////////////////
547     // Initialize the view manager subsystem.
548     ////////////////////////////////////////////////////////////////////
549
550     // Initialize win_ratio parameters
551     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
552         globals->get_viewmgr()->get_view(i)->
553             set_win_ratio( fgGetInt("/sim/startup/xsize") /
554                            fgGetInt("/sim/startup/ysize") );
555     }
556
557     // Initialize pilot view
558     FGViewerRPH *pilot_view =
559         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
560
561     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
562                                    cur_fdm_state->get_Lat_geocentric(), 
563                                    cur_fdm_state->get_Altitude() *
564                                    SG_FEET_TO_METER );
565     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
566                                       SG_FEET_TO_METER ); 
567     pilot_view->set_rph( cur_fdm_state->get_Phi(),
568                          cur_fdm_state->get_Theta(),
569                          cur_fdm_state->get_Psi() );
570
571     // set current view to 0 (first) which is our main pilot view
572     globals->set_current_view( pilot_view );
573
574     SG_LOG( SG_GENERAL, SG_DEBUG, "  abs_view_pos = "
575             << globals->get_current_view()->get_abs_view_pos());
576
577
578     ////////////////////////////////////////////////////////////////////
579     // Initialize the lighting subsystem.
580     ////////////////////////////////////////////////////////////////////
581
582     // fgUpdateSunPos() needs a few position and view parameters set
583     // so it can calculate local relative sun angle and a few other
584     // things for correctly orienting the sky.
585     fgUpdateSunPos();
586     fgUpdateMoonPos();
587     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
588                             fgEVENT::FG_EVENT_READY, 60000);
589     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
590                             fgEVENT::FG_EVENT_READY, 60000);
591
592     // Initialize Lighting interpolation tables
593     l->Init();
594
595     // update the lighting parameters (based on sun angle)
596     global_events.Register( "fgLight::Update()",
597                             fgMethodCallback<fgLIGHT>( &cur_light_params,
598                                                        &fgLIGHT::Update),
599                             fgEVENT::FG_EVENT_READY, 30000 );
600
601
602     ////////////////////////////////////////////////////////////////////
603     // Initialize the local time subsystem.
604     ////////////////////////////////////////////////////////////////////
605
606     // update the current timezone each 30 minutes
607     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
608                             fgEVENT::FG_EVENT_READY, 1800000);
609
610
611     ////////////////////////////////////////////////////////////////////
612     // Initialize the weather subsystem.
613     ////////////////////////////////////////////////////////////////////
614
615     // Initialize the weather modeling subsystem
616 #ifndef FG_OLD_WEATHER
617     // Initialize the WeatherDatabase
618     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
619     sgVec3 position;
620     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
621                current_aircraft.fdm_state->get_Longitude(),
622                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
623     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
624         new FGLocalWeatherDatabase( position,
625                                     globals->get_fg_root() );
626     // cout << theFGLocalWeatherDatabase << endl;
627     // cout << "visibility = " 
628     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
629
630     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
631     
632     double init_vis = fgGetDouble("/environment/visibility");
633     if ( init_vis > 0 ) {
634         WeatherDatabase->setWeatherVisibility( init_vis );
635     }
636
637     // register the periodic update of the weather
638     global_events.Register( "weather update", fgUpdateWeatherDatabase,
639                             fgEVENT::FG_EVENT_READY, 30000);
640 #else
641     current_weather.Init();
642 #endif
643
644     ////////////////////////////////////////////////////////////////////
645     // Initialize vor/ndb/ils/fix list management and query systems
646     ////////////////////////////////////////////////////////////////////
647
648     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
649
650     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
651     current_navlist = new FGNavList;
652     SGPath p_nav( globals->get_fg_root() );
653     p_nav.append( "Navaids/default.nav" );
654     current_navlist->init( p_nav );
655
656     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
657     current_beacons = new FGMarkerBeacons;
658     current_beacons->init();
659     current_ilslist = new FGILSList;
660     SGPath p_ils( globals->get_fg_root() );
661     p_ils.append( "Navaids/default.ils" );
662     current_ilslist->init( p_ils );
663
664     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
665     current_fixlist = new FGFixList;
666     SGPath p_fix( globals->get_fg_root() );
667     p_fix.append( "Navaids/default.fix" );
668     current_fixlist->init( p_fix );
669
670
671     ////////////////////////////////////////////////////////////////////
672     // Initialize the radio stack subsystem.
673     ////////////////////////////////////////////////////////////////////
674
675                                 // A textbook example of how FGSubsystem
676                                 // should work...
677     current_radiostack = new FGRadioStack;
678     current_radiostack->init();
679     current_radiostack->bind();
680
681
682     ////////////////////////////////////////////////////////////////////
683     // Initialize the cockpit subsystem
684     ////////////////////////////////////////////////////////////////////
685
686     if( fgCockpitInit( &current_aircraft )) {
687         // Cockpit initialized ok.
688     } else {
689         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
690         exit(-1);
691     }
692
693
694     ////////////////////////////////////////////////////////////////////
695     // Initialize the joystick subsystem.
696     ////////////////////////////////////////////////////////////////////
697
698     if ( ! fgJoystickInit() ) {
699         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Joystick initialization!" );
700     }
701
702
703     ////////////////////////////////////////////////////////////////////
704     // Initialize the autopilot subsystem.
705     ////////////////////////////////////////////////////////////////////
706
707     current_autopilot = new FGAutopilot;
708     current_autopilot->init();
709
710     // initialize the gui parts of the autopilot
711     NewTgtAirportInit();
712     fgAPAdjustInit() ;
713     NewHeadingInit();
714     NewAltitudeInit();
715
716     
717     ////////////////////////////////////////////////////////////////////
718     // Initialize I/O subsystem.
719     ////////////////////////////////////////////////////////////////////
720
721 #if ! defined( macintosh )
722     fgIOInit();
723 #endif
724
725     // Initialize the 2D panel.
726     string panel_path = fgGetString("/sim/panel/path",
727                                     "Panels/Default/default.xml");
728     current_panel = fgReadPanel(panel_path);
729     if (current_panel == 0) {
730         SG_LOG( SG_INPUT, SG_ALERT, 
731                 "Error reading new panel from " << panel_path );
732     } else {
733         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
734         current_panel->init();
735         current_panel->bind();
736     }
737
738     
739     ////////////////////////////////////////////////////////////////////
740     // Initialize the BFI.
741     ////////////////////////////////////////////////////////////////////
742
743     FGBFI::init();
744
745
746     ////////////////////////////////////////////////////////////////////
747     // Initialize the controls subsystem.
748     ////////////////////////////////////////////////////////////////////
749
750     controls.init();
751     controls.bind();
752
753
754     ////////////////////////////////////////////////////////////////////////
755     // End of subsystem initialization.
756     ////////////////////////////////////////////////////////////////////
757
758     SG_LOG( SG_GENERAL, SG_INFO, endl);
759
760                                 // Save the initial state for future
761                                 // reference.
762     globals->saveInitialState();
763
764     return true;
765 }
766
767
768 void fgReInitSubsystems( void )
769 {
770     SG_LOG( SG_GENERAL, SG_INFO,
771             "/position/altitude = " << fgGetDouble("/position/altitude") );
772
773     bool freeze = globals->get_freeze();
774     if( !freeze )
775         globals->set_freeze( true );
776     
777     // Initialize the Scenery Management subsystem
778     if ( ! fgSceneryInit() ) {
779         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Scenery initialization!" );
780         exit(-1);
781     }
782
783     if( global_tile_mgr.init() ) {
784         // Load the local scenery data
785         global_tile_mgr.update( fgGetDouble("/position/longitude"),
786                                 fgGetDouble("/position/latitude") );
787     } else {
788         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
789                 exit(-1);
790     }
791
792     // Initialize view parameters
793     FGViewerRPH *pilot_view =
794         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
795
796     pilot_view->set_view_offset( 0.0 );
797     pilot_view->set_goal_view_offset( 0.0 );
798
799     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
800                                    cur_fdm_state->get_Lat_geocentric(), 
801                                    cur_fdm_state->get_Altitude() *
802                                    SG_FEET_TO_METER );
803     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
804                                       SG_FEET_TO_METER ); 
805     pilot_view->set_rph( cur_fdm_state->get_Phi(),
806                          cur_fdm_state->get_Theta(),
807                          cur_fdm_state->get_Psi() );
808
809     // set current view to 0 (first) which is our main pilot view
810     globals->set_current_view( pilot_view );
811
812     SG_LOG( SG_GENERAL, SG_DEBUG, "  abs_view_pos = "
813             << globals->get_current_view()->get_abs_view_pos());
814
815     cur_fdm_state->init();
816
817     controls.reset_all();
818     current_autopilot->reset();
819
820     if( !freeze )
821         globals->set_freeze( false );
822 }