1use std::collections::HashMap;
27
28use glam::Vec2;
29
30use crate::clipmap::chebyshev_near;
31use crate::grid::{cell_center, floor_div};
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct HlodCell {
36 pub x: i64,
37 pub y: i64,
38}
39
40#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct HlodConfig {
43 pub cell_size: f64,
47 pub take_over: f64,
50 pub fade_out: f64,
52 pub hysteresis: f64,
55}
56
57impl HlodConfig {
58 pub fn cluster_center(&self, cell: HlodCell) -> Vec2 {
60 Vec2::new(
61 cell_center(cell.x, self.cell_size) as f32,
62 cell_center(cell.y, self.cell_size) as f32,
63 )
64 }
65
66 pub fn cell_at(&self, world: Vec2) -> HlodCell {
68 HlodCell {
69 x: floor_div(world.x as f64, self.cell_size),
70 y: floor_div(world.y as f64, self.cell_size),
71 }
72 }
73
74 fn checked(&self) {
75 assert!(self.cell_size > 0.0, "cell_size muss > 0 sein");
76 assert!(self.take_over > 0.0, "take_over muss > 0 sein");
77 assert!(
78 self.fade_out >= self.take_over,
79 "fade_out ({}) muss >= take_over ({}) sein",
80 self.fade_out,
81 self.take_over
82 );
83 assert!(
84 (0.0..0.5).contains(&self.hysteresis),
85 "hysteresis muss in 0..0.5 liegen"
86 );
87 }
88}
89
90#[derive(Clone, Debug, Default, PartialEq, Eq)]
92pub struct HlodDelta {
93 pub shown: Vec<HlodCell>,
96 pub hidden: Vec<HlodCell>,
98}
99
100impl HlodDelta {
101 pub fn is_empty(&self) -> bool {
102 self.shown.is_empty() && self.hidden.is_empty()
103 }
104}
105
106struct Cluster {
108 source_cells: u32,
111 shown: bool,
112}
113
114pub struct HlodSet {
120 cfg: HlodConfig,
121 clusters: HashMap<HlodCell, Cluster>,
122}
123
124impl HlodSet {
125 pub fn new(cfg: HlodConfig) -> Self {
126 cfg.checked();
127 Self {
128 cfg,
129 clusters: HashMap::new(),
130 }
131 }
132
133 pub fn config(&self) -> &HlodConfig {
134 &self.cfg
135 }
136
137 pub fn len(&self) -> usize {
138 self.clusters.len()
139 }
140
141 pub fn is_empty(&self) -> bool {
142 self.clusters.is_empty()
143 }
144
145 pub fn contains(&self, cell: HlodCell) -> bool {
146 self.clusters.contains_key(&cell)
147 }
148
149 pub fn cells(&self) -> Vec<HlodCell> {
152 let mut out: Vec<HlodCell> = self.clusters.keys().copied().collect();
153 out.sort_by_key(|c| (c.x, c.y));
154 out
155 }
156
157 pub fn register(&mut self, cell: HlodCell, source_cells: u32) {
161 self.clusters
162 .entry(cell)
163 .and_modify(|c| c.source_cells = source_cells)
164 .or_insert(Cluster {
165 source_cells,
166 shown: false,
167 });
168 }
169
170 pub fn unregister(&mut self, cell: HlodCell) -> Option<u32> {
173 self.clusters.remove(&cell).map(|c| c.source_cells)
174 }
175
176 pub fn source_cells(&self, cell: HlodCell) -> Option<u32> {
178 self.clusters.get(&cell).map(|c| c.source_cells)
179 }
180
181 pub fn is_shown(&self, cell: HlodCell) -> bool {
182 self.clusters.get(&cell).is_some_and(|c| c.shown)
183 }
184
185 pub fn shown(&self) -> Vec<HlodCell> {
187 let mut out: Vec<HlodCell> = self
188 .clusters
189 .iter()
190 .filter(|(_, c)| c.shown)
191 .map(|(k, _)| *k)
192 .collect();
193 out.sort_unstable();
194 out
195 }
196
197 pub fn update(&mut self, camera: Vec2) -> Option<HlodDelta> {
200 if self.clusters.is_empty() {
201 return None;
202 }
203 let mut delta = HlodDelta::default();
204 let mut keys: Vec<HlodCell> = self.clusters.keys().copied().collect();
207 keys.sort_unstable();
208 for key in keys {
209 let c = self.clusters.get_mut(&key).expect("sortierter Schlüssel");
210 let d = chebyshev_near(
211 camera.x as f64,
212 camera.y as f64,
213 key.x,
214 key.y,
215 self.cfg.cell_size,
216 );
217 let next = if d > self.cfg.fade_out {
218 false } else if c.shown {
220 d >= self.cfg.take_over * (1.0 - self.cfg.hysteresis)
221 } else {
222 d > self.cfg.take_over
223 };
224 if next != c.shown {
225 c.shown = next;
226 if next {
227 delta.shown.push(key);
228 } else {
229 delta.hidden.push(key);
230 }
231 }
232 }
233 (!delta.is_empty()).then_some(delta)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 fn set(take_over: f64, hysteresis: f64) -> HlodSet {
242 HlodSet::new(HlodConfig {
243 cell_size: 1000.0,
244 take_over,
245 fade_out: 10_000.0,
246 hysteresis,
247 })
248 }
249
250 fn cell(x: i64, y: i64) -> HlodCell {
251 HlodCell { x, y }
252 }
253
254 #[test]
255 fn leere_menge_ruht() {
256 let mut s = set(1000.0, 0.1);
257 assert!(s.update(Vec2::ZERO).is_none());
258 assert!(s.shown().is_empty());
259 }
260
261 #[test]
265 fn uebernahme_nach_distanz() {
266 let mut s = set(1500.0, 0.0);
267 s.register(cell(0, 0), 16); s.register(cell(1, 0), 16); s.register(cell(2, 0), 16); s.register(cell(5, 0), 16); let d = s.update(Vec2::ZERO).expect("zwei wechseln auf gezeigt");
272 assert_eq!(d.shown, vec![cell(2, 0), cell(5, 0)]);
273 assert!(d.hidden.is_empty());
274 assert_eq!(s.shown(), vec![cell(2, 0), cell(5, 0)]);
275 assert_eq!(s.source_cells(cell(5, 0)), Some(16));
276 assert!(!s.is_shown(cell(1, 0)));
277 }
278
279 #[test]
282 fn hysterese_verhindert_flackern() {
283 let mut s = set(2000.0, 0.1);
284 let edge = cell(2, 0); s.register(edge, 8);
286 let mut flips = 0;
287 for i in 0..240 {
288 let x = if i % 2 == 0 { 100.0 } else { 200.0 };
291 if let Some(d) = s.update(Vec2::new(x, 0.0)) {
292 if d.shown.contains(&edge) || d.hidden.contains(&edge) {
293 flips += 1;
294 }
295 }
296 }
297 assert_eq!(flips, 0, "keine Umschaltung in der Hysteresezone");
298 assert!(!s.is_shown(edge));
299 }
300
301 #[test]
302 fn klar_jenseits_uebernommen_klar_innerhalb_zurueck() {
303 let mut s = set(2000.0, 0.1);
304 let c = cell(3, 0); s.register(c, 8);
306 let d = s.update(Vec2::ZERO).unwrap();
308 assert_eq!(d.shown, vec![c]);
309 let d = s.update(Vec2::new(3500.0, 0.0)).unwrap();
311 assert_eq!(d.hidden, vec![c]);
312 assert!(s.update(Vec2::new(3500.0, 0.0)).is_none());
314 }
315
316 #[test]
319 fn fade_out_blendet_aus_und_wieder_ein() {
320 let mut s = HlodSet::new(HlodConfig {
321 cell_size: 1000.0,
322 take_over: 1000.0,
323 fade_out: 2500.0,
324 hysteresis: 0.0,
325 });
326 let c = cell(3, 0); s.register(c, 4);
328 assert!(s.update(Vec2::ZERO).is_none());
330 let d = s.update(Vec2::new(800.0, 0.0)).unwrap();
332 assert_eq!(d.shown, vec![c]);
333 let d = s.update(Vec2::ZERO).unwrap();
335 assert_eq!(d.hidden, vec![c]);
336 }
337
338 #[test]
339 fn raster_rechen_hilfen() {
340 let cfg = HlodConfig {
341 cell_size: 1000.0,
342 take_over: 1000.0,
343 fade_out: 2000.0,
344 hysteresis: 0.0,
345 };
346 assert_eq!(cfg.cell_at(Vec2::new(3500.0, -50.0)), cell(3, -1));
347 assert_eq!(cfg.cluster_center(cell(3, -1)), Vec2::new(3500.0, -500.0));
348 }
349
350 #[test]
351 fn unregister_meldet_entfernung() {
352 let mut s = set(1000.0, 0.0);
353 let c = cell(2, 0);
354 s.register(c, 6);
355 assert!(s.update(Vec2::ZERO).unwrap().shown.contains(&c));
356 assert_eq!(s.unregister(c), Some(6));
357 assert!(!s.contains(c));
358 assert!(s.shown().is_empty());
359 }
360
361 #[test]
363 fn ereignisfolgen_sind_deterministisch() {
364 fn run() -> Vec<(Vec<HlodCell>, Vec<HlodCell>)> {
365 let mut s = set(2000.0, 0.05);
366 for x in -3..=3 {
367 for y in -3..=3 {
368 s.register(cell(x, y), 64);
369 }
370 }
371 let mut log = Vec::new();
372 for i in 0..200 {
373 let t = i as f32 * 0.05;
374 let cam = Vec2::new(t * 137.0, (t * 0.7).sin() * 900.0);
375 match s.update(cam) {
376 Some(d) => log.push((d.shown, d.hidden)),
377 None => log.push((Vec::new(), Vec::new())),
378 }
379 }
380 log
381 }
382 let a = run();
383 assert_eq!(a, run());
384 let flips: usize = a.iter().map(|(s, h)| s.len() + h.len()).sum();
385 assert!(flips > 0, "das Skript bewegt wirklich Cluster");
386 }
387}