1use std::sync::Arc;
6
7use geometry::Point;
8use glam::{DVec2, Vec2};
9use mln_style::feature::GeometryCoordinates;
10use mln_style::hash::{HashMap, HashSet};
11use smallvec::SmallVec;
12
13use super::grid::{Aabb, Grid, Shape};
14use crate::camera::View;
15use crate::geo::ScreenLineString;
16use crate::geo::intersection_tests::polygon_intersects_polygon;
17use crate::map::MapMode;
18use crate::query::feature_index::{FeatureIndex, FeatureSortOrder, IndexedSubfeature};
19use crate::tile::OverscaledTileID;
20use crate::worker::job::SourceKey;
21
22const VIEWPORT_PADDING_DEFAULT: f32 = 100.0;
27const VIEWPORT_PADDING_FOR_STATIC_TILES: f32 = 1024.0;
30const CELL_SIZE: f32 = 25.0;
32
33fn find_viewport_padding(view: &View, map_mode: MapMode) -> f32 {
34 if map_mode == MapMode::Tile {
35 return VIEWPORT_PADDING_FOR_STATIC_TILES;
36 }
37 if view.pitch() == 0.0 { VIEWPORT_PADDING_DEFAULT } else { VIEWPORT_PADDING_DEFAULT * 2.0 }
38}
39
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum Overlap {
43 #[default]
45 Never,
46 Always,
48 Cooperative,
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
56pub struct CollisionGroup(Option<u16>);
57
58impl CollisionGroup {
59 pub const ALL: CollisionGroup = CollisionGroup(None);
61
62 fn id(self) -> u16 {
64 self.0.unwrap_or(0)
65 }
66
67 fn has(self, feature: &IndexedSubfeature) -> bool {
69 self.0.is_none_or(|group| feature.collision_group_id == group)
70 }
71}
72
73pub(crate) struct CollisionGroups<'a> {
75 ids: SmallVec<[&'a str; 4]>,
76 cross_source_collisions: bool,
77}
78
79impl<'a> CollisionGroups<'a> {
80 pub(crate) fn new(cross_source_collisions: bool) -> Self {
81 CollisionGroups { ids: SmallVec::new(), cross_source_collisions }
82 }
83
84 pub(crate) fn get(&mut self, source: &'a str) -> CollisionGroup {
86 if self.cross_source_collisions {
87 return CollisionGroup(None);
88 }
89 let index = self.ids.iter().position(|id| *id == source).unwrap_or_else(|| {
90 self.ids.push(source);
91 self.ids.len() - 1
92 });
93 CollisionGroup(Some(index as u16 + 1))
94 }
95}
96
97#[derive(Clone, Copy)]
99pub struct Item<'a> {
100 pub feature: &'a IndexedSubfeature,
102 pub record: u32,
105 pub overlap: Overlap,
108 pub ignore_placement: bool,
111}
112
113#[derive(Debug)]
115pub struct RetainedQueryData {
116 pub bucket_instance_id: u32,
117 pub feature_index: Option<Arc<FeatureIndex>>,
118 pub tile_id: OverscaledTileID,
119 pub source: SourceKey,
121 pub feature_sort_order: FeatureSortOrder,
124}
125
126pub struct CollisionIndex {
132 view: View,
133 size: DVec2,
135
136 viewport_padding: f32,
137 collision_grid: Grid<IndexedSubfeature>,
138 ignored_grid: Grid<IndexedSubfeature>,
139
140 screen_right_boundary: f32,
141 screen_bottom_boundary: f32,
142 grid_right_boundary: f32,
143 grid_bottom_boundary: f32,
144
145 retained_query_data: HashMap<u32, RetainedQueryData>,
146}
147
148impl CollisionIndex {
149 #[must_use]
151 pub fn new(view: &View, map_mode: MapMode) -> Self {
152 CollisionIndex::reusing(view, map_mode, None)
153 }
154
155 pub(crate) fn reusing(view: &View, map_mode: MapMode, previous: Option<CollisionIndex>) -> Self {
160 let viewport_padding = find_viewport_padding(view, map_mode);
161 let size = view.size();
162 let width = size.width as f32;
164 let height = size.height as f32;
165 let grid_width = width + 2.0 * viewport_padding;
166 let grid_height = height + 2.0 * viewport_padding;
167 let grid_size = Vec2::new(grid_width, grid_height);
168 let reset = |mut grid: Grid<IndexedSubfeature>| {
169 grid.reset(grid_size, CELL_SIZE);
170 grid
171 };
172 let (collision_grid, ignored_grid) = match previous {
173 Some(previous) => (reset(previous.collision_grid), reset(previous.ignored_grid)),
174 None => (Grid::new(grid_size, CELL_SIZE), Grid::new(grid_size, CELL_SIZE)),
175 };
176 CollisionIndex {
177 view: view.clone(),
178 size: DVec2::new(f64::from(size.width), f64::from(size.height)),
179 viewport_padding,
180 collision_grid,
181 ignored_grid,
182 screen_right_boundary: width + viewport_padding,
183 screen_bottom_boundary: height + viewport_padding,
184 grid_right_boundary: grid_width,
185 grid_bottom_boundary: grid_height,
186 retained_query_data: HashMap::default(),
187 }
188 }
189
190 #[must_use]
192 pub fn view(&self) -> &View {
193 &self.view
194 }
195
196 #[must_use]
199 pub fn viewport_padding(&self) -> f32 {
200 self.viewport_padding
201 }
202
203 #[inline]
206 #[must_use]
207 pub fn to_grid(&self, x: f64, y: f64) -> Vec2 {
208 let viewport_padding = f64::from(self.viewport_padding);
209 Vec2::new(
210 (f64::midpoint(x, 1.0) * self.size.x + viewport_padding) as f32,
211 (f64::midpoint(-y, 1.0) * self.size.y + viewport_padding) as f32,
212 )
213 }
214
215 #[inline]
218 #[must_use]
219 pub fn is_offscreen(&self, bounds: &Aabb) -> bool {
220 bounds.max.x < self.viewport_padding
221 || bounds.min.x >= self.screen_right_boundary
222 || bounds.max.y < self.viewport_padding
223 || bounds.min.y >= self.screen_bottom_boundary
224 }
225
226 #[inline]
229 #[must_use]
230 pub fn is_inside_grid(&self, bounds: &Aabb) -> bool {
231 bounds.max.x >= 0.0
232 && bounds.min.x < self.grid_right_boundary
233 && bounds.max.y >= 0.0
234 && bounds.min.y < self.grid_bottom_boundary
235 }
236
237 #[inline]
240 #[must_use]
241 pub fn collides(&self, shape: &Shape, overlap: Overlap, group: CollisionGroup) -> bool {
242 match overlap {
243 Overlap::Never => self.collision_grid.any(shape, |feature| group.has(feature)),
244 Overlap::Always => false,
245 Overlap::Cooperative => {
246 self.collision_grid.any(shape, |feature| feature.overlap_mode == Overlap::Never && group.has(feature))
247 }
248 }
249 }
250
251 #[inline]
253 pub fn insert(&mut self, shapes: &[Option<Shape>], item: &Item<'_>, group: CollisionGroup) {
254 let grid = if item.ignore_placement { &mut self.ignored_grid } else { &mut self.collision_grid };
255 for shape in shapes.iter().flatten() {
256 let feature = IndexedSubfeature {
257 bucket_instance_id: item.record,
258 collision_group_id: group.id(),
259 overlap_mode: item.overlap,
260 ..item.feature.clone()
261 };
262 grid.insert(feature, *shape);
263 }
264 }
265
266 pub fn retain(&mut self, record: u32, data: impl FnOnce() -> RetainedQueryData) {
269 self.retained_query_data.entry(record).or_insert_with(data);
270 }
271
272 pub fn set_query_order(&mut self, record: u32, order: &FeatureSortOrder) {
275 if let Some(retained) = self.retained_query_data.get_mut(&record) {
276 retained.feature_sort_order.clone_from(order);
277 }
278 }
279
280 pub(crate) fn query_data(&self, record: u32) -> Result<&RetainedQueryData, String> {
282 self.retained_query_data.get(&record).ok_or_else(|| format!("no query data of the bucket instance {record}"))
283 }
284
285 pub(crate) fn query_rendered(&self, query_geometry: &ScreenLineString) -> HashMap<u32, Vec<IndexedSubfeature>> {
288 let mut result: HashMap<u32, Vec<IndexedSubfeature>> = HashMap::default();
289 if query_geometry.is_empty() || (self.collision_grid.is_empty() && self.ignored_grid.is_empty()) {
290 return result;
291 }
292
293 let mut grid_query: Vec<Point<f32>> = Vec::with_capacity(query_geometry.len());
294 for point in query_geometry {
295 grid_query.push(Point::new(point.x as f32 + self.viewport_padding, point.y as f32 + self.viewport_padding));
296 }
297
298 let mut envelope = Aabb::new(Vec2::INFINITY, Vec2::NEG_INFINITY);
300 for point in &grid_query {
301 let point = Vec2::new(point.x, point.y);
302 envelope.min = envelope.min.min(point);
303 envelope.max = envelope.max.max(point);
304 }
305 let envelope = Shape::Box(envelope);
306
307 let features = self.collision_grid.query(&envelope).chain(self.ignored_grid.query(&envelope));
308 let mut seen_buckets: HashMap<u32, HashSet<usize>> = HashMap::default();
309 for (feature, shape) in features {
310 let seen_features = seen_buckets.entry(feature.bucket_instance_id).or_default();
312 if seen_features.contains(&feature.index) {
313 continue;
314 }
315
316 if !polygon_intersects_box(&grid_query, &shape.bounds()) {
317 continue;
318 }
319
320 seen_features.insert(feature.index);
321 result.entry(feature.bucket_instance_id).or_default().push(feature.clone());
322 }
323
324 result
325 }
326}
327
328fn polygon_intersects_box(polygon: &[Point<f32>], bbox: &Aabb) -> bool {
329 let mut integer_polygon = GeometryCoordinates::new();
332 for point in polygon {
333 integer_polygon.push(Point::new(point.x as i16, point.y as i16));
334 }
335 let min_x1 = bbox.min.x as i16;
336 let max_y1 = bbox.max.y as i16;
337 let min_y1 = bbox.min.y as i16;
338 let max_x1 = bbox.max.x as i16;
339
340 let bbox_points: GeometryCoordinates = vec![
341 Point::new(min_x1, min_y1),
342 Point::new(max_x1, min_y1),
343 Point::new(max_x1, max_y1),
344 Point::new(min_x1, max_y1),
345 ];
346
347 polygon_intersects_polygon(&integer_polygon, &bbox_points)
348}
349
350#[cfg(test)]
351mod tests {
352 use mln_style::size::Size;
353
354 use super::*;
355
356 fn feature() -> IndexedSubfeature {
357 IndexedSubfeature {
358 index: 0,
359 source_layer_name: Arc::from(""),
360 bucket_leader_id: Arc::from(""),
361 sort_index: 0,
362 bucket_instance_id: 0,
363 collision_group_id: 0,
364 overlap_mode: Overlap::Never,
365 }
366 }
367
368 fn collision_index() -> CollisionIndex {
369 let mut state = crate::camera::TransformState::default();
370 state.set_size(Size::new(512, 512));
371 CollisionIndex::new(state.view(), MapMode::Static)
372 }
373
374 fn insert(index: &mut CollisionIndex, overlap: Overlap, group: CollisionGroup) {
375 let projected = [Some(Shape::Box(Aabb::new(Vec2::splat(100.0), Vec2::splat(200.0))))];
376 let feature = feature();
377 let item = Item { feature: &feature, record: 1, overlap, ignore_placement: false };
378 index.insert(&projected, &item, group);
379 }
380
381 fn collides(index: &CollisionIndex, overlap: Overlap, group: CollisionGroup) -> bool {
382 let projected = Shape::Box(Aabb::new(Vec2::splat(150.0), Vec2::splat(250.0)));
383 index.collides(&projected, overlap, group)
384 }
385
386 const ALL: CollisionGroup = CollisionGroup::ALL;
387
388 #[test]
389 fn modes_collide_with_a_never_box() {
390 let mut index = collision_index();
391 insert(&mut index, Overlap::Never, ALL);
392 assert!(collides(&index, Overlap::Never, ALL));
393 assert!(!collides(&index, Overlap::Always, ALL));
394 assert!(collides(&index, Overlap::Cooperative, ALL));
395 }
396
397 #[test]
398 fn only_never_collides_with_an_overlapping_box() {
399 for placed in [Overlap::Always, Overlap::Cooperative] {
400 let mut index = collision_index();
401 insert(&mut index, placed, ALL);
402 assert!(collides(&index, Overlap::Never, ALL), "never over {placed:?}");
403 assert!(!collides(&index, Overlap::Always, ALL), "always over {placed:?}");
404 assert!(!collides(&index, Overlap::Cooperative, ALL), "cooperative over {placed:?}");
405 }
406 }
407
408 #[test]
409 fn cooperative_keeps_the_collision_group() {
410 let mut index = collision_index();
411 insert(&mut index, Overlap::Never, CollisionGroup(Some(2)));
412 assert!(collides(&index, Overlap::Cooperative, CollisionGroup(Some(2))));
413 assert!(!collides(&index, Overlap::Cooperative, CollisionGroup(Some(3))));
414 assert!(collides(&index, Overlap::Never, CollisionGroup(Some(2))));
415 assert!(!collides(&index, Overlap::Never, CollisionGroup(Some(3))));
416 }
417
418 #[test]
419 fn sources_take_groups_unless_they_collide_across() {
420 let mut groups = CollisionGroups::new(false);
421 let (a, b) = (groups.get("a"), groups.get("b"));
422 assert_ne!(a, b);
423 assert_eq!(groups.get("a"), a);
424 assert_eq!(CollisionGroups::new(true).get("a"), ALL);
425 }
426}