Skip to main content

bevy_pbr/decal/
clustered.rs

1//! Clustered decals, bounding regions that project textures onto surfaces.
2//!
3//! A *clustered decal* is a bounding box that projects a texture onto any
4//! surface within its bounds along the positive Z axis. In Bevy, clustered
5//! decals use the *clustered forward* rendering technique.
6//!
7//! Clustered decals are the highest-quality types of decals that Bevy supports,
8//! but they require bindless textures. This means that they presently can't be
9//! used on WebGL 2 or WebGPU. Bevy's clustered decals can be used with forward
10//! or deferred rendering and don't require a prepass.
11//!
12//! Each clustered decal may contain up to 4 textures. By default, the 4
13//! textures correspond to the base color, a normal map, a metallic-roughness
14//! map, and an emissive map respectively. However, with a custom shader, you
15//! can use these 4 textures for whatever you wish. Additionally, you can use
16//! the built-in *tag* field to store additional application-specific data; by
17//! reading the tag in the shader, you can modify the appearance of a clustered
18//! decal arbitrarily. See the documentation in `clustered.wesl` for more
19//! information and the `clustered_decals` example for an example of use.
20
21use core::{num::NonZero, ops::Deref};
22
23use bevy_app::{App, Plugin};
24use bevy_asset::{AssetId, Handle};
25use bevy_camera::visibility::ViewVisibility;
26use bevy_derive::{Deref, DerefMut};
27use bevy_ecs::{
28    entity::{Entity, EntityHashMap},
29    query::With,
30    resource::Resource,
31    schedule::IntoScheduleConfigs as _,
32    system::{Commands, Local, Query, Res, ResMut},
33};
34use bevy_image::Image;
35use bevy_light::{ClusteredDecal, DirectionalLightTexture, PointLightTexture, SpotLightTexture};
36use bevy_math::{Mat4, Vec3};
37use bevy_platform::collections::HashMap;
38use bevy_render::{
39    render_asset::RenderAssets,
40    render_resource::{
41        binding_types, BindGroupLayoutEntryBuilder, Buffer, BufferUsages, RawBufferVec, Sampler,
42        SamplerBindingType, ShaderType, TextureSampleType, TextureView,
43    },
44    renderer::{RenderAdapter, RenderDevice, RenderQueue},
45    settings::WgpuFeatures,
46    sync_component::{SyncComponent, SyncComponentPlugin},
47    sync_world::RenderEntity,
48    texture::{FallbackImage, GpuImage},
49    Extract, ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderSystems,
50};
51use bevy_shader::load_shader_library;
52use bevy_transform::components::GlobalTransform;
53use bytemuck::{Pod, Zeroable};
54
55use crate::{binding_arrays_are_usable, prepare_lights, GlobalClusterableObjectMeta};
56
57/// The number of textures that can be associated with each clustered decal.
58const IMAGES_PER_DECAL: usize = 4;
59
60/// A plugin that adds support for clustered decals.
61///
62/// In environments where bindless textures aren't available, clustered decals
63/// can still be added to a scene, but they won't project any decals.
64pub struct ClusteredDecalPlugin;
65
66/// Stores information about all the clustered decals in the scene.
67#[derive(Resource, Default)]
68pub struct RenderClusteredDecals {
69    /// Maps an index in the shader binding array to the associated decal image.
70    ///
71    /// The `texture_to_binding_index` field holds the inverse mapping.
72    pub binding_index_to_textures: Vec<AssetId<Image>>,
73    /// Maps a decal image to the shader binding array.
74    ///
75    /// [`Self::binding_index_to_textures`] holds the inverse mapping.
76    texture_to_binding_index: HashMap<AssetId<Image>, i32>,
77    /// The information concerning each decal that we provide to the shader.
78    ///
79    /// Light textures follow the true clustered decals in this list, so that
80    /// lights can reference them via their decal indices.
81    decals: Vec<RenderClusteredDecal>,
82    /// The number of true clustered decals at the start of `decals`. Light
83    /// textures past this count aren't clusterable objects.
84    clusterable_decal_count: usize,
85    /// Maps the [`bevy_render::sync_world::RenderEntity`] of each decal to the
86    /// index of that decal in the [`Self::decals`] list.
87    entity_to_decal_index: EntityHashMap<usize>,
88}
89
90impl RenderClusteredDecals {
91    /// Clears out this [`RenderClusteredDecals`] in preparation for a new
92    /// frame.
93    fn clear(&mut self) {
94        self.binding_index_to_textures.clear();
95        self.texture_to_binding_index.clear();
96        self.decals.clear();
97        self.clusterable_decal_count = 0;
98        self.entity_to_decal_index.clear();
99    }
100
101    /// Inserts a decal into the buffer, along with its associated textures.
102    ///
103    /// Decals inserted this way aren't assigned to clusters; use the
104    /// [`bevy_light::ClusteredDecal`] component for clusterable decals.
105    pub fn insert_decal(
106        &mut self,
107        entity: Entity,
108        images: [Option<AssetId<Image>>; IMAGES_PER_DECAL],
109        local_from_world: Mat4,
110        world_position: Vec3,
111        bounding_sphere_radius: f32,
112        tag: u32,
113    ) {
114        let image_indices = images.map(|maybe_image_id| match maybe_image_id {
115            Some(ref image_id) => self.get_or_insert_image(image_id),
116            None => -1,
117        });
118        let decal_index = self.decals.len();
119        self.decals.push(RenderClusteredDecal {
120            local_from_world,
121            image_indices,
122            world_position,
123            bounding_sphere_radius,
124            tag,
125            pad_a: 0,
126            pad_b: 0,
127            pad_c: 0,
128        });
129        self.entity_to_decal_index.insert(entity, decal_index);
130    }
131
132    pub fn get(&self, entity: Entity) -> Option<usize> {
133        self.entity_to_decal_index.get(&entity).copied()
134    }
135
136    /// Returns the number of entries in the decal buffer, light textures included.
137    pub fn len(&self) -> usize {
138        self.decals.len()
139    }
140
141    /// Returns true if there are no entries in the decal buffer.
142    pub fn is_empty(&self) -> bool {
143        self.decals.is_empty()
144    }
145
146    /// Returns the number of true clustered decals in the scene, excluding
147    /// light textures, which aren't clusterable objects.
148    pub(crate) fn clusterable_decal_count(&self) -> usize {
149        self.clusterable_decal_count
150    }
151}
152
153/// The per-view bind group entries pertaining to decals.
154pub(crate) struct RenderViewClusteredDecalBindGroupEntries<'a> {
155    /// The list of decals, corresponding to `mesh_view_bindings::decals` in the
156    /// shader.
157    pub(crate) decals: &'a Buffer,
158    /// The list of textures, corresponding to
159    /// `mesh_view_bindings::decal_textures` in the shader.
160    pub(crate) texture_views: Vec<&'a <TextureView as Deref>::Target>,
161    /// The sampler that the shader uses to sample decals, corresponding to
162    /// `mesh_view_bindings::decal_sampler` in the shader.
163    pub(crate) sampler: &'a Sampler,
164}
165
166/// A render-world resource that holds the buffer of [`ClusteredDecal`]s ready
167/// to upload to the GPU.
168#[derive(Resource, Deref, DerefMut)]
169pub struct DecalsBuffer(RawBufferVec<RenderClusteredDecal>);
170
171impl Default for DecalsBuffer {
172    fn default() -> Self {
173        DecalsBuffer(RawBufferVec::new(BufferUsages::STORAGE))
174    }
175}
176
177impl Plugin for ClusteredDecalPlugin {
178    fn build(&self, app: &mut App) {
179        load_shader_library!(app, "clustered.wesl");
180
181        app.add_plugins(SyncComponentPlugin::<ClusteredDecal, Self>::default());
182
183        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
184            return;
185        };
186
187        render_app
188            .init_gpu_resource::<DecalsBuffer>()
189            .init_resource::<RenderClusteredDecals>()
190            .add_systems(ExtractSchedule, (extract_decals, extract_clustered_decal))
191            .add_systems(
192                Render,
193                prepare_decals
194                    .in_set(RenderSystems::PrepareViews)
195                    .after(prepare_lights),
196            )
197            .add_systems(
198                Render,
199                upload_decals.in_set(RenderSystems::PrepareResources),
200            );
201    }
202}
203
204impl SyncComponent<RenderApp, ClusteredDecalPlugin> for ClusteredDecal {
205    type Target = Self;
206}
207
208// This is needed because of the orphan rule not allowing implementing
209// foreign trait ExtractComponent on foreign type ClusteredDecal
210fn extract_clustered_decal(
211    mut commands: Commands,
212    mut previous_len: Local<usize>,
213    query: Extract<Query<(RenderEntity, &ClusteredDecal)>>,
214) {
215    let mut values = Vec::with_capacity(*previous_len);
216    for (entity, query_item) in &query {
217        values.push((entity, query_item.clone()));
218    }
219    *previous_len = values.len();
220    commands.try_insert_batch(values);
221}
222
223/// The GPU data structure that stores information about each decal.
224#[derive(Clone, Copy, Default, ShaderType, Pod, Zeroable)]
225#[repr(C)]
226pub struct RenderClusteredDecal {
227    /// The inverse of the model matrix.
228    ///
229    /// The shader uses this in order to back-transform world positions into
230    /// model space.
231    local_from_world: Mat4,
232    /// The index of each decal texture in the binding array.
233    ///
234    /// These are in the order of the base color texture, the normal map
235    /// texture, the metallic-roughness map texture, and finally the emissive
236    /// texture.
237    ///
238    /// If the decal doesn't have a texture assigned to a slot, the index at
239    /// that slot will be -1.
240    image_indices: [i32; 4],
241    world_position: Vec3,
242    bounding_sphere_radius: f32,
243    /// A custom tag available for application-defined purposes.
244    tag: u32,
245    /// Padding.
246    pad_a: u32,
247    /// Padding.
248    pad_b: u32,
249    /// Padding.
250    pad_c: u32,
251}
252
253/// Extracts decals from the main world into the render world.
254pub fn extract_decals(
255    decals: Extract<
256        Query<(
257            RenderEntity,
258            &ClusteredDecal,
259            &GlobalTransform,
260            &ViewVisibility,
261        )>,
262    >,
263    spot_light_textures: Extract<
264        Query<(
265            RenderEntity,
266            &SpotLightTexture,
267            &GlobalTransform,
268            &ViewVisibility,
269        )>,
270    >,
271    point_light_textures: Extract<
272        Query<(
273            RenderEntity,
274            &PointLightTexture,
275            &GlobalTransform,
276            &ViewVisibility,
277        )>,
278    >,
279    directional_light_textures: Extract<
280        Query<(
281            RenderEntity,
282            &DirectionalLightTexture,
283            &GlobalTransform,
284            &ViewVisibility,
285        )>,
286    >,
287    mut render_decals: ResMut<RenderClusteredDecals>,
288) {
289    // Clear out the `RenderClusteredDecals` in preparation for a new frame.
290    render_decals.clear();
291
292    extract_clustered_decals(&decals, &mut render_decals);
293
294    // Light textures follow the true clustered decals in the buffer, but
295    // aren't clusterable objects. Record where they start.
296    render_decals.clusterable_decal_count = render_decals.decals.len();
297
298    extract_spot_light_textures(&spot_light_textures, &mut render_decals);
299    extract_point_light_textures(&point_light_textures, &mut render_decals);
300    extract_directional_light_textures(&directional_light_textures, &mut render_decals);
301}
302
303/// Extracts all clustered decals and light textures from the scene and transfers
304/// them to the render world.
305fn extract_clustered_decals(
306    decals: &Extract<
307        Query<(
308            RenderEntity,
309            &ClusteredDecal,
310            &GlobalTransform,
311            &ViewVisibility,
312        )>,
313    >,
314    render_decals: &mut RenderClusteredDecals,
315) {
316    // Loop over each decal.
317    for (decal_entity, clustered_decal, global_transform, view_visibility) in decals {
318        // If the decal is invisible, skip it.
319        if !view_visibility.get() {
320            continue;
321        }
322
323        // Insert the decal, grabbing the ID of every associated texture as we
324        // do.
325        render_decals.insert_decal(
326            decal_entity,
327            [
328                clustered_decal.base_color_texture.as_ref().map(Handle::id),
329                clustered_decal.normal_map_texture.as_ref().map(Handle::id),
330                clustered_decal
331                    .metallic_roughness_texture
332                    .as_ref()
333                    .map(Handle::id),
334                clustered_decal.emissive_texture.as_ref().map(Handle::id),
335            ],
336            global_transform.affine().inverse().into(),
337            global_transform.translation(),
338            (global_transform.scale() * Vec3::ONE).length(),
339            clustered_decal.tag,
340        );
341    }
342}
343
344/// Extracts all textures from spot lights from the main world to the render
345/// world as clustered decals.
346fn extract_spot_light_textures(
347    spot_light_textures: &Extract<
348        Query<(
349            RenderEntity,
350            &SpotLightTexture,
351            &GlobalTransform,
352            &ViewVisibility,
353        )>,
354    >,
355    render_decals: &mut RenderClusteredDecals,
356) {
357    for (decal_entity, texture, global_transform, view_visibility) in spot_light_textures {
358        // If the texture is invisible, skip it.
359        if !view_visibility.get() {
360            continue;
361        }
362
363        render_decals.insert_decal(
364            decal_entity,
365            [Some(texture.image.id()), None, None, None],
366            global_transform.affine().inverse().into(),
367            global_transform.translation(),
368            (global_transform.scale() * Vec3::ONE).length(),
369            0,
370        );
371    }
372}
373
374/// Extracts all textures from point lights from the main world to the render
375/// world as clustered decals.
376fn extract_point_light_textures(
377    point_light_textures: &Extract<
378        Query<(
379            RenderEntity,
380            &PointLightTexture,
381            &GlobalTransform,
382            &ViewVisibility,
383        )>,
384    >,
385    render_decals: &mut RenderClusteredDecals,
386) {
387    for (decal_entity, texture, global_transform, view_visibility) in point_light_textures {
388        // If the texture is invisible, skip it.
389        if !view_visibility.get() {
390            continue;
391        }
392
393        render_decals.insert_decal(
394            decal_entity,
395            [Some(texture.image.id()), None, None, None],
396            global_transform.affine().inverse().into(),
397            global_transform.translation(),
398            (global_transform.scale() * Vec3::ONE).length(),
399            texture.cubemap_layout as u32,
400        );
401    }
402}
403
404/// Extracts all textures from directional lights from the main world to the
405/// render world as clustered decals.
406fn extract_directional_light_textures(
407    directional_light_textures: &Extract<
408        Query<(
409            RenderEntity,
410            &DirectionalLightTexture,
411            &GlobalTransform,
412            &ViewVisibility,
413        )>,
414    >,
415    render_decals: &mut RenderClusteredDecals,
416) {
417    for (decal_entity, texture, global_transform, view_visibility) in directional_light_textures {
418        // If the texture is invisible, skip it.
419        if !view_visibility.get() {
420            continue;
421        }
422
423        render_decals.insert_decal(
424            decal_entity,
425            [Some(texture.image.id()), None, None, None],
426            global_transform.affine().inverse().into(),
427            global_transform.translation(),
428            (global_transform.scale() * Vec3::ONE).length(),
429            if texture.tiled { 1 } else { 0 },
430        );
431    }
432}
433
434/// Adds all decals in the scene to the [`GlobalClusterableObjectMeta`] table.
435fn prepare_decals(
436    decals: Query<Entity, With<ClusteredDecal>>,
437    mut global_clusterable_object_meta: ResMut<GlobalClusterableObjectMeta>,
438    render_decals: Res<RenderClusteredDecals>,
439) {
440    for decal_entity in &decals {
441        if let Some(index) = render_decals.entity_to_decal_index.get(&decal_entity) {
442            global_clusterable_object_meta
443                .entity_to_index
444                .insert(decal_entity, *index);
445        }
446    }
447}
448
449/// Returns the layout for the clustered-decal-related bind group entries for a
450/// single view.
451pub(crate) fn get_bind_group_layout_entries(
452    render_device: &RenderDevice,
453    render_adapter: &RenderAdapter,
454) -> Option<[BindGroupLayoutEntryBuilder; 3]> {
455    // If binding arrays aren't supported on the current platform, we have no
456    // bind group layout entries.
457    if !clustered_decals_are_usable(render_device, render_adapter) {
458        return None;
459    }
460
461    Some([
462        // `decals`
463        binding_types::storage_buffer_read_only::<RenderClusteredDecal>(false),
464        // `decal_textures`
465        binding_types::texture_2d(TextureSampleType::Float { filterable: true })
466            .count(NonZero::<u32>::new(max_view_decals(render_device)).unwrap()),
467        // `decal_sampler`
468        binding_types::sampler(SamplerBindingType::Filtering),
469    ])
470}
471
472impl<'a> RenderViewClusteredDecalBindGroupEntries<'a> {
473    /// Creates and returns the bind group entries for clustered decals for a
474    /// single view.
475    pub(crate) fn get(
476        render_decals: &RenderClusteredDecals,
477        decals_buffer: &'a DecalsBuffer,
478        images: &'a RenderAssets<GpuImage>,
479        fallback_image: &'a FallbackImage,
480        render_device: &RenderDevice,
481        render_adapter: &RenderAdapter,
482    ) -> Option<RenderViewClusteredDecalBindGroupEntries<'a>> {
483        // Skip the entries if decals are unsupported on the current platform.
484        if !clustered_decals_are_usable(render_device, render_adapter) {
485            return None;
486        }
487
488        // We use the first sampler among all the images. This assumes that all
489        // images use the same sampler, which is a documented restriction. If
490        // there's no sampler, we just use the one from the fallback image.
491        let sampler = match render_decals
492            .binding_index_to_textures
493            .iter()
494            .filter_map(|image_id| images.get(*image_id))
495            .next()
496        {
497            Some(gpu_image) => &gpu_image.sampler,
498            None => &fallback_image.d2.sampler,
499        };
500
501        // Gather up the decal textures.
502        let mut texture_views = vec![];
503        for image_id in &render_decals.binding_index_to_textures {
504            match images.get(*image_id) {
505                None => texture_views.push(&*fallback_image.d2.texture_view),
506                Some(gpu_image) => texture_views.push(&*gpu_image.texture_view),
507            }
508        }
509
510        // If required on this platform, pad out the binding array to its
511        // maximum length.
512        if !render_device
513            .features()
514            .contains(WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY)
515        {
516            let max_view_decals = max_view_decals(render_device);
517            while texture_views.len() < max_view_decals as usize {
518                texture_views.push(&*fallback_image.d2.texture_view);
519            }
520        } else if texture_views.is_empty() {
521            texture_views.push(&*fallback_image.d2.texture_view);
522        }
523
524        Some(RenderViewClusteredDecalBindGroupEntries {
525            decals: decals_buffer.buffer()?,
526            texture_views,
527            sampler,
528        })
529    }
530}
531
532impl RenderClusteredDecals {
533    /// Returns the index of the given image in the decal texture binding array,
534    /// adding it to the list if necessary.
535    fn get_or_insert_image(&mut self, image_id: &AssetId<Image>) -> i32 {
536        *self
537            .texture_to_binding_index
538            .entry(*image_id)
539            .or_insert_with(|| {
540                let index = self.binding_index_to_textures.len() as i32;
541                self.binding_index_to_textures.push(*image_id);
542                index
543            })
544    }
545}
546
547/// Uploads the list of decals from [`RenderClusteredDecals::decals`] to the
548/// GPU.
549fn upload_decals(
550    render_decals: Res<RenderClusteredDecals>,
551    mut decals_buffer: ResMut<DecalsBuffer>,
552    render_device: Res<RenderDevice>,
553    render_queue: Res<RenderQueue>,
554) {
555    decals_buffer.clear();
556
557    for &decal in &render_decals.decals {
558        decals_buffer.push(decal);
559    }
560
561    // Make sure the buffer is non-empty.
562    // Otherwise there won't be a buffer to bind.
563    if decals_buffer.is_empty() {
564        decals_buffer.push(RenderClusteredDecal::default());
565    }
566
567    decals_buffer.write_buffer(&render_device, &render_queue);
568}
569
570/// Returns true if clustered decals are usable on the current platform or false
571/// otherwise.
572///
573/// Clustered decals are currently disabled on macOS and iOS due to insufficient
574/// texture bindings and limited bindless support in `wgpu`.
575pub fn clustered_decals_are_usable(
576    render_device: &RenderDevice,
577    render_adapter: &RenderAdapter,
578) -> bool {
579    // Disable binding arrays on Metal. There aren't enough texture bindings available.
580    // See issue #17553.
581    // Re-enable this when `wgpu` has first-class bindless.
582    binding_arrays_are_usable(render_device, render_adapter)
583        && cfg!(feature = "pbr_clustered_decals")
584}
585
586/// Returns the maximum number of decals that can be in the scene, taking
587/// platform limitations into account.
588fn max_view_decals(render_device: &RenderDevice) -> u32 {
589    // If the current `wgpu` platform doesn't support partially-bound binding
590    // arrays, limit the number of decals to a low number. If we didn't do this,
591    // then on such platforms we'd pay the maximum overhead even if there are no
592    // decals are in the scene.
593    if render_device
594        .features()
595        .contains(WgpuFeatures::PARTIALLY_BOUND_BINDING_ARRAY)
596    {
597        // This number was determined arbitrarily as a reasonable value that
598        // would encompass most use cases (e.g. bullet holes in walls) while
599        // offering a failsafe to prevent shaders becoming too slow if there are
600        // extremely large numbers of decals.
601        1024
602    } else {
603        8
604    }
605}