write normals to tiletree texture

This commit is contained in:
2026-11-02 23:34:10 +00:00
parent ec7c5623de
commit d4bdb18a14
28 changed files with 702 additions and 561 deletions
+9 -7
View File
@@ -15,18 +15,18 @@ pub mod scene;
/// The solari prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
/// This includes the most common types in this crate, re-exported for your
/// convenience.
pub mod prelude {
pub use super::SolariPlugins;
pub use crate::realtime::SolariLighting;
pub use crate::scene::RaytracingMesh3d;
pub use crate::{realtime::SolariLighting, scene::RaytracingMesh3d};
}
use crate::realtime::SolariLightingPlugin;
use crate::scene::RaytracingScenePlugin;
use bevy_app::{PluginGroup, PluginGroupBuilder};
use bevy_render::settings::WgpuFeatures;
use crate::{realtime::SolariLightingPlugin, scene::RaytracingScenePlugin};
/// An experimental set of plugins for raytraced lighting.
///
/// This plugin group provides:
@@ -34,9 +34,11 @@ use bevy_render::settings::WgpuFeatures;
/// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding.
///
/// There's also:
/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for validation purposes (not added by default).
/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for
/// validation purposes (not added by default).
///
/// To get started, add this plugin to your app, and then add `RaytracingMesh3d` and `MeshMaterial3d::<StandardMaterial>` to your entities.
/// To get started, add this plugin to your app, and then add `RaytracingMesh3d`
/// and `MeshMaterial3d::<StandardMaterial>` to your entities.
pub struct SolariPlugins;
impl PluginGroup for SolariPlugins {
@@ -1,4 +1,3 @@
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use bevy_camera::Camera;
use bevy_ecs::{
change_detection::DetectChanges,
@@ -8,6 +7,8 @@ use bevy_ecs::{
use bevy_render::{Extract, sync_world::RenderEntity};
use bevy_transform::components::GlobalTransform;
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
pub fn extract_pathtracer(
cameras_3d: Extract<
Query<(
@@ -2,7 +2,6 @@ mod extract;
mod node;
mod prepare;
use crate::{SolariPlugins, scene::RaytracingSceneBindings};
use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::embedded_asset;
use bevy_camera::Hdr;
@@ -29,6 +28,8 @@ use node::{init_pathtracer_pipelines, pathtracer};
use prepare::prepare_pathtracer_accumulation_texture;
use tracing::warn;
use crate::{SolariPlugins, scene::RaytracingSceneBindings};
/// Non-realtime pathtracing.
///
/// This plugin is meant to generate reference screenshots to compare against,
@@ -81,7 +82,8 @@ pub struct Pathtracer {
pub reset: bool,
}
/// Turn off atmosphere cubemap filtering for pathtracer cameras to save performance, since the pathtracer does not require it.
/// Turn off atmosphere cubemap filtering for pathtracer cameras to save
/// performance, since the pathtracer does not require it.
fn disable_atmosphere_env_map_filtering(
mut commands: Commands,
lights: Query<(Entity, &AtmosphereEnvironmentMapLight), With<Pathtracer>>,
@@ -91,7 +93,8 @@ fn disable_atmosphere_env_map_filtering(
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
// Re-insert so the insert observer rebuilds the env map without
// filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
@@ -1,5 +1,3 @@
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use crate::scene::RaytracingSceneBindings;
use bevy_asset::{AssetServer, load_embedded_asset};
use bevy_ecs::{prelude::*, resource::Resource, system::Commands};
use bevy_render::{
@@ -15,6 +13,9 @@ use bevy_render::{
};
use bevy_utils::default;
use super::{Pathtracer, prepare::PathtracerAccumulationTexture};
use crate::scene::RaytracingSceneBindings;
/// Resource holding the pathtracer pipeline configuration.
#[derive(Resource)]
pub struct PathtracerPipelines {
@@ -1,4 +1,3 @@
use super::Pathtracer;
use bevy_ecs::{
component::Component,
entity::Entity,
@@ -13,6 +12,8 @@ use bevy_render::{
texture::{CachedTexture, TextureCache},
};
use super::Pathtracer;
#[derive(Component)]
pub struct PathtracerAccumulationTexture(pub CachedTexture);
@@ -1,9 +1,10 @@
use super::{SolariLighting, prepare::SolariLightingResources};
use bevy_camera::Camera;
use bevy_ecs::system::{Commands, ResMut};
use bevy_pbr::deferred::SkipDeferredLighting;
use bevy_render::{MainWorld, sync_world::RenderEntity};
use super::{SolariLighting, prepare::SolariLightingResources};
pub fn extract_solari_lighting(mut main_world: ResMut<MainWorld>, mut commands: Commands) {
let mut cameras_3d = main_world.query::<(RenderEntity, &Camera, Option<&mut SolariLighting>)>();
@@ -2,10 +2,6 @@ mod extract;
mod node;
mod prepare;
use crate::{
SolariPlugins,
scene::{RaytracingSceneBindings, prepare_raytracing_scene_resources},
};
use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::embedded_asset;
use bevy_camera::Hdr;
@@ -40,10 +36,15 @@ use prepare::{
};
use tracing::warn;
use crate::{
SolariPlugins,
scene::{RaytracingSceneBindings, prepare_raytracing_scene_resources},
};
/// Raytraced direct and indirect lighting.
///
/// When using this plugin, it's highly recommended to set `shadow_maps_enabled: false` on all lights, as Solari replaces
/// traditional shadow mapping.
/// When using this plugin, it's highly recommended to set `shadow_maps_enabled:
/// false` on all lights, as Solari replaces traditional shadow mapping.
pub struct SolariLightingPlugin;
impl Plugin for SolariLightingPlugin {
@@ -109,22 +110,27 @@ impl Plugin for SolariLightingPlugin {
}
}
/// A component for a 3d camera entity to enable the Solari raytraced lighting system.
/// A component for a 3d camera entity to enable the Solari raytraced lighting
/// system.
///
/// Must be used with `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`, and
/// `Msaa::Off`.
/// Must be used with
/// `CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING)`,
/// and `Msaa::Off`.
#[derive(Component, Reflect, Clone)]
#[reflect(Component, Default, Clone)]
#[require(Hdr, DeferredPrepass, DepthPrepass, MotionVectorPrepass)]
pub struct SolariLighting {
/// [ReSTIR](https://en.wikipedia.org/wiki/Spatiotemporal_reservoir_resampling) is a technique to reuse path samples
/// between pixels and frames. This dramatically reduces noise, at the cost of a few extra rays per pixel.
/// between pixels and frames. This dramatically reduces noise, at the cost
/// of a few extra rays per pixel.
///
/// However, modern denoisers cope well with very noisy input. In many cases, turning this on
/// won't dramatically improve quality after denoising.
/// However, modern denoisers cope well with very noisy input. In many
/// cases, turning this on won't dramatically improve quality after
/// denoising.
///
/// If you want more fine shadow detail, or have scenes with more difficult lighting conditions,
/// turning this on may improve quality and stability, at the cost of a decent chunk of performance.
/// If you want more fine shadow detail, or have scenes with more difficult
/// lighting conditions, turning this on may improve quality and stability,
/// at the cost of a decent chunk of performance.
///
/// Whether to enable this setting or not will be very scene dependent.
///
@@ -143,8 +149,8 @@ pub struct SolariLighting {
/// Number of direct light samples taken for the camera's primary hit during
/// initial sampling.
///
/// Higher values reduce noise in directly-lit areas at the cost of more work
/// per frame. Lower values are faster but noisier.
/// Higher values reduce noise in directly-lit areas at the cost of more
/// work per frame. Lower values are faster but noisier.
pub primary_di_samples: u32,
/// Number of direct light samples taken at each indirect bounce during
@@ -156,9 +162,9 @@ pub struct SolariLighting {
/// Maximum number of bounces traced when generating an initial path.
///
/// Higher values capture more detail in nested reflections and more indirect lighting,
/// at the cost of more rays traced per frame. Lower values are faster but lose
/// multi-bounce lighting for specular paths.
/// Higher values capture more detail in nested reflections and more
/// indirect lighting, at the cost of more rays traced per frame. Lower
/// values are faster but lose multi-bounce lighting for specular paths.
pub max_bounces: u32,
/// How responsive the world cache is to changes in lighting.
@@ -178,18 +184,20 @@ pub struct SolariLighting {
/// Maximum distance to trace GI rays between two world cache cells.
///
/// Higher values capture indirect light from farther away for more accurate
/// GI at the cost of longer (more expensive) ray traversal and increased noise.
/// Lower values are faster and less noisy but may miss distant lighting or leak sky lighting.
/// GI at the cost of longer (more expensive) ray traversal and increased
/// noise. Lower values are faster and less noisy but may miss distant
/// lighting or leak sky lighting.
///
/// Rays that miss within this distance are treated as reaching the environment
/// map light, and leak sky lighting into the cache.
/// Rays that miss within this distance are treated as reaching the
/// environment map light, and leak sky lighting into the cache.
pub world_cache_max_gi_ray_distance: f32,
/// Soft upper limit on the number of world cache cells to update each frame.
/// Soft upper limit on the number of world cache cells to update each
/// frame.
///
/// Higher values let the cache converge faster after lighting changes at the
/// cost of more work per frame. Lower values are cheaper but make the cache
/// slower to update.
/// Higher values let the cache converge faster after lighting changes at
/// the cost of more work per frame. Lower values are cheaper but make the
/// cache slower to update.
///
/// This is a stochastic target that only takes effect when the number of
/// active cells exceeds it: each active cell is then updated with
@@ -208,10 +216,10 @@ pub struct SolariLighting {
/// How fast the world cache transitions between LODs as a function of
/// distance to the camera.
///
/// Higher values keep cells small (high detail) out to greater distances for
/// better quality at the cost of more cells to fill. Lower values transition
/// to larger cells sooner, which is cheaper but coarser farther from the
/// camera.
/// Higher values keep cells small (high detail) out to greater distances
/// for better quality at the cost of more cells to fill. Lower values
/// transition to larger cells sooner, which is cheaper but coarser farther
/// from the camera.
pub world_cache_position_lod_scale: f32,
/// Set to true to delete the saved temporal history (past frames).
@@ -243,7 +251,8 @@ impl Default for SolariLighting {
}
}
/// Adds or removes the prepass double-buffer components according to [`SolariLighting::restir`].
/// Adds or removes the prepass double-buffer components according to
/// [`SolariLighting::restir`].
fn manage_prepass_double_buffers(
views: Query<(
Entity,
@@ -273,7 +282,8 @@ fn manage_prepass_double_buffers(
}
}
/// Turn off atmosphere cubemap filtering for Solari cameras to save performance, since Solari does not require it.
/// Turn off atmosphere cubemap filtering for Solari cameras to save
/// performance, since Solari does not require it.
fn disable_atmosphere_env_map_filtering(
mut commands: Commands,
lights: Query<(Entity, &AtmosphereEnvironmentMapLight), With<SolariLighting>>,
@@ -283,7 +293,8 @@ fn disable_atmosphere_env_map_filtering(
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
// Re-insert so the insert observer rebuilds the env map without
// filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
@@ -1,8 +1,3 @@
use super::prepare::{
LIGHT_TILE_BLOCKS, SolariLightingResources, WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET,
WORLD_CACHE_SIZE,
};
use crate::scene::RaytracingSceneBindings;
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
use bevy_anti_alias::dlss::ViewDlssRayReconstructionTextures;
use bevy_asset::{AssetServer, Handle, load_embedded_asset};
@@ -29,6 +24,12 @@ use bevy_render::{
use bevy_shader::{Shader, ShaderDefVal};
use bevy_utils::default;
use super::prepare::{
LIGHT_TILE_BLOCKS, SolariLightingResources, WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET,
WORLD_CACHE_SIZE,
};
use crate::scene::RaytracingSceneBindings;
/// Resource holding the Solari lighting pipeline configuration.
#[derive(Resource)]
pub struct SolariLightingPipelines {
@@ -200,7 +201,8 @@ pub fn solari_lighting(
return;
};
// Past every bail-out, so this view's reservoirs will be brought up to this frame's light ids
// Past every bail-out, so this view's reservoirs will be brought up to this
// frame's light ids
if restir.is_some() {
scene_bindings.note_light_translations_consumed();
}
@@ -490,14 +492,14 @@ pub fn init_solari_lighting_pipelines(
};
let mut layout = vec![scene_bindings.bind_group_layout.clone(), group_1.clone()];
match extra_bind_group {
ExtraBindGroup::None => {}
ExtraBindGroup::None => {},
ExtraBindGroup::WorldCacheDispatch => {
layout.push(bind_group_layout_world_cache_active_cells_dispatch.clone());
}
},
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
ExtraBindGroup::DlssRrGuideBuffers => {
layout.push(bind_group_layout_resolve_dlss_rr_textures.clone());
}
},
}
let mut shader_defs = vec![ShaderDefVal::UInt(
@@ -511,14 +513,14 @@ pub fn init_solari_lighting_pipelines(
shader_defs.push("RESTIR".into());
}
match extra_bind_group {
ExtraBindGroup::None => {}
ExtraBindGroup::None => {},
ExtraBindGroup::WorldCacheDispatch => {
shader_defs.push("WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into());
}
},
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
ExtraBindGroup::DlssRrGuideBuffers => {
shader_defs.push("DLSS_RR_GUIDE_BUFFERS".into());
}
},
}
shader_defs.extend_from_slice(&extra_shader_defs);
@@ -1,5 +1,3 @@
use super::SolariLighting;
use crate::scene::RaytracingSceneNeedsPreviousFrameData;
#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
use bevy_anti_alias::dlss::{
Dlss, DlssRayReconstructionFeature, ViewDlssRayReconstructionTextures,
@@ -30,6 +28,9 @@ use bevy_render::{
};
use bytemuck::{Pod, Zeroable};
use super::SolariLighting;
use crate::scene::RaytracingSceneNeedsPreviousFrameData;
/// Size of the `LightSample` shader struct in bytes.
const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8;
@@ -44,19 +45,21 @@ pub const LIGHT_TILE_SAMPLES_PER_BLOCK: u64 = 1024;
/// Amount of entries in the world cache (must be a power of 2, and >= 2^10)
pub const WORLD_CACHE_SIZE: u64 = 2u64.pow(20);
/// Sum of per-cell field sizes in `WorldCache`. Keep in sync with `realtime_bindings.wgsl`.
/// Sum of per-cell field sizes in `WorldCache`. Keep in sync with
/// `realtime_bindings.wgsl`.
const WORLD_CACHE_ENTRY_SIZE: u64 = 84;
/// Size of the fixed `b` array (`array<u32, WORLD_CACHE_SIZE / 1024>`).
const WORLD_CACHE_B_SIZE: u64 = (WORLD_CACHE_SIZE / 1024) * size_of::<u32>() as u64;
/// Offset of `active_cells_count`.
pub const WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET: u64 =
WORLD_CACHE_SIZE * WORLD_CACHE_ENTRY_SIZE + WORLD_CACHE_B_SIZE;
/// Must stay under wgpu's default `max_storage_buffer_binding_size` (128 MiB or 2^27 bytes).
/// Must stay under wgpu's default `max_storage_buffer_binding_size` (128 MiB or
/// 2^27 bytes).
pub const WORLD_CACHE_BUFFER_SIZE: u64 =
(WORLD_CACHE_ACTIVE_CELLS_COUNT_OFFSET + size_of::<u32>() as u64).next_multiple_of(16);
/// GPU representation of the user-configurable [`SolariLighting`] settings, plus
/// per-frame state.
/// GPU representation of the user-configurable [`SolariLighting`] settings,
/// plus per-frame state.
///
/// Field order and types must match the `SolariLightingSettings` struct in
/// `realtime_bindings.wgsl`.
@@ -96,7 +99,8 @@ impl SolariLightingUniforms {
}
}
/// Declares to the raytracing scene whether any view needs last frame's TLAS and light ids.
/// Declares to the raytracing scene whether any view needs last frame's TLAS
/// and light ids.
pub fn setup_raytracing_scene_needs_previous_frame_data(
views: Query<&SolariLighting>,
needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
@@ -106,7 +110,7 @@ pub fn setup_raytracing_scene_needs_previous_frame_data(
match (restir_used, needs_previous_frame_data.is_some()) {
(true, false) => commands.insert_resource(RaytracingSceneNeedsPreviousFrameData),
(false, true) => commands.remove_resource::<RaytracingSceneNeedsPreviousFrameData>(),
_ => {}
_ => {},
}
}
@@ -176,7 +180,8 @@ pub fn prepare_solari_lighting_resources(
SolariLightingUniforms::new(solari_lighting, frame_count.0, reusable.is_none());
if let Some(solari_lighting_resources) = reusable {
// The constants uniform can change every frame, so always upload it.
// The constants uniform can change every frame, so always upload
// it.
render_queue.write_buffer(
&solari_lighting_resources.constants,
0,
@@ -193,7 +198,9 @@ pub fn prepare_solari_lighting_resources(
let light_tile_samples = render_device.create_buffer(&BufferDescriptor {
label: Some("solari_lighting_light_tile_samples"),
size: LIGHT_TILE_BLOCKS * LIGHT_TILE_SAMPLES_PER_BLOCK * LIGHT_SAMPLE_STRUCT_SIZE,
size: LIGHT_TILE_BLOCKS
* LIGHT_TILE_SAMPLES_PER_BLOCK
* LIGHT_SAMPLE_STRUCT_SIZE,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
@@ -1,10 +1,12 @@
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`].
/// Released by [`IndexAllocator::retire`], and not reusable until
/// [`IndexAllocator::recycle_retired`].
retired: Vec<u32>,
high_water_mark: u32,
}
@@ -18,10 +20,11 @@ impl IndexAllocator {
}
}
/// 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) {
@@ -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)
}
@@ -103,16 +108,19 @@ 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.
/// 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>>>,
@@ -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;
@@ -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,7 +55,8 @@ 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>,
@@ -60,7 +64,8 @@ pub struct AssetState {
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.
/// 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>>,
@@ -70,7 +75,10 @@ impl AssetState {
pub fn new() -> Self {
Self {
textures: RetainedBindingArray::new(),
materials: AtomicSparseBufferVec::new(BufferUsages::STORAGE, "solari_materials".into()),
materials: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_materials".into(),
),
material_slots: SlotAllocator::new(),
material_textures: HashMap::default(),
emissive_materials: 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;
@@ -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;
@@ -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);
@@ -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]
@@ -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,
@@ -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,8 +155,9 @@ 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 =
@@ -163,19 +177,21 @@ 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
@@ -187,7 +203,8 @@ impl<A: hal::Api> Hal<A> {
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,
@@ -215,8 +232,8 @@ 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),
@@ -224,8 +241,8 @@ impl<A: hal::Api> RawTlasBackend for Hal<A> {
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 {
@@ -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]);
}
@@ -213,12 +213,12 @@ 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 { .. } => {},
}
}
}
@@ -372,7 +372,8 @@ 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
// 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),
});
@@ -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.
@@ -31,9 +33,9 @@ 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 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)
@@ -332,8 +334,8 @@ fn allocate_blas(
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)),
@@ -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,
)]
@@ -256,7 +256,7 @@ pub fn compile_raytracing_blas(
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()
@@ -329,6 +329,13 @@ 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);
+6 -1
View File
@@ -26,7 +26,12 @@ fn compile_replacement_shader(name: &str, entry_point: String, stage: naga::Shad
let shader = shader.to_string();
// Parse the source into a Module.
let module: naga::Module = naga::front::wgsl::parse_str(&shader)
let module: naga::Module =
naga::front::wgsl::Frontend::new_with_options(naga::front::wgsl::Options {
parse_doc_comments: false,
capabilities: naga::valid::Capabilities::all(),
})
.parse(&shader)
.inspect_err(|e| e.emit_to_stderr_with_path(&shader, format!("{SHADERS_IN}/{name}.wesl")))
.expect("Failed to parse WGSL");
// Validate the module.
@@ -589,7 +589,7 @@ impl ElementClass {
ElementClass::Metadata => BufferUsages::STORAGE,
ElementClass::Aabb => {
BufferUsages::union(BufferUsages::STORAGE, BufferUsages::BLAS_INPUT)
}
},
}
}
}
@@ -1,6 +1,6 @@
import package::render::aabb::PackedAabb;
import package::render::metadata_types::TapeMetadata;
import package::render::implicit::{interval_scene, scene};
import package::render::implicit::{interval_scene, scene, gradient_scene};
import package::render::util::{NAN, encode_internal_pos, internal_to_external_pos};
import package::render::spatial_implicit::{SPATIAL_SCENE_OFFSET, INVERSE_SPATIAL_SCENE_SCALE};
@@ -79,10 +79,39 @@ fn main(compute_input: ComputeInput) {
let point = scene(vec4(mid_point, metadata.time));
textureStore(spatial_texture, compute_input.global_invocation_id, vec4(point, 0., 0., 0.));
textureStore(spatial_texture, uinternal_pos, vec4(point, 0., 0., 0.));
}
if (push_constants.flags & FLAG_FILL_TILETREE) > 0 {
// subgroupElect is not implemented in naga
//let index = subgroupExclusiveAdd(1);
//let elect = subgroupBroadcastFirst(index) == index;
var exit = 0;
//if elect {
let base_index = encode_internal_pos(uinternal_pos / vec3u(128, 128, 6), metadata.subdivision_log2);
let aabb = &aabb_buffer.aabbs[push_constants.aabb_buffer_offset + base_index];
if bitcast<u32>(aabb.min_x) == 0xFFC00000u {
exit = 1;
}
//}
//exit = subgroupBroadcastFirst(exit);
if exit == 1 {
return;
}
let position = internal_to_external_pos(internal_pos / vec3(128.0, 128.0, 6.0), metadata);
//let grad = gradient_scene(vec4(position, metadata.time));
const EPSILON = 0.001;
let n = vec3(
scene(vec4(position.x + EPSILON, position.y, position.z, metadata.time)),
scene(vec4(position.x, position.y + EPSILON, position.z, metadata.time)),
scene(vec4(position.x, position.y, position.z + EPSILON, metadata.time)),
);
let grad = normalize(n - (scene(vec4(position, metadata.time))));
textureStore(tiletree, uinternal_pos, vec4(grad * 0.5 + 0.5, 0.0));
}
}
+7 -5
View File
@@ -356,7 +356,8 @@ fn setup_pica_pica(
Transform::from_translation(Vec3::new(0.219417, 2.5764852, 6.9718704)).with_rotation(
Quat::from_xyzw(-0.1466768, 0.013738206, 0.002037309, 0.989087),
),
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are
// required for Solari
CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
Msaa::Off,
));
@@ -426,7 +427,7 @@ fn setup_many_lights(
match plane_mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0).unwrap() {
VertexAttributeValues::Float32x2(items) => {
items.iter_mut().flatten().for_each(|x| *x *= 3.0);
}
},
_ => unreachable!(),
}
let plane_mesh = meshes.add(plane_mesh);
@@ -534,7 +535,8 @@ fn setup_many_lights(
Transform::from_translation(Vec3::new(6.11329, 166.74896, 451.8226)).with_rotation(
Quat::from_xyzw(-0.183938, 0.009093744, 0.0017017953, 0.9828943),
),
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are required for Solari
// Msaa::Off and CameraMainTextureUsages with STORAGE_BINDING are
// required for Solari
CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
Msaa::Off,
Bloom {
@@ -805,10 +807,10 @@ fn update_control_text(
match robot_light_material.and_then(|m| materials.get(&m.0)) {
Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
text.0.push_str("\n(2): Disable robot emissive light");
}
},
_ => {
text.0.push_str("\n(2): Enable robot emissive light");
}
},
}
}