1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use super::*;
impl MapState {
/// Run just the terrain update (used by tests and manual pipelines).
pub fn update_terrain(&mut self) {
if self.terrain.enabled() {
let cam_world = self.mercator_camera_world();
let meshes = self.terrain.update(
&self.viewport_bounds,
self.zoom_level,
cam_world,
self.camera.projection(),
self.camera.distance(),
self.camera.pitch(),
);
self.terrain_meshes = Arc::new(meshes);
self.hillshade_rasters = Arc::new(self.terrain.visible_hillshade_rasters().to_vec());
// Report terrain DEM demand to the coordinator.
self.request_coordinator
.report_demand(SourcePriority::Terrain, self.terrain.pending_count());
}
}
/// Determine the terrain tile set for the current frame.
///
/// In steep-pitch terrain views, terrain should cover both the tile layer's
/// selected raster targets and the stricter uncapped terrain footprint so
/// mesh coverage does not clip at the frustum edge.
///
/// When the camera is highly pitched the visible ground stretches far
/// toward the horizon. To avoid abrupt clipping where terrain tiles
/// end, we supplement the base-zoom tiles with progressively coarser
/// "horizon fill" tiles at lower zooms.
pub(super) fn desired_terrain_tiles(&self) -> Option<Vec<rustial_math::TileId>> {
let use_covering = self.terrain.enabled()
&& self.camera.pitch() > 0.3
&& self.camera.mode() == crate::camera::CameraMode::Perspective;
if !use_covering || self.visible_tiles.is_empty() {
return None;
}
// Build a set of all raster tile actuals (with loaded data) so we
// can verify that every candidate terrain tile has an ancestor
// with a raster texture available. This prevents spawning terrain
// meshes that would render with the white placeholder because the
// covering algorithm did not select a raster tile for that area
// (e.g. tiles in the viewport-overscan zone beyond the frustum).
let raster_actuals: HashSet<TileId> = self
.visible_tiles
.iter()
.filter(|vt| vt.data.is_some())
.map(|vt| vt.actual)
.collect();
let has_raster_ancestor = |tile: &TileId| -> bool {
// Exact match among raster targets.
if raster_actuals.contains(tile) {
return true;
}
// Walk up the parent chain looking for a loaded ancestor.
let mut current = *tile;
for _ in 0..8u8 {
let Some(parent) = current.parent() else {
break;
};
if raster_actuals.contains(&parent) {
return true;
}
current = parent;
}
false
};
let mut terrain_tiles: Vec<rustial_math::TileId> =
self.visible_tiles.iter().map(|tile| tile.target).collect();
let strict_tiles = if let Some(view) = self.camera.flat_tile_view() {
visible_tiles_flat_view_with_config(
&self.viewport_bounds,
self.zoom_level,
&view,
&FlatTileSelectionConfig {
footprint_pitch_threshold_rad: 0.0,
footprint_min_tiles: 0,
..FlatTileSelectionConfig::default()
},
)
} else {
visible_tiles(&self.viewport_bounds, self.zoom_level)
};
let mut seen = HashSet::with_capacity(terrain_tiles.len() + strict_tiles.len());
terrain_tiles.retain(|tile| seen.insert(*tile));
for tile in strict_tiles {
if seen.insert(tile) && has_raster_ancestor(&tile) {
terrain_tiles.push(tile);
}
}
// Near-field guarantee: at steep pitch the footprint polygon can
// clip tiles at the bottom viewport corners. Ensure tiles around
// the camera eye's ground projection are always included so the
// near-field terrain is never missing.
if self.camera.pitch() > 0.4 {
let target_world = self.camera.target_world();
let eye = target_world + self.camera.eye_offset();
let eye_ground = WorldCoord::new(eye.x, eye.y, 0.0);
// Radius proportional to the camera altitude, covering at
// least a few tiles in every direction below the eye.
let altitude = (eye.z - target_world.z).abs().max(1.0);
let half = altitude * 1.5;
let near_bounds = WorldBounds::new(
WorldCoord::new(
eye_ground.position.x - half,
eye_ground.position.y - half,
0.0,
),
WorldCoord::new(
eye_ground.position.x + half,
eye_ground.position.y + half,
0.0,
),
);
for tile in visible_tiles(&near_bounds, self.zoom_level) {
if seen.insert(tile) && has_raster_ancestor(&tile) {
terrain_tiles.push(tile);
}
}
}
let cam = self.mercator_camera_world();
// Cap base-zoom terrain tiles, keeping closest first. The cap
// must not fall below the strict footprint or steep views will
// visibly clip terrain against the lower raster layer.
let max_base_tiles = terrain_base_tile_budget(terrain_tiles.len());
if terrain_tiles.len() > max_base_tiles {
terrain_tiles.sort_by(|a, b| {
let da = tile_center_dist_sq(a, cam);
let db = tile_center_dist_sq(b, cam);
da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
});
terrain_tiles.truncate(max_base_tiles);
}
// Horizon fill: at steep pitch, add coarser tiles to cover the
// distant ground that base-zoom tiles don't reach. Each step
// reduces zoom by 2, so a single tile covers 4× the area.
// Only non-overlapping tiles are added (tiles that are NOT
// ancestors of any existing tile).
if self.camera.pitch() > 0.5 && self.zoom_level > 2 {
let base_tiles: Vec<TileId> = terrain_tiles.clone();
let is_ancestor_of_existing = |candidate: &TileId| -> bool {
base_tiles.iter().any(|t| {
if t.zoom <= candidate.zoom {
return false;
}
let dz = t.zoom - candidate.zoom;
(t.x >> dz) == candidate.x && (t.y >> dz) == candidate.y
})
};
let mut horizon_budget =
terrain_horizon_tile_budget(max_base_tiles, self.camera.pitch());
let mut hz = self.zoom_level.saturating_sub(2);
while hz > 0 && horizon_budget > 0 {
let coarse = visible_tiles(&self.viewport_bounds, hz);
let mut coarse_sorted: Vec<_> = coarse
.into_iter()
.filter(|t| {
!seen.contains(t) && !is_ancestor_of_existing(t) && has_raster_ancestor(t)
})
.map(|t| {
let d = tile_center_dist_sq(&t, cam);
(t, d)
})
.collect();
// Farthest first — fill the horizon end.
coarse_sorted
.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
let take = coarse_sorted.len().min(horizon_budget);
for (t, _) in coarse_sorted.into_iter().take(take) {
if seen.insert(t) {
terrain_tiles.push(t);
horizon_budget -= 1;
}
}
hz = hz.saturating_sub(2);
}
}
Some(terrain_tiles)
}
/// Run the terrain update using a pre-computed tile set from the tile
/// layer's covering-tiles selection. This ensures the terrain manager
/// generates meshes for exactly the same tiles that have raster textures
/// available, preventing untextured grey patches.
pub(super) fn update_terrain_with_tiles(&mut self, tiles: &[rustial_math::TileId]) {
if self.terrain.enabled() {
let meshes =
self.terrain
.update_with_tiles(tiles, self.zoom_level, self.camera.projection());
self.terrain_meshes = Arc::new(meshes);
self.hillshade_rasters = Arc::new(self.terrain.visible_hillshade_rasters().to_vec());
// Report terrain DEM demand to the coordinator.
self.request_coordinator
.report_demand(SourcePriority::Terrain, self.terrain.pending_count());
}
}
/// Lightweight per-frame tile layer update: poll completed HTTP
/// responses, recompute the visible tile set for the current camera
/// position, and issue new tile requests.
///
/// This is separated from the heavier terrain/vector/symbol/model
/// processing so it can run unconditionally every frame, even during
/// animation when the heavy layers are throttled.
pub(super) fn update_tile_layers(&mut self) {
use crate::layer::LayerKind;
use crate::layers::TileLayer;
// Begin a new coordinator frame so per-source budgets are
// allocated from the global cap before any source updates.
self.request_coordinator.begin_frame();
let zoom_level = self.zoom_level;
let camera_world = self.mercator_camera_world();
let flat_view = self.camera.flat_tile_view();
let camera_distance = self.camera.distance();
let viewport_bounds = self.viewport_bounds;
let predicted_viewport_bounds = *self.predicted_viewport_bounds();
let predicted_target_world = self.camera_motion_state.predicted_target_world;
let should_speculatively_prefetch =
self.camera_motion_state.pan_velocity_world.length_squared() > 1e-9;
let zoom_prefetch_direction = zoom_prefetch_direction(self.camera_zoom_delta);
let prefetch_route = self.prefetch_route.clone();
let use_covering = self.terrain.enabled()
&& self.camera.pitch() > 0.3
&& self.camera.mode() == crate::camera::CameraMode::Perspective;
let covering_params = if use_covering {
let fzoom = self.fractional_zoom();
self.camera.covering_camera(fzoom).map(|cam| {
let opts = rustial_math::CoveringTilesOptions {
min_zoom: 0,
max_zoom: rustial_math::MAX_ZOOM,
round_zoom: false,
tile_size: 256,
max_tiles: 512,
allow_variable_zoom: true,
render_world_copies: true,
};
(cam, opts)
})
} else {
None
};
// -- Raster tile layers -------------------------------------------
// Apply the coordinator's raster budget to each tile layer.
let raster_budget = self.request_coordinator.budget_for(SourcePriority::Raster);
for layer in self.layers.iter_mut() {
if !layer.visible() {
continue;
}
if layer.kind() == LayerKind::Tile {
if let Some(tile_layer) = layer.as_any_mut().downcast_mut::<TileLayer>() {
// Temporarily apply the coordinator's per-frame budget.
let mut sel = tile_layer.selection_config().clone();
sel.max_requests_per_frame = raster_budget;
tile_layer.set_selection_config(sel);
if let (Some(frustum), Some((ref cam, ref opts))) =
(self.frustum.as_ref(), covering_params.as_ref())
{
tile_layer.update_with_covering(frustum, cam, opts, camera_world);
} else {
tile_layer.update_with_view(
&viewport_bounds,
zoom_level,
camera_world,
camera_distance,
flat_view.as_ref(),
);
}
// Report raster results to the coordinator.
let stats = tile_layer.last_selection_stats();
let desired: HashSet<TileId> = tile_layer
.visible_tiles()
.tiles
.iter()
.map(|t| t.target)
.collect();
let mut total_raster_requested = stats.requested_tiles;
let raster_pending_demand =
stats.fallback_visible_tiles + stats.missing_visible_tiles;
let mut remaining_speculative_budget =
speculative_prefetch_budget(raster_budget, stats.requested_tiles);
// 1. Viewport-prediction prefetch (pan momentum).
if remaining_speculative_budget > 0 && should_speculatively_prefetch {
let prefetched = tile_layer.prefetch_with_view(
&predicted_viewport_bounds,
zoom_level,
(predicted_target_world.x, predicted_target_world.y),
None,
remaining_speculative_budget,
);
total_raster_requested += prefetched;
remaining_speculative_budget =
remaining_speculative_budget.saturating_sub(prefetched);
}
// 2. Zoom-direction prefetch.
if remaining_speculative_budget > 0 {
if let Some(direction) = zoom_prefetch_direction {
let prefetched = tile_layer.prefetch_zoom_direction(
camera_world,
direction,
remaining_speculative_budget,
);
total_raster_requested += prefetched;
remaining_speculative_budget =
remaining_speculative_budget.saturating_sub(prefetched);
}
}
// 3. Route-aware prefetch.
if remaining_speculative_budget > 0 {
if let Some(ref route) = prefetch_route {
let prefetched = tile_layer.prefetch_route(
route,
zoom_level,
camera_world,
remaining_speculative_budget,
);
total_raster_requested += prefetched;
}
}
self.request_coordinator.report(
SourcePriority::Raster,
desired,
total_raster_requested,
raster_pending_demand,
);
self.visible_tiles = Arc::new(tile_layer.visible_tiles().tiles.clone());
}
}
}
// -- Streamed vector source layers --------------------------------
self.update_streamed_vector_source_layers(
zoom_level,
camera_world,
camera_distance,
&viewport_bounds,
flat_view.as_ref(),
covering_params.as_ref(),
);
// Finish the coordinator frame and compute cross-source stats.
self.request_coordinator.finish_frame();
}
pub(super) fn update_streamed_vector_source_layers(
&mut self,
zoom_level: u8,
camera_world: (f64, f64),
camera_distance: f64,
viewport_bounds: &WorldBounds,
flat_view: Option<&rustial_math::FlatTileView>,
covering_params: Option<&(
rustial_math::CoveringCamera,
rustial_math::CoveringTilesOptions,
)>,
) {
// Apply the coordinator's vector budget to each streamed source.
// The budget is shared across all vector sources (split evenly).
let vector_budget = self.request_coordinator.budget_for(SourcePriority::Vector);
let source_count = self.streamed_vector_sources.len().max(1);
let per_source_budget = if vector_budget == usize::MAX {
usize::MAX
} else {
// Give each vector source a fair share of the vector budget.
(vector_budget / source_count).max(1)
};
let mut total_vector_requested = 0usize;
let mut all_vector_desired = HashSet::new();
let predicted_viewport_bounds = *self.predicted_viewport_bounds();
let predicted_target_world = self.camera_motion_state.predicted_target_world;
let should_speculatively_prefetch =
self.camera_motion_state.pan_velocity_world.length_squared() > 1e-9;
let zoom_prefetch_direction = zoom_prefetch_direction(self.camera_zoom_delta);
let prefetch_route = self.prefetch_route.clone();
for source_layer in self.streamed_vector_sources.values_mut() {
// Temporarily apply the coordinator's per-source budget.
let mut sel = source_layer.selection_config().clone();
sel.max_requests_per_frame = per_source_budget;
source_layer.set_selection_config(sel);
if let (Some(frustum), Some((cam, opts))) = (self.frustum.as_ref(), covering_params) {
source_layer.update_with_covering(frustum, cam, opts, camera_world);
} else {
source_layer.update_with_view(
viewport_bounds,
zoom_level,
camera_world,
camera_distance,
flat_view,
);
}
// Accumulate vector stats for the coordinator.
let stats = source_layer.last_selection_stats();
total_vector_requested += stats.requested_tiles;
for tile in source_layer.visible_tiles().tiles.iter() {
all_vector_desired.insert(tile.target);
}
let mut remaining_speculative_budget =
speculative_prefetch_budget(per_source_budget, stats.requested_tiles);
// 1. Viewport-prediction prefetch (pan momentum).
if remaining_speculative_budget > 0 && should_speculatively_prefetch {
let prefetched = source_layer.prefetch_with_view(
&predicted_viewport_bounds,
zoom_level,
(predicted_target_world.x, predicted_target_world.y),
None,
remaining_speculative_budget,
);
total_vector_requested += prefetched;
remaining_speculative_budget =
remaining_speculative_budget.saturating_sub(prefetched);
}
// 2. Zoom-direction prefetch.
if remaining_speculative_budget > 0 {
if let Some(direction) = zoom_prefetch_direction {
let prefetched = source_layer.prefetch_zoom_direction(
camera_world,
direction,
remaining_speculative_budget,
);
total_vector_requested += prefetched;
remaining_speculative_budget =
remaining_speculative_budget.saturating_sub(prefetched);
}
}
// 3. Route-aware prefetch.
if remaining_speculative_budget > 0 {
if let Some(ref route) = prefetch_route {
let prefetched = source_layer.prefetch_route(
route,
zoom_level,
camera_world,
remaining_speculative_budget,
);
total_vector_requested += prefetched;
}
}
}
// Report aggregate vector results.
self.request_coordinator.report(
SourcePriority::Vector,
all_vector_desired,
total_vector_requested,
total_vector_requested,
);
}
}
/// Squared distance from the centre of a tile to a camera world position.
fn tile_center_dist_sq(tile: &rustial_math::TileId, cam: (f64, f64)) -> f64 {
let b = rustial_math::tile_bounds_world(tile);
let cx = (b.min.position.x + b.max.position.x) * 0.5;
let cy = (b.min.position.y + b.max.position.y) * 0.5;
let dx = cx - cam.0;
let dy = cy - cam.1;
dx * dx + dy * dy
}
fn speculative_prefetch_budget(total_budget: usize, visible_requests: usize) -> usize {
if total_budget == 0 {
return 0;
}
if total_budget == usize::MAX {
return DEFAULT_SPECULATIVE_PREFETCH_REQUEST_BUDGET;
}
let remaining = total_budget.saturating_sub(visible_requests);
if remaining == 0 {
return 0;
}
let speculative_cap =
((total_budget as f64) * SPECULATIVE_PREFETCH_BUDGET_FRACTION).ceil() as usize;
remaining.min(speculative_cap.max(1))
}
fn zoom_prefetch_direction(zoom_delta: f64) -> Option<ZoomPrefetchDirection> {
if zoom_delta > ZOOM_DIRECTION_PREFETCH_THRESHOLD {
Some(ZoomPrefetchDirection::In)
} else if zoom_delta < -ZOOM_DIRECTION_PREFETCH_THRESHOLD {
Some(ZoomPrefetchDirection::Out)
} else {
None
}
}