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