Initial project import
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-05 21:44:45 -04:00
commit f29712d158
259 files changed
+52069

No files matched your search

@@ -0,0 +1,31 @@
//! Bevy auto exposure plugin and GPU capability probe.
use bevy::post_process::auto_exposure::{AutoExposure, AutoExposurePlugin};
use bevy::prelude::*;
use bevy::render::render_resource::DownlevelFlags;
use bevy::render::renderer::RenderAdapter;
pub struct AutoExposureRenderingPlugin;
impl Plugin for AutoExposureRenderingPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(AutoExposurePlugin);
}
}
/// Returns whether the GPU supports Bevy's histogram auto exposure (compute shaders).
pub fn probe_auto_exposure_support(render_adapter: &RenderAdapter) -> bool {
render_adapter
.get_downlevel_capabilities()
.flags
.contains(DownlevelFlags::COMPUTE_SHADERS)
}
/// Builds an [`AutoExposure`] component from the resolved render profile.
pub fn auto_exposure_from_profile(profile: &settings::ActiveCameraRenderProfile) -> AutoExposure {
AutoExposure {
speed_brighten: profile.auto_exposure_speed_brighten,
speed_darken: profile.auto_exposure_speed_darken,
..default()
}
}
+413
View File
@@ -0,0 +1,413 @@
//! Assembles the high-fidelity rendering stack on project cameras.
use bevy::anti_alias::taa::TemporalAntiAliasing;
use bevy::camera::Exposure;
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::pbr::{Atmosphere, AtmosphereSettings, ScatteringMedium, ScreenSpaceAmbientOcclusion};
use bevy::post_process::auto_exposure::AutoExposure;
use bevy::post_process::bloom::Bloom;
use bevy::prelude::*;
use bevy::render::view::Hdr;
use settings::{
effective_auto_exposure, ActiveCameraRenderProfile, GiPath, ProjectRenderCamera,
ProjectSettings, RenderingCapabilities, RenderingSettings,
};
use super::auto_exposure::auto_exposure_from_profile;
use sim::PlayerCamera;
use super::fullscreen_effects::{strip_fullscreen_effects, sync_fullscreen_effect};
use super::solari::{strip_gi_path, sync_gi_path, SolariRaytracingSceneStats};
use super::viewport_camera::effective_viewport_gi_path;
/// Environment variable name for HDR override (matches game launch).
pub const HDR_ENV_VAR: &str = "BEVY_FPS_HDR";
fn hdr_enabled_from_env() -> bool {
std::env::var(HDR_ENV_VAR)
.map(|value| {
!matches!(
value.trim().to_ascii_lowercase().as_str(),
"0" | "false" | "off" | "no"
)
})
.unwrap_or(true)
}
/// True when the camera should run auto exposure this frame (mode, HDR pass, compute).
pub fn camera_auto_exposure_active(
profile: &ActiveCameraRenderProfile,
caps: &RenderingCapabilities,
) -> bool {
effective_auto_exposure(profile, caps) && hdr_enabled_profile(profile)
}
/// Whether the HDR render pass is active for this profile (respects `BEVY_FPS_HDR`).
pub fn hdr_enabled_profile(profile: &ActiveCameraRenderProfile) -> bool {
if std::env::var(HDR_ENV_VAR).is_ok() {
hdr_enabled_from_env()
} else {
profile.hdr
}
}
/// True when the camera render target must be HDR for either authored HDR or Solari storage writes.
pub fn hdr_required_for_effective_gi(
profile: &ActiveCameraRenderProfile,
effective_gi: GiPath,
) -> bool {
hdr_required_for_render_stack(hdr_enabled_profile(profile), effective_gi)
}
pub fn hdr_required_for_render_stack(hdr_enabled: bool, effective_gi: GiPath) -> bool {
hdr_enabled || effective_gi == GiPath::SolariDeferred
}
/// Applies the shared project rendering profile to all [`ProjectRenderCamera`] entities.
#[unsafe(no_mangle)]
pub fn setup_project_camera_effects(
mut commands: Commands,
mut mediums: ResMut<Assets<ScatteringMedium>>,
settings: Res<ProjectSettings>,
profile: Option<Res<ActiveCameraRenderProfile>>,
caps: Option<Res<RenderingCapabilities>>,
solari_stats: Option<Res<SolariRaytracingSceneStats>>,
cameras: Query<Entity, With<ProjectRenderCamera>>,
points: Query<&PointLight>,
spots: Query<&SpotLight>,
) {
let default_caps = RenderingCapabilities::default();
let gi_caps = caps.as_deref().unwrap_or(&default_caps);
let active = profile.map(|p| p.clone()).unwrap_or_else(|| {
settings::ActiveCameraRenderProfile::from_project(
&settings.rendering,
settings::resolve_gi_path(settings.rendering.gi_mode, gi_caps),
)
});
let has_local_shadow_lights = super::viewport_camera::has_local_shadow_lights(&points, &spots);
for entity in &cameras {
apply_camera_render_profile(
&mut commands,
entity,
&active,
gi_caps,
solari_stats.as_deref(),
&mut mediums,
has_local_shadow_lights,
);
}
}
/// Inserts or removes manual [`Exposure`] vs [`AutoExposure`] for the active profile.
pub fn sync_exposure(
commands: &mut Commands,
entity: Entity,
profile: &ActiveCameraRenderProfile,
caps: &RenderingCapabilities,
) {
if camera_auto_exposure_active(profile, caps) {
commands
.entity(entity)
.remove::<Exposure>()
.insert(auto_exposure_from_profile(profile));
} else {
commands
.entity(entity)
.remove::<AutoExposure>()
.insert(Exposure {
ev100: profile.exposure_ev100,
});
}
}
/// Inserts post-processing on a camera entity from a resolved render profile.
pub fn apply_camera_render_profile(
commands: &mut Commands,
entity: Entity,
profile: &ActiveCameraRenderProfile,
caps: &RenderingCapabilities,
solari_stats: Option<&SolariRaytracingSceneStats>,
mediums: &mut Assets<ScatteringMedium>,
has_local_shadow_lights: bool,
) {
commands.entity(entity).insert(Msaa::Off);
let effective_gi =
effective_viewport_gi_path(profile.gi_path, caps, solari_stats, has_local_shadow_lights);
sync_exposure(commands, entity, profile, caps);
commands.entity(entity).insert(DistanceFog {
color: Color::srgb(
profile.fog_color[0],
profile.fog_color[1],
profile.fog_color[2],
),
falloff: FogFalloff::Exponential {
density: profile.fog_density,
},
..default()
});
if profile.atmosphere {
let medium = mediums.add(ScatteringMedium::default());
commands
.entity(entity)
.insert(Atmosphere::earthlike(medium));
commands
.entity(entity)
.insert(AtmosphereSettings::default());
}
if profile.tonemapping_aces {
commands.entity(entity).insert(Tonemapping::AcesFitted);
}
if profile.bloom {
commands.entity(entity).insert(Bloom::NATURAL);
}
if profile.ssao {
commands
.entity(entity)
.insert(ScreenSpaceAmbientOcclusion::default());
}
if profile.taa {
commands
.entity(entity)
.insert(TemporalAntiAliasing::default());
}
if hdr_required_for_effective_gi(profile, effective_gi) {
commands.entity(entity).insert(Hdr);
}
sync_gi_path(commands, entity, effective_gi);
sync_fullscreen_effect(commands, entity, profile.fullscreen_effect.as_deref());
}
/// Legacy entry: applies project settings directly (no volume blend).
pub fn apply_project_camera_fx(
commands: &mut Commands,
entity: Entity,
rendering: &RenderingSettings,
mediums: &mut Assets<ScatteringMedium>,
) {
let profile = ActiveCameraRenderProfile::from_project(rendering, settings::GiPath::Forward);
apply_camera_render_profile(
commands,
entity,
&profile,
&RenderingCapabilities::default(),
None,
mediums,
false,
);
}
/// Removes the high-cost post-processing stack from a camera entity.
pub fn strip_project_camera_fx(commands: &mut Commands, entity: Entity) {
strip_fullscreen_effects(commands, entity);
strip_gi_path(commands, entity);
commands
.entity(entity)
.remove::<ProjectRenderCamera>()
.remove::<Atmosphere>()
.remove::<AtmosphereSettings>()
.remove::<TemporalAntiAliasing>()
.remove::<ScreenSpaceAmbientOcclusion>()
.remove::<Bloom>()
.remove::<Hdr>()
.remove::<Tonemapping>()
.remove::<Exposure>()
.remove::<AutoExposure>()
.remove::<DistanceFog>()
.remove::<Msaa>();
}
/// Marks the player camera for the shared rendering stack.
#[unsafe(no_mangle)]
pub fn tag_player_camera(
mut commands: Commands,
cameras: Query<Entity, (With<PlayerCamera>, Without<ProjectRenderCamera>)>,
) {
for entity in &cameras {
commands.entity(entity).insert(ProjectRenderCamera);
}
}
/// Toggles optional post-processing components without stripping the whole stack.
#[allow(clippy::too_many_arguments)]
pub fn sync_optional_rendering_fx(
commands: &mut Commands,
entity: Entity,
profile: &ActiveCameraRenderProfile,
caps: &RenderingCapabilities,
solari_stats: Option<&SolariRaytracingSceneStats>,
mediums: &mut Assets<ScatteringMedium>,
has_atmosphere: bool,
has_tonemapping: bool,
has_bloom: bool,
has_ssao: bool,
has_taa: bool,
has_hdr: bool,
has_auto_exposure: bool,
has_local_shadow_lights: bool,
) {
let effective_gi =
effective_viewport_gi_path(profile.gi_path, caps, solari_stats, has_local_shadow_lights);
if profile.atmosphere && !has_atmosphere {
let medium = mediums.add(ScatteringMedium::default());
commands
.entity(entity)
.insert(Atmosphere::earthlike(medium));
commands
.entity(entity)
.insert(AtmosphereSettings::default());
} else if !profile.atmosphere && has_atmosphere {
commands
.entity(entity)
.remove::<Atmosphere>()
.remove::<AtmosphereSettings>();
}
if profile.tonemapping_aces && !has_tonemapping {
commands.entity(entity).insert(Tonemapping::AcesFitted);
} else if !profile.tonemapping_aces && has_tonemapping {
commands.entity(entity).remove::<Tonemapping>();
}
if profile.bloom && !has_bloom {
commands.entity(entity).insert(Bloom::NATURAL);
} else if !profile.bloom && has_bloom {
commands.entity(entity).remove::<Bloom>();
}
if profile.ssao && !has_ssao {
commands
.entity(entity)
.insert(ScreenSpaceAmbientOcclusion::default());
} else if !profile.ssao && has_ssao {
commands
.entity(entity)
.remove::<ScreenSpaceAmbientOcclusion>();
}
if profile.taa && !has_taa {
commands
.entity(entity)
.insert(TemporalAntiAliasing::default());
} else if !profile.taa && has_taa {
commands.entity(entity).remove::<TemporalAntiAliasing>();
}
let wants_hdr = hdr_required_for_effective_gi(profile, effective_gi);
if wants_hdr && !has_hdr {
commands.entity(entity).insert(Hdr);
} else if !wants_hdr && has_hdr {
commands.entity(entity).remove::<Hdr>();
}
let wants_auto = camera_auto_exposure_active(profile, caps);
if wants_auto != has_auto_exposure {
sync_exposure(commands, entity, profile, caps);
} else if wants_auto {
commands
.entity(entity)
.insert(auto_exposure_from_profile(profile));
} else {
commands.entity(entity).insert(Exposure {
ev100: profile.exposure_ev100,
});
}
sync_gi_path(commands, entity, effective_gi);
sync_fullscreen_effect(commands, entity, profile.fullscreen_effect.as_deref());
}
/// Patches exposure/fog/HDR when the active profile changes at runtime.
pub fn patch_camera_effects(
profile: &ActiveCameraRenderProfile,
caps: &RenderingCapabilities,
solari_stats: Option<&SolariRaytracingSceneStats>,
has_local_shadow_lights: bool,
commands: &mut Commands,
cameras: impl IntoIterator<Item = Entity>,
) {
for entity in cameras {
let effective_gi = effective_viewport_gi_path(
profile.gi_path,
caps,
solari_stats,
has_local_shadow_lights,
);
sync_exposure(commands, entity, profile, caps);
commands.entity(entity).insert(DistanceFog {
color: Color::srgb(
profile.fog_color[0],
profile.fog_color[1],
profile.fog_color[2],
),
falloff: FogFalloff::Exponential {
density: profile.fog_density,
},
..default()
});
if hdr_required_for_effective_gi(profile, effective_gi) {
commands.entity(entity).insert(Hdr);
} else {
commands.entity(entity).remove::<Hdr>();
}
sync_gi_path(commands, entity, effective_gi);
sync_fullscreen_effect(commands, entity, profile.fullscreen_effect.as_deref());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn solari_forces_hdr_render_target() {
assert!(hdr_required_for_render_stack(false, GiPath::SolariDeferred));
assert!(hdr_required_for_render_stack(true, GiPath::Forward));
assert!(!hdr_required_for_render_stack(false, GiPath::Forward));
}
}
/// Re-applies player camera FX tags after a hot reload.
pub fn refresh_player_camera_fx(world: &mut World) {
let Some(settings) = world.get_resource::<ProjectSettings>().cloned() else {
return;
};
let profile = world
.get_resource::<ActiveCameraRenderProfile>()
.cloned()
.unwrap_or_else(|| {
ActiveCameraRenderProfile::from_project(&settings.rendering, settings::GiPath::Forward)
});
let solari_stats = world.get_resource::<SolariRaytracingSceneStats>().copied();
let caps = world
.get_resource::<RenderingCapabilities>()
.cloned()
.unwrap_or_default();
let has_local_shadow_lights = super::viewport_camera::world_has_local_shadow_lights(world);
let cameras: Vec<Entity> = world
.query_filtered::<Entity, With<PlayerCamera>>()
.iter(world)
.collect();
for entity in &cameras {
if world.get::<ProjectRenderCamera>(*entity).is_none() {
world.commands().entity(*entity).insert(ProjectRenderCamera);
}
}
world.resource_scope(|world, mut mediums: Mut<Assets<ScatteringMedium>>| {
for entity in cameras {
apply_camera_render_profile(
&mut world.commands(),
entity,
&profile,
&caps,
solari_stats.as_ref(),
&mut mediums,
has_local_shadow_lights,
);
}
});
}
@@ -0,0 +1,116 @@
//! Fullscreen post-process effects driven by volume assets.
use bevy::prelude::*;
use bevy::render::extract_component::ExtractComponent;
use bevy::render::render_graph::{InternedRenderLabel, RenderLabel, RenderSubGraph};
use bevy::render::render_resource::ShaderType;
use bevy::shader::ShaderRef;
use bevy_core_pipeline::core_3d::graph::{Core3d, Node3d};
use bevy_core_pipeline::fullscreen_material::{FullscreenMaterial, FullscreenMaterialPlugin};
use shared::{PostProcessEffectAsset, PostProcessEffectKind};
/// Vignette fullscreen pass.
#[derive(Component, Clone, Copy, Default, ExtractComponent, ShaderType)]
pub struct VignetteFx {
pub intensity: f32,
pub radius: f32,
}
impl FullscreenMaterial for VignetteFx {
fn fragment_shader() -> ShaderRef {
"post_fx/vignette.wgsl".into()
}
fn node_edges() -> Vec<InternedRenderLabel> {
vec![
Node3d::Tonemapping.intern(),
Self::node_label().intern(),
Node3d::EndMainPassPostProcessing.intern(),
]
}
fn sub_graph() -> Option<bevy::render::render_graph::InternedRenderSubGraph> {
Some(Core3d.intern())
}
}
/// Chromatic aberration fullscreen pass.
#[derive(Component, Clone, Copy, Default, ExtractComponent, ShaderType)]
pub struct ChromaticAberrationFx {
pub intensity: f32,
pub radius: f32,
}
impl FullscreenMaterial for ChromaticAberrationFx {
fn fragment_shader() -> ShaderRef {
"post_fx/chromatic_aberration.wgsl".into()
}
fn node_edges() -> Vec<InternedRenderLabel> {
vec![
Node3d::Tonemapping.intern(),
Self::node_label().intern(),
Node3d::EndMainPassPostProcessing.intern(),
]
}
fn sub_graph() -> Option<bevy::render::render_graph::InternedRenderSubGraph> {
Some(Core3d.intern())
}
}
pub struct FullscreenEffectsPlugin;
impl Plugin for FullscreenEffectsPlugin {
fn build(&self, app: &mut App) {
app.add_plugins((
FullscreenMaterialPlugin::<VignetteFx>::default(),
FullscreenMaterialPlugin::<ChromaticAberrationFx>::default(),
));
}
}
fn load_effect(path: &str) -> Option<PostProcessEffectAsset> {
let catalog = if path.starts_with("assets/") {
path.to_string()
} else {
format!("assets/{path}")
};
PostProcessEffectAsset::load_from_path(&catalog).ok()
}
pub fn sync_fullscreen_effect(commands: &mut Commands, entity: Entity, effect_path: Option<&str>) {
commands
.entity(entity)
.remove::<VignetteFx>()
.remove::<ChromaticAberrationFx>();
let Some(path) = effect_path else {
return;
};
let Some(asset) = load_effect(path) else {
warn!("Could not load post FX asset at {path}");
return;
};
match asset.kind {
PostProcessEffectKind::Vignette => {
commands.entity(entity).insert(VignetteFx {
intensity: asset.intensity,
radius: asset.radius,
});
}
PostProcessEffectKind::ChromaticAberration => {
commands.entity(entity).insert(ChromaticAberrationFx {
intensity: asset.intensity,
radius: asset.radius,
});
}
}
}
pub fn strip_fullscreen_effects(commands: &mut Commands, entity: Entity) {
commands
.entity(entity)
.remove::<VignetteFx>()
.remove::<ChromaticAberrationFx>();
}
+25
View File
@@ -0,0 +1,25 @@
//! High-fidelity rendering setup layered onto project cameras.
mod auto_exposure;
mod camera_fx;
mod fullscreen_effects;
mod solari;
mod viewport_camera;
mod volumes;
pub use auto_exposure::AutoExposureRenderingPlugin;
pub use camera_fx::{
apply_camera_render_profile, apply_project_camera_fx, camera_auto_exposure_active,
hdr_enabled_profile, patch_camera_effects, refresh_player_camera_fx,
setup_project_camera_effects, strip_project_camera_fx, sync_optional_rendering_fx,
tag_player_camera, HDR_ENV_VAR,
};
pub use fullscreen_effects::FullscreenEffectsPlugin;
pub use solari::{effective_gi_path_for_camera, SolariRaytracingSceneStats, SolariRenderingPlugin};
pub use viewport_camera::{
clear_viewport_camera_stack, effective_viewport_gi_path, effective_viewport_render_stack,
has_local_shadow_lights, resolve_viewport_camera_owner, snapshot_viewport_fx,
sync_viewport_camera_stack, world_has_local_shadow_lights, ViewportCameraOwner,
ViewportFxSnapshot, ViewportStackApply,
};
pub use volumes::{resolve_active_camera_render_profile_system, sample_volumes_at};
+564
View File
@@ -0,0 +1,564 @@
//! Solari GI path integration and capability detection.
use bevy::camera::CameraMainTextureUsages;
use bevy::core_pipeline::prepass::{
DeferredPrepass, DeferredPrepassDoubleBuffer, DepthPrepass, DepthPrepassDoubleBuffer,
MotionVectorPrepass,
};
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::pbr::{DefaultOpaqueRendererMethod, ExtractedDirectionalLight};
use bevy::prelude::*;
use bevy::render::render_resource::TextureUsages;
use bevy::render::renderer::{RenderAdapter, RenderDevice};
use bevy::render::{Render, RenderApp, RenderSystems};
use bevy_solari::prelude::{RaytracingMesh3d, SolariLighting};
use bevy_solari::scene::RaytracingSceneBindings;
use bevy_solari::SolariPlugins;
use settings::{GiPath, ProjectSettings, RenderingCapabilities};
use shared::{LevelObject, RaytracingExcluded};
use std::sync::{Arc, Mutex};
#[derive(Resource, Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SolariRaytracingSceneStats {
pub project_meshes: usize,
pub tagged_meshes: usize,
pub excluded_meshes: usize,
pub unsupported_meshes: usize,
pub missing_level_root_meshes: usize,
pub emissive_meshes: usize,
pub compatible_mesh_assets: usize,
pub incompatible_mesh_assets: usize,
pub mesh_assets_missing_tangents: usize,
pub mesh_assets_missing_u32_indices: usize,
pub render_instances: usize,
pub render_directional_lights: usize,
pub render_bind_group_ready: bool,
}
impl SolariRaytracingSceneStats {
pub fn compatible_light_count(&self) -> usize {
self.render_directional_lights + self.emissive_meshes
}
pub fn solari_ready(&self) -> bool {
self.render_bind_group_ready
&& self.render_instances > 0
&& self.compatible_light_count() > 0
}
}
#[derive(Debug, Default, Clone, Copy)]
struct SolariRenderSceneStats {
render_instances: usize,
render_directional_lights: usize,
render_bind_group_ready: bool,
}
#[derive(Resource, Debug, Clone, Default)]
struct SolariRenderSceneReadback(Arc<Mutex<SolariRenderSceneStats>>);
pub struct SolariRenderingPlugin;
impl Plugin for SolariRenderingPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(SolariPlugins)
.init_resource::<RenderingCapabilities>()
.init_resource::<settings::EffectiveRenderStack>()
.init_resource::<SolariRaytracingSceneStats>()
.init_resource::<SolariRenderSceneReadback>()
.init_resource::<settings::ActiveCameraRenderProfile>()
.init_resource::<settings::ActiveVolumeContribution>()
.add_systems(Startup, init_opaque_renderer_method)
.add_systems(
Update,
detect_rendering_capabilities
.run_if(not(resource_exists::<RenderingCapabilitiesDetected>)),
)
.add_systems(
PostUpdate,
(
super::volumes::resolve_active_camera_render_profile_system,
sync_render_solari_scene_readback,
sync_opaque_renderer_method,
sync_auxiliary_camera_deferred_prepass,
sync_hydrated_raytracing_meshes,
)
.chain(),
);
}
fn finish(&self, app: &mut App) {
let readback = app.world().resource::<SolariRenderSceneReadback>().clone();
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app.insert_resource(readback).add_systems(
Render,
write_render_solari_scene_readback
.in_set(RenderSystems::Prepare)
.after(RenderSystems::PrepareBindGroups),
);
}
}
/// Set once GPU features have been probed via [`RenderDevice`].
#[derive(Resource, Default)]
struct RenderingCapabilitiesDetected;
fn detect_rendering_capabilities(
render_device: Option<Res<RenderDevice>>,
render_adapter: Option<Res<RenderAdapter>>,
mut caps: ResMut<RenderingCapabilities>,
mut commands: Commands,
) {
let Some(render_device) = render_device else {
return;
};
let rt_supported = probe_solari_rt_support(&render_device);
caps.rt_supported = rt_supported;
caps.auto_exposure_supported = render_adapter
.as_deref()
.map(super::auto_exposure::probe_auto_exposure_support)
.unwrap_or(false);
caps.requested_gi_path = GiPath::Forward;
caps.effective_gi_path = GiPath::Forward;
caps.active_gi_path = GiPath::Forward;
caps.fallback_reason = None;
if rt_supported {
info!("Rendering: Solari RT features available when GiMode permits");
} else {
warn!("Rendering: Solari RT features unavailable — GiMode::Auto uses forward PBR");
}
if caps.auto_exposure_supported {
info!("Rendering: auto exposure (compute) available");
} else {
warn!("Rendering: auto exposure unavailable — using manual EV100 fallback");
}
commands.insert_resource(RenderingCapabilitiesDetected);
}
/// Returns whether the active GPU exposes all wgpu features required by [`SolariPlugins`].
pub fn probe_solari_rt_support(render_device: &RenderDevice) -> bool {
if let Ok(value) = std::env::var("BEVY_FPS_FORCE_SOLARI") {
return !matches!(
value.trim().to_ascii_lowercase().as_str(),
"0" | "false" | "off" | "no"
);
}
let required = SolariPlugins::required_wgpu_features();
render_device.features().contains(required)
}
fn init_opaque_renderer_method(
settings: Res<ProjectSettings>,
caps: Res<RenderingCapabilities>,
mut commands: Commands,
) {
let requested = settings::resolve_gi_path(settings.rendering.gi_mode, &caps);
commands.insert_resource(opaque_renderer_method_for(requested));
}
fn sync_opaque_renderer_method(
caps: Res<RenderingCapabilities>,
stats: Res<SolariRaytracingSceneStats>,
mut commands: Commands,
) {
if !caps.is_changed() && !stats.is_changed() {
return;
}
commands.insert_resource(opaque_renderer_method_for(caps.effective_gi_path));
}
fn opaque_renderer_method_for(path: GiPath) -> DefaultOpaqueRendererMethod {
match path {
GiPath::SolariDeferred => DefaultOpaqueRendererMethod::deferred(),
GiPath::Forward => DefaultOpaqueRendererMethod::forward(),
}
}
/// Non-primary 3D cameras still need deferred prepass targets when Solari is active.
fn sync_auxiliary_camera_deferred_prepass(
caps: Res<RenderingCapabilities>,
mut commands: Commands,
cameras: Query<
Entity,
(
With<Camera3d>,
Without<SolariLighting>,
Without<DeferredPrepass>,
),
>,
) {
if caps.effective_gi_path != GiPath::SolariDeferred {
return;
}
for entity in &cameras {
commands.entity(entity).insert((
DeferredPrepass,
DepthPrepass,
MotionVectorPrepass,
DeferredPrepassDoubleBuffer,
DepthPrepassDoubleBuffer,
));
}
}
fn sync_hydrated_raytracing_meshes(
caps: Res<RenderingCapabilities>,
mut commands: Commands,
mut stats: ResMut<SolariRaytracingSceneStats>,
materials: Res<Assets<StandardMaterial>>,
mesh_assets: Res<Assets<Mesh>>,
meshes: Query<(
Entity,
&Mesh3d,
Option<&MeshMaterial3d<StandardMaterial>>,
Option<&RaytracingMesh3d>,
Option<&RaytracingExcluded>,
)>,
raytraced: Query<Entity, With<RaytracingMesh3d>>,
parents: Query<&ChildOf>,
level_roots: Query<(), With<LevelObject>>,
) {
let mut next_stats = *stats;
next_stats.project_meshes = 0;
next_stats.tagged_meshes = 0;
next_stats.excluded_meshes = 0;
next_stats.unsupported_meshes = 0;
next_stats.missing_level_root_meshes = 0;
next_stats.emissive_meshes = 0;
next_stats.compatible_mesh_assets = 0;
next_stats.incompatible_mesh_assets = 0;
next_stats.mesh_assets_missing_tangents = 0;
next_stats.mesh_assets_missing_u32_indices = 0;
if caps.requested_gi_path != GiPath::SolariDeferred {
for entity in &raytraced {
commands.entity(entity).remove::<RaytracingMesh3d>();
}
next_stats.render_instances = 0;
next_stats.render_directional_lights = 0;
next_stats.render_bind_group_ready = false;
if *stats != next_stats {
info!(
"Solari raytracing scene disabled: requested={:?}; removing {} raytracing mesh tags",
caps.requested_gi_path,
raytraced.iter().len()
);
*stats = next_stats;
}
return;
}
for (entity, mesh, material, rt_mesh, excluded) in &meshes {
if excluded.is_some() {
next_stats.excluded_meshes += 1;
if rt_mesh.is_some() {
commands.entity(entity).remove::<RaytracingMesh3d>();
}
continue;
}
if !has_level_object_ancestor(entity, &parents, &level_roots) {
next_stats.missing_level_root_meshes += 1;
continue;
}
next_stats.project_meshes += 1;
let Some(material) = material else {
next_stats.unsupported_meshes += 1;
if rt_mesh.is_some() {
commands.entity(entity).remove::<RaytracingMesh3d>();
}
continue;
};
if materials
.get(&material.0)
.is_some_and(|material| material.emissive.to_vec3() != Vec3::ZERO)
{
next_stats.emissive_meshes += 1;
}
match mesh_assets
.get(&mesh.0)
.map(classify_solari_mesh_compatibility)
{
Some(SolariMeshCompatibility::Compatible) => {
next_stats.compatible_mesh_assets += 1;
}
Some(SolariMeshCompatibility::MissingTangents) => {
next_stats.incompatible_mesh_assets += 1;
next_stats.mesh_assets_missing_tangents += 1;
}
Some(SolariMeshCompatibility::MissingU32Indices) => {
next_stats.incompatible_mesh_assets += 1;
next_stats.mesh_assets_missing_u32_indices += 1;
}
Some(SolariMeshCompatibility::Other) | None => {
next_stats.incompatible_mesh_assets += 1;
}
}
next_stats.tagged_meshes += 1;
let needs_insert = rt_mesh.is_none_or(|rt_mesh| rt_mesh.0 != mesh.0);
if needs_insert {
commands
.entity(entity)
.insert(RaytracingMesh3d(mesh.0.clone()));
}
}
for entity in &raytraced {
if !mesh_is_solari_project_geometry(entity, &meshes, &parents, &level_roots) {
commands.entity(entity).remove::<RaytracingMesh3d>();
}
}
if *stats != next_stats {
info!(
"Solari mesh eligibility: requested={:?} eligible={} tagged={} compatible_assets={} incompatible_assets={} missing_tangents={} missing_u32_indices={} unsupported={} excluded={} outside_level_roots={} emissive={}",
caps.requested_gi_path,
next_stats.project_meshes,
next_stats.tagged_meshes,
next_stats.compatible_mesh_assets,
next_stats.incompatible_mesh_assets,
next_stats.mesh_assets_missing_tangents,
next_stats.mesh_assets_missing_u32_indices,
next_stats.unsupported_meshes,
next_stats.excluded_meshes,
next_stats.missing_level_root_meshes,
next_stats.emissive_meshes,
);
*stats = next_stats;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SolariMeshCompatibility {
Compatible,
MissingTangents,
MissingU32Indices,
Other,
}
fn classify_solari_mesh_compatibility(mesh: &Mesh) -> SolariMeshCompatibility {
if mesh.primitive_topology() != PrimitiveTopology::TriangleList || !mesh.enable_raytracing {
return SolariMeshCompatibility::Other;
}
let attribute_ids: Vec<_> = mesh
.attributes()
.map(|(attribute, _)| attribute.id)
.collect();
let expected = [
Mesh::ATTRIBUTE_POSITION.id,
Mesh::ATTRIBUTE_NORMAL.id,
Mesh::ATTRIBUTE_UV_0.id,
Mesh::ATTRIBUTE_TANGENT.id,
];
if attribute_ids != expected {
if !attribute_ids.contains(&Mesh::ATTRIBUTE_TANGENT.id) {
return SolariMeshCompatibility::MissingTangents;
}
return SolariMeshCompatibility::Other;
}
if !matches!(mesh.indices(), Some(Indices::U32(_))) {
return SolariMeshCompatibility::MissingU32Indices;
}
SolariMeshCompatibility::Compatible
}
fn mesh_is_solari_project_geometry(
entity: Entity,
meshes: &Query<(
Entity,
&Mesh3d,
Option<&MeshMaterial3d<StandardMaterial>>,
Option<&RaytracingMesh3d>,
Option<&RaytracingExcluded>,
)>,
parents: &Query<&ChildOf>,
level_roots: &Query<(), With<LevelObject>>,
) -> bool {
let Ok((_, _, material, _, excluded)) = meshes.get(entity) else {
return false;
};
excluded.is_none()
&& material.is_some()
&& has_level_object_ancestor(entity, parents, level_roots)
}
fn has_level_object_ancestor(
mut entity: Entity,
parents: &Query<&ChildOf>,
level_roots: &Query<(), With<LevelObject>>,
) -> bool {
const MAX_DEPTH: usize = 64;
for _ in 0..MAX_DEPTH {
if level_roots.contains(entity) {
return true;
}
let Ok(parent) = parents.get(entity) else {
return false;
};
entity = parent.parent();
}
false
}
fn sync_render_solari_scene_readback(
caps: Res<RenderingCapabilities>,
readback: Res<SolariRenderSceneReadback>,
mut stats: ResMut<SolariRaytracingSceneStats>,
) {
if caps.requested_gi_path != GiPath::SolariDeferred {
let mut next = *stats;
next.render_instances = 0;
next.render_directional_lights = 0;
next.render_bind_group_ready = false;
if *stats != next {
*stats = next;
}
return;
}
let Ok(render_stats) = readback.0.lock() else {
return;
};
let mut next = *stats;
next.render_instances = render_stats.render_instances;
next.render_directional_lights = render_stats.render_directional_lights;
next.render_bind_group_ready = render_stats.render_bind_group_ready;
if *stats != next {
let was_ready = stats.solari_ready();
let is_ready = next.solari_ready();
if was_ready != is_ready
|| stats.render_instances != next.render_instances
|| stats.render_directional_lights != next.render_directional_lights
|| stats.render_bind_group_ready != next.render_bind_group_ready
{
info!(
"Solari render readback: ready={} instances={} directional_lights={} bind_group_ready={} compatible_lights={}",
is_ready,
next.render_instances,
next.render_directional_lights,
next.render_bind_group_ready,
next.compatible_light_count(),
);
}
*stats = next;
}
}
fn write_render_solari_scene_readback(
readback: Res<SolariRenderSceneReadback>,
scene_bindings: Option<Res<RaytracingSceneBindings>>,
raytracing_instances: Query<(), With<RaytracingMesh3d>>,
directional_lights: Query<(), With<ExtractedDirectionalLight>>,
) {
let Ok(mut stats) = readback.0.lock() else {
return;
};
*stats = SolariRenderSceneStats {
render_instances: raytracing_instances.iter().len(),
render_directional_lights: directional_lights.iter().len(),
render_bind_group_ready: scene_bindings
.is_some_and(|bindings| bindings.bind_group.is_some()),
};
}
pub fn effective_gi_path_for_camera(
requested: GiPath,
stats: Option<&SolariRaytracingSceneStats>,
) -> GiPath {
let _ = stats;
requested
}
pub fn sync_gi_path(commands: &mut Commands, entity: Entity, path: GiPath) {
match path {
GiPath::SolariDeferred => {
commands.entity(entity).insert((
SolariLighting::default(),
CameraMainTextureUsages::default().with(TextureUsages::STORAGE_BINDING),
));
}
GiPath::Forward => {
commands
.entity(entity)
.remove::<(SolariLighting, CameraMainTextureUsages)>();
}
}
}
pub fn strip_gi_path(commands: &mut Commands, entity: Entity) {
sync_gi_path(commands, entity, GiPath::Forward);
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::ecs::system::SystemState;
#[test]
fn level_object_descendant_is_project_geometry() {
let mut world = World::new();
let root = world.spawn(LevelObject).id();
let child = world.spawn(ChildOf(root)).id();
let mut state: SystemState<(Query<&ChildOf>, Query<(), With<LevelObject>>)> =
SystemState::new(&mut world);
let (parents, level_roots) = state.get(&world);
assert!(has_level_object_ancestor(child, &parents, &level_roots));
assert!(has_level_object_ancestor(root, &parents, &level_roots));
}
#[test]
fn orphan_mesh_is_not_project_geometry() {
let mut world = World::new();
let orphan = world.spawn_empty().id();
let mut state: SystemState<(Query<&ChildOf>, Query<(), With<LevelObject>>)> =
SystemState::new(&mut world);
let (parents, level_roots) = state.get(&world);
assert!(!has_level_object_ancestor(orphan, &parents, &level_roots));
}
#[test]
fn solari_request_can_start_before_render_scene_is_ready() {
let stats = SolariRaytracingSceneStats {
project_meshes: 1,
tagged_meshes: 1,
render_instances: 1,
render_directional_lights: 1,
render_bind_group_ready: false,
..default()
};
assert_eq!(
effective_gi_path_for_camera(GiPath::SolariDeferred, Some(&stats)),
GiPath::SolariDeferred
);
}
#[test]
fn solari_request_uses_solari_when_render_scene_is_ready() {
let stats = SolariRaytracingSceneStats {
project_meshes: 1,
tagged_meshes: 1,
render_instances: 1,
render_directional_lights: 1,
render_bind_group_ready: true,
..default()
};
assert_eq!(
effective_gi_path_for_camera(GiPath::SolariDeferred, Some(&stats)),
GiPath::SolariDeferred
);
}
}
@@ -0,0 +1,244 @@
//! Single owner for the viewport camera post/render stack (edit + play WYSIWYG).
use super::camera_fx::{
apply_camera_render_profile, camera_auto_exposure_active, hdr_required_for_effective_gi,
strip_project_camera_fx, sync_exposure, sync_optional_rendering_fx,
};
use super::solari::SolariRaytracingSceneStats;
use bevy::anti_alias::taa::TemporalAntiAliasing;
use bevy::camera::Exposure;
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::pbr::{Atmosphere, ScatteringMedium, ScreenSpaceAmbientOcclusion};
use bevy::post_process::auto_exposure::AutoExposure;
use bevy::post_process::bloom::Bloom;
use bevy::prelude::*;
use bevy::render::view::Hdr;
use settings::{
resolve_effective_render_stack, write_effective_render_stack, ActiveCameraRenderProfile,
EffectiveRenderStack, GiPath, ProjectRenderCamera, RenderingCapabilities,
};
/// Which camera entity owns the viewport render stack this frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewportCameraOwner {
EditorFly,
Player,
}
/// Maps editor mode + play possession to the active viewport camera owner.
pub fn resolve_viewport_camera_owner(
editing: bool,
playing_possessed: bool,
) -> ViewportCameraOwner {
if editing || !playing_possessed {
ViewportCameraOwner::EditorFly
} else {
ViewportCameraOwner::Player
}
}
/// True when any point or spot light in the world casts shadows (forces Forward GI).
pub fn has_local_shadow_lights(points: &Query<&PointLight>, spots: &Query<&SpotLight>) -> bool {
points.iter().any(|l| l.shadows_enabled) || spots.iter().any(|l| l.shadows_enabled)
}
/// [`has_local_shadow_lights`] for exclusive [`World`] access (hot reload, diagnostics).
pub fn world_has_local_shadow_lights(world: &mut World) -> bool {
for pl in world.query::<&PointLight>().iter(world) {
if pl.shadows_enabled {
return true;
}
}
for sl in world.query::<&SpotLight>().iter(world) {
if sl.shadows_enabled {
return true;
}
}
false
}
/// Effective GI path for the main viewport, including auto-forward for local shadow lights.
pub fn effective_viewport_gi_path(
requested: GiPath,
caps: &RenderingCapabilities,
stats: Option<&SolariRaytracingSceneStats>,
has_local_shadow_lights: bool,
) -> GiPath {
effective_viewport_render_stack(requested, caps, stats, has_local_shadow_lights)
.effective_gi_path
}
/// Effective render-stack decision for the main viewport.
pub fn effective_viewport_render_stack(
requested: GiPath,
caps: &RenderingCapabilities,
stats: Option<&SolariRaytracingSceneStats>,
has_local_shadow_lights: bool,
) -> EffectiveRenderStack {
resolve_effective_render_stack(
requested,
caps,
stats.is_some_and(SolariRaytracingSceneStats::solari_ready),
has_local_shadow_lights,
)
}
/// Removes the full project render stack from a camera (owner handoff or inactive viewport).
pub fn clear_viewport_camera_stack(commands: &mut Commands, entity: Entity) {
strip_project_camera_fx(commands, entity);
}
/// Snapshot of optional FX components on a camera for incremental sync.
#[derive(Debug, Clone, Copy, Default)]
pub struct ViewportFxSnapshot {
pub has_stack: bool,
pub has_atmosphere: bool,
pub has_tonemapping: bool,
pub has_bloom: bool,
pub has_ssao: bool,
pub has_taa: bool,
pub has_hdr: bool,
pub has_auto_exposure: bool,
}
/// How to apply the viewport stack this frame.
#[derive(Debug, Clone, Copy)]
pub enum ViewportStackApply {
/// Strip was already done or camera is bare — full profile apply.
Full,
/// Camera already carries [`ProjectRenderCamera`]; patch deltas only.
Incremental(ViewportFxSnapshot),
}
/// Applies or updates the viewport render stack on the active camera entity.
#[allow(clippy::too_many_arguments)]
pub fn sync_viewport_camera_stack(
commands: &mut Commands,
entity: Entity,
profile: &ActiveCameraRenderProfile,
caps: &mut RenderingCapabilities,
solari_stats: Option<&SolariRaytracingSceneStats>,
has_local_shadow_lights: bool,
mediums: &mut Assets<ScatteringMedium>,
mode: ViewportStackApply,
) {
let stack = effective_viewport_render_stack(
profile.gi_path,
caps,
solari_stats,
has_local_shadow_lights,
);
write_effective_render_stack(caps, stack);
commands.insert_resource(stack);
let effective_gi = stack.effective_gi_path;
match mode {
ViewportStackApply::Full => {
commands.entity(entity).insert(ProjectRenderCamera);
apply_camera_render_profile(
commands,
entity,
profile,
caps,
solari_stats,
mediums,
has_local_shadow_lights,
);
}
ViewportStackApply::Incremental(snap) => {
commands.entity(entity).insert(ProjectRenderCamera);
commands.entity(entity).insert(Msaa::Off);
sync_optional_rendering_fx(
commands,
entity,
profile,
caps,
solari_stats,
mediums,
snap.has_atmosphere,
snap.has_tonemapping,
snap.has_bloom,
snap.has_ssao,
snap.has_taa,
snap.has_hdr,
snap.has_auto_exposure,
has_local_shadow_lights,
);
commands.entity(entity).insert(DistanceFog {
color: Color::srgb(
profile.fog_color[0],
profile.fog_color[1],
profile.fog_color[2],
),
falloff: FogFalloff::Exponential {
density: profile.fog_density,
},
..default()
});
let wants_auto = camera_auto_exposure_active(profile, caps);
if wants_auto != snap.has_auto_exposure {
sync_exposure(commands, entity, profile, caps);
} else if !wants_auto {
commands.entity(entity).insert(Exposure {
ev100: profile.exposure_ev100,
});
}
super::solari::sync_gi_path(commands, entity, effective_gi);
super::fullscreen_effects::sync_fullscreen_effect(
commands,
entity,
profile.fullscreen_effect.as_deref(),
);
let wants_hdr = hdr_required_for_effective_gi(profile, effective_gi);
if wants_hdr != snap.has_hdr {
if wants_hdr {
commands.entity(entity).insert(Hdr);
} else {
commands.entity(entity).remove::<Hdr>();
}
}
}
}
}
/// Builds a [`ViewportFxSnapshot`] from an entity's current components.
#[cfg(test)]
mod tests {
use super::*;
use settings::RenderingCapabilities;
#[test]
fn effective_viewport_gi_forces_forward_when_local_shadow_lights_exist() {
let caps = RenderingCapabilities {
rt_supported: true,
..Default::default()
};
let stats = Some(SolariRaytracingSceneStats {
render_bind_group_ready: true,
render_instances: 1,
render_directional_lights: 1,
..Default::default()
});
assert_eq!(
effective_viewport_gi_path(GiPath::SolariDeferred, &caps, stats.as_ref(), true),
GiPath::Forward
);
assert_eq!(
effective_viewport_gi_path(GiPath::SolariDeferred, &caps, stats.as_ref(), false),
GiPath::SolariDeferred
);
}
}
pub fn snapshot_viewport_fx(entity: Entity, world: &World) -> ViewportFxSnapshot {
ViewportFxSnapshot {
has_stack: world.get::<ProjectRenderCamera>(entity).is_some(),
has_atmosphere: world.get::<Atmosphere>(entity).is_some(),
has_tonemapping: world.get::<Tonemapping>(entity).is_some(),
has_bloom: world.get::<Bloom>(entity).is_some(),
has_ssao: world.get::<ScreenSpaceAmbientOcclusion>(entity).is_some(),
has_taa: world.get::<TemporalAntiAliasing>(entity).is_some(),
has_hdr: world.get::<Hdr>(entity).is_some(),
has_auto_exposure: world.get::<AutoExposure>(entity).is_some(),
}
}
+487
View File
@@ -0,0 +1,487 @@
//! Post-process volume blending and active camera profile resolution.
use bevy::prelude::*;
use settings::{
resolve_effective_render_stack, resolve_gi_path, write_effective_render_stack,
ActiveCameraRenderProfile, ActiveVolumeContribution, EffectiveRenderStack, GiPath,
ProjectSettings, RenderingCapabilities, RenderingSettings, VolumeContribution,
};
use shared::{
inspector_component_active, InspectorOrder, LevelObject, PostProcessVolumeDesc,
PostProcessVolumeOverrides, COMPONENT_POST_PROCESS_VOLUME,
};
use super::solari::SolariRaytracingSceneStats;
use super::viewport_camera::has_local_shadow_lights;
/// Edge blend weight for a point in volume local space.
pub fn volume_edge_weight(local: Vec3, half_extents: Vec3, blend_distance: f32) -> f32 {
let dist = half_extents - local.abs();
if dist.x < 0.0 || dist.y < 0.0 || dist.z < 0.0 {
return 0.0;
}
if blend_distance <= 0.0 {
return 1.0;
}
let min_dist = dist.x.min(dist.y).min(dist.z);
(min_dist / blend_distance).clamp(0.0, 1.0)
}
/// Applies volume overrides onto project rendering defaults.
pub fn resolve_volume_overrides(
project: &RenderingSettings,
desc: &PostProcessVolumeDesc,
) -> ActiveCameraRenderProfile {
let gi_path = GiPath::Forward;
let mut profile = ActiveCameraRenderProfile::from_project(project, gi_path);
apply_overrides(&mut profile, &desc.overrides);
profile.fullscreen_effect = desc.fullscreen_effect.clone();
profile
}
fn apply_overrides(
profile: &mut ActiveCameraRenderProfile,
overrides: &PostProcessVolumeOverrides,
) {
if let Some(v) = overrides.exposure_ev100 {
profile.exposure_ev100 = v;
}
if let Some(v) = overrides.fog_color {
profile.fog_color = [v.r, v.g, v.b];
}
if let Some(v) = overrides.fog_density {
profile.fog_density = v;
}
if let Some(v) = overrides.bloom {
profile.bloom = v;
}
if let Some(v) = overrides.taa {
profile.taa = v;
}
if let Some(v) = overrides.ssao {
profile.ssao = v;
}
if let Some(v) = overrides.tonemapping_aces {
profile.tonemapping_aces = v;
}
if let Some(v) = overrides.atmosphere {
profile.atmosphere = v;
}
if let Some(v) = overrides.hdr {
profile.hdr = v;
}
}
#[derive(Debug, Clone)]
pub struct VolumeSample {
entity: Entity,
weight: f32,
priority: i32,
desc: PostProcessVolumeDesc,
}
fn blend_profiles(
project: &RenderingSettings,
gi_path: GiPath,
samples: &[VolumeSample],
) -> ActiveCameraRenderProfile {
let mut profile = ActiveCameraRenderProfile::from_project(project, gi_path);
if samples.is_empty() {
return profile;
}
let mut sorted: Vec<&VolumeSample> = samples.iter().filter(|s| s.weight > 0.0).collect();
sorted.sort_by(|a, b| {
b.priority
.cmp(&a.priority)
.then_with(|| a.entity.index().cmp(&b.entity.index()))
});
for sample in &sorted {
if sample.desc.fullscreen_effect.is_some() {
profile.fullscreen_effect = sample.desc.fullscreen_effect.clone();
break;
}
}
for sample in &sorted {
if sample.desc.overrides.exposure_ev100.is_some() {
profile.exposure_ev100 = resolve_volume_overrides(project, &sample.desc).exposure_ev100;
profile.exposure_mode = settings::ExposureMode::Manual;
break;
}
}
for sample in &sorted {
if sample.desc.overrides.fog_density.is_some() {
profile.fog_density = resolve_volume_overrides(project, &sample.desc).fog_density;
break;
}
}
for sample in &sorted {
if sample.desc.overrides.fog_color.is_some() {
profile.fog_color = resolve_volume_overrides(project, &sample.desc).fog_color;
break;
}
}
// Edge blend for scalars without explicit overrides: weighted by spatial weight.
let mut total_w = 0.0f32;
let mut exposure = 0.0f32;
let mut fog_density = 0.0f32;
let mut fog_color = [0.0f32; 3];
let any_exposure_override = sorted
.iter()
.any(|s| s.desc.overrides.exposure_ev100.is_some());
let any_fog_density_override = sorted
.iter()
.any(|s| s.desc.overrides.fog_density.is_some());
let any_fog_color_override = sorted.iter().any(|s| s.desc.overrides.fog_color.is_some());
for sample in &sorted {
let resolved = resolve_volume_overrides(project, &sample.desc);
let w = sample.weight;
if !any_exposure_override {
exposure += resolved.exposure_ev100 * w;
}
if !any_fog_density_override {
fog_density += resolved.fog_density * w;
}
if !any_fog_color_override {
fog_color[0] += resolved.fog_color[0] * w;
fog_color[1] += resolved.fog_color[1] * w;
fog_color[2] += resolved.fog_color[2] * w;
}
total_w += w;
}
if total_w > 0.0 {
if !any_exposure_override {
profile.exposure_ev100 = exposure / total_w;
}
if !any_fog_density_override {
profile.fog_density = fog_density / total_w;
}
if !any_fog_color_override {
profile.fog_color = fog_color.map(|c| c / total_w);
}
}
for sample in &sorted {
let o = &sample.desc.overrides;
if let Some(v) = o.hdr {
profile.hdr = v;
break;
}
}
for sample in &sorted {
if let Some(v) = sample.desc.overrides.bloom {
profile.bloom = v;
break;
}
}
for sample in &sorted {
if let Some(v) = sample.desc.overrides.taa {
profile.taa = v;
break;
}
}
for sample in &sorted {
if let Some(v) = sample.desc.overrides.ssao {
profile.ssao = v;
break;
}
}
for sample in &sorted {
if let Some(v) = sample.desc.overrides.tonemapping_aces {
profile.tonemapping_aces = v;
break;
}
}
for sample in &sorted {
if let Some(v) = sample.desc.overrides.atmosphere {
profile.atmosphere = v;
break;
}
}
profile
}
/// Resolves the active camera render profile from project settings and scene volumes.
pub fn resolve_active_camera_render_profile(
camera_world: Vec3,
project: &RenderingSettings,
caps: &RenderingCapabilities,
volumes: &[(Entity, &PostProcessVolumeDesc, &GlobalTransform)],
) -> (ActiveCameraRenderProfile, Vec<VolumeContribution>) {
let gi_path = resolve_gi_path(project.gi_mode, caps);
let mut samples = Vec::new();
for (entity, desc, global) in volumes {
let local = global.affine().inverse().transform_point3(camera_world);
let weight = volume_edge_weight(local, desc.half_extents, desc.blend_distance);
if weight > 0.0 {
samples.push(VolumeSample {
entity: *entity,
weight,
priority: desc.priority,
desc: (*desc).clone(),
});
}
}
let mut contributions: Vec<VolumeContribution> = samples
.iter()
.map(|s| VolumeContribution {
entity_bits: s.entity.to_bits(),
weight: s.weight,
label: s
.desc
.label
.clone()
.unwrap_or_else(|| format!("Volume {}", s.entity.index())),
override_count: s.desc.overrides.override_count(),
})
.collect();
contributions.sort_by(|a, b| {
b.weight
.partial_cmp(&a.weight)
.unwrap_or(std::cmp::Ordering::Equal)
});
let profile = blend_profiles(project, gi_path, &samples);
(profile, contributions)
}
/// Bevy system: updates [`ActiveCameraRenderProfile`] and [`ActiveVolumeContribution`].
pub fn sync_active_camera_render_profile(
mut commands: Commands,
settings: Res<ProjectSettings>,
volumes: Query<
(
Entity,
&PostProcessVolumeDesc,
&GlobalTransform,
Option<&InspectorOrder>,
),
With<LevelObject>,
>,
cameras: Query<&GlobalTransform, With<settings::ProjectRenderCamera>>,
mut profile: ResMut<ActiveCameraRenderProfile>,
mut contributions: ResMut<ActiveVolumeContribution>,
mut caps: ResMut<RenderingCapabilities>,
solari_stats: Res<SolariRaytracingSceneStats>,
points: Query<&PointLight>,
spots: Query<&SpotLight>,
mut last_request: Local<Option<(settings::GiMode, GiPath, bool)>>,
mut last_stack: Local<Option<EffectiveRenderStack>>,
) {
let gi_path = resolve_gi_path(settings.rendering.gi_mode, &caps);
let request_key = (settings.rendering.gi_mode, gi_path, caps.rt_supported);
if *last_request != Some(request_key) {
info!(
"Rendering profile request: gi_mode={:?} requested={:?} rt_supported={}",
settings.rendering.gi_mode, gi_path, caps.rt_supported
);
*last_request = Some(request_key);
}
let local_shadow_lights = has_local_shadow_lights(&points, &spots);
let Some(camera_tf) = cameras.iter().next() else {
let resolved = ActiveCameraRenderProfile::from_project(&settings.rendering, gi_path);
*profile = resolved.clone();
contributions.set_entries(Vec::new());
publish_effective_stack(
&mut commands,
&mut caps,
&solari_stats,
resolved.gi_path,
local_shadow_lights,
&mut last_stack,
);
return;
};
let volume_list: Vec<_> = volumes
.iter()
.filter(|(_, _, _, order)| {
inspector_component_active(*order, COMPONENT_POST_PROCESS_VOLUME)
})
.map(|(entity, desc, transform, _)| (entity, desc, transform))
.collect();
let (resolved, entries) = resolve_active_camera_render_profile(
camera_tf.translation(),
&settings.rendering,
&caps,
&volume_list,
);
*profile = resolved.clone();
publish_effective_stack(
&mut commands,
&mut caps,
&solari_stats,
resolved.gi_path,
local_shadow_lights,
&mut last_stack,
);
contributions.set_entries(entries);
}
fn publish_effective_stack(
commands: &mut Commands,
caps: &mut RenderingCapabilities,
solari_stats: &SolariRaytracingSceneStats,
requested_gi_path: GiPath,
local_shadow_lights: bool,
last_stack: &mut Local<Option<EffectiveRenderStack>>,
) {
let stack = resolve_effective_render_stack(
requested_gi_path,
caps,
solari_stats.solari_ready(),
local_shadow_lights,
);
write_effective_render_stack(caps, stack);
commands.insert_resource(stack);
if **last_stack != Some(stack) {
info!(
"Rendering effective stack: requested={:?} effective={:?} fallback={:?} rt_supported={} solari_ready={} local_shadow_lights={} tagged_meshes={} render_instances={} render_directional_lights={} bind_group_ready={} emissive_meshes={}",
stack.requested_gi_path,
stack.effective_gi_path,
stack.fallback_reason,
caps.rt_supported,
stack.solari_ready,
stack.local_shadow_lights,
solari_stats.tagged_meshes,
solari_stats.render_instances,
solari_stats.render_directional_lights,
solari_stats.render_bind_group_ready,
solari_stats.emissive_meshes,
);
**last_stack = Some(stack);
}
}
/// Alias used by [`SolariRenderingPlugin`] and editor ordering.
pub use sync_active_camera_render_profile as resolve_active_camera_render_profile_system;
/// Returns entities whose post-process volumes contain `world_pos` with weight > 0.
pub fn sample_volumes_at(
world_pos: Vec3,
volumes: &[(Entity, &PostProcessVolumeDesc, &GlobalTransform)],
) -> Vec<Entity> {
volumes
.iter()
.filter_map(|(entity, desc, global)| {
let local = global.affine().inverse().transform_point3(world_pos);
let weight = volume_edge_weight(local, desc.half_extents, desc.blend_distance);
(weight > 0.0).then_some(*entity)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use shared::ColorDesc;
fn default_project() -> RenderingSettings {
RenderingSettings::default()
}
#[test]
fn edge_weight_center_is_one() {
let w = volume_edge_weight(Vec3::ZERO, Vec3::ONE, 0.5);
assert!((w - 1.0).abs() < 1e-5);
}
#[test]
fn edge_weight_outside_is_zero() {
let w = volume_edge_weight(Vec3::new(2.0, 0.0, 0.0), Vec3::ONE, 0.5);
assert_eq!(w, 0.0);
}
#[test]
fn inherit_vs_override_exposure() {
let project = default_project();
let mut desc = PostProcessVolumeDesc::default();
desc.overrides.exposure_ev100 = Some(8.0);
let resolved = resolve_volume_overrides(&project, &desc);
assert!((resolved.exposure_ev100 - 8.0).abs() < 1e-5);
assert_eq!(resolved.bloom, project.bloom);
}
#[test]
fn priority_wins_at_overlap_center() {
let project = default_project();
let low = VolumeSample {
entity: Entity::from_raw_u32(1).unwrap(),
weight: 1.0,
priority: 0,
desc: PostProcessVolumeDesc {
overrides: PostProcessVolumeOverrides {
exposure_ev100: Some(5.0),
..Default::default()
},
..Default::default()
},
};
let high = VolumeSample {
entity: Entity::from_raw_u32(2).unwrap(),
weight: 1.0,
priority: 10,
desc: PostProcessVolumeDesc {
overrides: PostProcessVolumeOverrides {
exposure_ev100: Some(15.0),
..Default::default()
},
..Default::default()
},
};
let profile = blend_profiles(&project, GiPath::Forward, &[low, high]);
assert!((profile.exposure_ev100 - 15.0).abs() < 1e-4);
}
#[test]
fn volume_exposure_override_forces_manual_mode() {
let mut project = default_project();
project.exposure_mode = settings::ExposureMode::Auto;
let sample = VolumeSample {
entity: Entity::from_raw_u32(1).unwrap(),
weight: 1.0,
priority: 0,
desc: PostProcessVolumeDesc {
overrides: PostProcessVolumeOverrides {
exposure_ev100: Some(9.0),
..Default::default()
},
..Default::default()
},
};
let profile = blend_profiles(&project, GiPath::Forward, &[sample]);
assert_eq!(profile.exposure_mode, settings::ExposureMode::Manual);
assert!((profile.exposure_ev100 - 9.0).abs() < 1e-5);
}
#[test]
fn solari_stays_active_when_rt_is_supported() {
let mut project = default_project();
project.gi_mode = settings::GiMode::Solari;
let caps = RenderingCapabilities {
rt_supported: true,
..Default::default()
};
assert_eq!(
resolve_gi_path(project.gi_mode, &caps),
GiPath::SolariDeferred
);
}
#[test]
fn fog_color_override() {
let project = default_project();
let mut desc = PostProcessVolumeDesc::default();
desc.overrides.fog_color = Some(ColorDesc::srgb(0.1, 0.2, 0.3));
let resolved = resolve_volume_overrides(&project, &desc);
assert!((resolved.fog_color[0] - 0.1).abs() < 1e-5);
}
}