voxelize/world/utils/
chunk.rs

1use crate::{Vec2, Vec3};
2
3fn get_concat() -> &'static str {
4    if (cfg!(target_os = "windows")) {
5        "_"
6    } else {
7        "|"
8    }
9}
10
11/// A set of utility functions for chunk operations.
12pub struct ChunkUtils;
13
14fn floor_scale_coords(x: f32, y: f32, z: f32, factor: f32) -> Vec3<f32> {
15    Vec3(
16        (x * factor).floor(),
17        (y * factor).floor(),
18        (z * factor).floor(),
19    )
20}
21
22impl ChunkUtils {
23    /// Generate a chunk representation from a chunk coordinate.
24    pub fn get_chunk_name(cx: i32, cz: i32) -> String {
25        format!("{}{}{}", cx, get_concat(), cz)
26    }
27
28    /// Parse a chunk coordinate from a chunk representation.
29    pub fn parse_chunk_name(name: &str) -> Vec2<i32> {
30        let vec = name.split(get_concat()).collect::<Vec<&str>>();
31        Vec2(vec[0].parse().unwrap(), vec[1].parse().unwrap())
32    }
33
34    /// Generate a voxel representation from a voxel coordinate.
35    pub fn get_voxel_name(vx: i32, vy: i32, vz: i32) -> String {
36        let concat = get_concat();
37        format!("{}{}{}{}{}", vx, concat, vy, concat, vz)
38    }
39
40    /// Parse a voxel coordinate from a voxel representation.
41    pub fn parse_voxel_name(name: &str) -> Vec3<i32> {
42        let concat = get_concat();
43        let vec = name.split(concat).collect::<Vec<&str>>();
44        Vec3(
45            vec[0].parse().unwrap(),
46            vec[1].parse().unwrap(),
47            vec[2].parse().unwrap(),
48        )
49    }
50
51    /// Map a voxel coordinate to a chunk coordinate.
52    pub fn map_voxel_to_chunk(vx: i32, vy: i32, vz: i32, chunk_size: usize) -> Vec2<i32> {
53        let scaled = Vec3::<i32>::from(&floor_scale_coords(
54            vx as f32,
55            vy as f32,
56            vz as f32,
57            1.0 / (chunk_size as f32),
58        ));
59        Vec2(scaled.0, scaled.2)
60    }
61
62    /// Map a voxel coordinate to a chunk local coordinate.
63    pub fn map_voxel_to_chunk_local(vx: i32, vy: i32, vz: i32, chunk_size: usize) -> Vec3<usize> {
64        let Vec2(cx, cz) = ChunkUtils::map_voxel_to_chunk(vx, vy, vz, chunk_size);
65        let cs = chunk_size as i32;
66
67        Vec3(
68            (vx - cx * cs) as usize,
69            vy as usize,
70            (vz - cz * cs) as usize,
71        )
72    }
73
74    pub fn distance_squared(a: &Vec2<i32>, b: &Vec2<i32>) -> f32 {
75        let dx = a.0 - b.0;
76        let dz = a.1 - b.1;
77        (dx * dx + dz * dz) as f32
78    }
79}