]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Added Tony's function to set position on a glide slope.
[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_NEW_ENVIRONMENT
106 #  include <WeatherCM/FGLocalWeatherDatabase.h>
107 #else
108 #  include <Environment/environment.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 void fgSetPosFromGlideSlope(void) {
471     double gs = fgGetDouble("/velocities/glideslope");
472     double od = fgGetDouble("/sim/startup/offset-distance");
473     double alt = fgGetDouble("/position/altitude-ft");
474     
475     //if glideslope and offset-distance are set and altitude is
476     //not, calculate the initial altitude
477     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
478         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
479         alt = fabs(od*tan(gs));
480         fgSetDouble("/position/altitude-ft",alt);
481         fgSetBool("/sim/startup/onground", false);
482         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
483     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
484         od  = alt/tan(gs);
485         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
486         fgSetDouble("/sim/startup/offset-distance",od);
487         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
488                                        << od  << " nm");
489     } else if( fabs(gs) > 0.01 ) {
490         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
491                                   << " or offset-distance.  Resetting"
492                                   << " glideslope to zero" );
493         fgSetDouble("/velocities/glideslope",0);                                  
494     }                              
495                                       
496 }                       
497
498 // General house keeping initializations
499 bool fgInitGeneral( void ) {
500     string root;
501
502 #if defined(FX) && defined(XMESA)
503     char *mesa_win_state;
504 #endif
505
506     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
507     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
508
509     root = globals->get_fg_root();
510     if ( ! root.length() ) {
511         // No root path set? Then bail ...
512         SG_LOG( SG_GENERAL, SG_ALERT,
513                 "Cannot continue without a path to the base package "
514                 << "being defined." );
515         exit(-1);
516     }
517     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
518
519 #if defined(FX) && defined(XMESA)
520     // initialize full screen flag
521     globals->set_fullscreen(false);
522     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
523         // Test for the MESA_GLX_FX env variable
524         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
525             // test if we are fullscreen mesa/glide
526             if ( (mesa_win_state[0] == 'f') ||
527                  (mesa_win_state[0] == 'F') ) {
528                 globals->set_fullscreen(true);
529             }
530         }
531     }
532 #endif
533
534     return true;
535 }
536
537
538 // Initialize the flight model subsystem.  This just creates the
539 // object.  The actual fdm initialization is delayed until we get a
540 // proper scenery elevation hit.  This is checked for in main.cxx
541
542 void fgInitFDM() {
543
544     if ( cur_fdm_state ) {
545         delete cur_fdm_state;
546         cur_fdm_state = 0;
547     }
548
549     double dt = 1.0 / fgGetInt("/sim/model-hz");
550     aircraft_dir = fgGetString("/sim/aircraft-dir");
551     const string &model = fgGetString("/sim/flight-model");
552
553     try {
554         if (model == "larcsim") {
555             cur_fdm_state = new FGLaRCsim( dt );
556         } else if (model == "jsb") {
557             cur_fdm_state = new FGJSBsim( dt );
558         } else if (model == "ada") {
559             cur_fdm_state = new FGADA( dt );
560         } else if (model == "balloon") {
561             cur_fdm_state = new FGBalloonSim( dt );
562         } else if (model == "magic") {
563             cur_fdm_state = new FGMagicCarpet( dt );
564         } else if (model == "external") {
565             cur_fdm_state = new FGExternal( dt );
566         } else if (model == "null") {
567             cur_fdm_state = new FGNullFDM( dt );
568         } else if (model == "yasim") {
569             cur_fdm_state = new YASim( dt );
570         } else {
571             SG_LOG(SG_GENERAL, SG_ALERT,
572                    "Unrecognized flight model '" << model
573                    << "', cannot init flight dynamics model.");
574             exit(-1);
575         }
576     } catch ( ... ) {
577         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
578         exit(-1);
579     }
580 }
581
582
583 // Initialize view parameters
584 void fgInitView() {
585     // Initialize pilot view
586     static const SGPropertyNode *longitude
587         = fgGetNode("/position/longitude-deg");
588     static const SGPropertyNode *latitude
589         = fgGetNode("/position/latitude-deg");
590     static const SGPropertyNode *altitude
591         = fgGetNode("/position/altitude-ft");
592
593     FGViewerRPH *pilot_view
594         = (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
595
596     pilot_view->set_geod_view_pos( longitude->getDoubleValue()
597                                      * SGD_DEGREES_TO_RADIANS, 
598                                    latitude->getDoubleValue()
599                                      * SGD_DEGREES_TO_RADIANS,
600                                    altitude->getDoubleValue()
601                                      * SG_FEET_TO_METER );
602     pilot_view->set_rph( cur_fdm_state->get_Phi(),
603                          cur_fdm_state->get_Theta(),
604                          cur_fdm_state->get_Psi() );
605
606     // set current view to 0 (first) which is our main pilot view
607     globals->set_current_view( pilot_view );
608
609     SG_LOG( SG_GENERAL, SG_DEBUG, "  abs_view_pos = "
610             << globals->get_current_view()->get_abs_view_pos());
611 }
612
613
614 SGTime *fgInitTime() {
615     // Initialize time
616     static const SGPropertyNode *longitude
617         = fgGetNode("/position/longitude-deg");
618     static const SGPropertyNode *latitude
619         = fgGetNode("/position/latitude-deg");
620     static const SGPropertyNode *cur_time_override
621         = fgGetNode("/sim/time/cur-time-override", true);
622
623     SGPath zone( globals->get_fg_root() );
624     zone.append( "Timezone" );
625     SGTime *t = new SGTime( longitude->getDoubleValue()
626                               * SGD_DEGREES_TO_RADIANS,
627                             latitude->getDoubleValue()
628                               * SGD_DEGREES_TO_RADIANS,
629                             zone.str(),
630                             cur_time_override->getLongValue() );
631
632     // Handle potential user specified time offsets
633     time_t cur_time = t->get_cur_time();
634     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
635     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
636     time_t aircraftLocalTime = 
637         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
638
639     // Okay, we now have six possible scenarios
640     int offset = fgGetInt("/sim/startup/time-offset");
641     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
642     if (offset_type == "system-offset") {
643         globals->set_warp( offset );
644     } else if (offset_type == "gmt-offset") {
645         globals->set_warp( offset - (currGMT - systemLocalTime) );
646     } else if (offset_type == "latitude-offset") {
647         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
648     } else if (offset_type == "system") {
649         globals->set_warp( offset - cur_time );
650     } else if (offset_type == "gmt") {
651         globals->set_warp( offset - currGMT );
652     } else if (offset_type == "latitude") {
653         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
654                            cur_time ); 
655     } else {
656         SG_LOG( SG_GENERAL, SG_ALERT,
657                 "FG_TIME::Unsupported offset type " << offset_type );
658         exit( -1 );
659     }
660
661     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
662             << globals->get_warp() );
663
664     globals->set_warp_delta( 0 );
665
666     t->update( 0.0, 0.0,
667                cur_time_override->getLongValue(),
668                globals->get_warp() );
669
670     return t;
671 }
672
673
674 // This is the top level init routine which calls all the other
675 // initialization routines.  If you are adding a subsystem to flight
676 // gear, its initialization call should located in this routine.
677 // Returns non-zero if a problem encountered.
678 bool fgInitSubsystems( void ) {
679     static const SGPropertyNode *longitude
680         = fgGetNode("/position/longitude-deg");
681     static const SGPropertyNode *latitude
682         = fgGetNode("/position/latitude-deg");
683     static const SGPropertyNode *altitude
684         = fgGetNode("/position/altitude-ft");
685
686     fgLIGHT *l = &cur_light_params;
687
688     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
689     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
690
691
692     ////////////////////////////////////////////////////////////////////
693     // Initialize the material property subsystem.
694     ////////////////////////////////////////////////////////////////////
695
696     SGPath mpath( globals->get_fg_root() );
697     mpath.append( "materials.xml" );
698     if ( ! material_lib.load( mpath.str() ) ) {
699         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
700         exit(-1);
701     }
702
703
704     ////////////////////////////////////////////////////////////////////
705     // Initialize the scenery management subsystem.
706     ////////////////////////////////////////////////////////////////////
707
708     scenery.init();
709     scenery.bind();
710
711     if ( global_tile_mgr.init() ) {
712         // Load the local scenery data
713         global_tile_mgr.update( longitude->getDoubleValue(),
714                                 latitude->getDoubleValue() );
715     } else {
716         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
717         exit(-1);
718     }
719
720     SG_LOG( SG_GENERAL, SG_DEBUG,
721             "Current terrain elevation after tile mgr init " <<
722             scenery.get_cur_elev() );
723
724
725     ////////////////////////////////////////////////////////////////////
726     // Initialize the flight model subsystem.
727     ////////////////////////////////////////////////////////////////////
728
729     fgInitFDM();
730         
731     // allocates structures so must happen before any of the flight
732     // model or control parameters are set
733     fgAircraftInit();   // In the future this might not be the case.
734
735
736     ////////////////////////////////////////////////////////////////////
737     // Initialize the event manager subsystem.
738     ////////////////////////////////////////////////////////////////////
739
740     global_events.Init();
741
742     // Output event stats every 60 seconds
743     global_events.Register( "fgEVENT_MGR::PrintStats()",
744                             fgMethodCallback<fgEVENT_MGR>( &global_events,
745                                                    &fgEVENT_MGR::PrintStats),
746                             fgEVENT::FG_EVENT_READY, 60000 );
747
748
749     ////////////////////////////////////////////////////////////////////
750     // Initialize the view manager subsystem.
751     ////////////////////////////////////////////////////////////////////
752
753     fgInitView();
754
755
756     ////////////////////////////////////////////////////////////////////
757     // Initialize the lighting subsystem.
758     ////////////////////////////////////////////////////////////////////
759
760     // fgUpdateSunPos() needs a few position and view parameters set
761     // so it can calculate local relative sun angle and a few other
762     // things for correctly orienting the sky.
763     fgUpdateSunPos();
764     fgUpdateMoonPos();
765     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
766                             fgEVENT::FG_EVENT_READY, 60000);
767     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
768                             fgEVENT::FG_EVENT_READY, 60000);
769
770     // Initialize Lighting interpolation tables
771     l->Init();
772
773     // update the lighting parameters (based on sun angle)
774     global_events.Register( "fgLight::Update()",
775                             fgMethodCallback<fgLIGHT>( &cur_light_params,
776                                                        &fgLIGHT::Update),
777                             fgEVENT::FG_EVENT_READY, 30000 );
778
779
780     ////////////////////////////////////////////////////////////////////
781     // Initialize the local time subsystem.
782     ////////////////////////////////////////////////////////////////////
783
784     // update the current timezone each 30 minutes
785     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
786                             fgEVENT::FG_EVENT_READY, 1800000);
787
788
789     ////////////////////////////////////////////////////////////////////
790     // Initialize the weather subsystem.
791     ////////////////////////////////////////////////////////////////////
792
793     // Initialize the weather modeling subsystem
794 #ifndef FG_NEW_ENVIRONMENT
795     // Initialize the WeatherDatabase
796     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
797     sgVec3 position;
798     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
799                current_aircraft.fdm_state->get_Longitude(),
800                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
801     double init_vis = fgGetDouble("/environment/visibility-m");
802
803     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
804
805     if (fgGetString("/environment/weather/working-type") == "internet")
806     {
807       working_type = FGLocalWeatherDatabase::use_internet;
808     } else {
809       working_type = FGLocalWeatherDatabase::default_mode;
810     }
811     
812     if ( init_vis > 0 ) {
813       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
814         new FGLocalWeatherDatabase( position,
815                                     globals->get_fg_root(),
816                                     working_type,
817                                     init_vis );
818     } else {
819       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
820         new FGLocalWeatherDatabase( position,
821                                     globals->get_fg_root(),
822                                     working_type );
823     }
824
825     // cout << theFGLocalWeatherDatabase << endl;
826     // cout << "visibility = " 
827     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
828
829     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
830
831     // register the periodic update of the weather
832     global_events.Register( "weather update", fgUpdateWeatherDatabase,
833                             fgEVENT::FG_EVENT_READY, 30000);
834 #else
835     current_environment.init();
836     current_environment.bind();
837 #endif
838
839     ////////////////////////////////////////////////////////////////////
840     // Initialize vor/ndb/ils/fix list management and query systems
841     ////////////////////////////////////////////////////////////////////
842
843     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
844
845     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
846     current_navlist = new FGNavList;
847     SGPath p_nav( globals->get_fg_root() );
848     p_nav.append( "Navaids/default.nav" );
849     current_navlist->init( p_nav );
850
851     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
852     current_beacons = new FGMarkerBeacons;
853     current_beacons->init();
854     current_ilslist = new FGILSList;
855     SGPath p_ils( globals->get_fg_root() );
856     p_ils.append( "Navaids/default.ils" );
857     current_ilslist->init( p_ils );
858
859     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
860     current_fixlist = new FGFixList;
861     SGPath p_fix( globals->get_fg_root() );
862     p_fix.append( "Navaids/default.fix" );
863     current_fixlist->init( p_fix );
864
865     ////////////////////////////////////////////////////////////////////
866     // Initialize ATC list management and query systems
867     ////////////////////////////////////////////////////////////////////
868
869     //DCL
870     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
871     current_atislist = new FGATISList;
872     SGPath p_atis( globals->get_fg_root() );
873     p_atis.append( "ATC/default.atis" );
874     current_atislist->init( p_atis );
875
876     ////////////////////////////////////////////////////////////////////
877     // Initialise ATC display system
878     ////////////////////////////////////////////////////////////////////
879
880     //DCL
881     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
882     current_atcdisplay = new FGATCDisplay;
883     current_atcdisplay->init();   
884
885     ////////////////////////////////////////////////////////////////////
886     // Initialize the built-in commands.
887     ////////////////////////////////////////////////////////////////////
888     fgInitCommands();
889
890
891 #ifdef ENABLE_AUDIO_SUPPORT
892     ////////////////////////////////////////////////////////////////////
893     // Initialize the sound subsystem.
894     ////////////////////////////////////////////////////////////////////
895
896     globals->set_soundmgr(new FGSoundMgr);
897     globals->get_soundmgr()->init();
898     globals->get_soundmgr()->bind();
899
900
901     ////////////////////////////////////////////////////////////////////
902     // Initialize the sound-effects subsystem.
903     ////////////////////////////////////////////////////////////////////
904     globals->set_fx(new FGFX);
905     globals->get_fx()->init();
906     globals->get_fx()->bind();
907
908 #endif
909
910     ////////////////////////////////////////////////////////////////////
911     // Initialize the radio stack subsystem.
912     ////////////////////////////////////////////////////////////////////
913
914                                 // A textbook example of how FGSubsystem
915                                 // should work...
916     current_radiostack = new FGRadioStack;
917     current_radiostack->init();
918     current_radiostack->bind();
919
920
921     ////////////////////////////////////////////////////////////////////
922     // Initialize the cockpit subsystem
923     ////////////////////////////////////////////////////////////////////
924
925     if( fgCockpitInit( &current_aircraft )) {
926         // Cockpit initialized ok.
927     } else {
928         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
929         exit(-1);
930     }
931
932
933     ////////////////////////////////////////////////////////////////////
934     // Initialize the joystick subsystem.
935     ////////////////////////////////////////////////////////////////////
936
937     // if ( ! fgJoystickInit() ) {
938     //   SG_LOG( SG_GENERAL, SG_ALERT, "Error in Joystick initialization!" );
939     // }
940
941
942     ////////////////////////////////////////////////////////////////////
943     // Initialize the autopilot subsystem.
944     ////////////////////////////////////////////////////////////////////
945
946     current_autopilot = new FGAutopilot;
947     current_autopilot->init();
948
949     // initialize the gui parts of the autopilot
950     fgAPAdjustInit();
951     NewTgtAirportInit();
952     NewHeadingInit();
953     NewAltitudeInit();
954
955     ////////////////////////////////////////////////////////////////////
956     // Initialize I/O subsystem.
957     ////////////////////////////////////////////////////////////////////
958
959 #if ! defined( macintosh )
960     fgIOInit();
961 #endif
962
963     // Initialize the 2D panel.
964     string panel_path = fgGetString("/sim/panel/path",
965                                     "Panels/Default/default.xml");
966     current_panel = fgReadPanel(panel_path);
967     if (current_panel == 0) {
968         SG_LOG( SG_INPUT, SG_ALERT, 
969                 "Error reading new panel from " << panel_path );
970     } else {
971         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
972         current_panel->init();
973         current_panel->bind();
974     }
975
976     
977     ////////////////////////////////////////////////////////////////////
978     // Initialize the default (kludged) properties.
979     ////////////////////////////////////////////////////////////////////
980
981     fgInitProps();
982
983
984     ////////////////////////////////////////////////////////////////////
985     // Initialize the controls subsystem.
986     ////////////////////////////////////////////////////////////////////
987
988     globals->get_controls()->init();
989     globals->get_controls()->bind();
990
991
992     ////////////////////////////////////////////////////////////////////
993     // Initialize the input subsystem.
994     ////////////////////////////////////////////////////////////////////
995
996     current_input.init();
997     current_input.bind();
998
999
1000     ////////////////////////////////////////////////////////////////////////
1001     // End of subsystem initialization.
1002     ////////////////////////////////////////////////////////////////////
1003
1004     SG_LOG( SG_GENERAL, SG_INFO, endl);
1005
1006                                 // Save the initial state for future
1007                                 // reference.
1008     globals->saveInitialState();
1009
1010     return true;
1011 }
1012
1013
1014 void fgReInitSubsystems( void )
1015 {
1016     static const SGPropertyNode *longitude
1017         = fgGetNode("/position/longitude-deg");
1018     static const SGPropertyNode *latitude
1019         = fgGetNode("/position/latitude-deg");
1020     static const SGPropertyNode *altitude
1021         = fgGetNode("/position/altitude-ft");
1022     static const SGPropertyNode *master_freeze
1023         = fgGetNode("/sim/freeze/master");
1024
1025     SG_LOG( SG_GENERAL, SG_INFO,
1026             "/position/altitude = " << altitude->getDoubleValue() );
1027
1028     bool freeze = master_freeze->getBoolValue();
1029     if ( !freeze ) {
1030         fgSetBool("/sim/freeze/master", true);
1031     }
1032     
1033     // Initialize the Scenery Management subsystem
1034     scenery.init();
1035
1036 #if 0
1037     if( global_tile_mgr.init() ) {
1038         Load the local scenery data
1039         global_tile_mgr.update( longitude->getDoubleValue(),
1040                                 latitude->getDoubleValue() );
1041     } else {
1042         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1043         exit(-1);
1044     }
1045 #endif
1046
1047     fgInitFDM();
1048     
1049     // allocates structures so must happen before any of the flight
1050     // model or control parameters are set
1051     fgAircraftInit();   // In the future this might not be the case.
1052
1053     fgInitView();
1054
1055     globals->get_controls()->reset_all();
1056     current_autopilot->reset();
1057
1058     fgUpdateSunPos();
1059     fgUpdateMoonPos();
1060     cur_light_params.Update();
1061     fgUpdateLocalTime();
1062
1063     if ( !freeze ) {
1064         fgSetBool("/sim/freeze/master", false);
1065     }
1066 }