]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Don't scale elevator by 0.5.
[flightgear.git] / src / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
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 <plib/ssg.h>
29
30 #include <simgear/constants.h>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/math/point3d.hxx>
33 #include <simgear/math/polar3d.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/vector.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/viewer.hxx>
42
43 #include "newcache.hxx"
44 #include "scenery.hxx"
45 #include "tilemgr.hxx"
46
47 #define TEST_LAST_HIT_CACHE
48
49 #ifdef ENABLE_THREADS
50 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
51 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
52 #else
53 queue<FGTileEntry *> FGTileMgr::attach_queue;
54 queue<FGDeferredModel *> FGTileMgr::model_queue;
55 #endif // ENABLE_THREADS
56 queue<FGTileEntry *> FGTileMgr::delete_queue;
57
58
59 // Constructor
60 FGTileMgr::FGTileMgr():
61     state( Start ),
62     current_tile( NULL ),
63     vis( 16000 ),
64     counter_hack(0)
65 {
66 }
67
68
69 // Destructor
70 FGTileMgr::~FGTileMgr() {
71 }
72
73
74 // Initialize the Tile Manager subsystem
75 int FGTileMgr::init() {
76     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
77
78     tile_cache.init();
79
80 #if 0
81
82     // instead it's just a lot easier to let any pending work flush
83     // through, rather than trying to arrest the queue and nuke all
84     // the various work at all the various stages and get everything
85     // cleaned up properly.
86
87     while ( ! attach_queue.empty() ) {
88         attach_queue.pop();
89     }
90
91     while ( ! model_queue.empty() ) {
92 #ifdef ENABLE_THREADS
93         FGDeferredModel* dm = model_queue.pop();
94 #else
95         FGDeferredModel* dm = model_queue.front();
96         model_queue.pop();
97 #endif
98         delete dm;
99     }
100     loader.reinit();
101 #endif
102
103     hit_list.clear();
104
105     state = Inited;
106
107     previous_bucket.make_bad();
108     current_bucket.make_bad();
109
110     longitude = latitude = -1000.0;
111     last_longitude = last_latitude = -1000.0;
112
113     return 1;
114 }
115
116
117 // schedule a tile for loading
118 void FGTileMgr::sched_tile( const SGBucket& b ) {
119     // see if tile already exists in the cache
120     FGTileEntry *t = tile_cache.get_tile( b );
121
122     if ( t == NULL ) {
123         // make space in the cache
124         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
125             long index = tile_cache.get_oldest_tile();
126             if ( index >= 0 ) {
127                 FGTileEntry *old = tile_cache.get_tile( index );
128                 old->disconnect_ssg_nodes();
129                 delete_queue.push( old );
130                 tile_cache.clear_entry( index );
131             } else {
132                 // nothing to free ?!? forge ahead
133                 break;
134             }
135         }
136
137         // create a new entry
138         FGTileEntry *e = new FGTileEntry( b );
139
140         // insert the tile into the cache
141         if ( tile_cache.insert_tile( e ) ) {
142             // Schedule tile for loading
143             loader.add( e );
144         } else {
145             // insert failed (cache full with no available entries to
146             // delete.)  Try again later
147             delete e;
148         }
149     }
150 }
151
152
153 // schedule a needed buckets for loading
154 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
155     // sanity check (unfortunately needed!)
156     if ( longitude < -180.0 || longitude > 180.0 
157          || latitude < -90.0 || latitude > 90.0 )
158     {
159         SG_LOG( SG_TERRAIN, SG_ALERT,
160                 "Attempting to schedule tiles for bogus lon and lat  = ("
161                 << longitude << "," << latitude << ")" );
162         SG_LOG( SG_TERRAIN, SG_ALERT,
163                 "This is a FATAL error.  Exiting!" );
164         exit(-1);        
165     }
166
167     SG_LOG( SG_TERRAIN, SG_INFO,
168             "scheduling needed tiles for " << longitude << " " << latitude );
169
170     // vis = fgGetDouble("/environment/visibility-m");
171
172     double tile_width = curr_bucket.get_width_m();
173     double tile_height = curr_bucket.get_height_m();
174     // cout << "tile width = " << tile_width << "  tile_height = "
175     //      << tile_height !<< endl;
176
177     xrange = (int)(vis / tile_width) + 1;
178     yrange = (int)(vis / tile_height) + 1;
179     if ( xrange < 1 ) { xrange /= 1; }
180     if ( yrange < 1 ) { yrange = 1; }
181
182     // note * 2 at end doubles cache size (for fdm and viewer)
183     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
184
185     /*
186     cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
187     cout << "max cache size = " << tile_cache.get_max_cache_size()
188          << " current cache size = " << tile_cache.get_size() << endl;
189     */
190
191     SGBucket b;
192
193     // schedule center tile first so it can be loaded first
194     b = sgBucketOffset( longitude, latitude, 0, 0 );
195     sched_tile( b );
196
197     int x, y;
198
199     // schedule next ring of 8 tiles
200     for ( x = -1; x <= 1; ++x ) {
201         for ( y = -1; y <= 1; ++y ) {
202             if ( x != 0 || y != 0 ) {
203                 b = sgBucketOffset( longitude, latitude, x, y );
204                 sched_tile( b );
205             }
206         }
207     }
208
209     // schedule remaining tiles
210     for ( x = -xrange; x <= xrange; ++x ) {
211         for ( y = -yrange; y <= yrange; ++y ) {
212             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
213                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
214                 sched_tile( b );
215             }
216         }
217     }
218 }
219
220
221 void FGTileMgr::initialize_queue()
222 {
223     // First time through or we have teleported, initialize the
224     // system and load all relavant tiles
225
226     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
227     // cout << "tile cache size = " << tile_cache.get_size() << endl;
228
229     // wipe/initialize tile cache
230     // tile_cache.init();
231     previous_bucket.make_bad();
232
233     // build the local area list and schedule tiles for loading
234
235     // start with the center tile and work out in concentric
236     // "rings"
237
238     double visibility_meters = fgGetDouble("/environment/visibility-m");
239     schedule_needed(visibility_meters, current_bucket);
240
241     // do we really want to lose this? CLO
242 #if 0
243     // Now force a load of the center tile and inner ring so we
244     // have something to see in our first frame.
245     int i;
246     for ( i = 0; i < 9; ++i ) {
247         if ( load_queue.size() ) {
248             SG_LOG( SG_TERRAIN, SG_DEBUG, 
249                     "Load queue not empty, loading a tile" );
250
251             SGBucket pending = load_queue.front();
252             load_queue.pop_front();
253             load_tile( pending );
254         }
255     }
256 #endif
257 }
258
259
260 /**
261  * Update the various queues maintained by the tilemagr (private
262  * internal function, do not call directly.)
263  */
264 void FGTileMgr::update_queues()
265 {
266     // load the next model in the load queue.  Currently this must
267     // happen in the render thread because model loading can trigger
268     // texture loading which involves use of the opengl api.
269     if ( !model_queue.empty() ) {
270         // cout << "loading next model ..." << endl;
271         // load the next tile in the queue
272 #ifdef ENABLE_THREADS
273         FGDeferredModel* dm = model_queue.pop();
274 #else
275         FGDeferredModel* dm = model_queue.front();
276         model_queue.pop();
277 #endif
278
279         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
280         try
281         {
282             ssgEntity *obj_model =
283                 globals->get_model_lib()->load_model( ".",
284                                                       dm->get_model_path(),
285                                                       globals->get_props(),
286                                                       globals->get_sim_time_sec() );
287             if ( obj_model != NULL ) {
288                 dm->get_obj_trans()->addKid( obj_model );
289             }
290         }
291         catch (const sg_exception& exc)
292         {
293             SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
294         }
295
296         dm->get_tile()->dec_pending_models();
297         delete dm;
298     }
299     
300     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
301
302     // activate loader thread one out of every 5 frames
303     if ( counter_hack == 0 ) {
304         // Notify the tile loader that it can load another tile
305         loader.update();
306     } else {
307         counter_hack = (counter_hack + 1) % 5;
308     }
309
310     if ( !attach_queue.empty() ) {
311 #ifdef ENABLE_THREADS
312         FGTileEntry* e = attach_queue.pop();
313 #else
314         FGTileEntry* e = attach_queue.front();
315         attach_queue.pop();
316 #endif
317         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
318                           globals->get_scenery()->get_gnd_lights_root(),
319                           globals->get_scenery()->get_taxi_lights_root(),
320                           globals->get_scenery()->get_rwy_lights_root(),
321                           globals->get_scenery()->get_taxi_lights_root() );
322         // cout << "Adding ssg nodes for "
323     }
324
325     if ( !delete_queue.empty() ) {
326         // cout << "delete queue = " << delete_queue.size() << endl;
327
328         while ( delete_queue.size() > 30 ) {
329             // uh oh, delete queue is blowing up, we aren't clearing
330             // it fast enough.  Let's just panic, well not panic, but
331             // get real serious and agressively free up some tiles so
332             // we don't explode our memory usage.
333
334             SG_LOG( SG_TERRAIN, SG_ALERT,
335                     "Alert: catching up on tile delete queue" );
336
337             FGTileEntry* e = delete_queue.front();
338             while ( !e->free_tile() );
339             delete_queue.pop();
340             delete e;
341         }
342
343         FGTileEntry* e = delete_queue.front();
344         if ( e->free_tile() ) {
345             delete_queue.pop();
346             delete e;
347         }
348     }
349 }
350
351
352 // given the current lon/lat (in degrees), fill in the array of local
353 // chunks.  If the chunk isn't already in the cache, then read it from
354 // disk.
355 int FGTileMgr::update( double visibility_meters )
356 {
357     SGLocation *location = globals->get_current_view()->getSGLocation();
358     sgdVec3 abs_pos_vector;
359     sgdCopyVec3( abs_pos_vector,
360                  globals->get_current_view()->get_absolute_view_pos() );
361     return update( location, visibility_meters, abs_pos_vector );
362 }
363
364
365 int FGTileMgr::update( SGLocation *location, double visibility_meters,
366                        sgdVec3 abs_pos_vector )
367 {
368     longitude = location->getLongitude_deg();
369     latitude = location->getLatitude_deg();
370     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
371     //         << longitude << " " << latatitude );
372
373     current_bucket.set_bucket( longitude, latitude );
374     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
375     //         << current_bucket );
376     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
377
378     // set global scenery center from current tile center
379     current_tile = tile_cache.get_tile( current_bucket );
380     if ( current_tile != NULL ) {
381         globals->get_scenery()->set_next_center( current_tile->center );
382     } else {
383         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
384         globals->get_scenery()->set_next_center( Point3D(0.0) );
385     }
386
387     // do tile load scheduling. 
388     // Note that we need keep track of both viewer buckets and fdm buckets.
389     if ( state == Running ) {
390         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
391         if (!(current_bucket == previous_bucket )) {
392             // We've moved to a new bucket, we need to schedule any
393             // needed tiles for loading.
394             schedule_needed(visibility_meters, current_bucket);
395         }
396     } else if ( state == Start || state == Inited ) {
397         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
398         initialize_queue();
399         state = Running;
400
401         // load the next tile in the load queue (or authorize the next
402         // load in the case of the threaded tile pager)
403         loader.update();
404     }
405
406     update_queues();
407
408     // save bucket...
409     previous_bucket = current_bucket;
410
411     // no reason to update this if we haven't moved...
412     if ( longitude != last_longitude || latitude != last_latitude ) {
413         // update current elevation... 
414         if ( updateCurrentElevAtPos( abs_pos_vector,
415                                      location->get_tile_center() ) )
416         {
417             last_longitude = longitude;
418             last_latitude = latitude;
419         }
420     }
421
422     return 1;
423 }
424
425
426 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
427 void FGTileMgr::refresh_view_timestamps() {
428     SG_LOG( SG_TERRAIN, SG_INFO,
429             "Refreshing timestamps for " << current_bucket.get_center_lon()
430             << " " << current_bucket.get_center_lat() );
431     schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
432 }
433
434
435 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
436
437     sgdVec3 sc;
438
439     sgdSetVec3( sc, center[0], center[1], center[2]);
440
441     // overridden with actual values if a terrain intersection is
442     // found
443     double hit_elev = -9999.0;
444     double hit_radius = 0.0;
445     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
446     
447     bool hit = false;
448     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
449         // scenery center has been properly defined so any hit should
450         // be valid (and not just luck)
451         hit = fgCurrentElev(abs_pos_vector,
452                             sc,
453                 // uncomment next paramater to fly under
454                 // bridges and a slightly faster algorithm
455                 // but you won't be able to land on aircraft carriers
456                             // current_tile->get_terra_transform(),
457                             &hit_list,
458                             &hit_elev,
459                             &hit_radius,
460                             hit_normal);
461     }
462
463     if ( hit ) {
464         // cout << "elev = " << hit_elev << " " << hit_radius << endl;
465         globals->get_scenery()->set_cur_elev( hit_elev );
466         globals->get_scenery()->set_cur_radius( hit_radius );
467         globals->get_scenery()->set_cur_normal( hit_normal );
468     } else {
469         globals->get_scenery()->set_cur_elev( -9999.0 );
470         globals->get_scenery()->set_cur_radius( 0.0 );
471         globals->get_scenery()->set_cur_normal( hit_normal );
472     }
473     return hit;
474 }
475
476
477 void FGTileMgr::prep_ssg_nodes( SGLocation *location, float vis ) {
478
479     // traverse the potentially viewable tile list and update range
480     // selector and transform
481
482     Point3D center = location->get_tile_center();
483     float *up = location->get_world_up();
484
485     FGTileEntry *e;
486     tile_cache.reset_traversal();
487
488     while ( ! tile_cache.at_end() ) {
489         // cout << "processing a tile" << endl;
490         if ( (e = tile_cache.get_current()) ) {
491             e->prep_ssg_node( center, up, vis);
492         } else {
493             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
494         }
495         tile_cache.next();
496     }
497 }
498