]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Restructuring how tiles are freed to allow us to eventually spread the task
[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 #ifdef HAVE_WINDOWS_H
29 #  include <windows.h>
30 #endif
31
32 #include <GL/glut.h>
33
34 #include <plib/ssg.h>
35
36 #include <simgear/constants.h>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/math/point3d.hxx>
39 #include <simgear/math/polar3d.hxx>
40 #include <simgear/math/sg_geodesy.hxx>
41 #include <simgear/math/vector.hxx>
42
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Main/viewer.hxx>
46 #include <Objects/obj.hxx>
47
48 #include "newcache.hxx"
49 #include "scenery.hxx"
50 #include "tilemgr.hxx"
51
52 #define TEST_LAST_HIT_CACHE
53
54 // the tile manager
55 FGTileMgr global_tile_mgr;
56
57
58 #ifdef ENABLE_THREADS
59 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
60 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
61 #else
62 queue<FGTileEntry *> FGTileMgr::attach_queue;
63 queue<FGDeferredModel *> FGTileMgr::model_queue;
64 #endif // ENABLE_THREADS
65 queue<FGTileEntry *> FGTileMgr::delete_queue;
66
67
68 // Constructor
69 FGTileMgr::FGTileMgr():
70     state( Start ),
71     current_tile( NULL ),
72     vis( 16000 ),
73     counter_hack(0),
74     max_cache_size(100)
75 {
76 }
77
78
79 // Destructor
80 FGTileMgr::~FGTileMgr() {
81 }
82
83
84 // Initialize the Tile Manager subsystem
85 int FGTileMgr::init() {
86     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
87
88     tile_cache.init();
89
90 #if 0
91
92     // instead it's just a lot easier to let any pending work flush
93     // through, rather than trying to arrest the queue and nuke all
94     // the various work at all the various stages and get everything
95     // cleaned up properly.
96
97     while ( ! attach_queue.empty() ) {
98         attach_queue.pop();
99     }
100
101     while ( ! model_queue.empty() ) {
102 #ifdef ENABLE_THREADS
103         FGDeferredModel* dm = model_queue.pop();
104 #else
105         FGDeferredModel* dm = model_queue.front();
106         model_queue.pop();
107 #endif
108         delete dm;
109     }
110     loader.reinit();
111 #endif
112
113     hit_list.clear();
114
115     state = Inited;
116
117     previous_bucket.make_bad();
118     current_bucket.make_bad();
119
120     longitude = latitude = -1000.0;
121     last_longitude = last_latitude = -1000.0;
122         
123     return 1;
124 }
125
126
127 // schedule a tile for loading
128 void FGTileMgr::sched_tile( const SGBucket& b ) {
129     // see if tile already exists in the cache
130     FGTileEntry *t = tile_cache.get_tile( b );
131
132     if ( t == NULL ) {
133         // make space in the cache
134         while ( tile_cache.get_size() > max_cache_size ) {
135             long index = tile_cache.get_oldest_tile();
136             if ( index >= 0 ) {
137                 FGTileEntry *old = tile_cache.get_tile( index );
138                 delete_queue.push( old );
139                 tile_cache.clear_entry( index );
140             } else {
141                 // nothing to free ?!? forge ahead
142                 break;
143             }
144         }
145
146         // create a new entry
147         FGTileEntry *e = new FGTileEntry( b );
148
149         // insert the tile into the cache
150         if ( tile_cache.insert_tile( e ) ) {
151           // Schedule tile for loading
152           loader.add( e );
153         } else {
154           // insert failed (cache full with no available entries to
155           // delete.)  Try again later
156           delete e;
157         }
158     }
159 }
160
161
162 // schedule a needed buckets for loading
163 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
164     // sanity check (unfortunately needed!)
165     if ( longitude < -180.0 || longitude > 180.0 
166          || latitude < -90.0 || latitude > 90.0 )
167     {
168         SG_LOG( SG_TERRAIN, SG_ALERT,
169                 "Attempting to schedule tiles for bogus latitude and" );
170         SG_LOG( SG_TERRAIN, SG_ALERT,
171                 "longitude.  This is a FATAL error.  Exiting!" );
172         exit(-1);        
173     }
174
175    SG_LOG( SG_TERRAIN, SG_INFO,
176            "scheduling needed tiles for " << longitude << " " << latitude );
177
178 //   vis = fgGetDouble("/environment/visibility-m");
179
180     double tile_width = curr_bucket.get_width_m();
181     double tile_height = curr_bucket.get_height_m();
182     // cout << "tile width = " << tile_width << "  tile_height = "
183     //      << tile_height !<< endl;
184
185     xrange = (int)(vis / tile_width) + 1;
186     yrange = (int)(vis / tile_height) + 1;
187     if ( xrange < 1 ) { xrange = 1; }
188     if ( yrange < 1 ) { yrange = 1; }
189     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
190
191     // note * 2 at end doubles cache size (for fdm and viewer)
192     max_cache_size = (2*xrange + 2) * (2*yrange + 2) * 2;
193
194     SGBucket b;
195
196     // schedule center tile first so it can be loaded first
197     b = sgBucketOffset( longitude, latitude, 0, 0 );
198     sched_tile( b );
199
200     int x, y;
201
202     // schedule next ring of 8 tiles
203     for ( x = -1; x <= 1; ++x ) {
204         for ( y = -1; y <= 1; ++y ) {
205             if ( x != 0 || y != 0 ) {
206                 b = sgBucketOffset( longitude, latitude, x, y );
207                 sched_tile( b );
208             }
209         }
210     }
211     
212     // schedule remaining tiles
213     for ( x = -xrange; x <= xrange; ++x ) {
214         for ( y = -yrange; y <= yrange; ++y ) {
215             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
216                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
217                 sched_tile( b );
218             }
219         }
220     }
221 }
222
223
224 void FGTileMgr::initialize_queue()
225 {
226     // First time through or we have teleported, initialize the
227     // system and load all relavant tiles
228
229     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << 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 // given the current lon/lat (in degrees), fill in the array of local
264 // chunks.  If the chunk isn't already in the cache, then read it from
265 // disk.
266 int FGTileMgr::update( double lon, double lat, double visibility_meters ) {
267         sgdVec3 abs_pos_vector;
268         sgdCopyVec3(abs_pos_vector , globals->get_current_view()->get_absolute_view_pos());
269         return update( lon, lat, visibility_meters, abs_pos_vector,
270                        current_bucket, previous_bucket,
271                        globals->get_scenery()->get_center() );
272 }
273
274 int FGTileMgr::update( double lon, double lat, double visibility_meters,
275                        sgdVec3 abs_pos_vector, SGBucket p_current,
276                        SGBucket p_previous, Point3D center ) {
277     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
278     //         << lon << " " << lat );
279
280     longitude = lon;
281     latitude = lat;
282     current_bucket = p_current;
283     previous_bucket = p_previous;
284
285     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
286     //      " lat " << lonlat[LAT] );
287
288     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
289
290     setCurrentTile( longitude, latitude);
291
292     // do tile load scheduling. 
293     // Note that we need keep track of both viewer buckets and fdm buckets.
294     if ( state == Running ) {
295        SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
296        if (!(current_bucket == previous_bucket )) {
297          // We've moved to a new bucket, we need to schedule any
298          // needed tiles for loading.
299          schedule_needed(visibility_meters, current_bucket);
300        }
301     } else if ( state == Start || state == Inited ) {
302         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
303         initialize_queue();
304         state = Running;
305
306         // load the next tile in the load queue (or authorize the next
307         // load in the case of the threaded tile pager)
308         loader.update();
309     }
310
311     
312     // load the next model in the load queue.  Currently this must
313     // happen in the render thread because model loading can trigger
314     // texture loading which involves use of the opengl api.
315     if ( !model_queue.empty() ) {
316         // cout << "loading next model ..." << endl;
317         // load the next tile in the queue
318 #ifdef ENABLE_THREADS
319         FGDeferredModel* dm = model_queue.pop();
320 #else
321         FGDeferredModel* dm = model_queue.front();
322         model_queue.pop();
323 #endif
324         
325         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
326         ssgEntity *obj_model
327             = ssgLoad( (char *)(dm->get_model_path().c_str()) );
328         if ( obj_model != NULL ) {
329             dm->get_obj_trans()->addKid( obj_model );
330         }
331         dm->get_tile()->dec_pending_models();
332
333         delete dm;
334     }
335     
336     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
337
338
339     // save bucket...
340     previous_bucket = current_bucket;
341
342     // activate loader thread one out of every 5 frames
343     if ( counter_hack == 0 ) {
344       // Notify the tile loader that it can load another tile
345       loader.update();
346     } else {
347       counter_hack = (counter_hack + 1) % 5;
348     }
349
350     if ( !attach_queue.empty() ) {
351 #ifdef ENABLE_THREADS
352         FGTileEntry* e = attach_queue.pop();
353 #else
354         FGTileEntry* e = attach_queue.front();
355         attach_queue.pop();
356 #endif
357         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
358                           globals->get_scenery()->get_gnd_lights_branch(),
359                           globals->get_scenery()->get_rwy_lights_branch() );
360         // cout << "Adding ssg nodes for "
361     }
362
363     if ( !delete_queue.empty() ) {
364         FGTileEntry* e = delete_queue.front();
365         delete_queue.pop();
366         e->disconnect_ssg_nodes();
367         e->free_tile();
368         delete e;
369     }
370
371     // no reason to update this if we haven't moved...
372     if ( longitude != last_longitude || latitude != last_latitude ) {
373       // update current elevation... 
374       if (updateCurrentElevAtPos(abs_pos_vector, center)) {
375         last_longitude = longitude;
376         last_latitude = latitude;
377       }
378     }
379
380 #if 0
381     }
382 #endif
383
384     return 1;
385 }
386
387 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
388 void FGTileMgr::refresh_view_timestamps() {
389     SG_LOG( SG_TERRAIN, SG_INFO,
390         "Refreshing timestamps for " << current_bucket.get_center_lon()
391         << " " << current_bucket.get_center_lat() );
392     schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
393 }
394
395 // check and set current tile and scenery center...
396 void FGTileMgr::setCurrentTile(double longitude, double latitude) {
397
398     // check tile cache entry...
399     current_bucket.set_bucket( longitude, latitude );
400     if ( tile_cache.exists( current_bucket ) ) {
401         current_tile = tile_cache.get_tile( current_bucket );
402         globals->get_scenery()->set_next_center( current_tile->center );
403     } else {
404         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
405         globals->get_scenery()->set_next_center( Point3D(0.0) );
406     }
407 }
408
409 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
410
411   sgdVec3 sc;
412
413   sgdSetVec3( sc,
414     center[0],
415     center[1],
416     center[2]);
417
418     // overridden with actual values if a terrain intersection is
419     // found
420     double hit_elev = -9999.0;
421     double hit_radius = 0.0;
422     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
423     
424     bool hit = false;
425     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
426        // scenery center has been properly defined so any hit
427        // should be valid (and not just luck)
428        hit = fgCurrentElev(abs_pos_vector,
429           sc,
430           current_tile->get_terra_transform(),
431           &hit_list,
432           &hit_elev,
433           &hit_radius,
434           hit_normal);
435     }
436
437     if ( hit ) {
438           globals->get_scenery()->set_cur_elev( hit_elev );
439           globals->get_scenery()->set_cur_radius( hit_radius );
440           globals->get_scenery()->set_cur_normal( hit_normal );
441     } else {
442           globals->get_scenery()->set_cur_elev( -9999.0 );
443           globals->get_scenery()->set_cur_radius( 0.0 );
444           globals->get_scenery()->set_cur_normal( hit_normal );
445     }
446     return hit;
447 }
448
449 void FGTileMgr::prep_ssg_nodes(float vis) {
450
451     // traverse the potentially viewable tile list and update range
452     // selector and transform
453
454     // just setup and call new function...
455
456     sgVec3 up;
457     sgCopyVec3( up, globals->get_current_view()->get_world_up() );
458
459     Point3D center;
460     center = globals->get_scenery()->get_center();
461     prep_ssg_nodes( vis, up, center );
462
463 }
464
465 void FGTileMgr::prep_ssg_nodes(float vis, sgVec3 up, Point3D center) {
466
467     // traverse the potentially viewable tile list and update range
468     // selector and transform
469
470     FGTileEntry *e;
471     tile_cache.reset_traversal();
472
473     while ( ! tile_cache.at_end() ) {
474         // cout << "processing a tile" << endl;
475         if ( (e = tile_cache.get_current()) ) {
476             e->prep_ssg_node( center, up, vis);
477         } else {
478             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
479         }
480         tile_cache.next();
481    }
482 }
483