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