write normals to tiletree texture
This commit is contained in:
@@ -1,27 +1,30 @@
|
||||
use bevy_platform::collections::HashMap;
|
||||
use core::{hash::Hash, num::NonZeroU32};
|
||||
|
||||
use bevy_platform::collections::HashMap;
|
||||
|
||||
/// A free-list allocator for `u32` array indices meant for GPU allocations.
|
||||
pub struct IndexAllocator {
|
||||
free: Vec<u32>,
|
||||
/// Released by [`IndexAllocator::retire`], and not reusable until [`IndexAllocator::recycle_retired`].
|
||||
retired: Vec<u32>,
|
||||
free: Vec<u32>,
|
||||
/// Released by [`IndexAllocator::retire`], and not reusable until
|
||||
/// [`IndexAllocator::recycle_retired`].
|
||||
retired: Vec<u32>,
|
||||
high_water_mark: u32,
|
||||
}
|
||||
|
||||
impl IndexAllocator {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
free: Vec::new(),
|
||||
retired: Vec::new(),
|
||||
free: Vec::new(),
|
||||
retired: Vec::new(),
|
||||
high_water_mark: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusive upper bound on every index handed out, for sizing and dispatching over the data
|
||||
/// they key.
|
||||
/// 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.
|
||||
/// 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
|
||||
}
|
||||
@@ -38,7 +41,8 @@ impl IndexAllocator {
|
||||
self.free.push(index);
|
||||
}
|
||||
|
||||
/// Releases an index, but holds it back from reuse until the next [`IndexAllocator::recycle_retired`].
|
||||
/// Releases an index, but holds it back from reuse until the next
|
||||
/// [`IndexAllocator::recycle_retired`].
|
||||
///
|
||||
/// For indices that last frame's GPU data can still reference.
|
||||
pub fn retire(&mut self, index: u32) {
|
||||
@@ -58,14 +62,14 @@ impl IndexAllocator {
|
||||
|
||||
/// Assigns each key an index that stays put for as long as the key is live.
|
||||
pub struct SlotAllocator<K> {
|
||||
slots: HashMap<K, u32>,
|
||||
slots: HashMap<K, u32>,
|
||||
indices: IndexAllocator,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash> SlotAllocator<K> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: HashMap::default(),
|
||||
slots: HashMap::default(),
|
||||
indices: IndexAllocator::new(),
|
||||
}
|
||||
}
|
||||
@@ -94,7 +98,8 @@ impl<K: Eq + Hash> SlotAllocator<K> {
|
||||
Some(slot)
|
||||
}
|
||||
|
||||
/// How many more distinct keys can be taken on before running past `capacity`.
|
||||
/// How many more distinct keys can be taken on before running past
|
||||
/// `capacity`.
|
||||
fn vacancies(&self, capacity: u32) -> u32 {
|
||||
self.indices.vacancies(capacity)
|
||||
}
|
||||
@@ -102,20 +107,23 @@ impl<K: Eq + Hash> SlotAllocator<K> {
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
/// 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.
|
||||
/// `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>>>,
|
||||
slots: Vec<Option<BindingSlot<T>>>,
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
@@ -123,8 +131,8 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
allocator: SlotAllocator::new(),
|
||||
slots: Vec::new(),
|
||||
dirty: false,
|
||||
slots: Vec::new(),
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,26 +145,31 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
|
||||
self.allocator.vacancies(capacity)
|
||||
}
|
||||
|
||||
/// Whether [`Self::acquire`] would be able to hand out a reference to `key`.
|
||||
/// 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.
|
||||
/// 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.
|
||||
/// 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.
|
||||
/// 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.
|
||||
/// 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;
|
||||
@@ -173,7 +186,7 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
|
||||
occupied.references = occupied.references.saturating_add(1);
|
||||
} else {
|
||||
self.slots[index] = Some(BindingSlot {
|
||||
item: item(),
|
||||
item: item(),
|
||||
references: NonZeroU32::MIN,
|
||||
});
|
||||
self.dirty = true;
|
||||
@@ -202,7 +215,8 @@ impl<K: Eq + Hash, T> RetainedBindingArray<K, T> {
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Repoints an already-allocated slot at a new value, leaving its index and refcount alone.
|
||||
/// 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()
|
||||
@@ -260,7 +274,8 @@ mod tests {
|
||||
assert!(!bindings.dirty);
|
||||
assert!(bindings.contains(&7));
|
||||
|
||||
// The final release changes the binding array and makes the slot reusable
|
||||
// The final release changes the binding array and makes the slot
|
||||
// reusable
|
||||
bindings.release(&7);
|
||||
assert!(bindings.dirty);
|
||||
assert!(!bindings.contains(&7));
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use super::{
|
||||
StandardMaterialAssets,
|
||||
allocator::{RetainedBindingArray, SlotAllocator},
|
||||
instances::InstanceState,
|
||||
};
|
||||
use core::num::NonZeroU32;
|
||||
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_color::{ColorToComponents, LinearRgba};
|
||||
use bevy_image::Image;
|
||||
@@ -18,16 +15,22 @@ use bevy_render::{
|
||||
};
|
||||
use bevy_utils::once;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core::num::NonZeroU32;
|
||||
use tracing::{info_span, warn};
|
||||
|
||||
use super::{
|
||||
StandardMaterialAssets,
|
||||
allocator::{RetainedBindingArray, SlotAllocator},
|
||||
instances::InstanceState,
|
||||
};
|
||||
|
||||
pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
|
||||
const TEXTURE_MAP_NONE: u32 = u32::MAX;
|
||||
|
||||
const MATERIAL_FLAG_DOUBLE_SIDED: u32 = 1 << 0;
|
||||
const MATERIAL_FLAG_FLIP_NORMAL_MAP_Y: u32 = 1 << 1;
|
||||
|
||||
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`] field order.
|
||||
/// The four textures a [`StandardMaterial`] can reference, in [`GpuMaterial`]
|
||||
/// field order.
|
||||
type MaterialTextures = [Option<AssetId<Image>>; 4];
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
@@ -52,30 +55,35 @@ pub struct GpuMaterial {
|
||||
|
||||
impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
|
||||
|
||||
/// Stable material and texture slots, plus the retry state for assets that aren't ready yet.
|
||||
/// 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>>,
|
||||
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>>,
|
||||
pub non_opaque_materials: HashSet<AssetId<StandardMaterial>>,
|
||||
/// Materials to retry because at least one required texture is not on the GPU yet.
|
||||
unresolved_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>>,
|
||||
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(),
|
||||
non_opaque_materials: HashSet::default(),
|
||||
unresolved_materials: HashSet::default(),
|
||||
textures: RetainedBindingArray::new(),
|
||||
materials: AtomicSparseBufferVec::new(
|
||||
BufferUsages::STORAGE,
|
||||
"solari_materials".into(),
|
||||
),
|
||||
material_slots: SlotAllocator::new(),
|
||||
material_textures: HashMap::default(),
|
||||
emissive_materials: HashSet::default(),
|
||||
non_opaque_materials: HashSet::default(),
|
||||
unresolved_materials: HashSet::default(),
|
||||
pending_texture_updates: HashSet::default(),
|
||||
}
|
||||
}
|
||||
@@ -121,7 +129,7 @@ impl AssetState {
|
||||
),
|
||||
None => {
|
||||
self.pending_texture_updates.insert(image_id);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +172,8 @@ impl AssetState {
|
||||
}
|
||||
|
||||
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
|
||||
// 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);
|
||||
|
||||
@@ -206,7 +215,8 @@ impl AssetState {
|
||||
|
||||
let alpha_cutoff = match material.alpha_mode {
|
||||
AlphaMode::Mask(cutoff) => cutoff,
|
||||
// Without MSAA alpha to coverage is treated as a mask with a cutoff of 0.5
|
||||
// Without MSAA alpha to coverage is treated as a mask with a cutoff
|
||||
// of 0.5
|
||||
AlphaMode::AlphaToCoverage => 0.5,
|
||||
AlphaMode::Opaque
|
||||
| AlphaMode::Blend
|
||||
@@ -217,11 +227,12 @@ impl AssetState {
|
||||
let is_opaque = match material.alpha_mode {
|
||||
AlphaMode::Opaque => true,
|
||||
AlphaMode::Mask(_) | AlphaMode::AlphaToCoverage => false,
|
||||
// TODO: Solari doesn't support transparency yet, so these are traced as opaque for now
|
||||
// TODO: Solari doesn't support transparency yet, so these are
|
||||
// traced as opaque for now
|
||||
#[expect(clippy::match_same_arms, reason = "Transparency not yet supported")]
|
||||
AlphaMode::Blend | AlphaMode::Premultiplied | AlphaMode::Add | AlphaMode::Multiply => {
|
||||
true
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let mut flags = 0;
|
||||
|
||||
@@ -37,9 +37,9 @@ impl BindGroupCacheState {
|
||||
// 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,
|
||||
label: Some("solari_dummy_binding_array_buffer"),
|
||||
size: 48,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
@@ -207,7 +207,7 @@ impl RaytracingSceneBindings {
|
||||
let light_sources = BufferBinding {
|
||||
buffer: self.lights.sources.buffer().unwrap(),
|
||||
offset: 0,
|
||||
size: BufferSize::new(
|
||||
size: BufferSize::new(
|
||||
self.lights.index.len() as u64 * size_of::<GpuLightSource>() as u64,
|
||||
),
|
||||
};
|
||||
@@ -373,7 +373,7 @@ pub fn prepare_raytracing_scene_bind_group(
|
||||
#[derive(ShaderType, Default)]
|
||||
pub struct GpuEnvironmentMapLight {
|
||||
pub light_from_world: Mat3,
|
||||
pub intensity: f32,
|
||||
pub intensity: f32,
|
||||
}
|
||||
|
||||
fn prepare_environment_map_light<'a>(
|
||||
@@ -396,7 +396,7 @@ fn prepare_environment_map_light<'a>(
|
||||
light_from_world: Mat3::from_quat(
|
||||
extracted_environment_map_light.rotation.inverse(),
|
||||
),
|
||||
intensity: extracted_environment_map_light.intensity,
|
||||
intensity: extracted_environment_map_light.intensity,
|
||||
},
|
||||
),
|
||||
None => (
|
||||
|
||||
@@ -40,21 +40,21 @@ pub const MAX_TILETREE_COUNT: NonZeroU32 = NonZeroU32::new(5000).unwrap();
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuInstanceGeometryIds {
|
||||
vertex_buffer_id: u32,
|
||||
vertex_buffer_id: u32,
|
||||
vertex_buffer_offset: u32,
|
||||
index_buffer_id: u32,
|
||||
index_buffer_offset: u32,
|
||||
triangle_count: 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,
|
||||
spatial_texture_id: u32,
|
||||
tiletree_id: u32,
|
||||
metadata_buffer_id: u32,
|
||||
aabb_buffer_id: u32,
|
||||
aabb_buffer_offset: u32,
|
||||
spatial_texture_id: u32,
|
||||
tiletree_id: u32,
|
||||
metadata_buffer_id: u32,
|
||||
metadata_buffer_offset: u32,
|
||||
}
|
||||
|
||||
@@ -130,27 +130,27 @@ impl Buffers {
|
||||
/// Everything tracked per raytracing instance.
|
||||
#[derive(Clone, Copy)]
|
||||
struct MeshInstance {
|
||||
slot: u32,
|
||||
mesh: AssetId<Mesh>,
|
||||
slot: u32,
|
||||
mesh: AssetId<Mesh>,
|
||||
material: AssetId<StandardMaterial>,
|
||||
opacity: MeshBlasOpacity,
|
||||
buffers: Option<MeshBuffers>,
|
||||
opacity: MeshBlasOpacity,
|
||||
buffers: Option<MeshBuffers>,
|
||||
}
|
||||
|
||||
/// Everything tracked per raytracing instance.
|
||||
#[derive(Clone, Copy)]
|
||||
struct TapeInstance {
|
||||
slot: u32,
|
||||
tape: AssetId<Tape>,
|
||||
slot: u32,
|
||||
tape: AssetId<Tape>,
|
||||
material: AssetId<StandardMaterial>,
|
||||
opacity: TapeBlasOpacity,
|
||||
buffers: Option<TapeBuffers>,
|
||||
opacity: TapeBlasOpacity,
|
||||
buffers: Option<TapeBuffers>,
|
||||
}
|
||||
|
||||
impl MeshInstance {
|
||||
fn blas_key(&self) -> MeshBlasKey {
|
||||
MeshBlasKey {
|
||||
mesh: self.mesh,
|
||||
mesh: self.mesh,
|
||||
opacity: self.opacity,
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@ impl MeshInstance {
|
||||
impl TapeInstance {
|
||||
fn blas_key(&self) -> TapeBlasKey {
|
||||
TapeBlasKey {
|
||||
tape: self.tape,
|
||||
tape: self.tape,
|
||||
opacity: self.opacity,
|
||||
}
|
||||
}
|
||||
@@ -287,26 +287,26 @@ pub struct InstanceState {
|
||||
impl InstanceState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
vertex_buffers: RetainedBindingArray::new(),
|
||||
index_buffers: RetainedBindingArray::new(),
|
||||
aabb_buffers: RetainedBindingArray::new(),
|
||||
tape_metadata_buffers: RetainedBindingArray::new(),
|
||||
spatial_textures: RetainedBindingArray::new(),
|
||||
tiletrees: RetainedBindingArray::new(),
|
||||
transforms: storage_buffer("solari_transforms"),
|
||||
vertex_buffers: RetainedBindingArray::new(),
|
||||
index_buffers: RetainedBindingArray::new(),
|
||||
aabb_buffers: RetainedBindingArray::new(),
|
||||
tape_metadata_buffers: RetainedBindingArray::new(),
|
||||
spatial_textures: RetainedBindingArray::new(),
|
||||
tiletrees: 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(),
|
||||
retired_mesh_buffers: Vec::new(),
|
||||
retired_tape_buffers: Vec::new(),
|
||||
records: EntityHashMap::default(),
|
||||
live_count: 0,
|
||||
pending_refresh: EntityHashSet::default(),
|
||||
object_instances: HashMap::default(),
|
||||
material_instances: HashMap::default(),
|
||||
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(),
|
||||
retired_mesh_buffers: Vec::new(),
|
||||
retired_tape_buffers: Vec::new(),
|
||||
records: EntityHashMap::default(),
|
||||
live_count: 0,
|
||||
pending_refresh: EntityHashSet::default(),
|
||||
object_instances: HashMap::default(),
|
||||
material_instances: HashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,11 +366,11 @@ pub type ChangedTapeInstanceFilter = (
|
||||
|
||||
/// The scene state an instance resolves its GPU data against.
|
||||
pub struct InstanceInputs<'a> {
|
||||
pub assets: &'a AssetState,
|
||||
pub assets: &'a AssetState,
|
||||
pub mesh_blas_manager: &'a MeshBlasManager,
|
||||
pub mesh_allocator: &'a MeshAllocator,
|
||||
pub mesh_allocator: &'a MeshAllocator,
|
||||
pub tape_blas_manager: &'a TapeBlasManager,
|
||||
pub tape_allocator: &'a TapeAllocator,
|
||||
pub tape_allocator: &'a TapeAllocator,
|
||||
}
|
||||
|
||||
fn unlink<K: Eq + Hash>(map: &mut HashMap<K, EntityHashSet>, key: &K, entity: Entity) {
|
||||
@@ -473,11 +473,11 @@ impl InstanceState {
|
||||
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),
|
||||
},
|
||||
}
|
||||
@@ -560,10 +560,10 @@ impl InstanceState {
|
||||
match instance {
|
||||
Instance::Mesh(instance) => {
|
||||
self.resolve_mesh_instance(inputs, lights, entity, instance)
|
||||
}
|
||||
},
|
||||
Instance::Tape(instance) => {
|
||||
self.resolve_tape_instance(inputs, lights, entity, instance)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -759,8 +759,8 @@ impl InstanceState {
|
||||
.has_room(&spatial_texture_key, spatial_capacity)
|
||||
{
|
||||
once!(warn!(
|
||||
"Solari scene needs more than {} spatial textures. Instances past that limit will not \
|
||||
be rendered.",
|
||||
"Solari scene needs more than {} spatial textures. Instances past that limit will \
|
||||
not be rendered.",
|
||||
MAX_SPATIAL_TEXTURE_COUNT.get()
|
||||
));
|
||||
self.deactivate_tape_instance(lights, entity, instance);
|
||||
@@ -771,8 +771,8 @@ impl InstanceState {
|
||||
let tiletree_capacity = MAX_TILETREE_COUNT.get();
|
||||
if !self.tiletrees.has_room(&tiletree_key, spatial_capacity) {
|
||||
once!(warn!(
|
||||
"Solari scene needs more than {} tiletrees. Instances past that limit will not \
|
||||
be rendered.",
|
||||
"Solari scene needs more than {} tiletrees. Instances past that limit will not be \
|
||||
rendered.",
|
||||
MAX_TILETREE_COUNT.get()
|
||||
));
|
||||
self.deactivate_tape_instance(lights, entity, instance);
|
||||
@@ -921,10 +921,10 @@ impl InstanceState {
|
||||
match instance {
|
||||
Instance::Mesh(mut instance) => {
|
||||
self.deactivate_mesh_instance(lights, entity, &mut instance)
|
||||
}
|
||||
},
|
||||
Instance::Tape(mut instance) => {
|
||||
self.deactivate_tape_instance(lights, entity, &mut instance)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
self.slots.retire(instance.get_slot());
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
use core::{
|
||||
f32::consts::TAU,
|
||||
hash::Hash,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
|
||||
use bevy_math::{Vec3, ops::cos};
|
||||
use bevy_platform::collections::{HashMap, HashSet};
|
||||
use bevy_render::{
|
||||
impl_atomic_pod,
|
||||
render_resource::{AtomicPod, AtomicSparseBufferVec, BufferUsages},
|
||||
};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
use super::allocator::SlotAllocator;
|
||||
use crate::scene::extract::{
|
||||
ExtractedRaytracingDirectionalLight, ExtractedRaytracingPointLight,
|
||||
ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
|
||||
};
|
||||
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
|
||||
use bevy_math::{Vec3, ops::cos};
|
||||
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};
|
||||
|
||||
const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
|
||||
|
||||
@@ -25,7 +32,7 @@ const LIGHT_SOURCE_KIND_RECT: u32 = 3;
|
||||
#[repr(C)]
|
||||
pub struct GpuLightSource {
|
||||
kind: u32,
|
||||
id: u32,
|
||||
id: u32,
|
||||
}
|
||||
|
||||
/// Stable identity for one light in the light array.
|
||||
@@ -41,7 +48,7 @@ pub enum LightSourceId {
|
||||
#[derive(Default)]
|
||||
pub struct LightIndex {
|
||||
indices: HashMap<LightSourceId, u32>,
|
||||
ids: Vec<LightSourceId>,
|
||||
ids: Vec<LightSourceId>,
|
||||
changed: HashSet<LightSourceId>,
|
||||
}
|
||||
|
||||
@@ -72,8 +79,9 @@ impl LightIndex {
|
||||
|
||||
/// 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.
|
||||
/// 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);
|
||||
@@ -99,28 +107,28 @@ impl GpuLightSource {
|
||||
|
||||
Self {
|
||||
kind: (triangle_count << LIGHT_SOURCE_KIND_BITS) | LIGHT_SOURCE_KIND_EMISSIVE_MESH,
|
||||
id: instance_id,
|
||||
id: instance_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
|
||||
Self {
|
||||
kind: LIGHT_SOURCE_KIND_DIRECTIONAL,
|
||||
id: directional_light_id,
|
||||
id: directional_light_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_point_light(point_light_id: u32) -> GpuLightSource {
|
||||
Self {
|
||||
kind: LIGHT_SOURCE_KIND_POINT,
|
||||
id: point_light_id,
|
||||
id: point_light_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_rect_light(rect_light_id: u32) -> GpuLightSource {
|
||||
Self {
|
||||
kind: LIGHT_SOURCE_KIND_RECT,
|
||||
id: rect_light_id,
|
||||
id: rect_light_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,32 +137,32 @@ impl GpuLightSource {
|
||||
#[repr(C)]
|
||||
pub struct GpuDirectionalLight {
|
||||
direction_to_light: Vec3,
|
||||
cos_theta_max: f32,
|
||||
luminance: Vec3,
|
||||
inverse_pdf: f32,
|
||||
cos_theta_max: f32,
|
||||
luminance: Vec3,
|
||||
inverse_pdf: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuPointLight {
|
||||
position: Vec3,
|
||||
radius: f32,
|
||||
position: Vec3,
|
||||
radius: f32,
|
||||
intensity: Vec3,
|
||||
cos_inner: f32,
|
||||
axis: Vec3,
|
||||
axis: Vec3,
|
||||
cos_outer: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GpuRectLight {
|
||||
center: Vec3,
|
||||
area: f32,
|
||||
edge_x: Vec3,
|
||||
center: Vec3,
|
||||
area: f32,
|
||||
edge_x: Vec3,
|
||||
_padding0: f32,
|
||||
edge_y: Vec3,
|
||||
edge_y: Vec3,
|
||||
_padding1: f32,
|
||||
radiance: Vec3,
|
||||
radiance: Vec3,
|
||||
_padding2: f32,
|
||||
}
|
||||
|
||||
@@ -187,22 +195,22 @@ impl GpuPointLight {
|
||||
fn new_point(point_light: &ExtractedRaytracingPointLight) -> Self {
|
||||
// Point lights get a cone that never cuts anything off
|
||||
Self {
|
||||
position: point_light.position,
|
||||
radius: point_light.radius,
|
||||
position: point_light.position,
|
||||
radius: point_light.radius,
|
||||
intensity: point_light.intensity,
|
||||
cos_inner: -1.0,
|
||||
axis: Vec3::NEG_Z,
|
||||
axis: Vec3::NEG_Z,
|
||||
cos_outer: -1.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_spot(spot_light: &ExtractedRaytracingSpotLight) -> Self {
|
||||
Self {
|
||||
position: spot_light.position,
|
||||
radius: spot_light.radius,
|
||||
position: spot_light.position,
|
||||
radius: spot_light.radius,
|
||||
intensity: spot_light.intensity,
|
||||
cos_inner: spot_light.cos_inner,
|
||||
axis: spot_light.axis,
|
||||
axis: spot_light.axis,
|
||||
cos_outer: spot_light.cos_outer,
|
||||
}
|
||||
}
|
||||
@@ -211,13 +219,13 @@ impl GpuPointLight {
|
||||
impl GpuRectLight {
|
||||
fn new(rect_light: &ExtractedRaytracingRectLight) -> Self {
|
||||
Self {
|
||||
center: rect_light.center,
|
||||
area: rect_light.area,
|
||||
edge_x: rect_light.edge_x,
|
||||
center: rect_light.center,
|
||||
area: rect_light.area,
|
||||
edge_x: rect_light.edge_x,
|
||||
_padding0: 0.0,
|
||||
edge_y: rect_light.edge_y,
|
||||
edge_y: rect_light.edge_y,
|
||||
_padding1: 0.0,
|
||||
radiance: rect_light.radiance,
|
||||
radiance: rect_light.radiance,
|
||||
_padding2: 0.0,
|
||||
}
|
||||
}
|
||||
@@ -232,14 +240,17 @@ pub struct LightState {
|
||||
pub rect_lights: AtomicSparseBufferVec<GpuRectLight>,
|
||||
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.
|
||||
/// 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_light_slots: SlotAllocator<Entity>,
|
||||
/// Spot lights share the point light buffer, and so cannot be keyed by just Entity.
|
||||
/// Spot lights share the point light buffer, and so cannot be keyed by just
|
||||
/// Entity.
|
||||
point_light_slots: SlotAllocator<LightSourceId>,
|
||||
rect_light_slots: SlotAllocator<Entity>,
|
||||
/// Set by the lighting node once it has recorded work reading the translation table.
|
||||
/// Set by the lighting node once it has recorded work reading the
|
||||
/// translation table.
|
||||
translations_consumed: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -278,8 +289,9 @@ impl LightState {
|
||||
|
||||
/// Applies this frame's light changes.
|
||||
///
|
||||
/// Lights are retained, so only the ones that changed are processed. Removals go first so that
|
||||
/// a light removed and re-added in the same frame ends up present.
|
||||
/// Lights are retained, so only the ones that changed are processed.
|
||||
/// Removals go first so that a light removed and re-added in the same frame
|
||||
/// ends up present.
|
||||
pub fn update_directional_lights(
|
||||
&mut self,
|
||||
changed: &Query<
|
||||
@@ -288,7 +300,8 @@ impl LightState {
|
||||
>,
|
||||
removed: impl IntoIterator<Item = Entity>,
|
||||
) {
|
||||
// Removals go first so that a light removed and re-added in the same frame ends up present
|
||||
// Removals go first so that a light removed and re-added in the same
|
||||
// frame ends up present
|
||||
for entity in removed {
|
||||
if self.directional_light_slots.remove(&entity).is_some() {
|
||||
self.remove_light(LightSourceId::DirectionalLight(entity));
|
||||
@@ -392,7 +405,8 @@ impl LightState {
|
||||
self.sources.grow_and_set(index, source);
|
||||
}
|
||||
|
||||
/// Removes a light, moving the last one down into the hole so the array stays gap-free.
|
||||
/// 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;
|
||||
@@ -406,10 +420,11 @@ impl LightState {
|
||||
|
||||
/// 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
|
||||
/// `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) {
|
||||
@@ -432,11 +447,13 @@ impl LightState {
|
||||
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.
|
||||
/// 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
|
||||
// Lights that first appeared since the last read table have no
|
||||
// previous id
|
||||
let Some(&previous) = self.previous_index.get(id) else {
|
||||
continue;
|
||||
};
|
||||
@@ -464,9 +481,10 @@ impl LightState {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{LightIndex, LightSourceId};
|
||||
use bevy_ecs::entity::Entity;
|
||||
|
||||
use super::{LightIndex, LightSourceId};
|
||||
|
||||
const ENTITY: Entity = Entity::PLACEHOLDER;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -259,11 +259,11 @@ pub fn prepare_raytracing_scene_resources(
|
||||
.instances
|
||||
.remove_instances(&mut bindings.lights, removed_tape_instances.read());
|
||||
let inputs = InstanceInputs {
|
||||
assets: &bindings.assets,
|
||||
assets: &bindings.assets,
|
||||
mesh_blas_manager: &mesh_blas_manager,
|
||||
mesh_allocator: &mesh_allocator,
|
||||
mesh_allocator: &mesh_allocator,
|
||||
tape_blas_manager: &tape_blas_manager,
|
||||
tape_allocator: &tape_allocator,
|
||||
tape_allocator: &tape_allocator,
|
||||
};
|
||||
bindings.instances.refresh_instances(
|
||||
&inputs,
|
||||
|
||||
@@ -30,7 +30,7 @@ use super::{
|
||||
#[derive(Resource)]
|
||||
pub struct TlasInstanceSetupPipeline {
|
||||
pub layout: BindGroupLayoutDescriptor,
|
||||
pub id: Option<CachedComputePipelineId>,
|
||||
pub id: Option<CachedComputePipelineId>,
|
||||
}
|
||||
|
||||
impl FromWorld for TlasInstanceSetupPipeline {
|
||||
@@ -280,9 +280,9 @@ impl TlasState {
|
||||
|
||||
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,
|
||||
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;
|
||||
@@ -332,9 +332,9 @@ impl TlasState {
|
||||
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,
|
||||
label: Some("tlas"),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE,
|
||||
update_mode: AccelerationStructureUpdateMode::Build,
|
||||
max_instances: capacity,
|
||||
},
|
||||
));
|
||||
@@ -361,7 +361,7 @@ pub fn build_raytracing_tlas(
|
||||
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,
|
||||
@@ -433,7 +433,7 @@ fn setup_tlas_instances(
|
||||
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"),
|
||||
label: Some("setup_tlas_instances"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(compute_pipeline);
|
||||
@@ -446,11 +446,11 @@ fn setup_tlas_instances(
|
||||
[
|
||||
BufferTransition {
|
||||
buffer: &**instances,
|
||||
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
|
||||
state: BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
|
||||
},
|
||||
BufferTransition {
|
||||
buffer: &**scratch,
|
||||
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
|
||||
state: BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
|
||||
},
|
||||
]
|
||||
.into_iter(),
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Building the binder's TLAS through `wgpu_hal` directly, bypassing `wgpu-core` and using
|
||||
//! an indirect acceleration structure build.
|
||||
//! 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`].
|
||||
//! 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.
|
||||
//! 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,
|
||||
@@ -31,11 +33,12 @@
|
||||
)
|
||||
)]
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use bevy_render::{
|
||||
render_resource::{Blas, Buffer, BufferDescriptor, BufferUsages, CommandEncoder, Tlas},
|
||||
renderer::RenderDevice,
|
||||
};
|
||||
use core::marker::PhantomData;
|
||||
use wgpu::{BufferUses, hal};
|
||||
|
||||
/// Size of one TLAS instance descriptor, on both Vulkan and DXR.
|
||||
@@ -45,9 +48,11 @@ pub const INSTANCE_DESCRIPTOR_SIZE: u64 = 64;
|
||||
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`].
|
||||
/// 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.
|
||||
/// Scratch space a TLAS build over `instance_count` instances of
|
||||
/// `instances` needs.
|
||||
fn scratch_size(
|
||||
&self,
|
||||
render_device: &RenderDevice,
|
||||
@@ -57,27 +62,32 @@ pub trait RawTlasBackend: Send + Sync {
|
||||
|
||||
/// 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.
|
||||
/// 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`.
|
||||
/// 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'
|
||||
/// `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.
|
||||
/// `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.
|
||||
/// 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,
|
||||
@@ -114,13 +124,15 @@ pub fn resolve(render_device: &RenderDevice) -> Option<&'static dyn RawTlasBacke
|
||||
|
||||
/// [`RawTlasBackend`] for one hal backend.
|
||||
///
|
||||
/// `fn() -> A` rather than `A`, so the marker is [`Send`] and [`Sync`] whatever `A` is.
|
||||
/// `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.
|
||||
/// Records the build itself, leaving [`RawTlasBackend::build_tlas`] to mark
|
||||
/// it.
|
||||
fn record_build(
|
||||
&self,
|
||||
encoder: &mut CommandEncoder,
|
||||
@@ -133,7 +145,8 @@ impl<A: hal::Api> Hal<A> {
|
||||
|
||||
// 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
|
||||
// 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))
|
||||
};
|
||||
@@ -142,15 +155,16 @@ impl<A: hal::Api> Hal<A> {
|
||||
// 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
|
||||
// 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,
|
||||
count: instance_count,
|
||||
});
|
||||
|
||||
let descriptor = hal::BuildAccelerationStructureDescriptor {
|
||||
@@ -163,35 +177,38 @@ impl<A: hal::Api> Hal<A> {
|
||||
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.
|
||||
// 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
|
||||
// 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.
|
||||
// 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
|
||||
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
|
||||
// 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,
|
||||
to: hal::AccelerationStructureUses::SHADER_INPUT,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -215,22 +232,22 @@ impl<A: hal::Api> RawTlasBackend for 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
|
||||
// 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,
|
||||
count: instance_count,
|
||||
});
|
||||
|
||||
// SAFETY: `entries` describes a buffer belonging to backend `A`, and the query records
|
||||
// nothing and reads no memory through it
|
||||
// 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,
|
||||
flags: TLAS_BUILD_FLAGS,
|
||||
},
|
||||
)
|
||||
};
|
||||
@@ -245,8 +262,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
|
||||
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
|
||||
// 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"),
|
||||
@@ -258,7 +275,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
|
||||
.ok()?
|
||||
};
|
||||
|
||||
// `usage` is only consulted for wgpu-level validation, which this buffer never sees
|
||||
// `usage` is only consulted for wgpu-level validation, which this
|
||||
// buffer never sees
|
||||
let descriptor = BufferDescriptor {
|
||||
label: Some("solari_tlas_scratch"),
|
||||
size,
|
||||
@@ -266,8 +284,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
|
||||
mapped_at_creation: false,
|
||||
};
|
||||
|
||||
// SAFETY: `hal_buffer` was created from this device, matches `descriptor`, and has nonzero
|
||||
// size
|
||||
// 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())
|
||||
}
|
||||
|
||||
@@ -286,10 +304,12 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Without this the build is invisible to `wgpu-core` and it rejects the TLAS when bound
|
||||
// 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`
|
||||
// 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]);
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ pub fn extract_raytracing_scene_tapes_and_materials(
|
||||
/// world.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct StandardMaterialAssets {
|
||||
materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
|
||||
materials: HashMap<AssetId<StandardMaterial>, StandardMaterial>,
|
||||
/// Materials added or modified this frame.
|
||||
pub changed: Vec<AssetId<StandardMaterial>>,
|
||||
/// Materials removed this frame.
|
||||
@@ -213,54 +213,54 @@ pub fn extract_raytracing_material_assets(
|
||||
render_materials.materials.insert(*id, material.clone());
|
||||
render_materials.changed.push(*id);
|
||||
}
|
||||
}
|
||||
},
|
||||
AssetEvent::Removed { id } => {
|
||||
render_materials.materials.remove(id);
|
||||
render_materials.removed.push(*id);
|
||||
}
|
||||
AssetEvent::Unused { .. } | AssetEvent::LoadedWithDependencies { .. } => {}
|
||||
},
|
||||
AssetEvent::Unused { .. } | AssetEvent::LoadedWithDependencies { .. } => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy, PartialEq, Debug)]
|
||||
pub struct ExtractedRaytracingDirectionalLight {
|
||||
pub direction_to_light: Vec3,
|
||||
pub illuminance: Vec3,
|
||||
pub direction_to_light: Vec3,
|
||||
pub illuminance: Vec3,
|
||||
pub sun_disk_angular_size: f32,
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy, PartialEq, Debug)]
|
||||
pub struct ExtractedRaytracingPointLight {
|
||||
pub position: Vec3,
|
||||
pub radius: f32,
|
||||
pub position: Vec3,
|
||||
pub radius: f32,
|
||||
pub intensity: Vec3,
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy, PartialEq, Debug)]
|
||||
pub struct ExtractedRaytracingSpotLight {
|
||||
pub position: Vec3,
|
||||
pub radius: f32,
|
||||
pub position: Vec3,
|
||||
pub radius: f32,
|
||||
pub intensity: Vec3,
|
||||
pub axis: Vec3,
|
||||
pub axis: Vec3,
|
||||
pub cos_inner: f32,
|
||||
pub cos_outer: f32,
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy, PartialEq, Debug)]
|
||||
pub struct ExtractedRaytracingRectLight {
|
||||
pub center: Vec3,
|
||||
pub edge_x: Vec3,
|
||||
pub edge_y: Vec3,
|
||||
pub area: f32,
|
||||
pub center: Vec3,
|
||||
pub edge_x: Vec3,
|
||||
pub edge_y: Vec3,
|
||||
pub area: f32,
|
||||
pub radiance: Vec3,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default, Clone, PartialEq)]
|
||||
pub struct ExtractedEnvironmentMapLight {
|
||||
pub cubemap: Option<Handle<Image>>,
|
||||
pub cubemap: Option<Handle<Image>>,
|
||||
pub intensity: f32,
|
||||
pub rotation: Quat,
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
/// Lights whose extracted data needs updating.
|
||||
@@ -337,8 +337,8 @@ pub fn extract_raytracing_directional_lights(
|
||||
}
|
||||
|
||||
entity_commands.insert(ExtractedRaytracingDirectionalLight {
|
||||
direction_to_light: transform.back().into(),
|
||||
illuminance: LinearRgba::from(directional_light.color).to_vec3()
|
||||
direction_to_light: transform.back().into(),
|
||||
illuminance: LinearRgba::from(directional_light.color).to_vec3()
|
||||
* directional_light.illuminance,
|
||||
sun_disk_angular_size: sun_disk.unwrap_or_default().angular_size,
|
||||
});
|
||||
@@ -370,9 +370,10 @@ pub fn extract_raytracing_point_lights(
|
||||
}
|
||||
|
||||
entity_commands.insert(ExtractedRaytracingPointLight {
|
||||
position: transform.translation(),
|
||||
radius: point_light.radius,
|
||||
// Map from luminous power in lumens to luminous intensity in candela
|
||||
position: transform.translation(),
|
||||
radius: point_light.radius,
|
||||
// Map from luminous power in lumens to luminous intensity in
|
||||
// candela
|
||||
intensity: LinearRgba::from(point_light.color).to_vec3() * point_light.intensity
|
||||
/ (4.0 * PI),
|
||||
});
|
||||
@@ -407,11 +408,11 @@ pub fn extract_raytracing_spot_lights(
|
||||
let inner_angle = spot_light.inner_angle.min(outer_angle);
|
||||
|
||||
entity_commands.insert(ExtractedRaytracingSpotLight {
|
||||
position: transform.translation(),
|
||||
radius: spot_light.radius,
|
||||
position: transform.translation(),
|
||||
radius: spot_light.radius,
|
||||
intensity: LinearRgba::from(spot_light.color).to_vec3() * spot_light.intensity
|
||||
/ (4.0 * PI),
|
||||
axis: transform.forward().into(),
|
||||
axis: transform.forward().into(),
|
||||
cos_inner: cos(inner_angle),
|
||||
cos_outer: cos(outer_angle),
|
||||
});
|
||||
@@ -478,9 +479,9 @@ pub fn extract_raytracing_environment_map_light(
|
||||
};
|
||||
|
||||
let env_map_light = ExtractedEnvironmentMapLight {
|
||||
cubemap: Some(env_map.specular_map.clone()),
|
||||
cubemap: Some(env_map.specular_map.clone()),
|
||||
intensity: env_map.intensity,
|
||||
rotation: env_map.rotation,
|
||||
rotation: env_map.rotation,
|
||||
};
|
||||
|
||||
if extracted_env_map_light.cubemap.is_none() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use alloc::collections::VecDeque;
|
||||
|
||||
use bevy_asset::AssetId;
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
@@ -17,8 +18,9 @@ use bevy_render::{
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
};
|
||||
|
||||
/// After compacting this many vertices worth of meshes per frame, no further BLAS will be compacted.
|
||||
/// Lower this number to distribute the work across more frames.
|
||||
/// After compacting this many vertices worth of meshes per frame, no further
|
||||
/// BLAS will be compacted. Lower this number to distribute the work across more
|
||||
/// frames.
|
||||
const MAX_COMPACTION_VERTICES_PER_FRAME: u32 = 400_000;
|
||||
|
||||
/// Under the `wgpu_hal` build path, we need to manage BLAS lifetimes ourselves.
|
||||
@@ -28,12 +30,12 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct BlasManager {
|
||||
blas: HashMap<AssetId<Mesh>, MeshBlas>,
|
||||
compaction_queue: VecDeque<(BlasKey, u32, bool)>,
|
||||
changed: Vec<AssetId<Mesh>>,
|
||||
/// BLAS that are pending deletion, one batch per TLAS build. The back batch collects
|
||||
/// retirements since the last build, and every batch ahead of it has one more build to wait
|
||||
/// out.
|
||||
blas: HashMap<AssetId<Mesh>, MeshBlas>,
|
||||
compaction_queue: VecDeque<(BlasKey, u32, bool)>,
|
||||
changed: Vec<AssetId<Mesh>>,
|
||||
/// BLAS that are pending deletion, one batch per TLAS build. The back batch
|
||||
/// collects retirements since the last build, and every batch ahead of it
|
||||
/// has one more build to wait out.
|
||||
pending_deletions: VecDeque<Vec<Blas>>,
|
||||
}
|
||||
|
||||
@@ -46,8 +48,8 @@ impl BlasManager {
|
||||
self.get(key)?.handle()
|
||||
}
|
||||
|
||||
/// If a mesh is raytracing compatible, but its [`Mesh::raytracing`] flags don't declare
|
||||
/// the required opacity.
|
||||
/// If a mesh is raytracing compatible, but its [`Mesh::raytracing`] flags
|
||||
/// don't declare the required opacity.
|
||||
pub fn is_undeclared(&self, key: &BlasKey) -> bool {
|
||||
self.blas
|
||||
.get(&key.mesh)
|
||||
@@ -97,16 +99,16 @@ impl BlasManager {
|
||||
}
|
||||
|
||||
struct MeshBlas {
|
||||
requires: MeshRaytracingFlags,
|
||||
opaque: Option<Blas>,
|
||||
requires: MeshRaytracingFlags,
|
||||
opaque: Option<Blas>,
|
||||
non_opaque: Option<Blas>,
|
||||
}
|
||||
|
||||
impl Default for MeshBlas {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
requires: MeshRaytracingFlags::empty(),
|
||||
opaque: None,
|
||||
requires: MeshRaytracingFlags::empty(),
|
||||
opaque: None,
|
||||
non_opaque: None,
|
||||
}
|
||||
}
|
||||
@@ -134,7 +136,7 @@ impl MeshBlas {
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct BlasKey {
|
||||
pub mesh: AssetId<Mesh>,
|
||||
pub mesh: AssetId<Mesh>,
|
||||
pub opacity: BlasOpacity,
|
||||
}
|
||||
|
||||
@@ -232,17 +234,17 @@ pub fn prepare_raytracing_blas(
|
||||
.iter()
|
||||
.map(|(key, vertex_slice, index_slice, blas_size)| {
|
||||
let geometry = BlasTriangleGeometry {
|
||||
size: blas_size,
|
||||
vertex_buffer: vertex_slice.buffer,
|
||||
first_vertex: vertex_slice.range.start,
|
||||
vertex_stride: 48,
|
||||
index_buffer: Some(index_slice.buffer),
|
||||
first_index: Some(index_slice.range.start),
|
||||
transform_buffer: None,
|
||||
size: blas_size,
|
||||
vertex_buffer: vertex_slice.buffer,
|
||||
first_vertex: vertex_slice.range.start,
|
||||
vertex_stride: 48,
|
||||
index_buffer: Some(index_slice.buffer),
|
||||
first_index: Some(index_slice.range.start),
|
||||
transform_buffer: None,
|
||||
transform_buffer_offset: None,
|
||||
};
|
||||
BlasBuildEntry {
|
||||
blas: blas_manager.get(key).unwrap(),
|
||||
blas: blas_manager.get(key).unwrap(),
|
||||
geometry: BlasGeometries::TriangleGeometries(vec![geometry]),
|
||||
}
|
||||
})
|
||||
@@ -326,18 +328,18 @@ fn allocate_blas(
|
||||
) -> (Blas, BlasTriangleGeometrySizeDescriptor) {
|
||||
let blas_size = BlasTriangleGeometrySizeDescriptor {
|
||||
vertex_format: Mesh::ATTRIBUTE_POSITION.format,
|
||||
vertex_count: vertex_slice.range.len() as u32,
|
||||
index_format: Some(IndexFormat::Uint32),
|
||||
index_count: Some(index_slice.range.len() as u32),
|
||||
flags: key.opacity.geometry_flags(),
|
||||
vertex_count: vertex_slice.range.len() as u32,
|
||||
index_format: Some(IndexFormat::Uint32),
|
||||
index_count: Some(index_slice.range.len() as u32),
|
||||
flags: key.opacity.geometry_flags(),
|
||||
};
|
||||
|
||||
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS double-buffer
|
||||
// to avoid invalidating the previous frame TLAS
|
||||
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS
|
||||
// double-buffer to avoid invalidating the previous frame TLAS
|
||||
let blas = render_device.wgpu_device().create_blas(
|
||||
&CreateBlasDescriptor {
|
||||
label: Some(&format!("{} {:?}", key.mesh, key.opacity)),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
label: Some(&format!("{} {:?}", key.mesh, key.opacity)),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
| AccelerationStructureFlags::ALLOW_COMPACTION,
|
||||
update_mode: AccelerationStructureUpdateMode::Build,
|
||||
},
|
||||
|
||||
@@ -12,10 +12,12 @@ use derive_more::derive::From;
|
||||
///
|
||||
/// The mesh used in this component must declare the BLAS its material needs in
|
||||
/// [`Mesh::raytracing`],
|
||||
/// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0, TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`],
|
||||
/// use the following set of vertex attributes: `{POSITION, NORMAL, UV_0,
|
||||
/// TANGENT}`, use [`bevy_mesh::PrimitiveTopology::TriangleList`],
|
||||
/// and use [`bevy_mesh::Indices::U32`].
|
||||
///
|
||||
/// The material used for this entity must be [`MeshMaterial3d<StandardMaterial>`].
|
||||
/// The material used for this entity must be
|
||||
/// [`MeshMaterial3d<StandardMaterial>`].
|
||||
#[derive(
|
||||
Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
|
||||
)]
|
||||
|
||||
@@ -30,9 +30,9 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct BlasManager {
|
||||
blas: HashMap<AssetId<Tape>, TapeBlas>,
|
||||
changed: Vec<AssetId<Tape>>,
|
||||
needs_new_blas: Vec<AssetId<Tape>>,
|
||||
blas: HashMap<AssetId<Tape>, TapeBlas>,
|
||||
changed: Vec<AssetId<Tape>>,
|
||||
needs_new_blas: Vec<AssetId<Tape>>,
|
||||
/// BLAS that are pending deletion, one batch per TLAS build. The back batch
|
||||
/// collects retirements since the last build, and every batch ahead of
|
||||
/// it has one more build to wait out.
|
||||
@@ -106,16 +106,16 @@ impl BlasManager {
|
||||
}
|
||||
|
||||
struct TapeBlas {
|
||||
requires: MeshRaytracingFlags,
|
||||
opaque: Option<Blas>,
|
||||
requires: MeshRaytracingFlags,
|
||||
opaque: Option<Blas>,
|
||||
non_opaque: Option<Blas>,
|
||||
}
|
||||
|
||||
impl Default for TapeBlas {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
requires: MeshRaytracingFlags::empty(),
|
||||
opaque: None,
|
||||
requires: MeshRaytracingFlags::empty(),
|
||||
opaque: None,
|
||||
non_opaque: None,
|
||||
}
|
||||
}
|
||||
@@ -143,7 +143,7 @@ impl TapeBlas {
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct BlasKey {
|
||||
pub tape: AssetId<Tape>,
|
||||
pub tape: AssetId<Tape>,
|
||||
pub opacity: BlasOpacity,
|
||||
}
|
||||
|
||||
@@ -242,28 +242,28 @@ pub fn compile_raytracing_blas(
|
||||
let mut command_encoder = render_context.command_encoder();
|
||||
let time_span = diagnostics.time_span(command_encoder, "tape_blas_build");
|
||||
let mut compute_pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
|
||||
label: Some("enable_gen"),
|
||||
label: Some("enable_gen"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
struct PushConstants {
|
||||
aabb_buffer_offset: u32,
|
||||
aabb_buffer_offset: u32,
|
||||
metadata_buffer_offset: u32,
|
||||
flags: u32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
const FLAG_FILL_ENABLE_GEN: u32 = 1 << 0;
|
||||
const FLAG_FILL_SPATIAL_TEXTURE: u32 = 1 << 1;
|
||||
const FLAG_FILL_TILETREE: u32 = 1 << 1;
|
||||
const FLAG_FILL_TILETREE: u32 = 1 << 2;
|
||||
|
||||
let tape_info = tapes
|
||||
.iter()
|
||||
.filter(|(asset_id, _)| blas_manager.needs_new_blas.contains(asset_id))
|
||||
.map(|(asset_id, tape)| {
|
||||
let key = BlasKey {
|
||||
tape: asset_id,
|
||||
tape: asset_id,
|
||||
opacity: BlasOpacity::Opaque,
|
||||
};
|
||||
|
||||
@@ -274,7 +274,7 @@ pub fn compile_raytracing_blas(
|
||||
|
||||
let blas_size = BlasAABBGeometrySizeDescriptor {
|
||||
primitive_count: aabbs_slice.range.len() as u32,
|
||||
flags: key.opacity.geometry_flags(),
|
||||
flags: key.opacity.geometry_flags(),
|
||||
};
|
||||
|
||||
(
|
||||
@@ -309,9 +309,9 @@ pub fn compile_raytracing_blas(
|
||||
);
|
||||
|
||||
let mut pc = PushConstants {
|
||||
aabb_buffer_offset: aabbs_slice.range.start,
|
||||
aabb_buffer_offset: aabbs_slice.range.start,
|
||||
metadata_buffer_offset: metadata_slice.range.start,
|
||||
flags: FLAG_FILL_ENABLE_GEN,
|
||||
flags: FLAG_FILL_ENABLE_GEN,
|
||||
};
|
||||
|
||||
compute_pass.set_pipeline(pipeline);
|
||||
@@ -329,17 +329,24 @@ pub fn compile_raytracing_blas(
|
||||
tape.subdivision * 2,
|
||||
tape.subdivision * 2,
|
||||
);
|
||||
pc.flags = FLAG_FILL_TILETREE;
|
||||
compute_pass.set_immediates(0, bytemuck::bytes_of(&pc));
|
||||
compute_pass.dispatch_workgroups(
|
||||
(tape.subdivision / 4) * 128,
|
||||
(tape.subdivision / 4) * 128,
|
||||
(tape.subdivision / 4) * 6,
|
||||
);
|
||||
|
||||
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,
|
||||
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_uninit(&key).unwrap(),
|
||||
blas: blas_manager.get_uninit(&key).unwrap(),
|
||||
geometry: BlasGeometries::AabbGeometries(vec![geometry]),
|
||||
})
|
||||
},
|
||||
@@ -379,15 +386,15 @@ fn allocate_blas(
|
||||
) -> (Blas, BlasAABBGeometrySizeDescriptor) {
|
||||
let blas_size = BlasAABBGeometrySizeDescriptor {
|
||||
primitive_count: aabbs_slice.range.len() as u32,
|
||||
flags: key.opacity.geometry_flags(),
|
||||
flags: key.opacity.geometry_flags(),
|
||||
};
|
||||
|
||||
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS
|
||||
// double-buffer to avoid invalidating the previous frame TLAS
|
||||
let blas = render_device.wgpu_device().create_blas(
|
||||
&CreateBlasDescriptor {
|
||||
label: Some(&format!("{} {:?}", key.tape, key.opacity)),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
label: Some(&format!("{} {:?}", key.tape, key.opacity)),
|
||||
flags: AccelerationStructureFlags::PREFER_FAST_TRACE
|
||||
| AccelerationStructureFlags::ALLOW_COMPACTION,
|
||||
update_mode: AccelerationStructureUpdateMode::Build,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user