Debian Codegraph @

src/Scenery/tilemgr.cxx

raw symbols SCIP
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // SPDX-FileCopyrightText: 1998 Curtis L. Olson
6 // SPDX-License-Identifier: GPL-2.0-or-later
7
8 #include <config.h>
9
10 #include <algorithm>
11 #include <functional>
12
13 #include <osgViewer/Viewer>
14 #include <osgDB/Registry>
15
16 #include <simgear/constants.h>
17 #include <simgear/debug/logstream.hxx>
18 #include <simgear/structure/exception.hxx>
19 #include <simgear/scene/model/modellib.hxx>
20 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
21 #include <simgear/scene/tgdb/VPBTechnique.hxx>
22 #include <simgear/scene/tgdb/VPBLineFeatureRenderer.hxx>
23 #include <simgear/scene/tsync/terrasync.hxx>
24 #include <simgear/misc/strutils.hxx>
25 #include <simgear/scene/material/matlib.hxx>
26
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/sentryIntegration.hxx>
30 #include <Model/validateSharedModels.hxx>
31 #include <Scripting/NasalModelData.hxx>
32 #include <Scripting/NasalSys.hxx>
33 #include <Viewer/renderer.hxx>
34 #include <Viewer/splash.hxx>
35
36 #include "scenery.hxx"
37 #include "SceneryPager.hxx"
38 #include "tilemgr.hxx"
39
40 using flightgear::SceneryPager;
41
42 class FGTileMgr::TileManagerListener : public SGPropertyChangeListener
43 {
44 public:
45 TileManagerListener(FGTileMgr* manager) :
46 _manager(manager),
47 _useVBOsProp(fgGetNode("/sim/rendering/use-vbos", true)),
48 _enableCacheProp(fgGetNode("/sim/tile-cache/enable", true)),
49 _pagedLODMaximumProp(fgGetNode("/sim/rendering/max-paged-lod", true)),
50 _lodDetailed(fgGetNode("/sim/rendering/static-lod/detailed", true)),
51 _lodRoughDelta(fgGetNode("/sim/rendering/static-lod/rough-delta", true)),
52 _lodBareDelta(fgGetNode("/sim/rendering/static-lod/bare-delta", true)),
53 _lodRough(fgGetNode("/sim/rendering/static-lod/rough", true)),
54 _lodBare(fgGetNode("/sim/rendering/static-lod/bare", true))
55 {
56 _useVBOsProp->addChangeListener(this, true);
57
58 _enableCacheProp->addChangeListener(this, true);
59 if (_enableCacheProp->getType() == simgear::props::NONE) {
60 _enableCacheProp->setBoolValue(true);
61 }
62
63 if (_pagedLODMaximumProp->getType() == simgear::props::NONE) {
64 // not set, use OSG default / environment value variable
65 osg::ref_ptr<osgViewer::View> view(globals->get_renderer()->getView());
66 int current = view->getDatabasePager()->getTargetMaximumNumberOfPageLOD();
67 _pagedLODMaximumProp->setIntValue(current);
68 }
69 _pagedLODMaximumProp->addChangeListener(this, true);
70 _lodDetailed->addChangeListener(this, true);
71 _lodBareDelta->addChangeListener(this, true);
72 _lodRoughDelta->addChangeListener(this, true);
73 }
74
75 ~TileManagerListener()
76 {
77 _useVBOsProp->removeChangeListener(this);
78 _enableCacheProp->removeChangeListener(this);
79 _pagedLODMaximumProp->removeChangeListener(this);
80 _lodDetailed->removeChangeListener(this);
81 _lodBareDelta->removeChangeListener(this);
82 _lodRoughDelta->removeChangeListener(this);
83 }
84
85 void valueChanged(SGPropertyNode* prop) override
86 {
87 if (prop == _useVBOsProp) {
88 bool useVBOs = prop->getBoolValue();
89 _manager->_options->setPluginStringData("SimGear::USE_VBOS",
90 useVBOs ? "ON" : "OFF");
91 } else if (prop == _enableCacheProp) {
92 _manager->_enableCache = prop->getBoolValue();
93 } else if (prop == _pagedLODMaximumProp) {
94 int v = prop->getIntValue();
95 osg::ref_ptr<osgViewer::View> view(globals->get_renderer()->getView());
96 if (view) {
97 osgDB::DatabasePager* pager = view->getDatabasePager();
98 if (pager) pager->setTargetMaximumNumberOfPageLOD(v);
99 }
100 } else if (prop == _lodDetailed || prop == _lodBareDelta || prop == _lodRoughDelta) {
101 // compatibility with earlier versions; set the static LOD ranges appropriately as otherwise (bad) self managed
102 // LOD on scenery with range animations doesn't work.
103 // see also /sim/rendering/enable-range-lod-animations - which is false by default in > 2019.2 which also fixes
104 // the scenery but in a more efficient way.
105 _lodRough->setDoubleValue(_lodDetailed->getDoubleValue() + _lodRoughDelta->getDoubleValue());
106 _lodBare->setDoubleValue(_lodRough->getDoubleValue() + _lodBareDelta->getDoubleValue());
107 }
108
109 flightgear::addSentryBreadcrumb("Property:" + prop->getNameString() + " is now " +
110 prop->getStringValue(),
111 "info");
112 }
113
114 private:
115 FGTileMgr* _manager;
116 SGPropertyNode_ptr _useVBOsProp,
117 _enableCacheProp,
118 _pagedLODMaximumProp,
119 _lodDetailed,
120 _lodRoughDelta,
121 _lodBareDelta,
122 _lodRough,
123 _lodBare
124 ;
125 };
126
127 FGTileMgr::FGTileMgr():
128 state( Start ),
129 last_state( Running ),
130 scheduled_visibility(100.0),
131 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
132 _lodDetailed(fgGetNode("/sim/rendering/static-lod/detailed", true)),
133 _lodRoughDelta(fgGetNode("/sim/rendering/static-lod/rough-delta", true)),
134 _lodBareDelta(fgGetNode("/sim/rendering/static-lod/bare-delta", true)),
135 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
136 _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
137 _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
138 _pager_file_queue_size(fgGetNode("/sim/rendering/statistics/database-pager/file-queue-size", true)),
139 _pager_compile_queue_size(fgGetNode("/sim/rendering/statistics/database-pager/compile-queue-size", true)),
140 _pager_merge_queue_size(fgGetNode("/sim/rendering/statistics/database-pager/merge-queue-size", true)),
141 _pager_min_merge_time(fgGetNode("/sim/rendering/statistics/database-pager/min-merge-time", true)),
142 _pager_mean_merge_time(fgGetNode("/sim/rendering/statistics/database-pager/mean-merge-time", true)),
143 _pager_max_merge_time(fgGetNode("/sim/rendering/statistics/database-pager/max-merge-time", true)),
144 _pager(FGScenery::getPagerSingleton()),
145 _enableCache(true),
146 _use_vpb(false)
147 {
148 }
149
150
151 FGTileMgr::~FGTileMgr() = default;
152
153 // Initialize the Tile Manager subsystem
154 void FGTileMgr::init()
155 {
156 reinit();
157 }
158
159 void FGTileMgr::shutdown()
160 {
161 _listener.reset();
162
163 FGScenery* scenery = globals->get_scenery();
164 if (scenery && scenery->get_terrain_branch()) {
165 osg::Group* group = scenery->get_terrain_branch();
166 group->removeChildren(0, group->getNumChildren());
167 }
168 // clear OSG cache
169 osgDB::Registry::instance()->clearObjectCache();
170 state = Start; // need to init again
171 }
172
173 void FGTileMgr::reinit()
174 {
175 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
176 auto terraSync = globals->get_subsystem<simgear::SGTerraSync>();
177
178 // drops the previous options reference
179 _options = new simgear::SGReaderWriterOptions;
180 _listener.reset(new TileManagerListener(this));
181
182 materialLibChanged();
183 _options->setPropertyNode(globals->get_props());
184
185 osgDB::FilePathList &fp = _options->getDatabasePathList();
186 const PathList &sc = globals->get_fg_scenery();
187 fp.clear();
188 for (auto it = sc.begin(); it != sc.end(); ++it) {
189 fp.push_back(it->utf8Str());
190 }
191 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root().utf8Str());
192
193 if (terraSync) {
194 _options->setPluginStringData("SimGear::TERRASYNC_ROOT", globals->get_terrasync_dir().utf8Str());
195 }
196
197 if (!_disableNasalHooks->getBoolValue())
198 _options->setModelData(new FGNasalModelDataProxy);
199
200 double detailed = fgGetDouble("/sim/rendering/static-lod/detailed", SG_OBJECT_RANGE_DETAILED);
201 double rough = fgGetDouble("/sim/rendering/static-lod/rough-delta", SG_OBJECT_RANGE_ROUGH) + detailed;
202 double bare = fgGetDouble("/sim/rendering/static-lod/bare", SG_OBJECT_RANGE_BARE) + rough;
203 double tile_min_expiry = fgGetDouble("/sim/rendering/plod-minimum-expiry-time-secs", SG_TILE_MIN_EXPIRY);
204 flightgear::addSentryBreadcrumb("PLod-minimum-expiry time=" + std::to_string(tile_min_expiry), "info");
205
206 _use_vpb = fgGetBool("/scenery/use-vpb");
207
208 _options->setPluginStringData("SimGear::LOD_RANGE_BARE", std::to_string(bare));
209 _options->setPluginStringData("SimGear::LOD_RANGE_ROUGH", std::to_string(rough));
210 _options->setPluginStringData("SimGear::LOD_RANGE_DETAILED", std::to_string(detailed));
211 _options->setPluginStringData("SimGear::PAGED_LOD_EXPIRY", std::to_string(tile_min_expiry));
212
213 string_list scenerySuffixes;
214 for (auto node : fgGetNode("/sim/rendering/", true)->getChildren("scenery-path-suffix")) {
215 if (node->getBoolValue("enabled", true)) {
216 scenerySuffixes.push_back(node->getStringValue("name"));
217 }
218 }
219
220 if (scenerySuffixes.empty()) {
221 // if preferences didn't load, use some default
222 scenerySuffixes = {"Objects", "Terrain"}; // default values
223 }
224
225 if (terraSync) {
226 terraSync->setSceneryPathSuffixes(scenerySuffixes);
227 }
228 _options->setSceneryPathSuffixes(scenerySuffixes);
229
230 if (state != Start)
231 {
232 // protect against multiple scenery reloads and properly reset flags,
233 // otherwise aircraft fall through the ground while reloading scenery
234 if (_scenery_loaded->getBoolValue() == false) {
235 SG_LOG( SG_TERRAIN, SG_INFO, "/sim/sceneryloaded already false, avoiding duplicate re-init of tile manager" );
236 return;
237 }
238 }
239
240 _scenery_loaded->setBoolValue(false);
241 fgSetDouble("/sim/startup/splash-alpha", 1.0);
242
243 materialLibChanged();
244
245 // remove all old scenery nodes from scenegraph and clear cache
246 osg::Group* group = globals->get_scenery()->get_terrain_branch();
247 group->removeChildren(0, group->getNumChildren());
248 tile_cache.init();
249
250 // clear OSG cache, except on initial start-up
251 if (state != Start)
252 {
253 osgDB::Registry::instance()->clearObjectCache();
254 }
255
256 state = Inited;
257
258 previous_bucket.make_bad();
259 current_bucket.make_bad();
260 scheduled_visibility = 100.0;
261
262 // force an update now
263 update(0.0);
264 }
265
266 void FGTileMgr::materialLibChanged()
267 {
268 _options->setMaterialLib(globals->get_matlib());
269 }
270
271 /* schedule a tile for loading, keep request for given amount of time.
272 * Returns true if tile is already loaded. */
273 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
274 {
275 // see if tile already exists in the cache
276 STGTileEntry *t = tile_cache.get_stg_tile( b );
277 if (!t)
278 {
279 // create a new entry
280 t = new STGTileEntry( b );
281 SG_LOG( SG_TERRAIN, SG_INFO, "sched_tile: new STG tile entry for:" << b );
282
283 // insert the tile into the cache, update will generate load request
284 if ( tile_cache.insert_tile( t ) )
285 {
286 // Attach to scene graph
287
288 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
289 } else
290 {
291 // insert failed (cache full with no available entries to
292 // delete.) Try again later
293 delete t;
294 return false;
295 }
296
297 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
298 }
299
300 // update tile's properties
301 tile_cache.request_tile(t,priority,current_view,duration);
302
303 if (_use_vpb) {
304 VPBTileEntry *v = tile_cache.get_vpb_tile( b );
305
306 if (!v)
307 {
308 // create a new entry
309 v = new VPBTileEntry( b, _options );
310 SG_LOG( SG_TERRAIN, SG_INFO, "sched_tile: new VPB tile entry for:" << b );
311
312 // insert the tile into the cache, update will generate load request
313 if ( tile_cache.insert_tile( v ) )
314 {
315 // Attach to scene graph
316 v->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
317 } else {
318 // insert failed (cache full with no available entries to
319 // delete.) Try again later
320 delete v;
321 return false;
322 }
323
324 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
325 }
326
327 // update tile's properties. We ensure VPB tiles have maximum priority - priority is calculated as
328 // _negative_ the square of the distance from the viewer to the tile.
329 // so by multiplying by 0.1 we increase the number towards 0.
330 tile_cache.request_tile(v,priority * 0.1,current_view,duration);
331 }
332
333 return t->is_loaded();
334 }
335
336 /* schedule needed buckets for the current view position for loading,
337 * keep request for given amount of time */
338 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
339 {
340 // sanity check (unfortunately needed!)
341 if (!curr_bucket.isValid() )
342 {
343 SG_LOG( SG_TERRAIN, SG_ALERT,
344 "Attempting to schedule tiles for invalid bucket" );
345 return;
346 }
347
348 double tile_width = curr_bucket.get_width_m();
349 double tile_height = curr_bucket.get_height_m();
350 SG_LOG( SG_TERRAIN, SG_INFO,
351 "scheduling needed tiles for " << curr_bucket
352 << ", tile-width-m:" << tile_width << ", tile-height-m:" << tile_height);
353
354
355 // cout << "tile width = " << tile_width << " tile_height = "
356 // << tile_height << endl;
357 // starting with 2018.3 we will use deltas rather than absolutes as it is more intuitive for the user
358 // and somewhat easier to visualise
359 double maxTileRange = _lodDetailed->getDoubleValue() + _lodRoughDelta->getDoubleValue() + _lodBareDelta->getDoubleValue();
360
361 double tileRangeM = std::min(vis, maxTileRange);
362 int xrange = (int)(tileRangeM / tile_width) + 1;
363 int yrange = (int)(tileRangeM / tile_height) + 1;
364 if ( xrange < 1 ) { xrange = 1; }
365 if ( yrange < 1 ) { yrange = 1; }
366
367 // make the cache twice as large to avoid losing terrain when switching
368 // between aircraft and tower views
369 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
370 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
371 // cout << "max cache size = " << tile_cache.get_max_cache_size()
372 // << " current cache size = " << tile_cache.get_size() << endl;
373
374 // clear flags of all tiles belonging to the previous view set
375 tile_cache.clear_current_view();
376
377 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
378 osg::FrameStamp* framestamp
379 = globals->get_renderer()->getFrameStamp();
380 tile_cache.set_current_time(framestamp->getReferenceTime());
381
382 SGBucket b;
383
384 int x, y;
385 auto terraSync = globals->get_subsystem<simgear::SGTerraSync>();
386
387 /* schedule all tiles, use distance-based loading priority,
388 * so tiles are loaded in innermost-to-outermost sequence. */
389 for ( x = -xrange; x <= xrange; ++x )
390 {
391 for ( y = -yrange; y <= yrange; ++y )
392 {
393 SGBucket b = curr_bucket.sibling(x, y);
394 if (!b.isValid()) {
395 continue;
396 }
397
398 float priority = (-1.0) * (x*x+y*y);
399 sched_tile( b, priority, true, 0.0 );
400
401 if (terraSync) {
402 terraSync->scheduleTile(b);
403 }
404 }
405 }
406 }
407
408 /**
409 * Update the various queues maintained by the tilemgr (private
410 * internal function, do not call directly.)
411 */
412 void FGTileMgr::update_queues(bool& isDownloadingScenery)
413 {
414 osg::FrameStamp* framestamp = globals->get_renderer()->getFrameStamp();
415 double current_time = framestamp->getReferenceTime();
416 double vis = _visibilityMeters->getDoubleValue();
417 TileEntry *e;
418 int loading=0;
419 int sz=0;
420
421 tile_cache.set_current_time( current_time );
422 tile_cache.reset_traversal();
423
424 while ( ! tile_cache.at_end() )
425 {
426 e = tile_cache.get_current();
427 if ( e )
428 {
429 // Prepare the ssg nodes corresponding to each tile.
430 // Set the ssg transform and update it's range selector
431 // based on current visibility
432 e->prep_ssg_node(vis);
433
434 if (!e->is_loaded()) {
435 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
436 bool downloading = isTileDirSyncing(e->tileFileName);
437 isDownloadingScenery |= downloading;
438 if ( !downloading && nonExpiredOrCurrent) {
439 // schedule tile for loading with osg pager
440 _pager->queueRequest(e->tileFileName,
441 e->getNode(),
442 e->get_priority(),
443 framestamp,
444 e->getDatabaseRequest(),
445 _options.get());
446 loading++;
447 }
448 } // of tile not loaded case
449 } else {
450 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
451 }
452 tile_cache.next();
453 sz++;
454 }
455
456 int drop_count = sz - tile_cache.get_max_cache_size();
457 bool dropTiles = false;
458 if (_enableCache) {
459 dropTiles = ( drop_count > 0 ) && ((loading==0)||(drop_count > 10));
460 } else {
461 dropTiles = true;
462 drop_count = sz; // no limit on tiles to drop
463 }
464
465 if (dropTiles)
466 {
467 long drop_index = _enableCache ? tile_cache.get_drop_tile() :
468 tile_cache.get_first_expired_tile();
469 while ( drop_index > -1 )
470 {
471 // schedule tile for deletion with osg pager
472 TileEntry* old = tile_cache.get_tile(drop_index);
473 SG_LOG(SG_TERRAIN, SG_DEBUG, "Dropping:" << old->get_tile_bucket());
474
475 tile_cache.clear_entry(drop_index);
476
477 if (_use_vpb) {
478 // Clear out any VPB data - e.g. roads
479 simgear::VPBLineFeatureRenderer::unloadFeatures(old->get_tile_bucket());
480 }
481
482 osg::ref_ptr<osg::Object> subgraph = old->getNode();
483 old->removeFromSceneGraph();
484 delete old;
485 // zeros out subgraph ref_ptr, so subgraph is owned by
486 // the pager and will be deleted in the pager thread.
487 _pager->queueDeleteRequest(subgraph);
488
489 if (!_enableCache)
490 drop_index = tile_cache.get_first_expired_tile();
491 // limit tiles dropped to drop_count
492 else if (--drop_count > 0)
493 drop_index = tile_cache.get_drop_tile();
494 else
495 drop_index = -1;
496 }
497 } // of dropping tiles loop
498 }
499
500 // given the current lon/lat (in degrees), fill in the array of local
501 // chunks. If the chunk isn't already in the cache, then read it from
502 // disk.
503 void FGTileMgr::update(double)
504 {
505 double vis = _visibilityMeters->getDoubleValue();
506 schedule_tiles_at(globals->get_view_position(), vis);
507
508 bool waitingOnTerrasync = false;
509 update_queues(waitingOnTerrasync);
510
511 if (_pager) {
512 // Update various useful statistics
513 _pager_file_queue_size->setIntValue(_pager->getFileRequestListSize());
514 _pager_compile_queue_size->setIntValue(_pager->getDataToCompileListSize());
515 _pager_merge_queue_size->setIntValue(_pager->getDataToMergeListSize());
516 _pager_min_merge_time->setFloatValue(_pager->getMinimumTimeToMergeTile());
517 _pager_mean_merge_time->setFloatValue(_pager->getAverageTimeToMergeTiles());
518 _pager_max_merge_time->setFloatValue(_pager->getMaximumTimeToMergeTile());
519 }
520
521 // scenery loading check, triggers after each sim (tile manager) reinit
522 if (!_scenery_loaded->getBoolValue())
523 {
524 bool fdmInited = fgGetBool("sim/fdm-initialized");
525 bool positionFinalized = fgGetBool("sim/position-finalized");
526 bool sceneryOverride = _scenery_override->getBoolValue();
527
528
529 // we are done if final position is set and the scenery & FDM are done.
530 // scenery-override can ignore the last two, but not position finalization.
531 if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
532 {
533 _scenery_loaded->setBoolValue(true);
534 fgSplashProgress("");
535
536 // by this time Models/ should be in-sync, so run the check now.
537 // we could do this in a listener on the property, but we already have
538 // 'special' knowledge of Models/ in isTileDirSyncing so this feels
539 // reasonable.
540 flightgear::validateSharedModels();
541 }
542 else
543 {
544 if (!positionFinalized) {
545 fgSplashProgress("finalize-position");
546 } else if (waitingOnTerrasync) {
547 fgSplashProgress("downloading-scenery");
548 } else {
549 fgSplashProgress("loading-scenery");
550 }
551
552 // be nice to loader threads while waiting for initial scenery, reduce to 20fps
553 SGTimeStamp::sleepForMSec(50);
554 }
555 }
556 }
557
558 // schedule tiles for the viewer bucket
559 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
560 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
561 {
562 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
563 // << longitude << " " << latitude );
564
565 current_bucket = SGBucket( location );
566
567 // schedule more tiles when visibility increased considerably
568 // TODO Calculate tile size - instead of using fixed value (5000m)
569 if (range_m - scheduled_visibility > 5000.0)
570 previous_bucket.make_bad();
571
572 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
573 // << current_bucket );
574 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
575
576 // do tile load scheduling.
577 // Note that we need keep track of both viewer buckets and fdm buckets.
578 if ( state == Running ) {
579 if (last_state != state)
580 {
581 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
582 }
583 if (current_bucket != previous_bucket) {
584 // We've moved to a new bucket, we need to schedule any
585 // needed tiles for loading.
586 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr: at " << location << ", scheduling needed for:" << current_bucket
587 << ", visibility=" << range_m);
588 scheduled_visibility = range_m;
589 schedule_needed(current_bucket, range_m);
590 }
591
592 // save bucket
593 previous_bucket = current_bucket;
594 } else if ( state == Start || state == Inited ) {
595 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
596 // do not update bucket yet (position not valid in initial loop)
597 state = Running;
598 previous_bucket.make_bad();
599 }
600 last_state = state;
601 }
602
603 /** Schedules scenery for given position. Load request remains valid for given duration
604 * (duration=0.0 => nothing is loaded).
605 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
606 * Returns true when all tiles for the given position are already loaded, false otherwise.
607 */
608 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
609 {
610 // sanity check (unfortunately needed!)
611 if (!position.isValid())
612 return false;
613 const float priority = 0.0;
614 bool available = true;
615
616 SGBucket bucket(position);
617 available = sched_tile( bucket, priority, false, duration );
618
619 if ((!available)&&(duration==0.0)) {
620 SG_LOG( SG_TERRAIN, SG_DEBUG, "schedule_scenery: Scheduling tile at bucket:" << bucket << " return false" );
621 return false;
622 }
623
624 SGVec3d cartPos = SGVec3d::fromGeod(position);
625
626 // Traverse all tiles required to be there for the given visibility.
627 double tile_width = bucket.get_width_m();
628 double tile_height = bucket.get_height_m();
629 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
630 double max_dist = tile_r + range_m;
631 double max_dist2 = max_dist*max_dist;
632
633 int xrange = (int)fabs(range_m / tile_width) + 1;
634 int yrange = (int)fabs(range_m / tile_height) + 1;
635
636 for ( int x = -xrange; x <= xrange; ++x )
637 {
638 for ( int y = -yrange; y <= yrange; ++y )
639 {
640 // We have already checked for the center tile.
641 if ( x != 0 || y != 0 )
642 {
643 SGBucket b = bucket.sibling(x, y );
644 if (!b.isValid()) {
645 continue;
646 }
647
648 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
649 // Do not ask if it is just the next tile but way out of range.
650 if (distance2 <= max_dist2)
651 {
652 available &= sched_tile( b, priority, false, duration );
653 if ((!available)&&(duration==0.0))
654 return false;
655 }
656 }
657 }
658 }
659
660 return available;
661 }
662
663 // Returns true if tiles around current view position have been loaded
664 bool FGTileMgr::isSceneryLoaded()
665 {
666 double range_m = 100.0;
667 if (scheduled_visibility < range_m)
668 range_m = scheduled_visibility;
669
670 return schedule_scenery(globals->get_view_position(), range_m, 0.0);
671 }
672
673 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
674 {
675 auto terraSync = globals->get_subsystem<simgear::SGTerraSync>();
676 if (!terraSync) {
677 return false;
678 }
679
680 // if Models is syncing, also wait for it, since otherwise
681 // we get load errors
682 if (terraSync->isDataDirPending("Models")) {
683 return true;
684 }
685
686 std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
687 long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
688 SGBucket bucket(bucketIndex);
689
690 return terraSync->isTileDirPending(bucket.gen_base_path());
691 }