]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
b47e6246d60cd8ef61d61177ceb36ae7f26fdf64
[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 <Objects/obj.hxx>
45
46 #ifndef FG_OLD_WEATHER
47 #  include <WeatherCM/FGLocalWeatherDatabase.h>
48 #else
49 #  include <Weather/weather.hxx>
50 #endif
51
52 #include "newcache.hxx"
53 #include "scenery.hxx"
54 #include "tilemgr.hxx"
55
56 #define TEST_LAST_HIT_CACHE
57
58 extern ssgRoot *scene;
59 extern ssgBranch *terrain;
60 extern ssgBranch *ground;
61
62 // the tile manager
63 FGTileMgr global_tile_mgr;
64
65
66 // a temporary hack until we get everything rewritten with sgdVec3
67 static inline Point3D operator + (const Point3D& a, const sgdVec3 b)
68 {
69     return Point3D(a.x()+b[0], a.y()+b[1], a.z()+b[2]);
70 }
71
72 #ifdef ENABLE_THREADS
73 SGLockedQueue<FGTileEntry*> FGTileMgr::loaded_queue;
74 #endif // ENABLE_THREADS
75
76 // Constructor
77 FGTileMgr::FGTileMgr():
78     state( Start ),
79     vis( 16000 ),
80     counter_hack(0)
81 {
82 }
83
84
85 // Destructor
86 FGTileMgr::~FGTileMgr() {
87 }
88
89
90 // Initialize the Tile Manager subsystem
91 int FGTileMgr::init() {
92     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
93
94     if ( state != Start ) {
95         SG_LOG( SG_TERRAIN, SG_INFO,
96                 "... Reinitializing." );
97         destroy_queue();
98     } else {
99         SG_LOG( SG_TERRAIN, SG_INFO,
100                 "... First time through." );
101         tile_cache.init();
102     }
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         // create a new entry
125         FGTileEntry *e = new FGTileEntry( b );
126
127         // insert the tile into the cache
128         tile_cache.insert_tile( e );
129
130         // Schedule tile for loading
131         loader.add( e );
132     }
133 }
134
135
136 // depricated for threading
137 #if 0
138 // load a tile
139 void FGTileMgr::load_tile( const SGBucket& b ) {
140     // see if tile already exists in the cache
141     FGTileEntry *t = tile_cache.get_tile( b );
142
143     if ( t == NULL ) {
144         SG_LOG( SG_TERRAIN, SG_DEBUG, "Loading tile " << b );
145         tile_cache.fill_in( b );
146         t = tile_cache.get_tile( b );
147         t->prep_ssg_node( scenery.center, vis);
148     } else {
149         SG_LOG( SG_TERRAIN, SG_DEBUG, "Tile already in cache " << b );
150     }
151 }
152 #endif
153
154
155 static void CurrentNormalInLocalPlane(sgVec3 dst, sgVec3 src) {
156     sgVec3 tmp;
157     sgSetVec3(tmp, src[0], src[1], src[2] );
158     sgMat4 TMP;
159     sgTransposeNegateMat4 ( TMP, globals->get_current_view()->get_UP() ) ;
160     sgXformVec3(tmp, tmp, TMP);
161     sgSetVec3(dst, tmp[2], tmp[1], tmp[0] );
162 }
163
164
165 // Determine scenery altitude via ssg.  Normally this just happens
166 // when we render the scene, but we'd also like to be able to do this
167 // explicitely.  lat & lon are in radians.  view_pos in current world
168 // coordinate translated near (0,0,0) (in meters.)  Returns result in
169 // meters.
170 bool FGTileMgr::current_elev_ssg( sgdVec3 abs_view_pos, double *terrain_elev ) {
171     sgdVec3 view_pos;
172     sgdVec3 sc;
173     sgdSetVec3( sc, scenery.center.x(), scenery.center.y(), scenery.center.z());
174     sgdSubVec3( view_pos, abs_view_pos, sc );
175
176     sgdVec3 orig, dir;
177     sgdCopyVec3(orig, view_pos );
178     sgdCopyVec3(dir, abs_view_pos );
179
180     hit_list.Intersect( terrain, orig, dir );
181
182     int this_hit=0;
183     Point3D geoc;
184     double result = -9999;
185
186     int hitcount = hit_list.num_hits();
187     for ( int i = 0; i < hitcount; ++i ) {
188         geoc = sgCartToPolar3d( scenery.center + hit_list.get_point(i) );      
189         double lat_geod, alt, sea_level_r;
190         sgGeocToGeod(geoc.lat(), geoc.radius(), &lat_geod, 
191                      &alt, &sea_level_r);
192         if ( alt > result && alt < 10000 ) {
193             result = alt;
194             this_hit = i;
195         }
196     }
197
198     if ( result > -9000 ) {
199         *terrain_elev = result;
200         scenery.cur_radius = geoc.radius();
201         sgVec3 tmp;
202         sgSetVec3(tmp, hit_list.get_normal(this_hit));
203         // cout << "cur_normal: " << tmp[0] << " " << tmp[1] << " "
204         //      << tmp[2] << endl;
205         ssgState *IntersectedLeafState =
206             ((ssgLeaf*)hit_list.get_entity(this_hit))->getState();
207         CurrentNormalInLocalPlane(tmp, tmp);
208         sgdSetVec3( scenery.cur_normal, tmp );
209         // cout << "NED: " << tmp[0] << " " << tmp[1] << " " << tmp[2] << endl;
210         return true;
211     } else {
212         SG_LOG( SG_TERRAIN, SG_INFO, "no terrain intersection" );
213         *terrain_elev = 0.0;
214         float *up = globals->get_current_view()->get_world_up();
215         sgdSetVec3(scenery.cur_normal, up[0], up[1], up[2]);
216         return false;
217     }
218 }
219
220
221 // schedule a needed buckets for loading
222 void FGTileMgr::schedule_needed() {
223 #ifndef FG_OLD_WEATHER
224     if ( WeatherDatabase != NULL ) {
225         vis = WeatherDatabase->getWeatherVisibility();
226     } else {
227         vis = 16000;
228     }
229 #else
230     vis = current_weather.get_visibility();
231 #endif
232     // cout << "visibility = " << vis << endl;
233
234     double tile_width = current_bucket.get_width_m();
235     double tile_height = current_bucket.get_height_m();
236     // cout << "tile width = " << tile_width << "  tile_height = "
237     //      << tile_height !<< endl;
238
239     xrange = (int)(vis / tile_width) + 1;
240     yrange = (int)(vis / tile_height) + 1;
241     if ( xrange < 1 ) { xrange = 1; }
242     if ( yrange < 1 ) { yrange = 1; }
243     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
244
245     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) );
246
247     SGBucket b;
248
249     // schedule center tile first so it can be loaded first
250     b = sgBucketOffset( longitude, latitude, 0, 0 );
251     sched_tile( b );
252
253     int x, y;
254
255     // schedule next ring of 8 tiles
256     for ( x = -1; x <= 1; ++x ) {
257         for ( y = -1; y <= 1; ++y ) {
258             if ( x != 0 || y != 0 ) {
259                 b = sgBucketOffset( longitude, latitude, x, y );
260                 sched_tile( b );
261             }
262         }
263     }
264     
265     // schedule remaining tiles
266     for ( x = -xrange; x <= xrange; ++x ) {
267         for ( y = -yrange; y <= yrange; ++y ) {
268             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
269                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
270                 sched_tile( b );
271             }
272         }
273     }
274 }
275
276
277 void FGTileMgr::initialize_queue()
278 {
279     // First time through or we have teleported, initialize the
280     // system and load all relavant tiles
281
282     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
283     // cout << "tile cache size = " << tile_cache.get_size() << endl;
284
285     // wipe/initialize tile cache
286     // tile_cache.init();
287     previous_bucket.make_bad();
288
289     // build the local area list and schedule tiles for loading
290
291     // start with the center tile and work out in concentric
292     // "rings"
293
294     schedule_needed();
295
296     // do we really want to lose this? CLO
297 #if 0
298     // Now force a load of the center tile and inner ring so we
299     // have something to see in our first frame.
300     int i;
301     for ( i = 0; i < 9; ++i ) {
302         if ( load_queue.size() ) {
303             SG_LOG( SG_TERRAIN, SG_DEBUG, 
304                     "Load queue not empty, loading a tile" );
305
306             SGBucket pending = load_queue.front();
307             load_queue.pop_front();
308             load_tile( pending );
309         }
310     }
311 #endif
312 }
313
314
315 // forced emptying of the queue
316 // This is necessay to keep bookeeping straight for the
317 // tile_cache   -- which actually handles all the
318 // (de)allocations  
319 void FGTileMgr::destroy_queue() {
320     // load_queue.clear();
321 }
322
323
324 // given the current lon/lat (in degrees), fill in the array of local
325 // chunks.  If the chunk isn't already in the cache, then read it from
326 // disk.
327 int FGTileMgr::update( double lon, double lat ) {
328     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
329
330     // FGInterface *f = current_aircraft.fdm_state;
331
332     // lonlat for this update 
333     // longitude = f->get_Longitude() * SGD_RADIANS_TO_DEGREES;
334     // latitude = f->get_Latitude() * SGD_RADIANS_TO_DEGREES;
335     longitude = lon;
336     latitude = lat;
337     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
338     //      " lat " << lonlat[LAT] );
339
340     current_bucket.set_bucket( longitude, latitude );
341     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
342
343     if ( tile_cache.exists( current_bucket ) ) {
344         current_tile = tile_cache.get_tile( current_bucket );
345         scenery.next_center = current_tile->center;
346     } else {
347         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
348     }
349
350     if ( state == Running ) {
351         if ( !(current_bucket == previous_bucket) ) {
352             // We've moved to a new bucket, we need to schedule any
353             // needed tiles for loading.
354             schedule_needed();
355         }
356     } else if ( state == Start || state == Inited ) {
357         initialize_queue();
358         state = Running;
359     }
360
361     // now handled by threaded tile pager
362 #if 0
363     if ( load_queue.size() ) {
364         SG_LOG( SG_TERRAIN, SG_INFO, "Load queue size = " << load_queue.size()
365                 << " loading a tile" );
366
367         SGBucket pending = load_queue.front();
368         load_queue.pop_front();
369         load_tile( pending );
370     }
371 #endif
372
373     if ( scenery.center == Point3D(0.0) ) {
374         // initializing
375         cout << "initializing scenery current elevation  ... " << endl;
376         sgdVec3 tmp_abs_view_pos;
377         sgVec3 tmp_view_pos;
378
379         Point3D geod_pos = Point3D( longitude * SGD_DEGREES_TO_RADIANS,
380                                     latitude * SGD_DEGREES_TO_RADIANS,
381                                     0.0);
382         Point3D tmp = sgGeodToCart( geod_pos );
383         scenery.center = tmp;
384         sgdSetVec3( tmp_abs_view_pos, tmp.x(), tmp.y(), tmp.z() );
385
386         // cout << "abs_view_pos = " << tmp_abs_view_pos << endl;
387         prep_ssg_nodes();
388         sgSetVec3( tmp_view_pos, 0.0, 0.0, 0.0 );
389         double tmp_elev;
390         if ( current_elev_ssg(tmp_abs_view_pos, &tmp_elev) ) {
391             scenery.cur_elev = tmp_elev;
392         } else {
393             scenery.cur_elev = 0.0;
394         }
395         cout << "result = " << scenery.cur_elev << endl;
396     } else {
397         // cout << "abs view pos = " << current_view.abs_view_pos
398         //      << " view pos = " << current_view.view_pos << endl;
399         double tmp_elev;
400         if ( current_elev_ssg(globals->get_current_view()->get_abs_view_pos(),
401                               &tmp_elev) )
402         {
403             scenery.cur_elev = tmp_elev;
404         } else {
405             scenery.cur_elev = 0.0;
406         }  
407     }
408
409     // cout << "current elevation (ssg) == " << scenery.cur_elev << endl;
410
411     previous_bucket = current_bucket;
412     last_longitude = longitude;
413     last_latitude  = latitude;
414
415     // activate loader thread one out of every 5 frames
416     counter_hack = (counter_hack + 1) % 5;
417     if ( !counter_hack ) {
418         // Notify the tile loader that it can load another tile
419         // loader.update();
420
421 #ifdef ENABLE_THREADS
422         if (!loaded_queue.empty())
423         {
424             FGTileEntry* e = loaded_queue.pop();
425             e->add_ssg_nodes( terrain, ground );
426             //std::cout << "Adding ssg nodes for "
427             //<< e->get_tile_bucket() << "\n";
428         }
429 #endif // ENABLE_THREADS
430     }
431
432     return 1;
433 }
434
435
436 void FGTileMgr::prep_ssg_nodes() {
437     float vis = 0.0;
438
439 #ifndef FG_OLD_WEATHER
440     if ( WeatherDatabase ) {
441         vis = WeatherDatabase->getWeatherVisibility();
442     } else {
443         vis = 16000;
444     }
445 #else
446     vis = current_weather.get_visibility();
447 #endif
448     // cout << "visibility = " << vis << endl;
449
450     // traverse the potentially viewable tile list and update range
451     // selector and transform
452
453     FGTileEntry *e;
454     tile_cache.reset_traversal();
455
456     while ( ! tile_cache.at_end() ) {
457         // cout << "processing a tile" << endl;
458         if ( (e = tile_cache.get_current()) ) {
459             e->prep_ssg_node( scenery.center, vis);
460         } else {
461             cout << "warning ... empty tile in cache" << endl;
462         }
463         tile_cache.next();
464    }
465 }