split into two crates

This commit is contained in:
2026-10-02 18:01:02 +01:00
parent 10ca25b695
commit 663f67ae3c
55 changed files with 8405 additions and 614 deletions
@@ -0,0 +1,245 @@
use bevy_platform::collections::HashMap;
use core::{hash::Hash, num::NonZeroU32};
/// A free-list allocator for `u32` array indices meant for GPU allocations.
pub struct IndexAllocator {
free: Vec<u32>,
high_water_mark: u32,
}
impl IndexAllocator {
pub fn new() -> Self {
Self {
free: Vec::new(),
high_water_mark: 0,
}
}
/// An exclusive upper bound on every index handed out, for sizing and dispatching over the data
/// they key.
///
/// Not a live count: released indices leave holes below it, and it never shrinks.
pub fn high_water_mark(&self) -> u32 {
self.high_water_mark
}
pub fn allocate(&mut self) -> u32 {
self.free.pop().unwrap_or_else(|| {
let index = self.high_water_mark;
self.high_water_mark += 1;
index
})
}
pub fn release(&mut self, index: u32) {
self.free.push(index);
}
/// How many more indices can be handed out before running past `capacity`.
fn vacancies(&self, capacity: u32) -> u32 {
capacity.saturating_sub(self.high_water_mark) + self.free.len() as u32
}
}
/// Assigns each key an index that stays put for as long as the key is live.
pub struct SlotAllocator<K> {
slots: HashMap<K, u32>,
indices: IndexAllocator,
}
impl<K: Eq + Hash> SlotAllocator<K> {
pub fn new() -> Self {
Self {
slots: HashMap::default(),
indices: IndexAllocator::new(),
}
}
pub fn get(&self, key: &K) -> Option<u32> {
self.slots.get(key).copied()
}
pub fn contains(&self, key: &K) -> bool {
self.slots.contains_key(key)
}
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.slots.keys()
}
pub fn get_or_allocate(&mut self, key: K) -> u32 {
if let Some(&slot) = self.slots.get(&key) {
return slot;
}
let slot = self.indices.allocate();
self.slots.insert(key, slot);
slot
}
pub fn remove(&mut self, key: &K) -> Option<u32> {
let slot = self.slots.remove(key)?;
self.indices.release(slot);
Some(slot)
}
/// How many more distinct keys can be taken on before running past `capacity`.
fn vacancies(&self, capacity: u32) -> u32 {
self.indices.vacancies(capacity)
}
}
/// One occupied slot of a [`RetainedBindingArray`].
struct BindingSlot<T> {
item: T,
/// Live references to this slot. An occupied slot always has at least one live reference.
references: NonZeroU32,
}
/// A binding array whose indices are stable across frames.
///
/// Slots are reference counted by whatever points at them (e.g. materials for textures, instances for
/// mesh slab buffers), and are reused once the last reference goes away.
///
/// `dirty` marks that the contents have changed and the bind group has to be rebuilt.
pub struct RetainedBindingArray<K, T> {
allocator: SlotAllocator<K>,
slots: Vec<Option<BindingSlot<T>>>,
pub dirty: bool,
}
impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
pub fn new() -> Self {
Self {
allocator: SlotAllocator::new(),
slots: Vec::new(),
dirty: false,
}
}
pub fn contains(&self, key: &K) -> bool {
self.allocator.contains(key)
}
/// How many more distinct keys can be held before running past `capacity`.
pub fn vacancies(&self, capacity: u32) -> u32 {
self.allocator.vacancies(capacity)
}
/// Whether [`Self::acquire`] would be able to hand out a reference to `key`.
///
/// Callers that need more than one slot at once check this for all of them before acquiring
/// any, so that they never have to hand a slot straight back.
pub fn has_room(&self, key: &K, capacity: u32) -> bool {
self.contains(key) || self.vacancies(capacity) > 0
}
/// The array's contents in slot order, with `None` for slots that are currently free.
pub fn iter(&self) -> impl Iterator<Item = Option<&T>> {
self.slots
.iter()
.map(|slot| slot.as_ref().map(|slot| &slot.item))
}
/// Takes a reference to `key`'s slot, allocating and filling it if this is the first one.
///
/// Returns `None` if `key` would need a new slot and every slot below `capacity` is taken. The
/// bind group layout declares these arrays with a fixed length, so running past it makes
/// `create_bind_group` fail outright, and callers have to drop whatever wanted the slot.
pub fn acquire(&mut self, key: K, capacity: u32, item: impl FnOnce() -> T) -> Option<u32> {
if !self.has_room(&key, capacity) {
return None;
}
let slot = self.allocator.get_or_allocate(key);
let index = slot as usize;
if self.slots.len() <= index {
self.slots.resize_with(index + 1, || None);
}
if let Some(occupied) = self.slots[index].as_mut() {
occupied.references = occupied.references.saturating_add(1);
} else {
self.slots[index] = Some(BindingSlot {
item: item(),
references: NonZeroU32::MIN,
});
self.dirty = true;
}
Some(slot)
}
/// Drops a reference to `key`'s slot, freeing it if that was the last one.
pub fn release(&mut self, key: &K) {
let Some(slot) = self.allocator.get(key) else {
return;
};
let index = slot as usize;
let Some(occupied) = self.slots[index].as_mut() else {
return;
};
if let Some(remaining) = NonZeroU32::new(occupied.references.get() - 1) {
occupied.references = remaining;
return;
}
self.slots[index] = None;
self.allocator.remove(key);
self.dirty = true;
}
/// Repoints an already-allocated slot at a new value, leaving its index and refcount alone.
pub fn replace(&mut self, key: &K, item: T) {
if let Some(slot) = self.allocator.get(key)
&& let Some(occupied) = self.slots[slot as usize].as_mut()
{
occupied.item = item;
self.dirty = true;
}
}
}
#[cfg(test)]
mod tests {
use super::{IndexAllocator, RetainedBindingArray};
#[test]
fn index_allocator_reuses_released_slots_without_growing() {
let mut slots = IndexAllocator::new();
assert_eq!(slots.allocate(), 0);
assert_eq!(slots.allocate(), 1);
assert_eq!(slots.high_water_mark(), 2);
slots.release(0);
assert_eq!(slots.allocate(), 0);
assert_eq!(slots.high_water_mark(), 2);
}
#[test]
fn retained_binding_array_only_dirties_on_binding_changes() {
let mut bindings = RetainedBindingArray::new();
assert_eq!(bindings.acquire(7, 2, || 11), Some(0));
assert!(bindings.dirty);
bindings.dirty = false;
// Sharing the existing stable slot only changes its refcount
assert_eq!(bindings.acquire(7, 2, || 99), Some(0));
assert!(!bindings.dirty);
assert_eq!(bindings.iter().next(), Some(Some(&11)));
bindings.release(&7);
assert!(!bindings.dirty);
assert!(bindings.contains(&7));
// The final release changes the binding array and makes the slot reusable
bindings.release(&7);
assert!(bindings.dirty);
assert!(!bindings.contains(&7));
assert_eq!(bindings.acquire(8, 2, || 22), Some(0));
}
}
@@ -0,0 +1,265 @@
use super::{
allocator::{RetainedBindingArray, SlotAllocator},
instances::InstanceState,
StandardMaterialAssets,
};
use bevy_asset::AssetId;
use bevy_color::{ColorToComponents, LinearRgba};
use bevy_image::Image;
use bevy_math::Vec3;
use bevy_pbr::StandardMaterial;
use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::{
impl_atomic_pod,
render_asset::{ExtractedAssets, RenderAssets},
render_resource::{AtomicPod, AtomicSparseBufferVec, BufferUsages, Sampler, TextureView},
texture::GpuImage,
};
use bevy_utils::once;
use bytemuck::{Pod, Zeroable};
use core::num::NonZeroU32;
use tracing::{info_span, warn};
pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
const TEXTURE_MAP_NONE: u32 = u32::MAX;
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`] field order.
type MaterialTextures = [Option<AssetId<Image>>; 4];
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuMaterial {
normal_map_texture_id: u32,
base_color_texture_id: u32,
emissive_texture_id: u32,
metallic_roughness_texture_id: u32,
base_color: Vec3,
perceptual_roughness: f32,
emissive: Vec3,
metallic: f32,
_padding: Vec3,
reflectance: f32,
}
impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
/// Stable material and texture slots, plus the retry state for assets that aren't ready yet.
pub struct AssetState {
pub textures: RetainedBindingArray<AssetId<Image>, (TextureView, Sampler)>,
pub materials: AtomicSparseBufferVec<GpuMaterial>,
pub material_slots: SlotAllocator<AssetId<StandardMaterial>>,
material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>,
pub emissive_materials: HashSet<AssetId<StandardMaterial>>,
/// Materials to retry because at least one required texture is not on the GPU yet.
unresolved_materials: HashSet<AssetId<StandardMaterial>>,
/// Bound images whose replacement GPU data has not landed yet.
pending_texture_updates: HashSet<AssetId<Image>>,
}
impl AssetState {
pub fn new() -> Self {
Self {
textures: RetainedBindingArray::new(),
materials: AtomicSparseBufferVec::new(BufferUsages::STORAGE, "solari_materials".into()),
material_slots: SlotAllocator::new(),
material_textures: HashMap::default(),
emissive_materials: HashSet::default(),
unresolved_materials: HashSet::default(),
pending_texture_updates: HashSet::default(),
}
}
pub fn update_materials(
&mut self,
instances: &mut InstanceState,
material_assets: &StandardMaterialAssets,
texture_assets: &RenderAssets<GpuImage>,
) {
let _span = info_span!("update_materials").entered();
for material_id in &material_assets.removed {
self.remove_material(*material_id, instances);
}
for material_id in &material_assets.changed {
self.update_material(*material_id, instances, material_assets, texture_assets);
}
}
/// Swaps in uploaded replacements and retries materials waiting on images.
pub fn update_textures(
&mut self,
instances: &mut InstanceState,
extracted_images: &ExtractedAssets<GpuImage>,
texture_assets: &RenderAssets<GpuImage>,
material_assets: &StandardMaterialAssets,
) {
let _span = info_span!("update_textures").entered();
let mut pending = core::mem::take(&mut self.pending_texture_updates);
pending.extend(extracted_images.added.iter().copied());
for image_id in pending {
if !self.textures.contains(&image_id) {
continue;
}
match texture_assets.get(image_id) {
Some(image) => self.textures.replace(
&image_id,
(image.texture_view.clone(), image.sampler.clone()),
),
None => {
self.pending_texture_updates.insert(image_id);
}
}
}
for material_id in core::mem::take(&mut self.unresolved_materials) {
self.update_material(material_id, instances, material_assets, texture_assets);
}
}
/// Resolves a material's textures and writes it into its stable slot.
fn update_material(
&mut self,
material_id: AssetId<StandardMaterial>,
instances: &mut InstanceState,
material_assets: &StandardMaterialAssets,
texture_assets: &RenderAssets<GpuImage>,
) {
let Some(material) = material_assets.get(&material_id) else {
self.remove_material(material_id, instances);
return;
};
let was_resolved = self.material_slots.contains(&material_id);
let handles = [
&material.normal_map_texture,
&material.base_color_texture,
&material.emissive_texture,
&material.metallic_roughness_texture,
];
// Resolve first so a missing texture leaves no partially acquired slots
let mut textures: MaterialTextures = [None; 4];
for (slot, handle) in textures.iter_mut().zip(handles) {
let Some(handle) = handle else { continue };
let image_id = handle.id();
if texture_assets.get(image_id).is_none() {
self.defer_material(material_id, instances);
return;
}
*slot = Some(image_id);
}
if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get()) {
// At the limit, release the old set once so a replacement can reuse those slots
self.release_material_textures(material_id);
self.material_textures.remove(&material_id);
if self.new_texture_count(&textures) > self.textures.vacancies(MAX_TEXTURE_COUNT.get())
{
once!(warn!(
"Solari scene needs more than {} textures. Materials past that limit will not \
be rendered.",
MAX_TEXTURE_COUNT.get()
));
self.defer_material(material_id, instances);
return;
}
}
let mut texture_ids = [TEXTURE_MAP_NONE; 4];
for (texture_id, image_id) in texture_ids.iter_mut().zip(textures) {
let Some(image_id) = image_id else { continue };
let image = texture_assets.get(image_id).unwrap();
if let Some(slot) = self
.textures
.acquire(image_id, MAX_TEXTURE_COUNT.get(), || {
(image.texture_view.clone(), image.sampler.clone())
})
{
*texture_id = slot;
}
}
self.release_material_textures(material_id);
self.material_textures.insert(material_id, textures);
self.unresolved_materials.remove(&material_id);
let slot = self.material_slots.get_or_allocate(material_id);
let emissive = material.emissive.to_vec3();
let is_emissive = emissive != Vec3::ZERO;
self.materials.grow_and_set(
slot,
GpuMaterial {
normal_map_texture_id: texture_ids[0],
base_color_texture_id: texture_ids[1],
emissive_texture_id: texture_ids[2],
metallic_roughness_texture_id: texture_ids[3],
base_color: LinearRgba::from(material.base_color).to_vec3(),
perceptual_roughness: material.perceptual_roughness.clamp(0.0, 1.0),
emissive,
metallic: material.metallic.clamp(0.0, 1.0),
reflectance: material.reflectance,
_padding: Vec3::ZERO,
},
);
let was_emissive = if is_emissive {
!self.emissive_materials.insert(material_id)
} else {
self.emissive_materials.remove(&material_id)
};
if !was_resolved || was_emissive != is_emissive {
instances.invalidate_material(material_id);
}
}
fn new_texture_count(&self, textures: &MaterialTextures) -> u32 {
let mut count = 0;
for (index, image_id) in textures.iter().enumerate() {
let Some(image_id) = image_id else { continue };
let counted_already = textures[..index].contains(&Some(*image_id));
if !counted_already && !self.textures.contains(image_id) {
count += 1;
}
}
count
}
fn defer_material(
&mut self,
material_id: AssetId<StandardMaterial>,
instances: &mut InstanceState,
) {
self.remove_material(material_id, instances);
self.unresolved_materials.insert(material_id);
}
fn remove_material(
&mut self,
material_id: AssetId<StandardMaterial>,
instances: &mut InstanceState,
) {
self.unresolved_materials.remove(&material_id);
if self.material_slots.remove(&material_id).is_none() {
return;
}
self.release_material_textures(material_id);
self.material_textures.remove(&material_id);
self.emissive_materials.remove(&material_id);
instances.invalidate_material(material_id);
}
fn release_material_textures(&mut self, material_id: AssetId<StandardMaterial>) {
let Some(textures) = self.material_textures.get(&material_id).copied() else {
return;
};
for image_id in textures.into_iter().flatten() {
self.textures.release(&image_id);
}
}
}
@@ -0,0 +1,460 @@
use core::{mem::size_of, ops::Deref};
use bevy_ecs::system::{Res, ResMut};
use bevy_math::Mat3;
use bevy_pbr::DfgLut;
use bevy_render::{
render_asset::RenderAssets,
render_resource::{
BindGroup, BindGroupEntries, BindGroupLayout, Buffer, BufferBinding, BufferDescriptor,
BufferId, BufferSize, BufferUsages, PipelineCache, Sampler, SamplerId, ShaderType,
SparseBufferUpdateBindGroups, SparseBufferUpdateJobs, SparseBufferUpdatePipelines,
StorageBuffer, TextureView, TextureViewId,
},
renderer::{RenderDevice, RenderQueue},
texture::{FallbackImage, GpuImage},
};
use tracing::info_span;
use super::{
RaytracingSceneBindings, TlasInstanceSetupPipeline, allocator::RetainedBindingArray,
lights::GpuLightSource,
};
use crate::scene::extract::ExtractedEnvironmentMapLight;
pub struct BindGroupCacheState {
cached: [Option<BindGroup>; 2],
pub invalid: bool,
last_buffer_ids: [Option<BufferId>; 11],
last_light_count: u32,
last_dfg_ids: Option<(TextureViewId, SamplerId)>,
last_environment_map_light_id: Option<TextureViewId>,
pub dummy_buffer: Buffer,
}
impl BindGroupCacheState {
pub fn new(render_device: &RenderDevice) -> Self {
// Binding arrays are dense, so freed slots still need something valid
// bound into them
let dummy_buffer = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_dummy_binding_array_buffer"),
size: 48,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
Self {
cached: [None, None],
invalid: true,
last_buffer_ids: [None; 11],
last_light_count: 0,
last_dfg_ids: None,
last_environment_map_light_id: None,
dummy_buffer,
}
}
}
fn buffer_bindings<'a>(
buffers: &'a RetainedBindingArray<BufferId, Buffer>,
dummy: &'a Buffer,
) -> Vec<BufferBinding<'a>> {
buffers
.iter()
.map(|buffer| buffer.unwrap_or(dummy).as_entire_buffer_binding())
.collect()
}
impl RaytracingSceneBindings {
/// Each sparse buffer's GPU buffer id, or `None` where it has not been
/// created yet.
fn buffer_ids(&self) -> [Option<BufferId>; 11] {
[
self.assets.materials.buffer().map(Buffer::id),
self.instances.transforms.buffer().map(Buffer::id),
self.instances
.previous_frame_transforms
.buffer()
.map(Buffer::id),
self.instances.geometry_ids.buffer().map(Buffer::id),
self.instances.tape_ids.buffer().map(Buffer::id),
self.instances.material_ids.buffer().map(Buffer::id),
self.instances.blas_refs.buffer().map(Buffer::id),
self.lights.sources.buffer().map(Buffer::id),
self.lights.directional_lights.buffer().map(Buffer::id),
self.lights
.previous_frame_id_translations
.buffer()
.map(Buffer::id),
self.environment_map_light_buffer.buffer().map(Buffer::id),
]
}
fn take_bind_group_invalidation(
&mut self,
dfg_view: &TextureView,
dfg_sampler: &Sampler,
environment_map_light: &TextureView,
) -> bool {
let mut invalid = self.bind_groups.invalid;
self.bind_groups.invalid = false;
for dirty in [
&mut self.instances.vertex_buffers.dirty,
&mut self.instances.index_buffers.dirty,
&mut self.instances.aabb_buffers.dirty,
&mut self.assets.textures.dirty,
] {
invalid |= core::mem::replace(dirty, false);
}
let buffer_ids = self.buffer_ids();
if self.bind_groups.last_buffer_ids != buffer_ids {
self.bind_groups.last_buffer_ids = buffer_ids;
invalid = true;
}
let light_count = self.lights.index.len() as u32;
if self.bind_groups.last_light_count != light_count {
self.bind_groups.last_light_count = light_count;
invalid = true;
}
let dfg_ids = Some((dfg_view.id(), dfg_sampler.id()));
if self.bind_groups.last_dfg_ids != dfg_ids {
self.bind_groups.last_dfg_ids = dfg_ids;
invalid = true;
}
let environment_map_light_id = Some(environment_map_light.id());
if self.bind_groups.last_environment_map_light_id != environment_map_light_id {
self.bind_groups.last_environment_map_light_id = environment_map_light_id;
invalid = true;
}
invalid
}
fn create_bind_group(
&self,
current_index: usize,
render_device: &RenderDevice,
layout: &BindGroupLayout,
fallback_texture: &FallbackImage,
dfg_view: &TextureView,
dfg_sampler: &Sampler,
environment_map_light: &TextureView,
) -> BindGroup {
let _span = info_span!("create_bind_group").entered();
let dummy = &self.bind_groups.dummy_buffer;
let vertex_buffers = buffer_bindings(&self.instances.vertex_buffers, dummy);
let index_buffers = buffer_bindings(&self.instances.index_buffers, dummy);
let aabb_buffers = buffer_bindings(&self.instances.aabb_buffers, dummy);
let (mut textures, mut samplers): (Vec<_>, Vec<_>) = self
.assets
.textures
.iter()
.map(|texture| match texture {
Some((view, sampler)) => (view.deref(), sampler.deref()),
None => (
fallback_texture.d2.texture_view.deref(),
fallback_texture.d2.sampler.deref(),
),
})
.unzip();
if textures.is_empty() {
textures.push(fallback_texture.d2.texture_view.deref());
samplers.push(fallback_texture.d2.sampler.deref());
}
let light_sources = BufferBinding {
buffer: self.lights.sources.buffer().unwrap(),
offset: 0,
size: BufferSize::new(
self.lights.index.len() as u64 * size_of::<GpuLightSource>() as u64,
),
};
let materials = self
.assets
.materials
.buffer()
.unwrap()
.as_entire_buffer_binding();
let transforms = self
.instances
.transforms
.buffer()
.unwrap()
.as_entire_buffer_binding();
let previous_frame_transforms = self
.instances
.previous_frame_transforms
.buffer()
.unwrap()
.as_entire_buffer_binding();
let geometry_ids = self
.instances
.geometry_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let tape_ids = self
.instances
.tape_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let material_ids = self
.instances
.material_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let directional_lights = self
.lights
.directional_lights
.buffer()
.unwrap()
.as_entire_buffer_binding();
let translations = self
.lights
.previous_frame_id_translations
.buffer()
.unwrap()
.as_entire_buffer_binding();
let current = self.tlas.structures[current_index].as_ref().unwrap();
let previous = self.tlas.structures[current_index ^ 1]
.as_ref()
.filter(|_| self.tlas.built[current_index ^ 1])
.unwrap_or(current);
render_device.create_bind_group(
"raytracing_scene_bind_group",
layout,
&BindGroupEntries::sequential((
vertex_buffers.as_slice(),
index_buffers.as_slice(),
aabb_buffers.as_slice(),
textures.as_slice(),
samplers.as_slice(),
materials,
current.as_binding(),
previous.as_binding(),
transforms,
previous_frame_transforms,
geometry_ids,
tape_ids,
material_ids,
light_sources,
directional_lights,
translations,
dfg_view,
dfg_sampler,
environment_map_light,
&self.environment_map_light_sampler,
&self.environment_map_light_buffer,
)),
)
}
fn cache_bind_group(
&mut self,
current_index: usize,
render_device: &RenderDevice,
pipeline_cache: &PipelineCache,
fallback_texture: &FallbackImage,
dfg_view: &TextureView,
dfg_sampler: &Sampler,
environment_map_light: &TextureView,
) -> BindGroup {
if let Some(bind_group) = &self.bind_groups.cached[current_index] {
return bind_group.clone();
}
// Only resolve the layout on a miss, as it locks and hashes the whole
// descriptor
let layout = pipeline_cache.get_bind_group_layout(&self.bind_group_layout);
let bind_group = self.create_bind_group(
current_index,
render_device,
&layout,
fallback_texture,
dfg_view,
dfg_sampler,
environment_map_light,
);
if self.tlas.previous_binding_is_stable() {
self.bind_groups.cached[current_index] = Some(bind_group.clone());
}
bind_group
}
}
/// Finalizes sparse uploads and selects the cached bind group for this frame's
/// TLAS.
pub fn prepare_raytracing_scene_bind_group(
texture_assets: Res<RenderAssets<GpuImage>>,
fallback_texture: Res<FallbackImage>,
dfg_lut: Res<DfgLut>,
extracted_environment_map_light: Res<ExtractedEnvironmentMapLight>,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
pipeline_cache: Res<PipelineCache>,
sparse_buffer_update_pipelines: Res<SparseBufferUpdatePipelines>,
instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
mut sparse_buffer_update_jobs: ResMut<SparseBufferUpdateJobs>,
mut sparse_buffer_update_bind_groups: ResMut<SparseBufferUpdateBindGroups>,
mut bindings: ResMut<RaytracingSceneBindings>,
) {
let bindings = &mut *bindings;
prepare_sparse_uploads(
bindings,
&render_device,
&pipeline_cache,
&mut sparse_buffer_update_jobs,
&mut sparse_buffer_update_bind_groups,
&sparse_buffer_update_pipelines,
);
bindings.tlas.update_instance_setup_bind_group(
&bindings.instances,
&render_device,
&pipeline_cache,
&instance_setup_pipeline,
);
bindings.bind_group = None;
if bindings.instances.live_count == 0 || bindings.lights.index.is_empty() {
return;
}
if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
return;
}
let (dfg_view, dfg_sampler) = texture_assets
.get(&dfg_lut.texture)
.map(|image| (&image.texture_view, &image.sampler))
.unwrap_or((
&fallback_texture.d2.texture_view,
&fallback_texture.d2.sampler,
));
let environment_map_light = prepare_environment_map_light(
&extracted_environment_map_light,
&texture_assets,
&fallback_texture,
&mut bindings.environment_map_light_buffer,
&render_device,
&render_queue,
);
if bindings.take_bind_group_invalidation(dfg_view, dfg_sampler, environment_map_light) {
bindings.bind_groups.cached = [None, None];
}
let current_index = bindings.tlas.current_index;
bindings.bind_group = Some(bindings.cache_bind_group(
current_index,
&render_device,
&pipeline_cache,
&fallback_texture,
dfg_view,
dfg_sampler,
environment_map_light,
));
}
#[derive(ShaderType, Default)]
pub struct GpuEnvironmentMapLight {
pub light_from_world: Mat3,
pub intensity: f32,
}
fn prepare_environment_map_light<'a>(
extracted_environment_map_light: &ExtractedEnvironmentMapLight,
texture_assets: &'a RenderAssets<GpuImage>,
fallback_texture: &'a FallbackImage,
buffer: &mut StorageBuffer<GpuEnvironmentMapLight>,
render_device: &RenderDevice,
render_queue: &RenderQueue,
) -> &'a TextureView {
let cubemap = extracted_environment_map_light
.cubemap
.as_ref()
.and_then(|cubemap| texture_assets.get(cubemap));
let (texture, uniform) = match cubemap {
Some(cubemap) => (
&cubemap.texture_view,
GpuEnvironmentMapLight {
light_from_world: Mat3::from_quat(
extracted_environment_map_light.rotation.inverse(),
),
intensity: extracted_environment_map_light.intensity,
},
),
None => (
&fallback_texture.cube.texture_view,
GpuEnvironmentMapLight::default(),
),
};
buffer.set(uniform);
buffer.write_buffer(render_device, render_queue);
texture
}
/// Queues the compute jobs that scatter each buffer's staged elements into its
/// GPU buffer.
fn prepare_sparse_uploads(
bindings: &mut RaytracingSceneBindings,
device: &RenderDevice,
cache: &PipelineCache,
jobs: &mut SparseBufferUpdateJobs,
groups: &mut SparseBufferUpdateBindGroups,
pipelines: &SparseBufferUpdatePipelines,
) {
let _span = info_span!("prepare_sparse_uploads").entered();
bindings
.assets
.materials
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
let instances = &mut bindings.instances;
instances
.transforms
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
instances
.previous_frame_transforms
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
instances
.geometry_ids
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
instances
.tape_ids
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
instances
.material_ids
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
if bindings.tlas.uses_raw_build() {
instances
.blas_refs
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
}
let lights = &mut bindings.lights;
lights
.sources
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
lights
.directional_lights
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
lights
.previous_frame_id_translations
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
}
@@ -0,0 +1,618 @@
use core::{hash::Hash, num::NonZeroU32};
use bevy_asset::AssetId;
use bevy_ecs::{
entity::{Entity, EntityHashMap, EntityHashSet},
query::{Changed, Or, With},
system::Query,
};
use bevy_math::{Affine3, Affine3Ext, Vec4};
use bevy_mesh::Mesh;
use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
use bevy_platform::collections::HashMap;
use bevy_render::{
impl_atomic_pod,
mesh::allocator::MeshAllocator,
render_resource::{AtomicPod, AtomicSparseBufferVec, Buffer, BufferId, BufferUsages},
};
use bevy_tape_load::{Tape, render::allocator::TapeAllocator};
use bevy_transform::components::GlobalTransform;
use bevy_utils::once;
use bytemuck::{Pod, Zeroable};
use tracing::{info_span, warn};
use super::{
MeshBlasManager, RaytracingMesh3d, RaytracingSceneBindings, Tape3d, TapeBlasManager,
allocator::{IndexAllocator, RetainedBindingArray},
assets::AssetState,
lights::{GpuLightSource, LightSourceId, LightState},
};
pub const MAX_MESH_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
pub const MAX_TAPE_SLAB_COUNT: NonZeroU32 = NonZeroU32::new(500).unwrap();
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuInstanceGeometryIds {
vertex_buffer_id: u32,
vertex_buffer_offset: u32,
index_buffer_id: u32,
index_buffer_offset: u32,
triangle_count: u32,
}
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuInstanceTapeIds {
aabb_buffer_id: u32,
aabb_buffer_offset: u32,
aabb_count: u32,
}
/// A world-from-local affine transform, stored transposed as three rows.
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuTransform([Vec4; 3]);
impl GpuTransform {
/// The three rows as the flat row-major 3x4 a [`TlasInstance`] wants.
///
/// [`TlasInstance`]: bevy_render::render_resource::TlasInstance
fn rows(self) -> [f32; 12] {
bytemuck::cast(self)
}
}
/// The device address of a slot's acceleration structure. Zero marks an
/// inactive slot.
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(transparent)]
pub struct GpuBlasRef(u64);
impl GpuBlasRef {
const NONE: Self = Self(0);
}
impl_atomic_pod!(GpuInstanceGeometryIds, GpuInstanceGeometryIdsBlob);
impl_atomic_pod!(GpuInstanceTapeIds, GpuInstanceTapeIdsBlob);
impl_atomic_pod!(GpuTransform, GpuTransformBlob);
impl_atomic_pod!(GpuBlasRef, GpuBlasRefBlob);
fn storage_buffer<T: AtomicPod>(label: &str) -> AtomicSparseBufferVec<T> {
AtomicSparseBufferVec::new(BufferUsages::STORAGE, label.into())
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum Object {
Mesh(AssetId<Mesh>),
Tape(AssetId<Tape>),
}
/// Everything tracked per raytracing mesh instance.
#[derive(Clone, Copy)]
struct Instance {
slot: u32,
object: Object,
material: AssetId<StandardMaterial>,
buffers: Option<(BufferId, BufferId)>,
}
/// Stable slots, reverse dependency indices and GPU data owned by raytracing
/// instances.
pub struct InstanceState {
pub vertex_buffers: RetainedBindingArray<BufferId, Buffer>,
pub index_buffers: RetainedBindingArray<BufferId, Buffer>,
pub aabb_buffers: RetainedBindingArray<BufferId, Buffer>,
pub transforms: AtomicSparseBufferVec<GpuTransform>,
pub previous_frame_transforms: AtomicSparseBufferVec<GpuTransform>,
pub geometry_ids: AtomicSparseBufferVec<GpuInstanceGeometryIds>,
pub tape_ids: AtomicSparseBufferVec<GpuInstanceTapeIds>,
pub material_ids: AtomicSparseBufferVec<u32>,
pub blas_refs: AtomicSparseBufferVec<GpuBlasRef>,
pub slots: IndexAllocator,
records: EntityHashMap<Instance>,
pub live_count: u32,
pub pending_refresh: EntityHashSet,
object_instances: HashMap<Object, EntityHashSet>,
pub material_instances: HashMap<AssetId<StandardMaterial>, EntityHashSet>,
}
impl InstanceState {
pub fn new() -> Self {
Self {
vertex_buffers: RetainedBindingArray::new(),
index_buffers: RetainedBindingArray::new(),
aabb_buffers: RetainedBindingArray::new(),
transforms: storage_buffer("solari_transforms"),
previous_frame_transforms: storage_buffer("solari_previous_frame_transforms"),
geometry_ids: storage_buffer("solari_geometry_ids"),
tape_ids: storage_buffer("solari_tape_ids"),
material_ids: storage_buffer("solari_material_ids"),
blas_refs: storage_buffer("solari_blas_refs"),
slots: IndexAllocator::new(),
records: EntityHashMap::default(),
live_count: 0,
pending_refresh: EntityHashSet::default(),
object_instances: HashMap::default(),
material_instances: HashMap::default(),
}
}
/// Every drawable instance's slot, mesh and world-from-local transform.
///
/// Only the `wgpu-core` TLAS build path needs this, to fill in the instance
/// descriptors that the raw path sets up on the GPU. Slots with a null
/// acceleration structure reference are not currently drawable, and are
/// left out.
pub fn drawable(&self) -> impl Iterator<Item = (u32, Object, [f32; 12])> + '_ {
self.records.values().filter_map(|instance| {
let slot = instance.slot;
(self.blas_refs.get(slot) != GpuBlasRef::NONE)
.then(|| (slot, instance.object, self.transforms.get(slot).rows()))
})
}
/// Queues every instance using `material_id` to be re-resolved.
pub fn invalidate_material(&mut self, material_id: AssetId<StandardMaterial>) {
if let Some(instances) = self.material_instances.get(&material_id) {
self.pending_refresh.extend(instances.iter().copied());
}
}
}
pub type MeshInstanceQueryData<'w> = (
&'w RaytracingMesh3d,
&'w MeshMaterial3d<StandardMaterial>,
&'w GlobalTransform,
&'w PreviousGlobalTransform,
);
pub type TapeInstanceQueryData<'w> = (
&'w Tape3d,
&'w MeshMaterial3d<StandardMaterial>,
&'w GlobalTransform,
&'w PreviousGlobalTransform,
);
pub enum InstanceQueryData<'w> {
Mesh(MeshInstanceQueryData<'w>),
Tape(TapeInstanceQueryData<'w>),
}
pub type ChangedMeshInstanceFilter = (
With<RaytracingMesh3d>,
Or<(
Changed<RaytracingMesh3d>,
Changed<MeshMaterial3d<StandardMaterial>>,
)>,
);
pub type ChangedTapeInstanceFilter = (
With<Tape3d>,
Or<(Changed<Tape3d>, Changed<MeshMaterial3d<StandardMaterial>>)>,
);
/// The scene state an instance resolves its GPU data against.
pub struct InstanceInputs<'a> {
pub assets: &'a AssetState,
pub mesh_blas_manager: &'a MeshBlasManager,
pub mesh_allocator: &'a MeshAllocator,
pub tape_blas_manager: &'a TapeBlasManager,
pub tape_allocator: &'a TapeAllocator,
}
fn unlink<K: Eq + Hash>(map: &mut HashMap<K, EntityHashSet>, key: &K, entity: Entity) {
let now_empty = map.get_mut(key).is_some_and(|instances| {
instances.remove(&entity);
instances.is_empty()
});
if now_empty {
map.remove(key);
}
}
fn relink<K: Copy + Eq + Hash>(
map: &mut HashMap<K, EntityHashSet>,
entity: Entity,
previous: Option<K>,
key: K,
) {
if previous == Some(key) {
return;
}
if let Some(previous) = previous {
unlink(map, &previous, entity);
}
map.entry(key).or_default().insert(entity);
}
impl InstanceState {
pub fn remove_instances(
&mut self,
lights: &mut LightState,
removed: impl IntoIterator<Item = Entity>,
) {
let _span = info_span!("remove_instances").entered();
for entity in removed {
self.remove_instance(lights, entity);
}
}
pub fn refresh_instances(
&mut self,
inputs: &InstanceInputs,
lights: &mut LightState,
mesh_instances: &Query<MeshInstanceQueryData>,
changed_mesh_instances: &Query<Entity, ChangedMeshInstanceFilter>,
tape_instances: &Query<TapeInstanceQueryData>,
changed_tape_instances: &Query<Entity, ChangedTapeInstanceFilter>,
) {
let _span = info_span!("refresh_instances").entered();
let mut refresh = core::mem::take(&mut self.pending_refresh);
refresh.extend(changed_mesh_instances.iter());
refresh.extend(changed_tape_instances.iter());
let moved_meshes = inputs.mesh_allocator.meshes_displaced_by_slab_growth();
for mesh_id in inputs
.mesh_blas_manager
.changed_meshes()
.iter()
.copied()
.chain(moved_meshes)
{
if let Some(mesh_instances) = self.object_instances.get(&Object::Mesh(mesh_id)) {
refresh.extend(mesh_instances.iter().copied());
}
}
let moved_tapes = inputs.tape_allocator.tapes_displaced_by_slab_growth();
for tape_id in inputs
.tape_blas_manager
.changed_tapes()
.iter()
.copied()
.chain(moved_tapes)
{
if let Some(tape_instances) = self.object_instances.get(&Object::Tape(tape_id)) {
refresh.extend(tape_instances.iter().copied());
}
}
for entity in refresh {
match mesh_instances.get(entity) {
Ok(data) => {
self.refresh_instance(inputs, lights, entity, InstanceQueryData::Mesh(data))
},
Err(_) => match tape_instances.get(entity) {
Ok(data) => {
self.refresh_instance(inputs, lights, entity, InstanceQueryData::Tape(data))
},
Err(_) => self.remove_instance(lights, entity),
},
}
}
}
fn reserve_slot(&mut self, slot: u32) {
let len = slot + 1;
self.transforms.grow(len);
self.previous_frame_transforms.grow(len);
self.blas_refs.grow(len);
}
fn refresh_instance(
&mut self,
inputs: &InstanceInputs,
lights: &mut LightState,
entity: Entity,
data: InstanceQueryData,
) {
let previous = self.records.get(&entity).copied();
let (id, material, transform, previous_frame_transform) = match data {
InstanceQueryData::Mesh((mesh, material, transform, previous_frame_transform)) => (
Object::Mesh(mesh.id()),
material,
transform,
previous_frame_transform,
),
InstanceQueryData::Tape((tape, material, transform, previous_frame_transform)) => (
Object::Tape(tape.id()),
material,
transform,
previous_frame_transform,
),
};
let material_id = material.id();
relink(
&mut self.object_instances,
entity,
previous.map(|instance| instance.object),
id,
);
relink(
&mut self.material_instances,
entity,
previous.map(|instance| instance.material),
material_id,
);
let slot = match previous {
Some(previous) => previous.slot,
None => self.slots.allocate(),
};
self.reserve_slot(slot);
// Seed only once. Later refreshes must not overwrite transforms written
// by extraction.
if previous.is_none() {
self.write_transforms(slot, transform, previous_frame_transform);
}
let mut instance = Instance {
slot,
object: id,
material: material_id,
buffers: previous.and_then(|instance| instance.buffers),
};
let resolved = self.resolve_instance(inputs, lights, entity, &mut instance);
self.records.insert(entity, instance);
if !resolved {
self.pending_refresh.insert(entity);
}
}
fn resolve_instance(
&mut self,
inputs: &InstanceInputs,
lights: &mut LightState,
entity: Entity,
instance: &mut Instance,
) -> bool {
match instance.object {
Object::Mesh(asset_id) => {
self.resolve_mesh_instance(inputs, lights, entity, asset_id, instance)
},
Object::Tape(asset_id) => {
self.resolve_tape_instance(inputs, lights, entity, asset_id, instance)
},
}
}
fn resolve_mesh_instance(
&mut self,
inputs: &InstanceInputs,
lights: &mut LightState,
entity: Entity,
mesh_id: AssetId<Mesh>,
instance: &mut Instance,
) -> bool {
bevy_log::debug!("Resolving mesh instance {mesh_id}");
let slot = instance.slot;
let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = (
inputs.mesh_allocator.mesh_vertex_slice(&mesh_id),
inputs.mesh_allocator.mesh_index_slice(&mesh_id),
inputs.assets.material_slots.get(&instance.material),
inputs.mesh_blas_manager.device_address(&mesh_id),
) else {
self.deactivate_instance(lights, entity, instance);
return false;
};
let vertex_buffer_key = vertex_slice.buffer.id();
let index_buffer_key = index_slice.buffer.id();
let capacity = MAX_MESH_SLAB_COUNT.get();
if !self.vertex_buffers.has_room(&vertex_buffer_key, capacity)
|| !self.index_buffers.has_room(&index_buffer_key, capacity)
{
once!(warn!(
"Solari scene needs more than {} mesh slabs. Instances past that limit will not \
be rendered.",
MAX_MESH_SLAB_COUNT.get()
));
self.deactivate_instance(lights, entity, instance);
return false;
}
let previous_buffers = instance.buffers.take();
let vertex_buffer_id = self
.vertex_buffers
.acquire(vertex_buffer_key, capacity, || vertex_slice.buffer.clone())
.expect("vertex slab binding array had room but handed out no slot");
let index_buffer_id = self
.index_buffers
.acquire(index_buffer_key, capacity, || index_slice.buffer.clone())
.expect("index slab binding array had room but handed out no slot");
instance.buffers = Some((vertex_buffer_key, index_buffer_key));
self.release_mesh_buffers(previous_buffers);
let triangle_count = (index_slice.range.len() / 3) as u32;
self.geometry_ids.grow_and_set(
slot,
GpuInstanceGeometryIds {
vertex_buffer_id,
vertex_buffer_offset: vertex_slice.range.start,
index_buffer_id,
index_buffer_offset: index_slice.range.start,
triangle_count,
},
);
self.material_ids.grow_and_set(slot, material_slot);
self.set_blas_ref(slot, GpuBlasRef(blas_address));
let is_emissive = inputs
.assets
.emissive_materials
.contains(&instance.material);
if is_emissive {
lights.add_light(
LightSourceId::EmissiveMesh(entity),
GpuLightSource::new_emissive_mesh_light(slot, triangle_count),
);
} else {
lights.remove_light(LightSourceId::EmissiveMesh(entity));
}
true
}
fn resolve_tape_instance(
&mut self,
inputs: &InstanceInputs,
lights: &mut LightState,
entity: Entity,
tape_id: AssetId<Tape>,
instance: &mut Instance,
) -> bool {
bevy_log::debug!("Resolving tape instance {tape_id}");
let slot = instance.slot;
let (Some(aabb_slice), Some(material_slot), Some(blas_address)) = (
inputs.tape_allocator.tape_aabb_slice(&tape_id),
inputs.assets.material_slots.get(&instance.material),
inputs.tape_blas_manager.device_address(&tape_id),
) else {
self.deactivate_instance(lights, entity, instance);
return false;
};
let aabb_buffer_key = aabb_slice.buffer.id();
let capacity = MAX_TAPE_SLAB_COUNT.get();
if !self.aabb_buffers.has_room(&aabb_buffer_key, capacity) {
once!(warn!(
"Solari scene needs more than {} tape slabs. Instances past that limit will not \
be rendered.",
MAX_TAPE_SLAB_COUNT.get()
));
self.deactivate_instance(lights, entity, instance);
return false;
}
let previous_buffers = instance.buffers.take();
let aabb_buffer_id = self
.aabb_buffers
.acquire(aabb_buffer_key, capacity, || aabb_slice.buffer.clone())
.expect("aabb slab binding array had room but handed out no slot");
instance.buffers = Some((aabb_buffer_key, aabb_buffer_key));
self.release_tape_buffers(previous_buffers);
let aabb_count = (aabb_slice.range.len()) as u32;
self.tape_ids.grow_and_set(
slot,
GpuInstanceTapeIds {
aabb_buffer_id,
aabb_buffer_offset: aabb_slice.range.start,
aabb_count,
},
);
self.material_ids.grow_and_set(slot, material_slot);
self.set_blas_ref(slot, GpuBlasRef(blas_address));
/*
let is_emissive = inputs
.assets
.emissive_materials
.contains(&instance.material);
if is_emissive {
lights.add_light(
LightSourceId::EmissiveMesh(entity),
GpuLightSource::new_emissive_mesh_light(slot, triangle_count),
);
} else {
lights.remove_light(LightSourceId::EmissiveMesh(entity));
}
*/
true
}
fn write_transforms(
&self,
slot: u32,
transform: &GlobalTransform,
previous_frame_transform: &PreviousGlobalTransform,
) {
self.transforms.set_if_changed(
slot,
GpuTransform(Affine3::from(transform.affine()).to_transpose()),
);
self.previous_frame_transforms.set_if_changed(
slot,
GpuTransform(Affine3::from(previous_frame_transform.0).to_transpose()),
);
}
/// Points a slot at an acceleration structure, or at nothing, keeping
/// `live_count` in step.
fn set_blas_ref(&mut self, slot: u32, reference: GpuBlasRef) {
self.blas_refs.grow(slot + 1);
let previous = self.blas_refs.get(slot);
if previous == reference {
return;
}
self.blas_refs.set(slot, reference);
if previous == GpuBlasRef::NONE {
self.live_count += 1;
} else if reference == GpuBlasRef::NONE {
self.live_count -= 1;
}
}
fn deactivate_instance(
&mut self,
lights: &mut LightState,
entity: Entity,
instance: &mut Instance,
) {
self.set_blas_ref(instance.slot, GpuBlasRef::NONE);
lights.remove_light(LightSourceId::EmissiveMesh(entity));
match instance.object {
Object::Mesh(_) => self.release_mesh_buffers(instance.buffers.take()),
Object::Tape(_) => self.release_tape_buffers(instance.buffers.take()),
}
}
fn release_mesh_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
if let Some((vertex_key, index_key)) = buffers {
self.vertex_buffers.release(&vertex_key);
self.index_buffers.release(&index_key);
}
}
fn release_tape_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
if let Some((aabb_key, _)) = buffers {
self.aabb_buffers.release(&aabb_key);
}
}
fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) {
let Some(mut instance) = self.records.remove(&entity) else {
return;
};
self.deactivate_instance(lights, entity, &mut instance);
self.slots.release(instance.slot);
self.pending_refresh.remove(&entity);
unlink(&mut self.object_instances, &instance.object, entity);
unlink(&mut self.material_instances, &instance.material, entity);
}
}
impl RaytracingSceneBindings {
/// Parallel hot path: one entity lookup, then two allocation-free sparse
/// writes.
pub fn move_instance(
&self,
entity: Entity,
transform: &GlobalTransform,
previous_frame_transform: &PreviousGlobalTransform,
) {
if let Some(instance) = self.instances.records.get(&entity) {
self.instances
.write_transforms(instance.slot, transform, previous_frame_transform);
}
}
}
@@ -0,0 +1,310 @@
use super::allocator::SlotAllocator;
use bevy_color::ColorToComponents;
use bevy_ecs::{
entity::{Entity, EntityHashSet},
system::Query,
};
use bevy_math::{ops::cos, Vec3};
use bevy_pbr::ExtractedDirectionalLight;
use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::render_resource::{AtomicSparseBufferVec, BufferUsages};
use bevy_render::{impl_atomic_pod, render_resource::AtomicPod};
use bytemuck::{Pod, Zeroable};
use core::sync::atomic::{AtomicBool, Ordering};
use core::{f32::consts::TAU, hash::Hash};
use tracing::info_span;
const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuLightSource {
kind: u32,
id: u32,
}
/// Stable identity for one source in the light array.
///
/// An entity can contribute both kinds at once, so the entity alone is not enough to identify a
/// source.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum LightSourceId {
EmissiveMesh(Entity),
Directional(Entity),
}
#[derive(Default)]
pub struct LightIndex {
indices: HashMap<LightSourceId, u32>,
ids: Vec<LightSourceId>,
changed: HashSet<LightSourceId>,
}
impl LightIndex {
pub fn len(&self) -> usize {
self.ids.len()
}
pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
fn get(&self, id: &LightSourceId) -> Option<u32> {
self.indices.get(id).copied()
}
fn insert(&mut self, id: LightSourceId) -> u32 {
if let Some(&index) = self.indices.get(&id) {
return index;
}
let index = self.ids.len() as u32;
self.ids.push(id);
self.indices.insert(id, index);
self.changed.insert(id);
index
}
/// Removes `id` and reports both its old index and the old final index.
///
/// Only the ids tracked here are swapped down. When the two indices differ, the caller has to
/// mirror that swap in `sources`, copying the element at the old final index into the hole.
fn remove(&mut self, id: LightSourceId) -> Option<(u32, u32)> {
let index = self.indices.remove(&id)?;
self.changed.insert(id);
let last = self.ids.len() as u32 - 1;
self.ids.swap_remove(index as usize);
if index != last {
let moved = self.ids[index as usize];
self.indices.insert(moved, index);
self.changed.insert(moved);
}
Some((index, last))
}
}
impl GpuLightSource {
pub fn new_emissive_mesh_light(instance_id: u32, triangle_count: u32) -> GpuLightSource {
if triangle_count > u16::MAX as u32 {
panic!("Too many triangles ({triangle_count}) in an emissive mesh, maximum is 65535.");
}
Self {
kind: triangle_count << 1,
id: instance_id,
}
}
fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
Self {
kind: 1,
id: directional_light_id,
}
}
}
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuDirectionalLight {
direction_to_light: Vec3,
cos_theta_max: f32,
luminance: Vec3,
inverse_pdf: f32,
}
impl_atomic_pod!(GpuLightSource, GpuLightSourceBlob);
impl_atomic_pod!(GpuDirectionalLight, GpuDirectionalLightBlob);
impl GpuDirectionalLight {
fn new(directional_light: &ExtractedDirectionalLight) -> Self {
let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0);
let solid_angle = TAU * (1.0 - cos_theta_max);
let luminance =
(directional_light.color.to_vec3() * directional_light.illuminance) / solid_angle;
Self {
direction_to_light: directional_light.transform.back().into(),
cos_theta_max,
luminance,
inverse_pdf: solid_angle,
}
}
}
/// Light slots and the incremental previous-frame id translation state.
pub struct LightState {
/// Kept gap-free because shaders derive the light count with `arrayLength`.
pub sources: AtomicSparseBufferVec<GpuLightSource>,
pub directional_lights: AtomicSparseBufferVec<GpuDirectionalLight>,
pub previous_frame_id_translations: AtomicSparseBufferVec<u32>,
pub index: LightIndex,
/// Light ids as of the last frame whose translation table the lighting shader actually read.
previous_index: HashMap<LightSourceId, u32>,
nonidentity_translations: Vec<u32>,
directional_slots: SlotAllocator<Entity>,
/// Set by the lighting node once it has recorded work reading the translation table.
translations_consumed: AtomicBool,
}
impl LightState {
pub fn new() -> Self {
Self {
sources: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_light_sources".into(),
),
directional_lights: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_directional_lights".into(),
),
previous_frame_id_translations: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_previous_frame_light_id_translations".into(),
),
index: LightIndex::default(),
previous_index: HashMap::default(),
nonidentity_translations: Vec::new(),
directional_slots: SlotAllocator::new(),
translations_consumed: AtomicBool::new(false),
}
}
pub fn update(&mut self, directional_lights: &Query<(Entity, &ExtractedDirectionalLight)>) {
// There are few enough directional lights to just walk them every frame
let _span = info_span!("update_lights").entered();
let mut live_directional_lights = EntityHashSet::default();
for (entity, directional_light) in directional_lights {
live_directional_lights.insert(entity);
let slot = self.directional_slots.get_or_allocate(entity);
self.directional_lights
.grow_and_set(slot, GpuDirectionalLight::new(directional_light));
self.add_light(
LightSourceId::Directional(entity),
GpuLightSource::new_directional_light(slot),
);
}
let stale: Vec<Entity> = self
.directional_slots
.keys()
.copied()
.filter(|entity| !live_directional_lights.contains(entity))
.collect();
for entity in stale {
self.directional_slots.remove(&entity);
self.remove_light(LightSourceId::Directional(entity));
}
self.write_light_id_translations();
if self.index.len() > u16::MAX as usize {
panic!("Too many light sources in the scene, maximum is 65535.");
}
}
pub fn add_light(&mut self, id: LightSourceId, source: GpuLightSource) {
let index = self.index.insert(id);
self.sources.grow_and_set(index, source);
}
/// Removes a light, moving the last one down into the hole so the array stays gap-free.
pub fn remove_light(&mut self, id: LightSourceId) {
let Some((index, last)) = self.index.remove(id) else {
return;
};
if index != last {
let source = self.sources.get(last);
self.sources.grow_and_set(index, source);
}
}
/// Rolls the translation table over for a new frame.
///
/// `previous_index` and `changed` only advance once the shader has read the table. The
/// lighting node bails out while its pipelines compile, and the reservoirs keep the older ids
/// across such a gap, so the next table has to translate from those instead. `has_consumers`
/// is false when no view runs Solari lighting, where deferring forever would grow both
/// without bound.
pub fn begin_frame(&mut self, has_consumers: bool) {
for index in core::mem::take(&mut self.nonidentity_translations) {
self.previous_frame_id_translations
.grow_and_set(index, index);
}
if !has_consumers || self.translations_consumed.swap(false, Ordering::Relaxed) {
for id in core::mem::take(&mut self.index.changed) {
match self.index.get(&id) {
Some(index) => self.previous_index.insert(id, index),
None => self.previous_index.remove(&id),
};
}
}
}
/// Records that the lighting shader read this frame's translation table.
pub fn note_translations_consumed(&self) {
self.translations_consumed.store(true, Ordering::Relaxed);
}
/// Records where each light that moved or disappeared this frame ended up, so that reservoirs
/// still carrying last frame's light ids can be remapped.
fn write_light_id_translations(&mut self) {
for id in &self.index.changed {
// Lights that first appeared since the last read table have no previous id
let Some(&previous) = self.previous_index.get(id) else {
continue;
};
let current = self.index.get(id).unwrap_or(LIGHT_NOT_PRESENT_THIS_FRAME);
if current != previous {
self.previous_frame_id_translations
.grow_and_set(previous, current);
self.nonidentity_translations.push(previous);
}
}
// Every index the shader might read has to be backed by a real element
let light_count = self.index.len() as u32;
let translations = &mut self.previous_frame_id_translations;
if translations.len() < light_count {
let start = translations.len();
translations.grow(light_count);
for index in start..light_count {
translations.set(index, index);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{LightIndex, LightSourceId};
use bevy_ecs::entity::Entity;
#[test]
fn light_index_keeps_sources_on_the_same_entity_independent() {
let entity = Entity::PLACEHOLDER;
let emissive = LightSourceId::EmissiveMesh(entity);
let directional = LightSourceId::Directional(entity);
let mut lights = LightIndex::default();
assert_eq!(lights.insert(emissive), 0);
assert_eq!(lights.insert(directional), 1);
assert_eq!(lights.insert(emissive), 0);
assert_eq!(lights.len(), 2);
assert_eq!(lights.remove(emissive), Some((0, 1)));
assert_eq!(lights.get(&emissive), None);
assert_eq!(lights.get(&directional), Some(0));
assert_eq!(lights.len(), 1);
assert_eq!(lights.remove(directional), Some((0, 0)));
assert!(lights.is_empty());
}
}
@@ -0,0 +1,268 @@
mod allocator;
mod assets;
mod bind_group;
mod instances;
mod lights;
mod tlas;
mod tlas_build;
use bevy_ecs::{
entity::Entity,
lifecycle::RemovedComponents,
resource::Resource,
system::{Query, Res, ResMut},
world::{FromWorld, World},
};
use bevy_pbr::ExtractedDirectionalLight;
use bevy_render::{
mesh::allocator::MeshAllocator,
render_asset::{ExtractedAssets, RenderAssets},
render_resource::{binding_types::*, *},
renderer::{RenderDevice, RenderQueue},
texture::GpuImage,
};
use bevy_tape_load::render::allocator::TapeAllocator;
use tracing::info_span;
use self::{
assets::{AssetState, MAX_TEXTURE_COUNT},
bind_group::{BindGroupCacheState, GpuEnvironmentMapLight},
instances::{
ChangedMeshInstanceFilter, ChangedTapeInstanceFilter, InstanceInputs, InstanceState,
MAX_MESH_SLAB_COUNT, MeshInstanceQueryData, TapeInstanceQueryData,
},
lights::LightState,
tlas::TlasState,
};
pub use self::{
bind_group::prepare_raytracing_scene_bind_group,
tlas::{TlasInstanceSetupPipeline, build_raytracing_tlas},
};
use super::{
RaytracingMesh3d, Tape3d, extract::StandardMaterialAssets,
meshes::blas::BlasManager as MeshBlasManager, tapes::blas::BlasManager as TapeBlasManager,
};
/// Insert this resource into the render world to make the raytracing scene
/// retain the previous frame's TLAS and the light id translation table that
/// maps into it.
///
/// This is useful for temporal techniques that need last frame's data.
/// Retaining it costs a second TLAS allocation and rebuild, so the scene only
/// does so while something asks for it.
#[derive(Resource, Default)]
pub struct RaytracingSceneNeedsPreviousFrameData;
#[derive(Resource)]
pub struct RaytracingSceneBindings {
pub bind_group: Option<BindGroup>,
pub bind_group_layout: BindGroupLayoutDescriptor,
assets: AssetState,
instances: InstanceState,
lights: LightState,
tlas: TlasState,
bind_groups: BindGroupCacheState,
environment_map_light_sampler: Sampler,
environment_map_light_buffer: StorageBuffer<GpuEnvironmentMapLight>,
}
impl RaytracingSceneBindings {
/// Records that a lighting pass read
/// `previous_frame_light_id_translations`, so the next frame's table
/// translates from this frame's light ids rather than older ones.
pub fn note_light_translations_consumed(&self) {
self.lights.note_translations_consumed();
}
}
impl FromWorld for RaytracingSceneBindings {
fn from_world(world: &mut World) -> Self {
let render_device = world.resource::<RenderDevice>();
let bind_group_layout = BindGroupLayoutDescriptor::new(
"raytracing_scene_bind_group_layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
storage_buffer_read_only_sized(false, None).count(MAX_MESH_SLAB_COUNT),
texture_2d(TextureSampleType::Float { filterable: true })
.count(MAX_TEXTURE_COUNT),
sampler(SamplerBindingType::Filtering).count(MAX_TEXTURE_COUNT),
storage_buffer_read_only_sized(false, None),
acceleration_structure(),
acceleration_structure(),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
texture_cube(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering),
storage_buffer_read_only_sized(false, None),
),
),
);
let environment_map_light_sampler = render_device.create_sampler(&SamplerDescriptor {
label: Some("solari_environment_map_light_sampler"),
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mipmap_filter: MipmapFilterMode::Linear,
..Default::default()
});
let mut environment_map_light_buffer = StorageBuffer::<GpuEnvironmentMapLight>::default();
environment_map_light_buffer.set_label(Some("solari_environment_map_light"));
Self {
bind_group: None,
bind_group_layout,
assets: AssetState::new(),
instances: InstanceState::new(),
lights: LightState::new(),
tlas: TlasState::new(render_device),
bind_groups: BindGroupCacheState::new(render_device),
environment_map_light_sampler,
environment_map_light_buffer,
}
}
}
/// Applies this frame's scene changes to the retained buffers, binding arrays
/// and TLAS.
pub fn prepare_raytracing_scene_resources(
(mesh_instances, tape_instances): (Query<MeshInstanceQueryData>, Query<TapeInstanceQueryData>),
(changed_mesh_instances, changed_tape_instances): (
Query<Entity, ChangedMeshInstanceFilter>,
Query<Entity, ChangedTapeInstanceFilter>,
),
(mut removed_mesh_instances, mut removed_tape_instances): (
RemovedComponents<RaytracingMesh3d>,
RemovedComponents<Tape3d>,
),
directional_lights: Query<(Entity, &ExtractedDirectionalLight)>,
needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
(mesh_allocator, tape_allocator): (Res<MeshAllocator>, Res<TapeAllocator>),
(mesh_blas_manager, tape_blas_manager): (Res<MeshBlasManager>, Res<TapeBlasManager>),
material_assets: Res<StandardMaterialAssets>,
texture_assets: Res<RenderAssets<GpuImage>>,
extracted_images: Res<ExtractedAssets<GpuImage>>,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
pipeline_cache: Res<PipelineCache>,
instance_setup_pipeline: Res<TlasInstanceSetupPipeline>,
mut bindings: ResMut<RaytracingSceneBindings>,
) {
let bindings = &mut *bindings;
let needs_previous_frame_data = needs_previous_frame_data.is_some();
// Roll light ids over before any removal or compaction writes this frame's
// translations
bindings.lights.begin_frame(needs_previous_frame_data);
// Update material and texture assets
bindings
.assets
.update_materials(&mut bindings.instances, &material_assets, &texture_assets);
bindings.assets.update_textures(
&mut bindings.instances,
&extracted_images,
&texture_assets,
&material_assets,
);
// Apply structural instance changes, now that asset slots are current
bindings
.instances
.remove_instances(&mut bindings.lights, removed_mesh_instances.read());
bindings
.instances
.remove_instances(&mut bindings.lights, removed_tape_instances.read());
let inputs = InstanceInputs {
assets: &bindings.assets,
mesh_blas_manager: &mesh_blas_manager,
mesh_allocator: &mesh_allocator,
tape_blas_manager: &tape_blas_manager,
tape_allocator: &tape_allocator,
};
bindings.instances.refresh_instances(
&inputs,
&mut bindings.lights,
&mesh_instances,
&changed_mesh_instances,
&tape_instances,
&changed_tape_instances,
);
// Update the light set, now that emissive instances are resolved
bindings.lights.update(&directional_lights);
// Upload the above writes
write_sparse_buffers(bindings, &render_device, &render_queue);
// Prepare the next TLAS
let build_ready = !bindings.tlas.uses_raw_build()
|| instance_setup_pipeline
.id
.and_then(|id| pipeline_cache.get_compute_pipeline(id))
.is_some();
bindings.tlas.advance(
&bindings.instances,
&mut bindings.bind_groups,
&render_device,
build_ready,
needs_previous_frame_data,
);
}
/// Grows every sparse buffer to hold at least one element, then snapshots its
/// dirty set into either a staged sparse update or a full reupload.
fn write_sparse_buffers(
bindings: &mut RaytracingSceneBindings,
device: &RenderDevice,
queue: &RenderQueue,
) {
let _span = info_span!("write_buffers").entered();
let assets = &mut bindings.assets;
assets.materials.grow(1);
assets.materials.write_buffers(device, queue);
let instances = &mut bindings.instances;
instances.transforms.grow(1);
instances.transforms.write_buffers(device, queue);
instances.previous_frame_transforms.grow(1);
instances
.previous_frame_transforms
.write_buffers(device, queue);
instances.geometry_ids.grow(1);
instances.geometry_ids.write_buffers(device, queue);
instances.tape_ids.grow(1);
instances.tape_ids.write_buffers(device, queue);
instances.material_ids.grow(1);
instances.material_ids.write_buffers(device, queue);
if bindings.tlas.uses_raw_build() {
instances.blas_refs.grow(1);
instances.blas_refs.write_buffers(device, queue);
}
let lights = &mut bindings.lights;
lights.sources.grow(1);
lights.sources.write_buffers(device, queue);
lights.directional_lights.grow(1);
lights.directional_lights.write_buffers(device, queue);
lights.previous_frame_id_translations.grow(1);
lights
.previous_frame_id_translations
.write_buffers(device, queue);
}
@@ -0,0 +1,25 @@
@group(0) @binding(0) var<storage, read> transforms: array<array<vec4<f32>, 3>>;
@group(0) @binding(1) var<storage, read> blas_refs: array<vec2<u32>>;
@group(0) @binding(2) var<storage, read_write> instances: array<TlasInstance>;
struct TlasInstance {
transform: array<vec4<f32>, 3>,
custom_data_and_mask: u32,
sbt_offset_and_flags: u32,
blas_ref: vec2<u32>,
}
@compute @workgroup_size(64, 1, 1)
fn setup_tlas_instances(@builtin(global_invocation_id) global_id: vec3<u32>) {
let slot = global_id.x;
if slot >= arrayLength(&instances) || slot >= arrayLength(&blas_refs) || slot >= arrayLength(&transforms) {
return;
}
instances[slot] = TlasInstance(
transforms[slot],
(slot & 0xFFFFFFu) | 0xFF000000u,
0u,
blas_refs[slot],
);
}
@@ -0,0 +1,570 @@
use bevy_asset::load_embedded_asset;
use bevy_ecs::{
resource::Resource,
system::{Res, ResMut},
world::{FromWorld, World},
};
use bevy_render::{
diagnostic::RecordDiagnostics,
render_resource::{
AccelerationStructureFlags, AccelerationStructureUpdateMode, BindGroup, BindGroupEntries,
BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer, BufferDescriptor, BufferId,
BufferUsages, CachedComputePipelineId, CommandEncoderDescriptor, ComputePassDescriptor,
ComputePipelineDescriptor, CreateTlasDescriptor, PipelineCache, ShaderStages, Tlas,
TlasInstance,
binding_types::{storage_buffer_read_only_sized, storage_buffer_sized},
},
renderer::{RenderContext, RenderDevice},
};
use bevy_utils::{default, once};
use tracing::{info_span, warn};
use wgpu::{BufferTransition, BufferUses};
use super::{
MeshBlasManager, RaytracingSceneBindings, TapeBlasManager, bind_group::BindGroupCacheState,
instances::InstanceState, tlas_build,
};
use crate::scene::binder::instances::Object;
/// Compute pipeline that writes per-slot transforms and BLAS addresses into
/// TLAS descriptors.
#[derive(Resource)]
pub struct TlasInstanceSetupPipeline {
pub layout: BindGroupLayoutDescriptor,
pub id: Option<CachedComputePipelineId>,
}
impl FromWorld for TlasInstanceSetupPipeline {
fn from_world(world: &mut World) -> Self {
let layout = BindGroupLayoutDescriptor::new(
"tlas_instance_setup_bind_group_layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_sized(false, None),
),
),
);
if tlas_build::resolve(world.resource::<RenderDevice>()).is_none() {
return Self { layout, id: None };
}
let shader = load_embedded_asset!(world, "setup_tlas_instances.wesl");
let id =
world
.resource::<PipelineCache>()
.queue_compute_pipeline(ComputePipelineDescriptor {
label: Some("tlas_instance_setup_pipeline".into()),
layout: vec![layout.clone()],
shader,
entry_point: Some("setup_tlas_instances".into()),
..default()
});
Self {
layout,
id: Some(id),
}
}
}
/// Smallest TLAS instance capacity handed out, and the floor
/// [`tlas_capacity_for`] grows from.
const TLAS_MIN_CAPACITY: u32 = 128;
/// Width of a TLAS instance's custom data in both Vulkan
/// (`instanceCustomIndex`) and DXR (`InstanceID`). `setup_tlas_instances.wgsl`
/// writes instance slots into that field, so they have to fit.
const TLAS_CUSTOM_DATA_BITS: u32 = 24;
/// Instance capacity to allocate to hold `instance_count` slots.
///
/// Grows geometrically rather than by a fixed step, so reallocations over a
/// scene's lifetime are logarithmic in its size. Being a pure function of the
/// count keeps the descriptor buffer and both TLASes on the same capacity curve
/// without having to coordinate their previous sizes.
fn tlas_capacity_for(instance_count: u32) -> u32 {
let mut capacity = TLAS_MIN_CAPACITY;
while capacity < instance_count {
capacity = capacity.saturating_add(capacity.div_ceil(2));
}
capacity
}
/// The TLAS and its capacity state, double buffered only while something traces
/// last frame's.
///
/// An acceleration structure is only bindable once it has been built. Nothing
/// here owns a BLAS: keeping the ones a built structure points at alive is
/// [`BlasManager`]'s job, which defers every retirement until
/// [`BlasManager::note_tlas_build`] has seen both structures rebuilt.
pub struct TlasState {
/// The backend to build through, or `None` to go through `wgpu-core`.
raw: Option<&'static dyn tlas_build::RawTlasBackend>,
/// Whether last frame's structure is being retained alongside this frame's.
double_buffered: bool,
/// Alternating current/previous acceleration structures. The second is
/// `None` while single buffered.
pub structures: [Option<Tlas>; 2],
capacity: [u32; 2],
/// Whether each structure has had a build recorded since its latest
/// allocation.
pub built: [bool; 2],
/// Which of [`Self::structures`] this frame builds into. The other holds
/// last frame's.
pub current_index: usize,
pub instance_descriptors: Option<Buffer>,
instance_descriptor_capacity: u32,
pub scratch: Option<Buffer>,
scratch_capacity: u64,
scratch_sized_for: u32,
pub instance_setup_bind_group: Option<BindGroup>,
instance_setup_buffer_ids: Option<[BufferId; 3]>,
}
impl TlasState {
pub fn new(render_device: &RenderDevice) -> Self {
Self {
raw: tlas_build::resolve(render_device),
double_buffered: false,
structures: [None, None],
capacity: [0, 0],
built: [false, false],
current_index: 0,
instance_descriptors: None,
instance_descriptor_capacity: 0,
scratch: None,
scratch_capacity: 0,
scratch_sized_for: 0,
instance_setup_bind_group: None,
instance_setup_buffer_ids: None,
}
}
/// Whether builds go through [`tlas_build`]'s raw path rather than
/// `wgpu-core`.
pub fn uses_raw_build(&self) -> bool {
self.raw.is_some()
}
/// Brings the acceleration structure up to date with this frame's changes.
///
/// While `double_buffered`, the two structures alternate: this frame's is
/// rebuilt, and last frame's stays intact so the shaders can trace
/// against it. Otherwise the single structure is rebuilt in place,
/// which is safe because the build is recorded before any pass that traces
/// it and nothing reads last frame's contents.
///
/// `build_ready` reports whether this frame will be able to record a build.
/// When false nothing is allocated or swapped, though an unused
/// structure is still released.
pub fn advance(
&mut self,
instances: &InstanceState,
bind_groups: &mut BindGroupCacheState,
render_device: &RenderDevice,
build_ready: bool,
double_buffered: bool,
) {
let _span = info_span!("advance_tlas").entered();
// Free the retained structure as soon as nothing wants it
self.set_double_buffered(double_buffered, bind_groups);
// An empty scene must not allocate an unbuilt TLAS that could resurface
// as a later previous-frame entry
if !build_ready || instances.slots.high_water_mark() == 0 {
return;
}
debug_assert!(
instances.slots.high_water_mark() < 1 << TLAS_CUSTOM_DATA_BITS,
"instance slot count {} does not fit in a TLAS instance's custom data",
instances.slots.high_water_mark()
);
// Secure every build input before committing the swap. Neither buffer
// exists on the wgpu-core path, which builds from instances
// written into the TLAS itself.
let instance_count = instances.slots.high_water_mark();
if self.raw.is_some() {
self.reserve_instance_descriptors(instance_count, render_device);
self.reserve_tlas_scratch(render_device);
if self.instance_descriptors.is_none() || self.scratch.is_none() {
return;
}
}
if self.double_buffered {
self.current_index ^= 1;
}
let current_index = self.current_index;
self.reserve_tlas(current_index, instance_count, render_device, bind_groups);
}
/// Switches between retaining last frame's structure and rebuilding a
/// single one in place, dropping the structure that is no longer
/// traced.
fn set_double_buffered(
&mut self,
double_buffered: bool,
bind_groups: &mut BindGroupCacheState,
) {
if self.double_buffered != double_buffered {
self.double_buffered = double_buffered;
bind_groups.invalid = true;
}
if double_buffered {
return;
}
// Keep building into whichever structure is already current, so the
// frame this turns off does not have to allocate
let previous_index = self.current_index ^ 1;
if self.structures[previous_index].take().is_some() {
self.capacity[previous_index] = 0;
self.built[previous_index] = false;
bind_groups.invalid = true;
}
}
/// Whether the previous-frame slot's binding will still be correct next
/// frame, and so whether a bind group using it can be cached.
pub fn previous_binding_is_stable(&self) -> bool {
!self.double_buffered || self.built[self.current_index ^ 1]
}
/// Rebuilds the setup shader's bind group only when one of its three
/// buffers moves.
pub fn update_instance_setup_bind_group(
&mut self,
instances: &InstanceState,
render_device: &RenderDevice,
pipeline_cache: &PipelineCache,
pipeline: &TlasInstanceSetupPipeline,
) {
let (Some(transforms), Some(blas_refs), Some(instances)) = (
instances.transforms.buffer(),
instances.blas_refs.buffer(),
self.instance_descriptors.as_ref(),
) else {
self.instance_setup_bind_group = None;
return;
};
let ids = [transforms.id(), blas_refs.id(), instances.id()];
if self.instance_setup_bind_group.is_some() && self.instance_setup_buffer_ids == Some(ids) {
return;
}
let layout = pipeline_cache.get_bind_group_layout(&pipeline.layout);
self.instance_setup_bind_group = Some(render_device.create_bind_group(
"tlas_instance_setup_bind_group",
&layout,
&BindGroupEntries::sequential((
transforms.as_entire_binding(),
blas_refs.as_entire_binding(),
instances.as_entire_binding(),
)),
));
self.instance_setup_buffer_ids = Some(ids);
}
/// Makes sure the instance descriptor buffer covers every stable slot.
fn reserve_instance_descriptors(&mut self, needed: u32, render_device: &RenderDevice) {
if self.instance_descriptors.is_some() && needed <= self.instance_descriptor_capacity {
return;
}
let capacity = tlas_capacity_for(needed);
self.instance_descriptors = Some(render_device.create_buffer(&BufferDescriptor {
label: Some("solari_tlas_instance_descriptors"),
size: u64::from(capacity) * tlas_build::INSTANCE_DESCRIPTOR_SIZE,
usage: BufferUsages::STORAGE | BufferUsages::TLAS_INPUT,
mapped_at_creation: false,
}));
self.instance_descriptor_capacity = capacity;
self.instance_setup_bind_group = None;
}
/// Makes sure the build scratch buffer is big enough for this frame's
/// descriptor capacity.
fn reserve_tlas_scratch(&mut self, render_device: &RenderDevice) {
let capacity = self.instance_descriptor_capacity;
if self.scratch.is_some() && capacity <= self.scratch_sized_for {
return;
}
let (Some(backend), Some(instances)) = (self.raw, self.instance_descriptors.as_ref())
else {
return;
};
let Some(needed) = backend.scratch_size(render_device, instances, capacity) else {
return;
};
self.scratch_sized_for = capacity;
if self.scratch.is_some() && needed <= self.scratch_capacity {
return;
}
// The setup transition lets wgpu retain an outgrown scratch buffer
// until in-flight work releases it
self.scratch = backend.create_scratch_buffer(render_device, needed);
self.scratch_capacity = if self.scratch.is_some() { needed } else { 0 };
}
/// Makes sure one of the two structures can hold every instance slot,
/// leaving the other alone.
fn reserve_tlas(
&mut self,
current_index: usize,
needed: u32,
render_device: &RenderDevice,
bind_groups: &mut BindGroupCacheState,
) {
if self.structures[current_index].is_some() && needed <= self.capacity[current_index] {
return;
}
let capacity = tlas_capacity_for(needed);
self.structures[current_index] = Some(render_device.wgpu_device().create_tlas(
&CreateTlasDescriptor {
label: Some("tlas"),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: AccelerationStructureUpdateMode::Build,
max_instances: capacity,
},
));
self.capacity[current_index] = capacity;
self.built[current_index] = false;
bind_groups.invalid = true;
}
}
/// Records this frame's TLAS build into the render graph's command encoder.
pub fn build_raytracing_tlas(
mut bindings: ResMut<RaytracingSceneBindings>,
mut mesh_blas_manager: ResMut<MeshBlasManager>,
mut tape_blas_manager: ResMut<TapeBlasManager>,
pipeline_cache: Res<PipelineCache>,
pipeline: Res<TlasInstanceSetupPipeline>,
mut render_context: RenderContext,
) {
let bindings = &mut *bindings;
let current_index = bindings.tlas.current_index;
let built = match bindings.tlas.raw {
Some(backend) => {
setup_tlas_instances(bindings, &pipeline_cache, &pipeline, &mut render_context)
&& build_tlas_raw(bindings, backend, &mut render_context)
},
None => build_tlas_through_wgpu_core(
bindings,
&mesh_blas_manager,
&tape_blas_manager,
&mut render_context,
),
};
if built {
bindings.tlas.built[current_index] = true;
// This structure no longer points at whatever was retired before it,
// which is what lets the oldest retirements go
mesh_blas_manager.note_tlas_build();
tape_blas_manager.note_tlas_build();
}
}
/// Writes this frame's TLAS instance descriptors on the GPU, ready for
/// [`build_tlas_raw`].
///
/// Returns whether the pass was recorded. The build has nothing to read when it
/// wasn't.
fn setup_tlas_instances(
bindings: &mut RaytracingSceneBindings,
pipeline_cache: &PipelineCache,
pipeline: &TlasInstanceSetupPipeline,
render_context: &mut RenderContext,
) -> bool {
if bindings.tlas.structures[bindings.tlas.current_index].is_none() {
return false;
}
let (Some(bind_group), Some(compute_pipeline), Some(instances), Some(scratch)) = (
bindings.tlas.instance_setup_bind_group.as_ref(),
pipeline
.id
.and_then(|id| pipeline_cache.get_compute_pipeline(id)),
bindings.tlas.instance_descriptors.as_ref(),
bindings.tlas.scratch.as_ref(),
) else {
// `advance` secures all of these before it allocates the TLAS this is
// setting up for
once!(warn!(
"TLAS allocated but its instance setup pass could not be recorded: bind group={}, \
descriptors={}, scratch={}",
bindings.tlas.instance_setup_bind_group.is_some(),
bindings.tlas.instance_descriptors.is_some(),
bindings.tlas.scratch.is_some(),
));
return false;
};
let slot_count = bindings.instances.slots.high_water_mark();
if slot_count == 0 {
return false;
}
let diagnostics = render_context.diagnostic_recorder();
let diagnostics = diagnostics.as_deref();
let command_encoder = render_context.command_encoder();
let time_span = diagnostics.time_span(command_encoder, "setup_tlas_instances");
{
let mut pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("setup_tlas_instances"),
timestamp_writes: None,
});
pass.set_pipeline(compute_pipeline);
pass.set_bind_group(0, bind_group, &[]);
pass.dispatch_workgroups(slot_count.div_ceil(64), 1, 1);
}
time_span.end(command_encoder);
command_encoder.transition_resources(
[
BufferTransition {
buffer: &**instances,
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
},
BufferTransition {
buffer: &**scratch,
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
},
]
.into_iter(),
core::iter::empty(),
);
true
}
/// Builds from the descriptors [`setup_tlas_instances`] wrote, straight through
/// `wgpu_hal`.
fn build_tlas_raw(
bindings: &mut RaytracingSceneBindings,
backend: &dyn tlas_build::RawTlasBackend,
render_context: &mut RenderContext,
) -> bool {
let current_index = bindings.tlas.current_index;
let (Some(tlas), Some(instances), Some(scratch)) = (
bindings.tlas.structures[current_index].as_mut(),
bindings.tlas.instance_descriptors.as_ref(),
bindings.tlas.scratch.as_ref(),
) else {
once!(warn!(
"TLAS instances were set up but not built: structure={}, descriptors={}, scratch={}",
bindings.tlas.structures[current_index].is_some(),
bindings.tlas.instance_descriptors.is_some(),
bindings.tlas.scratch.is_some(),
));
return false;
};
let render_device = render_context.render_device().clone();
let diagnostics = render_context.diagnostic_recorder();
let diagnostics = diagnostics.as_deref();
let time_span = diagnostics.time_span(render_context.command_encoder(), "tlas_build");
let mut command_encoder = render_device.create_command_encoder(&CommandEncoderDescriptor {
label: Some("tlas_build_command_encoder"),
});
let built = backend.build_tlas(
&mut command_encoder,
tlas,
instances,
bindings.instances.slots.high_water_mark(),
scratch,
);
render_context.add_command_buffer(command_encoder.finish());
time_span.end(render_context.command_encoder());
if !built {
once!(warn!(
"TLAS build recorded nothing; the resolved backend does not own the build resources."
));
}
built
}
/// Builds from instance descriptors filled in on the CPU, through `wgpu-core`.
///
/// The portable path, and the only one Metal can use. It costs work per
/// instance every frame rather than only for the ones that moved, and
/// `wgpu-core` then re-derives the whole build from what it is handed here,
/// which is the cost [`tlas_build`] exists to avoid.
fn build_tlas_through_wgpu_core(
bindings: &mut RaytracingSceneBindings,
mesh_blas_manager: &MeshBlasManager,
tape_blas_manager: &TapeBlasManager,
render_context: &mut RenderContext,
) -> bool {
// An empty scene leaves the index unswapped, so whatever is here belongs to
// an earlier frame and is still being traced as the previous one
if bindings.instances.slots.high_water_mark() == 0 {
return false;
}
let current_index = bindings.tlas.current_index;
let Some(tlas) = bindings.tlas.structures[current_index].as_mut() else {
return false;
};
{
let _span = info_span!("fill_tlas_instances").entered();
// The TLAS outlives the frame, so a slot freed or deactivated since its
// last build still holds that build's instance and has to be
// cleared before this frame's are written
let capacity = tlas.get().len();
tlas[0..capacity].iter_mut().for_each(|entry| *entry = None);
for (slot, object, transform) in bindings.instances.drawable() {
// A mesh can lose its acceleration structure after the instance
// resolved against it, which leaves the slot with
// nothing to point at for a frame
let Some(blas) = (match object {
Object::Mesh(mesh) => mesh_blas_manager.get(&mesh),
Object::Tape(tape) => tape_blas_manager.get(&tape),
}) else {
continue;
};
tlas[slot as usize] = Some(TlasInstance::new(blas, transform, slot, 0xFF));
}
}
let diagnostics = render_context.diagnostic_recorder();
let diagnostics = diagnostics.as_deref();
let command_encoder = render_context.command_encoder();
let time_span = diagnostics.time_span(command_encoder, "tlas_build");
command_encoder.build_acceleration_structures(&[], [&*tlas]);
time_span.end(command_encoder);
true
}
#[cfg(test)]
mod tests {
use super::{TLAS_MIN_CAPACITY, tlas_capacity_for};
#[test]
fn tlas_capacity_grows_geometrically_at_boundaries() {
assert_eq!(tlas_capacity_for(0), TLAS_MIN_CAPACITY);
assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY), TLAS_MIN_CAPACITY);
assert_eq!(tlas_capacity_for(TLAS_MIN_CAPACITY + 1), 192);
assert_eq!(tlas_capacity_for(192), 192);
assert_eq!(tlas_capacity_for(193), 288);
}
}
@@ -0,0 +1,299 @@
//! Building the binder's TLAS through `wgpu_hal` directly, bypassing `wgpu-core` and using
//! an indirect acceleration structure build.
//!
//! Vulkan and DX12 only, as their instance descriptors are byte-identical. Metal cannot work this
//! way: `wgpu-core` makes a TLAS's BLASes resident from its dependency list, and
//! `mark_acceleration_structures_built` clears that list, so traversal would read memory Metal is
//! free to have evicted. Every other backend falls back to the `wgpu-core` build in [`super::tlas`].
//!
//! Every operation has to be instantiated per backend, as `as_hal` is generic over the hal type and
//! wgpu exposes no dynamic equivalent. [`resolve`] does that once, by trying each compiled-in
//! backend and relying on `as_hal` returning `None` for a device that isn't its own, which can't
//! disagree with the adapter actually in use.
#![expect(
unsafe_code,
reason = "Building the TLAS without wgpu-core's per-instance cost requires wgpu_hal."
)]
// With neither backend compiled in every arm is cfg'd away, so nothing here is instantiated. It
// still has to exist, because Solari compiles everywhere and only declines to load at runtime.
#![cfg_attr(
not(any(
windows,
target_os = "linux",
target_os = "android",
target_os = "freebsd"
)),
expect(
dead_code,
unused_variables,
reason = "no backend with a raw TLAS build path is compiled in for this target"
)
)]
use bevy_render::{
render_resource::{Blas, Buffer, BufferDescriptor, BufferUsages, CommandEncoder, Tlas},
renderer::RenderDevice,
};
use core::marker::PhantomData;
use wgpu::{hal, BufferUses};
/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
/// Flags the TLAS is created with, which its build has to be given again.
const TLAS_BUILD_FLAGS: wgpu::AccelerationStructureFlags =
wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE;
/// The `wgpu_hal` operations a raw TLAS build needs, bound to one backend by [`resolve`].
pub trait RawTlasBackend: Send + Sync {
/// Scratch space a TLAS build over `instance_count` instances of `instances` needs.
fn scratch_size(
&self,
render_device: &RenderDevice,
instances: &Buffer,
instance_count: u32,
) -> Option<u64>;
/// Allocates a buffer usable as acceleration structure build scratch.
///
/// There is no [`BufferUsages`] for scratch and `STORAGE` won't do, as Vulkan only adds
/// `SHADER_DEVICE_ADDRESS` for acceleration structure usages. So it is created through hal and
/// handed to `wgpu-core` to own. `wgpu-core` only defers freeing what a submission's tracker
/// references, so the caller transitioning it each frame is what makes replacing it safe.
fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer>;
/// Records a TLAS build reading instance descriptors straight out of `instances`.
///
/// The caller must already have transitioned `instances` to
/// `BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT` and `scratch` to
/// `BufferUses::ACCELERATION_STRUCTURE_SCRATCH`, on an earlier command buffer in the same
/// submission. The scratch transition is not optional even when its state is unchanged: scratch
/// is an exclusive usage, so the redundant-looking transition is what keeps consecutive frames'
/// builds from overlapping in it.
///
/// `encoder` must have no wgpu command recorded into it, including timestamp writes, as
/// `wgpu-core` panics if an encoder mixes the wgpu and raw encoding APIs.
///
/// Marking the build clears the TLAS's dependency list, which is what otherwise keeps the
/// BLASes it points at alive. The caller has to retain them past every submission that might
/// still trace it.
fn build_tlas(
&self,
encoder: &mut CommandEncoder,
tlas: &mut Tlas,
instances: &Buffer,
instance_count: u32,
scratch: &Buffer,
) -> bool;
}
/// The backend to build through, or `None` where this device has no raw path.
pub fn resolve(render_device: &RenderDevice) -> Option<&'static dyn RawTlasBackend> {
let device = render_device.wgpu_device();
#[cfg(any(
windows,
target_os = "linux",
target_os = "android",
target_os = "freebsd"
))]
// SAFETY: the handle is only read, and is dropped with the guard
if unsafe { device.as_hal::<hal::api::Vulkan>() }.is_some() {
return Some(&Hal::<hal::api::Vulkan>::NEW);
}
#[cfg(windows)]
// SAFETY: the handle is only read, and is dropped with the guard
if unsafe { device.as_hal::<hal::api::Dx12>() }.is_some() {
return Some(&Hal::<hal::api::Dx12>::NEW);
}
None
}
/// [`RawTlasBackend`] for one hal backend.
///
/// `fn() -> A` rather than `A`, so the marker is [`Send`] and [`Sync`] whatever `A` is.
struct Hal<A>(PhantomData<fn() -> A>);
impl<A: hal::Api> Hal<A> {
const NEW: Self = Self(PhantomData);
/// Records the build itself, leaving [`RawTlasBackend::build_tlas`] to mark it.
fn record_build(
&self,
encoder: &mut CommandEncoder,
tlas: &mut Tlas,
instances: &Buffer,
instance_count: u32,
scratch: &Buffer,
) -> Option<()> {
use hal::CommandEncoder as _;
// Workaround for https://github.com/gfx-rs/wgpu/issues/10191
let buffer_address = |buffer: &Buffer| {
// SAFETY: the handle is only read, and the buffer is not destroyed here
let guard = unsafe { buffer.as_hal::<A>() }?;
Some(core::ptr::from_ref::<A::Buffer>(&*guard))
};
let hal_instances = buffer_address(instances)?;
let hal_scratch = buffer_address(scratch)?;
// SAFETY: the handle is only read, and the TLAS is not destroyed here
let hal_tlas = unsafe { tlas.as_hal::<A>() }?;
// SAFETY: both buffers outlive this call through the caller's borrows, and neither is
// destroyed between reading its address and the build recording
let (hal_instances, hal_scratch) = unsafe { (&*hal_instances, &*hal_scratch) };
let entries =
hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
buffer: Some(hal_instances),
offset: 0,
count: instance_count,
});
let descriptor = hal::BuildAccelerationStructureDescriptor {
entries: &entries,
mode: hal::AccelerationStructureBuildMode::Build,
flags: TLAS_BUILD_FLAGS,
source_acceleration_structure: None,
destination_acceleration_structure: &*hal_tlas,
scratch_buffer: hal_scratch,
scratch_buffer_offset: 0,
};
// The caller transitioned both buffers, so the only barriers left are the acceleration
// structure's own, which have no public spelling.
//
// SAFETY: every resource in `descriptor` belongs to backend `A` and to this device, the
// scratch buffer is sized by `scratch_size` and used by no other build in this submission,
// and the encoder is neither ended nor its raw handle destroyed here
unsafe {
encoder.as_hal_mut::<A, _, _>(|encoder| {
let encoder = encoder?;
// Write-after-read against submissions still tracing this TLAS as their previous
// frame, and against a BLAS compaction copy submitted ahead of this build. A
// barrier's first scope covers everything already submitted, which covers both.
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
usage: hal::StateTransition {
from: hal::AccelerationStructureUses::SHADER_INPUT
| hal::AccelerationStructureUses::COPY_DST,
to: hal::AccelerationStructureUses::BUILD_OUTPUT
| hal::AccelerationStructureUses::BUILD_INPUT,
},
});
encoder.build_acceleration_structures(1, [descriptor]);
// And read-after-write, for the passes later this frame that trace the result
encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
usage: hal::StateTransition {
from: hal::AccelerationStructureUses::BUILD_OUTPUT,
to: hal::AccelerationStructureUses::SHADER_INPUT,
},
});
Some(())
})
}
}
}
impl<A: hal::Api> RawTlasBackend for Hal<A> {
fn scratch_size(
&self,
render_device: &RenderDevice,
instances: &Buffer,
instance_count: u32,
) -> Option<u64> {
use hal::Device as _;
// SAFETY: the handle is only read, and is dropped with the guard
let hal_device = unsafe { render_device.wgpu_device().as_hal::<A>() }?;
// SAFETY: the handle is only read, and is dropped with the guard
let hal_instances = unsafe { instances.as_hal::<A>() }?;
// Sizing ignores the buffer itself, but `wgpu_hal`'s Metal path unwraps it unconditionally,
// so a real one has to be handed over
let entries =
hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
buffer: Some(&*hal_instances),
offset: 0,
count: instance_count,
});
// SAFETY: `entries` describes a buffer belonging to backend `A`, and the query records
// nothing and reads no memory through it
let sizes = unsafe {
hal_device.get_acceleration_structure_build_sizes(
&hal::GetAccelerationStructureBuildSizesDescriptor {
entries: &entries,
flags: TLAS_BUILD_FLAGS,
},
)
};
Some(sizes.build_scratch_size)
}
fn create_scratch_buffer(&self, render_device: &RenderDevice, size: u64) -> Option<Buffer> {
use hal::Device as _;
let device = render_device.wgpu_device();
let hal_buffer = {
// SAFETY: the handle is only read, and is dropped with the guard
let hal_device = unsafe { device.as_hal::<A>() }?;
// SAFETY: the descriptor is valid and the buffer is handed to `wgpu-core` below, which
// takes over destroying it
unsafe {
hal_device.create_buffer(&hal::BufferDescriptor {
label: Some("solari_tlas_scratch"),
size,
usage: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
memory_flags: hal::MemoryFlags::empty(),
})
}
.ok()?
};
// `usage` is only consulted for wgpu-level validation, which this buffer never sees
let descriptor = BufferDescriptor {
label: Some("solari_tlas_scratch"),
size,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
};
// SAFETY: `hal_buffer` was created from this device, matches `descriptor`, and has nonzero
// size
Some(unsafe { device.create_buffer_from_hal::<A>(hal_buffer, &descriptor) }.into())
}
fn build_tlas(
&self,
encoder: &mut CommandEncoder,
tlas: &mut Tlas,
instances: &Buffer,
instance_count: u32,
scratch: &Buffer,
) -> bool {
if self
.record_build(encoder, tlas, instances, instance_count, scratch)
.is_none()
{
return false;
}
// Without this the build is invisible to `wgpu-core` and it rejects the TLAS when bound
//
// SAFETY: the TLAS was just built into this encoder, and every BLAS its instances point at
// was built and submitted earlier in the frame by `prepare_raytracing_blas`
unsafe {
encoder.mark_acceleration_structures_built(core::iter::empty::<&Blas>(), [&*tlas]);
}
true
}
}