Debian Codegraph @

servers/rendering/renderer_rd/shaders/effects/tonemap.glsl

raw
1 #[vertex]
2
3 #version 450
4
5 #VERSION_DEFINES
6
7 layout(location = 0) out vec2 uv_interp;
8
9 void main() {
10 // old code, ARM driver bug on Mali-GXXx GPUs and Vulkan API 1.3.xxx
11 // https://github.com/godotengine/godot/pull/92817#issuecomment-2168625982
12 //vec2 base_arr[3] = vec2[](vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0));
13 //gl_Position = vec4(base_arr[gl_VertexIndex], 0.0, 1.0);
14 //uv_interp = clamp(gl_Position.xy, vec2(0.0, 0.0), vec2(1.0, 1.0)) * 2.0; // saturate(x) * 2.0
15
16 vec2 vertex_base;
17 if (gl_VertexIndex == 0) {
18 vertex_base = vec2(-1.0, -1.0);
19 } else if (gl_VertexIndex == 1) {
20 vertex_base = vec2(-1.0, 3.0);
21 } else {
22 vertex_base = vec2(3.0, -1.0);
23 }
24 gl_Position = vec4(vertex_base, 0.0, 1.0);
25 uv_interp = clamp(vertex_base, vec2(0.0, 0.0), vec2(1.0, 1.0)) * 2.0; // saturate(x) * 2.0
26 }
27
28 #[fragment]
29
30 #version 450
31
32 #VERSION_DEFINES
33
34 #ifdef USE_MULTIVIEW
35 #extension GL_EXT_multiview : enable
36 #define ViewIndex gl_ViewIndex
37 #endif //USE_MULTIVIEW
38
39 layout(location = 0) in vec2 uv_interp;
40
41 #ifdef USE_MULTIVIEW
42 #define SAMPLER_FORMAT sampler2DArray
43 #else
44 #define SAMPLER_FORMAT sampler2D
45 #endif
46
47 layout(set = 0, binding = 0) uniform SAMPLER_FORMAT source_color;
48 layout(set = 1, binding = 0) uniform sampler2D source_auto_exposure;
49 layout(set = 2, binding = 0) uniform SAMPLER_FORMAT source_glow;
50 layout(set = 2, binding = 1) uniform sampler2D glow_map; // TODO needs multiview support
51
52 #ifdef USE_1D_LUT
53 layout(set = 3, binding = 0) uniform sampler2D source_color_correction;
54 #else
55 layout(set = 3, binding = 0) uniform sampler3D source_color_correction;
56 #endif
57
58 #define FLAG_USE_BCS (1 << 0)
59 #define FLAG_USE_GLOW (1 << 1)
60 #define FLAG_USE_AUTO_EXPOSURE (1 << 2)
61 #define FLAG_USE_COLOR_CORRECTION (1 << 3)
62 #define FLAG_USE_FXAA (1 << 4)
63 #define FLAG_USE_8_BIT_DEBANDING (1 << 5)
64 #define FLAG_CONVERT_TO_SRGB (1 << 6)
65
66 layout(push_constant, std430) uniform Params {
67 vec3 bcs;
68 uint flags;
69
70 vec2 pixel_size;
71 uint tonemapper;
72 uint pad;
73
74 uvec2 glow_texture_size;
75 float glow_intensity;
76 float glow_map_strength;
77
78 uint glow_mode;
79 float glow_levels[7];
80
81 float exposure;
82 float white;
83 float auto_exposure_scale;
84 float luminance_multiplier;
85
86 vec4 tonemapper_params;
87 }
88 params;
89
90 layout(location = 0) out vec4 frag_color;
91
92 // Based on Reinhard's extended formula, see equation 4 in https://doi.org/cjbgrt
93 vec3 tonemap_reinhard(vec3 color) {
94 float white_squared = params.tonemapper_params.x;
95 vec3 white_squared_color = white_squared * color;
96 // Equivalent to color * (1 + color / white_squared) / (1 + color)
97 return (white_squared_color + color * color) / (white_squared_color + white_squared);
98 }
99
100 vec3 tonemap_filmic(vec3 color) {
101 // These constants must match the those in the C++ code that calculates the parameters.
102 // exposure_bias: Input scale (color *= bias, env->white *= bias) to make the brightness consistent with other tonemappers.
103 // Also useful to scale the input to the range that the tonemapper is designed for (some require very high input values).
104 // Has no effect on the curve's general shape or visual properties.
105 const float exposure_bias = 2.0f;
106 const float A = 0.22f * exposure_bias * exposure_bias; // bias baked into constants for performance
107 const float B = 0.30f * exposure_bias;
108 const float C = 0.10f;
109 const float D = 0.20f;
110 const float E = 0.01f;
111 const float F = 0.30f;
112
113 vec3 color_tonemapped = ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E / F;
114
115 return color_tonemapped / params.tonemapper_params.x;
116 }
117
118 // Adapted from https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl
119 // (MIT License).
120 vec3 tonemap_aces(vec3 color) {
121 // These constants must match the those in the C++ code that calculates the parameters.
122 const float exposure_bias = 1.8f;
123 const float A = 0.0245786f;
124 const float B = 0.000090537f;
125 const float C = 0.983729f;
126 const float D = 0.432951f;
127 const float E = 0.238081f;
128
129 // Exposure bias baked into transform to save shader instructions. Equivalent to `color *= exposure_bias`
130 const mat3 rgb_to_rrt = mat3(
131 vec3(0.59719f * exposure_bias, 0.35458f * exposure_bias, 0.04823f * exposure_bias),
132 vec3(0.07600f * exposure_bias, 0.90834f * exposure_bias, 0.01566f * exposure_bias),
133 vec3(0.02840f * exposure_bias, 0.13383f * exposure_bias, 0.83777f * exposure_bias));
134
135 const mat3 odt_to_rgb = mat3(
136 vec3(1.60475f, -0.53108f, -0.07367f),
137 vec3(-0.10208f, 1.10813f, -0.00605f),
138 vec3(-0.00327f, -0.07276f, 1.07602f));
139
140 color *= rgb_to_rrt;
141 vec3 color_tonemapped = (color * (color + A) - B) / (color * (C * color + D) + E);
142 color_tonemapped *= odt_to_rgb;
143
144 return color_tonemapped / params.tonemapper_params.x;
145 }
146
147 // allenwp tonemapping curve; developed for use in the Godot game engine.
148 // Source and details: https://allenwp.com/blog/2025/05/29/allenwp-tonemapping-curve/
149 // Input must be a non-negative linear scene value.
150 vec3 allenwp_curve(vec3 x) {
151 const float output_max_value = 1.0; // SDR always has an output_max_value of 1.0
152
153 // These constants must match the those in the C++ code that calculates the parameters.
154 // 18% "middle gray" is perceptually 50% of the brightness of reference white.
155 const float awp_crossover_point = 0.18;
156 // When output_max_value and/or awp_crossover_point are no longer constant,
157 // awp_shoulder_max can be calculated on the CPU and passed in as params.tonemap_e.
158 const float awp_shoulder_max = output_max_value - awp_crossover_point;
159
160 float awp_contrast = params.tonemapper_params.x;
161 float awp_toe_a = params.tonemapper_params.y;
162 float awp_slope = params.tonemapper_params.z;
163 float awp_w = params.tonemapper_params.w;
164
165 // Reinhard-like shoulder:
166 vec3 s = x - awp_crossover_point;
167 vec3 slope_s = awp_slope * s;
168 s = slope_s * (1.0 + s / awp_w) / (1.0 + (slope_s / awp_shoulder_max));
169 s += awp_crossover_point;
170
171 // Sigmoid power function toe:
172 vec3 t = pow(x, vec3(awp_contrast));
173 t = t / (t + awp_toe_a);
174
175 return mix(s, t, lessThan(x, vec3(awp_crossover_point)));
176 }
177
178 // This is an approximation and simplification of EaryChow's AgX implementation that is used by Blender.
179 // This code is based off of the script that generates the AgX_Base_sRGB.cube LUT that Blender uses.
180 // Source: https://github.com/EaryChow/AgX_LUT_Gen/blob/main/AgXBasesRGB.py
181 // Colorspace transformation source: https://www.colour-science.org:8010/apps/rgb_colourspace_transformation_matrix
182 vec3 tonemap_agx(vec3 color) {
183 // Input color should be non-negative!
184 // Large negative values in one channel and large positive values in other
185 // channels can result in a colour that appears darker and more saturated than
186 // desired after passing it through the inset matrix. For this reason, it is
187 // best to prevent negative input values.
188 // This is done before the Rec. 2020 transform to allow the Rec. 2020
189 // transform to be combined with the AgX inset matrix. This results in a loss
190 // of color information that could be correctly interpreted within the
191 // Rec. 2020 color space as positive RGB values, but is often not worth
192 // the performance cost of an additional matrix multiplication.
193 //
194 // Additionally, this AgX configuration was created subjectively based on
195 // output appearance in the Rec. 709 color gamut, so it is possible that these
196 // matrices will not perform well with non-Rec. 709 output (more testing with
197 // future wide-gamut displays is be needed).
198 // See this comment from the author on the decisions made to create the matrices:
199 // https://github.com/godotengine/godot-proposals/issues/12317#issuecomment-2835824250
200
201 // Combined Rec. 709 to Rec. 2020 and Blender AgX inset matrices:
202 const mat3 rec709_to_rec2020_agx_inset_matrix = mat3(
203 0.544814746488245, 0.140416948464053, 0.0888104196149096,
204 0.373787398372697, 0.754137554567394, 0.178871756420858,
205 0.0813978551390581, 0.105445496968552, 0.732317823964232);
206
207 // Combined inverse AgX outset matrix and Rec. 2020 to Rec. 709 matrices.
208 const mat3 agx_outset_rec2020_to_rec709_matrix = mat3(
209 1.96488741169489, -0.299313364904742, -0.164352742528393,
210 -0.855988495690215, 1.32639796461980, -0.238183969428088,
211 -0.108898916004672, -0.0270845997150571, 1.40253671195648);
212
213 const float output_max_value = 1.0; // SDR always has an output_max_value of 1.0
214
215 // Apply inset matrix.
216 color = rec709_to_rec2020_agx_inset_matrix * color;
217
218 // Use the allenwp tonemapping curve to match the Blender AgX curve while
219 // providing stability across all variable dyanimc range (SDR, HDR, EDR).
220 color = allenwp_curve(color);
221
222 // Clipping to output_max_value is required to address a cyan colour that occurs
223 // with very bright inputs.
224 color = min(vec3(output_max_value), color);
225
226 // Apply outset to make the result more chroma-laden and then go back to Rec. 709.
227 color = agx_outset_rec2020_to_rec709_matrix * color;
228
229 // Blender's lusRGB.compensate_low_side is too complex for this shader, so
230 // simply return the color, even if it has negative components. These negative
231 // components may be useful for subsequent color adjustments.
232 return color;
233 }
234
235 vec3 linear_to_srgb(vec3 color) {
236 const vec3 a = vec3(0.055f);
237 return mix((vec3(1.0f) + a) * pow(color.rgb, vec3(1.0f / 2.4f)) - a, 12.92f * color.rgb, lessThan(color.rgb, vec3(0.0031308f)));
238 }
239
240 vec3 srgb_to_linear(vec3 color) {
241 const vec3 a = vec3(0.055f);
242 return mix(pow((color.rgb + a) * (1.0f / (vec3(1.0f) + a)), vec3(2.4f)), color.rgb * (1.0f / 12.92f), lessThan(color.rgb, vec3(0.04045f)));
243 }
244
245 #define TONEMAPPER_LINEAR 0
246 #define TONEMAPPER_REINHARD 1
247 #define TONEMAPPER_FILMIC 2
248 #define TONEMAPPER_ACES 3
249 #define TONEMAPPER_AGX 4
250
251 vec3 apply_tonemapping(vec3 color) { // inputs are LINEAR
252 if (params.tonemapper == TONEMAPPER_LINEAR) {
253 return color;
254 }
255
256 // Ensure color values passed to tonemappers are positive.
257 // They can be negative in the case of negative lights, which leads to undesired behavior.
258 color = max(vec3(0.0), color);
259
260 if (params.tonemapper == TONEMAPPER_REINHARD) {
261 return tonemap_reinhard(color);
262 } else if (params.tonemapper == TONEMAPPER_FILMIC) {
263 return tonemap_filmic(color);
264 } else if (params.tonemapper == TONEMAPPER_ACES) {
265 return tonemap_aces(color);
266 } else { // TONEMAPPER_AGX
267 return tonemap_agx(color);
268 }
269 }
270
271 #ifdef USE_GLOW_FILTER_BICUBIC
272 // w0, w1, w2, and w3 are the four cubic B-spline basis functions
273 float w0(float a) {
274 return (1.0f / 6.0f) * (a * (a * (-a + 3.0f) - 3.0f) + 1.0f);
275 }
276
277 float w1(float a) {
278 return (1.0f / 6.0f) * (a * a * (3.0f * a - 6.0f) + 4.0f);
279 }
280
281 float w2(float a) {
282 return (1.0f / 6.0f) * (a * (a * (-3.0f * a + 3.0f) + 3.0f) + 1.0f);
283 }
284
285 float w3(float a) {
286 return (1.0f / 6.0f) * (a * a * a);
287 }
288
289 // g0 and g1 are the two amplitude functions
290 float g0(float a) {
291 return w0(a) + w1(a);
292 }
293
294 float g1(float a) {
295 return w2(a) + w3(a);
296 }
297
298 // h0 and h1 are the two offset functions
299 float h0(float a) {
300 return -1.0f + w1(a) / (w0(a) + w1(a));
301 }
302
303 float h1(float a) {
304 return 1.0f + w3(a) / (w2(a) + w3(a));
305 }
306
307 #ifdef USE_MULTIVIEW
308 vec4 texture2D_bicubic(sampler2DArray tex, vec2 uv, int p_lod) {
309 float lod = float(p_lod);
310 vec2 tex_size = vec2(params.glow_texture_size >> p_lod);
311 vec2 pixel_size = vec2(1.0f) / tex_size;
312
313 uv = uv * tex_size + vec2(0.5f);
314
315 vec2 iuv = floor(uv);
316 vec2 fuv = fract(uv);
317
318 float g0x = g0(fuv.x);
319 float g1x = g1(fuv.x);
320 float h0x = h0(fuv.x);
321 float h1x = h1(fuv.x);
322 float h0y = h0(fuv.y);
323 float h1y = h1(fuv.y);
324
325 vec3 p0 = vec3((vec2(iuv.x + h0x, iuv.y + h0y) - vec2(0.5f)) * pixel_size, ViewIndex);
326 vec3 p1 = vec3((vec2(iuv.x + h1x, iuv.y + h0y) - vec2(0.5f)) * pixel_size, ViewIndex);
327 vec3 p2 = vec3((vec2(iuv.x + h0x, iuv.y + h1y) - vec2(0.5f)) * pixel_size, ViewIndex);
328 vec3 p3 = vec3((vec2(iuv.x + h1x, iuv.y + h1y) - vec2(0.5f)) * pixel_size, ViewIndex);
329
330 return (g0(fuv.y) * (g0x * textureLod(tex, p0, lod) + g1x * textureLod(tex, p1, lod))) +
331 (g1(fuv.y) * (g0x * textureLod(tex, p2, lod) + g1x * textureLod(tex, p3, lod)));
332 }
333
334 #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2D_bicubic(m_tex, m_uv, m_lod)
335 #else // USE_MULTIVIEW
336
337 vec4 texture2D_bicubic(sampler2D tex, vec2 uv, int p_lod) {
338 float lod = float(p_lod);
339 vec2 tex_size = vec2(params.glow_texture_size >> p_lod);
340 vec2 pixel_size = vec2(1.0f) / tex_size;
341
342 uv = uv * tex_size + vec2(0.5f);
343
344 vec2 iuv = floor(uv);
345 vec2 fuv = fract(uv);
346
347 float g0x = g0(fuv.x);
348 float g1x = g1(fuv.x);
349 float h0x = h0(fuv.x);
350 float h1x = h1(fuv.x);
351 float h0y = h0(fuv.y);
352 float h1y = h1(fuv.y);
353
354 vec2 p0 = (vec2(iuv.x + h0x, iuv.y + h0y) - vec2(0.5f)) * pixel_size;
355 vec2 p1 = (vec2(iuv.x + h1x, iuv.y + h0y) - vec2(0.5f)) * pixel_size;
356 vec2 p2 = (vec2(iuv.x + h0x, iuv.y + h1y) - vec2(0.5f)) * pixel_size;
357 vec2 p3 = (vec2(iuv.x + h1x, iuv.y + h1y) - vec2(0.5f)) * pixel_size;
358
359 return (g0(fuv.y) * (g0x * textureLod(tex, p0, lod) + g1x * textureLod(tex, p1, lod))) +
360 (g1(fuv.y) * (g0x * textureLod(tex, p2, lod) + g1x * textureLod(tex, p3, lod)));
361 }
362
363 #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2D_bicubic(m_tex, m_uv, m_lod)
364 #endif // !USE_MULTIVIEW
365
366 #else // USE_GLOW_FILTER_BICUBIC
367
368 #ifdef USE_MULTIVIEW
369 #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) textureLod(m_tex, vec3(m_uv, ViewIndex), float(m_lod))
370 #else // USE_MULTIVIEW
371 #define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) textureLod(m_tex, m_uv, float(m_lod))
372 #endif // !USE_MULTIVIEW
373
374 #endif // !USE_GLOW_FILTER_BICUBIC
375
376 vec3 gather_glow(SAMPLER_FORMAT tex, vec2 uv) { // sample all selected glow levels
377
378 vec3 glow = vec3(0.0f);
379
380 if (params.glow_levels[0] > 0.0001) {
381 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 0).rgb * params.glow_levels[0];
382 }
383
384 if (params.glow_levels[1] > 0.0001) {
385 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 1).rgb * params.glow_levels[1];
386 }
387
388 if (params.glow_levels[2] > 0.0001) {
389 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 2).rgb * params.glow_levels[2];
390 }
391
392 if (params.glow_levels[3] > 0.0001) {
393 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 3).rgb * params.glow_levels[3];
394 }
395
396 if (params.glow_levels[4] > 0.0001) {
397 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 4).rgb * params.glow_levels[4];
398 }
399
400 if (params.glow_levels[5] > 0.0001) {
401 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 5).rgb * params.glow_levels[5];
402 }
403
404 if (params.glow_levels[6] > 0.0001) {
405 glow += GLOW_TEXTURE_SAMPLE(tex, uv, 6).rgb * params.glow_levels[6];
406 }
407
408 glow = glow * params.luminance_multiplier;
409
410 return glow;
411 }
412
413 #define GLOW_MODE_ADD 0
414 #define GLOW_MODE_SCREEN 1
415 #define GLOW_MODE_SOFTLIGHT 2
416 #define GLOW_MODE_REPLACE 3
417 #define GLOW_MODE_MIX 4
418
419 // Applies glow using the selected blending mode. Does not handle the mix blend mode.
420 vec3 apply_glow(vec3 color, vec3 glow, float white) {
421 if (params.glow_mode == GLOW_MODE_ADD) {
422 return color + glow;
423 } else if (params.glow_mode == GLOW_MODE_SCREEN) {
424 // Glow cannot be above 1.0 after normalizing and should be non-negative
425 // to produce expected results. It is possible that glow can be negative
426 // if negative lights were used in the scene.
427 // We clamp to white because glow will be normalized to this range.
428 // Note: white cannot be smaller than the maximum output value.
429 glow.rgb = clamp(glow.rgb, 0.0, white);
430
431 // Normalize to white range.
432 //glow.rgb /= white;
433 //color.rgb /= white;
434 //color.rgb = (color.rgb + glow.rgb) - (color.rgb * glow.rgb);
435 // Expand back to original range.
436 //color.rgb *= white;
437
438 // The following is a mathematically simplified version of the above.
439 color.rgb = color.rgb + glow.rgb - (color.rgb * glow.rgb / white);
440
441 return color;
442 } else if (params.glow_mode == GLOW_MODE_SOFTLIGHT) {
443 // Glow cannot be above 1.0 should be non-negative to produce
444 // expected results. It is possible that glow can be negative
445 // if negative lights were used in the scene.
446 // Note: This approach causes a discontinuity with scene values
447 // at 1.0, but because this glow should have its strongest influence
448 // anchored at 0.25 there is no way around this.
449 glow.rgb = clamp(glow.rgb, 0.0, 1.0);
450
451 color.r = color.r > 1.0 ? color.r : color.r + glow.r * ((color.r <= 0.25f ? ((16.0f * color.r - 12.0f) * color.r + 4.0f) * color.r : sqrt(color.r)) - color.r);
452 color.g = color.g > 1.0 ? color.g : color.g + glow.g * ((color.g <= 0.25f ? ((16.0f * color.g - 12.0f) * color.g + 4.0f) * color.g : sqrt(color.g)) - color.g);
453 color.b = color.b > 1.0 ? color.b : color.b + glow.b * ((color.b <= 0.25f ? ((16.0f * color.b - 12.0f) * color.b + 4.0f) * color.b : sqrt(color.b)) - color.b);
454
455 return color;
456 } else { //replace
457 return glow;
458 }
459 }
460
461 #ifdef USE_1D_LUT
462 vec3 apply_color_correction(vec3 color) {
463 color.r = texture(source_color_correction, vec2(color.r, 0.0f)).r;
464 color.g = texture(source_color_correction, vec2(color.g, 0.0f)).g;
465 color.b = texture(source_color_correction, vec2(color.b, 0.0f)).b;
466 return color;
467 }
468 #else
469 vec3 apply_color_correction(vec3 color) {
470 return textureLod(source_color_correction, color, 0.0).rgb;
471 }
472 #endif
473
474 // FXAA 3.11 compact, Ported from https://github.com/kosua20/Rendu/blob/master/resources/common/shaders/screens/fxaa.frag
475 ///////////////////////////////////////////////////////////////////////////////////
476 // MIT License
477 //
478 // Copyright (c) 2017 Simon Rodriguez
479 //
480 // Permission is hereby granted, free of charge, to any person obtaining a copy
481 // of this software and associated documentation files (the "Software"), to deal
482 // in the Software without restriction, including without limitation the rights
483 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
484 // copies of the Software, and to permit persons to whom the Software is
485 // furnished to do so, subject to the following conditions:
486 //
487 // The above copyright notice and this permission notice shall be included in all
488 // copies or substantial portions of the Software.
489 //
490 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
491 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
492 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
493 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
494 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
495 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
496 // SOFTWARE.
497 ///////////////////////////////////////////////////////////////////////////////////
498
499 // Nvidia Original FXAA 3.11 License
500 //----------------------------------------------------------------------------------
501 // File: es3-kepler\FXAA/FXAA3_11.h
502 // SDK Version: v3.00
503 // Email: [email protected]
504 // Site: http://developer.nvidia.com/
505 //
506 // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
507 //
508 // Redistribution and use in source and binary forms, with or without
509 // modification, are permitted provided that the following conditions
510 // are met:
511 // * Redistributions of source code must retain the above copyright
512 // notice, this list of conditions and the following disclaimer.
513 // * Redistributions in binary form must reproduce the above copyright
514 // notice, this list of conditions and the following disclaimer in the
515 // documentation and/or other materials provided with the distribution.
516 // * Neither the name of NVIDIA CORPORATION nor the names of its
517 // contributors may be used to endorse or promote products derived
518 // from this software without specific prior written permission.
519 //
520 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
521 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
522 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
523 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
524 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
525 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
526 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
527 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
528 // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
529 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
530 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
531 //
532 //----------------------------------------------------------------------------------
533 //
534 // NVIDIA FXAA 3.11 by TIMOTHY LOTTES
535 //
536 //----------------------------------------------------------------------------------
537
538 float QUALITY(float q) {
539 return (q < 5 ? 1.0 : (q > 5 ? (q < 10 ? 2.0 : (q < 11 ? 4.0 : 8.0)) : 1.5));
540 }
541
542 float rgb2luma(vec3 rgb) {
543 return sqrt(dot(rgb, vec3(0.299, 0.587, 0.114)));
544 }
545
546 vec3 do_fxaa(vec3 color, float exposure, vec2 uv_interp) {
547 const float EDGE_THRESHOLD_MIN = 0.0312;
548 const float EDGE_THRESHOLD_MAX = 0.125;
549 const int ITERATIONS = 12;
550 const float SUBPIXEL_QUALITY = 0.75;
551
552 #ifdef USE_MULTIVIEW
553 float lumaUp = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(0, 1)).xyz * exposure * params.luminance_multiplier);
554 float lumaDown = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(0, -1)).xyz * exposure * params.luminance_multiplier);
555 float lumaLeft = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(-1, 0)).xyz * exposure * params.luminance_multiplier);
556 float lumaRight = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(1, 0)).xyz * exposure * params.luminance_multiplier);
557
558 float lumaCenter = rgb2luma(color);
559
560 float lumaMin = min(lumaCenter, min(min(lumaUp, lumaDown), min(lumaLeft, lumaRight)));
561 float lumaMax = max(lumaCenter, max(max(lumaUp, lumaDown), max(lumaLeft, lumaRight)));
562
563 float lumaRange = lumaMax - lumaMin;
564
565 if (lumaRange < max(EDGE_THRESHOLD_MIN, lumaMax * EDGE_THRESHOLD_MAX)) {
566 return color;
567 }
568
569 float lumaDownLeft = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(-1, -1)).xyz * exposure * params.luminance_multiplier);
570 float lumaUpRight = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(1, 1)).xyz * exposure * params.luminance_multiplier);
571 float lumaUpLeft = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(-1, 1)).xyz * exposure * params.luminance_multiplier);
572 float lumaDownRight = rgb2luma(textureLodOffset(source_color, vec3(uv_interp, ViewIndex), 0.0, ivec2(1, -1)).xyz * exposure * params.luminance_multiplier);
573
574 float lumaDownUp = lumaDown + lumaUp;
575 float lumaLeftRight = lumaLeft + lumaRight;
576
577 float lumaLeftCorners = lumaDownLeft + lumaUpLeft;
578 float lumaDownCorners = lumaDownLeft + lumaDownRight;
579 float lumaRightCorners = lumaDownRight + lumaUpRight;
580 float lumaUpCorners = lumaUpRight + lumaUpLeft;
581
582 float edgeHorizontal = abs(-2.0 * lumaLeft + lumaLeftCorners) + abs(-2.0 * lumaCenter + lumaDownUp) * 2.0 + abs(-2.0 * lumaRight + lumaRightCorners);
583 float edgeVertical = abs(-2.0 * lumaUp + lumaUpCorners) + abs(-2.0 * lumaCenter + lumaLeftRight) * 2.0 + abs(-2.0 * lumaDown + lumaDownCorners);
584
585 bool isHorizontal = (edgeHorizontal >= edgeVertical);
586
587 float stepLength = isHorizontal ? params.pixel_size.y : params.pixel_size.x;
588
589 float luma1 = isHorizontal ? lumaDown : lumaLeft;
590 float luma2 = isHorizontal ? lumaUp : lumaRight;
591 float gradient1 = luma1 - lumaCenter;
592 float gradient2 = luma2 - lumaCenter;
593
594 bool is1Steepest = abs(gradient1) >= abs(gradient2);
595
596 float gradientScaled = 0.25 * max(abs(gradient1), abs(gradient2));
597
598 float lumaLocalAverage = 0.0;
599 if (is1Steepest) {
600 stepLength = -stepLength;
601 lumaLocalAverage = 0.5 * (luma1 + lumaCenter);
602 } else {
603 lumaLocalAverage = 0.5 * (luma2 + lumaCenter);
604 }
605
606 vec2 currentUv = uv_interp;
607 if (isHorizontal) {
608 currentUv.y += stepLength * 0.5;
609 } else {
610 currentUv.x += stepLength * 0.5;
611 }
612
613 vec2 offset = isHorizontal ? vec2(params.pixel_size.x, 0.0) : vec2(0.0, params.pixel_size.y);
614 vec3 uv1 = vec3(currentUv - offset * QUALITY(0), ViewIndex);
615 vec3 uv2 = vec3(currentUv + offset * QUALITY(0), ViewIndex);
616
617 float lumaEnd1 = rgb2luma(textureLod(source_color, uv1, 0.0).xyz * exposure * params.luminance_multiplier);
618 float lumaEnd2 = rgb2luma(textureLod(source_color, uv2, 0.0).xyz * exposure * params.luminance_multiplier);
619 lumaEnd1 -= lumaLocalAverage;
620 lumaEnd2 -= lumaLocalAverage;
621
622 bool reached1 = abs(lumaEnd1) >= gradientScaled;
623 bool reached2 = abs(lumaEnd2) >= gradientScaled;
624 bool reachedBoth = reached1 && reached2;
625
626 if (!reached1) {
627 uv1 -= vec3(offset * QUALITY(1), 0.0);
628 }
629 if (!reached2) {
630 uv2 += vec3(offset * QUALITY(1), 0.0);
631 }
632
633 if (!reachedBoth) {
634 for (int i = 2; i < ITERATIONS; i++) {
635 if (!reached1) {
636 lumaEnd1 = rgb2luma(textureLod(source_color, uv1, 0.0).xyz * exposure * params.luminance_multiplier);
637 lumaEnd1 = lumaEnd1 - lumaLocalAverage;
638 }
639 if (!reached2) {
640 lumaEnd2 = rgb2luma(textureLod(source_color, uv2, 0.0).xyz * exposure * params.luminance_multiplier);
641 lumaEnd2 = lumaEnd2 - lumaLocalAverage;
642 }
643 reached1 = abs(lumaEnd1) >= gradientScaled;
644 reached2 = abs(lumaEnd2) >= gradientScaled;
645 reachedBoth = reached1 && reached2;
646 if (!reached1) {
647 uv1 -= vec3(offset * QUALITY(i), 0.0);
648 }
649 if (!reached2) {
650 uv2 += vec3(offset * QUALITY(i), 0.0);
651 }
652 if (reachedBoth) {
653 break;
654 }
655 }
656 }
657
658 float distance1 = isHorizontal ? (uv_interp.x - uv1.x) : (uv_interp.y - uv1.y);
659 float distance2 = isHorizontal ? (uv2.x - uv_interp.x) : (uv2.y - uv_interp.y);
660
661 bool isDirection1 = distance1 < distance2;
662 float distanceFinal = min(distance1, distance2);
663
664 float edgeThickness = (distance1 + distance2);
665
666 bool isLumaCenterSmaller = lumaCenter < lumaLocalAverage;
667
668 bool correctVariation1 = (lumaEnd1 < 0.0) != isLumaCenterSmaller;
669 bool correctVariation2 = (lumaEnd2 < 0.0) != isLumaCenterSmaller;
670
671 bool correctVariation = isDirection1 ? correctVariation1 : correctVariation2;
672
673 float pixelOffset = -distanceFinal / edgeThickness + 0.5;
674
675 float finalOffset = correctVariation ? pixelOffset : 0.0;
676
677 float lumaAverage = (1.0 / 12.0) * (2.0 * (lumaDownUp + lumaLeftRight) + lumaLeftCorners + lumaRightCorners);
678
679 float subPixelOffset1 = clamp(abs(lumaAverage - lumaCenter) / lumaRange, 0.0, 1.0);
680 float subPixelOffset2 = (-2.0 * subPixelOffset1 + 3.0) * subPixelOffset1 * subPixelOffset1;
681
682 float subPixelOffsetFinal = subPixelOffset2 * subPixelOffset2 * SUBPIXEL_QUALITY;
683
684 finalOffset = max(finalOffset, subPixelOffsetFinal);
685
686 vec3 finalUv = vec3(uv_interp, ViewIndex);
687 if (isHorizontal) {
688 finalUv.y += finalOffset * stepLength;
689 } else {
690 finalUv.x += finalOffset * stepLength;
691 }
692
693 vec3 finalColor = textureLod(source_color, finalUv, 0.0).xyz * exposure * params.luminance_multiplier;
694 return finalColor;
695
696 #else
697 float lumaUp = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(0, 1)).xyz * exposure * params.luminance_multiplier);
698 float lumaDown = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(0, -1)).xyz * exposure * params.luminance_multiplier);
699 float lumaLeft = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(-1, 0)).xyz * exposure * params.luminance_multiplier);
700 float lumaRight = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(1, 0)).xyz * exposure * params.luminance_multiplier);
701
702 float lumaCenter = rgb2luma(color);
703
704 float lumaMin = min(lumaCenter, min(min(lumaUp, lumaDown), min(lumaLeft, lumaRight)));
705 float lumaMax = max(lumaCenter, max(max(lumaUp, lumaDown), max(lumaLeft, lumaRight)));
706
707 float lumaRange = lumaMax - lumaMin;
708
709 if (lumaRange < max(EDGE_THRESHOLD_MIN, lumaMax * EDGE_THRESHOLD_MAX)) {
710 return color;
711 }
712
713 float lumaDownLeft = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(-1, -1)).xyz * exposure * params.luminance_multiplier);
714 float lumaUpRight = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(1, 1)).xyz * exposure * params.luminance_multiplier);
715 float lumaUpLeft = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(-1, 1)).xyz * exposure * params.luminance_multiplier);
716 float lumaDownRight = rgb2luma(textureLodOffset(source_color, uv_interp, 0.0, ivec2(1, -1)).xyz * exposure * params.luminance_multiplier);
717
718 float lumaDownUp = lumaDown + lumaUp;
719 float lumaLeftRight = lumaLeft + lumaRight;
720
721 float lumaLeftCorners = lumaDownLeft + lumaUpLeft;
722 float lumaDownCorners = lumaDownLeft + lumaDownRight;
723 float lumaRightCorners = lumaDownRight + lumaUpRight;
724 float lumaUpCorners = lumaUpRight + lumaUpLeft;
725
726 float edgeHorizontal = abs(-2.0 * lumaLeft + lumaLeftCorners) + abs(-2.0 * lumaCenter + lumaDownUp) * 2.0 + abs(-2.0 * lumaRight + lumaRightCorners);
727 float edgeVertical = abs(-2.0 * lumaUp + lumaUpCorners) + abs(-2.0 * lumaCenter + lumaLeftRight) * 2.0 + abs(-2.0 * lumaDown + lumaDownCorners);
728
729 bool isHorizontal = (edgeHorizontal >= edgeVertical);
730
731 float stepLength = isHorizontal ? params.pixel_size.y : params.pixel_size.x;
732
733 float luma1 = isHorizontal ? lumaDown : lumaLeft;
734 float luma2 = isHorizontal ? lumaUp : lumaRight;
735 float gradient1 = luma1 - lumaCenter;
736 float gradient2 = luma2 - lumaCenter;
737
738 bool is1Steepest = abs(gradient1) >= abs(gradient2);
739
740 float gradientScaled = 0.25 * max(abs(gradient1), abs(gradient2));
741
742 float lumaLocalAverage = 0.0;
743 if (is1Steepest) {
744 stepLength = -stepLength;
745 lumaLocalAverage = 0.5 * (luma1 + lumaCenter);
746 } else {
747 lumaLocalAverage = 0.5 * (luma2 + lumaCenter);
748 }
749
750 vec2 currentUv = uv_interp;
751 if (isHorizontal) {
752 currentUv.y += stepLength * 0.5;
753 } else {
754 currentUv.x += stepLength * 0.5;
755 }
756
757 vec2 offset = isHorizontal ? vec2(params.pixel_size.x, 0.0) : vec2(0.0, params.pixel_size.y);
758 vec2 uv1 = currentUv - offset * QUALITY(0);
759 vec2 uv2 = currentUv + offset * QUALITY(0);
760
761 float lumaEnd1 = rgb2luma(textureLod(source_color, uv1, 0.0).xyz * exposure * params.luminance_multiplier);
762 float lumaEnd2 = rgb2luma(textureLod(source_color, uv2, 0.0).xyz * exposure * params.luminance_multiplier);
763 lumaEnd1 -= lumaLocalAverage;
764 lumaEnd2 -= lumaLocalAverage;
765
766 bool reached1 = abs(lumaEnd1) >= gradientScaled;
767 bool reached2 = abs(lumaEnd2) >= gradientScaled;
768 bool reachedBoth = reached1 && reached2;
769
770 if (!reached1) {
771 uv1 -= offset * QUALITY(1);
772 }
773 if (!reached2) {
774 uv2 += offset * QUALITY(1);
775 }
776
777 if (!reachedBoth) {
778 for (int i = 2; i < ITERATIONS; i++) {
779 if (!reached1) {
780 lumaEnd1 = rgb2luma(textureLod(source_color, uv1, 0.0).xyz * exposure * params.luminance_multiplier);
781 lumaEnd1 = lumaEnd1 - lumaLocalAverage;
782 }
783 if (!reached2) {
784 lumaEnd2 = rgb2luma(textureLod(source_color, uv2, 0.0).xyz * exposure * params.luminance_multiplier);
785 lumaEnd2 = lumaEnd2 - lumaLocalAverage;
786 }
787 reached1 = abs(lumaEnd1) >= gradientScaled;
788 reached2 = abs(lumaEnd2) >= gradientScaled;
789 reachedBoth = reached1 && reached2;
790 if (!reached1) {
791 uv1 -= offset * QUALITY(i);
792 }
793 if (!reached2) {
794 uv2 += offset * QUALITY(i);
795 }
796 if (reachedBoth) {
797 break;
798 }
799 }
800 }
801
802 float distance1 = isHorizontal ? (uv_interp.x - uv1.x) : (uv_interp.y - uv1.y);
803 float distance2 = isHorizontal ? (uv2.x - uv_interp.x) : (uv2.y - uv_interp.y);
804
805 bool isDirection1 = distance1 < distance2;
806 float distanceFinal = min(distance1, distance2);
807
808 float edgeThickness = (distance1 + distance2);
809
810 bool isLumaCenterSmaller = lumaCenter < lumaLocalAverage;
811
812 bool correctVariation1 = (lumaEnd1 < 0.0) != isLumaCenterSmaller;
813 bool correctVariation2 = (lumaEnd2 < 0.0) != isLumaCenterSmaller;
814
815 bool correctVariation = isDirection1 ? correctVariation1 : correctVariation2;
816
817 float pixelOffset = -distanceFinal / edgeThickness + 0.5;
818
819 float finalOffset = correctVariation ? pixelOffset : 0.0;
820
821 float lumaAverage = (1.0 / 12.0) * (2.0 * (lumaDownUp + lumaLeftRight) + lumaLeftCorners + lumaRightCorners);
822
823 float subPixelOffset1 = clamp(abs(lumaAverage - lumaCenter) / lumaRange, 0.0, 1.0);
824 float subPixelOffset2 = (-2.0 * subPixelOffset1 + 3.0) * subPixelOffset1 * subPixelOffset1;
825
826 float subPixelOffsetFinal = subPixelOffset2 * subPixelOffset2 * SUBPIXEL_QUALITY;
827
828 finalOffset = max(finalOffset, subPixelOffsetFinal);
829
830 vec2 finalUv = uv_interp;
831 if (isHorizontal) {
832 finalUv.y += finalOffset * stepLength;
833 } else {
834 finalUv.x += finalOffset * stepLength;
835 }
836
837 vec3 finalColor = textureLod(source_color, finalUv, 0.0).xyz * exposure * params.luminance_multiplier;
838 return finalColor;
839
840 #endif
841 }
842
843 // From https://alex.vlachos.com/graphics/Alex_Vlachos_Advanced_VR_Rendering_GDC2015.pdf
844 // and https://www.shadertoy.com/view/MslGR8 (5th one starting from the bottom)
845 // NOTE: `frag_coord` is in pixels (i.e. not normalized UV).
846 // This dithering must be applied after encoding changes (linear/nonlinear) have been applied
847 // as the final step before quantization from floating point to integer values.
848 vec3 screen_space_dither(vec2 frag_coord, float bit_alignment_diviser) {
849 // Iestyn's RGB dither (7 asm instructions) from Portal 2 X360, slightly modified for VR.
850 // Removed the time component to avoid passing time into this shader.
851 vec3 dither = vec3(dot(vec2(171.0, 231.0), frag_coord));
852 dither.rgb = fract(dither.rgb / vec3(103.0, 71.0, 97.0));
853
854 // Subtract 0.5 to avoid slightly brightening the whole viewport.
855 // Use a dither strength of 100% rather than the 37.5% suggested by the original source.
856 return (dither.rgb - 0.5) / bit_alignment_diviser;
857 }
858
859 void main() {
860 #ifdef USE_MULTIVIEW
861 vec4 color = textureLod(source_color, vec3(uv_interp, ViewIndex), 0.0f);
862 #else
863 vec4 color = textureLod(source_color, uv_interp, 0.0f);
864 #endif
865 color.rgb *= params.luminance_multiplier;
866
867 // Exposure
868
869 float exposure = params.exposure;
870
871 if (bool(params.flags & FLAG_USE_AUTO_EXPOSURE)) {
872 exposure *= 1.0 / (texelFetch(source_auto_exposure, ivec2(0, 0), 0).r * params.luminance_multiplier / params.auto_exposure_scale);
873 }
874
875 color.rgb *= exposure;
876
877 // Single-pass FXAA and pre-tonemap glow.
878 if (bool(params.flags & FLAG_USE_FXAA)) {
879 // FXAA must be performed before glow to preserve the "bleed" effect of glow.
880 color.rgb = do_fxaa(color.rgb, exposure, uv_interp);
881 }
882
883 if (bool(params.flags & FLAG_USE_GLOW) && params.glow_mode != GLOW_MODE_SOFTLIGHT) {
884 vec3 glow = gather_glow(source_glow, uv_interp) * params.glow_intensity;
885 if (params.glow_map_strength > 0.001) {
886 glow = mix(glow, texture(glow_map, uv_interp).rgb * glow, params.glow_map_strength);
887 }
888
889 if (params.glow_mode == GLOW_MODE_MIX) {
890 color.rgb = color.rgb * (1.0 - params.glow_intensity) + glow;
891 } else {
892 color.rgb = apply_glow(color.rgb, glow, params.white);
893 }
894 }
895
896 // Tonemap to lower dynamic range.
897
898 color.rgb = apply_tonemapping(color.rgb);
899
900 // Post-tonemap glow.
901
902 if (bool(params.flags & FLAG_USE_GLOW) && params.glow_mode == GLOW_MODE_SOFTLIGHT) {
903 // Apply soft light after tonemapping to mitigate the issue of discontinuity
904 // at 1.0 and higher. This makes the issue only appear with HDR output that
905 // can exceed a 1.0 output value.
906 vec3 glow = gather_glow(source_glow, uv_interp) * params.glow_intensity;
907 if (params.glow_map_strength > 0.001) {
908 glow = mix(glow, texture(glow_map, uv_interp).rgb * glow, params.glow_map_strength);
909 }
910 glow = apply_tonemapping(glow);
911 color.rgb = apply_glow(color.rgb, glow, params.white);
912 }
913
914 // Additional effects.
915
916 if (bool(params.flags & FLAG_USE_BCS)) {
917 // Apply brightness:
918 // Apply to relative luminance. This ensures that the hue and saturation of
919 // colors is not affected by the adjustment, but requires the multiplication
920 // to be performed on linear-encoded values.
921 color.rgb = color.rgb * params.bcs.x;
922
923 color.rgb = linear_to_srgb(color.rgb);
924
925 // Apply contrast:
926 // By applying contrast to RGB values that are perceptually uniform (nonlinear),
927 // the darkest values are not hard-clipped as badly, which produces a
928 // higher quality contrast adjustment and maintains compatibility with
929 // existing projects.
930 color.rgb = mix(vec3(0.5), color.rgb, params.bcs.y);
931
932 // Apply saturation:
933 // By applying saturation adjustment to nonlinear sRGB-encoded values with
934 // even weights the preceived brightness of blues are affected, but this
935 // maintains compatibility with existing projects.
936 color.rgb = mix(vec3(dot(vec3(1.0), color.rgb) * (1.0 / 3.0)), color.rgb, params.bcs.z);
937
938 if (bool(params.flags & FLAG_USE_COLOR_CORRECTION)) {
939 color.rgb = clamp(color.rgb, vec3(0.0), vec3(1.0));
940 color.rgb = apply_color_correction(color.rgb);
941 // When using color correction and FLAG_CONVERT_TO_SRGB is false, there
942 // is no need to convert back to linear because the color correction
943 // texture sampling does this for us.
944 } else if (!bool(params.flags & FLAG_CONVERT_TO_SRGB)) {
945 color.rgb = srgb_to_linear(color.rgb);
946 }
947 } else if (bool(params.flags & FLAG_CONVERT_TO_SRGB)) {
948 color.rgb = linear_to_srgb(color.rgb);
949 }
950
951 // Debanding should be done at the end of tonemapping, but before writing to the LDR buffer.
952 // Otherwise, we're adding noise to an already-quantized image.
953
954 if (bool(params.flags & FLAG_USE_8_BIT_DEBANDING)) {
955 // Divide by 255 to align to 8-bit quantization.
956 color.rgb += screen_space_dither(gl_FragCoord.xy, 255.0);
957 }
958
959 frag_color = color;
960 }