]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Plib is willing callbacks to return 0, 1 or 2 and not simply a boolean
[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 bool FGTileMgr::tile_filter = true;
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
113     return 1;
114 }
115
116
117 // schedule a tile for loading
118 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
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     } else {
150         t->set_inner_ring( is_inner_ring );
151     }
152 }
153
154
155 // schedule a needed buckets for loading
156 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
157     // sanity check (unfortunately needed!)
158     if ( longitude < -180.0 || longitude > 180.0 
159          || latitude < -90.0 || latitude > 90.0 )
160     {
161         SG_LOG( SG_TERRAIN, SG_ALERT,
162                 "Attempting to schedule tiles for bogus lon and lat  = ("
163                 << longitude << "," << latitude << ")" );
164         SG_LOG( SG_TERRAIN, SG_ALERT,
165                 "This is a FATAL error.  Exiting!" );
166         exit(-1);        
167     }
168
169     SG_LOG( SG_TERRAIN, SG_INFO,
170             "scheduling needed tiles for " << longitude << " " << latitude );
171
172     // vis = fgGetDouble("/environment/visibility-m");
173
174     double tile_width = curr_bucket.get_width_m();
175     double tile_height = curr_bucket.get_height_m();
176     // cout << "tile width = " << tile_width << "  tile_height = "
177     //      << tile_height << endl;
178
179     xrange = (int)(vis / tile_width) + 1;
180     yrange = (int)(vis / tile_height) + 1;
181     if ( xrange < 1 ) { xrange = 1; }
182     if ( yrange < 1 ) { yrange = 1; }
183
184     // note * 2 at end doubles cache size (for fdm and viewer)
185     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
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     // clear the inner ring flags so we can set them below.  This
191     // prevents us from having "true" entries we aren't able to find
192     // to get rid of if we teleport a long ways away from the current
193     // location.
194     tile_cache.clear_inner_ring_flags();
195
196     SGBucket b;
197
198     // schedule center tile first so it can be loaded first
199     b = sgBucketOffset( longitude, latitude, 0, 0 );
200     sched_tile( b, true );
201
202     int x, y;
203
204     // schedule next ring of 8 tiles
205     for ( x = -1; x <= 1; ++x ) {
206         for ( y = -1; y <= 1; ++y ) {
207             if ( x != 0 || y != 0 ) {
208                 b = sgBucketOffset( longitude, latitude, x, y );
209                 sched_tile( b, true );
210             }
211         }
212     }
213
214     // schedule remaining tiles
215     for ( x = -xrange; x <= xrange; ++x ) {
216         for ( y = -yrange; y <= yrange; ++y ) {
217             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
218                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
219                 sched_tile( b, false );
220             }
221         }
222     }
223 }
224
225
226 void FGTileMgr::initialize_queue()
227 {
228     // First time through or we have teleported, initialize the
229     // system and load all relavant tiles
230
231     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
232             << current_bucket );
233     // cout << "tile cache size = " << tile_cache.get_size() << endl;
234
235     // wipe/initialize tile cache
236     // tile_cache.init();
237     previous_bucket.make_bad();
238
239     // build the local area list and schedule tiles for loading
240
241     // start with the center tile and work out in concentric
242     // "rings"
243
244     double visibility_meters = fgGetDouble("/environment/visibility-m");
245     schedule_needed(visibility_meters, current_bucket);
246
247     // do we really want to lose this? CLO
248 #if 0
249     // Now force a load of the center tile and inner ring so we
250     // have something to see in our first frame.
251     int i;
252     for ( i = 0; i < 9; ++i ) {
253         if ( load_queue.size() ) {
254             SG_LOG( SG_TERRAIN, SG_DEBUG, 
255                     "Load queue not empty, loading a tile" );
256
257             SGBucket pending = load_queue.front();
258             load_queue.pop_front();
259             load_tile( pending );
260         }
261     }
262 #endif
263 }
264
265
266 /**
267  * Update the various queues maintained by the tilemagr (private
268  * internal function, do not call directly.)
269  */
270 void FGTileMgr::update_queues()
271 {
272     // load the next model in the load queue.  Currently this must
273     // happen in the render thread because model loading can trigger
274     // texture loading which involves use of the opengl api.
275     if ( !model_queue.empty() ) {
276         // cout << "loading next model ..." << endl;
277         // load the next tile in the queue
278 #ifdef ENABLE_THREADS
279         FGDeferredModel* dm = model_queue.pop();
280 #else
281         FGDeferredModel* dm = model_queue.front();
282         model_queue.pop();
283 #endif
284
285         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
286         try
287         {
288             ssgEntity *obj_model =
289                 globals->get_model_lib()->load_model( ".",
290                                                       dm->get_model_path(),
291                                                       globals->get_props(),
292                                                       globals->get_sim_time_sec() );
293             if ( obj_model != NULL ) {
294                 dm->get_obj_trans()->addKid( obj_model );
295             }
296         }
297         catch (const sg_exception& exc)
298         {
299             SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
300         }
301
302         dm->get_tile()->dec_pending_models();
303         delete dm;
304     }
305     
306     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
307
308     // activate loader thread one out of every 5 frames
309     if ( counter_hack == 0 ) {
310         // Notify the tile loader that it can load another tile
311         loader.update();
312     } else {
313         counter_hack = (counter_hack + 1) % 5;
314     }
315
316     if ( !attach_queue.empty() ) {
317 #ifdef ENABLE_THREADS
318         FGTileEntry* e = attach_queue.pop();
319 #else
320         FGTileEntry* e = attach_queue.front();
321         attach_queue.pop();
322 #endif
323         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
324                           globals->get_scenery()->get_gnd_lights_root(),
325                           globals->get_scenery()->get_vasi_lights_root(),
326                           globals->get_scenery()->get_rwy_lights_root(),
327                           globals->get_scenery()->get_taxi_lights_root() );
328         // cout << "Adding ssg nodes for "
329     }
330
331     if ( !delete_queue.empty() ) {
332         // cout << "delete queue = " << delete_queue.size() << endl;
333
334         while ( delete_queue.size() > 30 ) {
335             // uh oh, delete queue is blowing up, we aren't clearing
336             // it fast enough.  Let's just panic, well not panic, but
337             // get real serious and agressively free up some tiles so
338             // we don't explode our memory usage.
339
340             SG_LOG( SG_TERRAIN, SG_ALERT,
341                     "Alert: catching up on tile delete queue" );
342
343             FGTileEntry* e = delete_queue.front();
344             while ( !e->free_tile() );
345             delete_queue.pop();
346             delete e;
347         }
348
349         FGTileEntry* e = delete_queue.front();
350         if ( e->free_tile() ) {
351             delete_queue.pop();
352             delete e;
353         }
354     }
355 }
356
357
358 // given the current lon/lat (in degrees), fill in the array of local
359 // chunks.  If the chunk isn't already in the cache, then read it from
360 // disk.
361 int FGTileMgr::update( double visibility_meters )
362 {
363     SGLocation *location = globals->get_current_view()->getSGLocation();
364     sgdVec3 abs_pos_vector;
365     sgdCopyVec3( abs_pos_vector,
366                  globals->get_current_view()->get_absolute_view_pos() );
367     return update( location, visibility_meters, abs_pos_vector );
368 }
369
370
371 int FGTileMgr::update( SGLocation *location, double visibility_meters,
372                        sgdVec3 abs_pos_vector )
373 {
374     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
375
376     longitude = location->getLongitude_deg();
377     latitude = location->getLatitude_deg();
378     // add 1.0m to the max altitude to give a little leeway to the
379     // ground reaction code.
380     altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
381
382     // if current altitude is apparently not initialized, set max
383     // altitude to something big.
384     if ( altitude_m < -1000 ) {
385         altitude_m = 10000;
386     }
387     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
388     //         << longitude << " " << latatitude );
389
390     current_bucket.set_bucket( longitude, latitude );
391     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
392     //         << current_bucket );
393     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
394
395     // set global scenery center from current tile center
396     current_tile = tile_cache.get_tile( current_bucket );
397     if ( current_tile != NULL ) {
398         globals->get_scenery()->set_next_center( current_tile->center );
399     } else {
400         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
401         globals->get_scenery()->set_next_center( Point3D(0.0) );
402     }
403
404     // do tile load scheduling. 
405     // Note that we need keep track of both viewer buckets and fdm buckets.
406     if ( state == Running ) {
407         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
408         if (!(current_bucket == previous_bucket )) {
409             // We've moved to a new bucket, we need to schedule any
410             // needed tiles for loading.
411             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
412             schedule_needed(visibility_meters, current_bucket);
413         }
414     } else if ( state == Start || state == Inited ) {
415         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
416 //        initialize_queue();
417         state = Running;
418
419         // load the next tile in the load queue (or authorize the next
420         // load in the case of the threaded tile pager)
421         loader.update();
422     }
423
424     update_queues();
425
426     // save bucket...
427     previous_bucket = current_bucket;
428
429     updateCurrentElevAtPos( abs_pos_vector, altitude_m,
430                             location->get_tile_center() );
431
432     return 1;
433 }
434
435
436 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
437 void FGTileMgr::refresh_view_timestamps() {
438     SG_LOG( SG_TERRAIN, SG_INFO,
439             "Refreshing timestamps for " << current_bucket.get_center_lon()
440             << " " << current_bucket.get_center_lat() );
441     if ( longitude >= -180.0 && longitude <= 180.0 
442          && latitude >= -90.0 && latitude <= 90.0 )
443     {
444         schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
445     }
446 }
447
448
449 int FGTileMgr::updateCurrentElevAtPos( sgdVec3 abs_pos_vector,
450                                        double max_alt_m,
451                                        Point3D center)
452 {
453     sgdVec3 sc;
454
455     sgdSetVec3( sc, center[0], center[1], center[2]);
456
457     // overridden with actual values if a terrain intersection is
458     // found
459     double hit_elev = -9999.0;
460     double hit_radius = 0.0;
461     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
462     
463     bool hit = false;
464     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
465         // scenery center has been properly defined so any hit should
466         // be valid (and not just luck)
467         hit = fgCurrentElev(abs_pos_vector,
468                             max_alt_m,
469                             sc,
470                 // uncomment next paramater to fly under
471                 // bridges and a slightly faster algorithm
472                 // but you won't be able to land on aircraft carriers
473                             // current_tile->get_terra_transform(),
474                             &hit_list,
475                             &hit_elev,
476                             &hit_radius,
477                             hit_normal);
478     }
479
480     if ( hit ) {
481         // cout << "elev = " << hit_elev << " " << hit_radius << endl;
482         globals->get_scenery()->set_cur_elev( hit_elev );
483         globals->get_scenery()->set_cur_radius( hit_radius );
484         globals->get_scenery()->set_cur_normal( hit_normal );
485     } else {
486         globals->get_scenery()->set_cur_elev( -9999.0 );
487         globals->get_scenery()->set_cur_radius( 0.0 );
488         globals->get_scenery()->set_cur_normal( hit_normal );
489     }
490     return hit;
491 }
492
493
494 void FGTileMgr::prep_ssg_nodes( SGLocation *location, float vis ) {
495
496     // traverse the potentially viewable tile list and update range
497     // selector and transform
498
499     Point3D center = location->get_tile_center();
500     float *up = location->get_world_up();
501
502     FGTileEntry *e;
503     tile_cache.reset_traversal();
504
505     while ( ! tile_cache.at_end() ) {
506         // cout << "processing a tile" << endl;
507         if ( (e = tile_cache.get_current()) ) {
508             e->prep_ssg_node( center, up, vis);
509         } else {
510             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
511         }
512         tile_cache.next();
513     }
514 }
515
516 bool FGTileMgr::set_tile_filter( bool f ) {
517     bool old = tile_filter;
518     tile_filter = f;
519     return old;
520 }
521
522 int FGTileMgr::tile_filter_cb( ssgEntity *, int )
523 {
524   return tile_filter ? 1 : 0;
525 }