]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
b38b3536a2ba51466a124a0c2e2f23d83e8176b3
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <plib/netSocket.h>
38
39 #include <osg/Camera>
40 #include <osg/GraphicsContext>
41 #include <osgDB/Registry>
42
43 // Class references
44 #include <simgear/ephemeris/ephemeris.hxx>
45 #include <simgear/scene/model/modellib.hxx>
46 #include <simgear/scene/material/matlib.hxx>
47 #include <simgear/scene/model/animation.hxx>
48 #include <simgear/scene/sky/sky.hxx>
49 #include <simgear/structure/event_mgr.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/math/sg_random.h>
53
54 #include <Time/light.hxx>
55 #include <Include/general.hxx>
56 #include <Aircraft/replay.hxx>
57 #include <Cockpit/cockpit.hxx>
58 #include <Cockpit/hud.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/modelmgr.hxx>
61 #include <Model/acmodel.hxx>
62 #include <Scenery/scenery.hxx>
63 #include <Scenery/tilemgr.hxx>
64 #include <Sound/beacon.hxx>
65 #include <Sound/morse.hxx>
66 #include <FDM/flight.hxx>
67 #include <ATCDCL/ATCmgr.hxx>
68 #include <ATCDCL/AIMgr.hxx>
69 #include <Time/tmp.hxx>
70 #include <Time/fg_timer.hxx>
71 #include <Environment/environment_mgr.hxx>
72 #include <GUI/new_gui.hxx>
73 #include <MultiPlayer/multiplaymgr.hxx>
74
75 #include "CameraGroup.hxx"
76 #include "fg_commands.hxx"
77 #include "fg_io.hxx"
78 #include "renderer.hxx"
79 #include "splash.hxx"
80 #include "main.hxx"
81 #include "util.hxx"
82 #include "fg_init.hxx"
83 #include "WindowSystemAdapter.hxx"
84
85
86 static double real_delta_time_sec = 0.0;
87 double delta_time_sec = 0.0;
88 extern float init_volume;
89
90 using namespace flightgear;
91
92 using std::cerr;
93
94 // This is a record containing a bit of global housekeeping information
95 FGGeneral general;
96
97 // Specify our current idle function state.  This is used to run all
98 // our initializations out of the idle callback so that we can get a
99 // splash screen up and running right away.
100 int idle_state = 0;
101 long global_multi_loop;
102
103 SGTimeStamp last_time_stamp;
104 SGTimeStamp current_time_stamp;
105
106 // The atexit() function handler should know when the graphical subsystem
107 // is initialized.
108 extern int _bootstrap_OSInit;
109
110
111
112 // Update internal time dependent calculations (i.e. flight model)
113 // FIXME: this distinction is obsolete; all subsystems now get delta
114 // time on update.
115 void fgUpdateTimeDepCalcs() {
116     static bool inited = false;
117
118     static const SGPropertyNode *replay_state
119         = fgGetNode( "/sim/freeze/replay-state", true );
120     static SGPropertyNode *replay_time
121         = fgGetNode( "/sim/replay/time", true );
122     // static const SGPropertyNode *replay_end_time
123     //     = fgGetNode( "/sim/replay/end-time", true );
124
125     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
126
127     // Initialize the FDM here if it hasn't been and if we have a
128     // scenery elevation hit.
129
130     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
131     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
132
133     if (!cur_fdm_state->get_inited()) {
134         // Check for scenery around the aircraft.
135         double lon = fgGetDouble("/sim/presets/longitude-deg");
136         double lat = fgGetDouble("/sim/presets/latitude-deg");
137         // We require just to have 50 meter scenery availabe around
138         // the aircraft.
139         double range = 1000.0;
140         if (globals->get_scenery()->scenery_available(lat, lon, range)) {
141             //SG_LOG(SG_FLIGHT, SG_INFO, "Finally initializing fdm");
142             cur_fdm_state->init();
143             if ( cur_fdm_state->get_bound() ) {
144                 cur_fdm_state->unbind();
145             }
146             cur_fdm_state->bind();
147         }
148     }
149
150     // conceptually, the following block could be done for each fdm
151     // instance ...
152     if ( cur_fdm_state->get_inited() ) {
153         // we have been inited, and  we are good to go ...
154
155         if ( replay_state->getIntValue() == 0 ) {
156             // replay off, run fdm
157             cur_fdm_state->update( delta_time_sec );
158         } else {
159             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
160             r->replay( replay_time->getDoubleValue() );
161             if ( replay_state->getIntValue() == 1 ) {
162                 // normal playback
163                 replay_time->setDoubleValue( replay_time->getDoubleValue()
164                                              + ( delta_time_sec
165                                                * fgGetInt("/sim/speed-up") ) );
166             } else if ( replay_state->getIntValue() == 2 ) {
167                 // paused playback (don't advance replay time)
168             }
169         }
170
171         if ( !inited ) {
172             inited = true;
173             fgSetBool("/sim/signals/fdm-initialized", true);
174         }
175
176     } else {
177         // do nothing, fdm isn't inited yet
178     }
179
180     globals->get_model_mgr()->update(delta_time_sec);
181     globals->get_aircraft_model()->update(delta_time_sec);
182
183     // Update solar system
184     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
185                                   globals->get_time_params()->getLst(),
186                                   cur_fdm_state->get_Latitude() );
187
188 }
189
190
191 void fgInitTimeDepCalcs( void ) {
192     // noop for now
193 }
194
195
196 static const double alt_adjust_ft = 3.758099;
197 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
198
199
200 // What should we do when we have nothing else to do?  Let's get ready
201 // for the next move and update the display?
202 static void fgMainLoop( void ) {
203     int model_hz = fgGetInt("/sim/model-hz");
204
205     static SGConstPropertyNode_ptr longitude
206         = fgGetNode("/position/longitude-deg");
207     static SGConstPropertyNode_ptr latitude
208         = fgGetNode("/position/latitude-deg");
209     static SGConstPropertyNode_ptr altitude
210         = fgGetNode("/position/altitude-ft");
211     static SGConstPropertyNode_ptr clock_freeze
212         = fgGetNode("/sim/freeze/clock", true);
213     static SGConstPropertyNode_ptr cur_time_override
214         = fgGetNode("/sim/time/cur-time-override", true);
215     static SGConstPropertyNode_ptr max_simtime_per_frame
216         = fgGetNode("/sim/max-simtime-per-frame", true);
217     static SGPropertyNode_ptr frame_signal
218         = fgGetNode("/sim/signals/frame", true);
219
220     frame_signal->fireValueChanged();
221     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
222
223     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
224     bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
225
226     // Update the elapsed time.
227     static bool first_time = true;
228     if ( first_time ) {
229         last_time_stamp.stamp();
230         first_time = false;
231     }
232
233     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
234     if ( throttle_hz > 0.0 && !wait_for_scenery ) {
235         // optionally throttle the frame rate (to get consistent frame
236         // rates or reduce cpu usage.
237
238         double frame_us = 1000000.0 / throttle_hz;
239
240 #define FG_SLEEP_BASED_TIMING 1
241 #if defined(FG_SLEEP_BASED_TIMING)
242         // sleep based timing loop.
243         //
244         // Calling sleep, even usleep() on linux is less accurate than
245         // we like, but it does free up the cpu for other tasks during
246         // the sleep so it is desirable.  Because of the way sleep()
247         // is implemented in consumer operating systems like windows
248         // and linux, you almost always sleep a little longer than the
249         // requested amount.
250         //
251         // To combat the problem of sleeping too long, we calculate the
252         // desired wait time and shorten it by 2000us (2ms) to avoid
253         // [hopefully] over-sleep'ing.  The 2ms value was arrived at
254         // via experimentation.  We follow this up at the end with a
255         // simple busy-wait loop to get the final pause timing exactly
256         // right.
257         //
258         // Assuming we don't oversleep by more than 2000us, this
259         // should be a reasonable compromise between sleep based
260         // waiting, and busy waiting.
261
262         // sleep() will always overshoot by a bit so undersleep by
263         // 2000us in the hopes of never oversleeping.
264         frame_us -= 2000.0;
265         if ( frame_us < 0.0 ) {
266             frame_us = 0.0;
267         }
268         current_time_stamp.stamp();
269         /* Convert to ms */
270         double elapsed_us = current_time_stamp - last_time_stamp;
271         if ( elapsed_us < frame_us ) {
272             double requested_us = frame_us - elapsed_us;
273             ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
274         }
275 #endif
276
277         // busy wait timing loop.
278         //
279         // This yields the most accurate timing.  If the previous
280         // ulMilliSecondSleep() call is omitted this will peg the cpu
281         // (which is just fine if FG is the only app you care about.)
282         current_time_stamp.stamp();
283         while ( current_time_stamp - last_time_stamp < frame_us ) {
284             current_time_stamp.stamp();
285         }
286     } else {
287         // run as fast as the app will go
288         current_time_stamp.stamp();
289     }
290
291     real_delta_time_sec
292         = double(current_time_stamp - last_time_stamp) / 1000000.0;
293
294     // Limit the time we need to spend in simulation loops
295     // That means, if the /sim/max-simtime-per-frame value is strictly positive
296     // you can limit the maximum amount of time you will do simulations for
297     // one frame to display. The cpu time spent in simulations code is roughly
298     // at least O(real_delta_time_sec). If this is (due to running debug
299     // builds or valgrind or something different blowing up execution times)
300     // larger than the real time you will no longer get any response
301     // from flightgear. This limits that effect. Just set to property from
302     // your .fgfsrc or commandline ...
303     double dtMax = max_simtime_per_frame->getDoubleValue();
304     if (0 < dtMax && dtMax < real_delta_time_sec)
305         real_delta_time_sec = dtMax;
306
307     // round the real time down to a multiple of 1/model-hz.
308     // this way all systems are updated the _same_ amount of dt.
309     {
310         static double rem = 0.0;
311         real_delta_time_sec += rem;
312         double hz = model_hz;
313         double nit = floor(real_delta_time_sec*hz);
314         rem = real_delta_time_sec - nit/hz;
315         real_delta_time_sec = nit/hz;
316     }
317
318
319     if (clock_freeze->getBoolValue() || wait_for_scenery) {
320         delta_time_sec = 0;
321     } else {
322         delta_time_sec = real_delta_time_sec;
323     }
324     last_time_stamp = current_time_stamp;
325     globals->inc_sim_time_sec( delta_time_sec );
326
327     // These are useful, especially for Nasal scripts.
328     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
329     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
330
331     static long remainder = 0;
332     long elapsed;
333 #ifdef FANCY_FRAME_COUNTER
334     int i;
335     double accum;
336 #else
337     static time_t last_time = 0;
338     static int frames = 0;
339 #endif // FANCY_FRAME_COUNTER
340
341     SGTime *t = globals->get_time_params();
342
343     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
344     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
345
346     // Fix elevation.  I'm just sticking this here for now, it should
347     // probably move eventually
348
349     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
350            scenery.get_cur_elev(),
351            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
352            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
353
354     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
355            scenery.get_cur_elev(),
356            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
357            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
358
359     // cout << "Warp = " << globals->get_warp() << endl;
360
361     // update "time"
362     static bool last_clock_freeze = false;
363
364     if ( clock_freeze->getBoolValue() ) {
365         // clock freeze requested
366         if ( cur_time_override->getLongValue() == 0 ) {
367             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
368             globals->set_warp( 0 );
369         }
370     } else {
371         // no clock freeze requested
372         if ( last_clock_freeze == true ) {
373             // clock just unfroze, let's set warp as the difference
374             // between frozen time and current time so we don't get a
375             // time jump (and corresponding sky object and lighting
376             // jump.)
377             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
378             fgSetLong( "/sim/time/cur-time-override", 0 );
379         }
380         if ( globals->get_warp_delta() != 0 ) {
381             globals->inc_warp( globals->get_warp_delta() );
382         }
383     }
384
385     last_clock_freeze = clock_freeze->getBoolValue();
386
387     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
388                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
389                cur_time_override->getLongValue(),
390                globals->get_warp() );
391
392     if (globals->get_warp_delta() != 0) {
393         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
394         l->update( 0.5 );
395     }
396
397     // update magvar model
398     globals->get_mag()->update( longitude->getDoubleValue()
399                                 * SGD_DEGREES_TO_RADIANS,
400                                 latitude->getDoubleValue()
401                                 * SGD_DEGREES_TO_RADIANS,
402                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
403                                 globals->get_time_params()->getJD() );
404
405     // Get elapsed time (in usec) for this past frame
406     elapsed = fgGetTimeInterval();
407     SG_LOG( SG_ALL, SG_DEBUG,
408             "Elapsed time interval is = " << elapsed
409             << ", previous remainder is = " << remainder );
410
411     // Calculate frame rate average
412 #ifdef FANCY_FRAME_COUNTER
413     /* old fps calculation */
414     if ( elapsed > 0 ) {
415         double tmp;
416         accum = 0.0;
417         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
418             tmp = general.get_frame(i);
419             accum += tmp;
420             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
421             general.set_frame(i+1,tmp);
422         }
423         tmp = 1000000.0 / (float)elapsed;
424         general.set_frame(0,tmp);
425         // printf("frame[0] = %.2f\n", general.frames[0]);
426         accum += tmp;
427         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
428         // printf("ave = %.2f\n", general.frame_rate);
429     }
430 #else
431     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
432         general.set_frame_rate( frames );
433         fgSetInt("/sim/frame-rate", frames);
434         SG_LOG( SG_ALL, SG_DEBUG,
435             "--> Frame rate is = " << general.get_frame_rate() );
436         frames = 0;
437     }
438     last_time = t->get_cur_time();
439     ++frames;
440 #endif
441
442     // Update any multiplayer's network queues, the AIMultiplayer
443     // implementation is an AI model and depends on that
444     globals->get_multiplayer_mgr()->Update();
445
446     // Run ATC subsystem
447     if (fgGetBool("/sim/atc/enabled"))
448         globals->get_ATC_mgr()->update(delta_time_sec);
449
450     // Run the AI subsystem
451     // FIXME: run that also if we have multiplaying enabled since the
452     // multiplayer information is interpreted by an AI model
453     if (fgGetBool("/sim/ai-traffic/enabled"))
454         globals->get_AI_mgr()->update(delta_time_sec);
455
456     // Run flight model
457
458     // Calculate model iterations needed for next frame
459     elapsed += remainder;
460
461     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
462     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
463     SG_LOG( SG_ALL, SG_DEBUG,
464             "Model iterations needed = " << global_multi_loop
465             << ", new remainder = " << remainder );
466
467     // chop max iterations to something reasonable if the sim was
468     // delayed for an excessive amount of time
469     if ( global_multi_loop > 2.0 * model_hz ) {
470         global_multi_loop = (int)(2.0 * model_hz );
471         remainder = 0;
472     }
473
474     // flight model
475     if ( global_multi_loop > 0) {
476         // first run the flight model each frame until it is initialized
477         // then continue running each frame only after initial scenery load is complete.
478         fgUpdateTimeDepCalcs();
479     } else {
480         SG_LOG( SG_ALL, SG_DEBUG,
481             "Elapsed time is zero ... we're zinging" );
482     }
483
484     // Run audio scheduler
485 #ifdef ENABLE_AUDIO_SUPPORT
486     if ( globals->get_soundmgr()->is_working() ) {
487         globals->get_soundmgr()->update( delta_time_sec );
488     }
489 #endif
490
491     globals->get_subsystem_mgr()->update(delta_time_sec);
492
493     //
494     // Tile Manager updates - see if we need to load any new scenery tiles.
495     //   this code ties together the fdm, viewer and scenery classes...
496     //   we may want to move this to its own class at some point
497     //
498     double visibility_meters = fgGetDouble("/environment/visibility-m");
499     FGViewer *current_view = globals->get_current_view();
500
501     globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
502     // update tile manager for view...
503     SGLocation *view_location = globals->get_current_view()->getSGLocation();
504     globals->get_tile_mgr()->update( view_location, visibility_meters );
505     {
506         double lon = view_location->getLongitude_deg();
507         double lat = view_location->getLatitude_deg();
508         double alt = view_location->getAltitudeASL_ft() * SG_FEET_TO_METER;
509
510         // check if we can reuse the groundcache for that purpose.
511         double ref_time, r;
512         SGVec3d pt;
513         bool valid = cur_fdm_state->is_valid_m(&ref_time, pt.sg(), &r);
514         SGVec3d viewpos(globals->get_current_view()->get_view_pos());
515         if (valid && distSqr(viewpos, pt) < r*r) {
516             // Reuse the cache ...
517             double lev
518                 = cur_fdm_state->get_groundlevel_m(lat*SGD_DEGREES_TO_RADIANS,
519                                                    lon*SGD_DEGREES_TO_RADIANS,
520                                                    alt + 2.0);
521             view_location->set_cur_elev_m( lev );
522         } else {
523             // Do full intersection test.
524             double lev;
525             if (globals->get_scenery()->get_elevation_m(lat, lon, alt+2, lev, 0))
526                 view_location->set_cur_elev_m( lev );
527             else
528                 view_location->set_cur_elev_m( -9999.0 );
529         }
530     }
531
532     // run Nasal's settimer() loops right before the view manager
533     globals->get_event_mgr()->update(delta_time_sec);
534
535     // update the view angle as late as possible, but before sound calculations
536     globals->get_viewmgr()->update(delta_time_sec);
537
538     // Do any I/O channel work that might need to be done (must come after viewmgr)
539     globals->get_io()->update(real_delta_time_sec);
540
541 #ifdef ENABLE_AUDIO_SUPPORT
542     // Right now we make a simplifying assumption that the primary
543     // aircraft is the source of all sounds and that all sounds are
544     // positioned in the aircraft base
545
546     static sgdVec3 last_visitor_pos = {0, 0, 0};
547     static sgdVec3 last_model_pos = {0, 0, 0};
548
549     // get the orientation
550     const SGQuatd view_or = current_view->getViewOrientation();
551     SGQuatd surf_or = SGQuatd::fromLonLatDeg(
552         current_view->getLongitude_deg(), current_view->getLatitude_deg());
553     SGQuatd model_or = SGQuatd::fromYawPitchRollDeg(
554         globals->get_aircraft_model()->get3DModel()->getHeadingDeg(),
555         globals->get_aircraft_model()->get3DModel()->getPitchDeg(),
556         globals->get_aircraft_model()->get3DModel()->getRollDeg());
557
558     // get the up and at vector in the aircraft base
559     // (ok, the up vector is a down vector, but the coordinates
560     // are finally calculated in a left hand system and openal
561     // lives in a right hand system. Therefore we need to pass
562     // the down vector to get correct stereo sound.)
563     SGVec3d sgv_up = model_or.rotateBack(
564         surf_or.rotateBack(view_or.rotate(SGVec3d(0, 1, 0))));
565     sgVec3 up;
566     sgSetVec3(up, sgv_up[0], sgv_up[1], sgv_up[2]);
567     SGVec3d sgv_at = model_or.rotateBack(
568         surf_or.rotateBack(view_or.rotate(SGVec3d(0, 0, 1))));
569     sgVec3 at;
570     sgSetVec3(at, sgv_at[0], sgv_at[1], sgv_at[2]);
571
572     // get the location data for the primary FDM (now hardcoded to ac model)...
573     SGLocation *acmodel_loc = NULL;
574     acmodel_loc = (SGLocation *)globals->
575         get_aircraft_model()->get3DModel()->getSGLocation();
576
577     // calculate speed of visitor and model
578     sgVec3 listener_vel, model_vel;
579     SGVec3d SGV3d_help;
580     sgdVec3 sgdv3_help;
581     sgdVec3 sgdv3_null = {0, 0, 0};
582
583     sgdSubVec3( sgdv3_help,
584                 last_visitor_pos, (double *)&current_view->get_view_pos());
585     sgdAddVec3( last_visitor_pos, sgdv3_null, (double *)&current_view->get_view_pos());
586     SGV3d_help = model_or.rotateBack(
587         surf_or.rotateBack(SGVec3d(sgdv3_help[0],
588         sgdv3_help[1], sgdv3_help[2])));
589     sgSetVec3( listener_vel, SGV3d_help[0], SGV3d_help[1], SGV3d_help[2]);
590
591     sgdSubVec3( sgdv3_help,
592                 last_model_pos, acmodel_loc->get_absolute_view_pos());
593     sgdAddVec3( last_model_pos, sgdv3_null, acmodel_loc->get_absolute_view_pos());
594     SGV3d_help = model_or.rotateBack(
595         surf_or.rotateBack(SGVec3d(sgdv3_help[0],
596         sgdv3_help[1], sgdv3_help[2])));
597     sgSetVec3( model_vel, SGV3d_help[0], SGV3d_help[1], SGV3d_help[2]);
598
599     if (delta_time_sec > 0) {
600         sgScaleVec3( model_vel, 1 / delta_time_sec );
601         sgScaleVec3( listener_vel, 1 / delta_time_sec );
602     }
603
604     // checking, if the listener pos has moved suddenly
605     if (sgLengthVec3(listener_vel) > 1000)
606     {
607         // check if the relative speed model vs listener has moved suddenly, too
608         sgVec3 delta_vel;
609         sgSubVec3(delta_vel, listener_vel, model_vel );
610         if (sgLengthVec3(delta_vel) > 1000)
611             sgSetVec3(listener_vel, model_vel[0], model_vel[1], model_vel[2] ); // a sane value
612         else
613             globals->get_soundmgr()->set_listener_vel( listener_vel );
614     }
615     else
616         globals->get_soundmgr()->set_listener_vel( listener_vel );
617
618     // set positional offset for sources
619     sgdVec3 dsource_pos_offset;
620     sgdSubVec3( dsource_pos_offset,
621                 (double*) &current_view->get_view_pos(),
622                 acmodel_loc->get_absolute_view_pos() );
623     SGVec3d sgv_dsource_pos_offset = model_or.rotateBack(
624         surf_or.rotateBack(SGVec3d(dsource_pos_offset[0],
625         dsource_pos_offset[1], dsource_pos_offset[2])));
626
627     sgVec3 source_pos_offset;
628     sgSetVec3(source_pos_offset, sgv_dsource_pos_offset[0],
629         sgv_dsource_pos_offset[1], sgv_dsource_pos_offset[2]);
630
631     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
632
633     float orient[6];
634     for (int i = 0; i < 3; i++) {
635         orient[i] = sgv_at[i];
636         orient[i + 3] = sgv_up[i];
637     }
638     globals->get_soundmgr()->set_listener_orientation( orient );
639
640     // set the velocity
641     // all sources are defined to be in the model
642     globals->get_soundmgr()->set_source_vel_all( model_vel );
643
644     // The listener is always positioned at the origin.
645     sgVec3 listener_pos;
646     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
647     globals->get_soundmgr()->set_listener_pos( listener_pos );
648 #endif
649
650     // END Tile Manager udpates
651
652     if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
653         && cur_fdm_state->get_inited()) {
654         fgSetBool("sim/sceneryloaded",true);
655         fgSetFloat("/sim/sound/volume", init_volume);
656         globals->get_soundmgr()->set_volume(init_volume);
657     }
658
659     fgRequestRedraw();
660
661     SG_LOG( SG_ALL, SG_DEBUG, "" );
662 }
663
664 // Operation for querying OpenGL parameters. This must be done in a
665 // valid OpenGL context, potentially in another thread.
666 namespace
667 {
668 struct GeneralInitOperation : public GraphicsContextOperation
669 {
670     GeneralInitOperation()
671         : GraphicsContextOperation(std::string("General init"))
672     {
673     }
674     void run(osg::GraphicsContext* gc)
675     {
676         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
677         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
678         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
679         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
680
681         GLint tmp;
682         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
683         general.set_glMaxTexSize( tmp );
684         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
685
686         glGetIntegerv( GL_DEPTH_BITS, &tmp );
687         general.set_glDepthBits( tmp );
688         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
689     }
690 };
691 }
692
693 // This is the top level master main function that is registered as
694 // our idle funciton
695
696 // The first few passes take care of initialization things (a couple
697 // per pass) and once everything has been initialized fgMainLoop from
698 // then on.
699
700 static void fgIdleFunction ( void ) {
701     static osg::ref_ptr<GeneralInitOperation> genOp;
702     if ( idle_state == 0 ) {
703         idle_state++;
704         // Pick some window on which to do queries.
705         // XXX Perhaps all this graphics initialization code should be
706         // moved to renderer.cxx?
707         genOp = new GeneralInitOperation;
708         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
709         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
710         osg::GraphicsContext* gc = 0;
711         if (guiCamera)
712             gc = guiCamera->getGraphicsContext();
713         if (gc) {
714             gc->add(genOp.get());
715         } else {
716             wsa->windows[0]->gc->add(genOp.get());
717         }
718         guiStartInit(gc);
719     } else if ( idle_state == 1 ) {
720         if (genOp.valid()) {
721             if (!genOp->isFinished())
722                 return;
723             genOp = 0;
724         }
725         if (!guiFinishInit())
726             return;
727         idle_state++;
728         fgSplashProgress("reading aircraft list");
729
730
731     } else if ( idle_state == 2 ) {
732         idle_state++;
733         // Read the list of available aircraft
734         fgReadAircraft();
735         fgSplashProgress("reading airport & navigation data");
736
737
738     } else if ( idle_state == 3 ) {
739         idle_state++;
740         fgInitNav();
741         fgSplashProgress("setting up scenery");
742
743
744     } else if ( idle_state == 4 ) {
745         idle_state++;
746         // based on the requested presets, calculate the true starting
747         // lon, lat
748         fgInitPosition();
749         fgInitTowerLocationListener();
750
751         SGTime *t = fgInitTime();
752         globals->set_time_params( t );
753
754         // Do some quick general initializations
755         if( !fgInitGeneral()) {
756             SG_LOG( SG_GENERAL, SG_ALERT,
757                 "General initialization failed ..." );
758             exit(-1);
759         }
760
761         ////////////////////////////////////////////////////////////////////
762         // Initialize the property-based built-in commands
763         ////////////////////////////////////////////////////////////////////
764         fgInitCommands();
765
766
767         ////////////////////////////////////////////////////////////////////
768         // Initialize the material manager
769         ////////////////////////////////////////////////////////////////////
770         globals->set_matlib( new SGMaterialLib );
771         simgear::SGModelLib::init(globals->get_fg_root());
772
773
774         ////////////////////////////////////////////////////////////////////
775         // Initialize the TG scenery subsystem.
776         ////////////////////////////////////////////////////////////////////
777         globals->set_scenery( new FGScenery );
778         globals->get_scenery()->init();
779         globals->get_scenery()->bind();
780         globals->set_tile_mgr( new FGTileMgr );
781
782
783         ////////////////////////////////////////////////////////////////////
784         // Initialize the general model subsystem.
785         ////////////////////////////////////////////////////////////////////
786         globals->set_model_mgr(new FGModelMgr);
787         globals->get_model_mgr()->init();
788         globals->get_model_mgr()->bind();
789         fgSplashProgress("loading aircraft");
790
791
792     } else if ( idle_state == 5 ) {
793         idle_state++;
794         ////////////////////////////////////////////////////////////////////
795         // Initialize the 3D aircraft model subsystem (has a dependency on
796         // the scenery subsystem.)
797         ////////////////////////////////////////////////////////////////////
798         globals->set_aircraft_model(new FGAircraftModel);
799         globals->get_aircraft_model()->init();
800         globals->get_aircraft_model()->bind();
801
802         ////////////////////////////////////////////////////////////////////
803         // Initialize the view manager subsystem.
804         ////////////////////////////////////////////////////////////////////
805         FGViewMgr *viewmgr = new FGViewMgr;
806         globals->set_viewmgr( viewmgr );
807         viewmgr->init();
808         viewmgr->bind();
809         fgSplashProgress("generating sky elements");
810
811
812     } else if ( idle_state == 6 ) {
813         idle_state++;
814         // Initialize the sky
815         SGPath ephem_data_path( globals->get_fg_root() );
816         ephem_data_path.append( "Astro" );
817         SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
818         ephem->update( globals->get_time_params()->getMjd(),
819                        globals->get_time_params()->getLst(),
820                        0.0 );
821         globals->set_ephem( ephem );
822
823         // TODO: move to environment mgr
824         thesky = new SGSky;
825         SGPath texture_path(globals->get_fg_root());
826         texture_path.append("Textures");
827         texture_path.append("Sky");
828         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
829             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
830             thesky->add_cloud_layer(layer);
831         }
832
833         SGPath sky_tex_path( globals->get_fg_root() );
834         sky_tex_path.append( "Textures" );
835         sky_tex_path.append( "Sky" );
836         thesky->texture_path( sky_tex_path.str() );
837
838         // The sun and moon diameters are scaled down numbers of the
839         // actual diameters. This was needed to fit both the sun and the
840         // moon within the distance to the far clip plane.
841         // Moon diameter:    3,476 kilometers
842         // Sun diameter: 1,390,000 kilometers
843         thesky->build( 80000.0, 80000.0,
844                        463.3, 361.8,
845                        globals->get_ephem()->getNumPlanets(),
846                        globals->get_ephem()->getPlanets(),
847                        globals->get_ephem()->getNumStars(),
848                        globals->get_ephem()->getStars(),
849                        fgGetNode("/environment", true));
850
851         // Initialize MagVar model
852         SGMagVar *magvar = new SGMagVar();
853         globals->set_mag( magvar );
854
855
856                                     // kludge to initialize mag compass
857                                     // (should only be done for in-flight
858                                     // startup)
859         // update magvar model
860         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
861                                     * SGD_DEGREES_TO_RADIANS,
862                                     fgGetDouble("/position/latitude-deg")
863                                     * SGD_DEGREES_TO_RADIANS,
864                                     fgGetDouble("/position/altitude-ft")
865                                     * SG_FEET_TO_METER,
866                                     globals->get_time_params()->getJD() );
867         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
868         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
869         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
870
871
872         // airport = new ssgBranch;
873         // airport->setName( "Airport Lighting" );
874         // lighting->addKid( airport );
875
876         // build our custom render states
877         fgSplashProgress("initializing subsystems");
878
879
880     } else if ( idle_state == 7 ) {
881         idle_state++;
882         // Initialize audio support
883 #ifdef ENABLE_AUDIO_SUPPORT
884
885         // Start the intro music
886         if ( fgGetBool("/sim/startup/intro-music") ) {
887             SGPath mp3file( globals->get_fg_root() );
888             mp3file.append( "Sounds/intro.mp3" );
889
890             SG_LOG( SG_GENERAL, SG_INFO,
891                 "Starting intro music: " << mp3file.str() );
892
893 #if defined( __CYGWIN__ )
894             string command = "start /m `cygpath -w " + mp3file.str() + "`";
895 #elif defined( WIN32 )
896             string command = "start /m " + mp3file.str();
897 #else
898             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
899 #endif
900
901             system ( command.c_str() );
902         }
903 #endif
904         // This is the top level init routine which calls all the
905         // other subsystem initialization routines.  If you are adding
906         // a subsystem to flightgear, its initialization call should be
907         // located in this routine.
908         if( !fgInitSubsystems()) {
909             SG_LOG( SG_GENERAL, SG_ALERT,
910                 "Subsystem initialization failed ..." );
911             exit(-1);
912         }
913         fgSplashProgress("setting up time & renderer");
914
915
916     } else if ( idle_state == 8 ) {
917         idle_state = 1000;
918         // Initialize the time offset (warp) after fgInitSubsystem
919         // (which initializes the lighting interpolation tables.)
920         fgInitTimeOffset();
921
922         // setup OpenGL view parameters
923         globals->get_renderer()->init();
924
925         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
926         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
927                                          fgGetInt("/sim/startup/ysize") );
928
929         fgSplashProgress("loading scenery objects");
930
931     }
932
933     if ( idle_state == 1000 ) {
934         // We've finished all our initialization steps, from now on we
935         // run the main loop.
936         fgSetBool("sim/sceneryloaded", false);
937         fgRegisterIdleHandler( fgMainLoop );
938     }
939 }
940
941
942 static void upper_case_property(const char *name)
943 {
944     SGPropertyNode *p = fgGetNode(name, false);
945     if (!p) {
946         p = fgGetNode(name, true);
947         p->setStringValue("");
948     } else {
949         SGPropertyNode::Type t = p->getType();
950         if (t == SGPropertyNode::NONE || t == SGPropertyNode::UNSPECIFIED)
951             p->setStringValue("");
952         else
953             assert(t == SGPropertyNode::STRING);
954     }
955     p->addChangeListener(new FGMakeUpperCase);
956 }
957
958
959 // Main top level initialization
960 bool fgMainInit( int argc, char **argv ) {
961
962     // set default log levels
963     sglog().setLogLevels( SG_ALL, SG_ALERT );
964
965     string version;
966 #ifdef FLIGHTGEAR_VERSION
967     version = FLIGHTGEAR_VERSION;
968 #else
969     version = "unknown version";
970 #endif
971     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
972             << version );
973     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
974
975     // Allocate global data structures.  This needs to happen before
976     // we parse command line options
977
978     globals = new FGGlobals;
979
980     // seed the random number generator
981     sg_srandom_time();
982
983     FGControls *controls = new FGControls;
984     globals->set_controls( controls );
985
986     string_list *col = new string_list;
987     globals->set_channel_options_list( col );
988
989     fgValidatePath("", false);  // initialize static variables
990     upper_case_property("/sim/presets/airport-id");
991     upper_case_property("/sim/presets/runway");
992     upper_case_property("/sim/tower/airport-id");
993     upper_case_property("/autopilot/route-manager/input");
994
995     // Scan the config file(s) and command line options to see if
996     // fg_root was specified (ignore all other options for now)
997     fgInitFGRoot(argc, argv);
998
999     // Check for the correct base package version
1000     static char required_version[] = "1.0.0";
1001     string base_version = fgBasePackageVersion();
1002     if ( !(base_version == required_version) ) {
1003         // tell the operator how to use this application
1004
1005         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1006         cerr << endl << "Base package check failed ... " \
1007              << "Found version " << base_version << " at: " \
1008              << globals->get_fg_root() << endl;
1009         cerr << "Please upgrade to version: " << required_version << endl;
1010 #ifdef _MSC_VER
1011         cerr << "Hit a key to continue..." << endl;
1012         cin.get();
1013 #endif
1014         exit(-1);
1015     }
1016
1017     // Load the configuration parameters.  (Command line options
1018     // override config file options.  Config file options override
1019     // defaults.)
1020     if ( !fgInitConfig(argc, argv) ) {
1021         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1022         exit(-1);
1023     }
1024
1025     // Initialize the Window/Graphics environment.
1026     fgOSInit(&argc, argv);
1027     _bootstrap_OSInit++;
1028
1029     fgRegisterWindowResizeHandler( &FGRenderer::resize );
1030     fgRegisterIdleHandler( &fgIdleFunction );
1031     fgRegisterDrawHandler( &FGRenderer::update );
1032
1033 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1034     bool get_stencil_buffer = true;
1035 #else
1036     bool get_stencil_buffer = false;
1037 #endif
1038
1039     // Initialize plib net interface
1040     netInit( &argc, argv );
1041
1042     // Clouds3D requires an alpha channel
1043     // clouds may require stencil buffer
1044     fgOSOpenWindow(get_stencil_buffer);
1045
1046     // Initialize the splash screen right away
1047     fntInit();
1048     fgSplashInit();
1049
1050     // pass control off to the master event handler
1051     fgOSMainLoop();
1052
1053     // we never actually get here ... but to avoid compiler warnings,
1054     // etc.
1055     return false;
1056 }
1057
1058