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