]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Remove the last traces of metakit (hopefully) :-)
[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 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>             // strcmp()
37
38
39 #if defined( unix ) || defined( __CYGWIN__ )
40 #  include <unistd.h>           // for gethostname()
41 #endif
42
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
45 #ifdef linux
46 #  define _G_NO_EXTERN_TEMPLATES
47 #endif
48
49 #include <simgear/compiler.h>
50 #include <simgear/misc/exception.hxx>
51
52 #include STL_STRING
53
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/math/point3d.hxx>
57 #include <simgear/math/polar3d.hxx>
58 #include <simgear/math/sg_geodesy.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #ifdef FG_USE_CLOUDS_3D
62 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
63 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
64 #  include <simgear/screen/texture.hxx>
65 #endif
66 #include <simgear/timing/sg_time.hxx>
67 #include <simgear/timing/lowleveltime.h>
68
69 #include <Aircraft/aircraft.hxx>
70 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <ATC/ATCdisplay.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/AIMgr.hxx>
76 #include <Autopilot/auto_gui.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
82 #include <FDM/ADA.hxx>
83 #include <FDM/Balloon.h>
84 #include <FDM/ExternalNet/ExternalNet.hxx>
85 #include <FDM/ExternalPipe/ExternalPipe.hxx>
86 #include <FDM/JSBSim/JSBSim.hxx>
87 #include <FDM/LaRCsim/LaRCsim.hxx>
88 #include <FDM/MagicCarpet.hxx>
89 #include <FDM/UFO.hxx>
90 #include <FDM/NullFDM.hxx>
91 #include <FDM/YASim/YASim.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Include/general.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Navaids/fixlist.hxx>
98 #include <Navaids/ilslist.hxx>
99 #include <Navaids/mkrbeacons.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Replay/replay.hxx>
102 #include <Scenery/scenery.hxx>
103 #include <Scenery/tilemgr.hxx>
104 #if defined(HAVE_PLIB_PSL)
105 #include <Scripting/scriptmgr.hxx>
106 #endif
107 #include <Sound/fg_fx.hxx>
108 #include <Systems/system_mgr.hxx>
109 #include <Time/FGEventMgr.hxx>
110 #include <Time/light.hxx>
111 #include <Time/sunpos.hxx>
112 #include <Time/moonpos.hxx>
113 #include <Time/tmp.hxx>
114
115 #ifdef FG_MPLAYER_AS
116 #include <MultiPlayer/multiplaytxmgr.hxx>
117 #include <MultiPlayer/multiplayrxmgr.hxx>
118 #endif
119
120 #ifdef FG_WEATHERCM
121 #  include <WeatherCM/FGLocalWeatherDatabase.h>
122 #else
123 #  include <Environment/environment_mgr.hxx>
124 #endif
125
126 #include "fg_init.hxx"
127 #include "fg_io.hxx"
128 #include "fg_commands.hxx"
129 #include "fg_props.hxx"
130 #include "options.hxx"
131 #include "globals.hxx"
132 #include "logger.hxx"
133 #include "viewmgr.hxx"
134
135 #if defined(FX) && defined(XMESA)
136 #include <GL/xmesa.h>
137 #endif
138
139 SG_USING_STD(string);
140
141
142 class Sound;
143
144 extern const char *default_root;
145
146 #ifdef FG_USE_CLOUDS_3D
147   SkySceneLoader *sgCloud3d;
148 #endif
149
150
151 // Scan the command line options for the specified option and return
152 // the value.
153 static string fgScanForOption( const string& option, int argc, char **argv ) {
154     int i = 1;
155
156     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
157
158     int len = option.length();
159
160     while ( i < argc ) {
161         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
162
163         string arg = argv[i];
164         if ( arg.find( option ) == 0 ) {
165             return arg.substr( len );
166         }
167
168         i++;
169     }
170
171     return "";
172 }
173
174
175 // Scan the user config files for the specified option and return
176 // the value.
177 static string fgScanForOption( const string& option, const string& path ) {
178     sg_gzifstream in( path );
179     if ( !in.is_open() ) {
180         return "";
181     }
182
183     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
184
185     int len = option.length();
186
187     in >> skipcomment;
188 #ifndef __MWERKS__
189     while ( ! in.eof() ) {
190 #else
191     char c = '\0';
192     while ( in.get(c) && c != '\0' ) {
193         in.putback(c);
194 #endif
195         string line;
196
197 #if defined( macintosh )
198         getline( in, line, '\r' );
199 #else
200         getline( in, line, '\n' );
201 #endif
202
203         // catch extraneous (DOS) line ending character
204         if ( line[line.length() - 1] < 32 ) {
205             line = line.substr( 0, line.length()-1 );
206         }
207
208         if ( line.find( option ) == 0 ) {
209             return line.substr( len );
210         }
211
212         in >> skipcomment;
213     }
214
215     return "";
216 }
217
218
219 // Read in configuration (files and command line options) but only set
220 // fg_root
221 bool fgInitFGRoot ( int argc, char **argv ) {
222     string root;
223     char* envp;
224
225     // First parse command line options looking for --fg-root=, this
226     // will override anything specified in a config file
227     root = fgScanForOption( "--fg-root=", argc, argv);
228
229 #if defined( unix ) || defined( __CYGWIN__ )
230     // Next check home directory for .fgfsrc.hostname file
231     if ( root.empty() ) {
232         envp = ::getenv( "HOME" );
233         if ( envp != NULL ) {
234             SGPath config( envp );
235             config.append( ".fgfsrc" );
236             char name[256];
237             gethostname( name, 256 );
238             config.concat( "." );
239             config.concat( name );
240             root = fgScanForOption( "--fg-root=", config.str() );
241         }
242     }
243 #endif
244
245     // Next check home directory for .fgfsrc file
246     if ( root.empty() ) {
247         envp = ::getenv( "HOME" );
248         if ( envp != NULL ) {
249             SGPath config( envp );
250             config.append( ".fgfsrc" );
251             root = fgScanForOption( "--fg-root=", config.str() );
252         }
253     }
254     
255     // Next check if fg-root is set as an env variable
256     if ( root.empty() ) {
257         envp = ::getenv( "FG_ROOT" );
258         if ( envp != NULL ) {
259             root = envp;
260         }
261     }
262
263     // Otherwise, default to a random compiled-in location if we can't
264     // find fg-root any other way.
265     if ( root.empty() ) {
266 #if defined( __CYGWIN__ )
267         root = "/FlightGear";
268 #elif defined( WIN32 )
269         root = "\\FlightGear";
270 #elif defined( macintosh )
271         root = "";
272 #else
273         root = PKGLIBDIR;
274 #endif
275     }
276
277     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
278     globals->set_fg_root(root);
279
280     return true;
281 }
282
283
284 // Read in configuration (files and command line options) but only set
285 // aircraft
286 bool fgInitFGAircraft ( int argc, char **argv ) {
287     string aircraft;
288     char* envp;
289
290     // First parse command line options looking for --aircraft=, this
291     // will override anything specified in a config file
292     aircraft = fgScanForOption( "--aircraft=", argc, argv );
293
294 #if defined( unix ) || defined( __CYGWIN__ )
295     // Next check home directory for .fgfsrc.hostname file
296     if ( aircraft.empty() ) {
297         envp = ::getenv( "HOME" );
298         if ( envp != NULL ) {
299             SGPath config( envp );
300             config.append( ".fgfsrc" );
301             char name[256];
302             gethostname( name, 256 );
303             config.concat( "." );
304             config.concat( name );
305             aircraft = fgScanForOption( "--aircraft=", config.str() );
306         }
307     }
308 #endif
309
310     // Next check home directory for .fgfsrc file
311     if ( aircraft.empty() ) {
312         envp = ::getenv( "HOME" );
313         if ( envp != NULL ) {
314             SGPath config( envp );
315             config.append( ".fgfsrc" );
316             aircraft = fgScanForOption( "--aircraft=", config.str() );
317         }
318     }
319
320     // if an aircraft was specified, set the property name
321     if ( !aircraft.empty() ) {
322         SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
323         fgSetString("/sim/aircraft", aircraft.c_str() );
324     } else {
325         SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
326     }
327
328     return true;
329 }
330
331
332 // Return the current base package version
333 string fgBasePackageVersion() {
334     SGPath base_path( globals->get_fg_root() );
335     base_path.append("version");
336
337     sg_gzifstream in( base_path.str() );
338     if ( !in.is_open() ) {
339         SGPath old_path( globals->get_fg_root() );
340         old_path.append( "Thanks" );
341         sg_gzifstream old( old_path.str() );
342         if ( !old.is_open() ) {
343             return "[none]";
344         } else {
345             return "[old version]";
346         }
347     }
348
349     string version;
350     in >> version;
351
352     return version;
353 }
354
355
356 // Initialize the localization
357 SGPropertyNode *fgInitLocale(const char *language) {
358    SGPropertyNode *c_node = NULL, *d_node = NULL;
359    SGPropertyNode *intl = fgGetNode("/sim/intl");
360
361    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
362
363    // localization not defined
364    if (!intl)
365       return NULL;
366
367    //
368    // Select the proper language from the list
369    //
370    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
371    for (unsigned int i = 0; i < locale.size(); i++) {
372
373       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
374       for (unsigned int j = 0; j < lang.size(); j++) {
375
376          if (!strcmp(lang[j]->getStringValue(), language)) {
377             c_node = locale[i];
378             break;
379          }
380       }
381    }
382
383
384    // Get the defaults
385    d_node = intl->getChild("locale");
386    if (!c_node)
387       c_node = d_node;
388
389    // Check for localized font
390    SGPropertyNode *font_n = c_node->getNode("font", true);
391    if ( !strcmp(font_n->getStringValue(), "") )
392       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
393
394
395    //
396    // Load the default strings
397    //
398    SGPath d_path( globals->get_fg_root() );
399
400    const char *d_path_str = d_node->getStringValue("strings");
401    if (!d_path_str) {
402       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
403       return NULL;
404    }
405
406    d_path.append(d_path_str);
407    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
408                                   << d_path.str());
409
410    SGPropertyNode *strings = c_node->getNode("strings");
411    try {
412       readProperties(d_path.str(), strings);
413    } catch (const sg_exception &e) {
414       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
415       return NULL;
416    }
417
418    //
419    // Load the language specific strings
420    //
421    if (c_node != d_node) {
422       SGPath c_path( globals->get_fg_root() );
423
424       const char *c_path_str = c_node->getStringValue("strings");
425       if (!c_path_str) {
426          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
427          return NULL;
428       }
429
430       c_path.append(c_path_str);
431       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
432                                      << c_path.str());
433
434       try {
435          readProperties(c_path.str(), strings);
436       } catch (const sg_exception &e) {
437          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
438          return NULL;
439       }
440    }
441
442    return c_node;
443 }
444
445
446
447 // Initialize the localization routines
448 bool fgDetectLanguage() {
449     char *language = ::getenv("LANG");
450
451     if (language == NULL) {
452         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
453         language = "C";
454     }
455
456     SGPropertyNode *locale = fgInitLocale(language);
457     if (!locale) {
458        SG_LOG(SG_GENERAL, SG_ALERT,
459               "No internationalization settings specified in preferences.xml" );
460
461        return false;
462     }
463
464     globals->set_locale( locale );
465
466     return true;
467 }
468
469 // Attempt to locate and parse the various non-XML config files in order
470 // from least precidence to greatest precidence
471 static void
472 do_options (int argc, char ** argv)
473 {
474     // Check for $fg_root/system.fgfsrc
475     SGPath config( globals->get_fg_root() );
476     config.append( "system.fgfsrc" );
477     fgParseOptions(config.str());
478
479 #if defined( unix ) || defined( __CYGWIN__ )
480     char name[256];
481     // Check for $fg_root/system.fgfsrc.hostname
482     gethostname( name, 256 );
483     config.concat( "." );
484     config.concat( name );
485     fgParseOptions(config.str());
486 #endif
487
488     // Check for ~/.fgfsrc
489     char* envp = ::getenv( "HOME" );
490     if ( envp != NULL ) {
491         config.set( envp );
492         config.append( ".fgfsrc" );
493         fgParseOptions(config.str());
494     }
495
496 #if defined( unix ) || defined( __CYGWIN__ )
497     // Check for ~/.fgfsrc.hostname
498     gethostname( name, 256 );
499     config.concat( "." );
500     config.concat( name );
501     fgParseOptions(config.str());
502 #endif
503
504     // Parse remaining command line options
505     // These will override anything specified in a config file
506     fgParseArgs(argc, argv);
507 }
508
509
510 // Read in configuration (file and command line)
511 bool fgInitConfig ( int argc, char **argv ) {
512
513     // First, set some sane default values
514     fgSetDefaults();
515
516     // Read global preferences from $FG_ROOT/preferences.xml
517     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
518     fgLoadProps("preferences.xml", globals->get_props());
519     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
520
521     // Detect the required language as early as possible
522     if ( !fgDetectLanguage() ) {
523         return false;
524     }
525
526     // Scan user config files and command line for a specified aircraft.
527     fgInitFGAircraft(argc, argv);
528
529     string aircraft = fgGetString("/sim/aircraft", "");
530     if ( aircraft.size() > 0 ) {
531         SGPath aircraft_path(globals->get_fg_root());
532         aircraft_path.append("Aircraft");
533         aircraft_path.append(aircraft);
534         aircraft_path.concat("-set.xml");
535         SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
536                << " from " << aircraft_path.str());
537         try {
538             readProperties(aircraft_path.str(), globals->get_props());
539         } catch (const sg_exception &e) {
540             string message = "Error reading default aircraft: ";
541             message += e.getFormattedMessage();
542             SG_LOG(SG_INPUT, SG_ALERT, message);
543             exit(2);
544         }
545     } else {
546         SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
547     }
548
549     // parse options after loading aircraft to ensure any user
550     // overrides of defaults are honored.
551     do_options(argc, argv);
552
553     return true;
554 }
555
556
557 // find basic airport location info from airport database
558 bool fgFindAirportID( const string& id, FGAirport *a ) {
559     FGAirport result;
560     if ( id.length() ) {
561         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
562
563         result = globals->get_airports()->search( id );
564
565         if ( result.id.empty() ) {
566             SG_LOG( SG_GENERAL, SG_ALERT,
567                     "Failed to find " << id << " in basic.dat.gz" );
568             return false;
569         }
570     } else {
571         return false;
572     }
573
574     *a = result;
575
576     SG_LOG( SG_GENERAL, SG_INFO,
577             "Position for " << id << " is ("
578             << a->longitude << ", "
579             << a->latitude << ")" );
580
581     return true;
582 }
583
584
585 // get airport elevation
586 static double fgGetAirportElev( const string& id ) {
587     FGAirport a;
588     // double lon, lat;
589
590     SG_LOG( SG_GENERAL, SG_INFO,
591             "Finding elevation for airport: " << id );
592
593     if ( fgFindAirportID( id, &a ) ) {
594         return a.elevation;
595     } else {
596         return -9999.0;
597     }
598 }
599
600
601 // Preset lon/lat given an airport id
602 static bool fgSetPosFromAirportID( const string& id ) {
603     FGAirport a;
604     // double lon, lat;
605
606     SG_LOG( SG_GENERAL, SG_INFO,
607             "Attempting to set starting position from airport code " << id );
608
609     if ( fgFindAirportID( id, &a ) ) {
610         // presets
611         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
612         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
613
614         // other code depends on the actual postition being set so set
615         // that as well
616         fgSetDouble("/position/longitude-deg", a.longitude );
617         fgSetDouble("/position/latitude-deg", a.latitude );
618
619         SG_LOG( SG_GENERAL, SG_INFO,
620                 "Position for " << id << " is (" << a.longitude
621                 << ", " << a.latitude << ")" );
622
623         return true;
624     } else {
625         return false;
626     }
627 }
628
629
630 // Set current tower position lon/lat given an airport id
631 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
632     FGAirport a;
633     // tower height hard coded for now...
634     float towerheight=50.0f;
635
636     // make a little off the heading for 1 runway airports...
637     float fudge_lon = fabs(sin(hdg)) * .003f;
638     float fudge_lat = .003f - fudge_lon;
639
640     if ( fgFindAirportID( id, &a ) ) {
641         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
642         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
643         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
644         return true;
645     } else {
646         return false;
647     }
648
649 }
650
651
652 // Set current_options lon/lat given an airport id and heading (degrees)
653 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
654     FGRunway r;
655
656     if ( id.length() ) {
657         // set initial position from runway and heading
658
659         SG_LOG( SG_GENERAL, SG_INFO,
660                 "Attempting to set starting position from airport code "
661                 << id << " heading " << tgt_hdg );
662                 
663         if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
664             SG_LOG( SG_GENERAL, SG_ALERT,
665                     "Failed to find a good runway for " << id << '\n' );
666             return false;
667         }       
668     } else {
669         return false;
670     }
671
672     double lat2, lon2, az2;
673     double heading = r.heading;
674     double azimuth = heading + 180.0;
675     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
676
677     SG_LOG( SG_GENERAL, SG_INFO,
678             "runway =  " << r.lon << ", " << r.lat
679             << " length = " << r.length * SG_FEET_TO_METER 
680             << " heading = " << azimuth );
681             
682     geo_direct_wgs_84 ( 0, r.lat, r.lon, azimuth, 
683                         r.length * SG_FEET_TO_METER * 0.5 - 5.0,
684                         &lat2, &lon2, &az2 );
685
686     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
687         double olat, olon;
688         double odist = fgGetDouble("/sim/presets/offset-distance");
689         odist *= SG_NM_TO_METER;
690         double oaz = azimuth;
691         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
692             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
693             heading = tgt_hdg;
694         }
695         while ( oaz >= 360.0 ) { oaz -= 360.0; }
696         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
697         lat2=olat;
698         lon2=olon;
699     }
700
701     // presets
702     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
703     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
704     fgSetDouble("/sim/presets/heading-deg", heading );
705
706     // other code depends on the actual values being set ...
707     fgSetDouble("/position/longitude-deg",  lon2 );
708     fgSetDouble("/position/latitude-deg",  lat2 );
709     fgSetDouble("/orientation/heading-deg", heading );
710
711     SG_LOG( SG_GENERAL, SG_INFO,
712             "Position for " << id << " is ("
713             << lon2 << ", "
714             << lat2 << ") new heading is "
715             << heading );
716             
717     return true;
718 }
719
720
721 // Set current_options lon/lat given an airport id and runway number
722 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
723     FGRunway r;
724
725     if ( id.length() ) {
726         // set initial position from airport and runway number
727
728         SG_LOG( SG_GENERAL, SG_INFO,
729                 "Attempting to set starting position for "
730                 << id << ":" << rwy );
731
732         if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
733             SG_LOG( SG_GENERAL, SG_ALERT,
734                     "Failed to find runway " << rwy << 
735                     " at airport " << id );
736             return false;
737         }
738     } else {
739         return false;
740     }
741
742     double lat2, lon2, az2;
743     double heading = r.heading;
744     double azimuth = heading + 180.0;
745     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
746     
747     SG_LOG( SG_GENERAL, SG_INFO,
748     "runway =  " << r.lon << ", " << r.lat
749     << " length = " << r.length * SG_FEET_TO_METER 
750     << " heading = " << azimuth );
751     
752     geo_direct_wgs_84 ( 0, r.lat, r.lon, 
753     azimuth,
754     r.length * SG_FEET_TO_METER * 0.5 - 5.0,
755     &lat2, &lon2, &az2 );
756     
757     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
758     {
759         double olat, olon;
760         double odist = fgGetDouble("/sim/presets/offset-distance");
761         odist *= SG_NM_TO_METER;
762         double oaz = azimuth;
763         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
764         {
765             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
766             heading = fgGetDouble("/sim/presets/heading-deg");
767         }
768         while ( oaz >= 360.0 ) { oaz -= 360.0; }
769         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
770         lat2=olat;
771         lon2=olon;
772     }
773     
774     // presets
775     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
776     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
777     fgSetDouble("/sim/presets/heading-deg", heading );
778     
779     // other code depends on the actual values being set ...
780     fgSetDouble("/position/longitude-deg",  lon2 );
781     fgSetDouble("/position/latitude-deg",  lat2 );
782     fgSetDouble("/orientation/heading-deg", heading );
783     
784     SG_LOG( SG_GENERAL, SG_INFO,
785     "Position for " << id << " is ("
786     << lon2 << ", "
787     << lat2 << ") new heading is "
788     << heading );
789     
790     return true;
791 }
792
793
794 static void fgSetDistOrAltFromGlideSlope() {
795     string apt_id = fgGetString("/sim/presets/airport-id");
796     double gs = fgGetDouble("/sim/presets/glideslope-deg")
797         * SG_DEGREES_TO_RADIANS ;
798     double od = fgGetDouble("/sim/presets/offset-distance");
799     double alt = fgGetDouble("/sim/presets/altitude-ft");
800
801     double apt_elev = 0.0;
802     if ( ! apt_id.empty() ) {
803         apt_elev = fgGetAirportElev( apt_id );
804         if ( apt_elev < -9990.0 ) {
805             apt_elev = 0.0;
806         }
807     } else {
808         apt_elev = 0.0;
809     }
810
811     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
812         // set altitude from glideslope and offset-distance
813         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
814         alt = fabs(od*tan(gs)) + apt_elev;
815         fgSetDouble("/sim/presets/altitude-ft", alt);
816         fgSetBool("/sim/presets/onground", false);
817         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
818                 << alt  << " ft" );
819     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
820         // set offset-distance from glideslope and altitude
821         od  = (alt - apt_elev) / tan(gs);
822         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
823         fgSetDouble("/sim/presets/offset-distance", od);
824         fgSetBool("/sim/presets/onground", false);
825         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
826                 << od  << " nm" );
827     } else if( fabs(gs) > 0.01 ) {
828         SG_LOG( SG_GENERAL, SG_ALERT,
829                 "Glideslope given but not altitude or offset-distance." );
830         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
831         fgSetDouble("/sim/presets/glideslope-deg", 0);
832         fgSetBool("/sim/presets/onground", true);
833     }                              
834 }                       
835
836
837 // Set current_options lon/lat given an airport id and heading (degrees)
838 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
839     FGNav *nav = current_navlist->findByIdentAndFreq( id.c_str(), freq );
840
841     // set initial position from runway and heading
842     if ( nav != NULL ) {
843         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
844                 << id << ":" << freq );
845
846         double lon = nav->get_lon();
847         double lat = nav->get_lat();
848
849         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
850         {
851             double odist = fgGetDouble("/sim/presets/offset-distance")
852                 * SG_NM_TO_METER;
853             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
854                 + 180.0;
855             while ( oaz >= 360.0 ) { oaz -= 360.0; }
856             double olat, olon, az2;
857             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
858
859             lat = olat;
860             lon = olon;
861         }
862
863         // presets
864         fgSetDouble("/sim/presets/longitude-deg",  lon );
865         fgSetDouble("/sim/presets/latitude-deg",  lat );
866
867         // other code depends on the actual values being set ...
868         fgSetDouble("/position/longitude-deg",  lon );
869         fgSetDouble("/position/latitude-deg",  lat );
870         fgSetDouble("/orientation/heading-deg", 
871                     fgGetDouble("/sim/presets/heading-deg") );
872
873         SG_LOG( SG_GENERAL, SG_INFO,
874                 "Position for " << id << ":" << freq << " is ("
875                 << lon << ", "<< lat << ")" );
876
877         return true;
878     } else {
879         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
880                 << id << ":" << freq );
881         return false;
882     }
883 }
884
885
886 // Set current_options lon/lat given an airport id and heading (degrees)
887 static bool fgSetPosFromFix( const string& id ) {
888     FGFix fix;
889
890     // set initial position from runway and heading
891     if ( current_fixlist->query( id.c_str(), &fix ) ) {
892         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
893                 << id );
894
895         double lon = fix.get_lon();
896         double lat = fix.get_lat();
897
898         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
899         {
900             double odist = fgGetDouble("/sim/presets/offset-distance")
901                 * SG_NM_TO_METER;
902             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
903                 + 180.0;
904             while ( oaz >= 360.0 ) { oaz -= 360.0; }
905             double olat, olon, az2;
906             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
907
908             lat = olat;
909             lon = olon;
910         }
911
912         // presets
913         fgSetDouble("/sim/presets/longitude-deg",  lon );
914         fgSetDouble("/sim/presets/latitude-deg",  lat );
915
916         // other code depends on the actual values being set ...
917         fgSetDouble("/position/longitude-deg",  lon );
918         fgSetDouble("/position/latitude-deg",  lat );
919         fgSetDouble("/orientation/heading-deg", 
920                     fgGetDouble("/sim/presets/heading-deg") );
921
922         SG_LOG( SG_GENERAL, SG_INFO,
923                 "Position for " << id << " is ("
924                 << lon << ", "<< lat << ")" );
925
926         return true;
927     } else {
928         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
929                 << id );
930         return false;
931     }
932 }
933
934
935 /**
936  * Initialize vor/ndb/ils/fix list management and query systems (as
937  * well as simple airport db list)
938  */
939 bool
940 fgInitNav ()
941 {
942     SG_LOG(SG_GENERAL, SG_INFO, "Loading Simple Airport List");
943     SGPath p_simple( globals->get_fg_root() );
944     p_simple.append( "Airports/basic.dat" );
945     FGAirportList *airports = new FGAirportList( p_simple.str() );
946     globals->set_airports( airports );
947
948     SG_LOG(SG_GENERAL, SG_INFO, "Loading Runway List");
949     SGPath p_runway( globals->get_fg_root() );
950     p_runway.append( "Airports/runways.dat" );
951     FGRunwayList *runways = new FGRunwayList( p_runway.str() );
952     globals->set_runways( runways );
953
954     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
955
956     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
957     current_navlist = new FGNavList;
958     SGPath p_nav( globals->get_fg_root() );
959     p_nav.append( "Navaids/default.nav" );
960     current_navlist->init( p_nav );
961
962     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
963     current_beacons = new FGMarkerBeacons;
964     current_beacons->init();
965     current_ilslist = new FGILSList;
966     SGPath p_ils( globals->get_fg_root() );
967     p_ils.append( "Navaids/default.ils" );
968     current_ilslist->init( p_ils );
969
970     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
971     current_fixlist = new FGFixList;
972     SGPath p_fix( globals->get_fg_root() );
973     p_fix.append( "Navaids/default.fix" );
974     current_fixlist->init( p_fix );
975
976     return true;
977 }
978
979
980 // Set the initial position based on presets (or defaults)
981 bool fgInitPosition() {
982     bool set_pos = false;
983
984     // If glideslope is specified, then calculate offset-distance or
985     // altitude relative to glide slope if either of those was not
986     // specified.
987     if ( fgGetDouble("/sim/presets/glideslope-deg") > 0.1 ) {
988         fgSetDistOrAltFromGlideSlope();
989     }
990
991     // Select ground or air start depending on if an altitude is
992     // specified (this choice can be refined later based on other
993     // input.)
994     if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
995         fgSetBool("/sim/presets/onground", false);
996     } else {
997         fgSetBool("/sim/presets/onground", true);
998     }
999
1000     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1001     // If not, check for an airport-id and use that.
1002     // If not, default to the middle of the KSFO field.
1003     // The default values for lon/lat are deliberately out of range
1004     // so that the airport-id can take effect; valid lon/lat will
1005     // override airport-id, however.
1006     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1007     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1008     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1009          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1010     {
1011         set_pos = true;
1012     }
1013
1014     string apt = fgGetString("/sim/presets/airport-id");
1015     string rwy_no = fgGetString("/sim/presets/runway");
1016     double hdg = fgGetDouble("/sim/presets/heading-deg");
1017     string vor = fgGetString("/sim/presets/vor-id");
1018     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1019     string ndb = fgGetString("/sim/presets/ndb-id");
1020     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1021     string fix = fgGetString("/sim/presets/fix");
1022
1023     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1024         // An airport + runway is requested
1025         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1026             // set tower position (a little off the heading for single
1027             // runway airports)
1028             fgSetTowerPosFromAirportID( apt, hdg );
1029             set_pos = true;
1030         }
1031     }
1032
1033     if ( !set_pos && !apt.empty() ) {
1034         // An airport is requested (find runway closest to hdg)
1035         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1036             // set tower position (a little off the heading for single
1037             // runway airports)
1038             fgSetTowerPosFromAirportID( apt, hdg );
1039             set_pos = true;
1040         }
1041     }
1042
1043     if ( !set_pos && !vor.empty() ) {
1044         // a VOR is requested
1045         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1046             set_pos = true;
1047         }
1048     }
1049
1050     if ( !set_pos && !ndb.empty() ) {
1051         // an NDB is requested
1052         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1053             set_pos = true;
1054         }
1055     }
1056
1057     if ( !set_pos && !fix.empty() ) {
1058         // a Fix is requested
1059         if ( fgSetPosFromFix( fix ) ) {
1060             set_pos = true;
1061         }
1062     }
1063
1064     if ( !set_pos ) {
1065         // No lon/lat specified, no airport specified, default to
1066         // middle of KSFO field.
1067         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1068         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1069     }
1070
1071     fgSetDouble( "/position/longitude-deg",
1072                  fgGetDouble("/sim/presets/longitude-deg") );
1073     fgSetDouble( "/position/latitude-deg",
1074                  fgGetDouble("/sim/presets/latitude-deg") );
1075     fgSetDouble( "/orientation/heading-deg",
1076                  fgGetDouble("/sim/presets/heading-deg") );
1077
1078     return true;
1079 }
1080
1081
1082 // General house keeping initializations
1083 bool fgInitGeneral() {
1084     string root;
1085
1086 #if defined(FX) && defined(XMESA)
1087     char *mesa_win_state;
1088 #endif
1089
1090     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1091     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1092
1093     root = globals->get_fg_root();
1094     if ( ! root.length() ) {
1095         // No root path set? Then bail ...
1096         SG_LOG( SG_GENERAL, SG_ALERT,
1097                 "Cannot continue without a path to the base package "
1098                 << "being defined." );
1099         exit(-1);
1100     }
1101     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1102
1103 #if defined(FX) && defined(XMESA)
1104     // initialize full screen flag
1105     globals->set_fullscreen(false);
1106     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1107         // Test for the MESA_GLX_FX env variable
1108         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1109             // test if we are fullscreen mesa/glide
1110             if ( (mesa_win_state[0] == 'f') ||
1111                  (mesa_win_state[0] == 'F') ) {
1112                 globals->set_fullscreen(true);
1113             }
1114         }
1115     }
1116 #endif
1117
1118     return true;
1119 }
1120
1121
1122 // Initialize the flight model subsystem.  This just creates the
1123 // object.  The actual fdm initialization is delayed until we get a
1124 // proper scenery elevation hit.  This is checked for in main.cxx
1125
1126 void fgInitFDM() {
1127
1128     if ( cur_fdm_state ) {
1129         delete cur_fdm_state;
1130         cur_fdm_state = 0;
1131     }
1132
1133     double dt = 1.0 / fgGetInt("/sim/model-hz");
1134     aircraft_dir = fgGetString("/sim/aircraft-dir");
1135     const string &model = fgGetString("/sim/flight-model");
1136
1137     try {
1138         if ( model == "larcsim" ) {
1139             cur_fdm_state = new FGLaRCsim( dt );
1140         } else if ( model == "jsb" ) {
1141             cur_fdm_state = new FGJSBsim( dt );
1142         } else if ( model == "ada" ) {
1143             cur_fdm_state = new FGADA( dt );
1144         } else if ( model == "balloon" ) {
1145             cur_fdm_state = new FGBalloonSim( dt );
1146         } else if ( model == "magic" ) {
1147             cur_fdm_state = new FGMagicCarpet( dt );
1148         } else if ( model == "ufo" ) {
1149             cur_fdm_state = new FGUFO( dt );
1150         } else if ( model == "external" ) {
1151             // external is a synonym for "--fdm=null" and is
1152             // maintained here for backwards compatibility
1153             cur_fdm_state = new FGNullFDM( dt );
1154         } else if ( model.find("network") == 0 ) {
1155             string host = "localhost";
1156             int port1 = 5501;
1157             int port2 = 5502;
1158             int port3 = 5503;
1159             string net_options = model.substr(8);
1160             string::size_type begin, end;
1161             begin = 0;
1162             // host
1163             end = net_options.find( ",", begin );
1164             if ( end != string::npos ) {
1165                 host = net_options.substr(begin, end - begin);
1166                 begin = end + 1;
1167             }
1168             // port1
1169             end = net_options.find( ",", begin );
1170             if ( end != string::npos ) {
1171                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1172                 begin = end + 1;
1173             }
1174             // port2
1175             end = net_options.find( ",", begin );
1176             if ( end != string::npos ) {
1177                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1178                 begin = end + 1;
1179             }
1180             // port3
1181             end = net_options.find( ",", begin );
1182             if ( end != string::npos ) {
1183                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1184                 begin = end + 1;
1185             }
1186             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1187         } else if ( model.find("pipe") == 0 ) {
1188             string pipe_path = model.substr(5);
1189             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1190         } else if ( model == "null" ) {
1191             cur_fdm_state = new FGNullFDM( dt );
1192         } else if ( model == "yasim" ) {
1193             cur_fdm_state = new YASim( dt );
1194         } else {
1195             SG_LOG(SG_GENERAL, SG_ALERT,
1196                    "Unrecognized flight model '" << model
1197                    << "', cannot init flight dynamics model.");
1198             exit(-1);
1199         }
1200     } catch ( ... ) {
1201         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1202         exit(-1);
1203     }
1204 }
1205
1206 static void printMat(const sgVec4 *mat, char *name="")
1207 {
1208     int i;
1209     SG_LOG(SG_GENERAL, SG_BULK, name );
1210     for(i=0; i<4; i++) {
1211         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1212                                     << " " << mat[i][2] << " " << mat[i][3] );
1213     }
1214 }
1215
1216 // Initialize view parameters
1217 void fgInitView() {
1218   // force update of model so that viewer can get some data...
1219   globals->get_aircraft_model()->update(0);
1220   // run update for current view so that data is current...
1221   globals->get_viewmgr()->update(0);
1222
1223   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1224   printMat(globals->get_current_view()->get_UP(),"UP");
1225   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1226   
1227 }
1228
1229
1230 SGTime *fgInitTime() {
1231     // Initialize time
1232     static const SGPropertyNode *longitude
1233         = fgGetNode("/position/longitude-deg");
1234     static const SGPropertyNode *latitude
1235         = fgGetNode("/position/latitude-deg");
1236     static const SGPropertyNode *cur_time_override
1237         = fgGetNode("/sim/time/cur-time-override", true);
1238
1239     SGPath zone( globals->get_fg_root() );
1240     zone.append( "Timezone" );
1241     SGTime *t = new SGTime( longitude->getDoubleValue()
1242                               * SGD_DEGREES_TO_RADIANS,
1243                             latitude->getDoubleValue()
1244                               * SGD_DEGREES_TO_RADIANS,
1245                             zone.str(),
1246                             cur_time_override->getLongValue() );
1247
1248     // Handle potential user specified time offsets
1249     time_t cur_time = t->get_cur_time();
1250     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1251     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1252     time_t aircraftLocalTime = 
1253         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1254
1255     // Okay, we now have six possible scenarios
1256     int offset = fgGetInt("/sim/startup/time-offset");
1257     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1258     if (offset_type == "system-offset") {
1259         globals->set_warp( offset );
1260     } else if (offset_type == "gmt-offset") {
1261         globals->set_warp( offset - (currGMT - systemLocalTime) );
1262     } else if (offset_type == "latitude-offset") {
1263         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1264     } else if (offset_type == "system") {
1265         globals->set_warp( offset - cur_time );
1266     } else if (offset_type == "gmt") {
1267         globals->set_warp( offset - currGMT );
1268     } else if (offset_type == "latitude") {
1269         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1270                            cur_time ); 
1271     } else {
1272         SG_LOG( SG_GENERAL, SG_ALERT,
1273                 "FG_TIME::Unsupported offset type " << offset_type );
1274         exit( -1 );
1275     }
1276
1277     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1278             << globals->get_warp() );
1279
1280     globals->set_warp_delta( 0 );
1281
1282     t->update( 0.0, 0.0,
1283                cur_time_override->getLongValue(),
1284                globals->get_warp() );
1285
1286     return t;
1287 }
1288
1289
1290 // This is the top level init routine which calls all the other
1291 // initialization routines.  If you are adding a subsystem to flight
1292 // gear, its initialization call should located in this routine.
1293 // Returns non-zero if a problem encountered.
1294 bool fgInitSubsystems() {
1295     // static const SGPropertyNode *longitude
1296     //     = fgGetNode("/sim/presets/longitude-deg");
1297     // static const SGPropertyNode *latitude
1298     //     = fgGetNode("/sim/presets/latitude-deg");
1299     // static const SGPropertyNode *altitude
1300     //     = fgGetNode("/sim/presets/altitude-ft");
1301
1302     fgLIGHT *l = &cur_light_params;
1303
1304     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1305     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1306
1307
1308     ////////////////////////////////////////////////////////////////////
1309     // Initialize the material property subsystem.
1310     ////////////////////////////////////////////////////////////////////
1311
1312     SGPath mpath( globals->get_fg_root() );
1313     mpath.append( "materials.xml" );
1314     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1315         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1316         exit(-1);
1317     }
1318
1319     ////////////////////////////////////////////////////////////////////
1320     // Initialize the event manager subsystem.
1321     ////////////////////////////////////////////////////////////////////
1322
1323     global_events.init();
1324
1325     // Output event stats every 60 seconds
1326     global_events.Register( "FGEventMgr::print_stats()",
1327                             &global_events, &FGEventMgr::print_stats,
1328                             60000 );
1329
1330
1331     ////////////////////////////////////////////////////////////////////
1332     // Initialize the scenery management subsystem.
1333     ////////////////////////////////////////////////////////////////////
1334
1335     if ( globals->get_tile_mgr()->init() ) {
1336         // Load the local scenery data
1337         double visibility_meters = fgGetDouble("/environment/visibility-m");
1338                 
1339         globals->get_tile_mgr()->update( visibility_meters );
1340     } else {
1341         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1342         exit(-1);
1343     }
1344
1345     // cause refresh of viewer scenery timestamps every 15 seconds...
1346     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1347                             globals->get_tile_mgr(),
1348                             &FGTileMgr::refresh_view_timestamps,
1349                             15000 );
1350
1351     SG_LOG( SG_GENERAL, SG_DEBUG,
1352             "Current terrain elevation after tile mgr init " <<
1353             globals->get_scenery()->get_cur_elev() );
1354
1355
1356     ////////////////////////////////////////////////////////////////////
1357     // Initialize the flight model subsystem.
1358     ////////////////////////////////////////////////////////////////////
1359
1360     fgInitFDM();
1361         
1362     // allocates structures so must happen before any of the flight
1363     // model or control parameters are set
1364     fgAircraftInit();   // In the future this might not be the case.
1365
1366
1367     ////////////////////////////////////////////////////////////////////
1368     // Initialize the view manager subsystem.
1369     ////////////////////////////////////////////////////////////////////
1370
1371     fgInitView();
1372
1373
1374     ////////////////////////////////////////////////////////////////////
1375     // Initialize the lighting subsystem.
1376     ////////////////////////////////////////////////////////////////////
1377
1378     // fgUpdateSunPos() needs a few position and view parameters set
1379     // so it can calculate local relative sun angle and a few other
1380     // things for correctly orienting the sky.
1381     fgUpdateSunPos();
1382     fgUpdateMoonPos();
1383     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1384                             60000);
1385     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1386                             60000);
1387
1388     // Initialize Lighting interpolation tables
1389     l->Init();
1390
1391     // force one lighting update to make it right to start with...
1392     l->Update();
1393     // update the lighting parameters (based on sun angle)
1394     global_events.Register( "fgLight::Update()",
1395                             &cur_light_params, &fgLIGHT::Update,
1396                             30000 );
1397
1398
1399     ////////////////////////////////////////////////////////////////////
1400     // Create and register the logger.
1401     ////////////////////////////////////////////////////////////////////
1402     
1403     globals->add_subsystem("logger", new FGLogger);
1404
1405
1406 #if defined(HAVE_PLIB_PSL)
1407     ////////////////////////////////////////////////////////////////////
1408     // Create and register the script manager.
1409     ////////////////////////////////////////////////////////////////////
1410
1411     globals->add_subsystem("scripting", new FGScriptMgr);
1412 #endif // HAVE_PLIB_PSL
1413
1414
1415     ////////////////////////////////////////////////////////////////////
1416     // Create and register the XML GUI.
1417     ////////////////////////////////////////////////////////////////////
1418
1419     globals->add_subsystem("gui", new NewGUI, FGSubsystemMgr::INIT);
1420
1421
1422     ////////////////////////////////////////////////////////////////////
1423     // Initialize the local time subsystem.
1424     ////////////////////////////////////////////////////////////////////
1425
1426     // update the current timezone each 30 minutes
1427     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1428                             30*60*1000 );
1429
1430
1431     ////////////////////////////////////////////////////////////////////
1432     // Initialize the weather subsystem.
1433     ////////////////////////////////////////////////////////////////////
1434
1435     // Initialize the weather modeling subsystem
1436 #ifdef FG_WEATHERCM
1437     // Initialize the WeatherDatabase
1438     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1439     sgVec3 position;
1440     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1441                current_aircraft.fdm_state->get_Longitude(),
1442                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1443     double init_vis = fgGetDouble("/environment/visibility-m");
1444
1445     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1446
1447     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1448     {
1449       working_type = FGLocalWeatherDatabase::use_internet;
1450     } else {
1451       working_type = FGLocalWeatherDatabase::default_mode;
1452     }
1453     
1454     if ( init_vis > 0 ) {
1455       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1456         new FGLocalWeatherDatabase( position,
1457                                     globals->get_fg_root(),
1458                                     working_type,
1459                                     init_vis );
1460     } else {
1461       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1462         new FGLocalWeatherDatabase( position,
1463                                     globals->get_fg_root(),
1464                                     working_type );
1465     }
1466
1467     // cout << theFGLocalWeatherDatabase << endl;
1468     // cout << "visibility = " 
1469     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1470
1471     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1472
1473     // register the periodic update of the weather
1474     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1475                             30000);
1476 #else
1477     globals->add_subsystem("environment", new FGEnvironmentMgr);
1478 #endif
1479
1480 #ifdef FG_USE_CLOUDS_3D
1481     ////////////////////////////////////////////////////////////////////
1482     // Initialize the 3D cloud subsystem.
1483     ////////////////////////////////////////////////////////////////////
1484     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1485         static const SGPropertyNode *longitude
1486            = fgGetNode("/sim/presets/longitude-deg");
1487         static const SGPropertyNode *latitude
1488            = fgGetNode("/sim/presets/latitude-deg");
1489         static const SGPropertyNode *altitude
1490            = fgGetNode("/sim/presets/altitude-ft");
1491
1492         SGPath cloud_path(globals->get_fg_root());
1493 #if 0
1494         cloud_path.append("Textures/Sky/scattered.rgba");
1495         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1496
1497         SGTexture tx;
1498         tx.read_rgba_texture(cloud_path.c_str());
1499         if ( !sgCloud3d->Load( tx.texture(), tx.width(),
1500 #else
1501         cloud_path.append("large.sky");
1502         if ( !sgCloud3d->Load( cloud_path.str(),
1503 #endif
1504                                latitude->getDoubleValue(),
1505                                longitude->getDoubleValue()) )
1506         {
1507             fgSetBool("/sim/rendering/clouds3d", false);
1508             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1509         }
1510         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1511     }
1512 #endif
1513
1514     ////////////////////////////////////////////////////////////////////
1515     // Initialise ATC display system
1516     ////////////////////////////////////////////////////////////////////
1517
1518     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1519     globals->set_ATC_display(new FGATCDisplay);
1520     globals->get_ATC_display()->init(); 
1521
1522     ////////////////////////////////////////////////////////////////////
1523     // Initialise the ATC Manager 
1524     ////////////////////////////////////////////////////////////////////
1525
1526     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1527     globals->set_ATC_mgr(new FGATCMgr);
1528     globals->get_ATC_mgr()->init(); 
1529     
1530     ////////////////////////////////////////////////////////////////////
1531     // Initialise the AI Manager 
1532     ////////////////////////////////////////////////////////////////////
1533
1534     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1535     globals->set_AI_mgr(new FGAIMgr);
1536     globals->get_AI_mgr()->init();
1537
1538
1539 #ifdef ENABLE_AUDIO_SUPPORT
1540     ////////////////////////////////////////////////////////////////////
1541     // Initialize the sound subsystem.
1542     ////////////////////////////////////////////////////////////////////
1543
1544     globals->set_soundmgr(new SGSoundMgr);
1545     globals->get_soundmgr()->init();
1546     globals->get_soundmgr()->bind();
1547
1548
1549     ////////////////////////////////////////////////////////////////////
1550     // Initialize the sound-effects subsystem.
1551     ////////////////////////////////////////////////////////////////////
1552
1553     globals->add_subsystem("fx", new FGFX);
1554     
1555 #endif
1556
1557     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1558     globals->add_subsystem("systems", new FGSystemMgr);
1559
1560     ////////////////////////////////////////////////////////////////////
1561     // Initialize the radio stack subsystem.
1562     ////////////////////////////////////////////////////////////////////
1563
1564     current_radiostack = new FGRadioStack;
1565     current_radiostack->init();
1566     current_radiostack->bind();
1567
1568
1569     ////////////////////////////////////////////////////////////////////
1570     // Initialize the cockpit subsystem
1571     ////////////////////////////////////////////////////////////////////
1572
1573     if( fgCockpitInit( &current_aircraft )) {
1574         // Cockpit initialized ok.
1575     } else {
1576         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1577         exit(-1);
1578     }
1579
1580
1581     ////////////////////////////////////////////////////////////////////
1582     // Initialize the autopilot subsystem.
1583     ////////////////////////////////////////////////////////////////////
1584
1585     globals->set_autopilot(new FGAutopilot);
1586     globals->get_autopilot()->init();
1587     globals->get_autopilot()->bind();
1588
1589                                 // FIXME: these should go in the
1590                                 // GUI initialization code, not here.
1591     fgAPAdjustInit();
1592     NewTgtAirportInit();
1593     NewHeadingInit();
1594     NewAltitudeInit();
1595
1596     ////////////////////////////////////////////////////////////////////
1597     // Initialize I/O subsystem.
1598     ////////////////////////////////////////////////////////////////////
1599
1600     globals->get_io()->init();
1601     globals->get_io()->bind();
1602
1603
1604     ////////////////////////////////////////////////////////////////////
1605     // Add a new 2D panel.
1606     ////////////////////////////////////////////////////////////////////
1607
1608     string panel_path = fgGetString("/sim/panel/path",
1609                                     "Panels/Default/default.xml");
1610
1611     globals->set_current_panel( fgReadPanel(panel_path) );
1612     if (globals->get_current_panel() == 0) {
1613         SG_LOG( SG_INPUT, SG_ALERT, 
1614                 "Error reading new panel from " << panel_path );
1615     } else {
1616         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1617         globals->get_current_panel()->init();
1618         globals->get_current_panel()->bind();
1619     }
1620
1621     
1622     ////////////////////////////////////////////////////////////////////
1623     // Initialize the default (kludged) properties.
1624     ////////////////////////////////////////////////////////////////////
1625
1626     fgInitProps();
1627
1628
1629     ////////////////////////////////////////////////////////////////////
1630     // Initialize the controls subsystem.
1631     ////////////////////////////////////////////////////////////////////
1632
1633     globals->get_controls()->init();
1634     globals->get_controls()->bind();
1635
1636
1637     ////////////////////////////////////////////////////////////////////
1638     // Initialize the input subsystem.
1639     ////////////////////////////////////////////////////////////////////
1640
1641     globals->add_subsystem("input", new FGInput);
1642
1643
1644     ////////////////////////////////////////////////////////////////////
1645     // Initialize the replay subsystem
1646     ////////////////////////////////////////////////////////////////////
1647     globals->add_subsystem("replay", new FGReplay);
1648
1649     ////////////////////////////////////////////////////////////////////
1650     // Bind and initialize subsystems.
1651     ////////////////////////////////////////////////////////////////////
1652
1653     globals->get_subsystem_mgr()->bind();
1654     globals->get_subsystem_mgr()->init();
1655
1656
1657 #ifdef FG_MPLAYER_AS
1658     ////////////////////////////////////////////////////////////////////
1659     // Initialize multiplayer subsystem
1660     ////////////////////////////////////////////////////////////////////
1661
1662     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1663     globals->get_multiplayer_tx_mgr()->init();
1664
1665     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1666     globals->get_multiplayer_rx_mgr()->init();
1667 #endif
1668
1669     ////////////////////////////////////////////////////////////////////////
1670     // End of subsystem initialization.
1671     ////////////////////////////////////////////////////////////////////
1672
1673     SG_LOG( SG_GENERAL, SG_INFO, endl);
1674
1675                                 // Save the initial state for future
1676                                 // reference.
1677     globals->saveInitialState();
1678
1679     return true;
1680 }
1681
1682
1683 void fgReInitSubsystems()
1684 {
1685     // static const SGPropertyNode *longitude
1686     //     = fgGetNode("/sim/presets/longitude-deg");
1687     // static const SGPropertyNode *latitude
1688     //     = fgGetNode("/sim/presets/latitude-deg");
1689     static const SGPropertyNode *altitude
1690         = fgGetNode("/sim/presets/altitude-ft");
1691     static const SGPropertyNode *master_freeze
1692         = fgGetNode("/sim/freeze/master");
1693
1694     SG_LOG( SG_GENERAL, SG_INFO,
1695             "fgReInitSubsystems(): /position/altitude = "
1696             << altitude->getDoubleValue() );
1697
1698     bool freeze = master_freeze->getBoolValue();
1699     if ( !freeze ) {
1700         fgSetBool("/sim/freeze/master", true);
1701     }
1702
1703     // Initialize the FDM
1704     fgInitFDM();
1705     
1706     // allocates structures so must happen before any of the flight
1707     // model or control parameters are set
1708     fgAircraftInit();   // In the future this might not be the case.
1709
1710     // reload offsets from config defaults
1711     globals->get_viewmgr()->reinit();
1712
1713     fgInitView();
1714
1715     globals->get_controls()->reset_all();
1716     globals->get_autopilot()->reset();
1717
1718     fgUpdateSunPos();
1719     fgUpdateMoonPos();
1720     cur_light_params.Update();
1721     fgUpdateLocalTime();
1722
1723     if ( !freeze ) {
1724         fgSetBool("/sim/freeze/master", false);
1725     }
1726 }
1727