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