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