Skip to main content

binary_greedy_meshing/
lib.rs

1#![no_std]
2
3#[macro_use]
4extern crate alloc;
5
6mod face;
7mod quad;
8
9use alloc::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec};
10
11pub use face::*;
12pub use quad::*;
13
14#[derive(Debug)]
15pub struct Mesher<const CS: usize> {
16    // Output
17    pub quads: [Vec<Quad>; 6],
18    // Internal buffers
19    /// CS_2 * 6
20    face_masks: Box<[u64]>,
21    /// CS_2
22    forward_merged: Box<[u8]>,
23    /// CS
24    right_merged: Box<[u8]>,
25}
26
27impl<const CS: usize> Mesher<CS> {
28    pub const CS_2: usize = CS * CS;
29    pub const CS_3: usize = CS * CS * CS;
30    pub const CS_P: usize = CS + 2;
31    pub const CS_P2: usize = Self::CS_P * Self::CS_P;
32    pub const CS_P3: usize = Self::CS_P * Self::CS_P * Self::CS_P;
33    pub const P_MASK: u64 = !(1 << (Self::CS_P - 1) | 1);
34
35    /// Creates a mesher object, allocates necessary buffers
36    pub fn new() -> Self {
37        Self {
38            face_masks: vec![0; Self::CS_2 * 6].into_boxed_slice(),
39            forward_merged: vec![0; Self::CS_2].into_boxed_slice(),
40            right_merged: vec![0; CS].into_boxed_slice(),
41            quads: core::array::from_fn(|_| Vec::new()),
42        }
43    }
44
45    /// Call this between each meshing call to reset the buffers without reallocating them
46    pub fn clear(&mut self) {
47        self.face_masks.fill(0);
48        self.forward_merged.fill(0);
49        self.right_merged.fill(0);
50        for i in 0..self.quads.len() {
51            self.quads[i].clear();
52        }
53    }
54
55    fn face_culling(&mut self, voxels: &[u16], transparents: &BTreeSet<u16>) {
56        // Hidden face culling
57        for a in 1..(Self::CS_P - 1) {
58            let a_cs_p = a * Self::CS_P;
59
60            for b in 1..(Self::CS_P - 1) {
61                let ab = (a_cs_p + b) * Self::CS_P;
62                let ba_index = (b - 1) + (a - 1) * CS;
63                let ab_index = (a - 1) + (b - 1) * CS;
64
65                for c in 1..(Self::CS_P - 1) {
66                    let abc = ab + c;
67                    let v1 = voxels[abc];
68                    if v1 == 0 {
69                        continue;
70                    }
71                    self.face_masks[ba_index + 0 * Self::CS_2] |=
72                        face_value(v1, voxels[abc + Self::CS_P2], &transparents) << (c - 1);
73                    self.face_masks[ba_index + 1 * Self::CS_2] |=
74                        face_value(v1, voxels[abc - Self::CS_P2], &transparents) << (c - 1);
75
76                    self.face_masks[ab_index + 2 * Self::CS_2] |=
77                        face_value(v1, voxels[abc + Self::CS_P], &transparents) << (c - 1);
78                    self.face_masks[ab_index + 3 * Self::CS_2] |=
79                        face_value(v1, voxels[abc - Self::CS_P], &transparents) << (c - 1);
80
81                    self.face_masks[ba_index + 4 * Self::CS_2] |=
82                        face_value(v1, voxels[abc + 1], &transparents) << c;
83                    self.face_masks[ba_index + 5 * Self::CS_2] |=
84                        face_value(v1, voxels[abc - 1], &transparents) << c;
85                }
86            }
87        }
88    }
89
90    fn fast_face_culling(&mut self, voxels: &[u16], opaque_mask: &[u64], trans_mask: &[u64]) {
91        // Hidden face culling
92        for a in 1..(Self::CS_P - 1) {
93            let a_ = a * Self::CS_P;
94
95            for b in 1..(Self::CS_P - 1) {
96                // Column-wise opaque step
97                let ab = a_ + b;
98                let opaque_col = opaque_mask[ab] & Self::P_MASK;
99                let unpadded_opaque_col = opaque_col >> 1;
100                let ba_index = (b - 1) + (a - 1) * CS;
101                let ab_index = (a - 1) + (b - 1) * CS;
102                let up_faces = ba_index + 0 * Self::CS_2;
103                let down_faces = ba_index + 1 * Self::CS_2;
104                let right_faces = ab_index + 2 * Self::CS_2;
105                let left_faces = ab_index + 3 * Self::CS_2;
106                let front_faces = ba_index + 4 * Self::CS_2;
107                let back_faces = ba_index + 5 * Self::CS_2;
108                let not_front_col = !opaque_mask[ab + Self::CS_P] >> 1;
109                let not_back_col = !opaque_mask[ab - Self::CS_P] >> 1;
110                let not_right_col = !opaque_mask[ab + 1] >> 1;
111                let not_left_col = !opaque_mask[ab - 1] >> 1;
112                let not_col_up = !(opaque_mask[ab] >> 1);
113                let not_col_down = !(opaque_mask[ab] << 1);
114                self.face_masks[up_faces] = unpadded_opaque_col & not_front_col;
115                self.face_masks[down_faces] = unpadded_opaque_col & not_back_col;
116
117                self.face_masks[right_faces] = unpadded_opaque_col & not_right_col;
118                self.face_masks[left_faces] = unpadded_opaque_col & not_left_col;
119
120                self.face_masks[front_faces] = opaque_col & not_col_up;
121                self.face_masks[back_faces] = opaque_col & not_col_down;
122
123                // check if there's transparent blocks in this column
124                let mut bits_here = trans_mask[ab] & Self::P_MASK;
125                if bits_here == 0 {
126                    continue;
127                }
128                // Block-wise transparent step
129                // The transparent step is slower than the opaque step
130                // because we need to check if neighboring transparent blocks are differents (we don't care about that for opaque blocks)
131                let ab_ = ab * Self::CS_P;
132                while bits_here != 0 {
133                    let c = bits_here.trailing_zeros() as usize;
134                    let c_mask = 1 << c;
135                    let unpadded_c_mask = c_mask >> 1;
136                    bits_here &= !(c_mask);
137                    let abc = ab_ + c;
138                    let v1 = voxels[abc];
139                    self.face_masks[up_faces] |= not_front_col
140                        & unpadded_c_mask
141                        & ((v1 != voxels[abc + Self::CS_P2]) as u64) << (c - 1);
142                    self.face_masks[down_faces] |= not_back_col
143                        & unpadded_c_mask
144                        & ((v1 != voxels[abc - Self::CS_P2]) as u64) << (c - 1);
145
146                    self.face_masks[right_faces] |= not_right_col
147                        & unpadded_c_mask
148                        & ((v1 != voxels[abc + Self::CS_P]) as u64) << (c - 1);
149                    self.face_masks[left_faces] |= not_left_col
150                        & unpadded_c_mask
151                        & ((v1 != voxels[abc - Self::CS_P]) as u64) << (c - 1);
152
153                    self.face_masks[front_faces] |=
154                        not_col_up & c_mask & ((v1 != voxels[abc + 1]) as u64) << c;
155                    self.face_masks[back_faces] |=
156                        not_col_down & c_mask & ((v1 != voxels[abc - 1]) as u64) << c;
157                }
158            }
159        }
160    }
161
162    fn face_merging(&mut self, voxels: &[u16]) {
163        // Greedy meshing faces 0-3
164        for face in 0..=3 {
165            let axis = face / 2;
166
167            for layer in 0..CS {
168                let bits_location = layer * CS + face * Self::CS_2;
169
170                for forward in 0..CS {
171                    let mut bits_here = self.face_masks[forward + bits_location];
172                    if bits_here == 0 {
173                        continue;
174                    }
175
176                    let bits_next = if forward + 1 < CS {
177                        self.face_masks[(forward + 1) + bits_location]
178                    } else {
179                        0
180                    };
181
182                    let mut right_merged = 1;
183                    while bits_here != 0 {
184                        let bit_pos = bits_here.trailing_zeros() as usize;
185
186                        let v_type =
187                            voxels[get_axis_index::<CS>(axis, forward + 1, bit_pos + 1, layer + 1)];
188
189                        if (bits_next >> bit_pos & 1) != 0
190                            && v_type
191                                == voxels[get_axis_index::<CS>(
192                                    axis,
193                                    forward + 2,
194                                    bit_pos + 1,
195                                    layer + 1,
196                                )]
197                        {
198                            self.forward_merged[bit_pos] += 1;
199                            bits_here &= !(1 << bit_pos);
200                            continue;
201                        }
202
203                        for right in (bit_pos + 1)..CS {
204                            if (bits_here >> right & 1) == 0
205                                || self.forward_merged[bit_pos] != self.forward_merged[right]
206                                || v_type
207                                    != voxels[get_axis_index::<CS>(
208                                        axis,
209                                        forward + 1,
210                                        right + 1,
211                                        layer + 1,
212                                    )]
213                            {
214                                break;
215                            }
216                            self.forward_merged[right] = 0;
217                            right_merged += 1;
218                        }
219                        bits_here &= !((1 << (bit_pos + right_merged)) - 1);
220
221                        let mesh_front = forward - self.forward_merged[bit_pos] as usize;
222                        let mesh_left = bit_pos;
223                        let mesh_up = layer + (!face & 1);
224
225                        let mesh_width = right_merged;
226                        let mesh_length = (self.forward_merged[bit_pos] + 1) as usize;
227
228                        self.forward_merged[bit_pos] = 0;
229                        right_merged = 1;
230
231                        let v_type = v_type as usize;
232
233                        let quad = match face {
234                            0 => Quad::pack(
235                                mesh_front,
236                                mesh_up,
237                                mesh_left,
238                                mesh_length,
239                                mesh_width,
240                                v_type,
241                            ),
242                            1 => Quad::pack(
243                                mesh_front + mesh_length as usize,
244                                mesh_up,
245                                mesh_left,
246                                mesh_length,
247                                mesh_width,
248                                v_type,
249                            ),
250                            2 => Quad::pack(
251                                mesh_up,
252                                mesh_front + mesh_length as usize,
253                                mesh_left,
254                                mesh_length,
255                                mesh_width,
256                                v_type,
257                            ),
258                            3 => Quad::pack(
259                                mesh_up,
260                                mesh_front,
261                                mesh_left,
262                                mesh_length,
263                                mesh_width,
264                                v_type,
265                            ),
266                            _ => unreachable!(),
267                        };
268                        self.quads[face].push(quad);
269                    }
270                }
271            }
272        }
273
274        // Greedy meshing faces 4-5
275        for face in 4..6 {
276            let axis = face / 2;
277
278            for forward in 0..CS {
279                let bits_location = forward * CS + face * Self::CS_2;
280                let bits_forward_location = (forward + 1) * CS + face * Self::CS_2;
281
282                for right in 0..CS {
283                    let mut bits_here = self.face_masks[right + bits_location];
284                    if bits_here == 0 {
285                        continue;
286                    }
287
288                    let bits_forward = if forward < CS - 1 {
289                        self.face_masks[right + bits_forward_location]
290                    } else {
291                        0
292                    };
293                    let bits_right = if right < CS - 1 {
294                        self.face_masks[right + 1 + bits_location]
295                    } else {
296                        0
297                    };
298                    let right_cs = right * CS;
299
300                    while bits_here != 0 {
301                        let bit_pos = bits_here.trailing_zeros() as usize;
302
303                        bits_here &= !(1 << bit_pos);
304
305                        let v_type =
306                            voxels[get_axis_index::<CS>(axis, right + 1, forward + 1, bit_pos)];
307                        let forward_merge_i = right_cs + (bit_pos - 1);
308                        let right_merged_ref = &mut self.right_merged[bit_pos - 1];
309
310                        if *right_merged_ref == 0
311                            && (bits_forward >> bit_pos & 1) != 0
312                            && v_type
313                                == voxels
314                                    [get_axis_index::<CS>(axis, right + 1, forward + 2, bit_pos)]
315                        {
316                            self.forward_merged[forward_merge_i] += 1;
317                            continue;
318                        }
319
320                        if (bits_right >> bit_pos & 1) != 0
321                            && self.forward_merged[forward_merge_i]
322                                == self.forward_merged[(right_cs + CS) + (bit_pos - 1)]
323                            && v_type
324                                == voxels
325                                    [get_axis_index::<CS>(axis, right + 2, forward + 1, bit_pos)]
326                        {
327                            self.forward_merged[forward_merge_i] = 0;
328                            *right_merged_ref += 1;
329                            continue;
330                        }
331
332                        let mesh_left = right - *right_merged_ref as usize;
333                        let mesh_front = forward - self.forward_merged[forward_merge_i] as usize;
334                        let mesh_up = bit_pos - 1 + (!face & 1);
335
336                        let mesh_width = 1 + *right_merged_ref;
337                        let mesh_length = 1 + self.forward_merged[forward_merge_i];
338
339                        self.forward_merged[forward_merge_i] = 0;
340                        *right_merged_ref = 0;
341
342                        let quad = Quad::pack(
343                            mesh_left + (if face == 4 { mesh_width } else { 0 }) as usize,
344                            mesh_front,
345                            mesh_up,
346                            mesh_width as usize,
347                            mesh_length as usize,
348                            v_type as usize,
349                        );
350                        self.quads[face].push(quad);
351                    }
352                }
353            }
354        }
355    }
356
357    /// Meshes a voxel buffer representing a chunk, using an opaque and transparent mask with 1 u64 per column with 1 bit per voxel in the column,
358    /// signaling if the voxel is opaque or transparent.
359    /// This is ~4x faster than the regular mesh method but requires maintaining 2 masks for each chunk.
360    /// See https://github.com/Inspirateur/binary-greedy-meshing?tab=readme-ov-file#what-to-do-with-mesh_dataquads for using the output
361    pub fn fast_mesh(&mut self, voxels: &[u16], opaque_mask: &[u64], trans_mask: &[u64]) {
362        self.fast_face_culling(voxels, opaque_mask, trans_mask);
363        self.face_merging(voxels);
364    }
365
366    /// Meshes a voxel buffer representing a chunk, using a BTreeSet signaling which voxel values are transparent.
367    /// This is ~4x slower than the fast_mesh method but does not require maintaining 2 masks for each chunk.
368    /// See https://github.com/Inspirateur/binary-greedy-meshing?tab=readme-ov-file#what-to-do-with-mesh_dataquads for using the output
369    pub fn mesh(&mut self, voxels: &[u16], transparents: &BTreeSet<u16>) {
370        self.face_culling(voxels, transparents);
371        self.face_merging(voxels);
372    }
373
374    /// Same as `mesh` but with a level-of-detail controlled by the `lod` parameter.
375    /// The LOD algorithm divides the chunk into cubic windows of size `lod`
376    /// and selects the most common air-exposed voxel to fill that window.
377    ///
378    /// You can save a O(n) check on voxels by providing the `max_voxel_value` if you already have it
379    /// (due to palette compression or equivalent).
380    ///
381    /// If `lod` is 1 (or 0), this is equivalent to calling `mesh`.
382    ///
383    /// *NB: you don't need to use multiples of the chunk size for `lod`. Partial windows are handled properly.*
384    pub fn mesh_lod(
385        &mut self,
386        voxels: &mut [u16],
387        transparents: &BTreeSet<u16>,
388        lod: usize,
389        max_voxel_value: Option<u16>,
390    ) {
391        if lod <= 1 {
392            return self.mesh(voxels, transparents);
393        }
394        let max_v = max_voxel_value.unwrap_or(*voxels.iter().max().unwrap_or(&0));
395        if max_v == 0 {
396            return;
397        }
398        // the lod view is unpadded, padding is only used to check air exposure and is not modified
399        let lod_cs = CS.div_ceil(lod);
400        let lod_view_volume = lod_cs.pow(3);
401        let lod_linearize = |x: usize, y: usize, z: usize| z + x * lod_cs + y * lod_cs * lod_cs;
402        let mut counters = (0..max_v + 1)
403            .map(|_| vec![0; lod_view_volume].into_boxed_slice())
404            .collect::<Vec<_>>();
405        let neighbors = [
406            -(Self::linearize_with_pad(1, 0, 0) as i32),
407            Self::linearize_with_pad(1, 0, 0) as i32,
408            -(Self::linearize_with_pad(0, 1, 0) as i32),
409            Self::linearize_with_pad(0, 1, 0) as i32,
410            -(Self::linearize_with_pad(0, 0, 1) as i32),
411            Self::linearize_with_pad(0, 0, 1) as i32,
412        ];
413        // Step 1: Count the occurrences of each air-exposed voxel in each LOD window
414        for x in 0..CS {
415            for y in 0..CS {
416                for z in 0..CS {
417                    let lod_index = lod_linearize(x / lod, y / lod, z / lod);
418                    let i = pad_linearize::<CS>(x, y, z);
419                    // count total blocks (to handle partial windows)
420                    counters[0][lod_index] += 1;
421                    // count blocks that are exposed to air
422                    if neighbors
423                        .iter()
424                        .any(|&n| voxels.get((i as i32 + n) as usize).copied() == Some(0))
425                    {
426                        // increase the counter for this voxel in the corresponding LOD window
427                        counters[voxels[i] as usize][lod_index] += 1;
428                    }
429                }
430            }
431        }
432        // Step 2: Compute a "winning" voxel for each LOD window based on the counters
433        let mut winning_voxels = vec![0_u16; lod_view_volume].into_boxed_slice();
434        for i in 0..lod_view_volume {
435            let mut max_count = 0;
436            let mut winning_voxel = 0;
437            let mut total_voxel: i32 = 0;
438            // iterate over the counters of non-air voxels
439            for (v, counter_view) in counters.iter().enumerate().skip(1) {
440                total_voxel += counter_view[i];
441                if counter_view[i] > max_count {
442                    max_count = counter_view[i];
443                    winning_voxel = v as u16;
444                }
445            }
446            // Air only wins if it occupies an overwhelming majority of the volume
447            if total_voxel.pow(3) < counters[0][i] {
448                winning_voxel = 0;
449            }
450            winning_voxels[i] = winning_voxel;
451        }
452        // Step 3: fill the voxels buffer with the "winning" blocks for each LOD window
453        // do not touch the padding
454        for x in 0..CS {
455            for y in 0..CS {
456                for z in 0..CS {
457                    voxels[pad_linearize::<CS>(x, y, z)] =
458                        winning_voxels[lod_linearize(x / lod, y / lod, z / lod)];
459                }
460            }
461        }
462        self.mesh(voxels, transparents);
463    }
464
465    /// A linearize function that uses the padded dimension instead of the chunk size.
466    ///
467    /// Used only in LOD calculations to account for the padded chunk dimensions.
468    fn linearize_with_pad(x: usize, y: usize, z: usize) -> usize {
469        z + x * Self::CS_P + y * Self::CS_P2
470    }
471}
472
473#[inline]
474/// v1 is not AIR
475fn face_value(v1: u16, v2: u16, transparents: &BTreeSet<u16>) -> u64 {
476    (v2 == 0 || (v1 != v2 && transparents.contains(&v2))) as u64
477}
478
479#[inline]
480fn get_axis_index<const CS: usize>(axis: usize, a: usize, b: usize, c: usize) -> usize {
481    match axis {
482        0 => b + (a * Mesher::<CS>::CS_P) + (c * Mesher::<CS>::CS_P2),
483        1 => b + (c * Mesher::<CS>::CS_P) + (a * Mesher::<CS>::CS_P2),
484        _ => c + (a * Mesher::<CS>::CS_P) + (b * Mesher::<CS>::CS_P2),
485    }
486}
487
488/// Compute Mesh indices for a given amount of quads
489pub fn indices(num_quads: usize) -> Vec<u32> {
490    // Each quads is made of 2 triangles which require 6 indices
491    // The indices are the same regardless of the face
492    let mut res = Vec::with_capacity(num_quads * 6);
493    for i in 0..num_quads as u32 {
494        res.push((i << 2) | 2);
495        res.push((i << 2) | 0);
496        res.push((i << 2) | 1);
497        res.push((i << 2) | 1);
498        res.push((i << 2) | 3);
499        res.push((i << 2) | 2);
500    }
501    res
502}
503
504/// Encode 3 coordinates into a linear index within the chunk.
505pub fn linearize<const CS: usize>(x: usize, y: usize, z: usize) -> usize {
506    z + x * CS + y * Mesher::<CS>::CS_2
507}
508
509pub fn delinearize<const CS: usize>(index: usize) -> (usize, usize, usize) {
510    let z = index % CS;
511    let x = (index / CS) % CS;
512    let y = index / (CS * CS);
513    (x, y, z)
514}
515
516/// Encode 3 coordinates into a linear index within a padded chunk.
517pub fn pad_linearize<const CS: usize>(x: usize, y: usize, z: usize) -> usize {
518    z + 1 + (x + 1) * Mesher::<CS>::CS_P + (y + 1) * Mesher::<CS>::CS_P2
519}
520
521/// Decode a linear index into 3 coordinates within a padded chunk.
522pub fn pad_de_linearize<const CS: usize>(index: usize) -> (usize, usize, usize) {
523    let z = index % Mesher::<CS>::CS_P - 1;
524    let x = (index / Mesher::<CS>::CS_P) % Mesher::<CS>::CS_P - 1;
525    let y = index / Mesher::<CS>::CS_P2 - 1;
526    (x, y, z)
527}
528
529/// Compute an opacity mask from a voxel buffer and a BTreeSet specifying which voxel values are transparent
530pub fn compute_opaque_mask<const CS: usize>(
531    voxels: &[u16],
532    transparents: &BTreeSet<u16>,
533) -> Box<[u64]> {
534    let mut opaque_mask = vec![0; Mesher::<CS>::CS_P2].into_boxed_slice();
535    // Fill the opacity mask
536    for (i, voxel) in voxels.iter().enumerate() {
537        // If the voxel is transparent we skip it
538        if *voxel == 0 || transparents.contains(voxel) {
539            continue;
540        }
541        let (r, q) = (i / Mesher::<CS>::CS_P, i % Mesher::<CS>::CS_P);
542        opaque_mask[r] |= 1 << q;
543    }
544    opaque_mask
545}
546
547/// Compute a transparent mask from a voxel buffer and a BTreeSet specifying which voxel values are transparent
548pub fn compute_transparent_mask<const CS: usize>(
549    voxels: &[u16],
550    transparents: &BTreeSet<u16>,
551) -> Box<[u64]> {
552    let mut trans_mask = vec![0; Mesher::<CS>::CS_P2].into_boxed_slice();
553    // Fill the opacity mask
554    for (i, voxel) in voxels.iter().enumerate() {
555        // If the voxel is opaque we skip it
556        if *voxel == 0 || !transparents.contains(voxel) {
557            continue;
558        }
559        let (r, q) = (i / Mesher::<CS>::CS_P, i % Mesher::<CS>::CS_P);
560        trans_mask[r] |= 1 << q;
561    }
562    trans_mask
563}
564
565#[cfg(test)]
566mod tests {
567    use crate::{self as bgm};
568    use alloc::{boxed::Box, collections::btree_set::BTreeSet};
569
570    pub const CS: usize = 62;
571
572    /// Show quad output on a simple 2 voxels case
573    #[test]
574    fn test_output() {
575        extern crate std;
576        let mut voxels = [0; bgm::Mesher::<CS>::CS_P3];
577        voxels[bgm::pad_linearize::<CS>(0, 0, 0)] = 1;
578        voxels[bgm::pad_linearize::<CS>(0, 1, 0)] = 1;
579
580        let mut mesher = bgm::Mesher::<CS>::new();
581        let opaque_mask = bgm::compute_opaque_mask::<CS>(&voxels, &BTreeSet::new());
582        let trans_mask = vec![0; bgm::Mesher::<CS>::CS_P2].into_boxed_slice();
583        mesher.fast_mesh(&voxels, &opaque_mask, &trans_mask);
584        // self.quads is the output
585        for (i, quads) in mesher.quads.iter().enumerate() {
586            std::println!("--- Face {i} ---");
587            for &quad in quads {
588                std::println!("{:?}", quad);
589            }
590        }
591    }
592
593    /// Ensures that mesh and fast_mesh return the same results
594    #[test]
595    fn mesh_and_fast_mesh_eq() {
596        let voxels = test_buffer();
597        let transparent_blocks = BTreeSet::from([2]);
598        let opaque_mask = bgm::compute_opaque_mask::<CS>(voxels.as_slice(), &BTreeSet::new());
599        let trans_mask =
600            bgm::compute_transparent_mask::<CS>(voxels.as_slice(), &transparent_blocks);
601        let mut mesher1 = bgm::Mesher::<CS>::new();
602        mesher1.mesh(voxels.as_slice(), &transparent_blocks);
603        let mut mesher2 = bgm::Mesher::<CS>::new();
604        mesher2.fast_mesh(voxels.as_slice(), &opaque_mask, &trans_mask);
605        assert_eq!(mesher1.quads, mesher2.quads);
606    }
607
608    /// Ensures that pad_linearize and pad_de_linearize are consistent with each other.
609    #[test]
610    fn pad_linearize_roundtrip() {
611        for x in 0..CS {
612            for y in 0..CS {
613                for z in 0..CS {
614                    let i = bgm::pad_linearize::<CS>(x, y, z);
615                    let (x_, y_, z_) = bgm::pad_de_linearize::<CS>(i);
616                    assert_eq!((x, y, z), (x_, y_, z_));
617                }
618            }
619        }
620    }
621
622    /// Ensures that linearize and delinearize are consistent with each other.
623    #[test]
624    fn linearize_roundtrip() {
625        for x in 0..CS {
626            for y in 0..CS {
627                for z in 0..CS {
628                    let i = bgm::linearize::<CS>(x, y, z);
629                    let (x_, y_, z_) = bgm::delinearize::<CS>(i);
630                    assert_eq!((x, y, z), (x_, y_, z_));
631                }
632            }
633        }
634    }
635
636    fn test_buffer() -> Box<[u16; bgm::Mesher::<CS>::CS_P3]> {
637        let mut voxels = Box::new([0; bgm::Mesher::<CS>::CS_P3]);
638        for x in 0..CS {
639            for y in 0..CS {
640                for z in 0..CS {
641                    voxels[bgm::pad_linearize::<CS>(x, y, z)] = transparent_sphere(x, y, z);
642                }
643            }
644        }
645        voxels
646    }
647
648    fn transparent_sphere(x: usize, y: usize, z: usize) -> u16 {
649        if x == 8 {
650            2
651        } else if (x as i32 - 31).pow(2) + (y as i32 - 31).pow(2) + (z as i32 - 31).pow(2)
652            < 16 as i32
653        {
654            1
655        } else {
656            0
657        }
658    }
659}