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