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