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