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