bevy_pbr/decal/
forward.rs

1use crate::{
2    ExtendedMaterial, Material, MaterialExtension, MaterialExtensionKey, MaterialExtensionPipeline,
3    MaterialPlugin, StandardMaterial,
4};
5use bevy_app::{App, Plugin};
6use bevy_asset::{Asset, Assets, Handle};
7use bevy_ecs::{
8    component::Component, lifecycle::HookContext, resource::Resource, world::DeferredWorld,
9};
10use bevy_math::{prelude::Rectangle, Quat, Vec2, Vec3};
11use bevy_mesh::{Mesh, Mesh3d, MeshBuilder, MeshVertexBufferLayoutRef, Meshable};
12use bevy_reflect::{Reflect, TypePath};
13use bevy_render::{
14    alpha::AlphaMode,
15    render_asset::RenderAssets,
16    render_resource::{
17        AsBindGroup, AsBindGroupShaderType, CompareFunction, RenderPipelineDescriptor, ShaderType,
18        SpecializedMeshPipelineError,
19    },
20    texture::GpuImage,
21    RenderDebugFlags,
22};
23use bevy_shader::load_shader_library;
24
25/// Plugin to render [`ForwardDecal`]s.
26pub struct ForwardDecalPlugin;
27
28impl Plugin for ForwardDecalPlugin {
29    fn build(&self, app: &mut App) {
30        load_shader_library!(app, "forward_decal.wgsl");
31
32        let mesh = app.world_mut().resource_mut::<Assets<Mesh>>().add(
33            Rectangle::from_size(Vec2::ONE)
34                .mesh()
35                .build()
36                .rotated_by(Quat::from_rotation_arc(Vec3::Z, Vec3::Y))
37                .with_generated_tangents()
38                .unwrap(),
39        );
40
41        app.insert_resource(ForwardDecalMesh(mesh));
42
43        app.add_plugins(MaterialPlugin::<ForwardDecalMaterial<StandardMaterial>> {
44            prepass_enabled: false,
45            shadows_enabled: false,
46            debug_flags: RenderDebugFlags::default(),
47            ..Default::default()
48        });
49    }
50}
51
52/// A decal that renders via a 1x1 transparent quad mesh, smoothly alpha-blending with the underlying
53/// geometry towards the edges.
54///
55/// Because forward decals are meshes, you can use arbitrary materials to control their appearance.
56///
57/// # Usage Notes
58///
59/// * Spawn this component on an entity with a [`crate::MeshMaterial3d`] component holding a [`ForwardDecalMaterial`].
60/// * Any camera rendering a forward decal must have the [`bevy_core_pipeline::prepass::DepthPrepass`] component.
61/// * Looking at forward decals at a steep angle can cause distortion. This can be mitigated by padding your decal's
62///   texture with extra transparent pixels on the edges.
63/// * On Wasm, requires using WebGPU and disabling `Msaa` on your camera.
64#[derive(Component, Reflect)]
65#[require(Mesh3d)]
66#[component(on_add=forward_decal_set_mesh)]
67pub struct ForwardDecal;
68
69/// Type alias for an extended material with a [`ForwardDecalMaterialExt`] extension.
70///
71/// Make sure to register the [`MaterialPlugin`] for this material in your app setup.
72///
73/// [`StandardMaterial`] comes with out of the box support for forward decals.
74#[expect(type_alias_bounds, reason = "Type alias generics not yet stable")]
75pub type ForwardDecalMaterial<B: Material> = ExtendedMaterial<B, ForwardDecalMaterialExt>;
76
77/// Material extension for a [`ForwardDecal`].
78///
79/// In addition to wrapping your material type with this extension, your shader must use
80/// the `bevy_pbr::decal::forward::get_forward_decal_info` function.
81///
82/// The `FORWARD_DECAL` shader define will be made available to your shader so that you can gate
83/// the forward decal code behind an ifdef.
84#[derive(Asset, AsBindGroup, TypePath, Clone, Debug)]
85#[uniform(200, ForwardDecalMaterialExtUniform)]
86pub struct ForwardDecalMaterialExt {
87    /// Controls the distance threshold for decal blending with surfaces.
88    ///
89    /// This parameter determines how far away a surface can be before the decal no longer blends
90    /// with it and instead renders with full opacity.
91    ///
92    /// Lower values cause the decal to only blend with close surfaces, while higher values allow
93    /// blending with more distant surfaces.
94    ///
95    /// Units are in meters.
96    pub depth_fade_factor: f32,
97}
98
99#[derive(Clone, Default, ShaderType)]
100pub struct ForwardDecalMaterialExtUniform {
101    pub inv_depth_fade_factor: f32,
102}
103
104impl AsBindGroupShaderType<ForwardDecalMaterialExtUniform> for ForwardDecalMaterialExt {
105    fn as_bind_group_shader_type(
106        &self,
107        _images: &RenderAssets<GpuImage>,
108    ) -> ForwardDecalMaterialExtUniform {
109        ForwardDecalMaterialExtUniform {
110            inv_depth_fade_factor: 1.0 / self.depth_fade_factor.max(0.001),
111        }
112    }
113}
114
115impl MaterialExtension for ForwardDecalMaterialExt {
116    fn alpha_mode() -> Option<AlphaMode> {
117        Some(AlphaMode::Blend)
118    }
119
120    fn specialize(
121        _pipeline: &MaterialExtensionPipeline,
122        descriptor: &mut RenderPipelineDescriptor,
123        _layout: &MeshVertexBufferLayoutRef,
124        _key: MaterialExtensionKey<Self>,
125    ) -> Result<(), SpecializedMeshPipelineError> {
126        descriptor.depth_stencil.as_mut().unwrap().depth_compare = CompareFunction::Always;
127
128        descriptor.vertex.shader_defs.push("FORWARD_DECAL".into());
129
130        if let Some(fragment) = &mut descriptor.fragment {
131            fragment.shader_defs.push("FORWARD_DECAL".into());
132        }
133
134        if let Some(label) = &mut descriptor.label {
135            *label = format!("forward_decal_{label}").into();
136        }
137
138        Ok(())
139    }
140}
141
142impl Default for ForwardDecalMaterialExt {
143    fn default() -> Self {
144        Self {
145            depth_fade_factor: 8.0,
146        }
147    }
148}
149
150#[derive(Resource)]
151struct ForwardDecalMesh(Handle<Mesh>);
152
153// Note: We need to use a hook here instead of required components since we cannot access resources
154// with required components, and we can't otherwise get a handle to the asset from a required
155// component constructor, since the constructor must be a function pointer, and we intentionally do
156// not want to use `uuid_handle!`.
157fn forward_decal_set_mesh(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
158    let decal_mesh = world.resource::<ForwardDecalMesh>().0.clone();
159    let mut entity = world.entity_mut(entity);
160    let mut entity_mesh = entity.get_mut::<Mesh3d>().unwrap();
161    // Only replace the mesh handle if the mesh handle is defaulted.
162    if **entity_mesh == Handle::default() {
163        entity_mesh.0 = decal_mesh;
164    }
165}