Skip to main content

bevy_core_pipeline/tonemapping/
mod.rs

1use bevy_app::prelude::*;
2use bevy_asset::{
3    embedded_asset, load_embedded_asset, AssetServer, Assets, Handle, RenderAssetUsages,
4};
5use bevy_camera::Camera;
6use bevy_ecs::prelude::*;
7use bevy_image::{CompressedImageFormats, Image, ImageSampler, ImageType};
8#[cfg(not(feature = "tonemapping_luts"))]
9use bevy_log::error;
10use bevy_log::warn;
11use bevy_render::{
12    extract_component::ExtractComponentPlugin,
13    extract_resource::{ExtractResource, ExtractResourcePlugin},
14    render_asset::RenderAssets,
15    render_resource::{
16        binding_types::{sampler, texture_2d, texture_3d, uniform_buffer},
17        *,
18    },
19    renderer::RenderDevice,
20    texture::{FallbackImage, GpuImage},
21    view::{ColorGrading, ExtractedView, ViewTarget, ViewUniform},
22    GpuResourceAppExt, Render, RenderApp, RenderStartup, RenderSystems,
23};
24use bevy_shader::{load_shader_library, Shader, ShaderDefVal};
25use bitflags::bitflags;
26
27mod node;
28
29pub use bevy_render::view::{DebandDither, Tonemapping};
30use bevy_utils::default;
31pub use node::tonemapping;
32
33use crate::FullscreenShader;
34
35/// 3D LUT (look up table) textures used for tonemapping
36#[derive(Resource, Clone, ExtractResource)]
37#[extract_app(RenderApp)]
38pub struct TonemappingLuts {
39    pub blender_filmic: Handle<Image>,
40    pub agx: Handle<Image>,
41    pub tony_mc_mapface: Handle<Image>,
42}
43
44pub struct TonemappingPlugin;
45
46impl Plugin for TonemappingPlugin {
47    fn build(&self, app: &mut App) {
48        load_shader_library!(app, "lut_bindings.wesl");
49
50        embedded_asset!(app, "tonemapping_frag.wesl");
51
52        if !app.world().is_resource_added::<TonemappingLuts>() {
53            let mut images = app.world_mut().resource_mut::<Assets<Image>>();
54
55            #[cfg(feature = "tonemapping_luts")]
56            let tonemapping_luts = {
57                TonemappingLuts {
58                    blender_filmic: images.add(setup_tonemapping_lut_image(
59                        include_bytes!("luts/Blender_-11_12.ktx2"),
60                        ImageType::Extension("ktx2"),
61                    )),
62                    agx: images.add(setup_tonemapping_lut_image(
63                        include_bytes!("luts/AgX-default_contrast.ktx2"),
64                        ImageType::Extension("ktx2"),
65                    )),
66                    tony_mc_mapface: images.add(setup_tonemapping_lut_image(
67                        include_bytes!("luts/tony_mc_mapface.ktx2"),
68                        ImageType::Extension("ktx2"),
69                    )),
70                }
71            };
72
73            #[cfg(not(feature = "tonemapping_luts"))]
74            let tonemapping_luts = {
75                let placeholder = images.add(lut_placeholder());
76                TonemappingLuts {
77                    blender_filmic: placeholder.clone(),
78                    agx: placeholder.clone(),
79                    tony_mc_mapface: placeholder,
80                }
81            };
82
83            app.insert_resource(tonemapping_luts);
84        }
85
86        app.add_plugins(ExtractResourcePlugin::<TonemappingLuts>::default());
87
88        app.add_plugins((
89            ExtractComponentPlugin::<Tonemapping>::default(),
90            ExtractComponentPlugin::<DebandDither>::default(),
91        ));
92
93        app.add_systems(PostUpdate, check_tonemapping_none);
94
95        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
96            return;
97        };
98        render_app
99            .init_gpu_resource::<SpecializedRenderPipelines<TonemappingPipeline>>()
100            .add_systems(RenderStartup, init_tonemapping_pipeline)
101            .add_systems(
102                Render,
103                prepare_view_tonemapping_pipelines.in_set(RenderSystems::Prepare),
104            );
105    }
106}
107
108/// Warns when a camera has [`Tonemapping::None`] together with
109/// [`DebandDither::Enabled`] or a non-default [`ColorGrading`], since neither
110/// has any effect without tonemapping.
111pub fn check_tonemapping_none(
112    cameras: Query<
113        (
114            NameOrEntity,
115            &Tonemapping,
116            Option<&DebandDither>,
117            Option<&ColorGrading>,
118        ),
119        (
120            With<Camera>,
121            Or<(
122                Changed<Tonemapping>,
123                Changed<DebandDither>,
124                Changed<ColorGrading>,
125            )>,
126        ),
127    >,
128) {
129    for (camera, tonemapping, dither, color_grading) in &cameras {
130        if tonemapping.is_enabled() {
131            continue;
132        }
133        if dither == Some(&DebandDither::Enabled) {
134            warn!(
135                "Camera {camera} has `Tonemapping::None` with `DebandDither::Enabled`, so dithering has no effect. \
136                Use `Tonemapping::Linear` to keep dithering, or set `DebandDither::Disabled`."
137            );
138        }
139        if color_grading.is_some_and(|grading| *grading != ColorGrading::default()) {
140            warn!(
141                "Camera {camera} has `Tonemapping::None` with a non-default `ColorGrading`, so color grading has no effect. \
142                Use `Tonemapping::Linear` to keep color grading, or set `ColorGrading::default()`."
143            );
144        }
145    }
146}
147
148#[derive(Resource)]
149pub struct TonemappingPipeline {
150    texture_bind_group: BindGroupLayoutDescriptor,
151    sampler: Sampler,
152    fullscreen_shader: FullscreenShader,
153    fragment_shader: Handle<Shader>,
154}
155
156bitflags! {
157    /// Various flags describing what tonemapping needs to do.
158    ///
159    /// This allows the shader to skip unneeded steps.
160    #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
161    pub struct TonemappingPipelineKeyFlags: u8 {
162        /// The hue needs to be changed.
163        const HUE_ROTATE                = 0x01;
164        /// The white balance needs to be adjusted.
165        const WHITE_BALANCE             = 0x02;
166        /// Saturation/contrast/gamma/gain/lift for one or more sections
167        /// (shadows, midtones, highlights) need to be adjusted.
168        const SECTIONAL_COLOR_GRADING   = 0x04;
169    }
170}
171
172#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
173pub struct TonemappingPipelineKey {
174    target_format: TextureFormat,
175    deband_dither: DebandDither,
176    tonemapping: Tonemapping,
177    flags: TonemappingPipelineKeyFlags,
178}
179
180impl SpecializedRenderPipeline for TonemappingPipeline {
181    type Key = TonemappingPipelineKey;
182
183    fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
184        let mut shader_defs = Vec::new();
185
186        shader_defs.push(ShaderDefVal::UInt(
187            "TONEMAPPING_LUT_TEXTURE_BINDING_INDEX".into(),
188            3,
189        ));
190        shader_defs.push(ShaderDefVal::UInt(
191            "TONEMAPPING_LUT_SAMPLER_BINDING_INDEX".into(),
192            4,
193        ));
194
195        if let DebandDither::Enabled = key.deband_dither {
196            shader_defs.push("DEBAND_DITHER".into());
197        }
198
199        // Define shader flags depending on the color grading options in use.
200        if key.flags.contains(TonemappingPipelineKeyFlags::HUE_ROTATE) {
201            shader_defs.push("HUE_ROTATE".into());
202        }
203        if key
204            .flags
205            .contains(TonemappingPipelineKeyFlags::WHITE_BALANCE)
206        {
207            shader_defs.push("WHITE_BALANCE".into());
208        }
209        if key
210            .flags
211            .contains(TonemappingPipelineKeyFlags::SECTIONAL_COLOR_GRADING)
212        {
213            shader_defs.push("SECTIONAL_COLOR_GRADING".into());
214        }
215
216        match key.tonemapping {
217            Tonemapping::None | Tonemapping::Linear => {
218                shader_defs.push("TONEMAP_METHOD_LINEAR".into());
219            }
220            Tonemapping::Reinhard => shader_defs.push("TONEMAP_METHOD_REINHARD".into()),
221            Tonemapping::ReinhardLuminance => {
222                shader_defs.push("TONEMAP_METHOD_REINHARD_LUMINANCE".into());
223            }
224            Tonemapping::AcesFitted => shader_defs.push("TONEMAP_METHOD_ACES_FITTED".into()),
225            Tonemapping::AgX => {
226                #[cfg(not(feature = "tonemapping_luts"))]
227                error!(
228                    "AgX tonemapping requires the `tonemapping_luts` feature.
229                    Either enable the `tonemapping_luts` feature for bevy in `Cargo.toml` (recommended),
230                    or use a different `Tonemapping` method for your `Camera2d`/`Camera3d`."
231                );
232                shader_defs.push("TONEMAP_METHOD_AGX".into());
233            }
234            Tonemapping::SomewhatBoringDisplayTransform => {
235                shader_defs.push("TONEMAP_METHOD_SOMEWHAT_BORING_DISPLAY_TRANSFORM".into());
236            }
237            Tonemapping::TonyMcMapface => {
238                #[cfg(not(feature = "tonemapping_luts"))]
239                error!(
240                    "TonyMcMapFace tonemapping requires the `tonemapping_luts` feature.
241                    Either enable the `tonemapping_luts` feature for bevy in `Cargo.toml` (recommended),
242                    or use a different `Tonemapping` method for your `Camera2d`/`Camera3d`."
243                );
244                shader_defs.push("TONEMAP_METHOD_TONY_MC_MAPFACE".into());
245            }
246            Tonemapping::BlenderFilmic => {
247                #[cfg(not(feature = "tonemapping_luts"))]
248                error!(
249                    "BlenderFilmic tonemapping requires the `tonemapping_luts` feature.
250                    Either enable the `tonemapping_luts` feature for bevy in `Cargo.toml` (recommended),
251                    or use a different `Tonemapping` method for your `Camera2d`/`Camera3d`."
252                );
253                shader_defs.push("TONEMAP_METHOD_BLENDER_FILMIC".into());
254            }
255            Tonemapping::KhronosPbrNeutral => shader_defs.push("TONEMAP_METHOD_PBR_NEUTRAL".into()),
256        }
257        RenderPipelineDescriptor {
258            label: Some("tonemapping pipeline".into()),
259            layout: vec![self.texture_bind_group.clone()],
260            vertex: self.fullscreen_shader.to_vertex_state(),
261            fragment: Some(FragmentState {
262                shader: self.fragment_shader.clone(),
263                shader_defs,
264                targets: vec![Some(ColorTargetState {
265                    format: key.target_format,
266                    blend: None,
267                    write_mask: ColorWrites::ALL,
268                })],
269                ..default()
270            }),
271            ..default()
272        }
273    }
274}
275
276pub fn init_tonemapping_pipeline(
277    mut commands: Commands,
278    render_device: Res<RenderDevice>,
279    fullscreen_shader: Res<FullscreenShader>,
280    asset_server: Res<AssetServer>,
281) {
282    let mut entries = DynamicBindGroupLayoutEntries::new_with_indices(
283        ShaderStages::FRAGMENT,
284        (
285            (0, uniform_buffer::<ViewUniform>(true)),
286            (
287                1,
288                texture_2d(TextureSampleType::Float { filterable: false }),
289            ),
290            (2, sampler(SamplerBindingType::NonFiltering)),
291        ),
292    );
293    let lut_layout_entries = get_lut_bind_group_layout_entries();
294    entries = entries.extend_with_indices(((3, lut_layout_entries[0]), (4, lut_layout_entries[1])));
295
296    let tonemap_texture_bind_group =
297        BindGroupLayoutDescriptor::new("tonemapping_hdr_texture_bind_group_layout", &entries);
298
299    let sampler = render_device.create_sampler(&SamplerDescriptor::default());
300
301    commands.insert_resource(TonemappingPipeline {
302        texture_bind_group: tonemap_texture_bind_group,
303        sampler,
304        fullscreen_shader: fullscreen_shader.clone(),
305        fragment_shader: load_embedded_asset!(asset_server.as_ref(), "tonemapping_frag.wesl"),
306    });
307}
308
309#[derive(Component)]
310pub struct ViewTonemappingPipeline(CachedRenderPipelineId);
311
312pub fn prepare_view_tonemapping_pipelines(
313    mut commands: Commands,
314    pipeline_cache: Res<PipelineCache>,
315    mut pipelines: ResMut<SpecializedRenderPipelines<TonemappingPipeline>>,
316    upscaling_pipeline: Res<TonemappingPipeline>,
317    view_targets: Query<
318        (
319            Entity,
320            &ExtractedView,
321            Option<&Tonemapping>,
322            Option<&DebandDither>,
323        ),
324        With<ViewTarget>,
325    >,
326) {
327    for (entity, view, tonemapping, dither) in view_targets.iter() {
328        // As an optimization, we omit parts of the shader that are unneeded.
329        let mut flags = TonemappingPipelineKeyFlags::empty();
330        flags.set(
331            TonemappingPipelineKeyFlags::HUE_ROTATE,
332            view.color_grading.global.hue != 0.0,
333        );
334        flags.set(
335            TonemappingPipelineKeyFlags::WHITE_BALANCE,
336            view.color_grading.global.temperature != 0.0 || view.color_grading.global.tint != 0.0,
337        );
338        flags.set(
339            TonemappingPipelineKeyFlags::SECTIONAL_COLOR_GRADING,
340            view.color_grading
341                .all_sections()
342                .any(|section| *section != default()),
343        );
344
345        let key = TonemappingPipelineKey {
346            target_format: view.target_format,
347            deband_dither: *dither.unwrap_or(&DebandDither::Disabled),
348            tonemapping: *tonemapping.unwrap_or(&Tonemapping::None),
349            flags,
350        };
351        let pipeline = pipelines.specialize(&pipeline_cache, &upscaling_pipeline, key);
352
353        commands
354            .entity(entity)
355            .insert(ViewTonemappingPipeline(pipeline));
356    }
357}
358
359pub fn get_lut_bindings<'a>(
360    images: &'a RenderAssets<GpuImage>,
361    tonemapping_luts: &'a TonemappingLuts,
362    tonemapping: &Tonemapping,
363    fallback_image: &'a FallbackImage,
364) -> (&'a TextureView, &'a Sampler) {
365    let image = match tonemapping {
366        // AgX lut texture used when tonemapping doesn't need a texture since it's very small (32x32x32)
367        Tonemapping::None
368        | Tonemapping::Linear
369        | Tonemapping::Reinhard
370        | Tonemapping::ReinhardLuminance
371        | Tonemapping::AcesFitted
372        | Tonemapping::AgX
373        | Tonemapping::KhronosPbrNeutral
374        | Tonemapping::SomewhatBoringDisplayTransform => &tonemapping_luts.agx,
375        Tonemapping::TonyMcMapface => &tonemapping_luts.tony_mc_mapface,
376        Tonemapping::BlenderFilmic => &tonemapping_luts.blender_filmic,
377    };
378    let lut_image = images.get(image).unwrap_or(&fallback_image.d3);
379    (&lut_image.texture_view, &lut_image.sampler)
380}
381
382pub fn get_lut_bind_group_layout_entries() -> [BindGroupLayoutEntryBuilder; 2] {
383    [
384        texture_3d(TextureSampleType::Float { filterable: true }),
385        sampler(SamplerBindingType::Filtering),
386    ]
387}
388
389#[expect(clippy::allow_attributes, reason = "`dead_code` is not always linted.")]
390#[allow(
391    dead_code,
392    reason = "There is unused code when the `tonemapping_luts` feature is disabled."
393)]
394fn setup_tonemapping_lut_image(bytes: &[u8], image_type: ImageType) -> Image {
395    let image_sampler = ImageSampler::Descriptor(bevy_image::ImageSamplerDescriptor {
396        label: Some("Tonemapping LUT sampler".to_string()),
397        address_mode_u: bevy_image::ImageAddressMode::ClampToEdge,
398        address_mode_v: bevy_image::ImageAddressMode::ClampToEdge,
399        address_mode_w: bevy_image::ImageAddressMode::ClampToEdge,
400        mag_filter: bevy_image::ImageFilterMode::Linear,
401        min_filter: bevy_image::ImageFilterMode::Linear,
402        mipmap_filter: bevy_image::ImageFilterMode::Linear,
403        ..default()
404    });
405    Image::from_buffer(
406        bytes,
407        image_type,
408        CompressedImageFormats::NONE,
409        false,
410        image_sampler,
411        // LUT must be kept in main world for render recovery reasons
412        RenderAssetUsages::default(),
413    )
414    .unwrap()
415}
416
417pub fn lut_placeholder() -> Image {
418    let format = TextureFormat::Rgba8Unorm;
419    let data = vec![255, 0, 255, 255];
420    Image {
421        data: Some(data),
422        data_order: TextureDataOrder::default(),
423        texture_descriptor: TextureDescriptor {
424            size: Extent3d::default(),
425            format,
426            dimension: TextureDimension::D3,
427            label: None,
428            mip_level_count: 1,
429            sample_count: 1,
430            usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
431            view_formats: &[],
432        },
433        sampler: ImageSampler::Default,
434        texture_view_descriptor: None,
435        asset_usage: RenderAssetUsages::RENDER_WORLD,
436        copy_on_resize: false,
437    }
438}