]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
- implement progress information (enabled by default; can be turned off via
[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., 675 Mass Ave, Cambridge, MA 02139, 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 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/netSocket.h>
45
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
49
50 // Class references
51 #include <simgear/ephemeris/ephemeris.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/animation.hxx>
55 #include <simgear/scene/sky/sky.hxx>
56 #include <Time/light.hxx>
57 #include <Include/general.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Model/modelmgr.hxx>
62 #include <Model/acmodel.hxx>
63 #include <Scenery/scenery.hxx>
64 #include <Scenery/tilemgr.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <FDM/flight.hxx>
68 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
69 // #include <FDM/ADA.hxx>
70 #include <ATC/ATCdisplay.hxx>
71 #include <ATC/ATCmgr.hxx>
72 #include <ATC/AIMgr.hxx>
73 #include <Replay/replay.hxx>
74 #include <Time/tmp.hxx>
75 #include <Time/fg_timer.hxx>
76 #include <Environment/environment_mgr.hxx>
77 #include <GUI/new_gui.hxx>
78
79 #ifdef FG_MPLAYER_AS
80 #include <MultiPlayer/multiplaytxmgr.hxx>
81 #include <MultiPlayer/multiplayrxmgr.hxx>
82 #endif
83
84
85
86 #include "fg_commands.hxx"
87 #include "fg_io.hxx"
88 #include "renderer.hxx"
89 #include "splash.hxx"
90 #include "main.hxx"
91
92
93
94 static double real_delta_time_sec = 0.0;
95 double delta_time_sec = 0.0;
96 extern float init_volume;
97
98
99 #ifdef macintosh
100 #  include <console.h>          // -dw- for command line dialog
101 #endif
102
103 // This is a record containing a bit of global housekeeping information
104 FGGeneral general;
105
106 // Specify our current idle function state.  This is used to run all
107 // our initializations out of the idle callback so that we can get a
108 // splash screen up and running right away.
109 int idle_state = 0;
110 long global_multi_loop;
111
112 SGTimeStamp last_time_stamp;
113 SGTimeStamp current_time_stamp;
114
115 // The atexit() functio handler should know when the graphical subsystem
116 // is initialized.
117 extern int _bootstrap_OSInit;
118
119
120
121 // Update internal time dependent calculations (i.e. flight model)
122 // FIXME: this distinction is obsolete; all subsystems now get delta
123 // time on update.
124 void fgUpdateTimeDepCalcs() {
125     static bool inited = false;
126
127     static const SGPropertyNode *replay_state
128         = fgGetNode( "/sim/freeze/replay-state", true );
129     static SGPropertyNode *replay_time
130         = fgGetNode( "/sim/replay/time", true );
131     // static const SGPropertyNode *replay_end_time
132     //     = fgGetNode( "/sim/replay/end-time", true );
133
134     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
135
136     // Initialize the FDM here if it hasn't been and if we have a
137     // scenery elevation hit.
138
139     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
140     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
141
142     if ( !cur_fdm_state->get_inited() &&
143          globals->get_scenery()->get_cur_elev() > -9990 )
144     {
145         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
146         cur_fdm_state->init();
147         if ( cur_fdm_state->get_bound() ) {
148             cur_fdm_state->unbind();
149         }
150         cur_fdm_state->bind();
151     }
152
153     // conceptually, the following block could be done for each fdm
154     // instance ...
155     if ( cur_fdm_state->get_inited() ) {
156         // we have been inited, and  we are good to go ...
157
158         if ( !inited ) {
159             inited = true;
160         }
161
162         if ( replay_state->getIntValue() == 0 ) {
163             // replay off, run fdm
164             cur_fdm_state->update( delta_time_sec );
165         } else {
166             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
167             r->replay( replay_time->getDoubleValue() );
168             if ( replay_state->getIntValue() == 1 ) {
169                 // normal playback
170                 replay_time->setDoubleValue( replay_time->getDoubleValue()
171                                              + ( delta_time_sec
172                                                * fgGetInt("/sim/speed-up") ) );
173             } else if ( replay_state->getIntValue() == 2 ) {
174                 // paused playback (don't advance replay time)
175             }
176         }
177     } else {
178         // do nothing, fdm isn't inited yet
179     }
180
181     globals->get_model_mgr()->update(delta_time_sec);
182     globals->get_aircraft_model()->update(delta_time_sec);
183
184     // update the view angle
185     globals->get_viewmgr()->update(delta_time_sec);
186
187     // Update solar system
188     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
189                                   globals->get_time_params()->getLst(),
190                                   cur_fdm_state->get_Latitude() );
191
192 }
193
194
195 void fgInitTimeDepCalcs( void ) {
196     // noop for now
197 }
198
199
200 static const double alt_adjust_ft = 3.758099;
201 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
202
203
204 // What should we do when we have nothing else to do?  Let's get ready
205 // for the next move and update the display?
206 static void fgMainLoop( void ) {
207     int model_hz = fgGetInt("/sim/model-hz");
208
209     static const SGPropertyNode *longitude
210         = fgGetNode("/position/longitude-deg");
211     static const SGPropertyNode *latitude
212         = fgGetNode("/position/latitude-deg");
213     static const SGPropertyNode *altitude
214         = fgGetNode("/position/altitude-ft");
215     static const SGPropertyNode *clock_freeze
216         = fgGetNode("/sim/freeze/clock", true);
217     static const SGPropertyNode *cur_time_override
218         = fgGetNode("/sim/time/cur-time-override", true);
219
220     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
221
222     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
223
224     // Update the elapsed time.
225     static bool first_time = true;
226     if ( first_time ) {
227         last_time_stamp.stamp();
228         first_time = false;
229     }
230
231     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
232     if ( throttle_hz > 0.0 && scenery_loaded ) {
233         // optionally throttle the frame rate (to get consistant frame
234         // rates or reduce cpu usage.
235
236         double frame_us = 1000000.0 / throttle_hz;
237
238 #define FG_SLEEP_BASED_TIMING 1
239 #if defined(FG_SLEEP_BASED_TIMING)
240         // sleep based timing loop.
241         //
242         // Calling sleep, even usleep() on linux is less accurate than
243         // we like, but it does free up the cpu for other tasks during
244         // the sleep so it is desireable.  Because of the way sleep()
245         // is implimented in consumer operating systems like windows
246         // and linux, you almost always sleep a little longer than the
247         // requested amount.
248         // 
249         // To combat the problem of sleeping to long, we calculate the
250         // desired wait time and shorten it by 2000us (2ms) to avoid
251         // [hopefully] over-sleep'ing.  The 2ms value was arrived at
252         // via experimentation.  We follow this up at the end with a
253         // simple busy-wait loop to get the final pause timing exactly
254         // right.
255         // 
256         // Assuming we don't oversleep by more than 2000us, this
257         // should be a reasonable compromise between sleep based
258         // waiting, and busy waiting.
259
260         // sleep() will always overshoot by a bit so undersleep by
261         // 2000us in the hopes of never oversleeping.
262         frame_us -= 2000.0;
263         if ( frame_us < 0.0 ) {
264             frame_us = 0.0;
265         }
266         current_time_stamp.stamp();
267         /* Convert to ms */
268         double elapsed_us = current_time_stamp - last_time_stamp;
269         if ( elapsed_us < frame_us ) {
270             double requested_us = frame_us - elapsed_us;
271             ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
272         }
273 #endif
274
275         // busy wait timing loop.
276         // 
277         // This yields the most accurate timing.  If the previous
278         // ulMilliSecondSleep() call is ommitted this will peg the cpu
279         // (which is just fine if FG is the only app you care about.)
280         current_time_stamp.stamp();
281         while ( current_time_stamp - last_time_stamp < frame_us ) {
282             current_time_stamp.stamp();
283         }
284     } else {
285         // run as fast as the app will go
286         current_time_stamp.stamp();
287     }
288
289     real_delta_time_sec
290         = double(current_time_stamp - last_time_stamp) / 1000000.0;
291     // round the real time down to a multiple of 1/model-hz.
292     // this way all systems are updated the _same_ amount of dt.
293     {
294       static double rem = 0.0;
295       real_delta_time_sec += rem;
296       double hz = model_hz;
297       double nit = floor(real_delta_time_sec*hz);
298       rem = real_delta_time_sec - nit/hz;
299       real_delta_time_sec = nit/hz;
300     }
301
302
303     if ( clock_freeze->getBoolValue() ) {
304         delta_time_sec = 0;
305     } else {
306         delta_time_sec = real_delta_time_sec;
307     }
308     last_time_stamp = current_time_stamp;
309     globals->inc_sim_time_sec( delta_time_sec );
310     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
311
312     // These are useful, especially for Nasal scripts.
313     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
314     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
315
316     static long remainder = 0;
317     long elapsed;
318 #ifdef FANCY_FRAME_COUNTER
319     int i;
320     double accum;
321 #else
322     static time_t last_time = 0;
323     static int frames = 0;
324 #endif // FANCY_FRAME_COUNTER
325
326     SGTime *t = globals->get_time_params();
327
328     globals->get_event_mgr()->update(delta_time_sec);
329
330     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
331     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
332
333 #if defined( ENABLE_PLIB_JOYSTICK )
334     // Read joystick and update control settings
335     // if ( fgGetString("/sim/control-mode") == "joystick" )
336     // {
337     //    fgJoystickRead();
338     // }
339 #endif
340
341     // Fix elevation.  I'm just sticking this here for now, it should
342     // probably move eventually
343
344     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
345            scenery.get_cur_elev(),
346            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
347            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
348
349     /* printf("Adjustment - 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     // cout << "Warp = " << globals->get_warp() << endl;
355
356     // update "time"
357     static bool last_clock_freeze = false;
358
359     if ( clock_freeze->getBoolValue() ) {
360         // clock freeze requested
361         if ( cur_time_override->getLongValue() == 0 ) {
362             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
363             globals->set_warp( 0 );
364         }
365     } else {
366         // no clock freeze requested
367         if ( last_clock_freeze == true ) {
368             // clock just unfroze, let's set warp as the difference
369             // between frozen time and current time so we don't get a
370             // time jump (and corresponding sky object and lighting
371             // jump.)
372             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
373             fgSetLong( "/sim/time/cur-time-override", 0 );
374         }
375         if ( globals->get_warp_delta() != 0 ) {
376             globals->inc_warp( globals->get_warp_delta() );
377         }
378     }
379
380     last_clock_freeze = clock_freeze->getBoolValue();
381
382     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
383                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
384                cur_time_override->getLongValue(),
385                globals->get_warp() );
386
387     if (globals->get_warp_delta() != 0) {
388         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
389         l->update( 0.5 );
390     }
391
392     // update magvar model
393     globals->get_mag()->update( longitude->getDoubleValue()
394                               * SGD_DEGREES_TO_RADIANS,
395                             latitude->getDoubleValue()
396                               * SGD_DEGREES_TO_RADIANS,
397                             altitude->getDoubleValue() * SG_FEET_TO_METER,
398                             globals->get_time_params()->getJD() );
399
400     // Get elapsed time (in usec) for this past frame
401     elapsed = fgGetTimeInterval();
402     SG_LOG( SG_ALL, SG_DEBUG, 
403             "Elapsed time interval is = " << elapsed 
404             << ", previous remainder is = " << remainder );
405
406     // Calculate frame rate average
407 #ifdef FANCY_FRAME_COUNTER
408     /* old fps calculation */
409     if ( elapsed > 0 ) {
410         double tmp;
411         accum = 0.0;
412         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
413             tmp = general.get_frame(i);
414             accum += tmp;
415             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
416             general.set_frame(i+1,tmp);
417         }
418         tmp = 1000000.0 / (float)elapsed;
419         general.set_frame(0,tmp);
420         // printf("frame[0] = %.2f\n", general.frames[0]);
421         accum += tmp;
422         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
423         // printf("ave = %.2f\n", general.frame_rate);
424     }
425 #else
426     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
427         general.set_frame_rate( frames );
428         fgSetInt("/sim/frame-rate", frames);
429         SG_LOG( SG_ALL, SG_DEBUG, 
430             "--> Frame rate is = " << general.get_frame_rate() );
431         frames = 0;
432     }
433     last_time = t->get_cur_time();
434     ++frames;
435 #endif
436
437     // Run ATC subsystem
438     if (fgGetBool("/sim/ATC/enabled"))
439         globals->get_ATC_mgr()->update(delta_time_sec);
440
441     // Run the AI subsystem
442     if (fgGetBool("/sim/ai-traffic/enabled"))
443         globals->get_AI_mgr()->update(delta_time_sec);
444
445 #ifdef FG_MPLAYER_AS
446     // Update any multiplayer models
447     globals->get_multiplayer_rx_mgr()->Update();
448 #endif
449
450     // Run flight model
451
452     // Calculate model iterations needed for next frame
453     elapsed += remainder;
454
455     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
456     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
457     SG_LOG( SG_ALL, SG_DEBUG, 
458             "Model iterations needed = " << global_multi_loop
459             << ", new remainder = " << remainder );
460         
461     // chop max interations to something reasonable if the sim was
462     // delayed for an excesive amount of time
463     if ( global_multi_loop > 2.0 * model_hz ) {
464         global_multi_loop = (int)(2.0 * model_hz );
465         remainder = 0;
466     }
467
468     // flight model
469     if ( global_multi_loop > 0) {
470         // first run the flight model each frame until it is intialized
471         // then continue running each frame only after initial scenery load is complete.
472         if (!cur_fdm_state->get_inited() || scenery_loaded) {
473             fgUpdateTimeDepCalcs();
474         }
475     } else {
476         SG_LOG( SG_ALL, SG_DEBUG, 
477             "Elapsed time is zero ... we're zinging" );
478     }
479
480     // Do any I/O channel work that might need to be done
481     globals->get_io()->update( real_delta_time_sec );
482
483     // see if we need to load any deferred-load textures
484     globals->get_matlib()->load_next_deferred();
485
486     // Run audio scheduler
487 #ifdef ENABLE_AUDIO_SUPPORT
488     if ( globals->get_soundmgr()->is_working() ) {
489         globals->get_soundmgr()->update( delta_time_sec );
490     }
491 #endif
492
493     globals->get_subsystem_mgr()->update(delta_time_sec);
494
495     //
496     // Tile Manager updates - see if we need to load any new scenery tiles.
497     //   this code ties together the fdm, viewer and scenery classes...
498     //   we may want to move this to it's own class at some point
499     //
500     double visibility_meters = fgGetDouble("/environment/visibility-m");
501     FGViewer *current_view = globals->get_current_view();
502
503     // Let the scenery center follow the current view position with
504     // 30m increments.
505     //
506     // Having the scenery center near the view position will eliminate
507     // jitter of objects which are placed very near the view position
508     // and haveing it's center near that view position.
509     // So the 3d insruments of the aircraft will not jitter with this.
510     // 
511     // Following the view position exactly would introduce jitter of
512     // the scenery tiles (they would be from their center up to 10000m
513     // to the view and this will introduce roundoff too). By stepping
514     // at 30m incements the roundoff error of the scenery tiles is
515     // still present, but we will make exactly the same roundoff error
516     // at each frame until the center is switched to a new
517     // position. This roundoff is still visible but you will most
518     // propably not notice.
519     double *vp = globals->get_current_view()->get_absolute_view_pos();
520     Point3D cntr(vp[0], vp[1], vp[2]);
521     if (30.0*30.0 < cntr.distance3Dsquared(globals->get_scenery()->get_center())) {
522       globals->get_scenery()->set_next_center( cntr );
523     }
524
525     // get the location data for the primary FDM (now hardcoded to ac model)...
526     SGLocation *acmodel_loc = NULL;
527     acmodel_loc = (SGLocation *)globals->
528         get_aircraft_model()->get3DModel()->getSGLocation();
529
530     // update tile manager for FDM...
531     // ...only if location is different than the current-view location
532     // (to avoid duplicating effort)
533     if( !fgGetBool("/sim/current-view/config/from-model") ) {
534         if( acmodel_loc != NULL ) {
535             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
536                                                      visibility_meters );
537             globals->get_tile_mgr()->
538                 update( acmodel_loc, visibility_meters,
539                         acmodel_loc->
540                         get_absolute_view_pos(globals->
541                                               get_scenery()->get_center()) );
542             globals->get_scenery()->set_center( cntr );
543
544             // save results of update in SGLocation for fdm...
545             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
546                 acmodel_loc->
547                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
548                 fgSetDouble("/position/ground-elev-m",
549                             globals->get_scenery()->get_cur_elev());
550             }
551             acmodel_loc->
552                 set_tile_center( globals->get_scenery()->get_next_center() );
553         }
554     }
555
556     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
557                                              visibility_meters );
558     // update tile manager for view...
559     // IMPORTANT!!! the tilemgr update for view location _must_ be
560     // done last after the FDM's until all of Flight Gear code
561     // references the viewer's location for elevation instead of the
562     // "scenery's" current elevation.
563     SGLocation *view_location = globals->get_current_view()->getSGLocation();
564     globals->get_tile_mgr()->update( view_location, visibility_meters,
565                                      current_view->get_absolute_view_pos() );
566     globals->get_scenery()->set_center( cntr );
567     // save results of update in SGLocation for fdm...
568     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
569         current_view->getSGLocation()->
570             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
571     }
572     current_view->getSGLocation()->
573         set_tile_center( globals->get_scenery()->get_next_center() );
574
575 #ifdef ENABLE_AUDIO_SUPPORT
576     // Right now we make a simplifying assumption that the primary
577     // aircraft is the source of all sounds and that all sounds are
578     // positioned relative to the current view position.
579
580     static sgVec3 last_pos_offset;
581
582     // set positional offset for sources
583     sgVec3 source_pos_offset;
584     sgSubVec3( source_pos_offset,
585                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
586     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
587     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
588
589     // set the velocity
590     sgVec3 source_vel;
591     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
592     sgScaleVec3( source_vel, delta_time_sec );
593     sgCopyVec3( last_pos_offset, source_pos_offset );
594     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
595     globals->get_soundmgr()->set_source_vel_all( source_vel );
596
597     // Right now we make a simplifying assumption that the listener is
598     // always positioned at the origin.
599     sgVec3 listener_pos;
600     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
601     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
602     globals->get_soundmgr()->set_listener_pos( listener_pos );
603 #endif
604
605     // If fdm location is same as viewer's then we didn't do the
606     // update for fdm location above so we need to save the viewer
607     // results in the fdm SGLocation as well...
608     if( fgGetBool("/sim/current-view/config/from-model") ) {
609         if( acmodel_loc != 0 ) {
610             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
611                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
612                                              get_cur_elev() );
613                 fgSetDouble("/position/ground-elev-m",
614                             globals->get_scenery()->get_cur_elev());
615             }
616             acmodel_loc->set_tile_center( globals->get_scenery()->
617                                           get_next_center() );
618         }
619     }
620
621     // END Tile Manager udpates
622
623     if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
624         fgSetBool("sim/sceneryloaded",true);
625         fgSetFloat("/sim/sound/volume", init_volume);
626         globals->get_soundmgr()->set_volume(init_volume);
627     }
628
629     if (fgGetBool("/sim/rendering/specular-highlight")) {
630         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
631         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
632     } else {
633         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
634         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
635     }
636
637     fgRequestRedraw();
638
639     SG_LOG( SG_ALL, SG_DEBUG, "" );
640 }
641
642
643 // This is the top level master main function that is registered as
644 // our idle funciton
645
646 // The first few passes take care of initialization things (a couple
647 // per pass) and once everything has been initialized fgMainLoop from
648 // then on.
649
650 static void fgIdleFunction ( void ) {
651     if ( idle_state == 0 ) {
652         idle_state++;
653         fgSplashProgress("setting up scenegraph & user interface");
654
655
656     } else if ( idle_state == 1 ) {
657         idle_state++;
658         // This seems to be the absolute earliest in the init sequence
659         // that these calls will return valid info.  Too bad it's after
660         // we've already created and sized out window. :-(
661         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
662         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
663         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
664         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
665
666         GLint tmp;
667         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
668         general.set_glMaxTexSize( tmp );
669         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
670
671         glGetIntegerv( GL_DEPTH_BITS, &tmp );
672         general.set_glDepthBits( tmp );
673         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
674
675         // Initialize ssg (from plib).  Needs to come before we do any
676         // other ssg stuff, but after opengl has been initialized.
677         ssgInit();
678
679         // Initialize the user interface (we need to do this before
680         // passing off control to the OS main loop and before
681          // fgInitGeneral to get our fonts !!!
682         guiInit();
683         fgSplashProgress("reading aircraft list");
684
685
686     } else if ( idle_state == 2 ) {
687         idle_state++;
688         // Read the list of available aircrafts
689         fgReadAircraft();
690
691 #ifdef GL_EXT_texture_lod_bias
692         glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
693 #endif
694
695         // get the address of our OpenGL extensions
696         if ( fgGetBool("/sim/rendering/distance-attenuation") ) {
697             if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
698                 glPointParameterIsSupported = true;
699                 glPointParameterfPtr = (glPointParameterfProc)
700                                        SGLookupFunction("glPointParameterfEXT");
701                 glPointParameterfvPtr = (glPointParameterfvProc)
702                                         SGLookupFunction("glPointParameterfvEXT");
703
704             } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
705                 glPointParameterIsSupported = true;
706                 glPointParameterfPtr = (glPointParameterfProc)
707                                        SGLookupFunction("glPointParameterfARB");
708                 glPointParameterfvPtr = (glPointParameterfvProc)
709                                         SGLookupFunction("glPointParameterfvARB");
710             } else
711                 glPointParameterIsSupported = false;
712         }
713         fgSplashProgress("reading navigation data");
714
715
716     } else if ( idle_state == 3 ) {
717         idle_state++;
718         fgInitNav();
719         fgSplashProgress("setting up scenery");
720
721
722     } else if ( idle_state == 4 ) {
723         idle_state++;
724         // based on the requested presets, calculate the true starting
725         // lon, lat
726         fgInitPosition();
727
728         SGTime *t = fgInitTime();
729         globals->set_time_params( t );
730
731         // Do some quick general initializations
732         if( !fgInitGeneral()) {
733             SG_LOG( SG_GENERAL, SG_ALERT, 
734                 "General initializations failed ..." );
735             exit(-1);
736         }
737
738         ////////////////////////////////////////////////////////////////////
739         // Initialize the property-based built-in commands
740         ////////////////////////////////////////////////////////////////////
741         fgInitCommands();
742
743
744         ////////////////////////////////////////////////////////////////////
745         // Initialize the material manager
746         ////////////////////////////////////////////////////////////////////
747         globals->set_matlib( new SGMaterialLib );
748         globals->set_model_lib(new SGModelLib);
749
750
751         ////////////////////////////////////////////////////////////////////
752         // Initialize the TG scenery subsystem.
753         ////////////////////////////////////////////////////////////////////
754         globals->set_scenery( new FGScenery );
755         globals->get_scenery()->init();
756         globals->get_scenery()->bind();
757         globals->set_tile_mgr( new FGTileMgr );
758
759
760         ////////////////////////////////////////////////////////////////////
761         // Initialize the general model subsystem.
762         ////////////////////////////////////////////////////////////////////
763         globals->set_model_mgr(new FGModelMgr);
764         globals->get_model_mgr()->init();
765         globals->get_model_mgr()->bind();
766         fgSplashProgress("loading aircraft");
767
768
769     } else if ( idle_state == 5 ) {
770         idle_state++;
771         ////////////////////////////////////////////////////////////////////
772         // Initialize the 3D aircraft model subsystem (has a dependency on
773         // the scenery subsystem.)
774         ////////////////////////////////////////////////////////////////////
775         globals->set_aircraft_model(new FGAircraftModel);
776         globals->get_aircraft_model()->init();
777         globals->get_aircraft_model()->bind();
778
779         ////////////////////////////////////////////////////////////////////
780         // Initialize the view manager subsystem.
781         ////////////////////////////////////////////////////////////////////
782         FGViewMgr *viewmgr = new FGViewMgr;
783         globals->set_viewmgr( viewmgr );
784         viewmgr->init();
785         viewmgr->bind();
786         fgSplashProgress("generating sky elements");
787
788
789     } else if ( idle_state == 6 ) {
790         idle_state++;
791         // Initialize the sky
792         SGPath ephem_data_path( globals->get_fg_root() );
793         ephem_data_path.append( "Astro" );
794         SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
795         ephem->update( globals->get_time_params()->getMjd(),
796                        globals->get_time_params()->getLst(),
797                        0.0 );
798         globals->set_ephem( ephem );
799
800         // TODO: move to environment mgr
801         thesky = new SGSky;
802         SGPath texture_path(globals->get_fg_root());
803         texture_path.append("Textures");
804         texture_path.append("Sky");
805         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
806             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
807             thesky->add_cloud_layer(layer);
808         }
809
810         SGPath sky_tex_path( globals->get_fg_root() );
811         sky_tex_path.append( "Textures" );
812         sky_tex_path.append( "Sky" );
813         thesky->texture_path( sky_tex_path.str() );
814
815         // The sun and moon diameters are scaled down numbers of the
816         // actual diameters. This was needed to fit bot the sun and the
817         // moon within the distance to the far clip plane.
818         // Moon diameter:    3,476 kilometers
819         // Sun diameter: 1,390,000 kilometers
820         thesky->build( 80000.0, 80000.0,
821                        463.3, 361.8,
822                        globals->get_ephem()->getNumPlanets(), 
823                        globals->get_ephem()->getPlanets(),
824                        globals->get_ephem()->getNumStars(),
825                        globals->get_ephem()->getStars() );
826
827         // Initialize MagVar model
828         SGMagVar *magvar = new SGMagVar();
829         globals->set_mag( magvar );
830
831
832                                     // kludge to initialize mag compass
833                                     // (should only be done for in-flight
834                                     // startup)
835         // update magvar model
836         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
837                                     * SGD_DEGREES_TO_RADIANS,
838                                     fgGetDouble("/position/latitude-deg")
839                                     * SGD_DEGREES_TO_RADIANS,
840                                     fgGetDouble("/position/altitude-ft")
841                                     * SG_FEET_TO_METER,
842                                     globals->get_time_params()->getJD() );
843         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
844         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
845
846         // airport = new ssgBranch;
847         // airport->setName( "Airport Lighting" );
848         // lighting->addKid( airport );
849
850         // build our custom render states
851         globals->get_renderer()->build_states();
852         fgSplashProgress("initializing subsystems");
853
854
855     } else if ( idle_state == 7 ) {
856         idle_state++;
857         // Initialize audio support
858 #ifdef ENABLE_AUDIO_SUPPORT
859
860         // Start the intro music
861         if ( fgGetBool("/sim/startup/intro-music") ) {
862             SGPath mp3file( globals->get_fg_root() );
863             mp3file.append( "Sounds/intro.mp3" );
864
865             SG_LOG( SG_GENERAL, SG_INFO, 
866                 "Starting intro music: " << mp3file.str() );
867
868 #if defined( __CYGWIN__ )
869             string command = "start /m `cygpath -w " + mp3file.str() + "`";
870 #elif defined( WIN32 )
871             string command = "start /m " + mp3file.str();
872 #else
873             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
874 #endif
875
876             system ( command.c_str() );
877         }
878 #endif
879
880         // These are a few miscellaneous things that aren't really
881         // "subsystems" but still need to be initialized.
882
883 #ifdef USE_GLIDE
884         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
885             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
886         }
887 #endif
888
889         // This is the top level init routine which calls all the
890         // other subsystem initialization routines.  If you are adding
891         // a subsystem to flightgear, its initialization call should
892         // located in this routine.
893         if( !fgInitSubsystems()) {
894             SG_LOG( SG_GENERAL, SG_ALERT,
895                 "Subsystem initializations failed ..." );
896             exit(-1);
897         }
898         fgSplashProgress("setup time & renderer");
899
900
901     } else if ( idle_state == 8 ) {
902         idle_state = 1000;
903         // Initialize the time offset (warp) after fgInitSubsystem
904         // (which initializes the lighting interpolation tables.)
905         fgInitTimeOffset();
906
907         // setup OpenGL view parameters
908         globals->get_renderer()->init();
909
910         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
911         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
912                                          fgGetInt("/sim/startup/ysize") );
913
914         fgSplashProgress("loading scenery objects");
915
916     }
917
918     if ( idle_state == 1000 ) {
919         // We've finished all our initialization steps, from now on we
920         // run the main loop.
921         fgSetBool("sim/sceneryloaded", false);
922         fgRegisterIdleHandler( fgMainLoop );
923     }
924 }
925
926
927 // Main top level initialization
928 bool fgMainInit( int argc, char **argv ) {
929
930 #if defined( macintosh )
931     freopen ("stdout.txt", "w", stdout );
932     freopen ("stderr.txt", "w", stderr );
933     argc = ccommand( &argv );
934 #endif
935
936     // set default log levels
937     sglog().setLogLevels( SG_ALL, SG_ALERT );
938
939     string version;
940 #ifdef FLIGHTGEAR_VERSION
941     version = FLIGHTGEAR_VERSION;
942 #else
943     version = "unknown version";
944 #endif
945     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
946             << version );
947     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
948
949     // Allocate global data structures.  This needs to happen before
950     // we parse command line options
951
952     globals = new FGGlobals;
953
954     // seed the random number generater
955     sg_srandom_time();
956
957     FGControls *controls = new FGControls;
958     globals->set_controls( controls );
959
960     string_list *col = new string_list;
961     globals->set_channel_options_list( col );
962
963     // Scan the config file(s) and command line options to see if
964     // fg_root was specified (ignore all other options for now)
965     fgInitFGRoot(argc, argv);
966
967     // Check for the correct base package version
968     static char required_version[] = "0.9.8";
969     string base_version = fgBasePackageVersion();
970     if ( !(base_version == required_version) ) {
971         // tell the operator how to use this application
972
973         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
974         cerr << endl << "Base package check failed ... " \
975              << "Found version " << base_version << " at: " \
976              << globals->get_fg_root() << endl;
977         cerr << "Please upgrade to version: " << required_version << endl;
978 #ifdef _MSC_VER
979         cerr << "Hit a key to continue..." << endl;
980         cin.get();
981 #endif
982         exit(-1);
983     }
984
985     sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
986
987     // Initialize the Aircraft directory to "" (UIUC)
988     aircraft_dir = "";
989
990     // Load the configuration parameters.  (Command line options
991     // overrides config file options.  Config file options override
992     // defaults.)
993     if ( !fgInitConfig(argc, argv) ) {
994         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
995         exit(-1);
996     }
997
998     // Initialize the Window/Graphics environment.
999 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1000     // Mac OS X command line ("non-bundle") applications call this
1001     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
1002     // feel free to add comments...
1003     fgOSInit(&argc, argv);
1004     _bootstrap_OSInit++;
1005 #endif
1006
1007     fgRegisterWindowResizeHandler( &FGRenderer::resize );
1008     fgRegisterIdleHandler( &fgIdleFunction );
1009     fgRegisterDrawHandler( &FGRenderer::update );
1010
1011 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1012     bool get_stencil_buffer = true;
1013 #else
1014     bool get_stencil_buffer = false;
1015 #endif
1016
1017     // Initialize plib net interface
1018     netInit( &argc, argv );
1019
1020     // Clouds3D requires an alpha channel
1021     // clouds may require stencil buffer
1022     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1023                     fgGetInt("/sim/startup/ysize"),
1024                     fgGetInt("/sim/rendering/bits-per-pixel"),
1025                     fgGetBool("/sim/rendering/clouds3d"),
1026                     get_stencil_buffer,
1027                     fgGetBool("/sim/startup/fullscreen") );
1028
1029     // Initialize the splash screen right away
1030     fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1031
1032     // pass control off to the master event handler
1033     fgOSMainLoop();
1034
1035     // we never actually get here ... but to avoid compiler warnings,
1036     // etc.
1037     return false;
1038 }
1039
1040