1use glam::{Mat4, Vec3};
15
16pub fn log_z_bounds(near: f32, far: f32, count: usize) -> Vec<f32> {
22 let near = near.max(1e-4);
23 let far = far.max(near * 1.001);
24 let n = count;
25 let ratio = far / near;
26 (0..=n)
27 .map(|i| {
28 if i == n {
29 far
30 } else {
31 near * ratio.powf(i as f32 / n.max(1) as f32)
32 }
33 })
34 .collect()
35}
36
37#[derive(Clone, Debug, PartialEq)]
39pub struct ClusterGrid {
40 pub tiles_x: u32,
42 pub tiles_y: u32,
44 z_bounds: Vec<f32>,
46}
47
48impl ClusterGrid {
49 pub fn new(tiles_x: u32, tiles_y: u32, slices: u32, near: f32, far: f32) -> Self {
53 Self {
54 tiles_x: tiles_x.max(1),
55 tiles_y: tiles_y.max(1),
56 z_bounds: log_z_bounds(near, far, slices.max(1) as usize),
57 }
58 }
59
60 pub fn for_render_size(
63 render_size: [u32; 2],
64 tile_size: u32,
65 slices: u32,
66 near: f32,
67 far: f32,
68 ) -> Self {
69 let ts = tile_size.max(1);
70 Self::new(
71 render_size[0].max(1).div_ceil(ts),
72 render_size[1].max(1).div_ceil(ts),
73 slices,
74 near,
75 far,
76 )
77 }
78
79 pub fn slice_count(&self) -> u32 {
81 (self.z_bounds.len() - 1) as u32
82 }
83
84 pub fn cluster_count(&self) -> u32 {
86 self.tiles_x * self.tiles_y * self.slice_count()
87 }
88
89 pub fn slice_bounds(&self, slice: u32) -> Option<(f32, f32)> {
91 let i = slice as usize;
92 if i + 1 < self.z_bounds.len() {
93 Some((self.z_bounds[i], self.z_bounds[i + 1]))
94 } else {
95 None
96 }
97 }
98
99 pub fn index(&self, tile_x: u32, tile_y: u32, slice: u32) -> u32 {
103 (slice * self.tiles_y + tile_y) * self.tiles_x + tile_x
104 }
105
106 pub fn coords(&self, index: u32) -> Option<(u32, u32, u32)> {
108 if index >= self.cluster_count() {
109 return None;
110 }
111 let x = index % self.tiles_x;
112 let y = (index / self.tiles_x) % self.tiles_y;
113 let z = index / (self.tiles_x * self.tiles_y);
114 Some((x, y, z))
115 }
116
117 pub fn slice_of(&self, view_depth: f32) -> Option<u32> {
121 let last = self.z_bounds.len() - 1;
122 if view_depth < self.z_bounds[0] || view_depth > self.z_bounds[last] {
123 return None;
124 }
125 let pp = self.z_bounds.partition_point(|&b| b < view_depth);
126 Some((pp.saturating_sub(1) as u32).min(self.slice_count() - 1))
127 }
128
129 pub fn locate(
133 &self,
134 pixel_x: u32,
135 pixel_y: u32,
136 tile_size: u32,
137 view_depth: f32,
138 ) -> Option<u32> {
139 let ts = tile_size.max(1);
140 let tx = (pixel_x / ts).min(self.tiles_x - 1);
141 let ty = (pixel_y / ts).min(self.tiles_y - 1);
142 self.slice_of(view_depth).map(|z| self.index(tx, ty, z))
143 }
144}
145
146#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct SphereLight {
157 pub position: Vec3,
158 pub radius: f32,
159}
160
161impl SphereLight {
162 pub fn new(position: Vec3, radius: f32) -> Self {
163 Self {
164 position,
165 radius: radius.max(0.0),
166 }
167 }
168}
169
170pub fn cluster_view_aabb(
181 grid: &ClusterGrid,
182 tile_x: u32,
183 tile_y: u32,
184 slice: u32,
185 proj: &Mat4,
186) -> Option<(Vec3, Vec3)> {
187 let a = proj.x_axis.x;
188 let b = proj.y_axis.y;
189 if a == 0.0 || b == 0.0 || !a.is_finite() || !b.is_finite() {
190 return None;
191 }
192 if tile_x >= grid.tiles_x || tile_y >= grid.tiles_y {
193 return None;
194 }
195 let (zn, zf) = grid.slice_bounds(slice)?;
196 let nx0 = 2.0 * tile_x as f32 / grid.tiles_x as f32 - 1.0;
198 let nx1 = 2.0 * (tile_x + 1) as f32 / grid.tiles_x as f32 - 1.0;
199 let ny1 = 1.0 - 2.0 * tile_y as f32 / grid.tiles_y as f32;
200 let ny0 = 1.0 - 2.0 * (tile_y + 1) as f32 / grid.tiles_y as f32;
201 let corner = |ndc_x: f32, ndc_y: f32, d: f32| Vec3::new(ndc_x * d / a, ndc_y * d / b, -d);
203 let mut mn = Vec3::splat(f32::MAX);
204 let mut mx = Vec3::splat(f32::MIN);
205 for (ex, ey) in [(nx0, ny0), (nx0, ny1), (nx1, ny0), (nx1, ny1)] {
206 for d in [zn, zf] {
207 let c = corner(ex, ey, d);
208 mn = mn.min(c);
209 mx = mx.max(c);
210 }
211 }
212 Some((mn, mx))
213}
214
215pub fn sphere_intersects_aabb(center: Vec3, radius: f32, min: Vec3, max: Vec3) -> bool {
217 let closest = center.clamp(min, max);
218 (closest - center).length_squared() <= radius * radius
219}
220
221pub fn cull_lights(
229 grid: &ClusterGrid,
230 view: &Mat4,
231 proj: &Mat4,
232 lights: &[SphereLight],
233) -> Vec<Vec<u32>> {
234 let view_lights: Vec<(Vec3, f32)> = lights
235 .iter()
236 .map(|l| (view.transform_point3(l.position), l.radius))
237 .collect();
238 let mut out = vec![Vec::new(); grid.cluster_count() as usize];
239 for z in 0..grid.slice_count() {
240 for y in 0..grid.tiles_y {
241 for x in 0..grid.tiles_x {
242 let Some((mn, mx)) = cluster_view_aabb(grid, x, y, z, proj) else {
243 continue;
244 };
245 let cell = &mut out[grid.index(x, y, z) as usize];
246 for (li, (c, r)) in view_lights.iter().enumerate() {
247 if sphere_intersects_aabb(*c, *r, mn, mx) {
248 cell.push(li as u32);
249 }
250 }
251 }
252 }
253 }
254 out
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 fn approx(a: f32, b: f32, eps: f32) -> bool {
262 (a - b).abs() < eps
263 }
264
265 #[test]
266 fn z_grenzen_verankert_monoton_und_log() {
267 let b = log_z_bounds(0.5, 200.0, 4);
268 assert_eq!(b.len(), 5);
269 assert!(approx(b[0], 0.5, 1e-5) && approx(*b.last().unwrap(), 200.0, 1e-5));
270 for w in b.windows(2) {
271 assert!(w[1] > w[0], "monoton: {w:?}");
272 }
273 let r0 = b[1] / b[0];
275 let r1 = b[2] / b[1];
276 let r3 = b[4] / b[3];
277 assert!(
278 approx(r0, r1, 1e-3) && approx(r1, r3, 1e-3),
279 "log-Verhältnis {r0},{r1},{r3}"
280 );
281 assert!(b[1] - b[0] < b[4] - b[3]);
283 }
284
285 #[test]
286 fn grid_baut_und_klemmt() {
287 let g = ClusterGrid::new(8, 6, 4, 0.1, 100.0);
288 assert_eq!(g.slice_count(), 4);
289 assert_eq!(g.cluster_count(), 8 * 6 * 4);
290 let e = ClusterGrid::new(0, 0, 0, 10.0, 5.0);
292 assert_eq!((e.tiles_x, e.tiles_y, e.slice_count()), (1, 1, 1));
293 let r = ClusterGrid::for_render_size([1920, 1080], 16, 4, 0.1, 400.0);
295 assert_eq!((r.tiles_x, r.tiles_y), (120, 68)); }
297
298 #[test]
299 fn index_und_coords_sind_invers() {
300 let g = ClusterGrid::new(4, 3, 5, 0.1, 100.0);
301 for z in 0..g.slice_count() {
302 for y in 0..g.tiles_y {
303 for x in 0..g.tiles_x {
304 let i = g.index(x, y, z);
305 assert!(i < g.cluster_count());
306 assert_eq!(g.coords(i), Some((x, y, z)), "Roundtrip {x},{y},{z}");
307 }
308 }
309 }
310 assert_eq!(g.coords(g.cluster_count()), None);
311 }
312
313 #[test]
314 fn scheibenzuordnung_eindeutig() {
315 let g = ClusterGrid::new(1, 1, 4, 1.0, 1000.0);
316 assert_eq!(g.slice_of(1.0), Some(0));
318 assert_eq!(g.slice_of(1000.0), Some(3));
319 assert_eq!(g.slice_of(0.99), None);
321 assert_eq!(g.slice_of(1000.1), None);
322 let b = log_z_bounds(1.0, 1000.0, 4);
325 for k in 0..4 {
326 let innen = (b[k] + b[k + 1]) * 0.5;
327 assert_eq!(g.slice_of(innen), Some(k as u32), "Mitte Scheibe {k}");
328 if k > 0 {
329 assert_eq!(
330 g.slice_of(b[k]),
331 Some((k - 1) as u32),
332 "Grenze {k} -> unten"
333 );
334 }
335 }
336 let (n, f) = g.slice_bounds(2).unwrap();
338 assert!(n < f && f <= 1000.0);
339 assert_eq!(g.slice_of((n + f) * 0.5), Some(2));
340 assert_eq!(g.slice_bounds(4), None);
341 }
342
343 #[test]
344 fn locate_nutzt_raster_richtig() {
345 let g = ClusterGrid::for_render_size([100, 50], 10, 4, 1.0, 1000.0);
346 assert_eq!((g.tiles_x, g.tiles_y), (10, 5));
347 let tiefe = 1.0; assert_eq!(g.locate(0, 0, 10, tiefe), Some(g.index(0, 0, 0)));
349 assert_eq!(g.locate(10, 0, 10, tiefe), Some(g.index(1, 0, 0)));
350 assert_eq!(g.locate(0, 10, 10, tiefe), Some(g.index(0, 1, 0)));
351 assert_eq!(g.locate(99, 49, 10, tiefe), Some(g.index(9, 4, 0)));
353 assert_eq!(g.locate(500, 500, 10, tiefe), Some(g.index(9, 4, 0)));
354 assert_eq!(g.locate(5, 5, 10, 2000.0), None);
356 }
357
358 #[test]
359 fn tiefe_und_index_haengen_konsistent_zusammen() {
360 let g = ClusterGrid::new(2, 2, 4, 1.0, 1000.0);
361 let b = log_z_bounds(1.0, 1000.0, 4);
362 for k in 0..4 {
363 let d = (b[k] + b[k + 1]) * 0.5;
364 let idx = g.locate(15, 15, 10, d).unwrap();
365 let (x, y, z) = g.coords(idx).unwrap();
366 assert_eq!((x, y), (1, 1), "Pixel (15,15) bei tile 10");
367 assert_eq!(z, k as u32, "Scheibe bei Tiefe {d}");
368 }
369 }
370
371 fn test_camera() -> (Mat4, Mat4) {
375 (
376 Mat4::IDENTITY,
377 Mat4::perspective_rh(std::f32::consts::FRAC_PI_2, 1.0, 1.0, 100.0),
378 )
379 }
380
381 #[test]
382 fn cluster_aabb_waechst_mit_der_tiefe() {
383 let (view, proj) = test_camera();
384 let _ = view;
385 let g = ClusterGrid::new(1, 1, 4, 1.0, 100.0);
386 let (mn0, mx0) = cluster_view_aabb(&g, 0, 0, 0, &proj).unwrap();
387 let (mn3, mx3) = cluster_view_aabb(&g, 0, 0, 3, &proj).unwrap();
388 assert!(approx(mx0.x, g.slice_bounds(0).unwrap().1, 1e-3));
390 assert!(mn0.z < mx0.z && approx(mn0.z, -g.slice_bounds(0).unwrap().1, 1e-5));
391 assert!(mn3.x < mn0.x, "ferne Zelle auch nach links breiter");
392 assert!(mx3.x > mx0.x * 3.0, "ferne Zelle deutlich breiter");
393 let (zn, zf) = g.slice_bounds(2).unwrap();
395 let (mn, mx) = cluster_view_aabb(&g, 0, 0, 2, &proj).unwrap();
396 assert!(approx(mn.z, -zf, 1e-4) && approx(mx.z, -zn, 1e-4));
397 }
398
399 #[test]
400 fn kugel_aabb_grundfaelle() {
401 let (mn, mx) = (Vec3::splat(-1.0), Vec3::splat(1.0));
402 assert!(sphere_intersects_aabb(Vec3::ZERO, 0.1, mn, mx), "Innen");
403 assert!(
404 sphere_intersects_aabb(Vec3::new(1.5, 0.0, 0.0), 0.5, mn, mx),
405 "Berührt"
406 );
407 assert!(
408 !sphere_intersects_aabb(Vec3::new(1.6, 0.0, 0.0), 0.5, mn, mx),
409 "Außerhalb"
410 );
411 assert!(
412 sphere_intersects_aabb(Vec3::new(3.0, 3.0, 0.0), 3.0, mn, mx),
413 "Ecke aus der Ferne"
414 );
415 }
416
417 #[test]
418 fn zentrales_licht_nur_in_seiner_scheibe() {
419 let (view, proj) = test_camera();
420 let g = ClusterGrid::new(2, 2, 4, 1.0, 100.0);
421 let lights = [SphereLight::new(Vec3::new(0.0, 0.0, -5.0), 0.1)];
423 let lists = cull_lights(&g, &view, &proj, &lights);
424 for z in 0..4 {
425 for t in 0..4 {
426 let cell = &lists[g.index(t % 2, t / 2, z) as usize];
427 if z == 1 {
428 assert!(cell.contains(&0), "Scheibe 1, Kachel {t} muss treffen");
430 } else {
431 assert!(cell.is_empty(), "Scheibe {z}, Kachel {t} muss leer sein");
432 }
433 }
434 }
435 }
436
437 #[test]
438 fn licht_hinter_oder_neben_der_kamera_faellt_weg() {
439 let (view, proj) = test_camera();
440 let g = ClusterGrid::new(2, 2, 4, 1.0, 100.0);
441 let lights = [
442 SphereLight::new(Vec3::new(0.0, 0.0, 5.0), 0.5), SphereLight::new(Vec3::new(50.0, 0.0, -5.0), 0.5), ];
445 let lists = cull_lights(&g, &view, &proj, &lights);
446 assert!(
447 lists.iter().all(|l| l.is_empty()),
448 "beide müssen komplett weg sein"
449 );
450 }
451
452 #[test]
453 fn riesiges_licht_trifft_alle_cluster() {
454 let (view, proj) = test_camera();
455 let g = ClusterGrid::new(3, 3, 4, 1.0, 100.0);
456 let lights = [SphereLight::new(Vec3::new(0.0, 0.0, -30.0), 500.0)];
457 let lists = cull_lights(&g, &view, &proj, &lights);
458 assert_eq!(lists.len(), g.cluster_count() as usize);
459 assert!(
460 lists.iter().all(|l| l == &vec![0]),
461 "riesige Kugel schneidet alles"
462 );
463 }
464
465 #[test]
466 fn keine_false_negatives_konservativ_wie_die_gpu() {
467 let (view, proj) = test_camera();
468 let g = ClusterGrid::new(4, 4, 4, 1.0, 100.0);
469 let d = 6.0;
471 let pos = Vec3::new(-0.4 * d, 0.4 * d, -d);
472 let lights = [SphereLight::new(pos, 0.05)];
473 let lists = cull_lights(&g, &view, &proj, &lights);
474 let hits: Vec<u32> = (0..g.cluster_count())
475 .filter(|&i| !lists[i as usize].is_empty())
476 .collect();
477 let target = g.index(1, 1, 1);
479 assert!(hits.contains(&target), "Ziel-Cluster fehlt: {hits:?}");
480 for h in &hits {
484 let (x, y, z) = g.coords(*h).unwrap();
485 assert_eq!(z, 1, "Treffer in falscher Scheibe: {h}");
486 assert!(
487 (x as i32 - 1).abs() <= 1 && (y as i32 - 1).abs() <= 1,
488 "Treffer zu weit weg: {h}"
489 );
490 }
491 }
492
493 #[test]
494 fn culling_ist_deterministisch_und_sortiert() {
495 let (view, proj) = test_camera();
496 let g = ClusterGrid::new(2, 2, 2, 1.0, 50.0);
497 let lights = [
498 SphereLight::new(Vec3::new(0.0, 0.0, -5.0), 2.0),
499 SphereLight::new(Vec3::new(0.2, 0.0, -5.2), 1.0),
500 SphereLight::new(Vec3::new(0.0, 0.0, -20.0), 3.0),
501 ];
502 let a = cull_lights(&g, &view, &proj, &lights);
503 let b = cull_lights(&g, &view, &proj, &lights);
504 assert_eq!(a, b, "zwei Läufe müssen identisch sein");
505 for l in &a {
506 let mut s = l.clone();
507 s.sort();
508 assert_eq!(l, &s, "Listen müssen aufsteigend sortiert sein");
509 }
510 assert!(
512 a.iter().any(|l| l == &vec![0u32, 1]),
513 "Überschneidung muss Liste [0,1] erzeugen"
514 );
515 }
516}