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