refactor: Splitting into crates

This commit is contained in:
2026-11-15 20:36:43 +01:00
parent c13a04c8e2
commit 828806fbc8
68 changed files with 929 additions and 330 deletions
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "vxls"
version = "0.1.0"
edition = "2024"
[dependencies]
vxls-bvh = { path = "../vxls-bvh" }
vxls-gpu = { path = "../vxls-gpu" }
vxls-production = { path = "../vxls-production" }
vxls-profiler = { path = "../vxls-profiler" }
vxls-terrain = { path = "../vxls-terrain" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
bytemuck.workspace = true
crevice.workspace = true
egui.workspace = true
egui-wgpu.workspace = true
egui-winit.workspace = true
egui_ltreeview.workspace = true
egui_plot.workspace = true
env_logger.workspace = true
fastapprox.workspace = true
glam.workspace = true
image.workspace = true
indicatif.workspace = true
itertools.workspace = true
noise.workspace = true
pollster.workspace = true
rand.workspace = true
rayon.workspace = true
tiff.workspace = true
wgpu.workspace = true
winit.workspace = true
+120
View File
@@ -0,0 +1,120 @@
use std::collections::HashSet;
use std::f32::consts::PI;
use glam::Mat4;
use glam::Vec2;
use glam::Vec3;
use winit::event::WindowEvent;
use winit::keyboard::KeyCode;
pub struct Camera
{
pub position: Vec3,
pitch: f32,
yaw: f32,
zfar: f32,
znear: f32,
fov: f32,
pub aspect: f32,
pub speed: f32,
pub pressed_keyset: HashSet<KeyCode>,
}
impl Default for Camera
{
fn default() -> Self
{
Self {
position: Vec3::new(0., 0., 0.),
pitch: Default::default(),
yaw: Default::default(),
speed: 0.1,
pressed_keyset: Default::default(),
znear: 0.01,
zfar: 100.,
fov: PI * 100.0f32 / 180.0f32,
aspect: 1.,
}
}
}
impl Camera
{
pub fn handle_input(&mut self, event: &WindowEvent)
{
if let WindowEvent::KeyboardInput { event, .. } = event
{
match (event.state, event.physical_key)
{
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) =>
{
self.pressed_keyset.insert(c);
}
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) =>
{
self.pressed_keyset.remove(&c);
}
_ =>
{}
}
}
}
pub fn update(&mut self)
{
let mut movement = Vec3::new(0., 0., 0.);
if self.pressed_keyset.contains(&KeyCode::KeyW)
{
movement.z += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyS)
{
movement.z -= self.speed;
}
// Left right
if self.pressed_keyset.contains(&KeyCode::KeyA)
{
movement.x += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyD)
{
movement.x -= self.speed;
}
let rot_movement = glam::Mat3::from_rotation_y(-self.yaw)
* glam::Mat3::from_rotation_x(-self.pitch)
* movement;
self.position -= rot_movement;
}
pub fn cursor_moved(&mut self, x: f32, y: f32)
{
const SENSITIVITY: f32 = 0.0004;
let position = Vec2::new(x, y);
let offset = position * SENSITIVITY;
self.yaw += offset.x;
self.pitch += offset.y;
}
pub fn view_proj(&self) -> Mat4
{
let view = glam::Mat4::from_translation(self.position)
* glam::Mat4::from_rotation_y(-self.yaw)
* glam::Mat4::from_rotation_x(-self.pitch);
let proj = glam::Mat4::perspective_rh(self.fov, self.aspect, self.znear, self.zfar);
OPENGL_TO_WGPU_MATRIX * proj * view.inverse()
}
}
#[rustfmt::skip]
pub const OPENGL_TO_WGPU_MATRIX: glam::Mat4 = glam::Mat4::from_cols(
glam::Vec4::new(1.0, 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, 0.5, 0.0),
glam::Vec4::new(0.0, 0.0, 0.5, 1.0),
);
+131
View File
@@ -0,0 +1,131 @@
use egui::Context;
use egui_wgpu::Renderer;
use egui_wgpu::RendererOptions;
use egui_wgpu::ScreenDescriptor;
use egui_winit::State;
use wgpu::CommandEncoder;
use wgpu::Device;
use wgpu::Queue;
use wgpu::RenderPassDescriptor;
use wgpu::TextureFormat;
use wgpu::TextureView;
use winit::event::WindowEvent;
use winit::window::Window;
pub struct EguiRenderer
{
state: State,
pub renderer: Renderer,
frame_started: bool,
}
impl EguiRenderer
{
pub fn context(&self) -> &Context
{
self.state.egui_ctx()
}
pub fn new(device: &Device, output_color_format: TextureFormat, window: &Window)
-> EguiRenderer
{
let egui_context = Context::default();
let egui_state = State::new(
egui_context,
egui::viewport::ViewportId::ROOT,
&window,
Some(window.scale_factor() as f32),
None,
Some(2 * 1024),
);
let egui_renderer = Renderer::new(device, output_color_format, RendererOptions::default());
EguiRenderer {
state: egui_state,
renderer: egui_renderer,
frame_started: false,
}
}
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent)
{
let _ = self.state.on_window_event(window, event);
}
pub fn ppp(&mut self, v: f32)
{
self.context().set_pixels_per_point(v);
}
pub fn begin_frame(&mut self, window: &Window)
{
let raw_input = self.state.take_egui_input(window);
self.state.egui_ctx().begin_pass(raw_input);
self.frame_started = true;
}
pub fn end_frame_and_draw(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
window: &Window,
window_surface_view: &TextureView,
screen_descriptor: ScreenDescriptor,
)
{
if !self.frame_started
{
panic!("begin_frame must be called before.");
}
self.ppp(screen_descriptor.pixels_per_point);
let mut full_output = self.state.egui_ctx().end_pass();
self.state
.handle_platform_output(window, full_output.platform_output);
let tris = self
.state
.egui_ctx()
.tessellate(full_output.shapes, self.state.egui_ctx().pixels_per_point());
for (id, image_delta) in &full_output.textures_delta.set
{
self.renderer
.update_texture(device, queue, *id, &image_delta[0]);
}
full_output.textures_delta.clear();
self.renderer
.update_buffers(device, queue, encoder, &tris, &screen_descriptor);
let rpass = encoder.begin_render_pass(&RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: window_surface_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
multiview_mask: None,
depth_stencil_attachment: None,
timestamp_writes: None,
label: Some("egui main render pass"),
occlusion_query_set: None,
});
self.renderer
.render(&mut rpass.forget_lifetime(), &tris, &screen_descriptor);
for x in &full_output.textures_delta.free
{
self.renderer.free_texture(x);
}
self.frame_started = false;
}
}
+50
View File
@@ -0,0 +1,50 @@
use crate::gi_pipeline::sparse_set::GpuSparseSet;
use vxls_voxel_cache::VoxelCache;
use vxls_voxel_cache::{self};
mod sparse_set;
pub struct VoxelGiPipeline<const N: usize>
where
[(); N * N * N]:,
{
voxel_cache: VoxelCache<N>,
/// Keeps a set of the leaves present in the cache.
/// Kept in correspondancy with the leaf list attribute within the cache
leaf_list: GpuSparseSet,
leaf_list_attribute: usize,
}
impl<const N: usize> VoxelGiPipeline<N>
where
[(); N * N * N]:,
{
pub fn new(
device: &wgpu::Device,
cache_size: usize,
max_requests: usize,
cache_layout: &mut vxls_voxel_cache::CacheLayout,
) -> Self
{
let leaf_list_attribute = cache_layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::leaf_list_pointer"),
word_count: 1,
init: vxls_voxel_cache::CacheAttributeInit::External,
});
cache_layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::radiance"),
word_count: 3,
init: vxls_voxel_cache::CacheAttributeInit::DontTouch,
});
let voxel_cache = VoxelCache::new(device, cache_size, max_requests, cache_layout);
Self {
voxel_cache,
leaf_list: GpuSparseSet::new(device, cache_size),
leaf_list_attribute,
}
}
}
+57
View File
@@ -0,0 +1,57 @@
use wgpu::util::DeviceExt;
use vxls_gpu::create_multi_buffers_bind_group;
use vxls_gpu::create_multi_buffers_bind_group_layout;
/// To keep a set of voxel nodes in the cache
pub struct GpuSparseSet
{
/// Maximum size of the set
size: usize,
/// Contains pointers to nodes in the cache
pointers_buffer: wgpu::Buffer,
/// Amount of elements in the set
count_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
}
impl GpuSparseSet
{
pub fn new(device: &wgpu::Device, size: usize) -> Self
{
let pointers_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::pointers_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::cast_slice(&vec![0u32; size]),
});
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::count_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::bytes_of(&0u32),
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&pointers_buffer, &count_buffer],
Some("GpuSparseSet::bind_group"),
);
Self {
size,
pointers_buffer,
count_buffer,
bind_group,
}
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
create_multi_buffers_bind_group_layout(device, 2, Some("GpuSparseSet::bind_group_layout"))
}
}
+15
View File
@@ -0,0 +1,15 @@
// Contains useful facilities to render data streamed in from the host
// Can produce a voxel given
// - Its depth
// - Its position within the chunk
// - The chunks position
pub trait ChunkVoxelProducer
{
fn produce_voxel(
&mut self,
depth: usize,
chunk_position: (usize, usize, usize),
voxel_position: (usize, usize, usize),
);
}
File diff suppressed because it is too large Load Diff
+683
View File
@@ -0,0 +1,683 @@
use std::fs::File;
use std::path::Path;
use glam::Vec3;
use itertools::Itertools;
use noise::Cylinders;
use noise::Fbm;
use noise::NoiseFn;
use noise::Simplex;
use rand::random;
use crate::sparse_tree::Color;
use vxls_voxel_cache::schema::ChildInformation;
pub struct BallGenerator<const N: usize>
{
chunk_power: usize,
}
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32
{
//((x - x_min) / (x_max - x_min)) * (y_max - y_min) + y_min
let input_range = x_max.algebraic_sub(x_min);
let output_range = y_max.algebraic_sub(y_min);
(x.algebraic_sub(x_min).algebraic_div(input_range))
.algebraic_mul(output_range)
.algebraic_add(y_min)
}
pub trait Producer<const N: usize>
where
[(); N * N * N]:,
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>;
}
impl<const N: usize> BallGenerator<N>
where
[(); N * N * N]:,
{
pub fn new(chunk_power: usize) -> Self
{
BallGenerator { chunk_power }
}
}
impl<const N: usize> Producer<N> for BallGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
{
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![];
let mut children_color = vec![];
let mut children_normal = vec![];
let gnx = nx * node_size;
let gny = ny * node_size;
let gnz = nz * node_size;
// Iterate on children of this node
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
let dist = Vec3::new(
gvx as f32 - (global_size / 2) as f32,
gvy as f32 - (global_size / 2) as f32,
gvz as f32 - (global_size / 2) as f32,
)
.length();
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist > 128. { 0. } else { 1. };
}
else if dist > (global_size as f32 / 2.)
{
subdivided = false;
alpha = 0.;
}
else
{
subdivided = false;
alpha = 1.;
}
// let alpha = 1.;
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
children_normal.push((0., 0., 0.));
children_color.push(Color(
gvx as f32 / global_size as f32,
gvy as f32 / global_size as f32,
gvz as f32 / global_size as f32,
alpha,
));
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normal[i].into()),
}
}
}
pub struct TerrainGenerator<const N: usize>
where
[(); N * N * N]:,
{
chunk_power: usize,
heightmap_width: usize,
heightmap_height: usize,
terrain_width: usize,
terrain_height: usize,
heightmap_min: f32,
heightmap_max: f32,
heightmap: Vec<f32>,
colormap: Vec<u8>,
heightmap_low_width: usize,
heightmap_low_height: usize,
heightmap_low: Vec<(f32, f32)>,
colormap_low_width: usize,
colormap_low_height: usize,
colormap_mip: Vec<u8>,
pub chunk_width: usize,
pub chunk_height: usize,
pub chunk_alt: usize,
}
impl<const N: usize> TerrainGenerator<N>
where
[(); N * N * N]:,
{
pub fn new<P: AsRef<Path>>(
chunk_power: usize,
height_path: P,
height_factor: f32,
color_path: P,
) -> Self
{
println!("Starting terrain producer");
println!("Loading height map.");
let mut tiff_dec = tiff::decoder::Decoder::new(File::open(height_path).unwrap()).unwrap();
let (heightmap_width, heightmap_height) = tiff_dec.dimensions().unwrap();
let (heightmap_width, heightmap_height) =
(heightmap_width as usize, heightmap_height as usize);
let mut heightmap = match tiff_dec.read_image().unwrap()
{
tiff::decoder::DecodingResult::F32(vec) => vec,
_ => panic!("Unsupported format"),
};
println!("Loading color map.");
let mut color = image::ImageReader::open(color_path).unwrap();
color.no_limits();
let color = color.decode().unwrap();
let mut colormap = color.as_rgb8().unwrap().to_vec();
println!("Converting color spaces");
colormap.iter_mut().for_each(|x| {
let normalized = map(*x as f32, 0., 255., 0., 1.);
let maped = normalized.powf(2.4);
*x = map(maped, 0., 1., 0., 255.) as u8;
});
let terrain_width = color.width() as usize;
let terrain_height = color.height() as usize;
println!("Computing heightmap min/max");
let heightmap_min = heightmap
.iter()
.copied()
.filter(|x| *x != -9999.)
.reduce(f32::min)
.unwrap();
let heightmap_max = heightmap.iter().copied().reduce(f32::max).unwrap();
heightmap
.iter_mut()
.filter(|x| **x == -9999.)
.for_each(|x| *x = heightmap_min);
// Decide size in chunks
let height_amplitude = heightmap_max - heightmap_min;
let chunk_size = N.pow(chunk_power as u32);
let chunk_width = terrain_width.div_ceil(chunk_size);
let chunk_height = terrain_height.div_ceil(chunk_size);
let chunk_alt = ((height_amplitude / height_factor) as usize).div_ceil(chunk_size);
// build the low heightmap
println!("Computing low res height/color maps");
let heightmap_low_width = heightmap_width / 8;
let heightmap_low_height = heightmap_height / 8;
let mut heightmap_low = vec![(0., 0.); heightmap_low_height * heightmap_low_width];
for y in 0..heightmap_low_height
{
for x in 0..heightmap_low_width
{
let mut min = heightmap_max;
let mut max = heightmap_min;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
min = min.min(heightmap[sx + sy * heightmap_width]);
max = max.max(heightmap[sx + sy * heightmap_width]);
}
}
heightmap_low[x + y * heightmap_low_width] = (min, max);
}
}
// build the color map mip
let colormap_low_width = terrain_width / 8;
let colormap_low_height = terrain_height / 8;
let mut colormap_mip = vec![0u8; colormap_low_width * colormap_low_height * 3];
for y in 0..colormap_low_height
{
for x in 0..colormap_low_width
{
let mut r = 0u32;
let mut g = 0u32;
let mut b = 0u32;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
r += colormap[(sx + sy * terrain_width) * 3] as u32;
g += colormap[(sx + sy * terrain_width) * 3 + 1] as u32;
b += colormap[(sx + sy * terrain_width) * 3 + 2] as u32;
}
}
colormap_mip[(x + y * colormap_low_width) * 3] =
((r as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
colormap_mip[(x + y * colormap_low_width) * 3 + 1] =
((g as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
colormap_mip[(x + y * colormap_low_width) * 3 + 2] =
((b as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
}
}
println!("Producer ready");
Self {
chunk_power,
heightmap_width,
heightmap_height,
heightmap_min,
heightmap_max,
terrain_width,
terrain_height,
heightmap,
colormap,
heightmap_low_width,
heightmap_low_height,
heightmap_low,
colormap_low_width,
colormap_low_height,
colormap_mip,
chunk_width,
chunk_height,
chunk_alt,
}
}
}
impl<const N: usize> ChunkedProducer<N> for TerrainGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![ChildInformation::NONE; N * N * N];
let mut children_color = vec![Color(0., 0., 0., 0.); N * N * N];
let mut children_normals = vec![(0., 0., 0.); N * N * N];
let gnx = chunk_pos.0 * global_size + nx * node_size;
let gny = chunk_pos.1 * global_size + ny * node_size;
let gnz = chunk_pos.2 * global_size + nz * node_size;
// Iterate on children of this node
for (cx, cz) in (0..N).cartesian_product(0..N)
{
let gcx = gnx + cx * child_size;
let gcz = gnz + cz * child_size;
// prepare 2d values
// Iterate on children
let mut sample_max = self.heightmap_min;
let mut sample_min = self.heightmap_max;
let mut color_avg = Color(0., 0., 0., 0.);
let mut count = 0;
if depth <= 2
{
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8))
{
let gvx = (gcx + x * 8) / 8;
let gvz = (gcz + z * 8) / 8;
if gvx < self.colormap_low_width && gvz < self.colormap_low_height
{
// Height sample
let height_x = (gvx * self.heightmap_low_width) / self.colormap_low_width;
let height_z = (gvz * self.heightmap_low_height) / self.colormap_low_height;
let sample =
self.heightmap_low[height_x + height_z * self.heightmap_low_width];
sample_min = sample_min.min(sample.0);
sample_max = sample_max.max(sample.1);
let sample_color_r =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3];
let sample_color_g =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3 + 1];
let sample_color_b =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3 + 2];
color_avg.0 += map(sample_color_r as f32, 0., 256., 0., 1.);
color_avg.1 += map(sample_color_g as f32, 0., 256., 0., 1.);
color_avg.2 += map(sample_color_b as f32, 0., 256., 0., 1.);
count += 1;
}
//let gvy = gcy;
}
}
else
{
for (z, x) in (0..child_size).cartesian_product(0..child_size)
{
let gvx = gcx + x;
let gvz = gcz + z;
if gvx < self.terrain_width && gvz < self.terrain_height
{
// Height sample
let height_x = (gvx * self.heightmap_width) / self.terrain_width;
let height_z = (gvz * self.heightmap_height) / self.terrain_height;
let sample = self.heightmap[height_x + height_z * self.heightmap_width];
sample_max = sample_max.max(sample);
sample_min = sample_min.min(sample);
let sample_color_r = self.colormap[(gvx + gvz * self.terrain_width) * 3];
let sample_color_g =
self.colormap[(gvx + gvz * self.terrain_width) * 3 + 1];
let sample_color_b =
self.colormap[(gvx + gvz * self.terrain_width) * 3 + 2];
color_avg.0 += map(sample_color_r as f32, 0., 256., 0., 1.);
color_avg.1 += map(sample_color_g as f32, 0., 256., 0., 1.);
color_avg.2 += map(sample_color_b as f32, 0., 256., 0., 1.);
count += 1;
}
//let gvy = gcy;
}
}
color_avg.0 /= count as f32;
color_avg.1 /= count as f32;
color_avg.2 /= count as f32;
let sample_min = map(
sample_min,
self.heightmap_min,
self.heightmap_max,
0.,
(self.chunk_alt * global_size) as f32,
) as usize;
let sample_max = map(
sample_max,
self.heightmap_min,
self.heightmap_max,
0.,
(self.chunk_alt * global_size) as f32,
) as usize;
for cy in 0..N
{
let gcy = gny + cy * child_size;
let index = cz * N * N + cy * N + cx;
let alpha;
let subdivided;
if gcy > sample_max
{
subdivided = false;
alpha = 0.;
}
else if gcy + child_size < sample_min
{
subdivided = false;
alpha = 1.;
}
else
{
subdivided = depth < (self.chunk_power - 1);
//children.push(StructurePointer(0));
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
{
1.
}
else
{
0.
};
}
children[index] = ChildInformation::new(subdivided, subdivided || alpha != 0.);
children_normals[index] = (0., 0., 0.);
children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha);
//children_color[index] = Color(1., 1., 1., alpha);
}
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normals[i].into()),
}
}
}
pub struct ProducedChunk<const N: usize>
where
[(); N * N * N]:,
{
pub children: [ChildInformation; N * N * N],
pub colors: [u32; N * N * N],
pub normals: [[f32; 3]; N * N * N],
}
pub trait ChunkedProducer<const N: usize>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>;
}
pub struct SdfGenerator<const N: usize>
{
chunk_power: usize,
perlin: Fbm<Simplex>,
//perlin: Cylinders,
}
impl<const N: usize> SdfGenerator<N>
{
pub fn new(chunk_power: usize) -> Self
{
Self {
chunk_power,
perlin: Fbm::new(67),
//perlin: Cylinders::new(),
}
}
}
impl<const N: usize> ChunkedProducer<N> for SdfGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
fn hash(mut p: [f32; 3]) -> f32
{
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
p[0].fract()
}
// let sdf = |x: f32, y: f32, z: f32| {
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
// };
// let sdf = |mut x: f32, mut y: f32, mut z: f32| {
// // x = -5000. * 1024.;
// // z = -5000. * 1024.;
// y -= 1024.;
// let scale = 2048.;
// let tx = x / scale;
// let ty = y / scale;
// let tz = z / scale;
//
// let val = (self.perlin.get([tx as f64, tz as f64, ty as f64]) + 0.5) * 0.23;
// let dist = val * scale as f64;
// return (dist as f32).max(ty);
// };
// let sdf = |x: f32, y: f32, z: f32| {
// let scale = 1024. * 10.;
// let domain = 1.;
// let tx = map(x, 0., scale, -domain, domain);
// let ty = map(y, 0., scale, -domain, domain);
// let tz = map(z, 0., scale, -domain, domain);
// nebula_sdf(tx, ty, tz) * 0.2 * scale / domain
// };
let sdf = |x: f32, y: f32, z: f32| {
let scale = 10. * 1024.;
let height = 5000.;
let tx = x / scale;
let tz = z / scale;
let ty = y;
let val = map(
self.perlin.get([tx as f64, tz as f64]) as f32,
-1.,
1.,
1.,
height,
);
// Trees
let tree_space = 10.;
let mx = x.rem_euclid(tree_space);
let mz = z.rem_euclid(tree_space);
let tree_x = x.div_euclid(tree_space);
let tree_z = z.div_euclid(tree_space);
let h1 = hash([tree_x, tree_z, 1.]);
let h2 = hash([tree_z, tree_x, 1.]);
let h3 = hash([tree_z, tree_x, tree_z]);
let d = Vec3::new(
mx + h1 * 3. - tree_space * 0.5,
(ty - val) * 0.2,
mz + h2 * 3. - tree_space * 0.5,
)
.length()
- 4. * map(h3, 0., 1., 0.8, 1.2);
let bound = 1. / scale * height;
((ty - val) / (1. + bound.powf(2.)).sqrt()).min(d)
};
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![];
let mut children_color = vec![];
let mut children_normals = vec![];
let cx = chunk_pos.0 * global_size;
let cy = chunk_pos.1 * global_size;
let cz = chunk_pos.2 * global_size;
let gnx = nx * node_size + cx;
let gny = ny * node_size + cy;
let gnz = nz * node_size + cz;
// Iterate on children of this node
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
let dist = sdf(gvx as f32, gvy as f32, gvz as f32);
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if dist.abs() < child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist >= 0. { 0. } else { 1. };
//alpha = 0.;
}
else if dist >= 0.
{
subdivided = false;
alpha = 0.;
}
else
{
subdivided = false;
alpha = 1.;
}
let offset = 1. * (child_size as f32 / 2.);
let a = sdf(
gvx as f32 + offset,
gvy as f32 - offset,
gvz as f32 - offset,
);
let b = sdf(
gvx as f32 - offset,
gvy as f32 - offset,
gvz as f32 + offset,
);
let c = sdf(
gvx as f32 - offset,
gvy as f32 + offset,
gvz as f32 - offset,
);
let d = sdf(
gvx as f32 + offset,
gvy as f32 + offset,
gvz as f32 + offset,
);
let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d);
let normal = if normal.length() <= f32::EPSILON
{
Vec3::new(1., 0., 0.)
}
else
{
normal.normalize()
};
let color = (normal.dot(Vec3::new(0., 1., 0.)) + 1.) * 0.5;
// let alpha = 1.;
// children_color.push(Color(
// (gvx - cx) as f32 / global_size as f32,
// (gvy - cy) as f32 / global_size as f32,
// (gvz - cz) as f32 / global_size as f32,
// alpha,
// ));
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
children_color.push(Color(color + random::<f32>() * 0.02, color, color, alpha));
children_normals.push((normal.x, normal.y, normal.z));
//children_color.push(Color(normal.x, normal.y, normal.z, alpha));
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normals[i].into()),
//normals: std::array::from_fn(|i| (1., 0., 0.)),
}
}
}
+464
View File
@@ -0,0 +1,464 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
use noise::Terrace;
use vxls_production::tree_locator::TreeLocator;
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct Color(pub f32, pub f32, pub f32, pub f32);
impl Color
{
pub fn average<I: Iterator<Item = Color>>(iter: I) -> Self
{
let mut c = Color(0., 0., 0., 0.);
let mut count = 0;
for Color(r, g, b, a) in iter
{
count += 1;
c.0 += r;
c.1 += g;
c.2 += b;
c.3 += a;
}
c.0 /= count as f32;
c.1 /= count as f32;
c.2 /= count as f32;
c.3 /= count as f32;
c
}
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
}
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
{
map: HashMap<TreeLocator<N>, NTreeNode>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
// one root => depth = 1
depth: usize,
}
pub struct NTreeIter<'a, const N: usize>
{
tree: &'a NTree<N>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
{
pub color: Color,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
where
[(); N * N * N]:,
{
pub fn constant(color: Color, depth: usize) -> Self
{
let mut map = HashMap::new();
let root = NTreeNode {
color,
subdivided: false,
};
map.insert(TreeLocator::<N>::root(), root);
Self { map, depth }
}
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
{
self.set_at_depth(x, y, z, self.depth, color);
}
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
{
assert!(x < N.pow(self.depth as u32));
assert!(y < N.pow(self.depth as u32));
assert!(z < N.pow(self.depth as u32));
// Try to walk down the tree, and create necessary nodes
let mut current_node_loc = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(&current_node_loc).unwrap();
loop
{
if !current_node.subdivided
{
return current_node.color;
}
// Descend to relevant node,
let child_node_size = current_node_size / N;
let child_x = (x % current_node_size) / child_node_size;
let child_y = (y % current_node_size) / child_node_size;
let child_z = (z % current_node_size) / child_node_size;
current_node_size = child_node_size;
current_node_loc =
current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get(&current_node_loc).unwrap();
}
}
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color)
{
assert!(x < N.pow(depth as u32));
assert!(y < N.pow(depth as u32));
assert!(z < N.pow(depth as u32));
// Try to walk down the tree, and create necessary nodes
let mut current_node_loc = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_depth = 0;
let mut current_node = self.map.get_mut(&current_node_loc).unwrap();
while current_depth != depth
{
if current_node.color == color
{
// Color is already correct, work is finished
return;
}
// Current is not subdivided, and color is different => subdivide
if !current_node.subdivided
{
current_node.subdivided = true;
let new_nodes = NTreeNode {
color: current_node.color,
subdivided: false,
};
current_node_loc.children().for_each(|child| {
self.map.insert(child, new_nodes);
});
}
// Descend to relevant node,
let child_node_size = current_node_size / N;
let child_x = (x % current_node_size) / child_node_size;
let child_y = (y % current_node_size) / child_node_size;
let child_z = (z % current_node_size) / child_node_size;
current_node_size = child_node_size;
current_depth += 1;
current_node_loc =
current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get_mut(&current_node_loc).unwrap();
}
if current_node.subdivided
{
self.make_constant(current_node_loc, color);
}
else
{
current_node.color = color;
}
// We need to go back up the hierarchy to combine nodes
// current_node is the modified node, go one up
loop
{
// Go one node up
current_depth -= 1;
current_node_loc = current_node_loc.parent().unwrap();
//current_node_size *= N;
// Access all children's colors
let children_color_avg = current_node_loc
.children()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
if current_depth == 0
{
break;
}
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, color: Color)
{
let mut dfs_stack = Vec::new();
dfs_stack.push(locator);
while let Some(current) = dfs_stack.pop()
{
// Remove element
let removed = self.map.remove(&current);
let handle_children = removed.is_some_and(|x| x.subdivided);
// If children have to be handled, push on stack
if handle_children
{
dfs_stack.extend(current.children());
}
}
self.map.insert(
locator,
NTreeNode {
color,
subdivided: false,
},
);
}
pub fn from_array(array: &[Color], depth: usize) -> Self
{
let mut structure = HashMap::new();
// Per voxel in the array :
// 0 -> Voxel not merged yet
// _ -> size of the block in which the voxel was merged
let mut merged_size = vec![0; array.len()];
let width = N.pow(depth as u32);
for (z, y) in (0..width).cartesian_product(0..width)
{
let mut x = 0;
while x < width
{
if merged_size[x + y * width + z * width * width] != 0
{
// If current voxel has already been accounted for -> skip
// We stumbled on a big merged block, we can skip it as a whole on the inner
// dimension
x += merged_size[x + y * width + z * width * width];
continue;
}
// Check smallest depth aligned with current position
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
let z_trailing = base_trailing_zeroes::<N>(z).unwrap_or(depth as u32);
// Biggest block size power of which this voxel can be a lower corner
let block_power = x_trailing.min(y_trailing.min(z_trailing));
// Try to merge for each depth
let mut max_power_merge = 0; // Single voxel can always be merged
let color = array[x + y * width + z * width * width];
let mut locator =
TreeLocator::<N>::from_node_coords(depth as u32, x as u32, y as u32, z as u32);
'power_search: for power in 1..=block_power
{
let block_size = N.pow(power);
// Check if candidate block has the same color
for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
if array
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width]
!= color
{
break 'power_search;
}
}
// Update biggest candidate block
locator = locator.parent().unwrap();
max_power_merge = power;
}
// We know which size we can know merge
// Say we accounted for those voxels :
let block_size = N.pow(max_power_merge);
for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
merged_size
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] =
block_size;
}
// Add new found block in our structure
// If power is depth, this is the whole structure, thus depth is 0
let node = NTreeNode {
color,
subdivided: false,
};
structure.insert(locator, node);
x += block_size;
}
}
// The structure now consists of the leaf most nodes, we need to rebuild the hierarchy
// bottom up
for current_power in 1..=depth
{
// Iterate on the blocks of this size
let block_size = N.pow(current_power as u32);
let block_count = width / block_size;
for ((block_x, block_y), block_z) in (0..block_count)
.cartesian_product(0..block_count)
.cartesian_product(0..block_count)
{
// Check the lower corner of this block
let corner = merged_size[(block_x * block_size)
+ (block_y * block_size) * width
+ (block_z * block_size) * width * width];
if corner >= block_size
{
// Children are merged in bigger block
continue;
}
// Add hierarchy node
let locator = TreeLocator::<N>::from_node_coords(
(depth - current_power) as u32,
block_x as u32,
block_y as u32,
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().color),
);
let hierarchy_node = NTreeNode {
color,
subdivided: true,
};
structure.insert(locator, hierarchy_node);
}
}
Self {
map: structure,
depth,
}
}
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
{
self.map.get(&locator).copied()
}
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
{
if number == 0
{
return None;
}
let mut trailing_zeroes = 0;
while number % N == 0
{
number /= N;
trailing_zeroes += 1;
}
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
where
[(); N * N * N]:,
{
let file = std::fs::read_to_string(path).unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::from_array(&colors, 4)
}
mod test
{
use glam::Vec3;
use rand::random;
use vxls_production::tree_locator::TreeLocator;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
#[test]
fn constant_set()
{
let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4);
assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.));
tree.set(0, 0, 0, Color(1., 1., 1., 1.));
assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.));
}
#[test]
fn load_read_same()
{
let file = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../dragon.txt"
))
.unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
println!("ok");
for x in 0..256
{
for y in 0..256
{
for z in 0..256
{
let index = x + y * 256 + z * 256 * 256;
let color = colors[index];
let t = tree.get(x, y, z);
assert!(t == color);
}
}
}
}
}