From 38658f0a2ad911cc17656fa84c7722cc664886c4 Mon Sep 17 00:00:00 2001 From: robtfm <50659922+robtfm@users.noreply.github.com> Date: Wed, 16 Aug 2023 13:54:20 +0100 Subject: [PATCH] add transparent depth bias for stability --- .../scene_runner/src/update_world/material.rs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/scene_runner/src/update_world/material.rs b/crates/scene_runner/src/update_world/material.rs index ba64b02a..934937e9 100644 --- a/crates/scene_runner/src/update_world/material.rs +++ b/crates/scene_runner/src/update_world/material.rs @@ -1,4 +1,4 @@ -use bevy::{ecs::system::SystemParam, pbr::NotShadowCaster, prelude::*}; +use bevy::{ecs::system::SystemParam, pbr::NotShadowCaster, prelude::*, render::primitives::Aabb}; use crate::{renderer_context::RendererSceneContext, ContainerEntity, SceneSets}; use common::util::TryInsertEx; @@ -128,7 +128,10 @@ impl Plugin for MaterialDefinitionPlugin { ComponentPosition::EntityOnly, ); - app.add_systems(Update, update_materials.in_set(SceneSets::PostLoop)); + app.add_systems( + Update, + (update_materials, update_bias).in_set(SceneSets::PostLoop), + ); } } @@ -272,3 +275,22 @@ fn update_materials( materials.get_mut(touch); } } + +#[allow(clippy::type_complexity)] +fn update_bias( + mut materials: ResMut>, + query: Query< + (&Aabb, &Handle), + Or<(Changed>, Changed)>, + >, +) { + for (aabb, h_material) in query.iter() { + if let Some(material) = materials.get_mut(h_material) { + if material.alpha_mode == AlphaMode::Blend { + // add a bias based on the aabb size, to force an explicit transparent order which is + // hopefully correct, but should be better than nothing even if not always perfect + material.depth_bias = aabb.half_extents.length() * 1e-5; + } + } + } +}