]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
3755480967700f2bd98bac580fe34ecb4df7251c
[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
43
44 #if defined( unix ) || defined( __CYGWIN__ )
45 #  include <unistd.h>           // for gethostname()
46 #endif
47
48 // work around a stdc++ lib bug in some versions of linux, but doesn't
49 // seem to hurt to have this here for all versions of Linux.
50 #ifdef linux
51 #  define _G_NO_EXTERN_TEMPLATES
52 #endif
53
54 #include <simgear/compiler.h>
55 #include <simgear/misc/exception.hxx>
56
57 #include STL_STRING
58
59 #include <simgear/constants.h>
60 #include <simgear/debug/logstream.hxx>
61 #include <simgear/math/point3d.hxx>
62 #include <simgear/math/polar3d.hxx>
63 #include <simgear/math/sg_geodesy.hxx>
64 #include <simgear/misc/sg_path.hxx>
65 #include <simgear/timing/sg_time.hxx>
66 #include <simgear/timing/lowleveltime.h>
67
68 #include <Aircraft/aircraft.hxx>
69 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
70 #include <Airports/runways.hxx>
71 #include <Airports/simple.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/atislist.hxx>
75 #include <Autopilot/auto_gui.hxx>
76 #include <Autopilot/newauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/radiostack.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
81 #include <FDM/ADA.hxx>
82 #include <FDM/Balloon.h>
83 #include <FDM/External.hxx>
84 #include <FDM/JSBSim/JSBSim.hxx>
85 #include <FDM/LaRCsim.hxx>
86 #include <FDM/MagicCarpet.hxx>
87 #include <FDM/NullFDM.hxx>
88 #include <FDM/YASim/YASim.hxx>
89 #include <Include/general.hxx>
90 #include <Input/input.hxx>
91 // #include <Joystick/joystick.hxx>
92 #include <Objects/matlib.hxx>
93 #include <Navaids/fixlist.hxx>
94 #include <Navaids/ilslist.hxx>
95 #include <Navaids/mkrbeacons.hxx>
96 #include <Navaids/navlist.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <Sound/fg_fx.hxx>
100 #include <Sound/soundmgr.hxx>
101 #include <Time/event.hxx>
102 #include <Time/light.hxx>
103 #include <Time/sunpos.hxx>
104 #include <Time/moonpos.hxx>
105 #include <Time/tmp.hxx>
106
107 #ifndef FG_NEW_ENVIRONMENT
108 #  include <WeatherCM/FGLocalWeatherDatabase.h>
109 #else
110 #  include <Environment/environment_mgr.hxx>
111 #endif
112
113 #include "fg_init.hxx"
114 #include "fg_io.hxx"
115 #include "fg_commands.hxx"
116 #include "fg_props.hxx"
117 #include "options.hxx"
118 #include "globals.hxx"
119 #include "logger.hxx"
120 #include "viewmgr.hxx"
121
122 #if defined(FX) && defined(XMESA)
123 #include <GL/xmesa.h>
124 #endif
125
126 SG_USING_STD(string);
127
128 extern const char *default_root;
129
130
131 // Read in configuration (file and command line) and just set fg_root
132 bool fgInitFGRoot ( int argc, char **argv ) {
133     string root;
134     char* envp;
135
136     // First parse command line options looking for fg-root, this will
137     // override anything specified in a config file
138     root = fgScanForRoot(argc, argv);
139
140 #if defined( unix ) || defined( __CYGWIN__ )
141     // Next check home directory for .fgfsrc.hostname file
142     if ( root == "" ) {
143         envp = ::getenv( "HOME" );
144         if ( envp != NULL ) {
145             SGPath config( envp );
146             config.append( ".fgfsrc" );
147             char name[256];
148             gethostname( name, 256 );
149             config.concat( "." );
150             config.concat( name );
151             root = fgScanForRoot(config.str());
152         }
153     }
154 #endif
155
156     // Next check home directory for .fgfsrc file
157     if ( root == "" ) {
158         envp = ::getenv( "HOME" );
159         if ( envp != NULL ) {
160             SGPath config( envp );
161             config.append( ".fgfsrc" );
162             root = fgScanForRoot(config.str());
163         }
164     }
165     
166     // Next check if fg-root is set as an env variable
167     if ( root == "" ) {
168         envp = ::getenv( "FG_ROOT" );
169         if ( envp != NULL ) {
170             root = envp;
171         }
172     }
173
174     // Otherwise, default to a random compiled-in location if we can't
175     // find fg-root any other way.
176     if ( root == "" ) {
177 #if defined( __CYGWIN__ )
178         root = "/FlightGear";
179 #elif defined( WIN32 )
180         root = "\\FlightGear";
181 #elif defined( macintosh )
182         root = "";
183 #else
184         root = PKGLIBDIR;
185 #endif
186     }
187
188     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
189     globals->set_fg_root(root);
190
191     return true;
192 }
193
194
195 // Return the current base package version
196 string fgBasePackageVersion() {
197     SGPath base_path( globals->get_fg_root() );
198     base_path.append("version");
199
200     sg_gzifstream in( base_path.str() );
201     if ( !in.is_open() ) {
202         SGPath old_path( globals->get_fg_root() );
203         old_path.append( "Thanks" );
204         sg_gzifstream old( old_path.str() );
205         if ( !old.is_open() ) {
206             return "[none]";
207         } else {
208             return "[old version]";
209         }
210     }
211
212     string version;
213     in >> version;
214
215     return version;
216 }
217
218
219 // Read in configuration (file and command line)
220 bool fgInitConfig ( int argc, char **argv ) {
221
222                                 // First, set some sane default values
223     fgSetDefaults();
224
225     // Read global preferences from $FG_ROOT/preferences.xml
226     SGPath props_path(globals->get_fg_root());
227     props_path.append("preferences.xml");
228     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
229     try {
230       readProperties(props_path.str(), globals->get_props());
231     } catch (const sg_exception &e) {
232       string message = "Error reading global preferences: ";
233       message += e.getFormattedMessage();
234       SG_LOG(SG_INPUT, SG_ALERT, message);
235       exit(2);
236     }
237     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
238
239     // Read the default aircraft config file.
240     string aircraft = fgGetString("/sim/aircraft", "");
241     if (aircraft.size() > 0) {
242       SGPath aircraft_path(globals->get_fg_root());
243       aircraft_path.append("Aircraft");
244       aircraft_path.append(aircraft);
245       aircraft_path.concat("-set.xml");
246       SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
247              << " from " << aircraft_path.str());
248       try {
249         readProperties(aircraft_path.str(), globals->get_props());
250       } catch (const sg_exception &e) {
251         string message = "Error reading default aircraft: ";
252         message += e.getFormattedMessage();
253         SG_LOG(SG_INPUT, SG_ALERT, message);
254         exit(2);
255       }
256     } else {
257       SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
258     }
259
260     // Attempt to locate and parse the various config files in order
261     // from least precidence to greatest precidence
262
263     // Check for $fg_root/system.fgfsrc
264     SGPath config( globals->get_fg_root() );
265     config.append( "system.fgfsrc" );
266     fgParseOptions(config.str());
267
268     char name[256];
269 #if defined( unix ) || defined( __CYGWIN__ )
270     // Check for $fg_root/system.fgfsrc.hostname
271     gethostname( name, 256 );
272     config.concat( "." );
273     config.concat( name );
274     fgParseOptions(config.str());
275 #endif
276
277     // Check for ~/.fgfsrc
278     char* envp = ::getenv( "HOME" );
279     if ( envp != NULL ) {
280         config.set( envp );
281         config.append( ".fgfsrc" );
282         fgParseOptions(config.str());
283     }
284
285 #if defined( unix ) || defined( __CYGWIN__ )
286     // Check for ~/.fgfsrc.hostname
287     gethostname( name, 256 );
288     config.concat( "." );
289     config.concat( name );
290     fgParseOptions(config.str());
291 #endif
292
293     // Parse remaining command line options
294     // These will override anything specified in a config file
295     fgParseArgs(argc, argv);
296
297     return true;
298 }
299
300
301 // find basic airport location info from airport database
302 bool fgFindAirportID( const string& id, FGAirport *a ) {
303     if ( id.length() ) {
304         SGPath path( globals->get_fg_root() );
305         path.append( "Airports" );
306         path.append( "simple.mk4" );
307         FGAirports airports( path.c_str() );
308
309         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
310
311         if ( ! airports.search( id, a ) ) {
312             SG_LOG( SG_GENERAL, SG_ALERT,
313                     "Failed to find " << id << " in " << path.str() );
314             return false;
315         }
316     } else {
317         return false;
318     }
319
320     SG_LOG( SG_GENERAL, SG_INFO,
321             "Position for " << id << " is ("
322             << a->longitude << ", "
323             << a->latitude << ")" );
324
325     return true;
326 }
327
328
329 // Set current_options lon/lat given an airport id
330 bool fgSetPosFromAirportID( const string& id ) {
331     FGAirport a;
332     // double lon, lat;
333
334     SG_LOG( SG_GENERAL, SG_INFO,
335             "Attempting to set starting position from airport code " << id );
336
337     if ( fgFindAirportID( id, &a ) ) {
338         fgSetDouble("/position/longitude-deg",  a.longitude );
339         fgSetDouble("/position/latitude-deg",  a.latitude );
340         SG_LOG( SG_GENERAL, SG_INFO,
341                 "Position for " << id << " is ("
342                 << a.longitude << ", "
343                 << a.latitude << ")" );
344
345         return true;
346     } else {
347         return false;
348     }
349
350 }
351
352
353 // Set current_options lon/lat given an airport id and heading (degrees)
354 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
355     FGRunway r;
356     FGRunway found_r;
357     double found_dir = 0.0;
358
359     if ( id.length() ) {
360         // set initial position from runway and heading
361
362         SGPath path( globals->get_fg_root() );
363         path.append( "Airports" );
364         path.append( "runways.mk4" );
365         FGRunways runways( path.c_str() );
366
367         SG_LOG( SG_GENERAL, SG_INFO,
368                 "Attempting to set starting position from runway code "
369                 << id << " heading " << tgt_hdg );
370
371         // SGPath inpath( globals->get_fg_root() );
372         // inpath.append( "Airports" );
373         // inpath.append( "apt_simple" );
374         // airports.load( inpath.c_str() );
375
376         // SGPath outpath( globals->get_fg_root() );
377         // outpath.append( "Airports" );
378         // outpath.append( "simple.gdbm" );
379         // airports.dump_gdbm( outpath.c_str() );
380
381         if ( ! runways.search( id, &r ) ) {
382             SG_LOG( SG_GENERAL, SG_ALERT,
383                     "Failed to find " << id << " in database." );
384             return false;
385         }
386
387         double diff;
388         double min_diff = 360.0;
389
390         while ( r.id == id ) {
391             // forward direction
392             diff = tgt_hdg - r.heading;
393             while ( diff < -180.0 ) { diff += 360.0; }
394             while ( diff >  180.0 ) { diff -= 360.0; }
395             diff = fabs(diff);
396             SG_LOG( SG_GENERAL, SG_INFO,
397                     "Runway " << r.rwy_no << " heading = " << r.heading <<
398                     " diff = " << diff );
399             if ( diff < min_diff ) {
400                 min_diff = diff;
401                 found_r = r;
402                 found_dir = 0;
403             }
404
405             // reverse direction
406             diff = tgt_hdg - r.heading - 180.0;
407             while ( diff < -180.0 ) { diff += 360.0; }
408             while ( diff >  180.0 ) { diff -= 360.0; }
409             diff = fabs(diff);
410             SG_LOG( SG_GENERAL, SG_INFO,
411                     "Runway -" << r.rwy_no << " heading = " <<
412                     r.heading + 180.0 <<
413                     " diff = " << diff );
414             if ( diff < min_diff ) {
415                 min_diff = diff;
416                 found_r = r;
417                 found_dir = 180.0;
418             }
419
420             runways.next( &r );
421         }
422
423         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
424                 << " + " << found_dir );
425
426     } else {
427         return false;
428     }
429
430     double heading = found_r.heading + found_dir;
431     while ( heading >= 360.0 ) { heading -= 360.0; }
432
433     double lat2, lon2, az2;
434     double azimuth = found_r.heading + found_dir + 180.0;
435     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
436
437     SG_LOG( SG_GENERAL, SG_INFO,
438             "runway =  " << found_r.lon << ", " << found_r.lat
439             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
440             << " heading = " << azimuth );
441     
442     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
443                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
444                         &lat2, &lon2, &az2 );
445
446     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > SG_EPSILON ) {
447         double olat, olon;
448         double odist = fgGetDouble("/sim/startup/offset-distance");
449         odist *= SG_NM_TO_METER;
450         double oaz = azimuth;
451         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > SG_EPSILON ) {
452             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
453         }
454         while ( oaz >= 360.0 ) { oaz -= 360.0; }
455         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
456         lat2=olat;
457         lon2=olon;
458     }
459         
460     fgSetDouble("/position/longitude-deg",  lon2 );
461     fgSetDouble("/position/latitude-deg",  lat2 );
462     fgSetDouble("/orientation/heading-deg", heading );
463
464     SG_LOG( SG_GENERAL, SG_INFO,
465             "Position for " << id << " is ("
466             << lon2 << ", "
467             << lat2 << ") new heading is "
468             << heading );
469
470     return true;
471 }
472
473 void fgSetPosFromGlideSlope(void) {
474     double gs = fgGetDouble("/velocities/glideslope");
475     double od = fgGetDouble("/sim/startup/offset-distance");
476     double alt = fgGetDouble("/position/altitude-ft");
477     
478     //if glideslope and offset-distance are set and altitude is
479     //not, calculate the initial altitude
480     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
481         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
482         alt = fabs(od*tan(gs));
483         fgSetDouble("/position/altitude-ft",alt);
484         fgSetBool("/sim/startup/onground", false);
485         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
486     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
487         od  = alt/tan(gs);
488         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
489         fgSetDouble("/sim/startup/offset-distance",od);
490         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
491                                        << od  << " nm");
492     } else if( fabs(gs) > 0.01 ) {
493         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
494                                   << " or offset-distance.  Resetting"
495                                   << " glideslope to zero" );
496         fgSetDouble("/velocities/glideslope",0);                                  
497     }                              
498                                       
499 }                       
500
501 // General house keeping initializations
502 bool fgInitGeneral( void ) {
503     string root;
504
505 #if defined(FX) && defined(XMESA)
506     char *mesa_win_state;
507 #endif
508
509     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
510     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
511
512     root = globals->get_fg_root();
513     if ( ! root.length() ) {
514         // No root path set? Then bail ...
515         SG_LOG( SG_GENERAL, SG_ALERT,
516                 "Cannot continue without a path to the base package "
517                 << "being defined." );
518         exit(-1);
519     }
520     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
521
522 #if defined(FX) && defined(XMESA)
523     // initialize full screen flag
524     globals->set_fullscreen(false);
525     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
526         // Test for the MESA_GLX_FX env variable
527         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
528             // test if we are fullscreen mesa/glide
529             if ( (mesa_win_state[0] == 'f') ||
530                  (mesa_win_state[0] == 'F') ) {
531                 globals->set_fullscreen(true);
532             }
533         }
534     }
535 #endif
536
537     return true;
538 }
539
540
541 // Initialize the flight model subsystem.  This just creates the
542 // object.  The actual fdm initialization is delayed until we get a
543 // proper scenery elevation hit.  This is checked for in main.cxx
544
545 void fgInitFDM() {
546
547     if ( cur_fdm_state ) {
548         delete cur_fdm_state;
549         cur_fdm_state = 0;
550     }
551
552     double dt = 1.0 / fgGetInt("/sim/model-hz");
553     aircraft_dir = fgGetString("/sim/aircraft-dir");
554     const string &model = fgGetString("/sim/flight-model");
555
556     try {
557         if (model == "larcsim") {
558             cur_fdm_state = new FGLaRCsim( dt );
559         } else if (model == "jsb") {
560             cur_fdm_state = new FGJSBsim( dt );
561         } else if (model == "ada") {
562             cur_fdm_state = new FGADA( dt );
563         } else if (model == "balloon") {
564             cur_fdm_state = new FGBalloonSim( dt );
565         } else if (model == "magic") {
566             cur_fdm_state = new FGMagicCarpet( dt );
567         } else if (model == "external") {
568             cur_fdm_state = new FGExternal( dt );
569         } else if (model == "null") {
570             cur_fdm_state = new FGNullFDM( dt );
571         } else if (model == "yasim") {
572             cur_fdm_state = new YASim( dt );
573         } else {
574             SG_LOG(SG_GENERAL, SG_ALERT,
575                    "Unrecognized flight model '" << model
576                    << "', cannot init flight dynamics model.");
577             exit(-1);
578         }
579     } catch ( ... ) {
580         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
581         exit(-1);
582     }
583 }
584
585
586 // Initialize view parameters
587 void fgInitView() {
588     // Initialize pilot view
589     static const SGPropertyNode *longitude
590         = fgGetNode("/position/longitude-deg");
591     static const SGPropertyNode *latitude
592         = fgGetNode("/position/latitude-deg");
593     static const SGPropertyNode *altitude
594         = fgGetNode("/position/altitude-ft");
595
596     FGViewerRPH *pilot_view
597         = (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
598
599     pilot_view->set_geod_view_pos( longitude->getDoubleValue()
600                                      * SGD_DEGREES_TO_RADIANS, 
601                                    latitude->getDoubleValue()
602                                      * SGD_DEGREES_TO_RADIANS,
603                                    altitude->getDoubleValue()
604                                      * SG_FEET_TO_METER );
605     pilot_view->set_rph( cur_fdm_state->get_Phi(),
606                          cur_fdm_state->get_Theta(),
607                          cur_fdm_state->get_Psi() );
608
609     // set current view to 0 (first) which is our main pilot view
610     globals->set_current_view( pilot_view );
611
612     SG_LOG( SG_GENERAL, SG_DEBUG, "  abs_view_pos = "
613             << globals->get_current_view()->get_abs_view_pos());
614 }
615
616
617 SGTime *fgInitTime() {
618     // Initialize time
619     static const SGPropertyNode *longitude
620         = fgGetNode("/position/longitude-deg");
621     static const SGPropertyNode *latitude
622         = fgGetNode("/position/latitude-deg");
623     static const SGPropertyNode *cur_time_override
624         = fgGetNode("/sim/time/cur-time-override", true);
625
626     SGPath zone( globals->get_fg_root() );
627     zone.append( "Timezone" );
628     SGTime *t = new SGTime( longitude->getDoubleValue()
629                               * SGD_DEGREES_TO_RADIANS,
630                             latitude->getDoubleValue()
631                               * SGD_DEGREES_TO_RADIANS,
632                             zone.str(),
633                             cur_time_override->getLongValue() );
634
635     // Handle potential user specified time offsets
636     time_t cur_time = t->get_cur_time();
637     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
638     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
639     time_t aircraftLocalTime = 
640         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
641
642     // Okay, we now have six possible scenarios
643     int offset = fgGetInt("/sim/startup/time-offset");
644     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
645     if (offset_type == "system-offset") {
646         globals->set_warp( offset );
647     } else if (offset_type == "gmt-offset") {
648         globals->set_warp( offset - (currGMT - systemLocalTime) );
649     } else if (offset_type == "latitude-offset") {
650         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
651     } else if (offset_type == "system") {
652         globals->set_warp( offset - cur_time );
653     } else if (offset_type == "gmt") {
654         globals->set_warp( offset - currGMT );
655     } else if (offset_type == "latitude") {
656         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
657                            cur_time ); 
658     } else {
659         SG_LOG( SG_GENERAL, SG_ALERT,
660                 "FG_TIME::Unsupported offset type " << offset_type );
661         exit( -1 );
662     }
663
664     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
665             << globals->get_warp() );
666
667     globals->set_warp_delta( 0 );
668
669     t->update( 0.0, 0.0,
670                cur_time_override->getLongValue(),
671                globals->get_warp() );
672
673     return t;
674 }
675
676
677 // This is the top level init routine which calls all the other
678 // initialization routines.  If you are adding a subsystem to flight
679 // gear, its initialization call should located in this routine.
680 // Returns non-zero if a problem encountered.
681 bool fgInitSubsystems( void ) {
682     static const SGPropertyNode *longitude
683         = fgGetNode("/position/longitude-deg");
684     static const SGPropertyNode *latitude
685         = fgGetNode("/position/latitude-deg");
686     static const SGPropertyNode *altitude
687         = fgGetNode("/position/altitude-ft");
688
689     fgLIGHT *l = &cur_light_params;
690
691     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
692     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
693
694
695     ////////////////////////////////////////////////////////////////////
696     // Initialize the material property subsystem.
697     ////////////////////////////////////////////////////////////////////
698
699     SGPath mpath( globals->get_fg_root() );
700     mpath.append( "materials.xml" );
701     if ( ! material_lib.load( mpath.str() ) ) {
702         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
703         exit(-1);
704     }
705
706
707     ////////////////////////////////////////////////////////////////////
708     // Initialize the scenery management subsystem.
709     ////////////////////////////////////////////////////////////////////
710
711     scenery.init();
712     scenery.bind();
713
714     if ( global_tile_mgr.init() ) {
715         // Load the local scenery data
716         global_tile_mgr.update( longitude->getDoubleValue(),
717                                 latitude->getDoubleValue() );
718     } else {
719         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
720         exit(-1);
721     }
722
723     SG_LOG( SG_GENERAL, SG_DEBUG,
724             "Current terrain elevation after tile mgr init " <<
725             scenery.get_cur_elev() );
726
727
728     ////////////////////////////////////////////////////////////////////
729     // Initialize the flight model subsystem.
730     ////////////////////////////////////////////////////////////////////
731
732     fgInitFDM();
733         
734     // allocates structures so must happen before any of the flight
735     // model or control parameters are set
736     fgAircraftInit();   // In the future this might not be the case.
737
738
739     ////////////////////////////////////////////////////////////////////
740     // Initialize the event manager subsystem.
741     ////////////////////////////////////////////////////////////////////
742
743     global_events.Init();
744
745     // Output event stats every 60 seconds
746     global_events.Register( "fgEVENT_MGR::PrintStats()",
747                             fgMethodCallback<fgEVENT_MGR>( &global_events,
748                                                    &fgEVENT_MGR::PrintStats),
749                             fgEVENT::FG_EVENT_READY, 60000 );
750
751
752     ////////////////////////////////////////////////////////////////////
753     // Initialize the view manager subsystem.
754     ////////////////////////////////////////////////////////////////////
755
756     fgInitView();
757
758
759     ////////////////////////////////////////////////////////////////////
760     // Initialize the lighting subsystem.
761     ////////////////////////////////////////////////////////////////////
762
763     // fgUpdateSunPos() needs a few position and view parameters set
764     // so it can calculate local relative sun angle and a few other
765     // things for correctly orienting the sky.
766     fgUpdateSunPos();
767     fgUpdateMoonPos();
768     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
769                             fgEVENT::FG_EVENT_READY, 60000);
770     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
771                             fgEVENT::FG_EVENT_READY, 60000);
772
773     // Initialize Lighting interpolation tables
774     l->Init();
775
776     // update the lighting parameters (based on sun angle)
777     global_events.Register( "fgLight::Update()",
778                             fgMethodCallback<fgLIGHT>( &cur_light_params,
779                                                        &fgLIGHT::Update),
780                             fgEVENT::FG_EVENT_READY, 30000 );
781
782
783     ////////////////////////////////////////////////////////////////////
784     // Initialize the logger.
785     ////////////////////////////////////////////////////////////////////
786     
787     globals->set_logger(new FGLogger);
788     globals->get_logger()->init();
789     globals->get_logger()->bind();
790
791     ////////////////////////////////////////////////////////////////////
792     // Initialize the local time subsystem.
793     ////////////////////////////////////////////////////////////////////
794
795     // update the current timezone each 30 minutes
796     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
797                             fgEVENT::FG_EVENT_READY, 1800000);
798
799
800     ////////////////////////////////////////////////////////////////////
801     // Initialize the weather subsystem.
802     ////////////////////////////////////////////////////////////////////
803
804     // Initialize the weather modeling subsystem
805 #ifndef FG_NEW_ENVIRONMENT
806     // Initialize the WeatherDatabase
807     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
808     sgVec3 position;
809     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
810                current_aircraft.fdm_state->get_Longitude(),
811                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
812     double init_vis = fgGetDouble("/environment/visibility-m");
813
814     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
815
816     if (fgGetString("/environment/weather/working-type") == "internet")
817     {
818       working_type = FGLocalWeatherDatabase::use_internet;
819     } else {
820       working_type = FGLocalWeatherDatabase::default_mode;
821     }
822     
823     if ( init_vis > 0 ) {
824       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
825         new FGLocalWeatherDatabase( position,
826                                     globals->get_fg_root(),
827                                     working_type,
828                                     init_vis );
829     } else {
830       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
831         new FGLocalWeatherDatabase( position,
832                                     globals->get_fg_root(),
833                                     working_type );
834     }
835
836     // cout << theFGLocalWeatherDatabase << endl;
837     // cout << "visibility = " 
838     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
839
840     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
841
842     // register the periodic update of the weather
843     global_events.Register( "weather update", fgUpdateWeatherDatabase,
844                             fgEVENT::FG_EVENT_READY, 30000);
845 #else
846     globals->get_environment_mgr()->init();
847     globals->get_environment_mgr()->bind();
848 #endif
849
850     ////////////////////////////////////////////////////////////////////
851     // Initialize vor/ndb/ils/fix list management and query systems
852     ////////////////////////////////////////////////////////////////////
853
854     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
855
856     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
857     current_navlist = new FGNavList;
858     SGPath p_nav( globals->get_fg_root() );
859     p_nav.append( "Navaids/default.nav" );
860     current_navlist->init( p_nav );
861
862     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
863     current_beacons = new FGMarkerBeacons;
864     current_beacons->init();
865     current_ilslist = new FGILSList;
866     SGPath p_ils( globals->get_fg_root() );
867     p_ils.append( "Navaids/default.ils" );
868     current_ilslist->init( p_ils );
869
870     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
871     current_fixlist = new FGFixList;
872     SGPath p_fix( globals->get_fg_root() );
873     p_fix.append( "Navaids/default.fix" );
874     current_fixlist->init( p_fix );
875
876     ////////////////////////////////////////////////////////////////////
877     // Initialize ATC list management and query systems
878     ////////////////////////////////////////////////////////////////////
879
880     //DCL
881     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
882     current_atislist = new FGATISList;
883     SGPath p_atis( globals->get_fg_root() );
884     p_atis.append( "ATC/default.atis" );
885     current_atislist->init( p_atis );
886
887     ////////////////////////////////////////////////////////////////////
888     // Initialise ATC display system
889     ////////////////////////////////////////////////////////////////////
890
891     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
892     globals->set_ATC_display(new FGATCDisplay);
893     globals->get_ATC_display()->init(); 
894
895     ////////////////////////////////////////////////////////////////////
896     // Initialise the ATC Manager 
897     ////////////////////////////////////////////////////////////////////
898
899     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
900     globals->set_ATC_mgr(new FGATCMgr);
901     globals->get_ATC_mgr()->init();     
902
903     ////////////////////////////////////////////////////////////////////
904     // Initialize the built-in commands.
905     ////////////////////////////////////////////////////////////////////
906     fgInitCommands();
907
908
909 #ifdef ENABLE_AUDIO_SUPPORT
910     ////////////////////////////////////////////////////////////////////
911     // Initialize the sound subsystem.
912     ////////////////////////////////////////////////////////////////////
913
914     globals->set_soundmgr(new FGSoundMgr);
915     globals->get_soundmgr()->init();
916     globals->get_soundmgr()->bind();
917
918
919     ////////////////////////////////////////////////////////////////////
920     // Initialize the sound-effects subsystem.
921     ////////////////////////////////////////////////////////////////////
922     globals->set_fx(new FGFX);
923     globals->get_fx()->init();
924     globals->get_fx()->bind();
925
926 #endif
927
928     ////////////////////////////////////////////////////////////////////
929     // Initialize the radio stack subsystem.
930     ////////////////////////////////////////////////////////////////////
931
932                                 // A textbook example of how FGSubsystem
933                                 // should work...
934     current_radiostack = new FGRadioStack;
935     current_radiostack->init();
936     current_radiostack->bind();
937
938
939     ////////////////////////////////////////////////////////////////////
940     // Initialize the cockpit subsystem
941     ////////////////////////////////////////////////////////////////////
942
943     if( fgCockpitInit( &current_aircraft )) {
944         // Cockpit initialized ok.
945     } else {
946         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
947         exit(-1);
948     }
949
950
951     ////////////////////////////////////////////////////////////////////
952     // Initialize the joystick subsystem.
953     ////////////////////////////////////////////////////////////////////
954
955     // if ( ! fgJoystickInit() ) {
956     //   SG_LOG( SG_GENERAL, SG_ALERT, "Error in Joystick initialization!" );
957     // }
958
959
960     ////////////////////////////////////////////////////////////////////
961     // Initialize the autopilot subsystem.
962     ////////////////////////////////////////////////////////////////////
963
964     current_autopilot = new FGAutopilot;
965     current_autopilot->init();
966
967     // initialize the gui parts of the autopilot
968     fgAPAdjustInit();
969     NewTgtAirportInit();
970     NewHeadingInit();
971     NewAltitudeInit();
972
973     ////////////////////////////////////////////////////////////////////
974     // Initialize I/O subsystem.
975     ////////////////////////////////////////////////////////////////////
976
977 #if ! defined( macintosh )
978     fgIOInit();
979 #endif
980
981     // Initialize the 2D panel.
982     string panel_path = fgGetString("/sim/panel/path",
983                                     "Panels/Default/default.xml");
984     current_panel = fgReadPanel(panel_path);
985     if (current_panel == 0) {
986         SG_LOG( SG_INPUT, SG_ALERT, 
987                 "Error reading new panel from " << panel_path );
988     } else {
989         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
990         current_panel->init();
991         current_panel->bind();
992     }
993
994     
995     ////////////////////////////////////////////////////////////////////
996     // Initialize the default (kludged) properties.
997     ////////////////////////////////////////////////////////////////////
998
999     fgInitProps();
1000
1001
1002     ////////////////////////////////////////////////////////////////////
1003     // Initialize the controls subsystem.
1004     ////////////////////////////////////////////////////////////////////
1005
1006     globals->get_controls()->init();
1007     globals->get_controls()->bind();
1008
1009
1010     ////////////////////////////////////////////////////////////////////
1011     // Initialize the input subsystem.
1012     ////////////////////////////////////////////////////////////////////
1013
1014     current_input.init();
1015     current_input.bind();
1016
1017
1018     ////////////////////////////////////////////////////////////////////////
1019     // End of subsystem initialization.
1020     ////////////////////////////////////////////////////////////////////
1021
1022     SG_LOG( SG_GENERAL, SG_INFO, endl);
1023
1024                                 // Save the initial state for future
1025                                 // reference.
1026     globals->saveInitialState();
1027
1028     return true;
1029 }
1030
1031
1032 void fgReInitSubsystems( void )
1033 {
1034     static const SGPropertyNode *longitude
1035         = fgGetNode("/position/longitude-deg");
1036     static const SGPropertyNode *latitude
1037         = fgGetNode("/position/latitude-deg");
1038     static const SGPropertyNode *altitude
1039         = fgGetNode("/position/altitude-ft");
1040     static const SGPropertyNode *master_freeze
1041         = fgGetNode("/sim/freeze/master");
1042
1043     SG_LOG( SG_GENERAL, SG_INFO,
1044             "/position/altitude = " << altitude->getDoubleValue() );
1045
1046     bool freeze = master_freeze->getBoolValue();
1047     if ( !freeze ) {
1048         fgSetBool("/sim/freeze/master", true);
1049     }
1050     
1051     // Initialize the Scenery Management subsystem
1052     scenery.init();
1053
1054 #if 0
1055     if( global_tile_mgr.init() ) {
1056         Load the local scenery data
1057         global_tile_mgr.update( longitude->getDoubleValue(),
1058                                 latitude->getDoubleValue() );
1059     } else {
1060         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1061         exit(-1);
1062     }
1063 #endif
1064
1065     fgInitFDM();
1066     
1067     // allocates structures so must happen before any of the flight
1068     // model or control parameters are set
1069     fgAircraftInit();   // In the future this might not be the case.
1070
1071     fgInitView();
1072
1073     globals->get_controls()->reset_all();
1074     current_autopilot->reset();
1075
1076     fgUpdateSunPos();
1077     fgUpdateMoonPos();
1078     cur_light_params.Update();
1079     fgUpdateLocalTime();
1080
1081     if ( !freeze ) {
1082         fgSetBool("/sim/freeze/master", false);
1083     }
1084 }