]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Fix a bug in tile manager updating when switching from one view to the next.
[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/misc/exception.hxx>
37
38 #include <Main/globals.hxx>
39 #include <Main/fg_props.hxx>
40 #include <Main/viewer.hxx>
41 #include <Model/loader.hxx>
42 #include <Objects/obj.hxx>
43
44 #include "newcache.hxx"
45 #include "scenery.hxx"
46 #include "tilemgr.hxx"
47
48 #define TEST_LAST_HIT_CACHE
49
50 #ifdef 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
60 // Constructor
61 FGTileMgr::FGTileMgr():
62     state( Start ),
63     current_tile( NULL ),
64     vis( 16000 ),
65     counter_hack(0)
66 {
67 }
68
69
70 // Destructor
71 FGTileMgr::~FGTileMgr() {
72 }
73
74
75 // Initialize the Tile Manager subsystem
76 int FGTileMgr::init() {
77     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
78
79     tile_cache.init();
80
81 #if 0
82
83     // instead it's just a lot easier to let any pending work flush
84     // through, rather than trying to arrest the queue and nuke all
85     // the various work at all the various stages and get everything
86     // cleaned up properly.
87
88     while ( ! attach_queue.empty() ) {
89         attach_queue.pop();
90     }
91
92     while ( ! model_queue.empty() ) {
93 #ifdef ENABLE_THREADS
94         FGDeferredModel* dm = model_queue.pop();
95 #else
96         FGDeferredModel* dm = model_queue.front();
97         model_queue.pop();
98 #endif
99         delete dm;
100     }
101     loader.reinit();
102 #endif
103
104     hit_list.clear();
105
106     state = Inited;
107
108     previous_bucket.make_bad();
109     current_bucket.make_bad();
110
111     longitude = latitude = -1000.0;
112     last_longitude = last_latitude = -1000.0;
113
114     return 1;
115 }
116
117
118 // schedule a tile for loading
119 void FGTileMgr::sched_tile( const SGBucket& b ) {
120     // see if tile already exists in the cache
121     FGTileEntry *t = tile_cache.get_tile( b );
122
123     if ( t == NULL ) {
124         // make space in the cache
125         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
126             long index = tile_cache.get_oldest_tile();
127             if ( index >= 0 ) {
128                 FGTileEntry *old = tile_cache.get_tile( index );
129                 old->disconnect_ssg_nodes();
130                 delete_queue.push( old );
131                 tile_cache.clear_entry( index );
132             } else {
133                 // nothing to free ?!? forge ahead
134                 break;
135             }
136         }
137
138         // create a new entry
139         FGTileEntry *e = new FGTileEntry( b );
140
141         // insert the tile into the cache
142         if ( tile_cache.insert_tile( e ) ) {
143             // Schedule tile for loading
144             loader.add( e );
145         } else {
146             // insert failed (cache full with no available entries to
147             // delete.)  Try again later
148             delete e;
149         }
150     }
151 }
152
153
154 // schedule a needed buckets for loading
155 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
156     // sanity check (unfortunately needed!)
157     if ( longitude < -180.0 || longitude > 180.0 
158          || latitude < -90.0 || latitude > 90.0 )
159     {
160         SG_LOG( SG_TERRAIN, SG_ALERT,
161                 "Attempting to schedule tiles for bogus latitude and" );
162         SG_LOG( SG_TERRAIN, SG_ALERT,
163                 "longitude.  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_loader()->load_model(dm->get_model_path());
284             if ( obj_model != NULL ) {
285                 dm->get_obj_trans()->addKid( obj_model );
286             }
287         }
288         catch (const sg_exception& exc)
289         {
290             SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
291         }
292
293         dm->get_tile()->dec_pending_models();
294         delete dm;
295     }
296     
297     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
298
299     // activate loader thread one out of every 5 frames
300     if ( counter_hack == 0 ) {
301         // Notify the tile loader that it can load another tile
302         loader.update();
303     } else {
304         counter_hack = (counter_hack + 1) % 5;
305     }
306
307     if ( !attach_queue.empty() ) {
308 #ifdef ENABLE_THREADS
309         FGTileEntry* e = attach_queue.pop();
310 #else
311         FGTileEntry* e = attach_queue.front();
312         attach_queue.pop();
313 #endif
314         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
315                           globals->get_scenery()->get_gnd_lights_root(),
316                           globals->get_scenery()->get_rwy_lights_root(),
317                           globals->get_scenery()->get_taxi_lights_root() );
318         // cout << "Adding ssg nodes for "
319     }
320
321     if ( !delete_queue.empty() ) {
322         // cout << "delete queue = " << delete_queue.size() << endl;
323
324         while ( delete_queue.size() > 30 ) {
325             // uh oh, delete queue is blowing up, we aren't clearing
326             // it fast enough.  Let's just panic, well not panic, but
327             // get real serious and agressively free up some tiles so
328             // we don't explode our memory usage.
329
330             SG_LOG( SG_TERRAIN, SG_ALERT,
331                     "Alert: catching up on tile delete queue" );
332
333             FGTileEntry* e = delete_queue.front();
334             while ( !e->free_tile() );
335             delete_queue.pop();
336             delete e;
337         }
338
339         FGTileEntry* e = delete_queue.front();
340         if ( e->free_tile() ) {
341             delete_queue.pop();
342             delete e;
343         }
344     }
345 }
346
347
348 // given the current lon/lat (in degrees), fill in the array of local
349 // chunks.  If the chunk isn't already in the cache, then read it from
350 // disk.
351 int FGTileMgr::update( double visibility_meters )
352 {
353     FGLocation *location = globals->get_current_view()->getFGLocation();
354     sgdVec3 abs_pos_vector;
355     sgdCopyVec3( abs_pos_vector,
356                  globals->get_current_view()->get_absolute_view_pos() );
357     return update( location, visibility_meters, abs_pos_vector );
358 }
359
360
361 int FGTileMgr::update( FGLocation *location, double visibility_meters,
362                        sgdVec3 abs_pos_vector )
363 {
364     longitude = location->getLongitude_deg();
365     latitude = location->getLatitude_deg();
366     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
367     //         << longitude << " " << latatitude );
368
369     current_bucket.set_bucket( longitude, latitude );
370     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
371     //         << current_bucket );
372
373     // set global scenery center from current tile center
374     current_tile = tile_cache.get_tile( current_bucket );
375     if ( current_tile != NULL ) {
376         globals->get_scenery()->set_next_center( current_tile->center );
377     } else {
378         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
379         globals->get_scenery()->set_next_center( Point3D(0.0) );
380     }
381
382     // do tile load scheduling. 
383     // Note that we need keep track of both viewer buckets and fdm buckets.
384     if ( state == Running ) {
385         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
386         if (!(current_bucket == previous_bucket )) {
387             // We've moved to a new bucket, we need to schedule any
388             // needed tiles for loading.
389             schedule_needed(visibility_meters, current_bucket);
390         }
391     } else if ( state == Start || state == Inited ) {
392         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
393         initialize_queue();
394         state = Running;
395
396         // load the next tile in the load queue (or authorize the next
397         // load in the case of the threaded tile pager)
398         loader.update();
399     }
400
401     update_queues();
402
403     // save bucket...
404     previous_bucket = current_bucket;
405
406     // no reason to update this if we haven't moved...
407     if ( longitude != last_longitude || latitude != last_latitude ) {
408         // update current elevation... 
409         if ( updateCurrentElevAtPos( abs_pos_vector,
410                                      globals->get_scenery()->get_next_center() ) )
411         {
412             last_longitude = longitude;
413             last_latitude = latitude;
414         }
415     }
416
417     return 1;
418 }
419
420
421 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
422 void FGTileMgr::refresh_view_timestamps() {
423     SG_LOG( SG_TERRAIN, SG_INFO,
424             "Refreshing timestamps for " << current_bucket.get_center_lon()
425             << " " << current_bucket.get_center_lat() );
426     schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
427 }
428
429
430 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
431
432     sgdVec3 sc;
433
434     sgdSetVec3( sc, center[0], center[1], center[2]);
435
436     // overridden with actual values if a terrain intersection is
437     // found
438     double hit_elev = -9999.0;
439     double hit_radius = 0.0;
440     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
441     
442     bool hit = false;
443     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
444         // scenery center has been properly defined so any hit should
445         // be valid (and not just luck)
446         hit = fgCurrentElev(abs_pos_vector,
447                             sc,
448                             // current_tile->get_terra_transform(),
449                             &hit_list,
450                             &hit_elev,
451                             &hit_radius,
452                             hit_normal);
453     }
454
455     if ( hit ) {
456         // cout << "elev = " << hit_elev << " " << hit_radius << endl;
457         globals->get_scenery()->set_cur_elev( hit_elev );
458         globals->get_scenery()->set_cur_radius( hit_radius );
459         globals->get_scenery()->set_cur_normal( hit_normal );
460     } else {
461         globals->get_scenery()->set_cur_elev( -9999.0 );
462         globals->get_scenery()->set_cur_radius( 0.0 );
463         globals->get_scenery()->set_cur_normal( hit_normal );
464     }
465     return hit;
466 }
467
468
469 void FGTileMgr::prep_ssg_nodes( FGLocation *location, float vis ) {
470
471     // traverse the potentially viewable tile list and update range
472     // selector and transform
473
474     Point3D center = location->get_tile_center();
475     float *up = location->get_world_up();
476
477     FGTileEntry *e;
478     tile_cache.reset_traversal();
479
480     while ( ! tile_cache.at_end() ) {
481         // cout << "processing a tile" << endl;
482         if ( (e = tile_cache.get_current()) ) {
483             e->prep_ssg_node( center, up, vis);
484         } else {
485             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
486         }
487         tile_cache.next();
488     }
489 }
490