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