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