use bevy::prelude::*;
use bevy::render::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use bevy::render::render_asset::RenderAssetUsages;
mod cube;
pub use cube::*;
mod marching_cubes_tri_table;
use marching_cubes_tri_table::MARCHING_CUBES_TRI_TABLE;
const EDGE_CONNECTIONS: [[usize; 2]; 12] = [
[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7], ];
const ISOVALUE_STEP: f32 = 0.005;
pub struct VolumetricPlugin;
impl Plugin for VolumetricPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(CubePlugin);
app.insert_resource(VolumetricUiState::default());
app.init_resource::<VolumetricIsosurfaceResources>();
app.add_systems(Startup, setup_volumetric_renderer);
app.add_systems(Update, create_or_update_isosurface);
app.add_systems(Update, cleanup_isosurface_on_disable);
app.add_systems(Update, isosurface_controls_system);
app.add_systems(Update, toggle_isosurface_visibility);
}
}
#[derive(Resource, Default)]
pub struct VolumetricIsosurfaceResources {
pub created: bool,
pub pos_entity: Option<Entity>,
pub pos_mesh_handle: Option<Handle<Mesh>>,
pub pos_material_handle: Option<Handle<StandardMaterial>>,
pub neg_entity: Option<Entity>,
pub neg_mesh_handle: Option<Handle<Mesh>>,
pub neg_material_handle: Option<Handle<StandardMaterial>>,
pub last_isovalue: Option<f32>,
pub last_smooth_normals: Option<bool>,
}
#[derive(Resource)]
pub struct VolumetricUiState {
pub enabled: bool,
}
impl Default for VolumetricUiState {
fn default() -> Self {
VolumetricUiState { enabled: true }
}
}
fn setup_volumetric_renderer(mut commands: Commands) {
commands.spawn((
Name::new("Volumetric Isosurface Renderer"),
VolumetricRenderer::default(),
));
info!("Volumetric renderer entity created (spawned at startup)");
}
fn isosurface_controls_system(
keyboard: Res<ButtonInput<KeyCode>>,
mut query: Query<&mut VolumetricRenderer>,
) {
if query.is_empty() {
return;
}
for mut r in query.iter_mut() {
if keyboard.just_pressed(KeyCode::KeyJ) {
r.isovalue = (r.isovalue - ISOVALUE_STEP).max(0.0);
info!("Isovalue decreased to {:.4}", r.isovalue);
}
if keyboard.just_pressed(KeyCode::KeyK) {
r.isovalue += ISOVALUE_STEP;
info!("Isovalue increased to {:.4}", r.isovalue);
}
if keyboard.just_pressed(KeyCode::KeyY) {
r.smooth_normals = !r.smooth_normals;
info!(
"Normal smoothing: {}",
if r.smooth_normals { "smooth" } else { "flat" }
);
}
if r.isovalue < 0.0 {
r.isovalue = 0.0;
}
}
}
fn toggle_isosurface_visibility(
keyboard: Res<ButtonInput<KeyCode>>,
iso_res: Res<VolumetricIsosurfaceResources>,
mut query: Query<&mut Visibility>,
) {
if keyboard.just_pressed(KeyCode::KeyV) {
let mut toggled = false;
if let Some(entity) = iso_res.pos_entity {
if let Ok(mut visibility) = query.get_mut(entity) {
*visibility = match *visibility {
Visibility::Visible => Visibility::Hidden,
_ => Visibility::Visible,
};
toggled = true;
}
}
if let Some(entity) = iso_res.neg_entity {
if let Ok(mut visibility) = query.get_mut(entity) {
*visibility = match *visibility {
Visibility::Visible => Visibility::Hidden,
_ => Visibility::Visible,
};
}
}
if toggled {
if let Some(entity) = iso_res.pos_entity {
if let Ok(visibility) = query.get(entity) {
match *visibility {
Visibility::Visible => info!("Isosurfaces visible"),
_ => info!("Isosurfaces hidden"),
}
}
}
}
}
}
fn create_or_update_isosurface(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut iso_res: ResMut<VolumetricIsosurfaceResources>,
vol_query: Query<&VolumetricRenderer>,
maybe_data: Option<Res<VolumetricData>>,
ui_state: Res<VolumetricUiState>,
) {
if !ui_state.enabled {
return;
}
let data = match maybe_data {
Some(d) => d,
None => return,
};
if vol_query.is_empty() {
return;
}
let renderer = vol_query.iter().next().unwrap();
let target_iso = renderer.isovalue.abs();
let smooth = renderer.smooth_normals;
let need_mesh_update = match (iso_res.last_isovalue, iso_res.last_smooth_normals) {
(Some(prev_iso), Some(prev_smooth)) => {
(prev_iso - target_iso).abs() > std::f32::EPSILON || prev_smooth != smooth
}
_ => true,
};
if !need_mesh_update && iso_res.created {
return;
}
let mesh_pos = if smooth {
generate_isosurface_mesh_smooth(&data, target_iso)
} else {
generate_isosurface_mesh_flat(&data, target_iso)
};
let mesh_neg = if smooth {
generate_isosurface_mesh_smooth(&data, -target_iso)
} else {
generate_isosurface_mesh_flat(&data, -target_iso)
};
let mat_pos = StandardMaterial {
base_color: Color::srgba(
renderer.positive_color.x,
renderer.positive_color.y,
renderer.positive_color.z,
1.0, ),
unlit: false,
perceptual_roughness: 0.3,
metallic: 0.3,
alpha_mode: AlphaMode::Opaque,
cull_mode: None,
double_sided: true,
..Default::default()
};
let mat_neg = StandardMaterial {
base_color: Color::srgba(
renderer.negative_color.x,
renderer.negative_color.y,
renderer.negative_color.z,
1.0, ),
unlit: false,
perceptual_roughness: 0.3,
metallic: 0.3,
alpha_mode: AlphaMode::Opaque,
cull_mode: None,
double_sided: true,
..Default::default()
};
if !iso_res.created {
let mesh_handle_pos = meshes.add(mesh_pos);
let mesh_handle_neg = meshes.add(mesh_neg);
let mat_handle_pos = materials.add(mat_pos);
let mat_handle_neg = materials.add(mat_neg);
let pos_ent = commands
.spawn((
Mesh3d(mesh_handle_pos.clone()),
MeshMaterial3d(mat_handle_pos.clone()),
Name::new("Isosurface +"),
Transform::from_translation(data.origin),
Visibility::Visible,
))
.id();
let neg_ent = commands
.spawn((
Mesh3d(mesh_handle_neg.clone()),
MeshMaterial3d(mat_handle_neg.clone()),
Name::new("Isosurface -"),
Transform::from_translation(data.origin),
Visibility::Visible,
))
.id();
iso_res.created = true;
iso_res.pos_entity = Some(pos_ent);
iso_res.neg_entity = Some(neg_ent);
iso_res.pos_mesh_handle = Some(mesh_handle_pos);
iso_res.neg_mesh_handle = Some(mesh_handle_neg);
iso_res.pos_material_handle = Some(mat_handle_pos);
iso_res.neg_material_handle = Some(mat_handle_neg);
iso_res.last_isovalue = Some(target_iso);
iso_res.last_smooth_normals = Some(smooth);
info!(
"Spawned opaque ± isosurfaces for isovalue {:.4} ({})",
target_iso,
if smooth { "smooth" } else { "flat" }
);
} else {
if let Some(mesh_handle_pos) = &iso_res.pos_mesh_handle {
if let Some(existing) = meshes.get_mut(mesh_handle_pos) {
*existing = mesh_pos;
info!(
"Updated positive isosurface mesh for isovalue {:.4}",
target_iso
);
} else {
let new_handle = meshes.add(mesh_pos);
iso_res.pos_mesh_handle = Some(new_handle.clone());
if let Some(ent) = iso_res.pos_entity {
commands.entity(ent).insert(Mesh3d(new_handle));
}
info!("Replaced positive mesh asset handle");
}
} else {
let new_handle = meshes.add(mesh_pos);
iso_res.pos_mesh_handle = Some(new_handle.clone());
if let Some(ent) = iso_res.pos_entity {
commands.entity(ent).insert(Mesh3d(new_handle));
}
info!("Attached positive mesh handle to existing entity");
}
if let Some(mesh_handle_neg) = &iso_res.neg_mesh_handle {
if let Some(existing) = meshes.get_mut(mesh_handle_neg) {
*existing = mesh_neg;
info!(
"Updated negative isosurface mesh for isovalue {:.4}",
target_iso
);
} else {
let new_handle = meshes.add(mesh_neg);
iso_res.neg_mesh_handle = Some(new_handle.clone());
if let Some(ent) = iso_res.neg_entity {
commands.entity(ent).insert(Mesh3d(new_handle));
}
info!("Replaced negative mesh asset handle");
}
} else {
let new_handle = meshes.add(mesh_neg);
iso_res.neg_mesh_handle = Some(new_handle.clone());
if let Some(ent) = iso_res.neg_entity {
commands.entity(ent).insert(Mesh3d(new_handle));
}
info!("Attached negative mesh handle to existing entity");
}
let mat_handle_pos = materials.add(mat_pos);
let mat_handle_neg = materials.add(mat_neg);
iso_res.pos_material_handle = Some(mat_handle_pos.clone());
iso_res.neg_material_handle = Some(mat_handle_neg.clone());
if let Some(ent) = iso_res.pos_entity {
commands.entity(ent).insert(MeshMaterial3d(mat_handle_pos));
}
if let Some(ent) = iso_res.neg_entity {
commands.entity(ent).insert(MeshMaterial3d(mat_handle_neg));
}
iso_res.last_isovalue = Some(target_iso);
iso_res.last_smooth_normals = Some(smooth);
}
}
fn cleanup_isosurface_on_disable(
mut commands: Commands,
mut iso_res: ResMut<VolumetricIsosurfaceResources>,
ui_state: Res<VolumetricUiState>,
) {
if ui_state.enabled {
return;
}
if !iso_res.created {
return;
}
if let Some(ent) = iso_res.pos_entity.take() {
commands.entity(ent).despawn_recursive();
}
if let Some(ent) = iso_res.neg_entity.take() {
commands.entity(ent).despawn_recursive();
}
iso_res.pos_mesh_handle = None;
iso_res.neg_mesh_handle = None;
iso_res.pos_material_handle = None;
iso_res.neg_material_handle = None;
iso_res.last_isovalue = None;
iso_res.last_smooth_normals = None;
iso_res.created = false;
info!("Cleaned up isosurfaces due to UI disable");
}
fn fix_winding_and_normals(mesh: &mut Mesh, voxel_basis: [Vec3; 3]) {
let a = Mat3::from_cols(voxel_basis[0], voxel_basis[1], voxel_basis[2]);
let is_left_handed = a.determinant() < 0.0;
let should_flip_winding = !is_left_handed;
if should_flip_winding {
if let Some(Indices::U32(idx)) = mesh.indices_mut() {
for tri in idx.chunks_exact_mut(3) {
tri.swap(1, 2); }
}
if let Some(VertexAttributeValues::Float32x3(nrm)) =
mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL)
{
for v in nrm.iter_mut() {
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
}
}
}
fn smooth_mesh_positions(mesh: &mut Mesh, iterations: usize, lambda: f32) {
let positions_data = mesh.attribute(Mesh::ATTRIBUTE_POSITION).cloned();
let indices_data = mesh.indices().cloned();
let Some(VertexAttributeValues::Float32x3(positions_vec)) = positions_data else {
return;
};
let Some(Indices::U32(indices_vec)) = indices_data else {
return;
};
let mut verts: Vec<Vec3> = positions_vec
.iter()
.map(|p| Vec3::new(p[0], p[1], p[2]))
.collect();
let mut neighbors: Vec<Vec<usize>> = vec![Vec::new(); verts.len()];
for tri in indices_vec.chunks(3) {
let i0 = tri[0] as usize;
let i1 = tri[1] as usize;
let i2 = tri[2] as usize;
neighbors[i0].push(i1);
neighbors[i0].push(i2);
neighbors[i1].push(i0);
neighbors[i1].push(i2);
neighbors[i2].push(i0);
neighbors[i2].push(i1);
}
for neighbor_list in neighbors.iter_mut() {
neighbor_list.sort_unstable();
neighbor_list.dedup();
}
for _ in 0..iterations {
let mut new_verts = verts.clone();
for (i, v) in verts.iter().enumerate() {
if neighbors[i].is_empty() {
continue; }
let avg_neighbor: Vec3 =
neighbors[i].iter().map(|&j| verts[j]).sum::<Vec3>() / neighbors[i].len() as f32;
new_verts[i] = v.lerp(avg_neighbor, lambda);
}
verts = new_verts;
}
let smoothed_positions: Vec<[f32; 3]> = verts.into_iter().map(|v| [v.x, v.y, v.z]).collect();
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, smoothed_positions);
}
fn generate_isosurface_mesh_smooth(data: &VolumetricData, isovalue: f32) -> Mesh {
let nx = data.dimensions.x as usize;
let ny = data.dimensions.y as usize;
let nz = data.dimensions.z as usize;
if nx < 2 || ny < 2 || nz < 2 {
return Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
}
let mut positions: Vec<[f32; 3]> = Vec::new();
let mut normals_accum: Vec<Vec3> = Vec::new(); let mut uvs: Vec<[f32; 2]> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
let mut vert_map: std::collections::HashMap<(i64, i64, i64), u32> =
std::collections::HashMap::new();
let get_val = |x: usize, y: usize, z: usize| -> f32 { data.get_voxel_unchecked(x, y, z) };
let quantize = |v: Vec3, tol: f32| -> (i64, i64, i64) {
let qx = (v.x / tol).round() as i64;
let qy = (v.y / tol).round() as i64;
let qz = (v.z / tol).round() as i64;
(qx, qy, qz)
};
let min_voxel_len = data
.voxel_vectors
.iter()
.map(|v| v.length())
.fold(f32::INFINITY, f32::min)
.max(1e-6);
let tol = (min_voxel_len * 1e-3).max(1e-6);
for z in 0..(nz - 1) {
for y in 0..(ny - 1) {
for x in 0..(nx - 1) {
let corners = [
(x, y, z),
(x + 1, y, z),
(x + 1, y + 1, z),
(x, y + 1, z),
(x, y, z + 1),
(x + 1, y, z + 1),
(x + 1, y + 1, z + 1),
(x, y + 1, z + 1),
];
let mut corner_vals = [0.0f32; 8];
let mut corner_pos = [Vec3::ZERO; 8];
for (i, &(cx, cy, cz)) in corners.iter().enumerate() {
corner_vals[i] = get_val(cx, cy, cz);
corner_pos[i] = data.voxel_to_world(cx, cy, cz);
}
let mut cube_index: usize = 0;
for i in 0..8 {
if corner_vals[i] < isovalue {
cube_index |= 1 << i;
}
}
let tri_entry = &MARCHING_CUBES_TRI_TABLE[cube_index];
if tri_entry[0] == -1 {
continue;
}
let mut idx_table = 0;
while idx_table < 16 {
let e0 = tri_entry[idx_table];
if e0 == -1 {
break;
}
let e1 = tri_entry[idx_table + 1];
let e2 = tri_entry[idx_table + 2];
if e1 == -1 || e2 == -1 {
break;
}
let v0 = interpolate_edge(&corner_pos, &corner_vals, e0 as usize, isovalue);
let v1 = interpolate_edge(&corner_pos, &corner_vals, e1 as usize, isovalue);
let v2 = interpolate_edge(&corner_pos, &corner_vals, e2 as usize, isovalue);
let tri_n = (v1 - v0).cross(v2 - v0).normalize_or_zero();
let (a, b, c, n_final) = (v0, v1, v2, tri_n);
let verts = [a, b, c];
for v in verts.iter() {
let local = Vec3::new(
v.x - data.origin.x,
v.y - data.origin.y,
v.z - data.origin.z,
);
let key = quantize(local, tol);
let vi = if let Some(&existing_idx) = vert_map.get(&key) {
existing_idx
} else {
let new_idx = positions.len() as u32;
positions.push([local.x, local.y, local.z]);
normals_accum.push(Vec3::ZERO);
uvs.push([0.0, 0.0]); vert_map.insert(key, new_idx);
new_idx
};
indices.push(vi);
if let Some(acc) = normals_accum.get_mut(vi as usize) {
*acc += n_final;
}
}
idx_table += 3;
}
}
}
}
let mut final_normals: Vec<[f32; 3]> = Vec::with_capacity(normals_accum.len());
for acc in normals_accum.iter() {
let n = acc.normalize_or_zero();
final_normals.push([n.x, n.y, n.z]);
}
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
if !positions.is_empty() && !indices.is_empty() {
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, final_normals);
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
mesh.insert_indices(Indices::U32(indices));
}
fix_winding_and_normals(&mut mesh, data.voxel_vectors);
smooth_mesh_positions(&mut mesh, 3, 0.5);
mesh
}
fn generate_isosurface_mesh_flat(data: &VolumetricData, isovalue: f32) -> Mesh {
let nx = data.dimensions.x as usize;
let ny = data.dimensions.y as usize;
let nz = data.dimensions.z as usize;
if nx < 2 || ny < 2 || nz < 2 {
return Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
}
let mut positions: Vec<[f32; 3]> = Vec::new();
let mut normals: Vec<[f32; 3]> = Vec::new();
let mut uvs: Vec<[f32; 2]> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
let get_val = |x: usize, y: usize, z: usize| -> f32 { data.get_voxel_unchecked(x, y, z) };
let _min_voxel_len = data
.voxel_vectors
.iter()
.map(|v| v.length())
.fold(f32::INFINITY, f32::min)
.max(1e-6);
for z in 0..(nz - 1) {
for y in 0..(ny - 1) {
for x in 0..(nx - 1) {
let corners = [
(x, y, z),
(x + 1, y, z),
(x + 1, y + 1, z),
(x, y + 1, z),
(x, y, z + 1),
(x + 1, y, z + 1),
(x + 1, y + 1, z + 1),
(x, y + 1, z + 1),
];
let mut corner_vals = [0.0f32; 8];
let mut corner_pos = [Vec3::ZERO; 8];
for (i, &(cx, cy, cz)) in corners.iter().enumerate() {
corner_vals[i] = get_val(cx, cy, cz);
corner_pos[i] = data.voxel_to_world(cx, cy, cz);
}
let mut cube_index: usize = 0;
for i in 0..8 {
if corner_vals[i] < isovalue {
cube_index |= 1 << i;
}
}
let tri_entry = &MARCHING_CUBES_TRI_TABLE[cube_index];
if tri_entry[0] == -1 {
continue;
}
let mut idx = 0;
while idx < 16 {
let e0 = tri_entry[idx];
if e0 == -1 {
break;
}
let e1 = tri_entry[idx + 1];
let e2 = tri_entry[idx + 2];
if e1 == -1 || e2 == -1 {
break;
}
let v0 = interpolate_edge(&corner_pos, &corner_vals, e0 as usize, isovalue);
let v1 = interpolate_edge(&corner_pos, &corner_vals, e1 as usize, isovalue);
let v2 = interpolate_edge(&corner_pos, &corner_vals, e2 as usize, isovalue);
let tri_n = (v1 - v0).cross(v2 - v0).normalize_or_zero();
let (a, b, c, n_final) = (v0, v1, v2, tri_n);
let base_idx = positions.len() as u32;
positions.push([
a.x - data.origin.x,
a.y - data.origin.y,
a.z - data.origin.z,
]);
positions.push([
b.x - data.origin.x,
b.y - data.origin.y,
b.z - data.origin.z,
]);
positions.push([
c.x - data.origin.x,
c.y - data.origin.y,
c.z - data.origin.z,
]);
normals.push([n_final.x, n_final.y, n_final.z]);
normals.push([n_final.x, n_final.y, n_final.z]);
normals.push([n_final.x, n_final.y, n_final.z]);
uvs.push([0.0, 0.0]);
uvs.push([0.5, 0.0]);
uvs.push([1.0, 1.0]);
indices.push(base_idx);
indices.push(base_idx + 1);
indices.push(base_idx + 2);
idx += 3;
}
}
}
}
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
);
if !positions.is_empty() && !indices.is_empty() {
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
mesh.insert_indices(Indices::U32(indices));
}
fix_winding_and_normals(&mut mesh, data.voxel_vectors);
mesh
}
fn interpolate_edge(
corner_pos: &[Vec3; 8],
corner_val: &[f32; 8],
edge_idx: usize,
iso: f32,
) -> Vec3 {
let pair = EDGE_CONNECTIONS[edge_idx];
let a = pair[0];
let b = pair[1];
let va = corner_val[a];
let vb = corner_val[b];
let pa = corner_pos[a];
let pb = corner_pos[b];
if (iso - va).abs() < std::f32::EPSILON {
return pa;
}
if (iso - vb).abs() < std::f32::EPSILON {
return pb;
}
if (va - vb).abs() < std::f32::EPSILON {
return pa;
}
let t = (iso - va) / (vb - va);
pa + (pb - pa) * t
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_interpolate_edge_midpoint() {
let p0 = Vec3::new(0.0, 0.0, 0.0);
let p1 = Vec3::new(1.0, 0.0, 0.0);
let mut corner_pos = [Vec3::ZERO; 8];
corner_pos[0] = p0;
corner_pos[1] = p1;
let mut corner_val = [0.0f32; 8];
corner_val[0] = -1.0;
corner_val[1] = 1.0;
let v = interpolate_edge(&corner_pos, &corner_val, 0, 0.0);
assert!((v - Vec3::new(0.5, 0.0, 0.0)).length() < 1e-6);
}
}