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