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