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