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