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