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