]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
91c7d082d44a17b8c948eb97b6e1006b9460f976
[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 // Preset 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         // presets
467         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
468         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
469
470         // other code depends on the actual postition being set so set
471         // that as well
472         fgSetDouble("/position/longitude-deg", a.longitude );
473         fgSetDouble("/position/latitude-deg", a.latitude );
474
475         SG_LOG( SG_GENERAL, SG_INFO,
476                 "Position for " << id << " is (" << a.longitude
477                 << ", " << a.latitude << ")" );
478
479         return true;
480     } else {
481         return false;
482     }
483
484 }
485
486
487
488 // Set current tower position lon/lat given an airport id
489 bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
490     FGAirport a;
491     // tower height hard coded for now...
492     float towerheight=50.0f;
493
494     // make a little off the heading for 1 runway airports...
495     float fudge_lon = fabs(sin(hdg)) * .003f;
496     float fudge_lat = .003f - fudge_lon;
497
498     if ( fgFindAirportID( id, &a ) ) {
499         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
500         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
501         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
502         return true;
503     } else {
504         return false;
505     }
506
507 }
508
509
510 // Set current_options lon/lat given an airport id and heading (degrees)
511 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
512     FGRunway r;
513     FGRunway found_r;
514     double found_dir = 0.0;
515
516     if ( id.length() ) {
517         // set initial position from runway and heading
518
519         SGPath path( globals->get_fg_root() );
520         path.append( "Airports" );
521         path.append( "runways.mk4" );
522         FGRunways runways( path.c_str() );
523
524         SG_LOG( SG_GENERAL, SG_INFO,
525                 "Attempting to set starting position from runway code "
526                 << id << " heading " << tgt_hdg );
527
528         // SGPath inpath( globals->get_fg_root() );
529         // inpath.append( "Airports" );
530         // inpath.append( "apt_simple" );
531         // airports.load( inpath.c_str() );
532
533         // SGPath outpath( globals->get_fg_root() );
534         // outpath.append( "Airports" );
535         // outpath.append( "simple.gdbm" );
536         // airports.dump_gdbm( outpath.c_str() );
537
538         if ( ! runways.search( id, &r ) ) {
539             SG_LOG( SG_GENERAL, SG_ALERT,
540                     "Failed to find " << id << " in database." );
541             return false;
542         }
543
544         double diff;
545         double min_diff = 360.0;
546
547         while ( r.id == id ) {
548             // forward direction
549             diff = tgt_hdg - r.heading;
550             while ( diff < -180.0 ) { diff += 360.0; }
551             while ( diff >  180.0 ) { diff -= 360.0; }
552             diff = fabs(diff);
553             SG_LOG( SG_GENERAL, SG_INFO,
554                     "Runway " << r.rwy_no << " heading = " << r.heading <<
555                     " diff = " << diff );
556             if ( diff < min_diff ) {
557                 min_diff = diff;
558                 found_r = r;
559                 found_dir = 0;
560             }
561
562             // reverse direction
563             diff = tgt_hdg - r.heading - 180.0;
564             while ( diff < -180.0 ) { diff += 360.0; }
565             while ( diff >  180.0 ) { diff -= 360.0; }
566             diff = fabs(diff);
567             SG_LOG( SG_GENERAL, SG_INFO,
568                     "Runway -" << r.rwy_no << " heading = " <<
569                     r.heading + 180.0 <<
570                     " diff = " << diff );
571             if ( diff < min_diff ) {
572                 min_diff = diff;
573                 found_r = r;
574                 found_dir = 180.0;
575             }
576
577             runways.next( &r );
578         }
579
580         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
581                 << " + " << found_dir );
582
583     } else {
584         return false;
585     }
586
587     double heading = found_r.heading + found_dir;
588     while ( heading >= 360.0 ) { heading -= 360.0; }
589
590     double lat2, lon2, az2;
591     double azimuth = found_r.heading + found_dir + 180.0;
592     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
593
594     SG_LOG( SG_GENERAL, SG_INFO,
595             "runway =  " << found_r.lon << ", " << found_r.lat
596             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
597             << " heading = " << azimuth );
598     
599     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
600                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
601                         &lat2, &lon2, &az2 );
602
603     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
604         double olat, olon;
605         double odist = fgGetDouble("/sim/presets/offset-distance");
606         odist *= SG_NM_TO_METER;
607         double oaz = azimuth;
608         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
609             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
610         }
611         while ( oaz >= 360.0 ) { oaz -= 360.0; }
612         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
613         lat2=olat;
614         lon2=olon;
615     }
616
617     // presets
618     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
619     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
620     fgSetDouble("/sim/presets/heading-deg", heading );
621
622     // other code depends on the actual values being set ...
623     fgSetDouble("/position/longitude-deg",  lon2 );
624     fgSetDouble("/position/latitude-deg",  lat2 );
625     fgSetDouble("/orientation/heading-deg", heading );
626
627     SG_LOG( SG_GENERAL, SG_INFO,
628             "Position for " << id << " is ("
629             << lon2 << ", "
630             << lat2 << ") new heading is "
631             << heading );
632
633     return true;
634 }
635
636
637 void fgSetPosFromGlideSlope(void) {
638     double gs = fgGetDouble("/velocities/glideslope");
639     double od = fgGetDouble("/sim/presets/offset-distance");
640     double alt = fgGetDouble("/sim/presets/altitude-ft");
641     
642     //if glideslope and offset-distance are set and altitude is
643     //not, calculate the initial altitude
644     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
645         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
646         alt = fabs(od*tan(gs));
647         fgSetDouble("/sim/presets/altitude-ft",alt);
648         fgSetBool("/sim/presets/onground", false);
649         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
650     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
651         od  = alt/tan(gs);
652         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
653         fgSetDouble("/sim/presets/offset-distance",od);
654         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
655                                        << od  << " nm");
656     } else if( fabs(gs) > 0.01 ) {
657         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
658                                   << " or offset-distance.  Resetting"
659                                   << " glideslope to zero" );
660         fgSetDouble("/velocities/glideslope",0);                                  
661     }                              
662                                       
663 }                       
664
665 // General house keeping initializations
666 bool fgInitGeneral( void ) {
667     string root;
668
669 #if defined(FX) && defined(XMESA)
670     char *mesa_win_state;
671 #endif
672
673     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
674     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
675
676     root = globals->get_fg_root();
677     if ( ! root.length() ) {
678         // No root path set? Then bail ...
679         SG_LOG( SG_GENERAL, SG_ALERT,
680                 "Cannot continue without a path to the base package "
681                 << "being defined." );
682         exit(-1);
683     }
684     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
685
686 #if defined(FX) && defined(XMESA)
687     // initialize full screen flag
688     globals->set_fullscreen(false);
689     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
690         // Test for the MESA_GLX_FX env variable
691         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
692             // test if we are fullscreen mesa/glide
693             if ( (mesa_win_state[0] == 'f') ||
694                  (mesa_win_state[0] == 'F') ) {
695                 globals->set_fullscreen(true);
696             }
697         }
698     }
699 #endif
700
701     return true;
702 }
703
704
705 // Initialize the flight model subsystem.  This just creates the
706 // object.  The actual fdm initialization is delayed until we get a
707 // proper scenery elevation hit.  This is checked for in main.cxx
708
709 void fgInitFDM() {
710
711     if ( cur_fdm_state ) {
712         delete cur_fdm_state;
713         cur_fdm_state = 0;
714     }
715
716     double dt = 1.0 / fgGetInt("/sim/model-hz");
717     aircraft_dir = fgGetString("/sim/aircraft-dir");
718     const string &model = fgGetString("/sim/flight-model");
719
720     try {
721         if ( model == "larcsim" ) {
722             cur_fdm_state = new FGLaRCsim( dt );
723         } else if ( model == "jsb" ) {
724             cur_fdm_state = new FGJSBsim( dt );
725         } else if ( model == "ada" ) {
726             cur_fdm_state = new FGADA( dt );
727         } else if ( model == "balloon" ) {
728             cur_fdm_state = new FGBalloonSim( dt );
729         } else if ( model == "magic" ) {
730             cur_fdm_state = new FGMagicCarpet( dt );
731         } else if ( model == "ufo" ) {
732             cur_fdm_state = new FGUFO( dt );
733         } else if ( model == "external" ) {
734             // external is a synonym for "--fdm=null" and is
735             // maintained here for backwards compatibility
736             cur_fdm_state = new FGNullFDM( dt );
737         } else if ( model.find("network") == 0 ) {
738             string host = "localhost";
739             int port1 = 5501;
740             int port2 = 5502;
741             int port3 = 5503;
742             string net_options = model.substr(8);
743             string::size_type begin, end;
744             begin = 0;
745             // host
746             end = net_options.find( ",", begin );
747             if ( end != string::npos ) {
748                 host = net_options.substr(begin, end - begin);
749                 begin = end + 1;
750             }
751             // port1
752             end = net_options.find( ",", begin );
753             if ( end != string::npos ) {
754                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
755                 begin = end + 1;
756             }
757             // port2
758             end = net_options.find( ",", begin );
759             if ( end != string::npos ) {
760                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
761                 begin = end + 1;
762             }
763             // port3
764             end = net_options.find( ",", begin );
765             if ( end != string::npos ) {
766                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
767                 begin = end + 1;
768             }
769             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
770         } else if ( model == "null" ) {
771             cur_fdm_state = new FGNullFDM( dt );
772         } else if ( model == "yasim" ) {
773             cur_fdm_state = new YASim( dt );
774         } else {
775             SG_LOG(SG_GENERAL, SG_ALERT,
776                    "Unrecognized flight model '" << model
777                    << "', cannot init flight dynamics model.");
778             exit(-1);
779         }
780     } catch ( ... ) {
781         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
782         exit(-1);
783     }
784 }
785
786 static void printMat(const sgVec4 *mat, char *name="")
787 {
788     int i;
789     cout << name << endl;
790     for(i=0; i<4; i++) {
791         cout <<"  "<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<" "<<mat[i][3]<<endl;
792     }
793     cout << endl;
794 }
795
796 // Initialize view parameters
797 void fgInitView() {
798   // force update of model so that viewer can get some data...
799   globals->get_aircraft_model()->update(0);
800   // run update for current view so that data is current...
801   globals->get_viewmgr()->update(0);
802
803   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
804   printMat(globals->get_current_view()->get_UP(),"UP");
805   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
806   
807 }
808
809
810 SGTime *fgInitTime() {
811     // Initialize time
812     static const SGPropertyNode *longitude
813         = fgGetNode("/position/longitude-deg");
814     static const SGPropertyNode *latitude
815         = fgGetNode("/position/latitude-deg");
816     static const SGPropertyNode *cur_time_override
817         = fgGetNode("/sim/time/cur-time-override", true);
818
819     SGPath zone( globals->get_fg_root() );
820     zone.append( "Timezone" );
821     SGTime *t = new SGTime( longitude->getDoubleValue()
822                               * SGD_DEGREES_TO_RADIANS,
823                             latitude->getDoubleValue()
824                               * SGD_DEGREES_TO_RADIANS,
825                             zone.str(),
826                             cur_time_override->getLongValue() );
827
828     // Handle potential user specified time offsets
829     time_t cur_time = t->get_cur_time();
830     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
831     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
832     time_t aircraftLocalTime = 
833         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
834
835     // Okay, we now have six possible scenarios
836     int offset = fgGetInt("/sim/startup/time-offset");
837     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
838     if (offset_type == "system-offset") {
839         globals->set_warp( offset );
840     } else if (offset_type == "gmt-offset") {
841         globals->set_warp( offset - (currGMT - systemLocalTime) );
842     } else if (offset_type == "latitude-offset") {
843         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
844     } else if (offset_type == "system") {
845         globals->set_warp( offset - cur_time );
846     } else if (offset_type == "gmt") {
847         globals->set_warp( offset - currGMT );
848     } else if (offset_type == "latitude") {
849         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
850                            cur_time ); 
851     } else {
852         SG_LOG( SG_GENERAL, SG_ALERT,
853                 "FG_TIME::Unsupported offset type " << offset_type );
854         exit( -1 );
855     }
856
857     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
858             << globals->get_warp() );
859
860     globals->set_warp_delta( 0 );
861
862     t->update( 0.0, 0.0,
863                cur_time_override->getLongValue(),
864                globals->get_warp() );
865
866     return t;
867 }
868
869
870 // This is the top level init routine which calls all the other
871 // initialization routines.  If you are adding a subsystem to flight
872 // gear, its initialization call should located in this routine.
873 // Returns non-zero if a problem encountered.
874 bool fgInitSubsystems( void ) {
875     static const SGPropertyNode *longitude
876         = fgGetNode("/sim/presets/longitude-deg");
877     static const SGPropertyNode *latitude
878         = fgGetNode("/sim/presets/latitude-deg");
879     static const SGPropertyNode *altitude
880         = fgGetNode("/sim/presets/altitude-ft");
881
882     fgLIGHT *l = &cur_light_params;
883
884     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
885     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
886
887
888     ////////////////////////////////////////////////////////////////////
889     // Initialize the material property subsystem.
890     ////////////////////////////////////////////////////////////////////
891
892     SGPath mpath( globals->get_fg_root() );
893     mpath.append( "materials.xml" );
894     if ( ! material_lib.load( mpath.str() ) ) {
895         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
896         exit(-1);
897     }
898
899     ////////////////////////////////////////////////////////////////////
900     // Initialize the event manager subsystem.
901     ////////////////////////////////////////////////////////////////////
902
903     global_events.init();
904
905     // Output event stats every 60 seconds
906     global_events.Register( "FGEventMgr::print_stats()",
907                             &global_events, &FGEventMgr::print_stats,
908                             60000 );
909
910
911     ////////////////////////////////////////////////////////////////////
912     // Initialize the scenery management subsystem.
913     ////////////////////////////////////////////////////////////////////
914
915     if ( global_tile_mgr.init() ) {
916         // Load the local scenery data
917         double visibility_meters = fgGetDouble("/environment/visibility-m");
918                 
919         global_tile_mgr.update( longitude->getDoubleValue(),
920                                 latitude->getDoubleValue(),
921                                 visibility_meters );
922     } else {
923         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
924         exit(-1);
925     }
926
927     // cause refresh of viewer scenery timestamps every 15 seconds...
928     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
929                             &global_tile_mgr, &FGTileMgr::refresh_view_timestamps,
930                             15000 );
931
932     SG_LOG( SG_GENERAL, SG_DEBUG,
933             "Current terrain elevation after tile mgr init " <<
934             globals->get_scenery()->get_cur_elev() );
935
936
937     ////////////////////////////////////////////////////////////////////
938     // Initialize the flight model subsystem.
939     ////////////////////////////////////////////////////////////////////
940
941     fgInitFDM();
942         
943     // allocates structures so must happen before any of the flight
944     // model or control parameters are set
945     fgAircraftInit();   // In the future this might not be the case.
946
947
948     ////////////////////////////////////////////////////////////////////
949     // Initialize the view manager subsystem.
950     ////////////////////////////////////////////////////////////////////
951
952     fgInitView();
953
954
955     ////////////////////////////////////////////////////////////////////
956     // Initialize the lighting subsystem.
957     ////////////////////////////////////////////////////////////////////
958
959     // fgUpdateSunPos() needs a few position and view parameters set
960     // so it can calculate local relative sun angle and a few other
961     // things for correctly orienting the sky.
962     fgUpdateSunPos();
963     fgUpdateMoonPos();
964     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
965                             60000);
966     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
967                             60000);
968
969     // Initialize Lighting interpolation tables
970     l->Init();
971
972     // force one lighting update to make it right to start with...
973     l->Update();
974     // update the lighting parameters (based on sun angle)
975     global_events.Register( "fgLight::Update()",
976                             &cur_light_params, &fgLIGHT::Update,
977                             30000 );
978
979
980     ////////////////////////////////////////////////////////////////////
981     // Create and register the logger.
982     ////////////////////////////////////////////////////////////////////
983     
984     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
985                                       "logger",
986                                       new FGLogger);
987
988
989     ////////////////////////////////////////////////////////////////////
990     // Create and register the XML GUI.
991     ////////////////////////////////////////////////////////////////////
992
993     globals->get_subsystem_mgr()->add(FGSubsystemMgr::INIT,
994                                       "gui",
995                                       new NewGUI);
996
997
998     ////////////////////////////////////////////////////////////////////
999     // Initialize the local time subsystem.
1000     ////////////////////////////////////////////////////////////////////
1001
1002     // update the current timezone each 30 minutes
1003     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1004                             30*60*1000 );
1005
1006
1007     ////////////////////////////////////////////////////////////////////
1008     // Initialize the weather subsystem.
1009     ////////////////////////////////////////////////////////////////////
1010
1011     // Initialize the weather modeling subsystem
1012 #ifdef FG_WEATHERCM
1013     // Initialize the WeatherDatabase
1014     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1015     sgVec3 position;
1016     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1017                current_aircraft.fdm_state->get_Longitude(),
1018                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1019     double init_vis = fgGetDouble("/environment/visibility-m");
1020
1021     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1022
1023     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1024     {
1025       working_type = FGLocalWeatherDatabase::use_internet;
1026     } else {
1027       working_type = FGLocalWeatherDatabase::default_mode;
1028     }
1029     
1030     if ( init_vis > 0 ) {
1031       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1032         new FGLocalWeatherDatabase( position,
1033                                     globals->get_fg_root(),
1034                                     working_type,
1035                                     init_vis );
1036     } else {
1037       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1038         new FGLocalWeatherDatabase( position,
1039                                     globals->get_fg_root(),
1040                                     working_type );
1041     }
1042
1043     // cout << theFGLocalWeatherDatabase << endl;
1044     // cout << "visibility = " 
1045     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1046
1047     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1048
1049     // register the periodic update of the weather
1050     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1051                             30000);
1052 #else
1053     globals->get_environment_mgr()->init();
1054     globals->get_environment_mgr()->bind();
1055 #endif
1056
1057     ////////////////////////////////////////////////////////////////////
1058     // Initialize the 3D cloud subsystem.
1059     ////////////////////////////////////////////////////////////////////
1060     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1061         SGPath cloud_path(globals->get_fg_root());
1062         cloud_path.append("large.sky");
1063         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1064         if ( !sgCloud3d->Load( cloud_path.str(),
1065                                latitude->getDoubleValue(),
1066                                longitude->getDoubleValue()) )
1067         {
1068             fgSetBool("/sim/rendering/clouds3d", false);
1069             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1070         }
1071         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1072     }
1073
1074     ////////////////////////////////////////////////////////////////////
1075     // Initialize vor/ndb/ils/fix list management and query systems
1076     ////////////////////////////////////////////////////////////////////
1077
1078     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1079
1080     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
1081     current_navlist = new FGNavList;
1082     SGPath p_nav( globals->get_fg_root() );
1083     p_nav.append( "Navaids/default.nav" );
1084     current_navlist->init( p_nav );
1085
1086     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
1087     current_beacons = new FGMarkerBeacons;
1088     current_beacons->init();
1089     current_ilslist = new FGILSList;
1090     SGPath p_ils( globals->get_fg_root() );
1091     p_ils.append( "Navaids/default.ils" );
1092     current_ilslist->init( p_ils );
1093
1094     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1095     current_fixlist = new FGFixList;
1096     SGPath p_fix( globals->get_fg_root() );
1097     p_fix.append( "Navaids/default.fix" );
1098     current_fixlist->init( p_fix );
1099
1100     ////////////////////////////////////////////////////////////////////
1101     // Initialize ATC list management and query systems
1102     ////////////////////////////////////////////////////////////////////
1103
1104     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
1105     current_atislist = new FGATISList;
1106     SGPath p_atis( globals->get_fg_root() );
1107     p_atis.append( "ATC/default.atis" );
1108     current_atislist->init( p_atis );
1109
1110     SG_LOG(SG_GENERAL, SG_INFO, "  Tower");
1111     current_towerlist = new FGTowerList;
1112     SGPath p_tower( globals->get_fg_root() );
1113     p_tower.append( "ATC/default.tower" );
1114     current_towerlist->init( p_tower );
1115
1116     SG_LOG(SG_GENERAL, SG_INFO, "  Approach");
1117     current_approachlist = new FGApproachList;
1118     SGPath p_approach( globals->get_fg_root() );
1119     p_approach.append( "ATC/default.approach" );
1120     current_approachlist->init( p_approach );
1121
1122     ////////////////////////////////////////////////////////////////////
1123     // Initialise ATC display system
1124     ////////////////////////////////////////////////////////////////////
1125
1126     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1127     globals->set_ATC_display(new FGATCDisplay);
1128     globals->get_ATC_display()->init(); 
1129
1130     ////////////////////////////////////////////////////////////////////
1131     // Initialise the ATC Manager 
1132     ////////////////////////////////////////////////////////////////////
1133
1134     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1135     globals->set_ATC_mgr(new FGATCMgr);
1136     globals->get_ATC_mgr()->init(); 
1137     
1138     ////////////////////////////////////////////////////////////////////
1139     // Initialise the AI Manager 
1140     ////////////////////////////////////////////////////////////////////
1141
1142     if (fgGetBool("/sim/ai-traffic/enabled")) {
1143         SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1144         globals->set_AI_mgr(new FGAIMgr);
1145         globals->get_AI_mgr()->init();
1146     }
1147
1148 #ifdef ENABLE_AUDIO_SUPPORT
1149     ////////////////////////////////////////////////////////////////////
1150     // Initialize the sound subsystem.
1151     ////////////////////////////////////////////////////////////////////
1152
1153     globals->set_soundmgr(new FGSoundMgr);
1154     globals->get_soundmgr()->init();
1155     globals->get_soundmgr()->bind();
1156
1157
1158     ////////////////////////////////////////////////////////////////////
1159     // Initialize the sound-effects subsystem.
1160     ////////////////////////////////////////////////////////////////////
1161
1162     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1163                                       "fx",
1164                                       new FGFX);
1165     
1166
1167 #endif
1168
1169     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1170                                       "instrumentation",
1171                                       new FGInstrumentMgr);
1172     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1173                                       "systems",
1174                                       new FGSystemMgr);
1175
1176     ////////////////////////////////////////////////////////////////////
1177     // Initialize the radio stack subsystem.
1178     ////////////////////////////////////////////////////////////////////
1179
1180                                 // A textbook example of how FGSubsystem
1181                                 // should work...
1182     current_radiostack = new FGRadioStack;
1183     current_radiostack->init();
1184     current_radiostack->bind();
1185
1186
1187     ////////////////////////////////////////////////////////////////////
1188     // Initialize the cockpit subsystem
1189     ////////////////////////////////////////////////////////////////////
1190
1191     if( fgCockpitInit( &current_aircraft )) {
1192         // Cockpit initialized ok.
1193     } else {
1194         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1195         exit(-1);
1196     }
1197
1198
1199     ////////////////////////////////////////////////////////////////////
1200     // Initialize the autopilot subsystem.
1201     ////////////////////////////////////////////////////////////////////
1202
1203     globals->set_autopilot(new FGAutopilot);
1204     globals->get_autopilot()->init();
1205     globals->get_autopilot()->bind();
1206
1207                                 // FIXME: these should go in the
1208                                 // GUI initialization code, not here.
1209     fgAPAdjustInit();
1210     NewTgtAirportInit();
1211     NewHeadingInit();
1212     NewAltitudeInit();
1213
1214     ////////////////////////////////////////////////////////////////////
1215     // Initialize I/O subsystem.
1216     ////////////////////////////////////////////////////////////////////
1217
1218     globals->get_io()->init();
1219     globals->get_io()->bind();
1220
1221     // Initialize the 2D panel.
1222     string panel_path = fgGetString("/sim/panel/path",
1223                                     "Panels/Default/default.xml");
1224     current_panel = fgReadPanel(panel_path);
1225     if (current_panel == 0) {
1226         SG_LOG( SG_INPUT, SG_ALERT, 
1227                 "Error reading new panel from " << panel_path );
1228     } else {
1229         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1230         current_panel->init();
1231         current_panel->bind();
1232     }
1233
1234     
1235     ////////////////////////////////////////////////////////////////////
1236     // Initialize the default (kludged) properties.
1237     ////////////////////////////////////////////////////////////////////
1238
1239     fgInitProps();
1240
1241
1242     ////////////////////////////////////////////////////////////////////
1243     // Initialize the controls subsystem.
1244     ////////////////////////////////////////////////////////////////////
1245
1246     globals->get_controls()->init();
1247     globals->get_controls()->bind();
1248
1249
1250     ////////////////////////////////////////////////////////////////////
1251     // Initialize the steam subsystem.
1252     ////////////////////////////////////////////////////////////////////
1253
1254     globals->get_steam()->init();
1255     globals->get_steam()->bind();
1256
1257
1258     ////////////////////////////////////////////////////////////////////
1259     // Initialize the input subsystem.
1260     ////////////////////////////////////////////////////////////////////
1261
1262     globals->get_subsystem_mgr()->add(FGSubsystemMgr::GENERAL,
1263                                       "input",
1264                                       new FGInput);
1265
1266
1267     ////////////////////////////////////////////////////////////////////
1268     // Bind and initialize subsystems.
1269     ////////////////////////////////////////////////////////////////////
1270
1271     globals->get_subsystem_mgr()->bind();
1272     globals->get_subsystem_mgr()->init();
1273
1274
1275     ////////////////////////////////////////////////////////////////////////
1276     // End of subsystem initialization.
1277     ////////////////////////////////////////////////////////////////////
1278
1279     SG_LOG( SG_GENERAL, SG_INFO, endl);
1280
1281                                 // Save the initial state for future
1282                                 // reference.
1283     globals->saveInitialState();
1284
1285     return true;
1286 }
1287
1288
1289 void fgReInitSubsystems( void )
1290 {
1291     static const SGPropertyNode *longitude
1292         = fgGetNode("/sim/presets/longitude-deg");
1293     static const SGPropertyNode *latitude
1294         = fgGetNode("/sim/presets/latitude-deg");
1295     static const SGPropertyNode *altitude
1296         = fgGetNode("/sim/presets/altitude-ft");
1297     static const SGPropertyNode *master_freeze
1298         = fgGetNode("/sim/freeze/master");
1299
1300     SG_LOG( SG_GENERAL, SG_INFO,
1301             "fgReInitSubsystems(): /position/altitude = "
1302             << altitude->getDoubleValue() );
1303
1304     bool freeze = master_freeze->getBoolValue();
1305     if ( !freeze ) {
1306         fgSetBool("/sim/freeze/master", true);
1307     }
1308     
1309     // Initialize the Scenery Management subsystem
1310     // FIXME, what really needs to get initialized here, at the time
1311     // this was commented out, scenery.init() was a noop
1312     // scenery.init();
1313
1314     fgInitFDM();
1315     
1316     // allocates structures so must happen before any of the flight
1317     // model or control parameters are set
1318     fgAircraftInit();   // In the future this might not be the case.
1319
1320     // copy viewer settings into current-view path
1321     globals->get_viewmgr()->copyToCurrent();
1322
1323     fgInitView();
1324
1325     globals->get_controls()->reset_all();
1326     globals->get_autopilot()->reset();
1327
1328     fgUpdateSunPos();
1329     fgUpdateMoonPos();
1330     cur_light_params.Update();
1331     fgUpdateLocalTime();
1332
1333     if ( !freeze ) {
1334         fgSetBool("/sim/freeze/master", false);
1335     }
1336 }
1337