Search across packages, versions, files, declarations, and comments. Use multiple terms to narrow results (AND), and add @vertex, @fragment, or @compute to filter by shader stage.
1#define_import_path bevy_core_pipeline::tonemapping
3#import bevy_render::{
4 view::ColorGrading,
5 color_operations::{hsv_to_rgb, rgb_to_hsv},
6 maths::{PI_2, powsafe},
7}
9#import bevy_core_pipeline::tonemapping_lut_bindings::{
10 dt_lut_texture,
11 dt_lut_sampler,
14// Half the size of the crossfade region between shadows and midtones and
15// between midtones and highlights. This value, 0.1, corresponds to 10% of the
16// gamut on either side of the cutoff point.
17const LEVEL_MARGIN: f32 = 0.1;
19// The inverse reciprocal of twice the above, used when scaling the midtone
20// region.
21const LEVEL_MARGIN_DIV: f32 = 0.5 / LEVEL_MARGIN;
23fn sample_current_lut(p: vec3<f32>) -> vec3<f32> {
24 // Don't include code that will try to sample from LUTs if tonemap method doesn't require it
25 // Allows this file to be imported without necessarily needing the lut texture bindings
26#ifdef TONEMAP_METHOD_AGX
27 return textureSampleLevel(dt_lut_texture, dt_lut_sampler, p, 0.0).rgb;
28#else ifdef TONEMAP_METHOD_TONY_MC_MAPFACE
29 return textureSampleLevel(dt_lut_texture, dt_lut_sampler, p, 0.0).rgb;
30#else ifdef TONEMAP_METHOD_BLENDER_FILMIC
31 return textureSampleLevel(dt_lut_texture, dt_lut_sampler, p, 0.0).rgb;
32#else
33 return vec3(1.0, 0.0, 1.0);
34 #endif
37// --------------------------------------
38// --- SomewhatBoringDisplayTransform ---
39// --------------------------------------
40// By Tomasz Stachowiak
42fn rgb_to_ycbcr(col: vec3<f32>) -> vec3<f32> {
43 let m = mat3x3<f32>(
44 0.2126, 0.7152, 0.0722,
45 -0.1146, -0.3854, 0.5,
46 0.5, -0.4542, -0.0458
47 );
48 return col * m;
51fn ycbcr_to_rgb(col: vec3<f32>) -> vec3<f32> {
52 let m = mat3x3<f32>(
53 1.0, 0.0, 1.5748,
54 1.0, -0.1873, -0.4681,
55 1.0, 1.8556, 0.0
56 );
57 return max(vec3(0.0), col * m);
60fn tonemap_curve(v: f32) -> f32 {
61#ifdef 0
62 // Large linear part in the lows, but compresses highs.
63 float c = v + v * v + 0.5 * v * v * v;
64 return c / (1.0 + c);
65#else
66 return 1.0 - exp(-v);
67#endif
70fn tonemap_curve3_(v: vec3<f32>) -> vec3<f32> {
71 return vec3(tonemap_curve(v.r), tonemap_curve(v.g), tonemap_curve(v.b));
74fn somewhat_boring_display_transform(col: vec3<f32>) -> vec3<f32> {
75 var boring_color = col;
76 let ycbcr = rgb_to_ycbcr(boring_color);
78 let bt = tonemap_curve(length(ycbcr.yz) * 2.4);
79 var desat = max((bt - 0.7) * 0.8, 0.0);
80 desat *= desat;
82 let desat_col = mix(boring_color.rgb, ycbcr.xxx, desat);
84 let tm_luma = tonemap_curve(ycbcr.x);
85 let tm0 = boring_color.rgb * max(0.0, tm_luma / max(1e-5, tonemapping_luminance(boring_color.rgb)));
86 let final_mult = 0.97;
87 let tm1 = tonemap_curve3_(desat_col);
89 boring_color = mix(tm0, tm1, bt * bt);
91 return boring_color * final_mult;
94// ------------------------------------------
95// ------------- Tony McMapface -------------
96// ------------------------------------------
97// By Tomasz Stachowiak
98// https://github.com/h3r2tic/tony-mc-mapface
100const TONY_MC_MAPFACE_LUT_DIMS: f32 = 48.0;
102fn sample_tony_mc_mapface_lut(stimulus: vec3<f32>) -> vec3<f32> {
103 var uv = (stimulus / (stimulus + 1.0)) * (f32(TONY_MC_MAPFACE_LUT_DIMS - 1.0) / f32(TONY_MC_MAPFACE_LUT_DIMS)) + 0.5 / f32(TONY_MC_MAPFACE_LUT_DIMS);
104 return sample_current_lut(saturate(uv)).rgb;
107// ---------------------------------
108// ---------- ACES Fitted ----------
109// ---------------------------------
111// Same base implementation that Godot 4.0 uses for Tonemap ACES.
113// https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl
115// The code in this file was originally written by Stephen Hill (@self_shadow), who deserves all
116// credit for coming up with this fit and implementing it. Buy him a beer next time you see him. :)
118fn RRTAndODTFit(v: vec3<f32>) -> vec3<f32> {
119 let a = v * (v + 0.0245786) - 0.000090537;
120 let b = v * (0.983729 * v + 0.4329510) + 0.238081;
121 return a / b;
124fn ACESFitted(color: vec3<f32>) -> vec3<f32> {
125 var fitted_color = color;
127 // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
128 let rgb_to_rrt = mat3x3<f32>(
129 vec3(0.59719, 0.35458, 0.04823),
130 vec3(0.07600, 0.90834, 0.01566),
131 vec3(0.02840, 0.13383, 0.83777)
132 );
134 // ODT_SAT => XYZ => D60_2_D65 => sRGB
135 let odt_to_rgb = mat3x3<f32>(
136 vec3(1.60475, -0.53108, -0.07367),
137 vec3(-0.10208, 1.10813, -0.00605),
138 vec3(-0.00327, -0.07276, 1.07602)
139 );
141 fitted_color *= rgb_to_rrt;
143 // Apply RRT and ODT
144 fitted_color = RRTAndODTFit(fitted_color);
146 fitted_color *= odt_to_rgb;
148 // Clamp to [0, 1]
149 fitted_color = saturate(fitted_color);
151 return fitted_color;
154// -------------------------------
155// ------------- AgX -------------
156// -------------------------------
157// By Troy Sobotka
158// https://github.com/MrLixm/AgXc
159// https://github.com/sobotka/AgX
161/*
162 Increase color saturation of the given color data.
163 :param color: expected sRGB primaries input
164 :param saturationAmount: expected 0-1 range with 1=neutral, 0=no saturation.
165 -- ref[2] [4]
166*/
167fn saturation(color: vec3<f32>, saturationAmount: f32) -> vec3<f32> {
168 let luma = tonemapping_luminance(color);
169 return mix(vec3(luma), color, vec3(saturationAmount));
172/*
173 Output log domain encoded data.
174 Similar to OCIO lg2 AllocationTransform.
175 ref[0]
176*/
177fn convertOpenDomainToNormalizedLog2_(color: vec3<f32>, minimum_ev: f32, maximum_ev: f32) -> vec3<f32> {
178 let in_midgray = 0.18;
180 // remove negative before log transform
181 var normalized_color = max(vec3(0.0), color);
182 // avoid infinite issue with log -- ref[1]
183 normalized_color = select(normalized_color, 0.00001525878 + normalized_color, normalized_color < vec3<f32>(0.00003051757));
184 normalized_color = clamp(
185 log2(normalized_color / in_midgray),
186 vec3(minimum_ev),
187 vec3(maximum_ev)
188 );
189 let total_exposure = maximum_ev - minimum_ev;
191 return (normalized_color - minimum_ev) / total_exposure;
194// Inverse of above
195fn convertNormalizedLog2ToOpenDomain(color: vec3<f32>, minimum_ev: f32, maximum_ev: f32) -> vec3<f32> {
196 var open_color = color;
197 let in_midgray = 0.18;
198 let total_exposure = maximum_ev - minimum_ev;
200 open_color = (open_color * total_exposure) + minimum_ev;
201 open_color = pow(vec3(2.0), open_color);
202 open_color = open_color * in_midgray;
204 return open_color;
208/*=================
209 Main processes
210=================*/
212// Prepare the data for display encoding. Converted to log domain.
213fn applyAgXLog(Image: vec3<f32>) -> vec3<f32> {
214 var prepared_image = max(vec3(0.0), Image); // clamp negatives
215 let r = dot(prepared_image, vec3(0.84247906, 0.0784336, 0.07922375));
216 let g = dot(prepared_image, vec3(0.04232824, 0.87846864, 0.07916613));
217 let b = dot(prepared_image, vec3(0.04237565, 0.0784336, 0.87914297));
218 prepared_image = vec3(r, g, b);
220 prepared_image = convertOpenDomainToNormalizedLog2_(prepared_image, -10.0, 6.5);
222 prepared_image = clamp(prepared_image, vec3(0.0), vec3(1.0));
223 return prepared_image;
226fn applyLUT3D(Image: vec3<f32>, block_size: f32) -> vec3<f32> {
227 return sample_current_lut(Image * ((block_size - 1.0) / block_size) + 0.5 / block_size).rgb;
230// -------------------------
231// -------------------------
232// -------------------------
234fn sample_blender_filmic_lut(stimulus: vec3<f32>) -> vec3<f32> {
235 let block_size = 64.0;
236 let normalized = saturate(convertOpenDomainToNormalizedLog2_(stimulus, -11.0, 12.0));
237 return applyLUT3D(normalized, block_size);
240// from https://64.github.io/tonemapping/
241// reinhard on RGB oversaturates colors
242fn tonemapping_reinhard(color: vec3<f32>) -> vec3<f32> {
243 return color / (1.0 + color);
246fn tonemapping_reinhard_extended(color: vec3<f32>, max_white: f32) -> vec3<f32> {
247 let numerator = color * (1.0 + (color / vec3<f32>(max_white * max_white)));
248 return numerator / (1.0 + color);
251// luminance coefficients from Rec. 709.
252// https://en.wikipedia.org/wiki/Rec._709
253fn tonemapping_luminance(v: vec3<f32>) -> f32 {
254 return dot(v, vec3<f32>(0.2126, 0.7152, 0.0722));
257fn tonemapping_change_luminance(c_in: vec3<f32>, l_out: f32) -> vec3<f32> {
258 let l_in = tonemapping_luminance(c_in);
259 return c_in * (l_out / l_in);
262fn tonemapping_reinhard_luminance(color: vec3<f32>) -> vec3<f32> {
263 let l_old = tonemapping_luminance(color);
264 let l_new = l_old / (1.0 + l_old);
265 return tonemapping_change_luminance(color, l_new);
268fn rgb_to_srgb_simple(color: vec3<f32>) -> vec3<f32> {
269 return pow(color, vec3<f32>(1.0 / 2.2));
272// Source: Advanced VR Rendering, GDC 2015, Alex Vlachos, Valve, Slide 49
273// https://media.steampowered.com/apps/valve/2015/Alex_Vlachos_Advanced_VR_Rendering_GDC2015.pdf
274fn screen_space_dither(frag_coord: vec2<f32>) -> vec3<f32> {
275 var dither = vec3<f32>(dot(vec2<f32>(171.0, 231.0), frag_coord)).xxx;
276 dither = fract(dither.rgb / vec3<f32>(103.0, 71.0, 97.0));
277 return (dither - 0.5) / 255.0;
280// Performs the "sectional" color grading: i.e. the color grading that applies
281// individually to shadows, midtones, and highlights.
282fn sectional_color_grading(
283 in: vec3<f32>,
284 color_grading: ptr<function, ColorGrading>,
285) -> vec3<f32> {
286 var color = in;
288 // Determine whether the color is a shadow, midtone, or highlight. Colors
289 // close to the edges are considered a mix of both, to avoid sharp
290 // discontinuities. The formulas are taken from Blender's compositor.
292 let level = (color.r + color.g + color.b) / 3.0;
294 // Determine whether this color is a shadow, midtone, or highlight. If close
295 // to the cutoff points, blend between the two to avoid sharp color
296 // discontinuities.
297 var levels = vec3(0.0);
298 let midtone_range = (*color_grading).midtone_range;
299 if (level < midtone_range.x - LEVEL_MARGIN) {
300 levels.x = 1.0;
301 } else if (level < midtone_range.x + LEVEL_MARGIN) {
302 levels.y = ((level - midtone_range.x) * LEVEL_MARGIN_DIV) + 0.5;
303 levels.z = 1.0 - levels.y;
304 } else if (level < midtone_range.y - LEVEL_MARGIN) {
305 levels.y = 1.0;
306 } else if (level < midtone_range.y + LEVEL_MARGIN) {
307 levels.z = ((level - midtone_range.y) * LEVEL_MARGIN_DIV) + 0.5;
308 levels.y = 1.0 - levels.z;
309 } else {
310 levels.z = 1.0;
311 }
313 // Calculate contrast/saturation/gamma/gain/lift.
314 let contrast = dot(levels, (*color_grading).contrast);
315 let saturation = dot(levels, (*color_grading).saturation);
316 let gamma = dot(levels, (*color_grading).gamma);
317 let gain = dot(levels, (*color_grading).gain);
318 let lift = dot(levels, (*color_grading).lift);
320 // Adjust saturation and contrast.
321 let luma = tonemapping_luminance(color);
322 color = luma + saturation * (color - luma);
323 color = 0.5 + (color - 0.5) * contrast;
325 // The [ASC CDL] formula for color correction. Given *i*, an input color, we
326 // have:
327 //
328 // out = (i × s + o)ⁿ
329 //
330 // Following the normal photographic naming convention, *gain* is the *s*
331 // factor, *lift* is the *o* term, and the inverse of *gamma* is the *n*
332 // exponent.
333 //
334 // [ASC CDL]: https://en.wikipedia.org/wiki/ASC_CDL#Combined_Function
335 color = powsafe(color * gain + lift, 1.0 / gamma);
337 // Account for exposure.
338 color = color * powsafe(vec3(2.0), (*color_grading).exposure);
339 return max(color, vec3(0.0));
342fn tone_mapping(in: vec4<f32>, in_color_grading: ColorGrading) -> vec4<f32> {
343 var color = max(in.rgb, vec3(0.0));
344 var color_grading = in_color_grading; // So we can take pointers to it.
346 // Rotate hue if needed, by converting to and from HSV. Remember that hue is
347 // an angle, so it needs to be modulo 2π.
348#ifdef HUE_ROTATE
349 var hsv = rgb_to_hsv(color);
350 hsv.r = (hsv.r + color_grading.hue) % PI_2;
351 color = hsv_to_rgb(hsv);
352#endif
354 // Perform white balance correction. Conveniently, this is a linear
355 // transform. The matrix was pre-calculated from the temperature and tint
356 // values on the CPU.
357#ifdef WHITE_BALANCE
358 color = max(color_grading.balance * color, vec3(0.0));
359#endif
361 // Perform the "sectional" color grading: i.e. the color grading that
362 // applies individually to shadows, midtones, and highlights.
363#ifdef SECTIONAL_COLOR_GRADING
364 color = sectional_color_grading(color, &color_grading);
365#else
366 // If we're not doing sectional color grading, the exposure might still need
367 // to be applied, for example when using auto exposure.
368 color = color * powsafe(vec3(2.0), color_grading.exposure);
369#endif
371 // tone_mapping
372#ifdef TONEMAP_METHOD_NONE
373 color = color;
374#else ifdef TONEMAP_METHOD_REINHARD
375 color = tonemapping_reinhard(color.rgb);
376#else ifdef TONEMAP_METHOD_REINHARD_LUMINANCE
377 color = tonemapping_reinhard_luminance(color.rgb);
378#else ifdef TONEMAP_METHOD_ACES_FITTED
379 color = ACESFitted(color.rgb);
380#else ifdef TONEMAP_METHOD_AGX
381 color = applyAgXLog(color);
382 color = applyLUT3D(color, 32.0);
383#else ifdef TONEMAP_METHOD_SOMEWHAT_BORING_DISPLAY_TRANSFORM
384 color = somewhat_boring_display_transform(color.rgb);
385#else ifdef TONEMAP_METHOD_TONY_MC_MAPFACE
386 color = sample_tony_mc_mapface_lut(color);
387#else ifdef TONEMAP_METHOD_BLENDER_FILMIC
388 color = sample_blender_filmic_lut(color.rgb);
389#endif
391 // Perceptual post tonemapping grading
392 color = saturation(color, color_grading.post_saturation);
394 return vec4(color, in.a);
397// This is an **incredibly crude** approximation of the inverse of the tone mapping function.
398// We assume here that there's a simple linear relationship between the input and output
399// which is not true at all, but useful to at least preserve the overall luminance of colors
400// when sampling from an already tonemapped image. (e.g. for transmissive materials when HDR is off)
401fn approximate_inverse_tone_mapping(in: vec4<f32>, color_grading: ColorGrading) -> vec4<f32> {
402 let out = tone_mapping(in, color_grading);
403 let approximate_ratio = length(in.rgb) / length(out.rgb);
404 return vec4(in.rgb * approximate_ratio, in.a);
Contents