update to latest solari

This commit is contained in:
2026-10-09 17:37:53 +01:00
parent 051b3a6c77
commit 867e9c146b
28 changed files with 1776 additions and 597 deletions
Generated
+1
View File
@@ -1662,6 +1662,7 @@ dependencies = [
"bevy_image", "bevy_image",
"bevy_light", "bevy_light",
"bevy_log", "bevy_log",
"bevy_material",
"bevy_math", "bevy_math",
"bevy_mesh", "bevy_mesh",
"bevy_pbr", "bevy_pbr",
+1
View File
@@ -186,6 +186,7 @@ bevy_ecs = { path = "../bevy/crates/bevy_ecs" }
bevy_light = { path = "../bevy/crates/bevy_light" } bevy_light = { path = "../bevy/crates/bevy_light" }
bevy_image = { path = "../bevy/crates/bevy_image" } bevy_image = { path = "../bevy/crates/bevy_image" }
bevy_log = { path = "../bevy/crates/bevy_log" } bevy_log = { path = "../bevy/crates/bevy_log" }
bevy_material = { path = "../bevy/crates/bevy_material" }
bevy_math = { path = "../bevy/crates/bevy_math" } bevy_math = { path = "../bevy/crates/bevy_math" }
bevy_mesh = { path = "../bevy/crates/bevy_mesh" } bevy_mesh = { path = "../bevy/crates/bevy_mesh" }
bevy_pbr = { path = "../bevy/crates/bevy_pbr" } bevy_pbr = { path = "../bevy/crates/bevy_pbr" }
+1
View File
@@ -22,6 +22,7 @@ bevy_image = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f57
] } ] }
bevy_light = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" } bevy_light = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
bevy_log = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" } bevy_log = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
bevy_material = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
bevy_math = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" } bevy_math = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
bevy_mesh = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" } bevy_mesh = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010" }
bevy_pbr = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [ bevy_pbr = { git = "https://github.com/bevyengine/bevy.git", rev = "0f38358f573a7dc6ea961076f6151be662142010", features = [
+7 -9
View File
@@ -14,18 +14,18 @@ pub mod scene;
/// The solari prelude. /// The solari prelude.
/// ///
/// This includes the most common types in this crate, re-exported for your /// This includes the most common types in this crate, re-exported for your convenience.
/// convenience.
pub mod prelude { pub mod prelude {
pub use super::SolariPlugins; pub use super::SolariPlugins;
pub use crate::{realtime::SolariLighting, scene::RaytracingMesh3d}; pub use crate::realtime::SolariLighting;
pub use crate::scene::RaytracingMesh3d;
} }
use crate::realtime::SolariLightingPlugin;
use crate::scene::RaytracingScenePlugin;
use bevy_app::{PluginGroup, PluginGroupBuilder}; use bevy_app::{PluginGroup, PluginGroupBuilder};
use bevy_render::settings::WgpuFeatures; use bevy_render::settings::WgpuFeatures;
use crate::{realtime::SolariLightingPlugin, scene::RaytracingScenePlugin};
/// An experimental set of plugins for raytraced lighting. /// An experimental set of plugins for raytraced lighting.
/// ///
/// This plugin group provides: /// This plugin group provides:
@@ -33,11 +33,9 @@ use crate::{realtime::SolariLightingPlugin, scene::RaytracingScenePlugin};
/// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding. /// * [`RaytracingScenePlugin`] - BLAS building, resource and lighting binding.
/// ///
/// There's also: /// There's also:
/// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for /// * [`pathtracer::PathtracingPlugin`] - A non-realtime pathtracer for validation purposes (not added by default).
/// validation purposes (not added by default).
/// ///
/// To get started, add this plugin to your app, and then add `RaytracingMesh3d` /// To get started, add this plugin to your app, and then add `RaytracingMesh3d` and `MeshMaterial3d::<StandardMaterial>` to your entities.
/// and `MeshMaterial3d::<StandardMaterial>` to your entities.
pub struct SolariPlugins; pub struct SolariPlugins;
impl PluginGroup for SolariPlugins { impl PluginGroup for SolariPlugins {
@@ -3,14 +3,22 @@ mod node;
mod prepare; mod prepare;
use crate::{scene::RaytracingSceneBindings, SolariPlugins}; use crate::{scene::RaytracingSceneBindings, SolariPlugins};
use bevy_app::{App, Plugin}; use bevy_app::{App, Plugin, PostUpdate};
use bevy_asset::embedded_asset; use bevy_asset::embedded_asset;
use bevy_camera::Hdr; use bevy_camera::Hdr;
use bevy_core_pipeline::{ use bevy_core_pipeline::{
schedule::{Core3d, Core3dSystems}, schedule::{Core3d, Core3dSystems},
tonemapping::tonemapping, tonemapping::tonemapping,
}; };
use bevy_ecs::{component::Component, reflect::ReflectComponent, schedule::IntoScheduleConfigs}; use bevy_ecs::{
component::Component,
entity::Entity,
query::With,
reflect::ReflectComponent,
schedule::IntoScheduleConfigs,
system::{Commands, Query},
};
use bevy_light::AtmosphereEnvironmentMapLight;
use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{ use bevy_render::{
init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup, init_gpu_resource, renderer::RenderDevice, ExtractSchedule, Render, RenderApp, RenderStartup,
@@ -61,6 +69,8 @@ impl Plugin for PathtracingPlugin {
.after(Core3dSystems::MainPass) .after(Core3dSystems::MainPass)
.before(tonemapping), .before(tonemapping),
); );
app.add_systems(PostUpdate, disable_atmosphere_env_map_filtering);
} }
} }
@@ -70,3 +80,23 @@ impl Plugin for PathtracingPlugin {
pub struct Pathtracer { pub struct Pathtracer {
pub reset: bool, pub reset: bool,
} }
/// 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>>,
) {
for (entity, light) in &lights {
if !light.filtered {
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
filtered: false,
..light.clone()
});
}
}
@@ -59,12 +59,8 @@ struct SolariLightingSettings {
/// Don't adjust the size of this struct without also adjusting `prepare::RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE`. /// Don't adjust the size of this struct without also adjusting `prepare::RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE`.
struct ResolvedLightSamplePacked { struct ResolvedLightSamplePacked {
world_position_x: f32, a: vec4<u32>,
world_position_y: f32, b: vec4<u32>,
world_position_z: f32,
world_normal: u32,
radiance: u32,
inverse_pdf: f32,
} }
/// Don't adjust the size of this struct without also adjusting `prepare::RESERVOIR_STRUCT_SIZE`. /// Don't adjust the size of this struct without also adjusting `prepare::RESERVOIR_STRUCT_SIZE`.
@@ -22,7 +22,7 @@ fn gpixel_resolve(gpixel: vec4<u32>, depth: f32, pixel_id: vec2<u32>, view_size:
let reflectance = props.r; let reflectance = props.r;
let metallic = props.g; let metallic = props.g;
let emissive = rgb9e5_to_vec3_(gpixel.g); let emissive = rgb9e5_to_vec3_(gpixel.g);
let material = ResolvedMaterial(base_color, emissive, reflectance, perceptual_roughness, roughness, metallic); let material = ResolvedMaterial(base_color, emissive, reflectance, perceptual_roughness, roughness, metallic, false);
return ResolvedGPixel(world_position, world_normal, material); return ResolvedGPixel(world_position, world_normal, material);
} }
@@ -6,7 +6,7 @@ import package::scene::brdf::{brdf_pdf, evaluate_and_sample_brdf, evaluate_brdf,
import package::realtime::presample_light_tiles::unpack_resolved_light_sample; import package::realtime::presample_light_tiles::unpack_resolved_light_sample;
import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view}; import package::realtime::bindings::{empty_reservoir, light_tile_resolved_samples, light_tile_samples, Reservoir, constants, view};
import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light}; import package::scene::sampling::{calculate_resolved_light_contribution, isinf, LightSample, NULL_LIGHT_ID, power_heuristic, trace_visibility, sample_environment_map_light};
import package::scene::bindings::{light_sources, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray}; import package::scene::bindings::{light_sources, MIRROR_ROUGHNESS_THRESHOLD, RAY_T_MAX, RAY_T_MIN, resolve_ray_hit_full, ResolvedMaterial, ResolvedRayHitFull, trace_ray};
import package::realtime::world_cache_query::{get_cell_size, query_world_cache, WORLD_CACHE_CELL_LIFETIME}; import package::realtime::world_cache_query::{get_cell_size, query_world_cache, WORLD_CACHE_CELL_LIFETIME};
@if(DLSS_RR_GUIDE_BUFFERS) @if(DLSS_RR_GUIDE_BUFFERS)
@@ -89,12 +89,9 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat
let NdotV = max(dot(path.normal, path.wo), 0.0001); let NdotV = max(dot(path.normal, path.wo), 0.0001);
let F_ab = F_AB(path.material.perceptual_roughness, NdotV); let F_ab = F_AB(path.material.perceptual_roughness, NdotV);
// Stochastic NEE, with probability proportional to how diffuse the vertex is. Mirror-like // Sample lights via NEE
// metals have too narrow a lobe for NEE to help, so mostly skip it there and let
// BRDF-sampled emissive do the work. Pure dielectrics always run NEE.
let p_nee = mix(1.0, path.material.perceptual_roughness, path.material.metallic);
let di_samples = select(constants.secondary_di_samples, constants.primary_di_samples, bounce == 0u); let di_samples = select(constants.secondary_di_samples, constants.primary_di_samples, bounce == 0u);
generate_nee_candidate(&path, F_ab, p_nee, di_samples, workgroup_id, bounce, rng); generate_nee_candidate(&path, F_ab, di_samples, workgroup_id, bounce, rng);
// Sample the BRDF and trace the next ray // Sample the BRDF and trace the next ray
let next_bounce = evaluate_and_sample_brdf(path.wo, path.normal, path.material, F_ab, rng); let next_bounce = evaluate_and_sample_brdf(path.wo, path.normal, path.material, F_ab, rng);
@@ -165,7 +162,7 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat
// Resample emissive hits // Resample emissive hits
if any(ray_hit.material.emissive > vec3(0.0)) && dot(ray_hit.world_normal, -next_bounce.wi) > 0.0 { if any(ray_hit.material.emissive > vec3(0.0)) && dot(ray_hit.world_normal, -next_bounce.wi) > 0.0 {
generate_emissive_candidate(&path, ray_hit, next_bounce.wi, p_brdf, ray.t, p_nee, di_samples, bounce, rng); generate_emissive_candidate(&path, ray_hit, next_bounce.wi, p_brdf, ray.t, di_samples, bounce, rng);
} }
// Try terminating into the world cache // Try terminating into the world cache
@@ -205,21 +202,39 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, mat
return result; return result;
} }
/// Probability of running NEE for lights that BRDF rays can also hit, proportional to how diffuse the
/// vertex is. On smooth metals BRDF samples find those lights well, so mostly skip NEE there to
/// increase performance. Perfect mirrors skip NEE entirely, since NEE can't sample their delta lobe.
/// Pure dielectrics always run NEE.
fn nee_probability(material: ResolvedMaterial) -> f32 {
if material.roughness <= MIRROR_ROUGHNESS_THRESHOLD && material.metallic > 0.9999 { return 0.0; }
return mix(1.0, material.perceptual_roughness, material.metallic);
}
fn generate_nee_candidate( fn generate_nee_candidate(
path: ptr<function, PathState>, path: ptr<function, PathState>,
F_ab: vec2<f32>, F_ab: vec2<f32>,
p_nee: f32,
di_samples: u32, di_samples: u32,
workgroup_id: vec2<u32>, workgroup_id: vec2<u32>,
bounce: u32, bounce: u32,
rng: ptr<function, u32>, rng: ptr<function, u32>,
) { ) {
if rand_f(rng) >= p_nee { return; } let p_nee = nee_probability((*path).material);
if p_nee == 0.0 { return; }
let di = sample_light_ris((*path).ray_origin, (*path).normal, (*path).wo, (*path).material, F_ab, di_samples, workgroup_id, bounce, rng); var di = sample_light_ris((*path).ray_origin, (*path).normal, (*path).wo, (*path).material, F_ab, di_samples, workgroup_id, bounce, rng);
let di_target_function = luminance(di.brdf_radiance); let di_target_function = luminance(di.brdf_radiance);
if di_target_function <= 0.0 { return; } if di_target_function <= 0.0 { return; }
// Only skip lights that can also be sampled by BRDF rays. NEE is the only way to find analytic lights like
// the sun, so skipping them would add a ton of variance.
let p_keep = select(1.0, p_nee, di.brdf_rays_can_hit);
if rand_f(rng) >= p_keep { return; }
// Trace visibility
di.unbiased_contribution_weight *= trace_visibility((*path).ray_origin, di.world_position);
if di.unbiased_contribution_weight <= 0.0 { return; }
// MIS against the BRDF strategy. RIS over N candidates makes the effective NEE pdf at the // MIS against the BRDF strategy. RIS over N candidates makes the effective NEE pdf at the
// winner roughly N * light_pdf(winner), so scale by p_nee for the stochastic gate. // winner roughly N * light_pdf(winner), so scale by p_nee for the stochastic gate.
var nee_mis_weight = 1.0; var nee_mis_weight = 1.0;
@@ -234,7 +249,7 @@ fn generate_nee_candidate(
// Bounce 0: Candidate is the light sample, stored by reference and re-resolved each frame // Bounce 0: Candidate is the light sample, stored by reference and re-resolved each frame
// nee_mis_weight goes into the target function since it gets recomputed per-pixel during reuse // nee_mis_weight goes into the target function since it gets recomputed per-pixel during reuse
let target_function = di_target_function * nee_mis_weight; let target_function = di_target_function * nee_mis_weight;
let resampling_weight = target_function * di.unbiased_contribution_weight / p_nee; let resampling_weight = target_function * di.unbiased_contribution_weight / p_keep;
(*path).weight_sum += resampling_weight; (*path).weight_sum += resampling_weight;
if rand_f(rng) * (*path).weight_sum < resampling_weight { if rand_f(rng) * (*path).weight_sum < resampling_weight {
@@ -242,11 +257,11 @@ fn generate_nee_candidate(
(*path).selected_target_function = target_function; (*path).selected_target_function = target_function;
} }
} @else { } @else {
(*path).radiance += di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee; (*path).radiance += di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_keep;
} }
} else { } else {
// Deeper bounces: Candidate is the reconnection radiance at x2 // Deeper bounces: Candidate is the reconnection radiance at x2
let L_at_reconnection = (*path).throughput_past_first_hit * di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_nee; let L_at_reconnection = (*path).throughput_past_first_hit * di.brdf_radiance * di.unbiased_contribution_weight * nee_mis_weight / p_keep;
@if(RESTIR) { @if(RESTIR) {
resample_reconnection_candidate(path, L_at_reconnection, rng); resample_reconnection_candidate(path, L_at_reconnection, rng);
@@ -259,6 +274,7 @@ fn generate_nee_candidate(
struct DiSample { struct DiSample {
unbiased_contribution_weight: f32, unbiased_contribution_weight: f32,
light_sample: LightSample, light_sample: LightSample,
world_position: vec4<f32>,
wi: vec3<f32>, wi: vec3<f32>,
brdf_radiance: vec3<f32>, brdf_radiance: vec3<f32>,
inverse_solid_angle_pdf: f32, inverse_solid_angle_pdf: f32,
@@ -304,10 +320,9 @@ fn sample_light_ris(ray_origin: vec3<f32>, normal: vec3<f32>, wo: vec3<f32>, mat
var unbiased_contribution_weight = 0.0; var unbiased_contribution_weight = 0.0;
if selected_target_function > 0.0 { if selected_target_function > 0.0 {
unbiased_contribution_weight = weight_sum / selected_target_function; unbiased_contribution_weight = weight_sum / selected_target_function;
unbiased_contribution_weight *= trace_visibility(ray_origin, selected_world_position);
} }
return DiSample(unbiased_contribution_weight, light_tile_samples[selected_tile_sample], selected_wi, selected_brdf_radiance, selected_inverse_solid_angle_pdf, selected_brdf_rays_can_hit); return DiSample(unbiased_contribution_weight, light_tile_samples[selected_tile_sample], selected_world_position, selected_wi, selected_brdf_radiance, selected_inverse_solid_angle_pdf, selected_brdf_rays_can_hit);
} }
fn generate_emissive_candidate( fn generate_emissive_candidate(
@@ -316,7 +331,6 @@ fn generate_emissive_candidate(
wi: vec3<f32>, wi: vec3<f32>,
p_brdf: f32, p_brdf: f32,
ray_t: f32, ray_t: f32,
p_nee: f32,
di_samples: u32, di_samples: u32,
bounce: u32, bounce: u32,
rng: ptr<function, u32>, rng: ptr<function, u32>,
@@ -325,6 +339,7 @@ fn generate_emissive_candidate(
let light_count = arrayLength(&light_sources); let light_count = arrayLength(&light_sources);
let area_pdf = 1.0 / (f32(light_count) * f32(ray_hit.triangle_count) * ray_hit.triangle_area); let area_pdf = 1.0 / (f32(light_count) * f32(ray_hit.triangle_count) * ray_hit.triangle_area);
let p_light = area_pdf * ray_t * ray_t / NdotV_hit; let p_light = area_pdf * ray_t * ray_t / NdotV_hit;
let p_nee = nee_probability((*path).material);
let emissive_mis_weight = power_heuristic(p_brdf, p_light * p_nee * f32(di_samples)); let emissive_mis_weight = power_heuristic(p_brdf, p_light * p_nee * f32(di_samples));
@if(RESTIR) { @if(RESTIR) {
@@ -20,11 +20,12 @@ use bevy_core_pipeline::{
use bevy_ecs::{ use bevy_ecs::{
component::Component, component::Component,
entity::Entity, entity::Entity,
query::Has, query::{Has, With},
reflect::ReflectComponent, reflect::ReflectComponent,
schedule::IntoScheduleConfigs, schedule::IntoScheduleConfigs,
system::{Commands, Query}, system::{Commands, Query},
}; };
use bevy_light::AtmosphereEnvironmentMapLight;
use bevy_pbr::DefaultOpaqueRendererMethod; use bevy_pbr::DefaultOpaqueRendererMethod;
use bevy_reflect::{std_traits::ReflectDefault, Reflect}; use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bevy_render::{ use bevy_render::{
@@ -76,7 +77,13 @@ impl Plugin for SolariLightingPlugin {
return; return;
} }
app.add_systems(PostUpdate, manage_prepass_double_buffers); app.add_systems(
PostUpdate,
(
manage_prepass_double_buffers,
disable_atmosphere_env_map_filtering,
),
);
app.sub_app_mut(RenderApp) app.sub_app_mut(RenderApp)
.add_systems( .add_systems(
@@ -265,3 +272,23 @@ fn manage_prepass_double_buffers(
} }
} }
} }
/// 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>>,
) {
for (entity, light) in &lights {
if !light.filtered {
continue;
}
// Re-insert so the insert observer rebuilds the env map without filtering.
commands
.entity(entity)
.insert(AtmosphereEnvironmentMapLight {
filtered: false,
..light.clone()
});
}
}
@@ -34,7 +34,7 @@ use bytemuck::{Pod, Zeroable};
const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8; const LIGHT_SAMPLE_STRUCT_SIZE: u64 = 8;
/// Size of the `ResolvedLightSamplePacked` shader struct in bytes. /// Size of the `ResolvedLightSamplePacked` shader struct in bytes.
const RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE: u64 = 24; const RESOLVED_LIGHT_SAMPLE_STRUCT_SIZE: u64 = 32;
/// Size of the `Reservoir` shader struct in bytes. /// Size of the `Reservoir` shader struct in bytes.
const RESERVOIR_STRUCT_SIZE: u64 = 48; const RESERVOIR_STRUCT_SIZE: u64 = 48;
@@ -7,6 +7,12 @@ import package::realtime::bindings::{light_tile_samples, light_tile_resolved_sam
enable wgpu_ray_query; enable wgpu_ray_query;
const CONE_COS_MASK = 0x7FFFu;
const CONE_COS_MAX = 32767.0;
const CONE_COS_OUTER_SHIFT = 15u;
const EMISSION_COSINE_EXPONENT_SHIFT = 30u;
const BRDF_RAYS_CAN_HIT_SHIFT = 31u;
@compute @workgroup_size(1024, 1, 1) @compute @workgroup_size(1024, 1, 1)
fn presample_light_tiles(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) sample_index: u32) { fn presample_light_tiles(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builtin(local_invocation_index) sample_index: u32) {
let tile_id = workgroup_id.x; let tile_id = workgroup_id.x;
@@ -20,21 +26,49 @@ fn presample_light_tiles(@builtin(workgroup_id) workgroup_id: vec3<u32>, @builti
} }
fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplePacked { fn pack_resolved_light_sample(sample: ResolvedLightSample) -> ResolvedLightSamplePacked {
let inverse_pdf = sample.inverse_pdf * select(1.0, -1.0, sample.world_position.w == 0.0);
return ResolvedLightSamplePacked( return ResolvedLightSamplePacked(
sample.world_position.x, vec4(
sample.world_position.y, bitcast<vec3<u32>>(sample.world_position.xyz),
sample.world_position.z, pack2x16unorm(octahedral_encode(sample.world_normal)),
pack2x16unorm(octahedral_encode(sample.world_normal)), ),
vec3_to_rgb9e5_(log2(sample.radiance * view.exposure + 1.0)), vec4(
sample.inverse_pdf * select(1.0, -1.0, sample.world_position.w == 0.0), vec3_to_rgb9e5_(log2(sample.radiance * view.exposure + 1.0)),
bitcast<u32>(inverse_pdf),
pack2x16unorm(octahedral_encode(sample.emission_axis)),
pack_emission_cone(sample.cone_cos_inner, sample.cone_cos_outer, sample.emission_cosine_exponent)
| (u32(sample.brdf_rays_can_hit) << BRDF_RAYS_CAN_HIT_SHIFT),
),
); );
} }
fn unpack_resolved_light_sample(packed: ResolvedLightSamplePacked, exposure: f32) -> ResolvedLightSample { fn unpack_resolved_light_sample(packed: ResolvedLightSamplePacked, exposure: f32) -> ResolvedLightSample {
let inverse_pdf = bitcast<f32>(packed.b.y);
let cone = packed.b.w;
return ResolvedLightSample( return ResolvedLightSample(
vec4(packed.world_position_x, packed.world_position_y, packed.world_position_z, select(1.0, 0.0, packed.inverse_pdf < 0.0)), vec4(bitcast<vec3<f32>>(packed.a.xyz), select(1.0, 0.0, inverse_pdf < 0.0)),
octahedral_decode(unpack2x16unorm(packed.world_normal)), octahedral_decode(unpack2x16unorm(packed.a.w)),
(exp2(rgb9e5_to_vec3_(packed.radiance)) - 1.0) / exposure, (exp2(rgb9e5_to_vec3_(packed.b.x)) - 1.0) / exposure,
abs(packed.inverse_pdf), abs(inverse_pdf),
octahedral_decode(unpack2x16unorm(packed.b.z)),
unpack_cone_cos(cone & CONE_COS_MASK),
unpack_cone_cos((cone >> CONE_COS_OUTER_SHIFT) & CONE_COS_MASK),
f32((cone >> EMISSION_COSINE_EXPONENT_SHIFT) & 1u),
(cone >> BRDF_RAYS_CAN_HIT_SHIFT) != 0u,
); );
} }
fn pack_emission_cone(cos_inner: f32, cos_outer: f32, emission_cosine_exponent: f32) -> u32 {
return pack_cone_cos(cos_inner)
| (pack_cone_cos(cos_outer) << CONE_COS_OUTER_SHIFT)
| (u32(emission_cosine_exponent == 1.0) << EMISSION_COSINE_EXPONENT_SHIFT);
}
fn pack_cone_cos(cos_angle: f32) -> u32 {
return u32(round(sqrt(saturate((1.0 - cos_angle) * 0.5)) * CONE_COS_MAX));
}
fn unpack_cone_cos(x: u32) -> f32 {
let sin_half_angle = f32(x) / CONE_COS_MAX;
return 1.0 - 2.0 * sin_half_angle * sin_half_angle;
}
@@ -5,7 +5,7 @@ import bevy_pbr::render::utils::{rand_f, rand_u, sample_disk};
import bevy_render::utils::octahedral_decode; import bevy_render::utils::octahedral_decode;
import package::scene::brdf::{brdf_pdf, evaluate_brdf, F_AB}; import package::scene::brdf::{brdf_pdf, evaluate_brdf, F_AB};
import package::realtime::gbuffer_utils::{gpixel_resolve, permute_pixel, pixel_dissimilar}; import package::realtime::gbuffer_utils::{gpixel_resolve, permute_pixel, pixel_dissimilar};
import package::realtime::initial_path::{generate_initial_path, InitialSamplingResult}; import package::realtime::initial_path::{generate_initial_path, InitialSamplingResult, nee_probability};
import package::realtime::bindings::{depth_buffer, empty_reservoir, gbuffer, load_motion_vector, previous_depth_buffer, previous_gbuffer, previous_view, reservoirs_a, reservoirs_b, Reservoir, constants, view, view_output}; import package::realtime::bindings::{depth_buffer, empty_reservoir, gbuffer, load_motion_vector, previous_depth_buffer, previous_gbuffer, previous_view, reservoirs_a, reservoirs_b, Reservoir, constants, view, view_output};
import package::scene::sampling::{balance_heuristic, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame}; import package::scene::sampling::{balance_heuristic, calculate_resolved_light_contribution, isinf, isnan, LightSample, NULL_LIGHT_ID, power_heuristic, resolve_light_sample, ResolvedLightSample, trace_visibility, trace_visibility_previous_frame};
import package::scene::bindings::{light_sources, LIGHT_NOT_PRESENT_THIS_FRAME, previous_frame_light_id_translations, RAY_T_MAX, RAY_T_MIN, ResolvedMaterial}; import package::scene::bindings::{light_sources, LIGHT_NOT_PRESENT_THIS_FRAME, previous_frame_light_id_translations, RAY_T_MAX, RAY_T_MIN, ResolvedMaterial};
@@ -152,7 +152,7 @@ struct NeighborInfo {
} }
fn empty_material() -> ResolvedMaterial { fn empty_material() -> ResolvedMaterial {
return ResolvedMaterial(vec3(0.0), vec3(0.0), 0.0, 0.0, 0.0, 0.0); return ResolvedMaterial(vec3(0.0), vec3(0.0), 0.0, 0.0, 0.0, 0.0, false);
} }
fn jacobian( fn jacobian(
@@ -325,7 +325,7 @@ fn reservoir_contribution(reservoir: Reservoir, resolved: ResolvedLightSample, w
if light_contribution.brdf_rays_can_hit && light_contribution.inverse_solid_angle_pdf > 0.0 { if light_contribution.brdf_rays_can_hit && light_contribution.inverse_solid_angle_pdf > 0.0 {
let light_count = arrayLength(&light_sources); let light_count = arrayLength(&light_sources);
let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf * f32(light_count); let inverse_solid_angle_pdf = light_contribution.inverse_solid_angle_pdf * f32(light_count);
let p_nee = mix(1.0, material.perceptual_roughness, material.metallic); let p_nee = nee_probability(material);
let p_nee_strategy = f32(constants.primary_di_samples) * (1.0 / inverse_solid_angle_pdf) * p_nee; let p_nee_strategy = f32(constants.primary_di_samples) * (1.0 / inverse_solid_angle_pdf) * p_nee;
let p_brdf_at_nee = brdf_pdf(wo, light_contribution.wi, world_normal, material, F_ab); let p_brdf_at_nee = brdf_pdf(wo, light_contribution.wi, world_normal, material, F_ab);
nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee); nee_mis_weight = power_heuristic(p_nee_strategy, p_brdf_at_nee);
@@ -351,7 +351,7 @@ fn reservoir_contribution(reservoir: Reservoir, resolved: ResolvedLightSample, w
brdf_radiance = vec3(0.0); brdf_radiance = vec3(0.0);
} else { } else {
let p_light = area_pdf * sample_distance * sample_distance / cos_theta_light; let p_light = area_pdf * sample_distance * sample_distance / cos_theta_light;
let p_nee = mix(1.0, material.perceptual_roughness, material.metallic); let p_nee = nee_probability(material);
let p_brdf = brdf_pdf(wo, wi, world_normal, material, F_ab); let p_brdf = brdf_pdf(wo, wi, world_normal, material, F_ab);
brdf_radiance *= power_heuristic(p_brdf, p_light * p_nee * f32(constants.primary_di_samples)); brdf_radiance *= power_heuristic(p_brdf, p_light * p_nee * f32(constants.primary_di_samples));
} }
@@ -4,6 +4,8 @@ use core::{hash::Hash, num::NonZeroU32};
/// A free-list allocator for `u32` array indices meant for GPU allocations. /// A free-list allocator for `u32` array indices meant for GPU allocations.
pub struct IndexAllocator { pub struct IndexAllocator {
free: Vec<u32>, free: Vec<u32>,
/// Released by [`IndexAllocator::retire`], and not reusable until [`IndexAllocator::recycle_retired`].
retired: Vec<u32>,
high_water_mark: u32, high_water_mark: u32,
} }
@@ -11,6 +13,7 @@ impl IndexAllocator {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
free: Vec::new(), free: Vec::new(),
retired: Vec::new(),
high_water_mark: 0, high_water_mark: 0,
} }
} }
@@ -35,6 +38,18 @@ impl IndexAllocator {
self.free.push(index); self.free.push(index);
} }
/// 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) {
self.retired.push(index);
}
/// Makes every index retired since the last call reusable.
pub fn recycle_retired(&mut self) {
self.free.append(&mut self.retired);
}
/// How many more indices can be handed out before running past `capacity`. /// How many more indices can be handed out before running past `capacity`.
fn vacancies(&self, capacity: u32) -> u32 { fn vacancies(&self, capacity: u32) -> u32 {
capacity.saturating_sub(self.high_water_mark) + self.free.len() as u32 capacity.saturating_sub(self.high_water_mark) + self.free.len() as u32
@@ -63,10 +78,6 @@ impl<K: Eq + Hash> SlotAllocator<K> {
self.slots.contains_key(key) self.slots.contains_key(key)
} }
pub fn keys(&self) -> impl Iterator<Item = &K> {
self.slots.keys()
}
pub fn get_or_allocate(&mut self, key: K) -> u32 { pub fn get_or_allocate(&mut self, key: K) -> u32 {
if let Some(&slot) = self.slots.get(&key) { if let Some(&slot) = self.slots.get(&key) {
return slot; return slot;
@@ -219,6 +230,19 @@ mod tests {
assert_eq!(slots.high_water_mark(), 2); assert_eq!(slots.high_water_mark(), 2);
} }
#[test]
fn index_allocator_holds_retired_slots_until_recycled() {
let mut slots = IndexAllocator::new();
assert_eq!(slots.allocate(), 0);
slots.retire(0);
assert_eq!(slots.allocate(), 1);
slots.recycle_retired();
assert_eq!(slots.allocate(), 0);
assert_eq!(slots.high_water_mark(), 2);
}
#[test] #[test]
fn retained_binding_array_only_dirties_on_binding_changes() { fn retained_binding_array_only_dirties_on_binding_changes() {
let mut bindings = RetainedBindingArray::new(); let mut bindings = RetainedBindingArray::new();
@@ -6,7 +6,8 @@ use super::{
use bevy_asset::AssetId; use bevy_asset::AssetId;
use bevy_color::{ColorToComponents, LinearRgba}; use bevy_color::{ColorToComponents, LinearRgba};
use bevy_image::Image; use bevy_image::Image;
use bevy_math::Vec3; use bevy_material::AlphaMode;
use bevy_math::{Mat2, Vec2, Vec3};
use bevy_pbr::StandardMaterial; use bevy_pbr::StandardMaterial;
use bevy_platform::collections::{HashMap, HashSet}; use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::{ use bevy_render::{
@@ -23,6 +24,9 @@ use tracing::{info_span, warn};
pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap(); pub const MAX_TEXTURE_COUNT: NonZeroU32 = NonZeroU32::new(5_000).unwrap();
const TEXTURE_MAP_NONE: u32 = u32::MAX; 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]; type MaterialTextures = [Option<AssetId<Image>>; 4];
@@ -33,13 +37,17 @@ pub struct GpuMaterial {
base_color_texture_id: u32, base_color_texture_id: u32,
emissive_texture_id: u32, emissive_texture_id: u32,
metallic_roughness_texture_id: u32, metallic_roughness_texture_id: u32,
base_color: Vec3, base_color: Vec3,
perceptual_roughness: f32, perceptual_roughness: f32,
emissive: Vec3, emissive: Vec3,
metallic: f32, metallic: f32,
_padding: Vec3,
reflectance: f32, reflectance: f32,
flags: u32,
uv_translation: Vec2,
uv_transform: Mat2,
alpha: f32,
alpha_cutoff: f32,
_padding: Vec2,
} }
impl_atomic_pod!(GpuMaterial, GpuMaterialBlob); impl_atomic_pod!(GpuMaterial, GpuMaterialBlob);
@@ -51,6 +59,7 @@ pub struct AssetState {
pub material_slots: SlotAllocator<AssetId<StandardMaterial>>, pub material_slots: SlotAllocator<AssetId<StandardMaterial>>,
material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>, material_textures: HashMap<AssetId<StandardMaterial>, MaterialTextures>,
pub emissive_materials: HashSet<AssetId<StandardMaterial>>, 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>>, unresolved_materials: HashSet<AssetId<StandardMaterial>>,
/// Bound images whose replacement GPU data has not landed yet. /// Bound images whose replacement GPU data has not landed yet.
@@ -65,6 +74,7 @@ impl AssetState {
material_slots: SlotAllocator::new(), material_slots: SlotAllocator::new(),
material_textures: HashMap::default(), material_textures: HashMap::default(),
emissive_materials: HashSet::default(), emissive_materials: HashSet::default(),
non_opaque_materials: HashSet::default(),
unresolved_materials: HashSet::default(), unresolved_materials: HashSet::default(),
pending_texture_updates: HashSet::default(), pending_texture_updates: HashSet::default(),
} }
@@ -187,10 +197,41 @@ impl AssetState {
self.release_material_textures(material_id); self.release_material_textures(material_id);
self.material_textures.insert(material_id, textures); self.material_textures.insert(material_id, textures);
self.unresolved_materials.remove(&material_id); self.unresolved_materials.remove(&material_id);
let slot = self.material_slots.get_or_allocate(material_id); let slot = self.material_slots.get_or_allocate(material_id);
let base_color = LinearRgba::from(material.base_color);
let emissive = material.emissive.to_vec3(); let emissive = material.emissive.to_vec3();
let is_emissive = emissive != Vec3::ZERO; let is_emissive = emissive != Vec3::ZERO;
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
AlphaMode::AlphaToCoverage => 0.5,
AlphaMode::Opaque
| AlphaMode::Blend
| AlphaMode::Premultiplied
| AlphaMode::Add
| AlphaMode::Multiply => 0.0,
};
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
#[expect(clippy::match_same_arms, reason = "Transparency not yet supported")]
AlphaMode::Blend | AlphaMode::Premultiplied | AlphaMode::Add | AlphaMode::Multiply => {
true
}
};
let mut flags = 0;
if material.double_sided {
flags |= MATERIAL_FLAG_DOUBLE_SIDED;
}
if material.flip_normal_map_y {
flags |= MATERIAL_FLAG_FLIP_NORMAL_MAP_Y;
}
self.materials.grow_and_set( self.materials.grow_and_set(
slot, slot,
GpuMaterial { GpuMaterial {
@@ -198,12 +239,17 @@ impl AssetState {
base_color_texture_id: texture_ids[1], base_color_texture_id: texture_ids[1],
emissive_texture_id: texture_ids[2], emissive_texture_id: texture_ids[2],
metallic_roughness_texture_id: texture_ids[3], metallic_roughness_texture_id: texture_ids[3],
base_color: LinearRgba::from(material.base_color).to_vec3(), base_color: base_color.to_vec3(),
perceptual_roughness: material.perceptual_roughness.clamp(0.0, 1.0), perceptual_roughness: material.perceptual_roughness.clamp(0.0, 1.0),
emissive, emissive,
metallic: material.metallic.clamp(0.0, 1.0), metallic: material.metallic.clamp(0.0, 1.0),
reflectance: material.reflectance, reflectance: material.reflectance,
_padding: Vec3::ZERO, flags,
uv_translation: material.uv_transform.translation,
uv_transform: material.uv_transform.matrix2,
alpha: base_color.alpha,
alpha_cutoff,
_padding: Vec2::ZERO,
}, },
); );
@@ -212,7 +258,12 @@ impl AssetState {
} else { } else {
self.emissive_materials.remove(&material_id) self.emissive_materials.remove(&material_id)
}; };
if !was_resolved || was_emissive != is_emissive { let was_opaque = if is_opaque {
!self.non_opaque_materials.remove(&material_id)
} else {
self.non_opaque_materials.insert(material_id)
};
if !was_resolved || was_emissive != is_emissive || was_opaque != is_opaque {
instances.invalidate_material(material_id); instances.invalidate_material(material_id);
} }
} }
@@ -251,6 +302,7 @@ impl AssetState {
self.release_material_textures(material_id); self.release_material_textures(material_id);
self.material_textures.remove(&material_id); self.material_textures.remove(&material_id);
self.emissive_materials.remove(&material_id); self.emissive_materials.remove(&material_id);
self.non_opaque_materials.remove(&material_id);
instances.invalidate_material(material_id); instances.invalidate_material(material_id);
} }
@@ -25,9 +25,9 @@ use crate::scene::extract::ExtractedEnvironmentMapLight;
pub struct BindGroupCacheState { pub struct BindGroupCacheState {
cached: [Option<BindGroup>; 2], cached: [Option<BindGroup>; 2],
pub invalid: bool, pub invalid: bool,
last_buffer_ids: [Option<BufferId>; 11], last_buffer_ids: Option<[BufferId; 12]>,
last_light_count: u32,
last_dfg_ids: Option<(TextureViewId, SamplerId)>, last_dfg_ids: Option<(TextureViewId, SamplerId)>,
last_light_count: u32,
last_environment_map_light_id: Option<TextureViewId>, last_environment_map_light_id: Option<TextureViewId>,
pub dummy_buffer: Buffer, pub dummy_buffer: Buffer,
} }
@@ -46,9 +46,9 @@ impl BindGroupCacheState {
Self { Self {
cached: [None, None], cached: [None, None],
invalid: true, invalid: true,
last_buffer_ids: [None; 11], last_buffer_ids: None,
last_light_count: 0,
last_dfg_ids: None, last_dfg_ids: None,
last_light_count: 0,
last_environment_map_light_id: None, last_environment_map_light_id: None,
dummy_buffer, dummy_buffer,
} }
@@ -66,28 +66,27 @@ fn buffer_bindings<'a>(
} }
impl RaytracingSceneBindings { impl RaytracingSceneBindings {
/// Each sparse buffer's GPU buffer id, or `None` where it has not been /// The id of each buffer in the bind group.
/// created yet. fn buffer_ids(&self) -> [BufferId; 12] {
fn buffer_ids(&self) -> [Option<BufferId>; 11] {
[ [
self.assets.materials.buffer().map(Buffer::id), self.assets.materials.buffer(),
self.instances.transforms.buffer().map(Buffer::id), self.instances.transforms.buffer(),
self.instances self.instances.previous_frame_transforms.buffer(),
.previous_frame_transforms self.instances.geometry_ids.buffer(),
.buffer() self.instances.tape_ids.buffer(),
.map(Buffer::id), self.instances.material_ids.buffer(),
self.instances.geometry_ids.buffer().map(Buffer::id), self.lights.sources.buffer(),
self.instances.tape_ids.buffer().map(Buffer::id), self.lights.directional_lights.buffer(),
self.instances.material_ids.buffer().map(Buffer::id), self.lights.point_lights.buffer(),
self.instances.blas_refs.buffer().map(Buffer::id), self.lights.rect_lights.buffer(),
self.lights.sources.buffer().map(Buffer::id), self.environment_map_light_buffer.buffer(),
self.lights.directional_lights.buffer().map(Buffer::id), self.lights.previous_frame_id_translations.buffer(),
self.lights
.previous_frame_id_translations
.buffer()
.map(Buffer::id),
self.environment_map_light_buffer.buffer().map(Buffer::id),
] ]
.map(|buffer| {
buffer
.expect("scene buffers should have been written before the bind group is prepared")
.id()
})
} }
fn take_bind_group_invalidation( fn take_bind_group_invalidation(
@@ -109,24 +108,24 @@ impl RaytracingSceneBindings {
invalid |= core::mem::replace(dirty, false); invalid |= core::mem::replace(dirty, false);
} }
let buffer_ids = self.buffer_ids(); let buffer_ids = Some(self.buffer_ids());
if self.bind_groups.last_buffer_ids != buffer_ids { if self.bind_groups.last_buffer_ids != buffer_ids {
self.bind_groups.last_buffer_ids = buffer_ids; self.bind_groups.last_buffer_ids = buffer_ids;
invalid = true; invalid = true;
} }
let light_count = self.lights.index.len() as u32;
if self.bind_groups.last_light_count != light_count {
self.bind_groups.last_light_count = light_count;
invalid = true;
}
let dfg_ids = Some((dfg_view.id(), dfg_sampler.id())); let dfg_ids = Some((dfg_view.id(), dfg_sampler.id()));
if self.bind_groups.last_dfg_ids != dfg_ids { if self.bind_groups.last_dfg_ids != dfg_ids {
self.bind_groups.last_dfg_ids = dfg_ids; self.bind_groups.last_dfg_ids = dfg_ids;
invalid = true; invalid = true;
} }
let light_count = self.lights.index.len() as u32;
if self.bind_groups.last_light_count != light_count {
self.bind_groups.last_light_count = light_count;
invalid = true;
}
let environment_map_light_id = Some(environment_map_light.id()); let environment_map_light_id = Some(environment_map_light.id());
if self.bind_groups.last_environment_map_light_id != environment_map_light_id { if self.bind_groups.last_environment_map_light_id != environment_map_light_id {
self.bind_groups.last_environment_map_light_id = environment_map_light_id; self.bind_groups.last_environment_map_light_id = environment_map_light_id;
@@ -152,7 +151,11 @@ impl RaytracingSceneBindings {
let index_buffers = buffer_bindings(&self.instances.index_buffers, dummy); let index_buffers = buffer_bindings(&self.instances.index_buffers, dummy);
let aabb_buffers = buffer_bindings(&self.instances.aabb_buffers, dummy); let aabb_buffers = buffer_bindings(&self.instances.aabb_buffers, dummy);
let tape_metadata_buffers = buffer_bindings(&self.instances.tape_metadata_buffers, dummy); let tape_metadata_buffers = buffer_bindings(&self.instances.tape_metadata_buffers, dummy);
if aabb_buffers.len() == 0 || tape_metadata_buffers.len() == 0 { if vertex_buffers.len() == 0
|| index_buffers.len() == 0
|| aabb_buffers.len() == 0
|| tape_metadata_buffers.len() == 0
{
return None; return None;
} }
@@ -181,89 +184,47 @@ impl RaytracingSceneBindings {
), ),
}; };
let materials = self
.assets
.materials
.buffer()
.unwrap()
.as_entire_buffer_binding();
let transforms = self
.instances
.transforms
.buffer()
.unwrap()
.as_entire_buffer_binding();
let previous_frame_transforms = self
.instances
.previous_frame_transforms
.buffer()
.unwrap()
.as_entire_buffer_binding();
let geometry_ids = self
.instances
.geometry_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let tape_ids = self
.instances
.tape_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let material_ids = self
.instances
.material_ids
.buffer()
.unwrap()
.as_entire_buffer_binding();
let directional_lights = self
.lights
.directional_lights
.buffer()
.unwrap()
.as_entire_buffer_binding();
let translations = self
.lights
.previous_frame_id_translations
.buffer()
.unwrap()
.as_entire_buffer_binding();
let current = self.tlas.structures[current_index].as_ref().unwrap(); let current = self.tlas.structures[current_index].as_ref().unwrap();
let previous = self.tlas.structures[current_index ^ 1] let previous = self.tlas.structures[current_index ^ 1]
.as_ref() .as_ref()
.filter(|_| self.tlas.built[current_index ^ 1]) .filter(|_| self.tlas.built[current_index ^ 1])
.unwrap_or(current); .unwrap_or(current);
Some(render_device.create_bind_group( Some(
"raytracing_scene_bind_group", render_device.create_bind_group(
layout, "raytracing_scene_bind_group",
&BindGroupEntries::sequential(( layout,
vertex_buffers.as_slice(), &BindGroupEntries::sequential((
index_buffers.as_slice(), vertex_buffers.as_slice(),
aabb_buffers.as_slice(), index_buffers.as_slice(),
tape_metadata_buffers.as_slice(), aabb_buffers.as_slice(),
textures.as_slice(), tape_metadata_buffers.as_slice(),
samplers.as_slice(), textures.as_slice(),
materials, samplers.as_slice(),
current.as_binding(), self.assets.materials.binding().unwrap(),
previous.as_binding(), current.as_binding(),
transforms, previous.as_binding(),
previous_frame_transforms, self.instances.transforms.binding().unwrap(),
geometry_ids, self.instances.previous_frame_transforms.binding().unwrap(),
tape_ids, self.instances.geometry_ids.binding().unwrap(),
material_ids, self.instances.tape_ids.binding().unwrap(),
light_sources, self.instances.material_ids.binding().unwrap(),
directional_lights, dfg_view,
translations, dfg_sampler,
dfg_view, light_sources,
dfg_sampler, self.lights.directional_lights.binding().unwrap(),
environment_map_light, self.lights.point_lights.binding().unwrap(),
&self.environment_map_light_sampler, self.lights.rect_lights.binding().unwrap(),
&self.environment_map_light_buffer, environment_map_light,
)), &self.environment_map_light_sampler,
)) &self.environment_map_light_buffer,
self.lights
.previous_frame_id_translations
.binding()
.unwrap(),
)),
),
)
} }
fn cache_bind_group( fn cache_bind_group(
@@ -463,6 +424,12 @@ fn prepare_sparse_uploads(
lights lights
.directional_lights .directional_lights
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines); .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
lights
.point_lights
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
lights
.rect_lights
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
lights lights
.previous_frame_id_translations .previous_frame_id_translations
.prepare_to_populate_buffers(device, cache, jobs, groups, pipelines); .prepare_to_populate_buffers(device, cache, jobs, groups, pipelines);
@@ -22,7 +22,8 @@ use bytemuck::{Pod, Zeroable};
use tracing::{info_span, warn}; use tracing::{info_span, warn};
use super::{ use super::{
MeshBlasManager, RaytracingMesh3d, RaytracingSceneBindings, Tape3d, TapeBlasManager, MeshBlasKey, MeshBlasManager, MeshBlasOpacity, RaytracingMesh3d, RaytracingSceneBindings,
Tape3d, TapeBlasKey, TapeBlasManager, TapeBlasOpacity,
allocator::{IndexAllocator, RetainedBindingArray}, allocator::{IndexAllocator, RetainedBindingArray},
assets::AssetState, assets::AssetState,
lights::{GpuLightSource, LightSourceId, LightState}, lights::{GpuLightSource, LightSourceId, LightState},
@@ -90,15 +91,149 @@ pub enum Object {
Tape(AssetId<Tape>), Tape(AssetId<Tape>),
} }
/// Everything tracked per raytracing mesh instance. #[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlasKey {
Mesh(MeshBlasKey),
Tape(TapeBlasKey),
}
/// Everything tracked per raytracing instance.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
struct Instance { struct MeshInstance {
slot: u32, slot: u32,
object: Object, mesh: AssetId<Mesh>,
material: AssetId<StandardMaterial>, material: AssetId<StandardMaterial>,
opacity: MeshBlasOpacity,
buffers: Option<(BufferId, BufferId)>, buffers: Option<(BufferId, BufferId)>,
} }
/// Everything tracked per raytracing instance.
#[derive(Clone, Copy)]
struct TapeInstance {
slot: u32,
tape: AssetId<Tape>,
material: AssetId<StandardMaterial>,
opacity: TapeBlasOpacity,
buffers: Option<(BufferId, BufferId)>,
}
impl MeshInstance {
fn blas_key(&self) -> MeshBlasKey {
MeshBlasKey {
mesh: self.mesh,
opacity: self.opacity,
}
}
}
impl TapeInstance {
fn blas_key(&self) -> TapeBlasKey {
TapeBlasKey {
tape: self.tape,
opacity: self.opacity,
}
}
}
#[derive(Clone, Copy)]
enum Instance {
Mesh(MeshInstance),
Tape(TapeInstance),
}
impl Instance {
fn get_key(&self) -> BlasKey {
match self {
Instance::Mesh(mesh_instance) => BlasKey::Mesh(mesh_instance.blas_key()),
Instance::Tape(tape_instance) => BlasKey::Tape(tape_instance.blas_key()),
}
}
fn get_slot(&self) -> u32 {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.slot,
Instance::Tape(tape_instance) => tape_instance.slot,
}
}
fn get_material(&self) -> AssetId<StandardMaterial> {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.material,
Instance::Tape(tape_instance) => tape_instance.material,
}
}
fn get_buffers(&self) -> Option<(BufferId, BufferId)> {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.buffers,
Instance::Tape(tape_instance) => tape_instance.buffers,
}
}
fn get_object(&self) -> Object {
match self {
Instance::Mesh(mesh_instance) => Object::Mesh(mesh_instance.mesh),
Instance::Tape(tape_instance) => Object::Tape(tape_instance.tape),
}
}
fn new(
slot: u32,
object: Object,
material: AssetId<StandardMaterial>,
buffers: Option<(BufferId, BufferId)>,
) -> Self {
match object {
Object::Mesh(mesh) => Instance::Mesh(MeshInstance {
slot,
mesh,
material,
opacity: MeshBlasOpacity::Opaque,
buffers,
}),
Object::Tape(tape) => Instance::Tape(TapeInstance {
slot,
tape,
material,
opacity: TapeBlasOpacity::Opaque,
buffers,
}),
}
}
fn take_buffers(&mut self) -> Option<(BufferId, BufferId)> {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.buffers.take(),
Instance::Tape(tape_instance) => tape_instance.buffers.take(),
}
}
fn set_slot(&mut self, slot: u32) {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.slot = slot,
Instance::Tape(tape_instance) => tape_instance.slot = slot,
}
}
fn set_material(&mut self, material: AssetId<StandardMaterial>) {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.material = material,
Instance::Tape(tape_instance) => tape_instance.material = material,
}
}
fn set_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
match self {
Instance::Mesh(mesh_instance) => mesh_instance.buffers = buffers,
Instance::Tape(tape_instance) => tape_instance.buffers = buffers,
}
}
fn get_shared(&self) -> (u32, AssetId<StandardMaterial>, Option<(BufferId, BufferId)>) {
(self.get_slot(), self.get_material(), self.get_buffers())
}
}
/// Stable slots, reverse dependency indices and GPU data owned by raytracing /// Stable slots, reverse dependency indices and GPU data owned by raytracing
/// instances. /// instances.
pub struct InstanceState { pub struct InstanceState {
@@ -113,6 +248,10 @@ pub struct InstanceState {
pub material_ids: AtomicSparseBufferVec<u32>, pub material_ids: AtomicSparseBufferVec<u32>,
pub blas_refs: AtomicSparseBufferVec<GpuBlasRef>, pub blas_refs: AtomicSparseBufferVec<GpuBlasRef>,
pub slots: IndexAllocator, pub slots: IndexAllocator,
/// Slab buffer references dropped this frame, released next frame since the
/// previous frame's TLAS can still reach them through `geometry_ids`.
retired_mesh_buffers: Vec<(BufferId, BufferId)>,
retired_tape_buffers: Vec<(BufferId, BufferId)>,
records: EntityHashMap<Instance>, records: EntityHashMap<Instance>,
pub live_count: u32, pub live_count: u32,
pub pending_refresh: EntityHashSet, pub pending_refresh: EntityHashSet,
@@ -134,6 +273,8 @@ impl InstanceState {
material_ids: storage_buffer("solari_material_ids"), material_ids: storage_buffer("solari_material_ids"),
blas_refs: storage_buffer("solari_blas_refs"), blas_refs: storage_buffer("solari_blas_refs"),
slots: IndexAllocator::new(), slots: IndexAllocator::new(),
retired_mesh_buffers: Vec::new(),
retired_tape_buffers: Vec::new(),
records: EntityHashMap::default(), records: EntityHashMap::default(),
live_count: 0, live_count: 0,
pending_refresh: EntityHashSet::default(), pending_refresh: EntityHashSet::default(),
@@ -148,11 +289,11 @@ impl InstanceState {
/// descriptors that the raw path sets up on the GPU. Slots with a null /// descriptors that the raw path sets up on the GPU. Slots with a null
/// acceleration structure reference are not currently drawable, and are /// acceleration structure reference are not currently drawable, and are
/// left out. /// left out.
pub fn drawable(&self) -> impl Iterator<Item = (u32, Object, [f32; 12])> + '_ { pub fn drawable(&self) -> impl Iterator<Item = (u32, BlasKey, [f32; 12])> + '_ {
self.records.values().filter_map(|instance| { self.records.values().filter_map(|instance| {
let slot = instance.slot; let slot = instance.get_slot();
(self.blas_refs.get(slot) != GpuBlasRef::NONE) (self.blas_refs.get(slot) != GpuBlasRef::NONE)
.then(|| (slot, instance.object, self.transforms.get(slot).rows())) .then(|| (slot, instance.get_key(), self.transforms.get(slot).rows()))
}) })
} }
@@ -231,6 +372,20 @@ fn relink<K: Copy + Eq + Hash>(
} }
impl InstanceState { impl InstanceState {
/// Frees slots and slab buffers dropped last frame, now that the previous
/// frame's TLAS no longer references them.
pub fn begin_frame(&mut self) {
self.slots.recycle_retired();
for (vertex_key, index_key) in core::mem::take(&mut self.retired_mesh_buffers) {
self.vertex_buffers.release(&vertex_key);
self.index_buffers.release(&index_key);
}
for (aabb_key, metadata_key) in core::mem::take(&mut self.retired_tape_buffers) {
self.aabb_buffers.release(&aabb_key);
self.tape_metadata_buffers.release(&metadata_key);
}
}
pub fn remove_instances( pub fn remove_instances(
&mut self, &mut self,
lights: &mut LightState, lights: &mut LightState,
@@ -331,21 +486,15 @@ impl InstanceState {
let material_id = material.id(); let material_id = material.id();
relink(
&mut self.object_instances,
entity,
previous.map(|instance| instance.object),
id,
);
relink( relink(
&mut self.material_instances, &mut self.material_instances,
entity, entity,
previous.map(|instance| instance.material), previous.map(|instance| instance.get_material()),
material_id, material_id,
); );
let slot = match previous { let slot = match previous {
Some(previous) => previous.slot, Some(previous) => previous.get_slot(),
None => self.slots.allocate(), None => self.slots.allocate(),
}; };
self.reserve_slot(slot); self.reserve_slot(slot);
@@ -356,12 +505,12 @@ impl InstanceState {
self.write_transforms(slot, transform, previous_frame_transform); self.write_transforms(slot, transform, previous_frame_transform);
} }
let mut instance = Instance { let mut instance = Instance::new(
slot, slot,
object: id, id,
material: material_id, material_id,
buffers: previous.and_then(|instance| instance.buffers), previous.and_then(|instance| instance.get_buffers()),
}; );
let resolved = self.resolve_instance(inputs, lights, entity, &mut instance); let resolved = self.resolve_instance(inputs, lights, entity, &mut instance);
self.records.insert(entity, instance); self.records.insert(entity, instance);
@@ -377,12 +526,12 @@ impl InstanceState {
entity: Entity, entity: Entity,
instance: &mut Instance, instance: &mut Instance,
) -> bool { ) -> bool {
match instance.object { match instance {
Object::Mesh(asset_id) => { Instance::Mesh(instance) => {
self.resolve_mesh_instance(inputs, lights, entity, asset_id, instance) self.resolve_mesh_instance(inputs, lights, entity, instance)
}, },
Object::Tape(asset_id) => { Instance::Tape(instance) => {
self.resolve_tape_instance(inputs, lights, entity, asset_id, instance) self.resolve_tape_instance(inputs, lights, entity, instance)
}, },
} }
} }
@@ -392,18 +541,44 @@ impl InstanceState {
inputs: &InstanceInputs, inputs: &InstanceInputs,
lights: &mut LightState, lights: &mut LightState,
entity: Entity, entity: Entity,
mesh_id: AssetId<Mesh>, instance: &mut MeshInstance,
instance: &mut Instance,
) -> bool { ) -> bool {
bevy_log::debug!("Resolving mesh instance {mesh_id}"); bevy_log::debug!("Resolving mesh instance {}", instance.mesh);
let slot = instance.slot; let slot = instance.slot;
let material_slot = inputs.assets.material_slots.get(&instance.material);
instance.opacity = if inputs
.assets
.non_opaque_materials
.contains(&instance.material)
{
MeshBlasOpacity::NonOpaque
} else {
MeshBlasOpacity::Opaque
};
let blas_key = instance.blas_key();
let blas_address = inputs.mesh_blas_manager.device_address(&blas_key);
if blas_address.is_none()
&& material_slot.is_some()
&& inputs.mesh_blas_manager.is_undeclared(&blas_key)
{
once!(warn!(
"RaytracingMesh3d entity {entity} uses a material that needs `{flag:?}`, but \
`Mesh::raytracing` of mesh {mesh} lacks it. Entities like it will not be \
raytraced.",
flag = instance.opacity.flag(),
mesh = instance.mesh,
));
}
let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = ( let (Some(vertex_slice), Some(index_slice), Some(material_slot), Some(blas_address)) = (
inputs.mesh_allocator.mesh_vertex_slice(&mesh_id), inputs.mesh_allocator.mesh_vertex_slice(&instance.mesh),
inputs.mesh_allocator.mesh_index_slice(&mesh_id), inputs.mesh_allocator.mesh_index_slice(&instance.mesh),
inputs.assets.material_slots.get(&instance.material), material_slot,
inputs.mesh_blas_manager.device_address(&mesh_id), blas_address,
) else { ) else {
self.deactivate_instance(lights, entity, instance); self.deactivate_mesh_instance(lights, entity, instance);
return false; return false;
}; };
@@ -418,7 +593,7 @@ impl InstanceState {
be rendered.", be rendered.",
MAX_MESH_SLAB_COUNT.get() MAX_MESH_SLAB_COUNT.get()
)); ));
self.deactivate_instance(lights, entity, instance); self.deactivate_mesh_instance(lights, entity, instance);
return false; return false;
} }
@@ -468,26 +643,56 @@ impl InstanceState {
inputs: &InstanceInputs, inputs: &InstanceInputs,
lights: &mut LightState, lights: &mut LightState,
entity: Entity, entity: Entity,
tape_id: AssetId<Tape>, instance: &mut TapeInstance,
instance: &mut Instance,
) -> bool { ) -> bool {
bevy_log::info!("Resolving tape instance {tape_id}"); bevy_log::debug!("Resolving tape instance {}", instance.tape);
let slot = instance.slot; let slot = instance.slot;
let material_slot = inputs.assets.material_slots.get(&instance.material);
instance.opacity = if inputs
.assets
.non_opaque_materials
.contains(&instance.material)
{
TapeBlasOpacity::NonOpaque
} else {
TapeBlasOpacity::Opaque
};
let blas_key = instance.blas_key();
let blas_address = inputs.tape_blas_manager.device_address(&blas_key);
if blas_address.is_none()
&& material_slot.is_some()
&& inputs.tape_blas_manager.is_undeclared(&blas_key)
{
once!(warn!(
"Tape3d entity {entity} uses a material that needs `{flag:?}`, but \
`Tape::raytracing` of tape {tape} lacks it. Entities like it will not be \
raytraced.",
flag = instance.opacity.flag(),
tape = instance.tape,
));
}
let (Some(aabb_slice), Some(metadata_slice), Some(material_slot), Some(blas_address)) = ( let (Some(aabb_slice), Some(metadata_slice), Some(material_slot), Some(blas_address)) = (
inputs.tape_allocator.tape_aabb_slice(&tape_id), inputs.tape_allocator.tape_aabb_slice(&instance.tape),
inputs.tape_allocator.tape_metadata_slice(&tape_id), inputs.tape_allocator.tape_metadata_slice(&instance.tape),
inputs.assets.material_slots.get(&instance.material), material_slot,
inputs.tape_blas_manager.device_address(&tape_id), blas_address,
) else { ) else {
bevy_log::info!("Deactivating tape instance {tape_id}"); bevy_log::info!("Deactivating tape instance {}", instance.tape);
self.deactivate_instance(lights, entity, instance); self.deactivate_tape_instance(lights, entity, instance);
return false; return false;
}; };
bevy_log::info!("Tape {tape_id} aabb_slice: {:?}", aabb_slice.range); bevy_log::info!("Tape {} aabb_slice: {:?}", instance.tape, aabb_slice.range);
bevy_log::info!("Tape {tape_id} metadata_slice: {:?}", metadata_slice.range); bevy_log::info!(
bevy_log::info!("Tape {tape_id} material_slot: {material_slot}"); "Tape {} metadata_slice: {:?}",
bevy_log::info!("Tape {tape_id} blas_address: {blas_address}"); instance.tape,
metadata_slice.range
);
bevy_log::info!("Tape {} material_slot: {material_slot}", instance.tape);
bevy_log::info!("Tape {} blas_address: {blas_address}", instance.tape);
let aabb_buffer_key = aabb_slice.buffer.id(); let aabb_buffer_key = aabb_slice.buffer.id();
let metadata_buffer_key = metadata_slice.buffer.id(); let metadata_buffer_key = metadata_slice.buffer.id();
@@ -502,7 +707,7 @@ impl InstanceState {
be rendered.", be rendered.",
MAX_TAPE_SLAB_COUNT.get() MAX_TAPE_SLAB_COUNT.get()
)); ));
self.deactivate_instance(lights, entity, instance); self.deactivate_tape_instance(lights, entity, instance);
return false; return false;
} }
@@ -549,7 +754,7 @@ impl InstanceState {
} }
*/ */
bevy_log::info!("Tape {tape_id} resolved"); bevy_log::info!("Tape {} resolved", instance.tape);
true true
} }
@@ -587,44 +792,66 @@ impl InstanceState {
} }
} }
fn deactivate_instance( fn deactivate_instance_common(
&mut self, &mut self,
lights: &mut LightState, lights: &mut LightState,
entity: Entity, entity: Entity,
instance: &mut Instance, instance: &Instance,
) { ) {
self.set_blas_ref(instance.slot, GpuBlasRef::NONE); self.set_blas_ref(instance.get_slot(), GpuBlasRef::NONE);
lights.remove_light(LightSourceId::EmissiveMesh(entity)); lights.remove_light(LightSourceId::EmissiveMesh(entity));
match instance.object { }
Object::Mesh(_) => self.release_mesh_buffers(instance.buffers.take()),
Object::Tape(_) => self.release_tape_buffers(instance.buffers.take()), fn deactivate_mesh_instance(
} &mut self,
lights: &mut LightState,
entity: Entity,
instance: &mut MeshInstance,
) {
self.deactivate_instance_common(lights, entity, &Instance::Mesh(*instance));
self.release_mesh_buffers(instance.buffers.take());
}
fn deactivate_tape_instance(
&mut self,
lights: &mut LightState,
entity: Entity,
instance: &mut TapeInstance,
) {
self.deactivate_instance_common(lights, entity, &Instance::Tape(*instance));
self.release_tape_buffers(instance.buffers.take());
} }
fn release_mesh_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) { fn release_mesh_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
if let Some((vertex_key, index_key)) = buffers { self.retired_mesh_buffers.extend(buffers);
self.vertex_buffers.release(&vertex_key);
self.index_buffers.release(&index_key);
}
} }
fn release_tape_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) { fn release_tape_buffers(&mut self, buffers: Option<(BufferId, BufferId)>) {
if let Some((aabb_key, metadata_key)) = buffers { self.retired_tape_buffers.extend(buffers);
self.aabb_buffers.release(&aabb_key);
self.tape_metadata_buffers.release(&metadata_key);
}
} }
fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) { fn remove_instance(&mut self, lights: &mut LightState, entity: Entity) {
let Some(mut instance) = self.records.remove(&entity) else { let Some(instance) = self.records.remove(&entity) else {
return; return;
}; };
self.deactivate_instance(lights, entity, &mut instance); match instance {
self.slots.release(instance.slot); 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());
self.pending_refresh.remove(&entity); self.pending_refresh.remove(&entity);
unlink(&mut self.object_instances, &instance.object, entity); unlink(&mut self.object_instances, &instance.get_object(), entity);
unlink(&mut self.material_instances, &instance.material, entity); unlink(
&mut self.material_instances,
&instance.get_material(),
entity,
);
} }
} }
@@ -638,8 +865,11 @@ impl RaytracingSceneBindings {
previous_frame_transform: &PreviousGlobalTransform, previous_frame_transform: &PreviousGlobalTransform,
) { ) {
if let Some(instance) = self.instances.records.get(&entity) { if let Some(instance) = self.instances.records.get(&entity) {
self.instances self.instances.write_transforms(
.write_transforms(instance.slot, transform, previous_frame_transform); instance.get_slot(),
transform,
previous_frame_transform,
);
} }
} }
} }
@@ -1,21 +1,26 @@
use super::allocator::SlotAllocator; use super::allocator::SlotAllocator;
use bevy_color::ColorToComponents; use crate::scene::extract::{
use bevy_ecs::{ ExtractedRaytracingDirectionalLight, ExtractedRaytracingPointLight,
entity::{Entity, EntityHashSet}, ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
system::Query,
}; };
use bevy_ecs::{entity::Entity, query::Changed, system::Query};
use bevy_math::{ops::cos, Vec3}; use bevy_math::{ops::cos, Vec3};
use bevy_pbr::ExtractedDirectionalLight;
use bevy_platform::collections::{HashMap, HashSet}; use bevy_platform::collections::{HashMap, HashSet};
use bevy_render::render_resource::{AtomicSparseBufferVec, BufferUsages}; use bevy_render::render_resource::{AtomicSparseBufferVec, BufferUsages};
use bevy_render::{impl_atomic_pod, render_resource::AtomicPod}; use bevy_render::{impl_atomic_pod, render_resource::AtomicPod};
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use core::sync::atomic::{AtomicBool, Ordering}; use core::sync::atomic::{AtomicBool, Ordering};
use core::{f32::consts::TAU, hash::Hash}; use core::{f32::consts::TAU, hash::Hash};
use tracing::info_span;
const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX; const LIGHT_NOT_PRESENT_THIS_FRAME: u32 = u32::MAX;
const LIGHT_SOURCE_KIND_BITS: u32 = 3;
const LIGHT_SOURCE_KIND_EMISSIVE_MESH: u32 = 0;
const LIGHT_SOURCE_KIND_DIRECTIONAL: u32 = 1;
const LIGHT_SOURCE_KIND_POINT: u32 = 2;
const LIGHT_SOURCE_KIND_RECT: u32 = 3;
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)] #[repr(C)]
pub struct GpuLightSource { pub struct GpuLightSource {
@@ -23,14 +28,14 @@ pub struct GpuLightSource {
id: u32, id: u32,
} }
/// Stable identity for one source in the light array. /// Stable identity for one light in the light array.
///
/// An entity can contribute both kinds at once, so the entity alone is not enough to identify a
/// source.
#[derive(Clone, Copy, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum LightSourceId { pub enum LightSourceId {
EmissiveMesh(Entity), EmissiveMesh(Entity),
Directional(Entity), DirectionalLight(Entity),
PointLight(Entity),
SpotLight(Entity),
RectLight(Entity),
} }
#[derive(Default)] #[derive(Default)]
@@ -93,17 +98,31 @@ impl GpuLightSource {
} }
Self { Self {
kind: triangle_count << 1, 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 { fn new_directional_light(directional_light_id: u32) -> GpuLightSource {
Self { Self {
kind: 1, 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,
}
}
fn new_rect_light(rect_light_id: u32) -> GpuLightSource {
Self {
kind: LIGHT_SOURCE_KIND_RECT,
id: rect_light_id,
}
}
} }
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)] #[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
@@ -115,21 +134,91 @@ pub struct GpuDirectionalLight {
inverse_pdf: f32, inverse_pdf: f32,
} }
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuPointLight {
position: Vec3,
radius: f32,
intensity: Vec3,
cos_inner: f32,
axis: Vec3,
cos_outer: f32,
}
#[derive(Clone, Copy, Default, PartialEq, Pod, Zeroable)]
#[repr(C)]
pub struct GpuRectLight {
center: Vec3,
area: f32,
edge_x: Vec3,
_padding0: f32,
edge_y: Vec3,
_padding1: f32,
radiance: Vec3,
_padding2: f32,
}
impl_atomic_pod!(GpuLightSource, GpuLightSourceBlob); impl_atomic_pod!(GpuLightSource, GpuLightSourceBlob);
impl_atomic_pod!(GpuDirectionalLight, GpuDirectionalLightBlob); impl_atomic_pod!(GpuDirectionalLight, GpuDirectionalLightBlob);
impl_atomic_pod!(GpuPointLight, GpuPointLightBlob);
impl_atomic_pod!(GpuRectLight, GpuRectLightBlob);
impl GpuDirectionalLight { impl GpuDirectionalLight {
fn new(directional_light: &ExtractedDirectionalLight) -> Self { fn new(directional_light: &ExtractedRaytracingDirectionalLight) -> Self {
let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0); let cos_theta_max = cos(directional_light.sun_disk_angular_size / 2.0);
let solid_angle = TAU * (1.0 - cos_theta_max); let solid_angle = TAU * (1.0 - cos_theta_max);
let luminance =
(directional_light.color.to_vec3() * directional_light.illuminance) / solid_angle; let (luminance, inverse_pdf) = if solid_angle > 0.0 {
(directional_light.illuminance / solid_angle, solid_angle)
} else {
(directional_light.illuminance, 1.0)
};
Self { Self {
direction_to_light: directional_light.transform.back().into(), direction_to_light: directional_light.direction_to_light,
cos_theta_max, cos_theta_max,
luminance, luminance,
inverse_pdf: solid_angle, inverse_pdf,
}
}
}
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,
intensity: point_light.intensity,
cos_inner: -1.0,
axis: Vec3::NEG_Z,
cos_outer: -1.0,
}
}
fn new_spot(spot_light: &ExtractedRaytracingSpotLight) -> Self {
Self {
position: spot_light.position,
radius: spot_light.radius,
intensity: spot_light.intensity,
cos_inner: spot_light.cos_inner,
axis: spot_light.axis,
cos_outer: spot_light.cos_outer,
}
}
}
impl GpuRectLight {
fn new(rect_light: &ExtractedRaytracingRectLight) -> Self {
Self {
center: rect_light.center,
area: rect_light.area,
edge_x: rect_light.edge_x,
_padding0: 0.0,
edge_y: rect_light.edge_y,
_padding1: 0.0,
radiance: rect_light.radiance,
_padding2: 0.0,
} }
} }
} }
@@ -139,12 +228,17 @@ pub struct LightState {
/// Kept gap-free because shaders derive the light count with `arrayLength`. /// Kept gap-free because shaders derive the light count with `arrayLength`.
pub sources: AtomicSparseBufferVec<GpuLightSource>, pub sources: AtomicSparseBufferVec<GpuLightSource>,
pub directional_lights: AtomicSparseBufferVec<GpuDirectionalLight>, pub directional_lights: AtomicSparseBufferVec<GpuDirectionalLight>,
pub point_lights: AtomicSparseBufferVec<GpuPointLight>,
pub rect_lights: AtomicSparseBufferVec<GpuRectLight>,
pub previous_frame_id_translations: AtomicSparseBufferVec<u32>, pub previous_frame_id_translations: AtomicSparseBufferVec<u32>,
pub index: LightIndex, 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>, previous_index: HashMap<LightSourceId, u32>,
nonidentity_translations: Vec<u32>, nonidentity_translations: Vec<u32>,
directional_slots: SlotAllocator<Entity>, directional_light_slots: SlotAllocator<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, translations_consumed: AtomicBool,
} }
@@ -160,6 +254,14 @@ impl LightState {
BufferUsages::STORAGE, BufferUsages::STORAGE,
"solari_directional_lights".into(), "solari_directional_lights".into(),
), ),
point_lights: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_point_lights".into(),
),
rect_lights: AtomicSparseBufferVec::new(
BufferUsages::STORAGE,
"solari_rect_lights".into(),
),
previous_frame_id_translations: AtomicSparseBufferVec::new( previous_frame_id_translations: AtomicSparseBufferVec::new(
BufferUsages::STORAGE, BufferUsages::STORAGE,
"solari_previous_frame_light_id_translations".into(), "solari_previous_frame_light_id_translations".into(),
@@ -167,39 +269,105 @@ impl LightState {
index: LightIndex::default(), index: LightIndex::default(),
previous_index: HashMap::default(), previous_index: HashMap::default(),
nonidentity_translations: Vec::new(), nonidentity_translations: Vec::new(),
directional_slots: SlotAllocator::new(), directional_light_slots: SlotAllocator::new(),
point_light_slots: SlotAllocator::new(),
rect_light_slots: SlotAllocator::new(),
translations_consumed: AtomicBool::new(false), translations_consumed: AtomicBool::new(false),
} }
} }
pub fn update(&mut self, directional_lights: &Query<(Entity, &ExtractedDirectionalLight)>) { /// Applies this frame's light changes.
// There are few enough directional lights to just walk them every frame ///
let _span = info_span!("update_lights").entered(); /// 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.
let mut live_directional_lights = EntityHashSet::default(); pub fn update_directional_lights(
for (entity, directional_light) in directional_lights { &mut self,
live_directional_lights.insert(entity); changed: &Query<
(Entity, &ExtractedRaytracingDirectionalLight),
let slot = self.directional_slots.get_or_allocate(entity); Changed<ExtractedRaytracingDirectionalLight>,
>,
removed: impl IntoIterator<Item = Entity>,
) {
// 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));
}
}
for (entity, directional_light) in changed {
let slot = self.directional_light_slots.get_or_allocate(entity);
self.directional_lights self.directional_lights
.grow_and_set(slot, GpuDirectionalLight::new(directional_light)); .grow_and_set(slot, GpuDirectionalLight::new(directional_light));
self.add_light( self.add_light(
LightSourceId::Directional(entity), LightSourceId::DirectionalLight(entity),
GpuLightSource::new_directional_light(slot), GpuLightSource::new_directional_light(slot),
); );
} }
}
let stale: Vec<Entity> = self pub fn update_point_lights(
.directional_slots &mut self,
.keys() changed: &Query<
.copied() (Entity, &ExtractedRaytracingPointLight),
.filter(|entity| !live_directional_lights.contains(entity)) Changed<ExtractedRaytracingPointLight>,
.collect(); >,
for entity in stale { removed: impl IntoIterator<Item = Entity>,
self.directional_slots.remove(&entity); ) {
self.remove_light(LightSourceId::Directional(entity)); for entity in removed {
self.remove_point_or_spot_light(LightSourceId::PointLight(entity));
} }
for (entity, point_light) in changed {
self.set_point_or_spot_light(
LightSourceId::PointLight(entity),
GpuPointLight::new_point(point_light),
);
}
}
pub fn update_spot_lights(
&mut self,
changed: &Query<
(Entity, &ExtractedRaytracingSpotLight),
Changed<ExtractedRaytracingSpotLight>,
>,
removed: impl IntoIterator<Item = Entity>,
) {
for entity in removed {
self.remove_point_or_spot_light(LightSourceId::SpotLight(entity));
}
for (entity, spot_light) in changed {
self.set_point_or_spot_light(
LightSourceId::SpotLight(entity),
GpuPointLight::new_spot(spot_light),
);
}
}
pub fn update_rect_lights(
&mut self,
changed: &Query<
(Entity, &ExtractedRaytracingRectLight),
Changed<ExtractedRaytracingRectLight>,
>,
removed: impl IntoIterator<Item = Entity>,
) {
for entity in removed {
if self.rect_light_slots.remove(&entity).is_some() {
self.remove_light(LightSourceId::RectLight(entity));
}
}
for (entity, rect_light) in changed {
let slot = self.rect_light_slots.get_or_allocate(entity);
self.rect_lights
.grow_and_set(slot, GpuRectLight::new(rect_light));
self.add_light(
LightSourceId::RectLight(entity),
GpuLightSource::new_rect_light(slot),
);
}
}
pub fn finish_update(&mut self) {
self.write_light_id_translations(); self.write_light_id_translations();
if self.index.len() > u16::MAX as usize { if self.index.len() > u16::MAX as usize {
@@ -207,6 +375,18 @@ impl LightState {
} }
} }
fn set_point_or_spot_light(&mut self, id: LightSourceId, light: GpuPointLight) {
let slot = self.point_light_slots.get_or_allocate(id);
self.point_lights.grow_and_set(slot, light);
self.add_light(id, GpuLightSource::new_point_light(slot));
}
fn remove_point_or_spot_light(&mut self, id: LightSourceId) {
if self.point_light_slots.remove(&id).is_some() {
self.remove_light(id);
}
}
pub fn add_light(&mut self, id: LightSourceId, source: GpuLightSource) { pub fn add_light(&mut self, id: LightSourceId, source: GpuLightSource) {
let index = self.index.insert(id); let index = self.index.insert(id);
self.sources.grow_and_set(index, source); self.sources.grow_and_set(index, source);
@@ -287,23 +467,78 @@ mod tests {
use super::{LightIndex, LightSourceId}; use super::{LightIndex, LightSourceId};
use bevy_ecs::entity::Entity; use bevy_ecs::entity::Entity;
const ENTITY: Entity = Entity::PLACEHOLDER;
#[test] #[test]
fn light_index_keeps_sources_on_the_same_entity_independent() { fn light_index_keeps_sources_on_the_same_entity_independent() {
let entity = Entity::PLACEHOLDER;
let emissive = LightSourceId::EmissiveMesh(entity);
let directional = LightSourceId::Directional(entity);
let mut lights = LightIndex::default(); let mut lights = LightIndex::default();
assert_eq!(lights.insert(emissive), 0); assert_eq!(lights.insert(LightSourceId::EmissiveMesh(ENTITY)), 0);
assert_eq!(lights.insert(directional), 1); assert_eq!(lights.insert(LightSourceId::DirectionalLight(ENTITY)), 1);
assert_eq!(lights.insert(emissive), 0); assert_eq!(lights.insert(LightSourceId::PointLight(ENTITY)), 2);
assert_eq!(lights.len(), 2); assert_eq!(lights.insert(LightSourceId::SpotLight(ENTITY)), 3);
assert_eq!(lights.insert(LightSourceId::RectLight(ENTITY)), 4);
assert_eq!(lights.len(), 5);
}
assert_eq!(lights.remove(emissive), Some((0, 1))); #[test]
fn light_index_insert_is_idempotent() {
let point = LightSourceId::PointLight(ENTITY);
let mut lights = LightIndex::default();
assert_eq!(lights.insert(point), 0);
assert_eq!(lights.insert(point), 0);
assert_eq!(lights.len(), 1);
}
#[test]
fn light_index_remove_moves_the_last_source_into_the_hole() {
let emissive = LightSourceId::EmissiveMesh(ENTITY);
let point = LightSourceId::PointLight(ENTITY);
let rect = LightSourceId::RectLight(ENTITY);
let mut lights = LightIndex::default();
lights.insert(emissive);
lights.insert(point);
lights.insert(rect);
assert_eq!(lights.remove(emissive), Some((0, 2)));
assert_eq!(lights.get(&emissive), None); assert_eq!(lights.get(&emissive), None);
assert_eq!(lights.get(&rect), Some(0));
assert_eq!(lights.get(&point), Some(1));
assert_eq!(lights.len(), 2);
}
#[test]
fn light_index_remove_of_the_last_source_moves_nothing() {
let directional = LightSourceId::DirectionalLight(ENTITY);
let rect = LightSourceId::RectLight(ENTITY);
let mut lights = LightIndex::default();
lights.insert(directional);
lights.insert(rect);
assert_eq!(lights.remove(rect), Some((1, 1)));
assert_eq!(lights.get(&directional), Some(0)); assert_eq!(lights.get(&directional), Some(0));
assert_eq!(lights.len(), 1); assert_eq!(lights.len(), 1);
}
#[test]
fn light_index_remove_of_a_missing_source_returns_none() {
let mut lights = LightIndex::default();
lights.insert(LightSourceId::PointLight(ENTITY));
assert_eq!(lights.remove(LightSourceId::RectLight(ENTITY)), None);
assert_eq!(lights.len(), 1);
}
#[test]
fn light_index_remove_of_every_source_leaves_it_empty() {
let emissive = LightSourceId::EmissiveMesh(ENTITY);
let directional = LightSourceId::DirectionalLight(ENTITY);
let mut lights = LightIndex::default();
lights.insert(emissive);
lights.insert(directional);
assert_eq!(lights.remove(emissive), Some((0, 1)));
assert_eq!(lights.remove(directional), Some((0, 0))); assert_eq!(lights.remove(directional), Some((0, 0)));
assert!(lights.is_empty()); assert!(lights.is_empty());
} }
@@ -9,11 +9,11 @@ mod tlas_build;
use bevy_ecs::{ use bevy_ecs::{
entity::Entity, entity::Entity,
lifecycle::RemovedComponents, lifecycle::RemovedComponents,
query::Changed,
resource::Resource, resource::Resource,
system::{Query, Res, ResMut}, system::{Query, Res, ResMut},
world::{FromWorld, World}, world::{FromWorld, World},
}; };
use bevy_pbr::ExtractedDirectionalLight;
use bevy_render::{ use bevy_render::{
mesh::allocator::MeshAllocator, mesh::allocator::MeshAllocator,
render_asset::{ExtractedAssets, RenderAssets}, render_asset::{ExtractedAssets, RenderAssets},
@@ -39,10 +39,22 @@ pub use self::{
tlas::{TlasInstanceSetupPipeline, build_raytracing_tlas}, tlas::{TlasInstanceSetupPipeline, build_raytracing_tlas},
}; };
use super::{ use super::{
RaytracingMesh3d, Tape3d, extract::StandardMaterialAssets, RaytracingMesh3d, Tape3d,
meshes::blas::BlasManager as MeshBlasManager, tapes::blas::BlasManager as TapeBlasManager, extract::StandardMaterialAssets,
meshes::blas::{
BlasKey as MeshBlasKey, BlasManager as MeshBlasManager, BlasOpacity as MeshBlasOpacity,
},
tapes::blas::{
BlasKey as TapeBlasKey, BlasManager as TapeBlasManager, BlasOpacity as TapeBlasOpacity,
},
};
use crate::scene::{
binder::instances::MAX_TAPE_SLAB_COUNT,
extract::{
ExtractedRaytracingDirectionalLight, ExtractedRaytracingPointLight,
ExtractedRaytracingRectLight, ExtractedRaytracingSpotLight,
},
}; };
use crate::scene::binder::instances::MAX_TAPE_SLAB_COUNT;
/// Insert this resource into the render world to make the raytracing scene /// Insert this resource into the render world to make the raytracing scene
/// retain the previous frame's TLAS and the light id translation table that /// retain the previous frame's TLAS and the light id translation table that
@@ -61,10 +73,10 @@ pub struct RaytracingSceneBindings {
assets: AssetState, assets: AssetState,
instances: InstanceState, instances: InstanceState,
lights: LightState, lights: LightState,
tlas: TlasState,
bind_groups: BindGroupCacheState,
environment_map_light_sampler: Sampler, environment_map_light_sampler: Sampler,
environment_map_light_buffer: StorageBuffer<GpuEnvironmentMapLight>, environment_map_light_buffer: StorageBuffer<GpuEnvironmentMapLight>,
tlas: TlasState,
bind_groups: BindGroupCacheState,
} }
impl RaytracingSceneBindings { impl RaytracingSceneBindings {
@@ -100,14 +112,16 @@ impl FromWorld for RaytracingSceneBindings {
storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
texture_2d(TextureSampleType::Float { filterable: true }), texture_2d(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering), sampler(SamplerBindingType::Filtering),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
texture_cube(TextureSampleType::Float { filterable: true }), texture_cube(TextureSampleType::Float { filterable: true }),
sampler(SamplerBindingType::Filtering), sampler(SamplerBindingType::Filtering),
storage_buffer_read_only_sized(false, None), storage_buffer_read_only_sized(false, None),
storage_buffer_read_only_sized(false, None),
), ),
), ),
); );
@@ -132,10 +146,10 @@ impl FromWorld for RaytracingSceneBindings {
assets: AssetState::new(), assets: AssetState::new(),
instances: InstanceState::new(), instances: InstanceState::new(),
lights: LightState::new(), lights: LightState::new(),
tlas: TlasState::new(render_device),
bind_groups: BindGroupCacheState::new(render_device),
environment_map_light_sampler, environment_map_light_sampler,
environment_map_light_buffer, environment_map_light_buffer,
tlas: TlasState::new(render_device),
bind_groups: BindGroupCacheState::new(render_device),
} }
} }
} }
@@ -152,7 +166,28 @@ pub fn prepare_raytracing_scene_resources(
RemovedComponents<RaytracingMesh3d>, RemovedComponents<RaytracingMesh3d>,
RemovedComponents<Tape3d>, RemovedComponents<Tape3d>,
), ),
directional_lights: Query<(Entity, &ExtractedDirectionalLight)>, (
changed_directional_lights,
mut removed_directional_lights,
changed_point_lights,
mut removed_point_lights,
changed_spot_lights,
mut removed_spot_lights,
changed_rect_lights,
mut removed_rect_lights,
): (
Query<
(Entity, &ExtractedRaytracingDirectionalLight),
Changed<ExtractedRaytracingDirectionalLight>,
>,
RemovedComponents<ExtractedRaytracingDirectionalLight>,
Query<(Entity, &ExtractedRaytracingPointLight), Changed<ExtractedRaytracingPointLight>>,
RemovedComponents<ExtractedRaytracingPointLight>,
Query<(Entity, &ExtractedRaytracingSpotLight), Changed<ExtractedRaytracingSpotLight>>,
RemovedComponents<ExtractedRaytracingSpotLight>,
Query<(Entity, &ExtractedRaytracingRectLight), Changed<ExtractedRaytracingRectLight>>,
RemovedComponents<ExtractedRaytracingRectLight>,
),
needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>, needs_previous_frame_data: Option<Res<RaytracingSceneNeedsPreviousFrameData>>,
(mesh_allocator, tape_allocator): (Res<MeshAllocator>, Res<TapeAllocator>), (mesh_allocator, tape_allocator): (Res<MeshAllocator>, Res<TapeAllocator>),
(mesh_blas_manager, tape_blas_manager): (Res<MeshBlasManager>, Res<TapeBlasManager>), (mesh_blas_manager, tape_blas_manager): (Res<MeshBlasManager>, Res<TapeBlasManager>),
@@ -171,6 +206,7 @@ pub fn prepare_raytracing_scene_resources(
// Roll light ids over before any removal or compaction writes this frame's // Roll light ids over before any removal or compaction writes this frame's
// translations // translations
bindings.lights.begin_frame(needs_previous_frame_data); bindings.lights.begin_frame(needs_previous_frame_data);
bindings.instances.begin_frame();
// Update material and texture assets // Update material and texture assets
bindings bindings
@@ -207,7 +243,18 @@ pub fn prepare_raytracing_scene_resources(
); );
// Update the light set, now that emissive instances are resolved // Update the light set, now that emissive instances are resolved
bindings.lights.update(&directional_lights); {
let _span = info_span!("update_lights").entered();
let lights = &mut bindings.lights;
lights.update_directional_lights(
&changed_directional_lights,
removed_directional_lights.read(),
);
lights.update_point_lights(&changed_point_lights, removed_point_lights.read());
lights.update_spot_lights(&changed_spot_lights, removed_spot_lights.read());
lights.update_rect_lights(&changed_rect_lights, removed_rect_lights.read());
lights.finish_update();
}
// Upload the above writes // Upload the above writes
write_sparse_buffers(bindings, &render_device, &render_queue); write_sparse_buffers(bindings, &render_device, &render_queue);
@@ -237,34 +284,32 @@ fn write_sparse_buffers(
let _span = info_span!("write_buffers").entered(); let _span = info_span!("write_buffers").entered();
let assets = &mut bindings.assets; let assets = &mut bindings.assets;
assets.materials.grow(1); assets.materials.write_buffers_non_empty(device, queue);
assets.materials.write_buffers(device, queue);
let instances = &mut bindings.instances; let instances = &mut bindings.instances;
instances.transforms.grow(1); instances.transforms.write_buffers_non_empty(device, queue);
instances.transforms.write_buffers(device, queue);
instances.previous_frame_transforms.grow(1);
instances instances
.previous_frame_transforms .previous_frame_transforms
.write_buffers(device, queue); .write_buffers_non_empty(device, queue);
instances.geometry_ids.grow(1); instances
instances.geometry_ids.write_buffers(device, queue); .geometry_ids
instances.tape_ids.grow(1); .write_buffers_non_empty(device, queue);
instances.tape_ids.write_buffers(device, queue); instances.tape_ids.write_buffers_non_empty(device, queue);
instances.material_ids.grow(1); instances
instances.material_ids.write_buffers(device, queue); .material_ids
.write_buffers_non_empty(device, queue);
if bindings.tlas.uses_raw_build() { if bindings.tlas.uses_raw_build() {
instances.blas_refs.grow(1); instances.blas_refs.write_buffers_non_empty(device, queue);
instances.blas_refs.write_buffers(device, queue);
} }
let lights = &mut bindings.lights; let lights = &mut bindings.lights;
lights.sources.grow(1); lights.sources.write_buffers_non_empty(device, queue);
lights.sources.write_buffers(device, queue); lights
lights.directional_lights.grow(1); .directional_lights
lights.directional_lights.write_buffers(device, queue); .write_buffers_non_empty(device, queue);
lights.previous_frame_id_translations.grow(1); lights.point_lights.write_buffers_non_empty(device, queue);
lights.rect_lights.write_buffers_non_empty(device, queue);
lights lights
.previous_frame_id_translations .previous_frame_id_translations
.write_buffers(device, queue); .write_buffers_non_empty(device, queue);
} }
@@ -24,7 +24,6 @@ use super::{
MeshBlasManager, RaytracingSceneBindings, TapeBlasManager, bind_group::BindGroupCacheState, MeshBlasManager, RaytracingSceneBindings, TapeBlasManager, bind_group::BindGroupCacheState,
instances::InstanceState, tlas_build, instances::InstanceState, tlas_build,
}; };
use crate::scene::binder::instances::Object;
/// Compute pipeline that writes per-slot transforms and BLAS addresses into /// Compute pipeline that writes per-slot transforms and BLAS addresses into
/// TLAS descriptors. /// TLAS descriptors.
@@ -531,13 +530,13 @@ fn build_tlas_through_wgpu_core(
let capacity = tlas.get().len(); let capacity = tlas.get().len();
tlas[0..capacity].iter_mut().for_each(|entry| *entry = None); tlas[0..capacity].iter_mut().for_each(|entry| *entry = None);
for (slot, object, transform) in bindings.instances.drawable() { for (slot, blas_key, transform) in bindings.instances.drawable() {
// A mesh can lose its acceleration structure after the instance // A mesh can lose its acceleration structure after the instance
// resolved against it, which leaves the slot with // resolved against it, which leaves the slot with
// nothing to point at for a frame // nothing to point at for a frame
let Some(blas) = (match object { let Some(blas) = (match blas_key {
Object::Mesh(mesh) => mesh_blas_manager.get(&mesh), super::instances::BlasKey::Mesh(blas_key) => mesh_blas_manager.get(&blas_key),
Object::Tape(tape) => tape_blas_manager.get(&tape), super::instances::BlasKey::Tape(blas_key) => tape_blas_manager.get(&blas_key),
}) else { }) else {
continue; continue;
}; };
@@ -65,26 +65,45 @@ struct Material {
base_color_texture_id: u32, base_color_texture_id: u32,
emissive_texture_id: u32, emissive_texture_id: u32,
metallic_roughness_texture_id: u32, metallic_roughness_texture_id: u32,
base_color: vec3<f32>, base_color: vec3<f32>,
perceptual_roughness: f32, perceptual_roughness: f32,
emissive: vec3<f32>, emissive: vec3<f32>,
metallic: f32, metallic: f32,
_padding: vec3<f32>,
reflectance: f32, reflectance: f32,
flags: u32,
uv_translation: vec2<f32>,
uv_transform: mat2x2<f32>,
alpha: f32,
alpha_cutoff: f32,
_padding: vec2<f32>,
} }
const TEXTURE_MAP_NONE = 0xFFFFFFFFu; const TEXTURE_MAP_NONE = 0xFFFFFFFFu;
const MATERIAL_FLAG_DOUBLE_SIDED = 1u << 0u;
const MATERIAL_FLAG_FLIP_NORMAL_MAP_Y = 1u << 1u;
const MIRROR_ROUGHNESS_THRESHOLD = 0.001f; const MIRROR_ROUGHNESS_THRESHOLD = 0.001f;
struct LightSource { struct LightSource {
kind: u32, // 1 bit for kind, 31 bits for extra data kind: u32, // LIGHT_SOURCE_KIND_BITS bits for kind, rest of the bits for extra data
id: u32, id: u32,
} }
const LIGHT_SOURCE_KIND_BITS = 3u;
const LIGHT_SOURCE_KIND_EMISSIVE_MESH = 0u; const LIGHT_SOURCE_KIND_EMISSIVE_MESH = 0u;
const LIGHT_SOURCE_KIND_DIRECTIONAL = 1u; const LIGHT_SOURCE_KIND_DIRECTIONAL = 1u;
const LIGHT_SOURCE_KIND_POINT = 2u;
const LIGHT_SOURCE_KIND_RECT = 3u;
fn light_source_kind(light_source: LightSource) -> u32 {
return light_source.kind & ((1u << LIGHT_SOURCE_KIND_BITS) - 1u);
}
fn emissive_mesh_triangle_count(light_source: LightSource) -> u32 {
return light_source.kind >> LIGHT_SOURCE_KIND_BITS;
}
struct DirectionalLight { struct DirectionalLight {
direction_to_light: vec3<f32>, direction_to_light: vec3<f32>,
@@ -93,6 +112,28 @@ struct DirectionalLight {
inverse_pdf: f32, inverse_pdf: f32,
} }
/// A point or spot light. Point lights have no cone, e.g. `cos_outer <= -1`.
struct PointLight {
position: vec3<f32>,
radius: f32,
intensity: vec3<f32>,
cos_inner: f32,
axis: vec3<f32>,
cos_outer: f32,
}
/// A one-sided rectangular light facing `cross(edge_y, edge_x)`.
struct RectLight {
center: vec3<f32>,
area: f32,
edge_x: vec3<f32>,
_padding0: f32,
edge_y: vec3<f32>,
_padding1: f32,
radiance: vec3<f32>,
_padding2: f32,
}
struct EnvironmentMapLight { struct EnvironmentMapLight {
light_from_world: mat3x3<f32>, light_from_world: mat3x3<f32>,
intensity: f32, intensity: f32,
@@ -100,86 +141,72 @@ struct EnvironmentMapLight {
const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu; const LIGHT_NOT_PRESENT_THIS_FRAME = 0xFFFFFFFFu;
@group(0) @binding(0) @group(0) @binding(0) var<storage> vertex_buffers: binding_array<VertexBuffer>;
var<storage> vertex_buffers: binding_array<VertexBuffer>; @group(0) @binding(1) var<storage> index_buffers: binding_array<IndexBuffer>;
@group(0) @binding(1)
var<storage> index_buffers: binding_array<IndexBuffer>;
@group(0) @binding(2) @group(0) @binding(2)
var<storage> aabb_buffers: binding_array<AabbBuffer>; var<storage> aabb_buffers: binding_array<AabbBuffer>;
@group(0) @binding(3) @group(0) @binding(3)
var<storage> tape_metadata_buffers: binding_array<TapeMetadataBuffer>; var<storage> tape_metadata_buffers: binding_array<TapeMetadataBuffer>;
@group(0) @binding(4) @group(0) @binding(4) var textures: binding_array<texture_2d<f32>>;
var textures: binding_array<texture_2d<f32>>; @group(0) @binding(5) var samplers: binding_array<sampler>;
@group(0) @binding(5) @group(0) @binding(6) var<storage> materials: array<Material>;
var samplers: binding_array<sampler>; @group(0) @binding(7) var tlas: acceleration_structure;
@group(0) @binding(6) @group(0) @binding(8) var previous_frame_tlas: acceleration_structure;
var<storage> materials: array<Material>; @group(0) @binding(9) var<storage> transforms: array<mat3x4<f32>>;
@group(0) @binding(7) @group(0) @binding(10) var<storage> previous_frame_transforms: array<mat3x4<f32>>;
var tlas: acceleration_structure; @group(0) @binding(11) var<storage> geometry_ids: array<InstanceGeometryIds>;
@group(0) @binding(8) @group(0) @binding(12)
var previous_frame_tlas: acceleration_structure;
@group(0) @binding(9)
var<storage> transforms: array<mat3x4<f32>>;
@group(0) @binding(10)
var<storage> previous_frame_transforms: array<mat3x4<f32>>;
@group(0) @binding(11)
var<storage> geometry_ids: array<InstanceGeometryIds>;
@group(0) @binding(12)
var<storage> tape_ids: array<InstanceTapeIds>; var<storage> tape_ids: array<InstanceTapeIds>;
@group(0) @binding(13) @group(0) @binding(13) var<storage> material_ids: array<u32>;
var<storage> material_ids: array<u32>; @group(0) @binding(14) var brdf_dfg_lut: texture_2d<f32>;
@group(0) @binding(14) @group(0) @binding(15) var brdf_dfg_lut_sampler: sampler;
var<storage> light_sources: array<LightSource>; @group(0) @binding(16) var<storage> light_sources: array<LightSource>;
@group(0) @binding(15) @group(0) @binding(17) var<storage> directional_lights: array<DirectionalLight>;
var<storage> directional_lights: array<DirectionalLight>; @group(0) @binding(18) var<storage> point_lights: array<PointLight>;
@group(0) @binding(16) @group(0) @binding(19) var<storage> rect_lights: array<RectLight>;
var<storage> previous_frame_light_id_translations: array<u32>; @group(0) @binding(20) var environment_map: texture_cube<f32>;
@group(0) @binding(17) @group(0) @binding(21) var environment_map_sampler: sampler;
var brdf_dfg_lut: texture_2d<f32>; @group(0) @binding(22) var<storage> environment_map_light: EnvironmentMapLight;
@group(0) @binding(18) @group(0) @binding(23) var<storage> previous_frame_light_id_translations: array<u32>;
var brdf_dfg_lut_sampler: sampler;
@group(0) @binding(19)
var environment_map: texture_cube<f32>;
@group(0) @binding(20)
var environment_map_sampler: sampler;
@group(0) @binding(21)
var<storage> environment_map_light: EnvironmentMapLight;
const RAY_T_MIN = 0.001f; const RAY_T_MIN = 0.001f;
const RAY_T_MAX = 100000.0f; const RAY_T_MAX = 100000.0f;
const RAY_NO_CULL = 0xFFu; const RAY_NO_CULL = 0xFFu;
fn trace_ray( fn trace_ray(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
ray_origin: vec3<f32>,
ray_direction: vec3<f32>,
ray_t_min: f32,
ray_t_max: f32,
ray_flag: u32,
) -> RayIntersection {
let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction); let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction);
var rq: ray_query; var rq: ray_query;
rayQueryInitialize(&rq, tlas, ray); rayQueryInitialize(&rq, tlas, ray);
rayQueryProceed(&rq); while rayQueryProceed(&rq) {
let candidate = rayQueryGetCandidateIntersection(&rq);
if passes_alpha_test(candidate) {
rayQueryConfirmIntersection(&rq);
}
}
return rayQueryGetCommittedIntersection(&rq); return rayQueryGetCommittedIntersection(&rq);
} }
fn trace_ray_previous_frame( fn trace_ray_previous_frame(ray_origin: vec3<f32>, ray_direction: vec3<f32>, ray_t_min: f32, ray_t_max: f32, ray_flag: u32) -> RayIntersection {
ray_origin: vec3<f32>,
ray_direction: vec3<f32>,
ray_t_min: f32,
ray_t_max: f32,
ray_flag: u32,
) -> RayIntersection {
let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction); let ray = RayDesc(ray_flag, RAY_NO_CULL, ray_t_min, ray_t_max, ray_origin, ray_direction);
var rq: ray_query; var rq: ray_query;
rayQueryInitialize(&rq, previous_frame_tlas, ray); rayQueryInitialize(&rq, previous_frame_tlas, ray);
rayQueryProceed(&rq); while rayQueryProceed(&rq) {
let candidate = rayQueryGetCandidateIntersection(&rq);
if passes_alpha_test(candidate) {
rayQueryConfirmIntersection(&rq);
}
}
return rayQueryGetCommittedIntersection(&rq); return rayQueryGetCommittedIntersection(&rq);
} }
fn sample_texture(id: u32, uv: vec2<f32>) -> vec3<f32> { fn passes_alpha_test(candidate: RayIntersection) -> bool {
return textureSampleLevel(textures[id], samplers[id], uv, 0.0).rgb; // TODO: Mipmap let barycentrics = vec3(1.0 - candidate.barycentrics.x - candidate.barycentrics.y, candidate.barycentrics);
return !resolve_triangle_data_full(candidate.instance_custom_data, candidate.primitive_index, barycentrics).material.alpha_masked_out;
}
fn sample_texture(id: u32, uv: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(textures[id], samplers[id], uv, 0.0); // TODO: Mipmap
} }
struct ResolvedMaterial { struct ResolvedMaterial {
@@ -189,6 +216,7 @@ struct ResolvedMaterial {
perceptual_roughness: f32, perceptual_roughness: f32,
roughness: f32, roughness: f32,
metallic: f32, metallic: f32,
alpha_masked_out: bool,
} }
struct ResolvedRayHitFull { struct ResolvedRayHitFull {
@@ -201,19 +229,27 @@ struct ResolvedRayHitFull {
triangle_area: f32, triangle_area: f32,
triangle_count: u32, triangle_count: u32,
material: ResolvedMaterial, material: ResolvedMaterial,
double_sided: bool,
} }
fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial { fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial {
var m: ResolvedMaterial; var m: ResolvedMaterial;
m.base_color = material.base_color.rgb; m.base_color = material.base_color.rgb;
var alpha = material.alpha;
if material.base_color_texture_id != TEXTURE_MAP_NONE { if material.base_color_texture_id != TEXTURE_MAP_NONE {
m.base_color *= sample_texture(material.base_color_texture_id, uv); let base_color = sample_texture(material.base_color_texture_id, uv);
m.base_color *= base_color.rgb;
alpha *= base_color.a;
} }
m.emissive = material.emissive.rgb; m.emissive = material.emissive.rgb;
if material.emissive_texture_id != TEXTURE_MAP_NONE { if material.emissive_texture_id != TEXTURE_MAP_NONE {
m.emissive *= sample_texture(material.emissive_texture_id, uv); m.emissive *= sample_texture(material.emissive_texture_id, uv).rgb;
}
m.alpha_masked_out = alpha < material.alpha_cutoff;
if m.alpha_masked_out {
m.emissive = vec3(0.0);
} }
m.reflectance = material.reflectance; m.reflectance = material.reflectance;
@@ -221,7 +257,7 @@ fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial {
m.perceptual_roughness = material.perceptual_roughness; m.perceptual_roughness = material.perceptual_roughness;
m.metallic = material.metallic; m.metallic = material.metallic;
if material.metallic_roughness_texture_id != TEXTURE_MAP_NONE { if material.metallic_roughness_texture_id != TEXTURE_MAP_NONE {
let metallic_roughness = sample_texture(material.metallic_roughness_texture_id, uv); let metallic_roughness = sample_texture(material.metallic_roughness_texture_id, uv).rgb;
m.perceptual_roughness *= metallic_roughness.g; m.perceptual_roughness *= metallic_roughness.g;
m.metallic *= metallic_roughness.b; m.metallic *= metallic_roughness.b;
} }
@@ -232,49 +268,44 @@ fn resolve_material(material: Material, uv: vec2<f32>) -> ResolvedMaterial {
} }
fn resolve_ray_hit_full(ray_hit: RayIntersection) -> ResolvedRayHitFull { fn resolve_ray_hit_full(ray_hit: RayIntersection) -> ResolvedRayHitFull {
let barycentrics = vec3( let barycentrics = vec3(1.0 - ray_hit.barycentrics.x - ray_hit.barycentrics.y, ray_hit.barycentrics);
1.0 - ray_hit.barycentrics.x - ray_hit.barycentrics.y, var resolved = resolve_triangle_data_full(ray_hit.instance_custom_data, ray_hit.primitive_index, barycentrics);
ray_hit.barycentrics,
); // Flip normals for backfacing hits of double sided materials
return resolve_triangle_data_full( if !ray_hit.front_face && resolved.double_sided {
ray_hit.instance_custom_data, resolved.world_normal = -resolved.world_normal;
ray_hit.primitive_index, resolved.geometric_world_normal = -resolved.geometric_world_normal;
barycentrics,
); // Emissive surfaces only emit from their front side
resolved.material.emissive = vec3(0.0);
}
return resolved;
} }
fn load_vertices(instance_geometry_ids: InstanceGeometryIds, triangle_id: u32) -> array<Vertex, 3> { fn load_vertices(instance_geometry_ids: InstanceGeometryIds, triangle_id: u32) -> array<Vertex, 3> {
let index_buffer = &index_buffers[instance_geometry_ids.index_buffer_id].indices; let index_buffer = &index_buffers[instance_geometry_ids.index_buffer_id].indices;
let vertex_buffer = &vertex_buffers[instance_geometry_ids.vertex_buffer_id].vertices; let vertex_buffer = &vertex_buffers[instance_geometry_ids.vertex_buffer_id].vertices;
let indices_i = (triangle_id * 3u) + vec3(0u, 1u, 2u) let indices_i = (triangle_id * 3u) + vec3(0u, 1u, 2u) + instance_geometry_ids.index_buffer_offset;
+ instance_geometry_ids.index_buffer_offset; let indices = vec3((*index_buffer)[indices_i.x], (*index_buffer)[indices_i.y], (*index_buffer)[indices_i.z]) + instance_geometry_ids.vertex_buffer_offset;
let indices = vec3(
(*index_buffer)[indices_i.x],
(*index_buffer)[indices_i.y],
(*index_buffer)[indices_i.z],
) + instance_geometry_ids.vertex_buffer_offset;
return array<Vertex, 3>( return array<Vertex, 3>(
unpack_vertex((*vertex_buffer)[indices.x]), unpack_vertex((*vertex_buffer)[indices.x]),
unpack_vertex((*vertex_buffer)[indices.y]), unpack_vertex((*vertex_buffer)[indices.y]),
unpack_vertex((*vertex_buffer)[indices.z]), unpack_vertex((*vertex_buffer)[indices.z])
); );
} }
fn transform_positions(transform: mat4x4<f32>, vertices: array<Vertex, 3>) -> array<vec3<f32>, 3> { fn transform_positions(transform: mat4x4<f32>, vertices: array<Vertex, 3>) -> array<vec3<f32>, 3> {
return array<vec3<f32>, 3>( return array<vec3<f32>, 3>(
(transform * vec4(vertices[0].position, 1.0)).xyz, (transform * vec4(vertices[0].position, 1.0)).xyz,
(transform * vec4(vertices[1].position, 1.0)).xyz, (transform * vec4(vertices[1].position, 1.0)).xyz,
(transform * vec4(vertices[2].position, 1.0)).xyz, (transform * vec4(vertices[2].position, 1.0)).xyz
); );
} }
fn resolve_triangle_data_full( fn resolve_triangle_data_full(instance_id: u32, triangle_id: u32, barycentrics: vec3<f32>) -> ResolvedRayHitFull {
instance_id: u32,
triangle_id: u32,
barycentrics: vec3<f32>,
) -> ResolvedRayHitFull {
let material_id = material_ids[instance_id]; let material_id = material_ids[instance_id];
let material = materials[material_id]; let material = materials[material_id];
@@ -285,51 +316,24 @@ fn resolve_triangle_data_full(
let vertices = load_vertices(instance_geometry_ids, triangle_id); let vertices = load_vertices(instance_geometry_ids, triangle_id);
let world_vertices = transform_positions(transform, vertices); let world_vertices = transform_positions(transform, vertices);
let world_position = mat3x3( let world_position = mat3x3(world_vertices[0], world_vertices[1], world_vertices[2]) * barycentrics;
world_vertices[0],
world_vertices[1],
world_vertices[2],
) * barycentrics;
let previous_frame_world_vertices = transform_positions(previous_frame_transform, vertices); let previous_frame_world_vertices = transform_positions(previous_frame_transform, vertices);
let previous_frame_world_position = mat3x3( let previous_frame_world_position = mat3x3(previous_frame_world_vertices[0], previous_frame_world_vertices[1], previous_frame_world_vertices[2]) * barycentrics;
previous_frame_world_vertices[0],
previous_frame_world_vertices[1],
previous_frame_world_vertices[2],
) * barycentrics;
let uv = mat3x2(vertices[0].uv, vertices[1].uv, vertices[2].uv) * barycentrics; let mesh_uv = mat3x2(vertices[0].uv, vertices[1].uv, vertices[2].uv) * barycentrics;
let uv = material.uv_transform * mesh_uv + material.uv_translation;
let transform_3x3 = mat3x3( let transform_3x3 = mat3x3(transform[0].xyz, transform[1].xyz, transform[2].xyz);
transform[0].xyz,
transform[1].xyz,
transform[2].xyz,
);
let cofactor = mat3x3( let cofactor = mat3x3(cross(transform_3x3[1], transform_3x3[2]), cross(transform_3x3[2], transform_3x3[0]), cross(transform_3x3[0], transform_3x3[1]));
cross(transform_3x3[1], transform_3x3[2]),
cross(transform_3x3[2], transform_3x3[0]),
cross(transform_3x3[0], transform_3x3[1]),
);
let determinant = dot(transform_3x3[0], cofactor[0]); let determinant = dot(transform_3x3[0], cofactor[0]);
let determinant_sign = select(sign(determinant), 1.0, determinant == 0.0); let determinant_sign = select(sign(determinant), 1.0, determinant == 0.0);
let local_tangent = mat3x3( let local_tangent = mat3x3(vertices[0].tangent.xyz, vertices[1].tangent.xyz, vertices[2].tangent.xyz) * barycentrics;
vertices[0].tangent.xyz, let world_tangent = vec4(normalize(transform_3x3 * local_tangent), vertices[0].tangent.w * determinant_sign);
vertices[1].tangent.xyz,
vertices[2].tangent.xyz,
) * barycentrics;
let world_tangent = vec4(
normalize(transform_3x3 * local_tangent),
vertices[0].tangent.w * determinant_sign,
);
let local_normal = mat3x3( let local_normal = mat3x3(vertices[0].normal, vertices[1].normal, vertices[2].normal) * barycentrics; // TODO: Use barycentric lerp, ray_hit.object_to_world, cross product geo normal
vertices[0].normal,
vertices[1].normal,
vertices[2].normal,
)
* barycentrics; // TODO: Use barycentric lerp, ray_hit.object_to_world, cross product geo normal
var world_normal = normalize(determinant_sign * (cofactor * local_normal)); var world_normal = normalize(determinant_sign * (cofactor * local_normal));
let geometric_world_normal = world_normal; let geometric_world_normal = world_normal;
@@ -338,10 +342,11 @@ fn resolve_triangle_data_full(
let T = TBN[0]; let T = TBN[0];
let B = TBN[1]; let B = TBN[1];
let N = TBN[2]; let N = TBN[2];
var Nt = sample_texture(material.normal_map_texture_id, uv) * 2.0 - 1.0; var Nt = sample_texture(material.normal_map_texture_id, uv).rgb * 2.0 - 1.0;
Nt.z = sqrt( if (material.flags & MATERIAL_FLAG_FLIP_NORMAL_MAP_Y) != 0u {
max(1.0 - dot(Nt.xy, Nt.xy), 0.0), Nt.y = -Nt.y;
); // Reconstruct Z to support two-channel normal maps }
Nt.z = sqrt(max(1.0 - dot(Nt.xy, Nt.xy), 0.0)); // Reconstruct Z to support two-channel normal maps
world_normal = normalize(Nt.x * T + Nt.y * B + Nt.z * N); world_normal = normalize(Nt.x * T + Nt.y * B + Nt.z * N);
} }
@@ -352,14 +357,15 @@ fn resolve_triangle_data_full(
let resolved_material = resolve_material(material, uv); let resolved_material = resolve_material(material, uv);
return ResolvedRayHitFull( return ResolvedRayHitFull(
world_position, world_position,
previous_frame_world_position, previous_frame_world_position,
world_normal, world_normal,
geometric_world_normal, geometric_world_normal,
world_tangent, world_tangent,
uv, uv,
triangle_area, triangle_area,
instance_geometry_ids.triangle_count, instance_geometry_ids.triangle_count,
resolved_material, resolved_material,
); (material.flags & MATERIAL_FLAG_DOUBLE_SIDED) != 0u,
);
} }
@@ -1,6 +1,10 @@
use core::f32::consts::PI;
use bevy_asset::{AssetEvent, AssetId, Assets, Handle}; use bevy_asset::{AssetEvent, AssetId, Assets, Handle};
use bevy_camera::Camera; use bevy_camera::{Camera, visibility::InheritedVisibility};
use bevy_color::{ColorToComponents, LinearRgba};
use bevy_ecs::{ use bevy_ecs::{
component::Component,
lifecycle::RemovedComponents, lifecycle::RemovedComponents,
message::MessageReader, message::MessageReader,
query::{Added, Changed, Or, With}, query::{Added, Changed, Or, With},
@@ -8,8 +12,10 @@ use bevy_ecs::{
system::{Commands, Query, Res, ResMut}, system::{Commands, Query, Res, ResMut},
}; };
use bevy_image::Image; use bevy_image::Image;
use bevy_light::{EnvironmentMapLight, GeneratedEnvironmentMapLight}; use bevy_light::{
use bevy_math::Quat; DirectionalLight, EnvironmentMapLight, PointLight, RectLight, SpotLight, SunDisk,
};
use bevy_math::{Quat, Vec3, ops::cos};
use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial}; use bevy_pbr::{MeshMaterial3d, PreviousGlobalTransform, StandardMaterial};
use bevy_platform::collections::HashMap; use bevy_platform::collections::HashMap;
use bevy_render::{Extract, sync_world::RenderEntity}; use bevy_render::{Extract, sync_world::RenderEntity};
@@ -217,6 +223,39 @@ pub fn extract_raytracing_material_assets(
} }
} }
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingDirectionalLight {
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 intensity: Vec3,
}
#[derive(Component, Clone, Copy, PartialEq, Debug)]
pub struct ExtractedRaytracingSpotLight {
pub position: Vec3,
pub radius: f32,
pub intensity: 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 radiance: Vec3,
}
#[derive(Resource, Default, Clone, PartialEq)] #[derive(Resource, Default, Clone, PartialEq)]
pub struct ExtractedEnvironmentMapLight { pub struct ExtractedEnvironmentMapLight {
pub cubemap: Option<Handle<Image>>, pub cubemap: Option<Handle<Image>>,
@@ -224,36 +263,224 @@ pub struct ExtractedEnvironmentMapLight {
pub rotation: Quat, pub rotation: Quat,
} }
/// Finds the environment map light to use for the raytraced scene, if any. /// Lights whose extracted data needs updating.
pub fn extract_raytracing_environment_map_light( type ChangedLightFilter<L> = Or<(
cameras: Extract< Changed<L>,
Changed<GlobalTransform>,
Changed<InheritedVisibility>,
)>;
type ChangedLightQuery<'w, 's, L> = Query<
'w,
's,
(
RenderEntity,
&'static L,
&'static GlobalTransform,
&'static InheritedVisibility,
),
ChangedLightFilter<L>,
>;
/// Keeps the render world's directional lights up to date.
pub fn extract_raytracing_directional_lights(
changed_directional_lights: Extract<
Query<
(
RenderEntity,
&DirectionalLight,
&GlobalTransform,
&InheritedVisibility,
Option<&SunDisk>,
),
Or<(ChangedLightFilter<DirectionalLight>, Changed<SunDisk>)>,
>,
>,
directional_lights: Extract<
Query<( Query<(
&Camera, RenderEntity,
Option<&GeneratedEnvironmentMapLight>, &DirectionalLight,
Option<&EnvironmentMapLight>, &GlobalTransform,
&InheritedVisibility,
Option<&SunDisk>,
)>, )>,
>, >,
mut removed_directional_lights: Extract<RemovedComponents<DirectionalLight>>,
mut removed_sun_disks: Extract<RemovedComponents<SunDisk>>,
render_entities: Extract<Query<RenderEntity>>,
mut commands: Commands,
) {
// Process removed components before changes, that way it properly handles
// same-frame removal->insertion
for main_entity in removed_directional_lights.read() {
if let Ok(render_entity) = render_entities.get(main_entity) {
commands
.entity(render_entity)
.remove::<ExtractedRaytracingDirectionalLight>();
}
}
// Removing a light's SunDisk changes its angular size back to the default,
// but no change filter fires for a component that no longer exists, so
// re-extract those lights too
let sun_disk_removed = removed_sun_disks
.read()
.filter_map(|main_entity| directional_lights.get(main_entity).ok());
for (render_entity, directional_light, transform, visibility, sun_disk) in
changed_directional_lights.iter().chain(sun_disk_removed)
{
let mut entity_commands = commands.entity(render_entity);
if !visibility.get() {
entity_commands.remove::<ExtractedRaytracingDirectionalLight>();
continue;
}
entity_commands.insert(ExtractedRaytracingDirectionalLight {
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,
});
}
}
/// Keeps the render world's point lights up to date.
pub fn extract_raytracing_point_lights(
changed_point_lights: Extract<ChangedLightQuery<PointLight>>,
mut removed_point_lights: Extract<RemovedComponents<PointLight>>,
render_entities: Extract<Query<RenderEntity>>,
mut commands: Commands,
) {
// Process removed components before changes, that way it properly handles
// same-frame removal->insertion
for main_entity in removed_point_lights.read() {
if let Ok(render_entity) = render_entities.get(main_entity) {
commands
.entity(render_entity)
.remove::<ExtractedRaytracingPointLight>();
}
}
for (render_entity, point_light, transform, visibility) in &changed_point_lights {
let mut entity_commands = commands.entity(render_entity);
if !visibility.get() {
entity_commands.remove::<ExtractedRaytracingPointLight>();
continue;
}
entity_commands.insert(ExtractedRaytracingPointLight {
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),
});
}
}
/// Keeps the render world's spot lights up to date.
pub fn extract_raytracing_spot_lights(
changed_spot_lights: Extract<ChangedLightQuery<SpotLight>>,
mut removed_spot_lights: Extract<RemovedComponents<SpotLight>>,
render_entities: Extract<Query<RenderEntity>>,
mut commands: Commands,
) {
// Process removed components before changes, that way it properly handles
// same-frame removal->insertion
for main_entity in removed_spot_lights.read() {
if let Ok(render_entity) = render_entities.get(main_entity) {
commands
.entity(render_entity)
.remove::<ExtractedRaytracingSpotLight>();
}
}
for (render_entity, spot_light, transform, visibility) in &changed_spot_lights {
let mut entity_commands = commands.entity(render_entity);
if !visibility.get() {
entity_commands.remove::<ExtractedRaytracingSpotLight>();
continue;
}
let outer_angle = spot_light.outer_angle;
let inner_angle = spot_light.inner_angle.min(outer_angle);
entity_commands.insert(ExtractedRaytracingSpotLight {
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(),
cos_inner: cos(inner_angle),
cos_outer: cos(outer_angle),
});
}
}
/// Keeps the render world's rect lights up to date.
pub fn extract_raytracing_rect_lights(
changed_rect_lights: Extract<ChangedLightQuery<RectLight>>,
mut removed_rect_lights: Extract<RemovedComponents<RectLight>>,
render_entities: Extract<Query<RenderEntity>>,
mut commands: Commands,
) {
// Process removed components before changes, that way it properly handles
// same-frame removal->insertion
for main_entity in removed_rect_lights.read() {
if let Ok(render_entity) = render_entities.get(main_entity) {
commands
.entity(render_entity)
.remove::<ExtractedRaytracingRectLight>();
}
}
for (render_entity, rect_light, transform, visibility) in &changed_rect_lights {
let affine = transform.affine();
let edge_x = Vec3::from(affine.matrix3.x_axis) * rect_light.width;
let edge_y = Vec3::from(affine.matrix3.y_axis) * rect_light.height;
let area = edge_x.cross(edge_y).length();
let mut entity_commands = commands.entity(render_entity);
if !visibility.get() || !area.is_finite() || area <= 0.0 {
entity_commands.remove::<ExtractedRaytracingRectLight>();
continue;
}
entity_commands.insert(ExtractedRaytracingRectLight {
center: transform.translation(),
edge_x,
edge_y,
area,
// Map from luminous power in lumens to luminance
radiance: LinearRgba::from(rect_light.color).to_vec3() * rect_light.intensity
/ (area * PI),
});
}
}
/// Finds the environment map light to use for the raytraced scene, if any.
///
/// Only mip 0 of the specular cubemap is sampled.
pub fn extract_raytracing_environment_map_light(
cameras: Extract<Query<(&Camera, Option<&EnvironmentMapLight>)>>,
mut environment_map_light: ResMut<ExtractedEnvironmentMapLight>, mut environment_map_light: ResMut<ExtractedEnvironmentMapLight>,
) { ) {
let mut extracted_env_map_light = ExtractedEnvironmentMapLight::default(); let mut extracted_env_map_light = ExtractedEnvironmentMapLight::default();
for (camera, generated, pregenerated) in &cameras { for (camera, env_map) in &cameras {
if !camera.is_active { if !camera.is_active {
continue; continue;
} }
let env_map_light = match (generated, pregenerated) { let Some(env_map) = env_map else {
(Some(generated), _) => ExtractedEnvironmentMapLight { continue;
cubemap: Some(generated.environment_map.clone()), };
intensity: generated.intensity,
rotation: generated.rotation, let env_map_light = ExtractedEnvironmentMapLight {
}, cubemap: Some(env_map.specular_map.clone()),
(None, Some(pregenerated)) => ExtractedEnvironmentMapLight { intensity: env_map.intensity,
cubemap: Some(pregenerated.specular_map.clone()), rotation: env_map.rotation,
intensity: pregenerated.intensity,
rotation: pregenerated.rotation,
},
(None, None) => continue,
}; };
if extracted_env_map_light.cubemap.is_none() { if extracted_env_map_light.cubemap.is_none() {
@@ -4,7 +4,7 @@ use bevy_ecs::{
resource::Resource, resource::Resource,
system::{Res, ResMut}, system::{Res, ResMut},
}; };
use bevy_mesh::{Indices, Mesh}; use bevy_mesh::{Indices, Mesh, MeshRaytracingFlags};
use bevy_platform::collections::HashMap; use bevy_platform::collections::HashMap;
use bevy_render::{ use bevy_render::{
diagnostic::{DiagnosticsRecorder, RecordDiagnostics}, diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
@@ -28,8 +28,8 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct BlasManager { pub struct BlasManager {
blas: HashMap<AssetId<Mesh>, Blas>, blas: HashMap<AssetId<Mesh>, MeshBlas>,
compaction_queue: VecDeque<(AssetId<Mesh>, u32, bool)>, compaction_queue: VecDeque<(BlasKey, u32, bool)>,
changed: Vec<AssetId<Mesh>>, changed: Vec<AssetId<Mesh>>,
/// BLAS that are pending deletion, one batch per TLAS build. The back batch collects /// 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 /// retirements since the last build, and every batch ahead of it has one more build to wait
@@ -38,12 +38,24 @@ pub struct BlasManager {
} }
impl BlasManager { impl BlasManager {
pub fn get(&self, mesh: &AssetId<Mesh>) -> Option<&Blas> { pub fn get(&self, key: &BlasKey) -> Option<&Blas> {
self.blas.get(mesh) self.blas.get(&key.mesh)?.get(key.opacity)
} }
pub fn device_address(&self, mesh: &AssetId<Mesh>) -> Option<u64> { pub fn device_address(&self, key: &BlasKey) -> Option<u64> {
self.blas.get(mesh)?.handle() self.get(key)?.handle()
}
/// 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)
.is_some_and(|mesh| !mesh.requires.contains(key.opacity.flag()))
}
fn require(&mut self, mesh: AssetId<Mesh>, flags: MeshRaytracingFlags) {
self.blas.entry(mesh).or_default().requires = flags;
} }
pub fn changed_meshes(&self) -> &[AssetId<Mesh>] { pub fn changed_meshes(&self) -> &[AssetId<Mesh>] {
@@ -56,19 +68,23 @@ impl BlasManager {
} }
} }
fn insert(&mut self, mesh: AssetId<Mesh>, blas: Blas) { fn insert(&mut self, key: BlasKey, blas: Blas) {
if let Some(old) = self.blas.insert(mesh, blas) { let slot = self.blas.entry(key.mesh).or_default().slot_mut(key.opacity);
if let Some(old) = slot.replace(blas) {
self.retire(old); self.retire(old);
} }
self.changed.push(mesh); self.changed.push(key.mesh);
} }
fn remove(&mut self, mesh: AssetId<Mesh>) { fn remove_mesh(&mut self, mesh: AssetId<Mesh>) {
self.changed.push(mesh); self.changed.push(mesh);
self.compaction_queue.retain(|(key, ..)| key.mesh != mesh);
if let Some(removed) = self.blas.remove(&mesh) { if let Some(removed) = self.blas.remove(&mesh) {
self.retire(removed); for blas in removed.into_iter() {
self.retire(blas);
}
} }
} }
@@ -80,6 +96,76 @@ impl BlasManager {
} }
} }
struct MeshBlas {
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
non_opaque: Option<Blas>,
}
impl Default for MeshBlas {
fn default() -> Self {
Self {
requires: MeshRaytracingFlags::empty(),
opaque: None,
non_opaque: None,
}
}
}
impl MeshBlas {
fn get(&self, opacity: BlasOpacity) -> Option<&Blas> {
match opacity {
BlasOpacity::Opaque => self.opaque.as_ref(),
BlasOpacity::NonOpaque => self.non_opaque.as_ref(),
}
}
fn slot_mut(&mut self, opacity: BlasOpacity) -> &mut Option<Blas> {
match opacity {
BlasOpacity::Opaque => &mut self.opaque,
BlasOpacity::NonOpaque => &mut self.non_opaque,
}
}
fn into_iter(self) -> impl Iterator<Item = Blas> {
self.opaque.into_iter().chain(self.non_opaque)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BlasKey {
pub mesh: AssetId<Mesh>,
pub opacity: BlasOpacity,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum BlasOpacity {
Opaque,
NonOpaque,
}
impl BlasOpacity {
fn declared(flags: MeshRaytracingFlags) -> impl Iterator<Item = Self> {
[Self::Opaque, Self::NonOpaque]
.into_iter()
.filter(move |opacity: &BlasOpacity| flags.contains(opacity.flag()))
}
pub fn flag(self) -> MeshRaytracingFlags {
match self {
Self::Opaque => MeshRaytracingFlags::OPAQUE,
Self::NonOpaque => MeshRaytracingFlags::NON_OPAQUE,
}
}
fn geometry_flags(self) -> AccelerationStructureGeometryFlags {
match self {
Self::Opaque => AccelerationStructureGeometryFlags::OPAQUE,
Self::NonOpaque => AccelerationStructureGeometryFlags::empty(),
}
}
}
pub fn prepare_raytracing_blas( pub fn prepare_raytracing_blas(
mut blas_manager: ResMut<BlasManager>, mut blas_manager: ResMut<BlasManager>,
extracted_meshes: Res<ExtractedAssets<RenderMesh>>, extracted_meshes: Res<ExtractedAssets<RenderMesh>>,
@@ -96,38 +182,50 @@ pub fn prepare_raytracing_blas(
.iter() .iter()
.chain(extracted_meshes.modified.iter()) .chain(extracted_meshes.modified.iter())
{ {
blas_manager.remove(*asset_id); blas_manager.remove_mesh(*asset_id);
} }
if extracted_meshes.extracted.is_empty() { if extracted_meshes.extracted.is_empty() {
return; return;
} }
// Create new BLAS for added or changed meshes // Record which BLAS added or changed meshes declare, even if none
for (asset_id, mesh) in &extracted_meshes.extracted {
if is_mesh_raytracing_compatible(mesh) {
blas_manager.require(*asset_id, mesh.raytracing);
}
}
// Create a BLAS for each opacity that added or changed meshes declare
let blas_resources = extracted_meshes let blas_resources = extracted_meshes
.extracted .extracted
.iter() .iter()
.filter(|(_, mesh)| is_mesh_raytracing_compatible(mesh)) .filter(|(_, mesh)| is_mesh_raytracing_compatible(mesh))
.map(|(asset_id, _)| { .flat_map(|(asset_id, mesh)| {
let vertex_slice = mesh_allocator.mesh_vertex_slice(asset_id).unwrap(); BlasOpacity::declared(mesh.raytracing).map(|opacity| BlasKey {
let index_slice = mesh_allocator.mesh_index_slice(asset_id).unwrap(); mesh: *asset_id,
opacity,
})
})
.map(|key| {
let vertex_slice = mesh_allocator.mesh_vertex_slice(&key.mesh).unwrap();
let index_slice = mesh_allocator.mesh_index_slice(&key.mesh).unwrap();
let (blas, blas_size) = let (blas, blas_size) = allocate_blas(&vertex_slice, &index_slice, key, &render_device);
allocate_blas(&vertex_slice, &index_slice, asset_id, &render_device);
blas_manager.insert(*asset_id, blas); blas_manager.insert(key, blas);
blas_manager blas_manager
.compaction_queue .compaction_queue
.push_back((*asset_id, blas_size.vertex_count, false)); .push_back((key, blas_size.vertex_count, false));
(*asset_id, vertex_slice, index_slice, blas_size) (key, vertex_slice, index_slice, blas_size)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Build geometry into each BLAS // Build geometry into each BLAS
let build_entries = blas_resources let build_entries = blas_resources
.iter() .iter()
.map(|(asset_id, vertex_slice, index_slice, blas_size)| { .map(|(key, vertex_slice, index_slice, blas_size)| {
let geometry = BlasTriangleGeometry { let geometry = BlasTriangleGeometry {
size: blas_size, size: blas_size,
vertex_buffer: vertex_slice.buffer, vertex_buffer: vertex_slice.buffer,
@@ -139,7 +237,7 @@ pub fn prepare_raytracing_blas(
transform_buffer_offset: None, transform_buffer_offset: None,
}; };
BlasBuildEntry { BlasBuildEntry {
blas: &blas_manager.blas[asset_id], blas: blas_manager.get(key).unwrap(),
geometry: BlasGeometries::TriangleGeometries(vec![geometry]), geometry: BlasGeometries::TriangleGeometries(vec![geometry]),
} }
}) })
@@ -172,10 +270,10 @@ pub fn compact_raytracing_blas(
{ {
meshes_processed += 1; meshes_processed += 1;
let (mesh, vertex_count, compaction_started) = let (key, vertex_count, compaction_started) =
blas_manager.compaction_queue.pop_front().unwrap(); blas_manager.compaction_queue.pop_front().unwrap();
let Some(blas) = blas_manager.get(&mesh) else { let Some(blas) = blas_manager.get(&key) else {
continue; continue;
}; };
@@ -185,7 +283,7 @@ pub fn compact_raytracing_blas(
if blas.ready_for_compaction() { if blas.ready_for_compaction() {
let compacted_blas = render_queue.compact_blas(blas); let compacted_blas = render_queue.compact_blas(blas);
blas_manager.insert(mesh, compacted_blas); blas_manager.insert(key, compacted_blas);
vertices_compacted += vertex_count; vertices_compacted += vertex_count;
continue; continue;
@@ -194,7 +292,7 @@ pub fn compact_raytracing_blas(
// BLAS not ready for compaction, put back in queue // BLAS not ready for compaction, put back in queue
blas_manager blas_manager
.compaction_queue .compaction_queue
.push_back((mesh, vertex_count, true)); .push_back((key, vertex_count, true));
} }
} }
@@ -218,7 +316,7 @@ pub fn delete_raytracing_blas(
fn allocate_blas( fn allocate_blas(
vertex_slice: &MeshBufferSlice, vertex_slice: &MeshBufferSlice,
index_slice: &MeshBufferSlice, index_slice: &MeshBufferSlice,
asset_id: &AssetId<Mesh>, key: BlasKey,
render_device: &RenderDevice, render_device: &RenderDevice,
) -> (Blas, BlasTriangleGeometrySizeDescriptor) { ) -> (Blas, BlasTriangleGeometrySizeDescriptor) {
let blas_size = BlasTriangleGeometrySizeDescriptor { let blas_size = BlasTriangleGeometrySizeDescriptor {
@@ -226,14 +324,14 @@ fn allocate_blas(
vertex_count: vertex_slice.range.len() as u32, vertex_count: vertex_slice.range.len() as u32,
index_format: Some(IndexFormat::Uint32), index_format: Some(IndexFormat::Uint32),
index_count: Some(index_slice.range.len() as u32), index_count: Some(index_slice.range.len() as u32),
flags: AccelerationStructureGeometryFlags::OPAQUE, flags: key.opacity.geometry_flags(),
}; };
// TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS double-buffer // TODO: If we ever introduce BLAS refits, we need to be aware of the TLAS double-buffer
// to avoid invalidating the previous frame TLAS // to avoid invalidating the previous frame TLAS
let blas = render_device.wgpu_device().create_blas( let blas = render_device.wgpu_device().create_blas(
&CreateBlasDescriptor { &CreateBlasDescriptor {
label: Some(&asset_id.to_string()), label: Some(&format!("{} {:?}", key.mesh, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE flags: AccelerationStructureFlags::PREFER_FAST_TRACE
| AccelerationStructureFlags::ALLOW_COMPACTION, | AccelerationStructureFlags::ALLOW_COMPACTION,
update_mode: AccelerationStructureUpdateMode::Build, update_mode: AccelerationStructureUpdateMode::Build,
@@ -258,5 +356,5 @@ fn is_mesh_raytracing_compatible(mesh: &Mesh) -> bool {
(Mesh::ATTRIBUTE_TANGENT.id, Mesh::ATTRIBUTE_TANGENT.format), (Mesh::ATTRIBUTE_TANGENT.id, Mesh::ATTRIBUTE_TANGENT.format),
]); ]);
let indexed_32 = matches!(mesh.indices(), Some(Indices::U32(..))); let indexed_32 = matches!(mesh.indices(), Some(Indices::U32(..)));
mesh.enable_raytracing && triangle_list && vertex_attributes && indexed_32 triangle_list && vertex_attributes && indexed_32
} }
@@ -3,20 +3,19 @@ use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{component::Component, prelude::ReflectComponent, template::FromTemplate}; use bevy_ecs::{component::Component, prelude::ReflectComponent, template::FromTemplate};
use bevy_mesh::Mesh; use bevy_mesh::Mesh;
use bevy_pbr::{MeshMaterial3d, StandardMaterial}; use bevy_pbr::{MeshMaterial3d, StandardMaterial};
use bevy_reflect::{Reflect, prelude::ReflectDefault}; use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_render::sync_world::SyncToRenderWorld; use bevy_render::sync_world::SyncToRenderWorld;
use bevy_transform::components::Transform; use bevy_transform::components::Transform;
use derive_more::derive::From; use derive_more::derive::From;
/// A mesh component used for raytracing. /// A mesh component used for raytracing.
/// ///
/// The mesh used in this component must have [`Mesh::enable_raytracing`] set to /// The mesh used in this component must declare the BLAS its material needs in
/// true, use the following set of vertex attributes: `{POSITION, NORMAL, UV_0, /// [`Mesh::raytracing`],
/// 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`]. /// and use [`bevy_mesh::Indices::U32`].
/// ///
/// The material used for this entity must be /// The material used for this entity must be [`MeshMaterial3d<StandardMaterial>`].
/// [`MeshMaterial3d<StandardMaterial>`].
#[derive( #[derive(
Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From, Component, FromTemplate, Clone, Debug, Default, Deref, DerefMut, Reflect, PartialEq, Eq, From,
)] )]
@@ -1,7 +1,6 @@
mod binder; mod binder;
mod extract; mod extract;
mod meshes; mod meshes;
mod tapes; mod tapes;
use bevy_app::{App, Plugin}; use bevy_app::{App, Plugin};
@@ -41,10 +40,8 @@ pub use meshes::types::RaytracingMesh3d;
use tracing::warn; use tracing::warn;
use crate::{ use crate::{
SolariPlugins, SolariPlugins, scene::extract::{
scene::extract::{ extract_raytracing_directional_lights, extract_raytracing_point_lights, extract_raytracing_rect_lights, extract_raytracing_scene_meshes_structural, extract_raytracing_scene_tapes_and_materials, extract_raytracing_scene_tapes_structural, extract_raytracing_spot_lights,
extract_raytracing_scene_meshes_structural, extract_raytracing_scene_tapes_and_materials,
extract_raytracing_scene_tapes_structural,
}, },
}; };
@@ -94,6 +91,10 @@ impl Plugin for RaytracingScenePlugin {
extract_raytracing_scene_meshes_and_materials, extract_raytracing_scene_meshes_and_materials,
extract_raytracing_scene_tapes_and_materials, extract_raytracing_scene_tapes_and_materials,
extract_raytracing_material_assets, extract_raytracing_material_assets,
extract_raytracing_directional_lights,
extract_raytracing_point_lights,
extract_raytracing_spot_lights,
extract_raytracing_rect_lights,
extract_raytracing_environment_map_light, extract_raytracing_environment_map_light,
), ),
) )
@@ -1,7 +1,7 @@
import bevy_pbr::render::pbr_lighting::D_GGX; import bevy_pbr::render::pbr_lighting::D_GGX;
import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u}; import bevy_pbr::render::utils::{rand_vec2f, rand_u, rand_range_u, sample_uniform_sphere};
import bevy_render::maths::{PI_2, orthonormalize}; import bevy_render::maths::{PI_2, orthonormalize};
import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, LIGHT_SOURCE_KIND_DIRECTIONAL, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD}; import package::scene::bindings::{trace_ray, trace_ray_previous_frame, RAY_T_MIN, RAY_T_MAX, light_sources, directional_lights, point_lights, rect_lights, environment_map, environment_map_sampler, environment_map_light, LightSource, light_source_kind, emissive_mesh_triangle_count, LIGHT_SOURCE_KIND_EMISSIVE_MESH, LIGHT_SOURCE_KIND_DIRECTIONAL, LIGHT_SOURCE_KIND_POINT, LIGHT_SOURCE_KIND_RECT, resolve_triangle_data_full, ResolvedRayHitFull, MIRROR_ROUGHNESS_THRESHOLD};
enable wgpu_ray_query; enable wgpu_ray_query;
@@ -98,11 +98,29 @@ struct LightSample {
seed: u32, seed: u32,
} }
/// A point on (or direction to) a light, resolved independently of any shading point.
///
/// Every kind of light is described by the same data, and shaded by the same formula in
/// `calculate_resolved_light_contribution`.
struct ResolvedLightSample { struct ResolvedLightSample {
/// If w = 1, the sample is a point on a light. If w = 0, it's a direction towards a light.
world_position: vec4<f32>, world_position: vec4<f32>,
/// The emitting surface's normal. Unused when `emission_cosine_exponent` is 0.
world_normal: vec3<f32>, world_normal: vec3<f32>,
radiance: vec3<f32>, radiance: vec3<f32>,
/// inverse_pdf may not be in solid angle measure (e.g. area measure)
inverse_pdf: f32, inverse_pdf: f32,
/// Axis of the emission cone, see `emission_cone_attenuation`.
emission_axis: vec3<f32>,
/// Cosines of the emission cone's inner and outer angles. `cos_outer <= -1` means no cone.
cone_cos_inner: f32,
cone_cos_outer: f32,
/// 1 if emission falls off with the cosine of the angle to `world_normal`, e.g. emissive triangles, rect lights, and sphere lights.
/// 0 if emission is the same in every direction, e.g. point and spot lights with no radius.
emission_cosine_exponent: f32,
/// Whether rays can hit this light, needed for MIS between NEE and BRDF sampling.
/// Only emissive meshes can be hit. Analytic lights (directional, point, spot, rect) can only be found via NEE.
brdf_rays_can_hit: bool,
} }
struct LightContribution { struct LightContribution {
@@ -110,7 +128,8 @@ struct LightContribution {
inverse_pdf: f32, inverse_pdf: f32,
/// inverse_pdf may not be in solid angle measure (e.g. area measure) /// inverse_pdf may not be in solid angle measure (e.g. area measure)
/// but inverse_solid_angle_pdf is always in solid angle measure /// but inverse_solid_angle_pdf is always in solid angle measure
/// for cases where it's required, e.g. MIS between light sampling techniques /// for cases where it's required, e.g. MIS between light sampling techniques.
/// Only meaningful when `brdf_rays_can_hit` is true.
inverse_solid_angle_pdf: f32, inverse_solid_angle_pdf: f32,
wi: vec3<f32>, wi: vec3<f32>,
brdf_rays_can_hit: bool, brdf_rays_can_hit: bool,
@@ -151,9 +170,8 @@ fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightS
let light_source = light_sources[light_id]; let light_source = light_sources[light_id];
var triangle_id = 0u; var triangle_id = 0u;
if light_source.kind != LIGHT_SOURCE_KIND_DIRECTIONAL { if light_source_kind(light_source) == LIGHT_SOURCE_KIND_EMISSIVE_MESH {
let triangle_count = light_source.kind >> 1u; triangle_id = rand_range_u(emissive_mesh_triangle_count(light_source), rng);
triangle_id = rand_range_u(triangle_count, rng);
} }
let seed = rand_u(rng); let seed = rand_u(rng);
@@ -166,7 +184,8 @@ fn generate_random_light_sample(rng: ptr<function, u32>) -> GenerateRandomLightS
} }
fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) -> ResolvedLightSample { fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) -> ResolvedLightSample {
if light_source.kind == LIGHT_SOURCE_KIND_DIRECTIONAL { let kind = light_source_kind(light_source);
if kind == LIGHT_SOURCE_KIND_DIRECTIONAL {
let directional_light = directional_lights[light_source.id]; let directional_light = directional_lights[light_source.id];
var direction_to_light: vec3<f32>; var direction_to_light: vec3<f32>;
@@ -189,13 +208,66 @@ fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) ->
} }
return ResolvedLightSample( return ResolvedLightSample(
vec4(direction_to_light, 0.0), vec4(direction_to_light, 0.0),
-direction_to_light, -direction_to_light,
directional_light.luminance, directional_light.luminance,
directional_light.inverse_pdf, directional_light.inverse_pdf,
); -direction_to_light,
} else { NO_EMISSION_CONE,
let triangle_count = light_source.kind >> 1u; NO_EMISSION_CONE,
1.0,
false,
);
} else if kind == LIGHT_SOURCE_KIND_POINT {
let point_light = point_lights[light_source.id];
if point_light.radius == 0.0 {
return ResolvedLightSample(
vec4(point_light.position, 1.0),
point_light.axis,
point_light.intensity,
1.0,
point_light.axis,
point_light.cos_inner,
point_light.cos_outer,
0.0,
false,
);
}
var rng = light_sample.seed;
let sphere_normal = sample_uniform_sphere(&rng);
return ResolvedLightSample(
vec4(point_light.position + point_light.radius * sphere_normal, 1.0),
sphere_normal,
4.0 * point_light.intensity,
1.0,
point_light.axis,
point_light.cos_inner,
point_light.cos_outer,
1.0,
false,
);
} else if kind == LIGHT_SOURCE_KIND_RECT {
let rect_light = rect_lights[light_source.id];
var rng = light_sample.seed;
let uv = rand_vec2f(&rng) - 0.5;
let world_normal = normalize(cross(rect_light.edge_y, rect_light.edge_x));
return ResolvedLightSample(
vec4(rect_light.center + uv.x * rect_light.edge_x + uv.y * rect_light.edge_y, 1.0),
world_normal,
rect_light.radiance,
rect_light.area,
world_normal,
NO_EMISSION_CONE,
NO_EMISSION_CONE,
1.0,
false,
);
} else {
let triangle_count = emissive_mesh_triangle_count(light_source);
let triangle_id = light_sample.light_id & 0xFFFFu; let triangle_id = light_sample.light_id & 0xFFFFu;
let barycentrics = triangle_barycentrics(light_sample.seed); let barycentrics = triangle_barycentrics(light_sample.seed);
let triangle_data = resolve_triangle_data_full(light_source.id, triangle_id, barycentrics); let triangle_data = resolve_triangle_data_full(light_source.id, triangle_id, barycentrics);
@@ -205,10 +277,18 @@ fn resolve_light_sample(light_sample: LightSample, light_source: LightSource) ->
triangle_data.world_normal, triangle_data.world_normal,
triangle_data.material.emissive.rgb, triangle_data.material.emissive.rgb,
f32(triangle_count) * triangle_data.triangle_area, f32(triangle_count) * triangle_data.triangle_area,
triangle_data.world_normal,
NO_EMISSION_CONE,
NO_EMISSION_CONE,
1.0,
true,
); );
} }
} }
/// Shades every kind of light with the same formula:
///
/// `radiance * saturate(dot(-wi, world_normal))^emission_cosine_exponent * cone(dot(-wi, emission_axis)) / d^2`
fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSample, ray_origin: vec3<f32>, origin_world_normal: vec3<f32>) -> LightContribution { fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSample, ray_origin: vec3<f32>, origin_world_normal: vec3<f32>) -> LightContribution {
let ray = resolved_light_sample.world_position.xyz - (resolved_light_sample.world_position.w * ray_origin); let ray = resolved_light_sample.world_position.xyz - (resolved_light_sample.world_position.w * ray_origin);
let light_distance = length(ray); let light_distance = length(ray);
@@ -216,12 +296,24 @@ fn calculate_resolved_light_contribution(resolved_light_sample: ResolvedLightSam
let cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal)); let cos_theta_light = saturate(dot(-wi, resolved_light_sample.world_normal));
let light_distance_squared = light_distance * light_distance; let light_distance_squared = light_distance * light_distance;
let denominator = cos_theta_light / light_distance_squared;
let radiance = resolved_light_sample.radiance * denominator; var emission = select(1.0, cos_theta_light, resolved_light_sample.emission_cosine_exponent == 1.0);
let inverse_solid_angle_pdf = resolved_light_sample.inverse_pdf * denominator; emission *= emission_cone_attenuation(dot(-wi, resolved_light_sample.emission_axis), resolved_light_sample.cone_cos_inner, resolved_light_sample.cone_cos_outer);
return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, resolved_light_sample.world_position.w == 1.0); let radiance = resolved_light_sample.radiance * (emission / light_distance_squared);
let inverse_solid_angle_pdf = resolved_light_sample.inverse_pdf * (cos_theta_light / light_distance_squared);
return LightContribution(radiance, resolved_light_sample.inverse_pdf, inverse_solid_angle_pdf, wi, resolved_light_sample.brdf_rays_can_hit);
}
const NO_EMISSION_CONE = -1.0;
fn emission_cone_attenuation(cos_theta: f32, cos_inner: f32, cos_outer: f32) -> f32 {
if cos_outer <= NO_EMISSION_CONE { return 1.0; }
let scale = 1.0 / max(cos_inner - cos_outer, 1e-4);
let attenuation = saturate((cos_theta - cos_outer) * scale);
return attenuation * attenuation;
} }
fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 { fn trace_visibility(ray_origin: vec3<f32>, point: vec4<f32>) -> f32 {
@@ -5,6 +5,7 @@ use bevy_ecs::{
resource::Resource, resource::Resource,
system::{Res, ResMut}, system::{Res, ResMut},
}; };
use bevy_mesh::MeshRaytracingFlags;
use bevy_platform::collections::HashMap; use bevy_platform::collections::HashMap;
use bevy_render::{ use bevy_render::{
diagnostic::{DiagnosticsRecorder, RecordDiagnostics}, diagnostic::{DiagnosticsRecorder, RecordDiagnostics},
@@ -28,7 +29,7 @@ const TLAS_BUILDS_BEFORE_DELETION_ALLOWED: usize = 2;
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct BlasManager { pub struct BlasManager {
blas: HashMap<AssetId<Tape>, Blas>, blas: HashMap<AssetId<Tape>, TapeBlas>,
changed: Vec<AssetId<Tape>>, changed: Vec<AssetId<Tape>>,
/// BLAS that are pending deletion, one batch per TLAS build. The back batch /// BLAS that are pending deletion, one batch per TLAS build. The back batch
/// collects retirements since the last build, and every batch ahead of /// collects retirements since the last build, and every batch ahead of
@@ -37,12 +38,24 @@ pub struct BlasManager {
} }
impl BlasManager { impl BlasManager {
pub fn get(&self, tape: &AssetId<Tape>) -> Option<&Blas> { pub fn get(&self, key: &BlasKey) -> Option<&Blas> {
self.blas.get(tape) self.blas.get(&key.tape)?.get(key.opacity)
} }
pub fn device_address(&self, tape: &AssetId<Tape>) -> Option<u64> { pub fn device_address(&self, key: &BlasKey) -> Option<u64> {
self.blas.get(tape)?.handle() self.get(key)?.handle()
}
/// If a tape 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.tape)
.is_some_and(|tape| !tape.requires.contains(key.opacity.flag()))
}
fn require(&mut self, tape: AssetId<Tape>, flags: MeshRaytracingFlags) {
self.blas.entry(tape).or_default().requires = flags;
} }
pub fn changed_tapes(&self) -> &[AssetId<Tape>] { pub fn changed_tapes(&self) -> &[AssetId<Tape>] {
@@ -55,19 +68,22 @@ impl BlasManager {
} }
} }
fn insert(&mut self, tape: AssetId<Tape>, blas: Blas) { fn insert(&mut self, key: BlasKey, blas: Blas) {
if let Some(old) = self.blas.insert(tape, blas) { let slot = self.blas.entry(key.tape).or_default().slot_mut(key.opacity);
if let Some(old) = slot.replace(blas) {
self.retire(old); self.retire(old);
} }
self.changed.push(tape); self.changed.push(key.tape);
} }
fn remove(&mut self, tape: AssetId<Tape>) { fn remove_tape(&mut self, tape: AssetId<Tape>) {
self.changed.push(tape); self.changed.push(tape);
if let Some(removed) = self.blas.remove(&tape) { if let Some(removed) = self.blas.remove(&tape) {
self.retire(removed); for blas in removed.into_iter() {
self.retire(blas);
}
} }
} }
@@ -79,6 +95,76 @@ impl BlasManager {
} }
} }
struct TapeBlas {
requires: MeshRaytracingFlags,
opaque: Option<Blas>,
non_opaque: Option<Blas>,
}
impl Default for TapeBlas {
fn default() -> Self {
Self {
requires: MeshRaytracingFlags::empty(),
opaque: None,
non_opaque: None,
}
}
}
impl TapeBlas {
fn get(&self, opacity: BlasOpacity) -> Option<&Blas> {
match opacity {
BlasOpacity::Opaque => self.opaque.as_ref(),
BlasOpacity::NonOpaque => self.non_opaque.as_ref(),
}
}
fn slot_mut(&mut self, opacity: BlasOpacity) -> &mut Option<Blas> {
match opacity {
BlasOpacity::Opaque => &mut self.opaque,
BlasOpacity::NonOpaque => &mut self.non_opaque,
}
}
fn into_iter(self) -> impl Iterator<Item = Blas> {
self.opaque.into_iter().chain(self.non_opaque)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BlasKey {
pub tape: AssetId<Tape>,
pub opacity: BlasOpacity,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum BlasOpacity {
Opaque,
NonOpaque,
}
impl BlasOpacity {
fn declared(flags: MeshRaytracingFlags) -> impl Iterator<Item = Self> {
[Self::Opaque, Self::NonOpaque]
.into_iter()
.filter(move |opacity: &BlasOpacity| flags.contains(opacity.flag()))
}
pub fn flag(self) -> MeshRaytracingFlags {
match self {
Self::Opaque => MeshRaytracingFlags::OPAQUE,
Self::NonOpaque => MeshRaytracingFlags::NON_OPAQUE,
}
}
fn geometry_flags(self) -> AccelerationStructureGeometryFlags {
match self {
Self::Opaque => AccelerationStructureGeometryFlags::OPAQUE,
Self::NonOpaque => AccelerationStructureGeometryFlags::empty(),
}
}
}
pub fn prepare_raytracing_blas( pub fn prepare_raytracing_blas(
mut blas_manager: ResMut<BlasManager>, mut blas_manager: ResMut<BlasManager>,
extracted_tapes: Res<ExtractedAssets<RenderTape>>, extracted_tapes: Res<ExtractedAssets<RenderTape>>,
@@ -95,33 +181,44 @@ pub fn prepare_raytracing_blas(
.iter() .iter()
.chain(extracted_tapes.modified.iter()) .chain(extracted_tapes.modified.iter())
{ {
blas_manager.remove(*asset_id); blas_manager.remove_tape(*asset_id);
} }
if extracted_tapes.extracted.is_empty() { if extracted_tapes.extracted.is_empty() {
return; return;
} }
// Create new BLAS for added or changed tapes // Record which BLAS added or changed tapes declare, even if none
for (asset_id, tape) in &extracted_tapes.extracted {
blas_manager.require(*asset_id, tape.raytracing);
}
// Create a BLAS for each opacity that added or changed tapes declare
let blas_resources = extracted_tapes let blas_resources = extracted_tapes
.extracted .extracted
.iter() .iter()
.map(|(asset_id, _)| { .flat_map(|(asset_id, tape)| {
bevy_log::info!("Tape {}: Getting the aabb slice", asset_id); BlasOpacity::declared(tape.raytracing).map(|opacity| BlasKey {
let aabbs_slice = tape_allocator.tape_aabb_slice(asset_id).unwrap(); tape: *asset_id,
opacity,
})
})
.map(|key| {
bevy_log::info!("Tape {}: Getting the aabb slice", &key.tape);
let aabbs_slice = tape_allocator.tape_aabb_slice(&key.tape).unwrap();
let (blas, blas_size) = allocate_blas(&aabbs_slice, asset_id, &render_device); let (blas, blas_size) = allocate_blas(&aabbs_slice, key, &render_device);
blas_manager.insert(*asset_id, blas); blas_manager.insert(key, blas);
(*asset_id, aabbs_slice, blas_size) (key, aabbs_slice, blas_size)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Build geometry into each BLAS // Build geometry into each BLAS
let build_entries = blas_resources let build_entries = blas_resources
.iter() .iter()
.map(|(asset_id, aabbs_slice, blas_size)| { .map(|(key, aabbs_slice, blas_size)| {
let geometry = BlasAabbGeometry { let geometry = BlasAabbGeometry {
size: blas_size, size: blas_size,
stride: size_of::<bevy_tape_load::render::Aabb>() as u64, stride: size_of::<bevy_tape_load::render::Aabb>() as u64,
@@ -129,7 +226,7 @@ pub fn prepare_raytracing_blas(
primitive_offset: aabbs_slice.range.start, primitive_offset: aabbs_slice.range.start,
}; };
BlasBuildEntry { BlasBuildEntry {
blas: &blas_manager.blas[asset_id], blas: blas_manager.get(key).unwrap(),
geometry: BlasGeometries::AabbGeometries(vec![geometry]), geometry: BlasGeometries::AabbGeometries(vec![geometry]),
} }
}) })
@@ -167,19 +264,19 @@ pub fn delete_raytracing_blas(
fn allocate_blas( fn allocate_blas(
aabbs_slice: &TapeBufferSlice, aabbs_slice: &TapeBufferSlice,
asset_id: &AssetId<Tape>, key: BlasKey,
render_device: &RenderDevice, render_device: &RenderDevice,
) -> (Blas, BlasAABBGeometrySizeDescriptor) { ) -> (Blas, BlasAABBGeometrySizeDescriptor) {
let blas_size = BlasAABBGeometrySizeDescriptor { let blas_size = BlasAABBGeometrySizeDescriptor {
primitive_count: aabbs_slice.range.len() as u32, primitive_count: aabbs_slice.range.len() as u32,
flags: AccelerationStructureGeometryFlags::OPAQUE, flags: key.opacity.geometry_flags(),
}; };
// TODO: If we ever introduce BLAS refits, we need to be aware of the 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 // double-buffer to avoid invalidating the previous frame TLAS
let blas = render_device.wgpu_device().create_blas( let blas = render_device.wgpu_device().create_blas(
&CreateBlasDescriptor { &CreateBlasDescriptor {
label: Some(&asset_id.to_string()), label: Some(&format!("{} {:?}", key.tape, key.opacity)),
flags: AccelerationStructureFlags::PREFER_FAST_TRACE flags: AccelerationStructureFlags::PREFER_FAST_TRACE
| AccelerationStructureFlags::ALLOW_COMPACTION, | AccelerationStructureFlags::ALLOW_COMPACTION,
update_mode: AccelerationStructureUpdateMode::Build, update_mode: AccelerationStructureUpdateMode::Build,
+3
View File
@@ -1,6 +1,7 @@
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use bevy_asset::Asset; use bevy_asset::Asset;
use bevy_mesh::MeshRaytracingFlags;
use bevy_reflect::Reflect; use bevy_reflect::Reflect;
use bevy_shader::Shader; use bevy_shader::Shader;
use bevy_shape::Aabb3d; use bevy_shape::Aabb3d;
@@ -12,6 +13,7 @@ use crate::{render::Aabb, ssa::*};
#[derive(Asset, Clone, Debug, Reflect, PartialEq, Hash)] #[derive(Asset, Clone, Debug, Reflect, PartialEq, Hash)]
#[reflect(Clone)] #[reflect(Clone)]
pub struct Tape { pub struct Tape {
pub raytracing: MeshRaytracingFlags,
pub parts: SSATape, pub parts: SSATape,
pub seed: u64, pub seed: u64,
pub subdivision: u32, pub subdivision: u32,
@@ -20,6 +22,7 @@ pub struct Tape {
impl Default for Tape { impl Default for Tape {
fn default() -> Self { fn default() -> Self {
Self { Self {
raytracing: MeshRaytracingFlags::OPAQUE,
parts: Default::default(), parts: Default::default(),
seed: 0, seed: 0,
subdivision: 8, subdivision: 8,
+23 -22
View File
@@ -17,7 +17,7 @@ use bevy::{
diagnostic::{Diagnostic, DiagnosticPath, DiagnosticsStore}, diagnostic::{Diagnostic, DiagnosticPath, DiagnosticsStore},
gltf::GltfMaterialName, gltf::GltfMaterialName,
image::{ImageAddressMode, ImageLoaderSettings}, image::{ImageAddressMode, ImageLoaderSettings},
mesh::{Indices, VertexAttributeValues}, mesh::{Indices, MeshRaytracingFlags, VertexAttributeValues},
post_process::bloom::Bloom, post_process::bloom::Bloom,
prelude::*, prelude::*,
render::{diagnostic::RenderDiagnosticsPlugin, render_resource::TextureUsages}, render::{diagnostic::RenderDiagnosticsPlugin, render_resource::TextureUsages},
@@ -317,6 +317,28 @@ fn setup_pica_pica(
)), )),
)); ));
let csg = create_csg(0);
let tape = Tape {
raytracing: MeshRaytracingFlags::OPAQUE,
parts: csg,
seed: 0,
subdivision: 8,
};
let loaded_tape = asset_server.add(tape);
let tape_material = StandardMaterial {
base_color: RED.into(),
..Default::default()
};
let loaded_material = asset_server.add(tape_material);
commands.spawn((
Tape3d(loaded_tape),
MeshMaterial3d(loaded_material),
Transform::default(),
));
let mut camera = commands.spawn(( let mut camera = commands.spawn((
Camera3d::default(), Camera3d::default(),
Camera { Camera {
@@ -378,27 +400,6 @@ fn setup_pica_pica(
}, },
)], )],
)); ));
let csg = create_csg(0);
let tape = Tape {
parts: csg,
seed: 0,
subdivision: 8,
};
let loaded_tape = asset_server.add(tape);
let tape_material = StandardMaterial {
base_color: RED.into(),
..Default::default()
};
let loaded_material = asset_server.add(tape_material);
commands.spawn((
Tape3d(loaded_tape),
MeshMaterial3d(loaded_material),
Transform::default(),
));
} }
fn setup_many_lights( fn setup_many_lights(