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