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