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