]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Started new, XML-configurable GUI subsystem.
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #ifdef HAVE_WINDOWS_H
35 #  include <windows.h>
36 #endif
37
38 #include <GL/glut.h>
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>             // strcmp()
43
44
45 #if defined( unix ) || defined( __CYGWIN__ )
46 #  include <unistd.h>           // for gethostname()
47 #endif
48
49 // work around a stdc++ lib bug in some versions of linux, but doesn't
50 // seem to hurt to have this here for all versions of Linux.
51 #ifdef linux
52 #  define _G_NO_EXTERN_TEMPLATES
53 #endif
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/exception.hxx>
57
58 #include STL_STRING
59
60 #include <simgear/constants.h>
61 #include <simgear/debug/logstream.hxx>
62 #include <simgear/math/point3d.hxx>
63 #include <simgear/math/polar3d.hxx>
64 #include <simgear/math/sg_geodesy.hxx>
65 #include <simgear/misc/sg_path.hxx>
66 #include <simgear/sky/clouds3d/SkySceneLoader.hpp>
67 #include <simgear/sky/clouds3d/SkyUtil.hpp>
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/atislist.hxx>
78 #include <ATC/towerlist.hxx>
79 #include <ATC/approachlist.hxx>
80 #include <ATC/AIMgr.hxx>
81 #include <Autopilot/auto_gui.hxx>
82 #include <Autopilot/newauto.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/radiostack.hxx>
85 #include <Cockpit/steam.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
88 #include <FDM/ADA.hxx>
89 #include <FDM/Balloon.h>
90 #include <FDM/ExternalNet/ExternalNet.hxx>
91 #include <FDM/JSBSim/JSBSim.hxx>
92 #include <FDM/LaRCsim.hxx>
93 #include <FDM/MagicCarpet.hxx>
94 #include <FDM/UFO.hxx>
95 #include <FDM/NullFDM.hxx>
96 #include <FDM/YASim/YASim.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Include/general.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 // #include <Joystick/joystick.hxx>
102 #include <Objects/matlib.hxx>
103 #include <Model/acmodel.hxx>
104 #include <Navaids/fixlist.hxx>
105 #include <Navaids/ilslist.hxx>
106 #include <Navaids/mkrbeacons.hxx>
107 #include <Navaids/navlist.hxx>
108 #include <Scenery/scenery.hxx>
109 #include <Scenery/tilemgr.hxx>
110 #include <Sound/fg_fx.hxx>
111 #include <Sound/soundmgr.hxx>
112 #include <Systems/system_mgr.hxx>
113 #include <Time/FGEventMgr.hxx>
114 #include <Time/light.hxx>
115 #include <Time/sunpos.hxx>
116 #include <Time/moonpos.hxx>
117 #include <Time/tmp.hxx>
118
119 #ifdef FG_WEATHERCM
120 #  include <WeatherCM/FGLocalWeatherDatabase.h>
121 #else
122 #  include <Environment/environment_mgr.hxx>
123 #endif
124
125 #include "fg_init.hxx"
126 #include "fg_io.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "options.hxx"
130 #include "globals.hxx"
131 #include "logger.hxx"
132 #include "viewmgr.hxx"
133
134 #if defined(FX) && defined(XMESA)
135 #include <GL/xmesa.h>
136 #endif
137
138 SG_USING_STD(string);
139
140 extern const char *default_root;
141
142 SkySceneLoader *sgCloud3d;
143
144 // Read in configuration (file and command line) and just set fg_root
145 bool fgInitFGRoot ( int argc, char **argv ) {
146     string root;
147     char* envp;
148
149     // First parse command line options looking for fg-root, this will
150     // override anything specified in a config file
151     root = fgScanForRoot(argc, argv);
152
153 #if defined( unix ) || defined( __CYGWIN__ )
154     // Next check home directory for .fgfsrc.hostname file
155     if ( root.empty() ) {
156         envp = ::getenv( "HOME" );
157         if ( envp != NULL ) {
158             SGPath config( envp );
159             config.append( ".fgfsrc" );
160             char name[256];
161             gethostname( name, 256 );
162             config.concat( "." );
163             config.concat( name );
164             root = fgScanForRoot(config.str());
165         }
166     }
167 #endif
168
169     // Next check home directory for .fgfsrc file
170     if ( root.empty() ) {
171         envp = ::getenv( "HOME" );
172         if ( envp != NULL ) {
173             SGPath config( envp );
174             config.append( ".fgfsrc" );
175             root = fgScanForRoot(config.str());
176         }
177     }
178     
179     // Next check if fg-root is set as an env variable
180     if ( root.empty() ) {
181         envp = ::getenv( "FG_ROOT" );
182         if ( envp != NULL ) {
183             root = envp;
184         }
185     }
186
187     // Otherwise, default to a random compiled-in location if we can't
188     // find fg-root any other way.
189     if ( root.empty() ) {
190 #if defined( __CYGWIN__ )
191         root = "/FlightGear";
192 #elif defined( WIN32 )
193         root = "\\FlightGear";
194 #elif defined( macintosh )
195         root = "";
196 #else
197         root = PKGLIBDIR;
198 #endif
199     }
200
201     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
202     globals->set_fg_root(root);
203
204     return true;
205 }
206
207
208 // Return the current base package version
209 string fgBasePackageVersion() {
210     SGPath base_path( globals->get_fg_root() );
211     base_path.append("version");
212
213     sg_gzifstream in( base_path.str() );
214     if ( !in.is_open() ) {
215         SGPath old_path( globals->get_fg_root() );
216         old_path.append( "Thanks" );
217         sg_gzifstream old( old_path.str() );
218         if ( !old.is_open() ) {
219             return "[none]";
220         } else {
221             return "[old version]";
222         }
223     }
224
225     string version;
226     in >> version;
227
228     return version;
229 }
230
231
232 // Initialize the localization
233 SGPropertyNode *fgInitLocale(const char *language) {
234    SGPropertyNode *c_node = NULL, *d_node = NULL;
235    SGPropertyNode *intl = fgGetNode("/sim/intl");
236
237    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
238
239    // localization not defined
240    if (!intl)
241       return NULL;
242
243    //
244    // Select the proper language from the list
245    //
246    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
247    for (unsigned int i = 0; i < locale.size(); i++) {
248
249       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
250       for (unsigned int j = 0; j < lang.size(); j++) {
251
252          if (!strcmp(lang[j]->getStringValue(), language)) {
253             c_node = locale[i];
254             break;
255          }
256       }
257    }
258
259
260    // Get the defaults
261    d_node = intl->getChild("locale");
262    if (!c_node)
263       c_node = d_node;
264
265    // Check for localized font
266    SGPropertyNode *font_n = c_node->getNode("font", true);
267    if ( !strcmp(font_n->getStringValue(), "") )
268       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
269
270
271    //
272    // Load the default strings
273    //
274    SGPath d_path( globals->get_fg_root() );
275
276    const char *d_path_str = d_node->getStringValue("strings");
277    if (!d_path_str) {
278       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
279       return NULL;
280    }
281
282    d_path.append(d_path_str);
283    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
284                                   << d_path.str());
285
286    SGPropertyNode *strings = c_node->getNode("strings");
287    try {
288       readProperties(d_path.str(), strings);
289    } catch (const sg_exception &e) {
290       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
291       return NULL;
292    }
293
294    //
295    // Load the language specific strings
296    //
297    if (c_node != d_node) {
298       SGPath c_path( globals->get_fg_root() );
299
300       const char *c_path_str = c_node->getStringValue("strings");
301       if (!c_path_str) {
302          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
303          return NULL;
304       }
305
306       c_path.append(c_path_str);
307       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
308                                      << c_path.str());
309
310       try {
311          readProperties(c_path.str(), strings);
312       } catch (const sg_exception &e) {
313          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
314          return NULL;
315       }
316    }
317
318    return c_node;
319 }
320
321
322
323 // Initialize the localization routines
324 bool fgDetectLanguage() {
325     char *language = ::getenv("LANG");
326
327     if (language == NULL) {
328         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
329         language = "C";
330     }
331
332     SGPropertyNode *locale = fgInitLocale(language);
333     if (!locale) {
334        cerr << "No internationalization settings specified in preferences.xml"
335             << endl;
336
337        return false;
338     }
339
340     globals->set_locale( locale );
341
342     return true;
343 }
344
345 // Attempt to locate and parse the various non-XML config files in order
346 // from least precidence to greatest precidence
347 static void
348 do_options (int argc, char ** argv)
349 {
350     // Check for $fg_root/system.fgfsrc
351     SGPath config( globals->get_fg_root() );
352     config.append( "system.fgfsrc" );
353     fgParseOptions(config.str());
354
355 #if defined( unix ) || defined( __CYGWIN__ )
356     char name[256];
357     // Check for $fg_root/system.fgfsrc.hostname
358     gethostname( name, 256 );
359     config.concat( "." );
360     config.concat( name );
361     fgParseOptions(config.str());
362 #endif
363
364     // Check for ~/.fgfsrc
365     char* envp = ::getenv( "HOME" );
366     if ( envp != NULL ) {
367         config.set( envp );
368         config.append( ".fgfsrc" );
369         fgParseOptions(config.str());
370     }
371
372 #if defined( unix ) || defined( __CYGWIN__ )
373     // Check for ~/.fgfsrc.hostname
374     gethostname( name, 256 );
375     config.concat( "." );
376     config.concat( name );
377     fgParseOptions(config.str());
378 #endif
379
380     // Parse remaining command line options
381     // These will override anything specified in a config file
382     fgParseArgs(argc, argv);
383 }
384
385
386 // Read in configuration (file and command line)
387 bool fgInitConfig ( int argc, char **argv ) {
388
389                                 // First, set some sane default values
390     fgSetDefaults();
391
392     // Read global preferences from $FG_ROOT/preferences.xml
393     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
394     fgLoadProps("preferences.xml", globals->get_props());
395     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
396
397     // Detect the required language as early as possible
398     if (fgDetectLanguage() != true)
399        return false;
400
401     // Read the default aircraft config file.
402     do_options(argc, argv);     // preparse options for default aircraft
403     string aircraft = fgGetString("/sim/aircraft", "");
404     if (aircraft.size() > 0) {
405       SGPath aircraft_path(globals->get_fg_root());
406       aircraft_path.append("Aircraft");
407       aircraft_path.append(aircraft);
408       aircraft_path.concat("-set.xml");
409       SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
410              << " from " << aircraft_path.str());
411       try {
412         readProperties(aircraft_path.str(), globals->get_props());
413       } catch (const sg_exception &e) {
414         string message = "Error reading default aircraft: ";
415         message += e.getFormattedMessage();
416         SG_LOG(SG_INPUT, SG_ALERT, message);
417         exit(2);
418       }
419     } else {
420       SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
421     }
422
423     do_options(argc, argv);
424
425     return true;
426 }
427
428
429 // find basic airport location info from airport database
430 bool fgFindAirportID( const string& id, FGAirport *a ) {
431     if ( id.length() ) {
432         SGPath path( globals->get_fg_root() );
433         path.append( "Airports" );
434         path.append( "simple.mk4" );
435         FGAirports airports( path.c_str() );
436
437         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
438
439         if ( ! airports.search( id, a ) ) {
440             SG_LOG( SG_GENERAL, SG_ALERT,
441                     "Failed to find " << id << " in " << path.str() );
442             return false;
443         }
444     } else {
445         return false;
446     }
447
448     SG_LOG( SG_GENERAL, SG_INFO,
449             "Position for " << id << " is ("
450             << a->longitude << ", "
451             << a->latitude << ")" );
452
453     return true;
454 }
455
456
457 // Set current_options lon/lat given an airport id
458 bool fgSetPosFromAirportID( const string& id ) {
459     FGAirport a;
460     // double lon, lat;
461
462     SG_LOG( SG_GENERAL, SG_INFO,
463             "Attempting to set starting position from airport code " << id );
464
465     if ( fgFindAirportID( id, &a ) ) {
466         fgSetDouble("/position/longitude-deg",  a.longitude );
467         fgSetDouble("/position/latitude-deg",  a.latitude );
468         SG_LOG( SG_GENERAL, SG_INFO,
469                 "Position for " << id << " is ("
470                 << a.longitude << ", "
471                 << a.latitude << ")" );
472
473         return true;
474     } else {
475         return false;
476     }
477
478 }
479
480
481
482 // Set current tower position lon/lat given an airport id
483 bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
484     FGAirport a;
485     // tower height hard coded for now...
486     float towerheight=50.0f;
487
488     // make a little off the heading for 1 runway airports...
489     float fudge_lon = fabs(sin(hdg)) * .003f;
490     float fudge_lat = .003f - fudge_lon;
491
492     if ( fgFindAirportID( id, &a ) ) {
493         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
494         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
495         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
496         return true;
497     } else {
498         return false;
499     }
500
501 }
502
503
504 // Set current_options lon/lat given an airport id and heading (degrees)
505 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
506     FGRunway r;
507     FGRunway found_r;
508     double found_dir = 0.0;
509
510     if ( id.length() ) {
511         // set initial position from runway and heading
512
513         SGPath path( globals->get_fg_root() );
514         path.append( "Airports" );
515         path.append( "runways.mk4" );
516         FGRunways runways( path.c_str() );
517
518         SG_LOG( SG_GENERAL, SG_INFO,
519                 "Attempting to set starting position from runway code "
520                 << id << " heading " << tgt_hdg );
521
522         // SGPath inpath( globals->get_fg_root() );
523         // inpath.append( "Airports" );
524         // inpath.append( "apt_simple" );
525         // airports.load( inpath.c_str() );
526
527         // SGPath outpath( globals->get_fg_root() );
528         // outpath.append( "Airports" );
529         // outpath.append( "simple.gdbm" );
530         // airports.dump_gdbm( outpath.c_str() );
531
532         if ( ! runways.search( id, &r ) ) {
533             SG_LOG( SG_GENERAL, SG_ALERT,
534                     "Failed to find " << id << " in database." );
535             return false;
536         }
537
538         double diff;
539         double min_diff = 360.0;
540
541         while ( r.id == id ) {
542             // forward direction
543             diff = tgt_hdg - r.heading;
544             while ( diff < -180.0 ) { diff += 360.0; }
545             while ( diff >  180.0 ) { diff -= 360.0; }
546             diff = fabs(diff);
547             SG_LOG( SG_GENERAL, SG_INFO,
548                     "Runway " << r.rwy_no << " heading = " << r.heading <<
549                     " diff = " << diff );
550             if ( diff < min_diff ) {
551                 min_diff = diff;
552                 found_r = r;
553                 found_dir = 0;
554             }
555
556             // reverse direction
557             diff = tgt_hdg - r.heading - 180.0;
558             while ( diff < -180.0 ) { diff += 360.0; }
559             while ( diff >  180.0 ) { diff -= 360.0; }
560             diff = fabs(diff);
561             SG_LOG( SG_GENERAL, SG_INFO,
562                     "Runway -" << r.rwy_no << " heading = " <<
563                     r.heading + 180.0 <<
564                     " diff = " << diff );
565             if ( diff < min_diff ) {
566                 min_diff = diff;
567                 found_r = r;
568                 found_dir = 180.0;
569             }
570
571             runways.next( &r );
572         }
573
574         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
575                 << " + " << found_dir );
576
577     } else {
578         return false;
579     }
580
581     double heading = found_r.heading + found_dir;
582     while ( heading >= 360.0 ) { heading -= 360.0; }
583
584     double lat2, lon2, az2;
585     double azimuth = found_r.heading + found_dir + 180.0;
586     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
587
588     SG_LOG( SG_GENERAL, SG_INFO,
589             "runway =  " << found_r.lon << ", " << found_r.lat
590             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
591             << " heading = " << azimuth );
592     
593     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
594                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
595                         &lat2, &lon2, &az2 );
596
597     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > SG_EPSILON ) {
598         double olat, olon;
599         double odist = fgGetDouble("/sim/startup/offset-distance");
600         odist *= SG_NM_TO_METER;
601         double oaz = azimuth;
602         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > SG_EPSILON ) {
603             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
604         }
605         while ( oaz >= 360.0 ) { oaz -= 360.0; }
606         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
607         lat2=olat;
608         lon2=olon;
609     }
610         
611     fgSetDouble("/position/longitude-deg",  lon2 );
612     fgSetDouble("/position/latitude-deg",  lat2 );
613     fgSetDouble("/orientation/heading-deg", heading );
614
615     SG_LOG( SG_GENERAL, SG_INFO,
616             "Position for " << id << " is ("
617             << lon2 << ", "
618             << lat2 << ") new heading is "
619             << heading );
620
621     return true;
622 }
623
624
625 void fgSetPosFromGlideSlope(void) {
626     double gs = fgGetDouble("/velocities/glideslope");
627     double od = fgGetDouble("/sim/startup/offset-distance");
628     double alt = fgGetDouble("/position/altitude-ft");
629     
630     //if glideslope and offset-distance are set and altitude is
631     //not, calculate the initial altitude
632     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
633         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
634         alt = fabs(od*tan(gs));
635         fgSetDouble("/position/altitude-ft",alt);
636         fgSetBool("/sim/startup/onground", false);
637         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
638     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
639         od  = alt/tan(gs);
640         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
641         fgSetDouble("/sim/startup/offset-distance",od);
642         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
643                                        << od  << " nm");
644     } else if( fabs(gs) > 0.01 ) {
645         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
646                                   << " or offset-distance.  Resetting"
647                                   << " glideslope to zero" );
648         fgSetDouble("/velocities/glideslope",0);                                  
649     }                              
650                                       
651 }                       
652
653 // General house keeping initializations
654 bool fgInitGeneral( void ) {
655     string root;
656
657 #if defined(FX) && defined(XMESA)
658     char *mesa_win_state;
659 #endif
660
661     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
662     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
663
664     root = globals->get_fg_root();
665     if ( ! root.length() ) {
666         // No root path set? Then bail ...
667         SG_LOG( SG_GENERAL, SG_ALERT,
668                 "Cannot continue without a path to the base package "
669                 << "being defined." );
670         exit(-1);
671     }
672     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
673
674 #if defined(FX) && defined(XMESA)
675     // initialize full screen flag
676     globals->set_fullscreen(false);
677     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
678         // Test for the MESA_GLX_FX env variable
679         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
680             // test if we are fullscreen mesa/glide
681             if ( (mesa_win_state[0] == 'f') ||
682                  (mesa_win_state[0] == 'F') ) {
683                 globals->set_fullscreen(true);
684             }
685         }
686     }
687 #endif
688
689     return true;
690 }
691
692
693 // Initialize the flight model subsystem.  This just creates the
694 // object.  The actual fdm initialization is delayed until we get a
695 // proper scenery elevation hit.  This is checked for in main.cxx
696
697 void fgInitFDM() {
698
699     if ( cur_fdm_state ) {
700         delete cur_fdm_state;
701         cur_fdm_state = 0;
702     }
703
704     double dt = 1.0 / fgGetInt("/sim/model-hz");
705     aircraft_dir = fgGetString("/sim/aircraft-dir");
706     const string &model = fgGetString("/sim/flight-model");
707
708     try {
709         if ( model == "larcsim" ) {
710             cur_fdm_state = new FGLaRCsim( dt );
711         } else if ( model == "jsb" ) {
712             cur_fdm_state = new FGJSBsim( dt );
713         } else if ( model == "ada" ) {
714             cur_fdm_state = new FGADA( dt );
715         } else if ( model == "balloon" ) {
716             cur_fdm_state = new FGBalloonSim( dt );
717         } else if ( model == "magic" ) {
718             cur_fdm_state = new FGMagicCarpet( dt );
719         } else if ( model == "ufo" ) {
720             cur_fdm_state = new FGUFO( dt );
721         } else if ( model == "external" ) {
722             // external is a synonym for "--fdm=null" and is
723             // maintained here for backwards compatibility
724             cur_fdm_state = new FGNullFDM( dt );
725         } else if ( model.find("network") == 0 ) {
726             string host = "localhost";
727             int port1 = 5501;
728             int port2 = 5502;
729             int port3 = 5503;
730             string net_options = model.substr(8);
731             string::size_type begin, end;
732             begin = 0;
733             // host
734             end = net_options.find( ",", begin );
735             if ( end != string::npos ) {
736                 host = net_options.substr(begin, end - begin);
737                 begin = end + 1;
738             }
739             // port1
740             end = net_options.find( ",", begin );
741             if ( end != string::npos ) {
742                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
743                 begin = end + 1;
744             }
745             // port2
746             end = net_options.find( ",", begin );
747             if ( end != string::npos ) {
748                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
749                 begin = end + 1;
750             }
751             // port3
752             end = net_options.find( ",", begin );
753             if ( end != string::npos ) {
754                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
755                 begin = end + 1;
756             }
757             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
758         } else if ( model == "null" ) {
759             cur_fdm_state = new FGNullFDM( dt );
760         } else if ( model == "yasim" ) {
761             cur_fdm_state = new YASim( dt );
762         } else {
763             SG_LOG(SG_GENERAL, SG_ALERT,
764                    "Unrecognized flight model '" << model
765                    << "', cannot init flight dynamics model.");
766             exit(-1);
767         }
768     } catch ( ... ) {
769         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
770         exit(-1);
771     }
772 }
773
774 static void printMat(const sgVec4 *mat, char *name="")
775 {
776     int i;
777     cout << name << endl;
778     for(i=0; i<4; i++) {
779         cout <<"  "<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<" "<<mat[i][3]<<endl;
780     }
781     cout << endl;
782 }
783
784 // Initialize view parameters
785 void fgInitView() {
786   // force update of model so that viewer can get some data...
787   globals->get_aircraft_model()->update(0);
788   // run update for current view so that data is current...
789   globals->get_viewmgr()->update(0);
790
791   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
792   printMat(globals->get_current_view()->get_UP(),"UP");
793   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
794   
795 }
796
797
798 SGTime *fgInitTime() {
799     // Initialize time
800     static const SGPropertyNode *longitude
801         = fgGetNode("/position/longitude-deg");
802     static const SGPropertyNode *latitude
803         = fgGetNode("/position/latitude-deg");
804     static const SGPropertyNode *cur_time_override
805         = fgGetNode("/sim/time/cur-time-override", true);
806
807     SGPath zone( globals->get_fg_root() );
808     zone.append( "Timezone" );
809     SGTime *t = new SGTime( longitude->getDoubleValue()
810                               * SGD_DEGREES_TO_RADIANS,
811                             latitude->getDoubleValue()
812                               * SGD_DEGREES_TO_RADIANS,
813                             zone.str(),
814                             cur_time_override->getLongValue() );
815
816     // Handle potential user specified time offsets
817     time_t cur_time = t->get_cur_time();
818     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
819     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
820     time_t aircraftLocalTime = 
821         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
822
823     // Okay, we now have six possible scenarios
824     int offset = fgGetInt("/sim/startup/time-offset");
825     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
826     if (offset_type == "system-offset") {
827         globals->set_warp( offset );
828     } else if (offset_type == "gmt-offset") {
829         globals->set_warp( offset - (currGMT - systemLocalTime) );
830     } else if (offset_type == "latitude-offset") {
831         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
832     } else if (offset_type == "system") {
833         globals->set_warp( offset - cur_time );
834     } else if (offset_type == "gmt") {
835         globals->set_warp( offset - currGMT );
836     } else if (offset_type == "latitude") {
837         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
838                            cur_time ); 
839     } else {
840         SG_LOG( SG_GENERAL, SG_ALERT,
841                 "FG_TIME::Unsupported offset type " << offset_type );
842         exit( -1 );
843     }
844
845     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
846             << globals->get_warp() );
847
848     globals->set_warp_delta( 0 );
849
850     t->update( 0.0, 0.0,
851                cur_time_override->getLongValue(),
852                globals->get_warp() );
853
854     return t;
855 }
856
857
858 // This is the top level init routine which calls all the other
859 // initialization routines.  If you are adding a subsystem to flight
860 // gear, its initialization call should located in this routine.
861 // Returns non-zero if a problem encountered.
862 bool fgInitSubsystems( void ) {
863     static const SGPropertyNode *longitude
864         = fgGetNode("/position/longitude-deg");
865     static const SGPropertyNode *latitude
866         = fgGetNode("/position/latitude-deg");
867     static const SGPropertyNode *altitude
868         = fgGetNode("/position/altitude-ft");
869
870     fgLIGHT *l = &cur_light_params;
871
872     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
873     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
874
875
876     ////////////////////////////////////////////////////////////////////
877     // Initialize the material property subsystem.
878     ////////////////////////////////////////////////////////////////////
879
880     SGPath mpath( globals->get_fg_root() );
881     mpath.append( "materials.xml" );
882     if ( ! material_lib.load( mpath.str() ) ) {
883         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
884         exit(-1);
885     }
886
887     ////////////////////////////////////////////////////////////////////
888     // Initialize the event manager subsystem.
889     ////////////////////////////////////////////////////////////////////
890
891     global_events.init();
892
893     // Output event stats every 60 seconds
894     global_events.Register( "FGEventMgr::print_stats()",
895                             &global_events, &FGEventMgr::print_stats,
896                             60000 );
897
898
899     ////////////////////////////////////////////////////////////////////
900     // Initialize the scenery management subsystem.
901     ////////////////////////////////////////////////////////////////////
902
903     if ( global_tile_mgr.init() ) {
904         // Load the local scenery data
905         double visibility_meters = fgGetDouble("/environment/visibility-m");
906                 
907         global_tile_mgr.update( longitude->getDoubleValue(),
908                                 latitude->getDoubleValue(),
909                                 visibility_meters );
910     } else {
911         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
912         exit(-1);
913     }
914
915     // cause refresh of viewer scenery timestamps every 15 seconds...
916     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
917                             &global_tile_mgr, &FGTileMgr::refresh_view_timestamps,
918                             15000 );
919
920     SG_LOG( SG_GENERAL, SG_DEBUG,
921             "Current terrain elevation after tile mgr init " <<
922             globals->get_scenery()->get_cur_elev() );
923
924
925     ////////////////////////////////////////////////////////////////////
926     // Initialize the flight model subsystem.
927     ////////////////////////////////////////////////////////////////////
928
929     fgInitFDM();
930         
931     // allocates structures so must happen before any of the flight
932     // model or control parameters are set
933     fgAircraftInit();   // In the future this might not be the case.
934
935
936     ////////////////////////////////////////////////////////////////////
937     // Initialize the view manager subsystem.
938     ////////////////////////////////////////////////////////////////////
939
940     fgInitView();
941
942
943     ////////////////////////////////////////////////////////////////////
944     // Initialize the lighting subsystem.
945     ////////////////////////////////////////////////////////////////////
946
947     // fgUpdateSunPos() needs a few position and view parameters set
948     // so it can calculate local relative sun angle and a few other
949     // things for correctly orienting the sky.
950     fgUpdateSunPos();
951     fgUpdateMoonPos();
952     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
953                             60000);
954     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
955                             60000);
956
957     // Initialize Lighting interpolation tables
958     l->Init();
959
960     // force one lighting update to make it right to start with...
961     l->Update();
962     // update the lighting parameters (based on sun angle)
963     global_events.Register( "fgLight::Update()",
964                             &cur_light_params, &fgLIGHT::Update,
965                             30000 );
966
967
968     ////////////////////////////////////////////////////////////////////
969     // Create and register the logger.
970     ////////////////////////////////////////////////////////////////////
971     
972     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
973                                       "logger",
974                                       new FGLogger);
975
976
977     ////////////////////////////////////////////////////////////////////
978     // Create and register the XML GUI.
979     ////////////////////////////////////////////////////////////////////
980
981     globals->get_subsystem_mgr()->add(FGSubsystemMgr::INIT,
982                                       "gui",
983                                       new NewGUI);
984
985
986     ////////////////////////////////////////////////////////////////////
987     // Initialize the local time subsystem.
988     ////////////////////////////////////////////////////////////////////
989
990     // update the current timezone each 30 minutes
991     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
992                             30*60*1000 );
993
994
995     ////////////////////////////////////////////////////////////////////
996     // Initialize the weather subsystem.
997     ////////////////////////////////////////////////////////////////////
998
999     // Initialize the weather modeling subsystem
1000 #ifdef FG_WEATHERCM
1001     // Initialize the WeatherDatabase
1002     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1003     sgVec3 position;
1004     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1005                current_aircraft.fdm_state->get_Longitude(),
1006                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1007     double init_vis = fgGetDouble("/environment/visibility-m");
1008
1009     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1010
1011     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1012     {
1013       working_type = FGLocalWeatherDatabase::use_internet;
1014     } else {
1015       working_type = FGLocalWeatherDatabase::default_mode;
1016     }
1017     
1018     if ( init_vis > 0 ) {
1019       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1020         new FGLocalWeatherDatabase( position,
1021                                     globals->get_fg_root(),
1022                                     working_type,
1023                                     init_vis );
1024     } else {
1025       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1026         new FGLocalWeatherDatabase( position,
1027                                     globals->get_fg_root(),
1028                                     working_type );
1029     }
1030
1031     // cout << theFGLocalWeatherDatabase << endl;
1032     // cout << "visibility = " 
1033     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1034
1035     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1036
1037     // register the periodic update of the weather
1038     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1039                             30000);
1040 #else
1041     globals->get_environment_mgr()->init();
1042     globals->get_environment_mgr()->bind();
1043 #endif
1044
1045     ////////////////////////////////////////////////////////////////////
1046     // Initialize the 3D cloud subsystem.
1047     ////////////////////////////////////////////////////////////////////
1048     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1049         SGPath cloud_path(globals->get_fg_root());
1050         cloud_path.append("large.sky");
1051         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1052         if ( !sgCloud3d->Load( cloud_path.str(),
1053                                latitude->getDoubleValue(),
1054                                longitude->getDoubleValue()) )
1055         {
1056             fgSetBool("/sim/rendering/clouds3d", false);
1057             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1058         }
1059         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1060     }
1061
1062     ////////////////////////////////////////////////////////////////////
1063     // Initialize vor/ndb/ils/fix list management and query systems
1064     ////////////////////////////////////////////////////////////////////
1065
1066     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1067
1068     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
1069     current_navlist = new FGNavList;
1070     SGPath p_nav( globals->get_fg_root() );
1071     p_nav.append( "Navaids/default.nav" );
1072     current_navlist->init( p_nav );
1073
1074     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
1075     current_beacons = new FGMarkerBeacons;
1076     current_beacons->init();
1077     current_ilslist = new FGILSList;
1078     SGPath p_ils( globals->get_fg_root() );
1079     p_ils.append( "Navaids/default.ils" );
1080     current_ilslist->init( p_ils );
1081
1082     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1083     current_fixlist = new FGFixList;
1084     SGPath p_fix( globals->get_fg_root() );
1085     p_fix.append( "Navaids/default.fix" );
1086     current_fixlist->init( p_fix );
1087
1088     ////////////////////////////////////////////////////////////////////
1089     // Initialize ATC list management and query systems
1090     ////////////////////////////////////////////////////////////////////
1091
1092     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
1093     current_atislist = new FGATISList;
1094     SGPath p_atis( globals->get_fg_root() );
1095     p_atis.append( "ATC/default.atis" );
1096     current_atislist->init( p_atis );
1097
1098     SG_LOG(SG_GENERAL, SG_INFO, "  Tower");
1099     current_towerlist = new FGTowerList;
1100     SGPath p_tower( globals->get_fg_root() );
1101     p_tower.append( "ATC/default.tower" );
1102     current_towerlist->init( p_tower );
1103
1104     SG_LOG(SG_GENERAL, SG_INFO, "  Approach");
1105     current_approachlist = new FGApproachList;
1106     SGPath p_approach( globals->get_fg_root() );
1107     p_approach.append( "ATC/default.approach" );
1108     current_approachlist->init( p_approach );
1109
1110     ////////////////////////////////////////////////////////////////////
1111     // Initialise ATC display system
1112     ////////////////////////////////////////////////////////////////////
1113
1114     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1115     globals->set_ATC_display(new FGATCDisplay);
1116     globals->get_ATC_display()->init(); 
1117
1118     ////////////////////////////////////////////////////////////////////
1119     // Initialise the ATC Manager 
1120     ////////////////////////////////////////////////////////////////////
1121
1122     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1123     globals->set_ATC_mgr(new FGATCMgr);
1124     globals->get_ATC_mgr()->init(); 
1125     
1126     ////////////////////////////////////////////////////////////////////
1127     // Initialise the AI Manager 
1128     ////////////////////////////////////////////////////////////////////
1129
1130     if (fgGetBool("/sim/ai-traffic/enabled")) {
1131         SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1132         globals->set_AI_mgr(new FGAIMgr);
1133         globals->get_AI_mgr()->init();
1134     }
1135
1136 #ifdef ENABLE_AUDIO_SUPPORT
1137     ////////////////////////////////////////////////////////////////////
1138     // Initialize the sound subsystem.
1139     ////////////////////////////////////////////////////////////////////
1140
1141     globals->set_soundmgr(new FGSoundMgr);
1142     globals->get_soundmgr()->init();
1143     globals->get_soundmgr()->bind();
1144
1145
1146     ////////////////////////////////////////////////////////////////////
1147     // Initialize the sound-effects subsystem.
1148     ////////////////////////////////////////////////////////////////////
1149
1150     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1151                                       "fx",
1152                                       new FGFX);
1153     
1154
1155 #endif
1156
1157     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1158                                       "instrumentation",
1159                                       new FGInstrumentMgr);
1160     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1161                                       "systems",
1162                                       new FGSystemMgr);
1163
1164     ////////////////////////////////////////////////////////////////////
1165     // Initialize the radio stack subsystem.
1166     ////////////////////////////////////////////////////////////////////
1167
1168                                 // A textbook example of how FGSubsystem
1169                                 // should work...
1170     current_radiostack = new FGRadioStack;
1171     current_radiostack->init();
1172     current_radiostack->bind();
1173
1174
1175     ////////////////////////////////////////////////////////////////////
1176     // Initialize the cockpit subsystem
1177     ////////////////////////////////////////////////////////////////////
1178
1179     if( fgCockpitInit( &current_aircraft )) {
1180         // Cockpit initialized ok.
1181     } else {
1182         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1183         exit(-1);
1184     }
1185
1186
1187     ////////////////////////////////////////////////////////////////////
1188     // Initialize the autopilot subsystem.
1189     ////////////////////////////////////////////////////////////////////
1190
1191     globals->set_autopilot(new FGAutopilot);
1192     globals->get_autopilot()->init();
1193     globals->get_autopilot()->bind();
1194
1195                                 // FIXME: these should go in the
1196                                 // GUI initialization code, not here.
1197     fgAPAdjustInit();
1198     NewTgtAirportInit();
1199     NewHeadingInit();
1200     NewAltitudeInit();
1201
1202     ////////////////////////////////////////////////////////////////////
1203     // Initialize I/O subsystem.
1204     ////////////////////////////////////////////////////////////////////
1205
1206     globals->get_io()->init();
1207     globals->get_io()->bind();
1208
1209     // Initialize the 2D panel.
1210     string panel_path = fgGetString("/sim/panel/path",
1211                                     "Panels/Default/default.xml");
1212     current_panel = fgReadPanel(panel_path);
1213     if (current_panel == 0) {
1214         SG_LOG( SG_INPUT, SG_ALERT, 
1215                 "Error reading new panel from " << panel_path );
1216     } else {
1217         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1218         current_panel->init();
1219         current_panel->bind();
1220     }
1221
1222     
1223     ////////////////////////////////////////////////////////////////////
1224     // Initialize the default (kludged) properties.
1225     ////////////////////////////////////////////////////////////////////
1226
1227     fgInitProps();
1228
1229
1230     ////////////////////////////////////////////////////////////////////
1231     // Initialize the controls subsystem.
1232     ////////////////////////////////////////////////////////////////////
1233
1234     globals->get_controls()->init();
1235     globals->get_controls()->bind();
1236
1237
1238     ////////////////////////////////////////////////////////////////////
1239     // Initialize the steam subsystem.
1240     ////////////////////////////////////////////////////////////////////
1241
1242     globals->get_steam()->init();
1243     globals->get_steam()->bind();
1244
1245
1246     ////////////////////////////////////////////////////////////////////
1247     // Initialize the input subsystem.
1248     ////////////////////////////////////////////////////////////////////
1249
1250     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1251                                       "input",
1252                                       new FGInput);
1253
1254
1255     ////////////////////////////////////////////////////////////////////
1256     // Bind and initialize subsystems.
1257     ////////////////////////////////////////////////////////////////////
1258
1259     globals->get_subsystem_mgr()->bind();
1260     globals->get_subsystem_mgr()->init();
1261
1262
1263     ////////////////////////////////////////////////////////////////////////
1264     // End of subsystem initialization.
1265     ////////////////////////////////////////////////////////////////////
1266
1267     SG_LOG( SG_GENERAL, SG_INFO, endl);
1268
1269                                 // Save the initial state for future
1270                                 // reference.
1271     globals->saveInitialState();
1272
1273     return true;
1274 }
1275
1276
1277 void fgReInitSubsystems( void )
1278 {
1279     static const SGPropertyNode *longitude
1280         = fgGetNode("/position/longitude-deg");
1281     static const SGPropertyNode *latitude
1282         = fgGetNode("/position/latitude-deg");
1283     static const SGPropertyNode *altitude
1284         = fgGetNode("/position/altitude-ft");
1285     static const SGPropertyNode *master_freeze
1286         = fgGetNode("/sim/freeze/master");
1287
1288     SG_LOG( SG_GENERAL, SG_INFO,
1289             "fgReInitSubsystems(): /position/altitude = "
1290             << altitude->getDoubleValue() );
1291
1292     bool freeze = master_freeze->getBoolValue();
1293     if ( !freeze ) {
1294         fgSetBool("/sim/freeze/master", true);
1295     }
1296     
1297     // Initialize the Scenery Management subsystem
1298     // FIXME, what really needs to get initialized here, at the time
1299     // this was commented out, scenery.init() was a noop
1300     // scenery.init();
1301
1302     fgInitFDM();
1303     
1304     // allocates structures so must happen before any of the flight
1305     // model or control parameters are set
1306     fgAircraftInit();   // In the future this might not be the case.
1307
1308     // copy viewer settings into current-view path
1309     globals->get_viewmgr()->copyToCurrent();
1310
1311     fgInitView();
1312
1313     globals->get_controls()->reset_all();
1314     globals->get_autopilot()->reset();
1315
1316     fgUpdateSunPos();
1317     fgUpdateMoonPos();
1318     cur_light_params.Update();
1319     fgUpdateLocalTime();
1320
1321     if ( !freeze ) {
1322         fgSetBool("/sim/freeze/master", false);
1323     }
1324 }
1325