]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
db78a6dbfd7c86047ce5388e2693055067cdd1e9
[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::attach_queue;
74 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
75 #else
76 queue<FGTileEntry *> FGTileMgr::attach_queue;
77 queue<FGTileDeferredModel *> FGTileMgr::model_queue;
78 #endif // ENABLE_THREADS
79
80
81 // Constructor
82 FGTileMgr::FGTileMgr():
83     state( Start ),
84     vis( 16000 ),
85     counter_hack(0)
86 {
87 }
88
89
90 // Destructor
91 FGTileMgr::~FGTileMgr() {
92 }
93
94
95 // Initialize the Tile Manager subsystem
96 int FGTileMgr::init() {
97     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
98
99     if ( state != Start ) {
100         SG_LOG( SG_TERRAIN, SG_INFO,
101                 "... Reinitializing." );
102         destroy_queue();
103     } else {
104         SG_LOG( SG_TERRAIN, SG_INFO,
105                 "... First time through." );
106         tile_cache.init();
107     }
108
109     hit_list.clear();
110
111     state = Inited;
112
113     previous_bucket.make_bad();
114     current_bucket.make_bad();
115
116     longitude = latitude = -1000.0;
117     last_longitude = last_latitude = -1000.0;
118         
119     return 1;
120 }
121
122
123 // schedule a tile for loading
124 void FGTileMgr::sched_tile( const SGBucket& b ) {
125     // see if tile already exists in the cache
126     FGTileEntry *t = tile_cache.get_tile( b );
127
128     if ( t == NULL ) {
129         // create a new entry
130         FGTileEntry *e = new FGTileEntry( b );
131
132         // insert the tile into the cache
133         tile_cache.insert_tile( e );
134
135         // Schedule tile for loading
136         loader.add( e );
137     }
138 }
139
140
141 static void CurrentNormalInLocalPlane(sgVec3 dst, sgVec3 src) {
142     sgVec3 tmp;
143     sgSetVec3(tmp, src[0], src[1], src[2] );
144     sgMat4 TMP;
145     sgTransposeNegateMat4 ( TMP, globals->get_current_view()->get_UP() ) ;
146     sgXformVec3(tmp, tmp, TMP);
147     sgSetVec3(dst, tmp[2], tmp[1], tmp[0] );
148 }
149
150
151 // Determine scenery altitude via ssg.  Normally this just happens
152 // when we render the scene, but we'd also like to be able to do this
153 // explicitely.  lat & lon are in radians.  view_pos in current world
154 // coordinate translated near (0,0,0) (in meters.)  Returns result in
155 // meters.
156 bool FGTileMgr::current_elev_ssg( sgdVec3 abs_view_pos, double *terrain_elev ) {
157     sgdVec3 view_pos;
158     sgdVec3 sc;
159     sgdSetVec3( sc, scenery.center.x(), scenery.center.y(), scenery.center.z());
160     sgdSubVec3( view_pos, abs_view_pos, sc );
161
162     sgdVec3 orig, dir;
163     sgdCopyVec3(orig, view_pos );
164     sgdCopyVec3(dir, abs_view_pos );
165
166     hit_list.Intersect( terrain, orig, dir );
167
168     int this_hit=0;
169     Point3D geoc;
170     double result = -9999;
171
172     int hitcount = hit_list.num_hits();
173     for ( int i = 0; i < hitcount; ++i ) {
174         geoc = sgCartToPolar3d( scenery.center + hit_list.get_point(i) );      
175         double lat_geod, alt, sea_level_r;
176         sgGeocToGeod(geoc.lat(), geoc.radius(), &lat_geod, 
177                      &alt, &sea_level_r);
178         if ( alt > result && alt < 10000 ) {
179             result = alt;
180             this_hit = i;
181         }
182     }
183
184     if ( result > -9000 ) {
185         *terrain_elev = result;
186         scenery.cur_radius = geoc.radius();
187         sgVec3 tmp;
188         sgSetVec3(tmp, hit_list.get_normal(this_hit));
189         // cout << "cur_normal: " << tmp[0] << " " << tmp[1] << " "
190         //      << tmp[2] << endl;
191         ssgState *IntersectedLeafState =
192             ((ssgLeaf*)hit_list.get_entity(this_hit))->getState();
193         CurrentNormalInLocalPlane(tmp, tmp);
194         sgdSetVec3( scenery.cur_normal, tmp );
195         // cout << "NED: " << tmp[0] << " " << tmp[1] << " " << tmp[2] << endl;
196         return true;
197     } else {
198         SG_LOG( SG_TERRAIN, SG_INFO, "no terrain intersection" );
199         *terrain_elev = 0.0;
200         float *up = globals->get_current_view()->get_world_up();
201         sgdSetVec3(scenery.cur_normal, up[0], up[1], up[2]);
202         return false;
203     }
204 }
205
206
207 // schedule a needed buckets for loading
208 void FGTileMgr::schedule_needed() {
209 #ifndef FG_OLD_WEATHER
210     if ( WeatherDatabase != NULL ) {
211         vis = WeatherDatabase->getWeatherVisibility();
212     } else {
213         vis = 16000;
214     }
215 #else
216     vis = current_weather.get_visibility();
217 #endif
218     // cout << "visibility = " << vis << endl;
219
220     double tile_width = current_bucket.get_width_m();
221     double tile_height = current_bucket.get_height_m();
222     // cout << "tile width = " << tile_width << "  tile_height = "
223     //      << tile_height !<< endl;
224
225     xrange = (int)(vis / tile_width) + 1;
226     yrange = (int)(vis / tile_height) + 1;
227     if ( xrange < 1 ) { xrange = 1; }
228     if ( yrange < 1 ) { yrange = 1; }
229     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
230
231     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) );
232
233     SGBucket b;
234
235     // schedule center tile first so it can be loaded first
236     b = sgBucketOffset( longitude, latitude, 0, 0 );
237     sched_tile( b );
238
239     int x, y;
240
241     // schedule next ring of 8 tiles
242     for ( x = -1; x <= 1; ++x ) {
243         for ( y = -1; y <= 1; ++y ) {
244             if ( x != 0 || y != 0 ) {
245                 b = sgBucketOffset( longitude, latitude, x, y );
246                 sched_tile( b );
247             }
248         }
249     }
250     
251     // schedule remaining tiles
252     for ( x = -xrange; x <= xrange; ++x ) {
253         for ( y = -yrange; y <= yrange; ++y ) {
254             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
255                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
256                 sched_tile( b );
257             }
258         }
259     }
260 }
261
262
263 void FGTileMgr::initialize_queue()
264 {
265     // First time through or we have teleported, initialize the
266     // system and load all relavant tiles
267
268     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
269     // cout << "tile cache size = " << tile_cache.get_size() << endl;
270
271     // wipe/initialize tile cache
272     // tile_cache.init();
273     previous_bucket.make_bad();
274
275     // build the local area list and schedule tiles for loading
276
277     // start with the center tile and work out in concentric
278     // "rings"
279
280     schedule_needed();
281
282     // do we really want to lose this? CLO
283 #if 0
284     // Now force a load of the center tile and inner ring so we
285     // have something to see in our first frame.
286     int i;
287     for ( i = 0; i < 9; ++i ) {
288         if ( load_queue.size() ) {
289             SG_LOG( SG_TERRAIN, SG_DEBUG, 
290                     "Load queue not empty, loading a tile" );
291
292             SGBucket pending = load_queue.front();
293             load_queue.pop_front();
294             load_tile( pending );
295         }
296     }
297 #endif
298 }
299
300
301 // forced emptying of the queue
302 // This is necessay to keep bookeeping straight for the
303 // tile_cache   -- which actually handles all the
304 // (de)allocations  
305 void FGTileMgr::destroy_queue() {
306     // load_queue.clear();
307 }
308
309
310 // given the current lon/lat (in degrees), fill in the array of local
311 // chunks.  If the chunk isn't already in the cache, then read it from
312 // disk.
313 int FGTileMgr::update( double lon, double lat ) {
314     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
315
316     // FGInterface *f = current_aircraft.fdm_state;
317
318     // lonlat for this update 
319     // longitude = f->get_Longitude() * SGD_RADIANS_TO_DEGREES;
320     // latitude = f->get_Latitude() * SGD_RADIANS_TO_DEGREES;
321     longitude = lon;
322     latitude = lat;
323     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
324     //      " lat " << lonlat[LAT] );
325
326     current_bucket.set_bucket( longitude, latitude );
327     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
328
329     if ( tile_cache.exists( current_bucket ) ) {
330         current_tile = tile_cache.get_tile( current_bucket );
331         scenery.next_center = current_tile->center;
332     } else {
333         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
334     }
335
336     if ( state == Running ) {
337         if ( !(current_bucket == previous_bucket) ) {
338             // We've moved to a new bucket, we need to schedule any
339             // needed tiles for loading.
340             schedule_needed();
341         }
342     } else if ( state == Start || state == Inited ) {
343         initialize_queue();
344         state = Running;
345     }
346
347     // load the next tile in the load queue (or authorize the next
348     // load in the case of the threaded tile pager)
349     loader.update();
350
351     // load the next model in the load queue.  Currently this must
352     // happen in the render thread because model loading can trigger
353     // texture loading which involves use of the opengl api.
354     if ( !model_queue.empty() ) {
355         cout << "loading next model ..." << endl;
356         // load the next tile in the queue
357 #ifdef ENABLE_THREADS
358         FGDeferredModel* dm = model_queue.pop();
359 #else
360         FGDeferredModel* dm = model_queue.front();
361         model_queue.pop();
362 #endif
363         
364         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
365         ssgEntity *obj_model
366             = ssgLoad( (char *)(dm->get_model_path().c_str()) );
367         dm->get_obj_trans()->addKid( obj_model );
368         dm->get_tile()->dec_pending_models();
369
370         delete dm;
371     }
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         if ( !attach_queue.empty() ) {
422 #ifdef ENABLE_THREADS
423             FGTileEntry* e = attach_queue.pop();
424 #else
425             FGTileEntry* e = attach_queue.front();
426             attach_queue.pop();
427 #endif
428             e->add_ssg_nodes( terrain, ground );
429             // cout << "Adding ssg nodes for "
430         }
431     }
432
433     return 1;
434 }
435
436
437 void FGTileMgr::prep_ssg_nodes() {
438     float vis = 0.0;
439
440 #ifndef FG_OLD_WEATHER
441     if ( WeatherDatabase ) {
442         vis = WeatherDatabase->getWeatherVisibility();
443     } else {
444         vis = 16000;
445     }
446 #else
447     vis = current_weather.get_visibility();
448 #endif
449     // cout << "visibility = " << vis << endl;
450
451     // traverse the potentially viewable tile list and update range
452     // selector and transform
453
454     FGTileEntry *e;
455     tile_cache.reset_traversal();
456
457     while ( ! tile_cache.at_end() ) {
458         // cout << "processing a tile" << endl;
459         if ( (e = tile_cache.get_current()) ) {
460             e->prep_ssg_node( scenery.center, vis);
461         } else {
462             cout << "warning ... empty tile in cache" << endl;
463         }
464         tile_cache.next();
465    }
466 }