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