use bevy::asset::RenderAssetUsages;
use bevy::mesh::{Indices, Mesh, MeshVertexAttribute, PrimitiveTopology, VertexFormat};
use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE};
use crate::voxel::{TerrainMaterialId, VoxelType};
pub const ATTRIBUTE_TEXTURE_LAYER: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_TextureLayer", 988540919, VertexFormat::Uint32);
pub const ATTRIBUTE_FACE_EXPOSED: MeshVertexAttribute =
MeshVertexAttribute::new("Vertex_FaceExposed", 988540920, VertexFormat::Float32);
pub(crate) struct FaceDir {
pub axis: usize,
pub positive: bool,
pub u_axis: usize,
pub v_axis: usize,
normal: [f32; 3],
}
pub(crate) const FACE_DIRS: [FaceDir; 6] = [
FaceDir {
axis: 1,
positive: true,
u_axis: 0,
v_axis: 2,
normal: [0.0, 1.0, 0.0],
},
FaceDir {
axis: 1,
positive: false,
u_axis: 0,
v_axis: 2,
normal: [0.0, -1.0, 0.0],
},
FaceDir {
axis: 0,
positive: true,
u_axis: 2,
v_axis: 1,
normal: [1.0, 0.0, 0.0],
},
FaceDir {
axis: 0,
positive: false,
u_axis: 2,
v_axis: 1,
normal: [-1.0, 0.0, 0.0],
},
FaceDir {
axis: 2,
positive: true,
u_axis: 0,
v_axis: 1,
normal: [0.0, 0.0, 1.0],
},
FaceDir {
axis: 2,
positive: false,
u_axis: 0,
v_axis: 1,
normal: [0.0, 0.0, -1.0],
},
];
#[inline]
pub(crate) fn super_voxel<V: VoxelType>(
chunk: &Chunk<V>,
sx: usize,
sy: usize,
sz: usize,
step: usize,
) -> V {
let mut first_visible = V::air();
for dx in 0..step {
for dy in 0..step {
for dz in 0..step {
let x = sx + dx;
let y = sy + dy;
let z = sz + dz;
if x < CHUNK_SIZE && y < CHUNK_SIZE && z < CHUNK_SIZE {
let v = chunk.get(x, y, z);
if v.is_solid() {
return v; }
if first_visible.color()[3] == 0.0 && v.color()[3] > 0.0 {
first_visible = v; }
}
}
}
}
first_visible
}
pub fn generate_chunk_mesh<V: VoxelType>(chunk: &Chunk<V>, step: usize) -> Mesh {
crate::profile_span!("voxel::mesh::greedy");
build_mesh(chunk, step, &default_face_visible::<V>)
}
#[inline]
fn default_face_visible<V: VoxelType>(
chunk: &Chunk<V>,
x: usize,
y: usize,
z: usize,
face: &FaceDir,
step: usize,
) -> bool {
let (nx, ny, nz) = neighbor_coords(x, y, z, face, step);
if nx >= CHUNK_SIZE || ny >= CHUNK_SIZE || nz >= CHUNK_SIZE {
return true;
}
let neighbor = super_voxel(chunk, nx, ny, nz, step);
!neighbor.is_solid() || neighbor.color()[3] < 1.0
}
#[inline]
fn neighbor_coords(
x: usize,
y: usize,
z: usize,
face: &FaceDir,
step: usize,
) -> (usize, usize, usize) {
let mut result = [x, y, z];
if face.positive {
result[face.axis] = result[face.axis].wrapping_add(step);
} else {
result[face.axis] = result[face.axis].wrapping_sub(step);
}
(result[0], result[1], result[2])
}
#[derive(Default)]
pub(crate) struct MeshBuffers {
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
uvs: Vec<[f32; 2]>,
colors: Vec<[f32; 4]>,
texture_layers: Vec<u32>,
exposed: Vec<f32>,
indices: Vec<u32>,
}
impl MeshBuffers {
fn into_mesh(self) -> Mesh {
Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
)
.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, self.positions)
.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, self.normals)
.with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, self.uvs)
.with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, self.colors)
.with_inserted_attribute(ATTRIBUTE_TEXTURE_LAYER, self.texture_layers)
.with_inserted_attribute(ATTRIBUTE_FACE_EXPOSED, self.exposed)
.with_inserted_indices(Indices::U32(self.indices))
}
}
pub(crate) struct Chamfer<'a, V> {
pub width: f32,
pub sample: &'a dyn Fn([i32; 3]) -> Option<V>,
}
const EDGE_LOW_U: u8 = 1;
const EDGE_HIGH_U: u8 = 2;
const EDGE_LOW_V: u8 = 4;
const EDGE_HIGH_V: u8 = 8;
const FACE_EXPOSED: u8 = 16;
type MaskCell<V> = Option<(V, u8, u8)>;
#[inline]
fn is_empty_at<V: VoxelType>(chamfer: &Chamfer<V>, coords: [i32; 3]) -> bool {
(chamfer.sample)(coords).is_some_and(|voxel| voxel.color()[3] <= 0.0)
}
#[inline]
fn is_chamferable<V: VoxelType>(voxel: V) -> bool {
voxel.is_solid() && voxel.color()[3] >= 1.0
}
#[inline]
fn offset(mut coords: [i32; 3], axis: usize, amount: i32) -> [i32; 3] {
coords[axis] += amount;
coords
}
#[inline]
fn is_convex_edge<V: VoxelType>(
chamfer: &Chamfer<V>,
coords: [i32; 3],
(axis_a, sign_a): (usize, i32),
(axis_b, sign_b): (usize, i32),
) -> bool {
(chamfer.sample)(coords).is_some_and(is_chamferable)
&& is_empty_at(chamfer, offset(coords, axis_a, sign_a))
&& is_empty_at(chamfer, offset(coords, axis_b, sign_b))
}
pub(crate) type FaceVisible<'a, V> =
&'a dyn Fn(&Chunk<V>, usize, usize, usize, &FaceDir, usize) -> bool;
pub(crate) fn build_mesh<V: VoxelType>(
chunk: &Chunk<V>,
step: usize,
face_visible: FaceVisible<V>,
) -> Mesh {
build_material_meshes(chunk, step, face_visible, None, &|_| {
TerrainMaterialId::DEFAULT
})
.pop()
.map(|(_, mesh)| mesh)
.unwrap_or_else(|| MeshBuffers::default().into_mesh())
}
pub(crate) fn build_material_meshes<V: VoxelType, K: Copy + Ord>(
chunk: &Chunk<V>,
step: usize,
face_visible: FaceVisible<V>,
chamfer: Option<&Chamfer<V>>,
material_of: &dyn Fn(V) -> K,
) -> Vec<(K, Mesh)> {
let chamfer = chamfer.filter(|chamfer| step == 1 && chamfer.width > 0.0);
let size = CHUNK_SIZE / step;
let mut sections: Vec<(K, MeshBuffers)> = Vec::new();
let mut mask: Vec<MaskCell<V>> = vec![None; size * size];
for (face_index, face) in FACE_DIRS.iter().enumerate() {
for d in 0..size {
build_mask(
chunk,
face,
face_index,
d,
step,
size,
&mut mask,
face_visible,
chamfer,
);
greedy_merge(
chunk,
&mut mask,
size,
face,
face_index,
d,
step,
&mut sections,
material_of,
chamfer,
);
}
}
sections.sort_by_key(|(id, _)| *id);
sections
.into_iter()
.map(|(id, buffers)| (id, buffers.into_mesh()))
.collect()
}
#[allow(clippy::too_many_arguments)] #[inline]
fn build_mask<V: VoxelType>(
chunk: &Chunk<V>,
face: &FaceDir,
face_index: usize,
d: usize,
step: usize,
size: usize,
mask: &mut [MaskCell<V>],
face_visible: FaceVisible<V>,
chamfer: Option<&Chamfer<V>>,
) {
for v in 0..size {
for u in 0..size {
let (x, y, z) = slice_to_chunk(face, d * step, u * step, v * step);
let voxel = super_voxel(chunk, x, y, z, step);
let has_color = voxel.color()[3] > 0.0;
if has_color && face_visible(chunk, x, y, z, face, step) {
let state = chunk.get_state(x, y, z);
let mut edges = chamfer.map_or(0, |chamfer| {
convex_edges(chamfer, face, [x as i32, y as i32, z as i32])
});
if chunk.exposed_faces(x, y, z) & (1 << face_index) != 0 {
edges |= FACE_EXPOSED;
}
mask[v * size + u] = Some((voxel, state, edges));
} else {
mask[v * size + u] = None;
}
}
}
}
fn convex_edges<V: VoxelType>(chamfer: &Chamfer<V>, face: &FaceDir, coords: [i32; 3]) -> u8 {
let front = (face.axis, if face.positive { 1 } else { -1 });
let mut edges = 0;
for (bit, side) in [
(EDGE_LOW_U, (face.u_axis, -1)),
(EDGE_HIGH_U, (face.u_axis, 1)),
(EDGE_LOW_V, (face.v_axis, -1)),
(EDGE_HIGH_V, (face.v_axis, 1)),
] {
if is_convex_edge(chamfer, coords, front, side) {
edges |= bit;
}
}
edges
}
#[inline]
fn slice_to_chunk(face: &FaceDir, d: usize, u: usize, v: usize) -> (usize, usize, usize) {
let mut coords = [0usize; 3];
coords[face.axis] = d;
coords[face.u_axis] = u;
coords[face.v_axis] = v;
(coords[0], coords[1], coords[2])
}
#[allow(clippy::too_many_arguments)] fn greedy_merge<V: VoxelType, K: Copy + Ord>(
chunk: &Chunk<V>,
mask: &mut [MaskCell<V>],
size: usize,
face: &FaceDir,
face_index: usize,
d: usize,
step: usize,
sections: &mut Vec<(K, MeshBuffers)>,
material_of: &dyn Fn(V) -> K,
chamfer: Option<&Chamfer<V>>,
) {
const U_EDGES: u8 = EDGE_LOW_U | EDGE_HIGH_U;
const V_EDGES: u8 = EDGE_LOW_V | EDGE_HIGH_V;
for v in 0..size {
let mut u = 0;
while u < size {
let (voxel, state, first_edges) = match mask[v * size + u] {
Some(entry) => entry,
None => {
u += 1;
continue;
}
};
let mut width = 1;
while u + width < size {
match mask[v * size + u + width] {
Some((next_voxel, next_state, next_edges))
if next_voxel == voxel
&& next_state == state
&& next_edges & (V_EDGES | FACE_EXPOSED)
== first_edges & (V_EDGES | FACE_EXPOSED) =>
{
width += 1;
}
_ => break,
}
}
let last_edges = mask[v * size + u + width - 1].map_or(0, |cell| cell.2);
let mut quad_edges =
(first_edges & (EDGE_LOW_U | V_EDGES)) | (last_edges & EDGE_HIGH_U);
let mut height = 1;
'outer: while v + height < size {
let row = (v + height) * size + u;
let mut row_high_v = None;
for du in 0..width {
let Some((next_voxel, next_state, next_edges)) = mask[row + du] else {
break 'outer;
};
if next_voxel != voxel
|| next_state != state
|| next_edges & FACE_EXPOSED != first_edges & FACE_EXPOSED
{
break 'outer;
}
let mut expected_u = 0;
if du == 0 {
expected_u |= quad_edges & EDGE_LOW_U;
}
if du == width - 1 {
expected_u |= quad_edges & EDGE_HIGH_U;
}
if next_edges & U_EDGES != expected_u {
break 'outer;
}
let high_v = next_edges & EDGE_HIGH_V;
if *row_high_v.get_or_insert(high_v) != high_v {
break 'outer;
}
}
quad_edges = (quad_edges & !EDGE_HIGH_V) | row_high_v.unwrap_or(0);
height += 1;
}
for dv in 0..height {
for du in 0..width {
mask[(v + dv) * size + u + du] = None;
}
}
let material = material_of(voxel);
let section = match sections.iter().position(|(id, _)| *id == material) {
Some(index) => index,
None => {
sections.push((material, MeshBuffers::default()));
sections.len() - 1
}
};
emit_quad(
chunk,
face,
face_index,
d,
u,
v,
width,
height,
step,
voxel,
state,
quad_edges,
chamfer,
&mut sections[section].1,
);
let buffers = &mut sections[section].1;
let exposed = if first_edges & FACE_EXPOSED != 0 {
1.0
} else {
0.0
};
buffers.exposed.resize(buffers.positions.len(), exposed);
u += width;
}
}
}
#[inline]
fn ao_neighbor_solid<V: VoxelType>(chunk: &Chunk<V>, coords: [usize; 3]) -> bool {
if coords[0] >= CHUNK_SIZE || coords[1] >= CHUNK_SIZE || coords[2] >= CHUNK_SIZE {
return false;
}
chunk.get(coords[0], coords[1], coords[2]).is_solid()
}
#[inline]
fn compute_ao(side1: bool, side2: bool, corner: bool) -> f32 {
match side1 as u8 + side2 as u8 + corner as u8 {
0 => 1.0,
1 => 0.8,
2 => 0.6,
_ => 0.4,
}
}
#[inline]
fn vertex_ao<V: VoxelType>(
chunk: &Chunk<V>,
face: &FaceDir,
d_voxel: usize,
cu_voxel: usize,
cv_voxel: usize,
high_u: bool,
high_v: bool,
) -> f32 {
let (own_u, other_u) = if high_u {
(cu_voxel.wrapping_sub(1), cu_voxel)
} else {
(cu_voxel, cu_voxel.wrapping_sub(1))
};
let (own_v, other_v) = if high_v {
(cv_voxel.wrapping_sub(1), cv_voxel)
} else {
(cv_voxel, cv_voxel.wrapping_sub(1))
};
let solid_at = |u: usize, v: usize| {
let mut coords = [0usize; 3];
coords[face.axis] = d_voxel;
coords[face.u_axis] = u;
coords[face.v_axis] = v;
ao_neighbor_solid(chunk, coords)
};
compute_ao(
solid_at(other_u, own_v),
solid_at(own_u, other_v),
solid_at(other_u, other_v),
)
}
#[allow(clippy::too_many_arguments)] #[inline]
fn emit_quad<V: VoxelType>(
chunk: &Chunk<V>,
face: &FaceDir,
face_index: usize,
d: usize,
u: usize,
v: usize,
width: usize,
height: usize,
step: usize,
voxel: V,
state: u8,
edges: u8,
chamfer: Option<&Chamfer<V>>,
out: &mut MeshBuffers,
) {
let MeshBuffers {
positions,
normals,
uvs,
colors,
texture_layers,
indices,
..
} = out;
let s = step as f32 * VOXEL_SIZE;
let d_pos = if face.positive {
(d as f32 + 1.0) * s
} else {
d as f32 * s
};
let ao_depth: usize = if face.positive {
(d + 1) * step
} else {
(d * step).wrapping_sub(1)
};
let u_start = u as f32 * s;
let v_start = v as f32 * s;
let u_end = (u + width) as f32 * s;
let v_end = (v + height) as f32 * s;
let (u0, v0) = (u * step, v * step);
let (u1, v1) = ((u + width) * step, (v + height) * step);
let ao_v0 = vertex_ao(chunk, face, ao_depth, u0, v0, false, false);
let ao_v1 = vertex_ao(chunk, face, ao_depth, u1, v0, true, false);
let ao_v2 = vertex_ao(chunk, face, ao_depth, u1, v1, true, true);
let ao_v3 = vertex_ao(chunk, face, ao_depth, u0, v1, false, true);
let cut = chamfer.map_or(0.0, |chamfer| chamfer.width);
let inset = |bit: u8| if edges & bit != 0 { cut } else { 0.0 };
let face_u = [u_start + inset(EDGE_LOW_U), u_end - inset(EDGE_HIGH_U)];
let face_v = [v_start + inset(EDGE_LOW_V), v_end - inset(EDGE_HIGH_V)];
let corners = [
(face_u[0], face_v[0], ao_v0),
(face_u[1], face_v[0], ao_v1),
(face_u[1], face_v[1], ao_v2),
(face_u[0], face_v[1], ao_v3),
];
let base_idx = positions.len() as u32;
let srgb = voxel.color();
let to_linear = |c: f32| -> f32 {
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
};
let base_color = [
to_linear(srgb[0]),
to_linear(srgb[1]),
to_linear(srgb[2]),
srgb[3],
];
let layer = voxel.texture_layer_for_state(face_index, state);
for &(cu, cv, ao) in &corners {
let mut pos = [0.0f32; 3];
pos[face.axis] = d_pos;
pos[face.u_axis] = cu;
pos[face.v_axis] = cv;
positions.push(pos);
normals.push(face.normal);
colors.push([
base_color[0] * ao,
base_color[1] * ao,
base_color[2] * ao,
base_color[3],
]);
texture_layers.push(layer);
}
let uv_of = |cu: f32, cv: f32| {
[
(cu - u_start) / (u_end - u_start),
(cv - v_start) / (v_end - v_start),
]
};
for &(cu, cv, _) in &corners {
uvs.push(uv_of(cu, cv));
}
let ao_flip = ao_v0 + ao_v2 < ao_v1 + ao_v3;
let ccw = face.positive != (face.axis == 2);
match (ccw, ao_flip) {
(true, false) => {
indices.push(base_idx);
indices.push(base_idx + 2);
indices.push(base_idx + 1);
indices.push(base_idx);
indices.push(base_idx + 3);
indices.push(base_idx + 2);
}
(true, true) => {
indices.push(base_idx);
indices.push(base_idx + 3);
indices.push(base_idx + 1);
indices.push(base_idx + 1);
indices.push(base_idx + 3);
indices.push(base_idx + 2);
}
(false, false) => {
indices.push(base_idx);
indices.push(base_idx + 1);
indices.push(base_idx + 2);
indices.push(base_idx);
indices.push(base_idx + 2);
indices.push(base_idx + 3);
}
(false, true) => {
indices.push(base_idx);
indices.push(base_idx + 1);
indices.push(base_idx + 3);
indices.push(base_idx + 1);
indices.push(base_idx + 2);
indices.push(base_idx + 3);
}
}
let Some(chamfer) = chamfer.filter(|_| edges != 0) else {
return;
};
let sign = if face.positive { 1.0 } else { -1.0 };
let face_sign = if face.positive { 1 } else { -1 };
let point = |cu: f32, cv: f32, depth: f32| {
let mut pos = [0.0f32; 3];
pos[face.axis] = d_pos - sign * depth;
pos[face.u_axis] = cu;
pos[face.v_axis] = cv;
pos
};
let direction = |along_u: f32, along_v: f32, out: f32| {
let mut dir = [0.0f32; 3];
dir[face.axis] = sign * out;
dir[face.u_axis] = along_u;
dir[face.v_axis] = along_v;
dir
};
let ao_at = |high_u: bool, high_v: bool| match (high_u, high_v) {
(false, false) => ao_v0,
(true, false) => ao_v1,
(true, true) => ao_v2,
(false, true) => ao_v3,
};
let color_at = |high_u: bool, high_v: bool| {
let ao = ao_at(high_u, high_v);
[
base_color[0] * ao,
base_color[1] * ao,
base_color[2] * ao,
base_color[3],
]
};
let half = cut * 0.5;
let third = cut * 2.0 / 3.0;
let cell_at = |high_u: bool, high_v: bool| {
let mut coords = [0i32; 3];
coords[face.axis] = d as i32;
coords[face.u_axis] = if high_u { u + width - 1 } else { u } as i32;
coords[face.v_axis] = if high_v { v + height - 1 } else { v } as i32;
coords
};
let mut push = |points: &[[f32; 3]], normal: [f32; 3], vertices: &[([f32; 2], [f32; 4])]| {
push_polygon(
positions,
normals,
uvs,
colors,
texture_layers,
indices,
points,
normal,
vertices,
layer,
);
};
for (high_u, bit) in [(false, EDGE_LOW_U), (true, EDGE_HIGH_U)] {
if edges & bit == 0 {
continue;
}
let (edge_u, inward) = if high_u {
(u_end, -1.0)
} else {
(u_start, 1.0)
};
let cut_u = edge_u + inward * cut;
let mid_u = edge_u + inward * half;
let low = (uv_of(cut_u, face_v[0]), color_at(high_u, false));
let high = (uv_of(cut_u, face_v[1]), color_at(high_u, true));
push(
&[
point(cut_u, face_v[0], 0.0),
point(cut_u, face_v[1], 0.0),
point(mid_u, face_v[1], half),
point(mid_u, face_v[0], half),
],
direction(-inward, 0.0, 1.0),
&[low, high, high, low],
);
for (high_v, end_bit) in [(false, EDGE_LOW_V), (true, EDGE_HIGH_V)] {
let (edge_v, inward_v) = if high_v {
(v_end, -1.0)
} else {
(v_start, 1.0)
};
let vertex = (
uv_of(cut_u, if high_v { face_v[1] } else { face_v[0] }),
color_at(high_u, high_v),
);
if edges & end_bit != 0 {
push(
&[
point(cut_u, edge_v + inward_v * cut, 0.0),
point(mid_u, edge_v + inward_v * cut, half),
point(edge_u + inward * third, edge_v + inward_v * third, third),
point(cut_u, edge_v + inward_v * half, half),
],
direction(-inward, -inward_v, 1.0),
&[vertex; 4],
);
} else {
let beyond = offset(
cell_at(high_u, high_v),
face.v_axis,
if high_v { 1 } else { -1 },
);
let continues = is_convex_edge(
chamfer,
beyond,
(face.axis, face_sign),
(face.u_axis, if high_u { 1 } else { -1 }),
);
if !continues {
push(
&[
point(edge_u, edge_v, 0.0),
point(cut_u, edge_v, 0.0),
point(mid_u, edge_v, half),
],
direction(0.0, inward_v, 0.0),
&[vertex; 3],
);
}
}
}
}
for (high_v, bit) in [(false, EDGE_LOW_V), (true, EDGE_HIGH_V)] {
if edges & bit == 0 {
continue;
}
let (edge_v, inward) = if high_v {
(v_end, -1.0)
} else {
(v_start, 1.0)
};
let cut_v = edge_v + inward * cut;
let mid_v = edge_v + inward * half;
let low = (uv_of(face_u[0], cut_v), color_at(false, high_v));
let high = (uv_of(face_u[1], cut_v), color_at(true, high_v));
push(
&[
point(face_u[0], cut_v, 0.0),
point(face_u[1], cut_v, 0.0),
point(face_u[1], mid_v, half),
point(face_u[0], mid_v, half),
],
direction(0.0, -inward, 1.0),
&[low, high, high, low],
);
for (high_u, end_bit) in [(false, EDGE_LOW_U), (true, EDGE_HIGH_U)] {
if edges & end_bit != 0 {
continue; }
let (edge_u, inward_u) = if high_u {
(u_end, -1.0)
} else {
(u_start, 1.0)
};
let beyond = offset(
cell_at(high_u, high_v),
face.u_axis,
if high_u { 1 } else { -1 },
);
let continues = is_convex_edge(
chamfer,
beyond,
(face.axis, face_sign),
(face.v_axis, if high_v { 1 } else { -1 }),
);
if !continues {
let vertex = (uv_of(edge_u, cut_v), color_at(high_u, high_v));
push(
&[
point(edge_u, edge_v, 0.0),
point(edge_u, cut_v, 0.0),
point(edge_u, mid_v, half),
],
direction(inward_u, 0.0, 0.0),
&[vertex; 3],
);
}
}
}
}
#[allow(clippy::too_many_arguments)] fn push_polygon(
positions: &mut Vec<[f32; 3]>,
normals: &mut Vec<[f32; 3]>,
uvs: &mut Vec<[f32; 2]>,
colors: &mut Vec<[f32; 4]>,
texture_layers: &mut Vec<u32>,
indices: &mut Vec<u32>,
points: &[[f32; 3]],
normal: [f32; 3],
vertices: &[([f32; 2], [f32; 4])],
layer: u32,
) {
let sub = |a: [f32; 3], b: [f32; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
let ab = sub(points[1], points[0]);
let ac = sub(points[2], points[0]);
let cross = [
ab[1] * ac[2] - ab[2] * ac[1],
ab[2] * ac[0] - ab[0] * ac[2],
ab[0] * ac[1] - ab[1] * ac[0],
];
let facing = cross[0] * normal[0] + cross[1] * normal[1] + cross[2] * normal[2];
let length = (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
let unit = [normal[0] / length, normal[1] / length, normal[2] / length];
let base = positions.len() as u32;
for (point, (uv, color)) in points.iter().zip(vertices) {
positions.push(*point);
normals.push(unit);
uvs.push(*uv);
colors.push(*color);
texture_layers.push(layer);
}
for i in 1..points.len() as u32 - 1 {
if facing >= 0.0 {
indices.extend([base, base + i, base + i + 1]);
} else {
indices.extend([base, base + i + 1, base + i]);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::voxel::DefaultVoxel;
use bevy::mesh::VertexAttributeValues;
fn vertex_count(mesh: &Mesh) -> usize {
match mesh.attribute(Mesh::ATTRIBUTE_POSITION).expect("positions") {
VertexAttributeValues::Float32x3(v) => v.len(),
_ => panic!("unexpected attribute type"),
}
}
fn index_count(mesh: &Mesh) -> usize {
match mesh.indices().expect("indices") {
Indices::U32(idx) => idx.len(),
_ => panic!("expected U32 indices"),
}
}
fn quad_ao(mesh: &Mesh, normal: [f32; 3], plane: f32) -> Vec<f32> {
let axis = normal.iter().position(|n| *n != 0.0).expect("axis normal");
let Some(VertexAttributeValues::Float32x3(positions)) =
mesh.attribute(Mesh::ATTRIBUTE_POSITION)
else {
panic!("positions");
};
let Some(VertexAttributeValues::Float32x3(normals)) =
mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
else {
panic!("normals");
};
let Some(VertexAttributeValues::Float32x4(colors)) = mesh.attribute(Mesh::ATTRIBUTE_COLOR)
else {
panic!("colors");
};
let brightest = colors.iter().map(|c| c[0]).fold(0.0f32, f32::max);
let mut ao: Vec<f32> = (0..positions.len())
.filter(|&i| normals[i] == normal && positions[i][axis] == plane)
.map(|i| (colors[i][0] / brightest * 10.0).round() / 10.0)
.collect();
assert_eq!(ao.len(), 4, "expected exactly one quad on that plane");
ao.sort_by(f32::total_cmp);
ao
}
fn voxel_with_occluder(occluder: [usize; 3]) -> Chunk<DefaultVoxel> {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
chunk.set(occluder[0], occluder[1], occluder[2], DefaultVoxel::Rock);
chunk
}
#[test]
fn a_voxel_beside_a_face_darkens_the_two_vertices_on_that_edge() {
let cases: [([f32; 3], f32, [usize; 3]); 12] = [
([0.0, 1.0, 0.0], 6.0, [6, 6, 5]),
([0.0, 1.0, 0.0], 6.0, [4, 6, 5]),
([0.0, 1.0, 0.0], 6.0, [5, 6, 6]),
([0.0, 1.0, 0.0], 6.0, [5, 6, 4]),
([0.0, -1.0, 0.0], 5.0, [6, 4, 5]),
([0.0, -1.0, 0.0], 5.0, [5, 4, 4]),
([1.0, 0.0, 0.0], 6.0, [6, 6, 5]),
([1.0, 0.0, 0.0], 6.0, [6, 5, 4]),
([-1.0, 0.0, 0.0], 5.0, [4, 6, 5]),
([-1.0, 0.0, 0.0], 5.0, [4, 5, 6]),
([0.0, 0.0, 1.0], 6.0, [6, 5, 6]),
([0.0, 0.0, -1.0], 5.0, [5, 4, 4]),
];
for (normal, plane, occluder) in cases {
let mesh = generate_chunk_mesh(&voxel_with_occluder(occluder), 1);
assert_eq!(
quad_ao(&mesh, normal, plane),
vec![0.8, 0.8, 1.0, 1.0],
"normal {normal:?}, occluder {occluder:?}"
);
}
}
#[test]
fn a_voxel_diagonal_to_a_face_darkens_only_the_vertex_at_that_corner() {
let cases: [([f32; 3], f32, [usize; 3]); 8] = [
([0.0, 1.0, 0.0], 6.0, [4, 6, 4]),
([0.0, 1.0, 0.0], 6.0, [6, 6, 4]),
([0.0, 1.0, 0.0], 6.0, [6, 6, 6]),
([0.0, 1.0, 0.0], 6.0, [4, 6, 6]),
([0.0, -1.0, 0.0], 5.0, [6, 4, 6]),
([-1.0, 0.0, 0.0], 5.0, [4, 6, 6]),
([1.0, 0.0, 0.0], 6.0, [6, 4, 4]),
([0.0, 0.0, -1.0], 5.0, [6, 6, 4]),
];
for (normal, plane, occluder) in cases {
let mesh = generate_chunk_mesh(&voxel_with_occluder(occluder), 1);
assert_eq!(
quad_ao(&mesh, normal, plane),
vec![0.8, 1.0, 1.0, 1.0],
"normal {normal:?}, occluder {occluder:?}"
);
}
}
#[test]
fn a_lone_voxel_has_no_ambient_occlusion() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
let mesh = generate_chunk_mesh(&chunk, 1);
for (normal, plane) in [
([0.0, 1.0, 0.0], 6.0),
([0.0, -1.0, 0.0], 5.0),
([1.0, 0.0, 0.0], 6.0),
([-1.0, 0.0, 0.0], 5.0),
([0.0, 0.0, 1.0], 6.0),
([0.0, 0.0, -1.0], 5.0),
] {
assert_eq!(quad_ao(&mesh, normal, plane), vec![1.0; 4]);
}
}
#[test]
fn empty_chunk_produces_empty_mesh() {
let chunk = Chunk::<DefaultVoxel>::new();
let mesh = generate_chunk_mesh(&chunk, 1);
assert_eq!(
vertex_count(&mesh),
0,
"empty chunk should produce 0 vertices"
);
}
#[test]
fn fully_solid_chunk_produces_six_quads() {
let mut chunk = Chunk::<DefaultVoxel>::new();
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
chunk.set(x, y, z, DefaultVoxel::Rock);
}
}
}
let mesh = generate_chunk_mesh(&chunk, 1);
assert_eq!(
vertex_count(&mesh),
24,
"fully solid chunk should have 24 vertices (4 per face x 6 faces)"
);
assert_eq!(
index_count(&mesh),
36,
"fully solid chunk should have 36 indices (6 per face x 6 faces)"
);
}
#[test]
fn single_voxel_produces_six_faces() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(0, 0, 0, DefaultVoxel::Rock);
let mesh = generate_chunk_mesh(&chunk, 1);
assert_eq!(
vertex_count(&mesh),
24,
"single voxel should have 24 vertices (4 per face x 6 faces)"
);
assert_eq!(
index_count(&mesh),
36,
"single voxel should have 36 indices (6 per face x 6 faces)"
);
}
#[test]
fn lod_mesh_has_fewer_vertices() {
let mut chunk = Chunk::<DefaultVoxel>::new();
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
if (x + y + z) % 2 == 0 {
chunk.set(x, y, z, DefaultVoxel::Rock);
} else {
chunk.set(x, y, z, DefaultVoxel::IronOre);
}
}
}
}
let mesh_lod0 = generate_chunk_mesh(&chunk, 1);
let mesh_lod1 = generate_chunk_mesh(&chunk, 2);
let count_lod0 = vertex_count(&mesh_lod0);
let count_lod1 = vertex_count(&mesh_lod1);
assert!(
count_lod1 < count_lod0,
"LOD 1 ({count_lod1} verts) should have fewer vertices than LOD 0 ({count_lod0} verts)"
);
}
}