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