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