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