Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / games / voxels / src / main / rust / src / raycast.rs
raycast.rs204 lines · 9.7 KiBRaw
| 1 | use glam::Vec3; |
| 2 | use crate::world::{ChunkMap, block::{Block, Shape}}; |
| 3 | |
| 4 | #[derive(Debug, Clone, Copy)] |
| 5 | pub struct HitResult { pub pos: (i32,i32,i32), pub prev: (i32,i32,i32), pub normal: (i32,i32,i32), pub dist: f32 } |
| 6 | |
| 7 | /// Slab in `t` for a ray against one box, in world space. Returns the entry distance and the axis |
| 8 | /// that was crossed on entry, or None if the ray misses. |
| 9 | fn ray_box(origin: Vec3, dir: Vec3, min: [f32; 3], max: [f32; 3]) -> Option<(f32, usize, bool)> { |
| 10 | let o = [origin.x, origin.y, origin.z]; |
| 11 | let d = [dir.x, dir.y, dir.z]; |
| 12 | let (mut t_near, mut t_far) = (f32::NEG_INFINITY, f32::INFINITY); |
| 13 | let (mut axis, mut positive) = (0usize, false); |
| 14 | for i in 0..3 { |
| 15 | if d[i].abs() < 1e-8 { |
| 16 | // Parallel to this slab: a miss unless the origin already lies inside it. |
| 17 | if o[i] < min[i] || o[i] > max[i] { return None; } |
| 18 | continue; |
| 19 | } |
| 20 | let inv = 1.0 / d[i]; |
| 21 | let mut t0 = (min[i] - o[i]) * inv; |
| 22 | let mut t1 = (max[i] - o[i]) * inv; |
| 23 | let mut enter_positive = false; // the ray enters through this axis' max face |
| 24 | if t0 > t1 { std::mem::swap(&mut t0, &mut t1); enter_positive = true; } |
| 25 | if t0 > t_near { t_near = t0; axis = i; positive = enter_positive; } |
| 26 | if t1 < t_far { t_far = t1; } |
| 27 | if t_near > t_far { return None; } |
| 28 | } |
| 29 | if t_far < 0.0 { return None; } |
| 30 | Some((t_near.max(0.0), axis, positive)) |
| 31 | } |
| 32 | |
| 33 | /// The nearest surface of a block within its cell, and the outward normal of the face hit. Cubes |
| 34 | /// short-circuit; slabs and stairs are tested box by box so you can look through their empty half. |
| 35 | fn hit_in_cell(chunks: &ChunkMap, cell: (i32, i32, i32), origin: Vec3, dir: Vec3) -> Option<(f32, (i32, i32, i32))> { |
| 36 | let (x, y, z) = cell; |
| 37 | let id = chunks.get_block_world(x, y, z); |
| 38 | if id == 0 { return None; } |
| 39 | let block = Block::from_id(id); |
| 40 | if !block.is_solid() { return None; } |
| 41 | let meta = chunks.get_meta_world(x, y, z); |
| 42 | let base = [x as f32, y as f32, z as f32]; |
| 43 | let mut best: Option<(f32, (i32, i32, i32))> = None; |
| 44 | for b in block.collision_boxes(meta).as_slice() { |
| 45 | let min = [base[0] + b.min[0], base[1] + b.min[1], base[2] + b.min[2]]; |
| 46 | let max = [base[0] + b.max[0], base[1] + b.max[1], base[2] + b.max[2]]; |
| 47 | let Some((t, axis, positive)) = ray_box(origin, dir, min, max) else { continue; }; |
| 48 | if best.is_some_and(|(bt, _)| bt <= t) { continue; } |
| 49 | let mut n = [0i32; 3]; |
| 50 | n[axis] = if positive { 1 } else { -1 }; |
| 51 | best = Some((t, (n[0], n[1], n[2]))); |
| 52 | } |
| 53 | best |
| 54 | } |
| 55 | |
| 56 | /// The cell a face normal points into — where a block placed against this hit would go. |
| 57 | fn step_out(cell: (i32, i32, i32), normal: (i32, i32, i32)) -> (i32, i32, i32) { |
| 58 | (cell.0 + normal.0, cell.1 + normal.1, cell.2 + normal.2) |
| 59 | } |
| 60 | |
| 61 | pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Option<HitResult> { |
| 62 | let dir = dir.normalize_or_zero(); |
| 63 | if dir.length_squared() < 1e-6 { return None; } |
| 64 | let mut x = origin.x.floor() as i32; |
| 65 | let mut y = origin.y.floor() as i32; |
| 66 | let mut z = origin.z.floor() as i32; |
| 67 | let step_x = if dir.x > 0.0 { 1 } else if dir.x < 0.0 { -1 } else { 0 }; |
| 68 | let step_y = if dir.y > 0.0 { 1 } else if dir.y < 0.0 { -1 } else { 0 }; |
| 69 | let step_z = if dir.z > 0.0 { 1 } else if dir.z < 0.0 { -1 } else { 0 }; |
| 70 | let t_delta_x = if dir.x != 0.0 { 1.0 / dir.x.abs() } else { f32::INFINITY }; |
| 71 | let t_delta_y = if dir.y != 0.0 { 1.0 / dir.y.abs() } else { f32::INFINITY }; |
| 72 | let t_delta_z = if dir.z != 0.0 { 1.0 / dir.z.abs() } else { f32::INFINITY }; |
| 73 | let mut t_max_x = if step_x != 0 { |
| 74 | let border = if step_x > 0 { x as f32 + 1.0 } else { x as f32 }; |
| 75 | (border - origin.x) / dir.x |
| 76 | } else { f32::INFINITY }; |
| 77 | let mut t_max_y = if step_y != 0 { |
| 78 | let border = if step_y > 0 { y as f32 + 1.0 } else { y as f32 }; |
| 79 | (border - origin.y) / dir.y |
| 80 | } else { f32::INFINITY }; |
| 81 | let mut t_max_z = if step_z != 0 { |
| 82 | let border = if step_z > 0 { z as f32 + 1.0 } else { z as f32 }; |
| 83 | (border - origin.z) / dir.z |
| 84 | } else { f32::INFINITY }; |
| 85 | let mut prev = (x,y,z); |
| 86 | let mut dist = 0.0; |
| 87 | // Which axis the DDA last crossed, so a cube hit reports the face it entered through without |
| 88 | // relying on float equality between accumulated t values. |
| 89 | let mut step_axis; |
| 90 | // Starting inside a block still counts, but only if the ray actually meets its geometry — the |
| 91 | // eye can sit in the empty half of a slab's cell. |
| 92 | if let Some((t, normal)) = hit_in_cell(chunks, (x,y,z), origin, dir) { |
| 93 | return Some(HitResult{ pos: (x,y,z), prev: step_out((x,y,z), normal), normal, dist: t }); |
| 94 | } |
| 95 | loop { |
| 96 | if dist > max_dist { return None; } |
| 97 | if t_max_x < t_max_y && t_max_x < t_max_z { |
| 98 | prev = (x,y,z); x += step_x; dist = t_max_x; t_max_x += t_delta_x; step_axis = 0; |
| 99 | } else if t_max_y < t_max_z { |
| 100 | prev = (x,y,z); y += step_y; dist = t_max_y; t_max_y += t_delta_y; step_axis = 1; |
| 101 | } else { |
| 102 | prev = (x,y,z); z += step_z; dist = t_max_z; t_max_z += t_delta_z; step_axis = 2; |
| 103 | } |
| 104 | if dist > max_dist { return None; } |
| 105 | let id = chunks.get_block_world(x, y, z); |
| 106 | if id != 0 && Block::from_id(id).is_solid() { |
| 107 | if Block::from_id(id).shape() == Shape::Cube { |
| 108 | // A full cube is entered exactly at the DDA boundary we just crossed. |
| 109 | let normal = match step_axis { |
| 110 | 0 => (-step_x, 0, 0), |
| 111 | 1 => (0, -step_y, 0), |
| 112 | _ => (0, 0, -step_z), |
| 113 | }; |
| 114 | return Some(HitResult{ pos: (x,y,z), prev, normal, dist }); |
| 115 | } |
| 116 | // Partial block: keep going unless the ray really meets one of its boxes. |
| 117 | if let Some((t, normal)) = hit_in_cell(chunks, (x,y,z), origin, dir) { |
| 118 | if t <= max_dist { |
| 119 | return Some(HitResult{ pos: (x,y,z), prev: step_out((x,y,z), normal), normal, dist: t }); |
| 120 | } |
| 121 | return None; |
| 122 | } |
| 123 | } |
| 124 | if x.abs() > 10000 || y.abs() > 10000 || z.abs() > 10000 { return None; } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | #[cfg(test)] |
| 129 | mod tests { |
| 130 | use super::*; |
| 131 | use crate::world::block::Id; |
| 132 | use crate::world::block::{Block, FACE_NORTH, META_TOP}; |
| 133 | use glam::vec3; |
| 134 | |
| 135 | // Terrain never reaches this high, so the test cells around it are guaranteed empty air. |
| 136 | const SKY: i32 = 200; |
| 137 | |
| 138 | fn world() -> ChunkMap { |
| 139 | let dir = std::env::temp_dir().join("voxels_raycast_test").to_string_lossy().into_owned(); |
| 140 | ChunkMap::new(1, dir) |
| 141 | } |
| 142 | |
| 143 | // A bottom slab leaves the top half of its cell empty; a ray through that half must pass by. |
| 144 | #[test] |
| 145 | fn a_ray_passes_through_a_slabs_empty_half() { |
| 146 | let mut w = world(); |
| 147 | w.set_block_meta_world(4, SKY, 0, Block::StoneSlab as Id, 0); |
| 148 | |
| 149 | // Aim along +X at 0.75 up the cell, above the slab's solid half. |
| 150 | let high = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.5), vec3(1.0, 0.0, 0.0), 20.0); |
| 151 | assert!(high.is_none(), "the upper half of a bottom slab's cell is empty"); |
| 152 | |
| 153 | // The same ray at 0.25 up must strike it. |
| 154 | let low = raycast(&w, vec3(0.0, SKY as f32 + 0.25, 0.5), vec3(1.0, 0.0, 0.0), 20.0).expect("must hit the slab"); |
| 155 | assert_eq!(low.pos, (4, SKY, 0)); |
| 156 | assert_eq!(low.normal, (-1, 0, 0), "entered through the slab's west face"); |
| 157 | assert_eq!(low.prev, (3, SKY, 0), "a block placed here goes in front of the slab"); |
| 158 | } |
| 159 | |
| 160 | // Looking straight down onto a bottom slab must report the top surface, not the cell's ceiling. |
| 161 | #[test] |
| 162 | fn looking_down_hits_the_slabs_top_surface() { |
| 163 | let mut w = world(); |
| 164 | w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, 0); |
| 165 | let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit"); |
| 166 | assert_eq!(hit.pos, (0, SKY, 0)); |
| 167 | assert_eq!(hit.normal, (0, 1, 0)); |
| 168 | assert!((hit.dist - 4.5).abs() < 1e-3, "the surface is half a block up, got dist {}", hit.dist); |
| 169 | assert_eq!(hit.prev, (0, SKY + 1, 0), "placing against the top goes in the cell above"); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn a_top_slab_is_hit_from_above_at_the_cell_ceiling() { |
| 174 | let mut w = world(); |
| 175 | w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, META_TOP); |
| 176 | let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit"); |
| 177 | assert!((hit.dist - 4.0).abs() < 1e-3, "a top slab's surface is the cell ceiling"); |
| 178 | } |
| 179 | |
| 180 | // Cubes must behave exactly as before the sub-voxel test was added. |
| 181 | #[test] |
| 182 | fn cubes_still_hit_at_the_cell_boundary() { |
| 183 | let mut w = world(); |
| 184 | w.set_block_world(4, SKY, 0, Block::Stone as Id); |
| 185 | let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.5, 0.5), vec3(1.0, 0.0, 0.0), 20.0).expect("must hit"); |
| 186 | assert_eq!(hit.pos, (4, SKY, 0)); |
| 187 | assert_eq!(hit.normal, (-1, 0, 0)); |
| 188 | assert_eq!(hit.prev, (3, SKY, 0)); |
| 189 | assert!((hit.dist - 4.0).abs() < 1e-3); |
| 190 | } |
| 191 | |
| 192 | // Stairs facing north keep their tall half on the +Z side; a ray into the low half at head |
| 193 | // height should sail over the tread. |
| 194 | #[test] |
| 195 | fn stairs_are_open_above_their_low_half() { |
| 196 | let mut w = world(); |
| 197 | w.set_block_meta_world(4, SKY, 0, Block::StoneStairs as Id, FACE_NORTH); |
| 198 | // z = 0.25 is the low (north) half, 0.75 up the cell is above the tread. |
| 199 | assert!(raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.25), vec3(1.0, 0.0, 0.0), 20.0).is_none()); |
| 200 | // z = 0.75 is under the tall step, so the same height is solid. |
| 201 | let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.75), vec3(1.0, 0.0, 0.0), 20.0); |
| 202 | assert!(hit.is_some(), "the stair's tall half must block the ray"); |
| 203 | } |
| 204 | } |