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