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