Spatial texture writing works

This commit is contained in:
2026-10-20 22:03:16 +01:00
parent 2c05cc28a0
commit 41b27347cb
7 changed files with 154 additions and 180 deletions
@@ -745,7 +745,7 @@ impl InstanceState {
return false;
}
let spatial_texture_key = spatial_texture.id();
let spatial_texture_key = spatial_texture.0.id();
let spatial_capacity = MAX_SPATIAL_TEXTURE_COUNT.get();
if !self
.spatial_textures
@@ -774,13 +774,7 @@ impl InstanceState {
let spatial_texture_id = self
.spatial_textures
.acquire(spatial_texture_key, spatial_capacity, || {
spatial_texture.create_view(&TextureViewDescriptor {
label: Some(&format!(
"Tape {} slot {} spatial texture view",
instance.tape, instance.slot
)),
..Default::default()
})
spatial_texture.1.clone()
})
.expect("spatial vslab binding array had room but handed out no slot");
instance.buffers = Some((aabb_buffer_key, metadata_buffer_key, spatial_texture_key));
@@ -243,9 +243,12 @@ pub fn compile_raytracing_blas(
struct PushConstants {
aabb_buffer_offset: u32,
metadata_buffer_offset: u32,
time: f32,
flags: u32,
}
const FLAG_FILL_ENABLE_GEN: u32 = 1 << 0;
const FLAG_FILL_SPATIAL_TEXTURE: u32 = 1 << 1;
let tape_info = tapes
.iter()
.filter(|(asset_id, _)| blas_manager.needs_new_blas.contains(asset_id))
@@ -257,13 +260,21 @@ pub fn compile_raytracing_blas(
let aabbs_slice = tape_allocator.tape_aabb_slice(&asset_id).unwrap();
let metadata_slice = tape_allocator.tape_metadata_slice(&asset_id).unwrap();
let spatial_texture = tape_allocator.tape_spatial_texture(&asset_id).unwrap();
let blas_size = BlasAABBGeometrySizeDescriptor {
primitive_count: aabbs_slice.range.len() as u32,
flags: key.opacity.geometry_flags(),
};
(key, tape, aabbs_slice, metadata_slice, blas_size)
(
key,
tape,
aabbs_slice,
metadata_slice,
spatial_texture,
blas_size,
)
})
.collect::<Vec<_>>();
@@ -271,42 +282,45 @@ pub fn compile_raytracing_blas(
let mut updated_blases = vec![];
let build_entries = tape_info
.iter()
.filter_map(|(key, tape, aabbs_slice, metadata_slice, blas_size)| {
let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?;
.filter_map(
|(key, tape, aabbs_slice, metadata_slice, spatial_texture, blas_size)| {
let pipeline = pipeline_cache.get_compute_pipeline(tape.enable_gen_pipeline)?;
let bind_group = render_device.create_bind_group(
"enable_gen_bind_group",
&pipeline_cache.get_bind_group_layout(&replacement_modules.enable_gen_layout),
&BindGroupEntries::sequential((
aabbs_slice.buffer.as_entire_buffer_binding(),
metadata_slice.buffer.as_entire_buffer_binding(),
)),
);
let bind_group = render_device.create_bind_group(
"enable_gen_bind_group",
&pipeline_cache.get_bind_group_layout(&replacement_modules.enable_gen_layout),
&BindGroupEntries::sequential((
aabbs_slice.buffer.as_entire_buffer_binding(),
metadata_slice.buffer.as_entire_buffer_binding(),
&spatial_texture.1,
)),
);
let pc = PushConstants {
aabb_buffer_offset: aabbs_slice.range.start,
metadata_buffer_offset: metadata_slice.range.start,
time: 0.0,
};
let pc = PushConstants {
aabb_buffer_offset: aabbs_slice.range.start,
metadata_buffer_offset: metadata_slice.range.start,
flags: FLAG_FILL_ENABLE_GEN | FLAG_FILL_SPATIAL_TEXTURE,
};
compute_pass.set_pipeline(pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.set_immediates(0, bytemuck::bytes_of(&pc));
compute_pass.dispatch_workgroups(1, 1, 1);
compute_pass.set_pipeline(pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.set_immediates(0, bytemuck::bytes_of(&pc));
compute_pass.dispatch_workgroups(1, 1, 1);
updated_blases.push(key.tape);
updated_blases.push(key.tape);
let geometry = BlasAabbGeometry {
size: blas_size,
stride: size_of::<bevy_tape_load::render::PackedAabb>() as u64,
aabb_buffer: aabbs_slice.buffer,
primitive_offset: aabbs_slice.range.start,
};
Some(BlasBuildEntry {
blas: blas_manager.get(&key).unwrap(),
geometry: BlasGeometries::AabbGeometries(vec![geometry]),
})
})
let geometry = BlasAabbGeometry {
size: blas_size,
stride: size_of::<bevy_tape_load::render::PackedAabb>() as u64,
aabb_buffer: aabbs_slice.buffer,
primitive_offset: aabbs_slice.range.start,
};
Some(BlasBuildEntry {
blas: blas_manager.get(&key).unwrap(),
geometry: BlasGeometries::AabbGeometries(vec![geometry]),
})
},
)
.collect::<Vec<_>>();
drop(compute_pass);
+3 -3
View File
@@ -78,8 +78,8 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
let asm = std::fs::read_to_string(format!("{SHADERS_OUT}/{name}.stage0.spv-dis")).unwrap();
let asm =
regex::regex!("(?ms)%package_implicit__1scene =.*?OpFunctionEnd").replace_all(&asm, "");
let asm = regex::regex!("%package_implicit__1scene").replace_all(&asm, "%10000");
regex::regex!("(?ms)%package_implicit_scene =.*?OpFunctionEnd").replace_all(&asm, "");
let asm = regex::regex!("%package_implicit_scene").replace_all(&asm, "%10000");
let asm = regex::regex!("(?ms)%package_implicit__1interval_scene =.*?OpFunctionEnd")
.replace_all(&asm, "");
let asm = regex::regex!("%package_implicit__1interval_scene").replace_all(&asm, "%20000");
@@ -95,7 +95,7 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
let asm = regex::regex!("OpName %gradient_scene_input_one \"gradient_scene_input_one\"")
.replace_all(&asm, "");
let asm = regex::regex!("OpName %10000 \"package_implicit__1scene\"").replace_all(&asm, "");
let asm = regex::regex!("OpName %10000 \"package_implicit_scene\"").replace_all(&asm, "");
let asm =
regex::regex!("OpName %20000 \"package_implicit__1interval_scene\"").replace_all(&asm, "");
let asm =
+62 -42
View File
@@ -1,6 +1,6 @@
import package::aabb::PackedAabb;
import package::metadata_types::TapeMetadata;
import package::implicit::interval_scene;
import package::implicit::{interval_scene, scene};
import package::NAN;
enable wgpu_binding_array;
@@ -14,13 +14,18 @@ struct TapeMetadataBuffer {
struct PushConstants {
aabb_buffer_offset: u32,
metadata_buffer_offset: u32,
time: f32,
flags: u32
}
const FLAG_FILL_ENABLE_GEN = 1 << 0;
const FLAG_FILL_SPATIAL_TEXTURE = 1 << 1;
@group(0) @binding(0)
var<storage, read_write> aabb_buffer: AabbBuffer;
@group(0) @binding(1)
var<storage> tape_metadata_buffer: TapeMetadataBuffer;
@group(0) @binding(2)
var spatial_texture: texture_storage_3d<r32float, write>;
var<immediate> push_constants: PushConstants;
@@ -34,51 +39,66 @@ struct ComputeInput {
fn main(compute_input: ComputeInput) {
let metadata = &tape_metadata_buffer.metadata[push_constants.metadata_buffer_offset];
let total_invocations = compute_input.num_workgroups * vec3u(8);
let base_index =
(((compute_input.global_invocation_id.z * total_invocations.y)
+ compute_input.global_invocation_id.y) * total_invocations.x)
+ compute_input.global_invocation_id.x;
if (push_constants.flags & FLAG_FILL_ENABLE_GEN) > 0 {
let total_invocations = compute_input.num_workgroups * vec3u(8);
let base_index =
(((compute_input.global_invocation_id.z * total_invocations.y)
+ compute_input.global_invocation_id.y) * total_invocations.x)
+ compute_input.global_invocation_id.x;
let internal_pos = vec3(
f32(
(base_index >> (metadata.subdivision_log2 * 2))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
f32(
(base_index >> (metadata.subdivision_log2 * 1))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
f32(
(base_index >> (metadata.subdivision_log2 * 0))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
);
let internal_pos = vec3(
f32(
(base_index >> (metadata.subdivision_log2 * 2))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
f32(
(base_index >> (metadata.subdivision_log2 * 1))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
f32(
(base_index >> (metadata.subdivision_log2 * 0))
& u32((1 << metadata.subdivision_log2) - 1),
) / f32(1 << metadata.subdivision_log2),
);
let low_corner =
(((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions)
+ metadata.lowest_corner;
let high_corner =
(((vec3(1.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions)
+ metadata.lowest_corner;
let interval = interval_scene(
vec4(low_corner, push_constants.time),
vec4(high_corner, push_constants.time),
);
let low_corner =
(((vec3(0.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions)
+ metadata.lowest_corner;
let high_corner =
(((vec3(1.0f) / f32(1 << metadata.subdivision_log2)) + internal_pos) * metadata.dimensions)
+ metadata.lowest_corner;
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
let interval = interval_scene(
vec4(low_corner, metadata.time),
vec4(high_corner, metadata.time),
);
let en = (interval.x < 0) && (interval.y > 0);
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
if en {
aabb.min_x = low_corner.x;
aabb.min_y = low_corner.y;
aabb.min_z = low_corner.z;
aabb.max_x = high_corner.x;
aabb.max_y = high_corner.y;
aabb.max_z = high_corner.z;
} else {
aabb.min_x = NAN();
let en = (interval.x < 0) && (interval.y > 0);
if en {
aabb.min_x = low_corner.x;
aabb.min_y = low_corner.y;
aabb.min_z = low_corner.z;
aabb.max_x = high_corner.x;
aabb.max_y = high_corner.y;
aabb.max_z = high_corner.z;
} else {
aabb.min_x = NAN();
}
}
if (push_constants.flags & FLAG_FILL_SPATIAL_TEXTURE) > 0 {
let internal_pos = vec3f(compute_input.global_invocation_id);
let mid_point =
(((internal_pos + 0.5f) / f32(1 << metadata.subdivision_log2)) * metadata.dimensions)
+ metadata.lowest_corner;
let point = scene(vec4(mid_point, metadata.time));
textureStore(spatial_texture, compute_input.global_invocation_id, vec4(point, 0., 0., 0.));
}
}
@@ -1,7 +1,6 @@
struct TapeMetadata {
/// AABB for decompressing positions.
lowest_corner: vec3<f32>,
pad_a: u32,
time: f32,
dimensions: vec3<f32>,
subdivision_log2: u32,
}
+26 -22
View File
@@ -16,7 +16,7 @@ use bevy_platform::collections::HashMap;
use bevy_render::{
GpuResourceAppExt, Render, RenderApp, RenderSystems,
render_asset::{ExtractedAssets, prepare_assets},
render_resource::Texture,
render_resource::{Texture, TextureView},
renderer::{RenderDevice, RenderQueue},
slab_allocator::{
Slab, SlabAllocationBufferSlice, SlabAllocator, SlabAllocatorSettings, SlabId, SlabItem,
@@ -26,7 +26,7 @@ use bevy_render::{
use wgpu::{
BufferUsages, COPY_BUFFER_ALIGNMENT, Extent3d, TextureDimension, TextureFormat, TextureUsages,
};
use wgpu_types::TextureDescriptor;
use wgpu_types::{TextureDescriptor, TextureViewDescriptor};
use super::{PackedAabb, RenderTape, TapeMetadata};
use crate::tape::Tape;
@@ -48,7 +48,7 @@ pub struct TapeAllocator {
/// Holds all buffers and offset allocators.
#[deref]
slab_allocator: SlabAllocator<TapeSlabItem>,
spatial_texture_allocator: HashMap<AssetId<Tape>, Texture>,
spatial_texture_allocator: HashMap<AssetId<Tape>, (Texture, TextureView)>,
}
/// Tunable parameters that customize the behavior of the allocator.
@@ -278,7 +278,7 @@ impl TapeAllocator {
/// Returns the spatial texture for the tape with the given ID.
///
/// If the tape wasn't allocated, returns None.
pub fn tape_spatial_texture(&self, tape_id: &AssetId<Tape>) -> Option<&Texture> {
pub fn tape_spatial_texture(&self, tape_id: &AssetId<Tape>) -> Option<&(Texture, TextureView)> {
self.spatial_texture_allocator.get(tape_id)
}
@@ -376,24 +376,28 @@ impl TapeAllocator {
tape_allocator_settings,
);
let texture = render_device.create_texture(&TextureDescriptor {
label: Some(&format!("Tape {} spatial texture", tape_id)),
format: TextureFormat::R32Float,
dimension: TextureDimension::D3,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
mip_level_count: 1,
sample_count: 1,
view_formats: &[TextureFormat::R32Float],
size: Extent3d {
width: tape.subdivision,
height: tape.subdivision,
depth_or_array_layers: tape.subdivision,
},
});
let texture_view = texture.create_view(&TextureViewDescriptor {
label: Some(&format!("Tape {} spatial texture view", tape_id)),
..Default::default()
});
// Allocate spatial texture.
self.spatial_texture_allocator.insert(
*tape_id,
render_device.create_texture(&TextureDescriptor {
label: Some(&format!("Tape {} spatial texture", tape_id)),
format: TextureFormat::R32Float,
dimension: TextureDimension::D3,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,
mip_level_count: 1,
sample_count: 1,
view_formats: &[TextureFormat::R32Float],
size: Extent3d {
width: tape.subdivision,
height: tape.subdivision,
depth_or_array_layers: tape.subdivision,
},
}),
);
self.spatial_texture_allocator
.insert(*tape_id, (texture, texture_view));
}
// Perform growth.
@@ -430,7 +434,7 @@ impl TapeAllocator {
lowest_corner,
dimensions,
subdivision_log2: tape.subdivision.ilog2(),
..Default::default()
time: tape.time,
}
};
// Call the generic function.
+13 -70
View File
@@ -19,13 +19,19 @@ use bevy_render::{
render_resource::{
BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, CachedComputePipelineId,
ComputePipelineDescriptor, PipelineCache, ShaderType,
binding_types::{storage_buffer, storage_buffer_read_only},
binding_types::{
storage_buffer, storage_buffer_read_only, texture_3d, texture_storage_2d_array,
texture_storage_3d,
},
},
};
use bevy_shader::{Shader, load_shader_library};
use bytemuck::{Pod, Zeroable};
use rspirv::dr::Module;
use wgpu::{ShaderModuleDescriptorPassthrough, ShaderStages, include_spirv_raw};
use wgpu::{
ShaderModuleDescriptorPassthrough, ShaderStages, StorageTextureAccess, TextureFormat,
TextureSampleType, include_spirv_raw,
};
use crate::{
render::allocator::{ElementClass, TapeAllocationKey, TapeAllocator, TapeSlabId},
@@ -47,7 +53,7 @@ pub struct PackedAabb {
#[repr(C)]
pub struct TapeMetadata {
lowest_corner: Vec3,
pad_a: u32,
time: f32,
dimensions: Vec3,
subdivision_log2: u32,
}
@@ -82,9 +88,7 @@ impl Plugin for TapeRenderAssetPlugin {
let modules = ReplacementModules {
enable_gen: get_module(enable_gen.clone()),
fuzz: get_module(enable_gen.clone()),
normals: get_module(enable_gen.clone()),
spatial_texture: get_module(enable_gen.clone()),
trace: get_module(enable_gen.clone()),
enable_gen_layout: BindGroupLayoutDescriptor::new(
"Enable Gen Layout",
@@ -93,26 +97,10 @@ impl Plugin for TapeRenderAssetPlugin {
(
storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false),
),
),
),
fuzz_layout: BindGroupLayoutDescriptor::new(
"Tape Fuzz Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false),
),
),
),
spatial_texture_layout: BindGroupLayoutDescriptor::new(
"Spatial Texture Layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer::<PackedAabb>(false),
storage_buffer_read_only::<TapeMetadata>(false),
texture_storage_3d(
TextureFormat::R32Float,
StorageTextureAccess::WriteOnly,
),
),
),
),
@@ -172,14 +160,10 @@ pub fn prepare_tape_metadata_fallback_buffer(
#[derive(Resource)]
pub struct ReplacementModules {
pub enable_gen: Module,
pub fuzz: Module,
pub normals: Module,
pub spatial_texture: Module,
pub trace: Module,
pub enable_gen_layout: BindGroupLayoutDescriptor,
pub fuzz_layout: BindGroupLayoutDescriptor,
pub spatial_texture_layout: BindGroupLayoutDescriptor,
}
/// The render world representation of a [`Tape`].
@@ -191,14 +175,10 @@ pub struct RenderTape {
pub key: u64,
pub enable_gen: Handle<Shader>,
pub fuzz: Handle<Shader>,
pub normals: Handle<Shader>,
pub spatial_texture: Handle<Shader>,
pub trace: Handle<Shader>,
pub enable_gen_pipeline: CachedComputePipelineId,
pub fuzz_pipeline: CachedComputePipelineId,
pub spatial_texture_pipeline: CachedComputePipelineId,
}
impl RenderAsset for RenderTape {
@@ -239,13 +219,9 @@ impl RenderAsset for RenderTape {
time: tape.time,
key,
enable_gen: previous.enable_gen.clone(),
fuzz: previous.fuzz.clone(),
normals: previous.normals.clone(),
spatial_texture: previous.spatial_texture.clone(),
trace: previous.trace.clone(),
enable_gen_pipeline: previous.enable_gen_pipeline,
fuzz_pipeline: previous.fuzz_pipeline,
spatial_texture_pipeline: previous.spatial_texture_pipeline,
});
}
@@ -254,21 +230,11 @@ impl RenderAsset for RenderTape {
replacement_modules.enable_gen.clone(),
"enable_gen",
));
let fuzz = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.fuzz.clone(),
"fuzz",
));
let normals = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.normals.clone(),
"normals",
));
let spatial_texture = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.spatial_texture.clone(),
"spatial_texture",
));
let trace = asset_server.add(tape.sdf_specialize_module_with_key(
key,
replacement_modules.trace.clone(),
@@ -285,38 +251,15 @@ impl RenderAsset for RenderTape {
..Default::default()
});
let fuzz_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
label: Some(format!("bevy_tape_drive::gen_shader::fuzz::{key}").into()),
layout: vec![replacement_modules.fuzz_layout.clone()],
shader: fuzz.clone(),
immediate_size: 12,
entry_point: Some("main".into()),
..Default::default()
});
let spatial_texture_pipeline =
pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
label: Some(format!("bevy_tape_drive::gen_shader::spatial_texture::{key}").into()),
layout: vec![replacement_modules.spatial_texture_layout.clone()],
shader: spatial_texture.clone(),
immediate_size: 12,
entry_point: Some("main".into()),
..Default::default()
});
Ok(RenderTape {
seed: tape.seed,
subdivision: tape.subdivision,
time: tape.time,
key,
enable_gen,
fuzz,
normals,
spatial_texture,
trace,
enable_gen_pipeline,
fuzz_pipeline,
spatial_texture_pipeline,
})
}