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