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