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