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