1 // Ported to Unity & tweaked by Thomas Hourdel (thomas@hourdel.com)
2 #include "../Colors.hlsl"
5 * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com)
6 * Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com)
7 * Copyright (C) 2013 Belen Masia (bmasia@unizar.es)
8 * Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com)
9 * Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es)
11 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * this software and associated documentation files (the "Software"), to deal in
13 * the Software without restriction, including without limitation the rights to
14 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
15 * of the Software, and to permit persons to whom the Software is furnished to
16 * do so, subject to the following conditions:
18 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software. As clarification, there
20 * is no requirement that the copyright notice and permission be included in
21 * binary distributions of the Software.
23 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34 * _______ ___ ___ ___ ___
36 * | (---- | \ / | / ^ \ / ^ \
37 * \ \ | |\/| | / /_\ \ / /_\ \
38 * ----) | | | | | / _____ \ / _____ \
39 * |_______/ |__| |__| /__/ \__\ /__/ \__\
42 * S U B P I X E L M O R P H O L O G I C A L A N T I A L I A S I N G
44 * http://www.iryoku.com/smaa/
48 * Here you'll find instructions to get the shader up and running as fast as
51 * IMPORTANTE NOTICE: when updating, remember to update both this file and the
52 * precomputed textures! They may change from version to version.
54 * The shader has three passes, chained together as follows:
56 * |input|------------------�
58 * [ SMAA*EdgeDetection ] |
62 * [ SMAABlendingWeightCalculation ] |
66 * [ SMAANeighborhoodBlending ] <------�
70 * Note that each [pass] has its own vertex and pixel shader. Remember to use
71 * oversized triangles instead of quads to avoid overshading along the
74 * You've three edge detection methods to choose from: luma, color or depth.
75 * They represent different quality/performance and anti-aliasing/sharpness
76 * tradeoffs, so our recommendation is for you to choose the one that best
77 * suits your particular scenario:
79 * - Depth edge detection is usually the fastest but it may miss some edges.
81 * - Luma edge detection is usually more expensive than depth edge detection,
82 * but catches visible edges that depth edge detection can miss.
84 * - Color edge detection is usually the most expensive one but catches
87 * For quickstarters: just use luma edge detection.
89 * The general advice is to not rush the integration process and ensure each
90 * step is done correctly (don't try to integrate SMAA T2x with predicated edge
91 * detection from the start!). Ok then, let's go!
93 * 1. The first step is to create two RGBA temporal render targets for holding
94 * |edgesTex| and |blendTex|.
96 * In DX10 or DX11, you can use a RG render target for the edges texture.
97 * In the case of NVIDIA GPUs, using RG render targets seems to actually be
100 * On the Xbox 360, you can use the same render target for resolving both
101 * |edgesTex| and |blendTex|, as they aren't needed simultaneously.
103 * 2. Both temporal render targets |edgesTex| and |blendTex| must be cleared
104 * each frame. Do not forget to clear the alpha channel!
106 * 3. The next step is loading the two supporting precalculated textures,
107 * 'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as
108 * C++ headers, and also as regular DDS files. They'll be needed for the
109 * 'SMAABlendingWeightCalculation' pass.
111 * If you use the C++ headers, be sure to load them in the format specified
114 * You can also compress 'areaTex' and 'searchTex' using BC5 and BC4
115 * respectively, if you have that option in your content processor pipeline.
116 * When compressing then, you get a non-perceptible quality decrease, and a
117 * marginal performance increase.
119 * 4. All samplers must be set to linear filtering and clamp.
121 * After you get the technique working, remember that 64-bit inputs have
122 * half-rate linear filtering on GCN.
124 * If SMAA is applied to 64-bit color buffers, switching to point filtering
125 * when accesing them will increase the performance. Search for
126 * 'SMAASamplePoint' to see which textures may benefit from point
127 * filtering, and where (which is basically the color input in the edge
128 * detection and resolve passes).
130 * 5. All texture reads and buffer writes must be non-sRGB, with the exception
131 * of the input read and the output write in
132 * 'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in
133 * this last pass are not possible, the technique will work anyway, but
134 * will perform antialiasing in gamma space.
136 * IMPORTANT: for best results the input read for the color/luma edge
137 * detection should *NOT* be sRGB.
139 * 6. Before including SMAA.h you'll have to setup the render target metrics,
140 * the target and any optional configuration defines. Optionally you can
143 * You have the following targets available:
150 * * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below).
153 * SMAA_PRESET_LOW (%60 of the quality)
154 * SMAA_PRESET_MEDIUM (%80 of the quality)
155 * SMAA_PRESET_HIGH (%95 of the quality)
156 * SMAA_PRESET_ULTRA (%99 of the quality)
159 * #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0)
160 * #define SMAA_HLSL_4
161 * #define SMAA_PRESET_HIGH
164 * Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a
165 * uniform variable. The code is designed to minimize the impact of not
166 * using a constant value, but it is still better to hardcode it.
168 * Depending on how you encoded 'areaTex' and 'searchTex', you may have to
169 * add (and customize) the following defines before including SMAA.h:
170 * #define SMAA_AREATEX_SELECT(sample) sample.rg
171 * #define SMAA_SEARCHTEX_SELECT(sample) sample.r
173 * If your engine is already using porting macros, you can define
174 * SMAA_CUSTOM_SL, and define the porting functions by yourself.
176 * 7. Then, you'll have to setup the passes as indicated in the scheme above.
177 * You can take a look into SMAA.fx, to see how we did it for our demo.
178 * Checkout the function wrappers, you may want to copy-paste them!
180 * 8. It's recommended to validate the produced |edgesTex| and |blendTex|.
181 * You can use a screenshot from your engine to compare the |edgesTex|
182 * and |blendTex| produced inside of the engine with the results obtained
183 * with the reference demo.
185 * 9. After you get the last pass to work, it's time to optimize. You'll have
186 * to initialize a stencil buffer in the first pass (discard is already in
187 * the code), then mask execution by using it the second pass. The last
188 * pass should be executed in all pixels.
191 * After this point you can choose to enable predicated thresholding,
192 * temporal supersampling and motion blur integration:
194 * a) If you want to use predicated thresholding, take a look into
195 * SMAA_PREDICATION; you'll need to pass an extra texture in the edge
198 * b) If you want to enable temporal supersampling (SMAA T2x):
200 * 1. The first step is to render using subpixel jitters. I won't go into
201 * detail, but it's as simple as moving each vertex position in the
202 * vertex shader, you can check how we do it in our DX10 demo.
204 * 2. Then, you must setup the temporal resolve. You may want to take a look
205 * into SMAAResolve for resolving 2x modes. After you get it working, you'll
206 * probably see ghosting everywhere. But fear not, you can enable the
207 * CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro.
208 * Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded.
210 * 3. The next step is to apply SMAA to each subpixel jittered frame, just as
213 * 4. At this point you should already have something usable, but for best
214 * results the proper area textures must be set depending on current jitter.
215 * For this, the parameter 'subsampleIndices' of
216 * 'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x
221 * | S# | Camera Jitter | subsampleIndices |
222 * +----+------------------+---------------------+
223 * | 0 | ( 0.25, -0.25) | float4(1, 1, 1, 0) |
224 * | 1 | (-0.25, 0.25) | float4(2, 2, 2, 0) |
226 * These jitter positions assume a bottom-to-top y axis. S# stands for the
229 * More information about temporal supersampling here:
230 * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
232 * c) If you want to enable spatial multisampling (SMAA S2x):
234 * 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be
236 * - DX10: see below (*)
237 * - DX10.1: D3D10_STANDARD_MULTISAMPLE_PATTERN or
238 * - DX11: D3D11_STANDARD_MULTISAMPLE_PATTERN
240 * This allows to ensure that the subsample order matches the table in
241 * @SUBSAMPLE_INDICES.
243 * (*) In the case of DX10, we refer the reader to:
244 * - SMAA::detectMSAAOrder and
245 * - SMAA::msaaReorder
247 * These functions allow to match the standard multisample patterns by
248 * detecting the subsample order for a specific GPU, and reordering
249 * them appropriately.
251 * 2. A shader must be run to output each subsample into a separate buffer
252 * (DX10 is required). You can use SMAASeparate for this purpose, or just do
253 * it in an existing pass (for example, in the tone mapping pass, which has
254 * the advantage of feeding tone mapped subsamples to SMAA, which will yield
257 * 3. The full SMAA 1x pipeline must be run for each separated buffer, storing
258 * the results in the final buffer. The second run should alpha blend with
259 * the existing final buffer using a blending factor of 0.5.
260 * 'subsampleIndices' must be adjusted as in the SMAA T2x case (see point
263 * d) If you want to enable temporal supersampling on top of SMAA S2x
264 * (which actually is SMAA 4x):
266 * 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is
267 * to calculate SMAA S2x for current frame. In this case, 'subsampleIndices'
268 * must be set as follows:
270 * | F# | S# | Camera Jitter | Net Jitter | subsampleIndices |
271 * +----+----+--------------------+-------------------+----------------------+
272 * | 0 | 0 | ( 0.125, 0.125) | ( 0.375, -0.125) | float4(5, 3, 1, 3) |
273 * | 0 | 1 | ( 0.125, 0.125) | (-0.125, 0.375) | float4(4, 6, 2, 3) |
274 * +----+----+--------------------+-------------------+----------------------+
275 * | 1 | 2 | (-0.125, -0.125) | ( 0.125, -0.375) | float4(3, 5, 1, 4) |
276 * | 1 | 3 | (-0.125, -0.125) | (-0.375, 0.125) | float4(6, 4, 2, 4) |
278 * These jitter positions assume a bottom-to-top y axis. F# stands for the
279 * frame number. S# stands for the sample number.
281 * 2. After calculating SMAA S2x for current frame (with the new subsample
282 * indices), previous frame must be reprojected as in SMAA T2x mode (see
285 * e) If motion blur is used, you may want to do the edge detection pass
286 * together with motion blur. This has two advantages:
288 * 1. Pixels under heavy motion can be omitted from the edge detection process.
289 * For these pixels we can just store "no edge", as motion blur will take
291 * 2. The center pixel tap is reused.
293 * Note that in this case depth testing should be used instead of stenciling,
294 * as we have to write all the pixels in the motion blur pass.
299 //-----------------------------------------------------------------------------
303 * Note that if you use one of these presets, the following configuration
304 * macros will be ignored if set in the "Configurable Defines" section.
307 #if defined(SMAA_PRESET_LOW)
308 #define SMAA_THRESHOLD 0.15
309 #define SMAA_MAX_SEARCH_STEPS 4
310 #define SMAA_DISABLE_DIAG_DETECTION
311 #define SMAA_DISABLE_CORNER_DETECTION
312 #elif defined(SMAA_PRESET_MEDIUM)
313 #define SMAA_THRESHOLD 0.1
314 #define SMAA_MAX_SEARCH_STEPS 8
315 #define SMAA_DISABLE_DIAG_DETECTION
316 #define SMAA_DISABLE_CORNER_DETECTION
317 #elif defined(SMAA_PRESET_HIGH)
318 #define SMAA_THRESHOLD 0.1
319 #define SMAA_MAX_SEARCH_STEPS 16
320 #define SMAA_MAX_SEARCH_STEPS_DIAG 8
321 #define SMAA_CORNER_ROUNDING 25
322 #elif defined(SMAA_PRESET_ULTRA)
323 #define SMAA_THRESHOLD 0.05
324 #define SMAA_MAX_SEARCH_STEPS 32
325 #define SMAA_MAX_SEARCH_STEPS_DIAG 16
326 #define SMAA_CORNER_ROUNDING 25
329 //-----------------------------------------------------------------------------
330 // Configurable Defines
333 * SMAA_THRESHOLD specifies the threshold or sensitivity to edges.
334 * Lowering this value you will be able to detect more edges at the expense of
338 * 0.1 is a reasonable value, and allows to catch most visible edges.
339 * 0.05 is a rather overkill value, that allows to catch 'em all.
341 * If temporal supersampling is used, 0.2 could be a reasonable value, as low
342 * contrast edges are properly filtered by just 2x.
344 #ifndef SMAA_THRESHOLD
345 #define SMAA_THRESHOLD 0.1
349 * SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection.
351 * Range: depends on the depth range of the scene.
353 #ifndef SMAA_DEPTH_THRESHOLD
354 #define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD)
358 * SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the
359 * horizontal/vertical pattern searches, at each side of the pixel.
361 * In number of pixels, it's actually the double. So the maximum line length
362 * perfectly handled by, for example 16, is 64 (by perfectly, we meant that
363 * longer lines won't look as good, but still antialiased).
367 #ifndef SMAA_MAX_SEARCH_STEPS
368 #define SMAA_MAX_SEARCH_STEPS 16
372 * SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the
373 * diagonal pattern searches, at each side of the pixel. In this case we jump
374 * one pixel at time, instead of two.
378 * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16
379 * steps), but it can have a significant impact on older machines.
381 * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing.
383 #ifndef SMAA_MAX_SEARCH_STEPS_DIAG
384 #define SMAA_MAX_SEARCH_STEPS_DIAG 8
388 * SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded.
392 * Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing.
394 #ifndef SMAA_CORNER_ROUNDING
395 #define SMAA_CORNER_ROUNDING 25
399 * If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times
400 * bigger contrast than current edge, current edge will be discarded.
402 * This allows to eliminate spurious crossing edges, and is based on the fact
403 * that, if there is too much contrast in a direction, that will hide
404 * perceptually contrast in the other neighbors.
406 #ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
407 #define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0
411 * Predicated thresholding allows to better preserve texture details and to
412 * improve performance, by decreasing the number of detected edges using an
413 * additional buffer like the light accumulation buffer, object ids or even the
414 * depth buffer (the depth buffer usage may be limited to indoor or short range
417 * It locally decreases the luma or color threshold if an edge is found in an
418 * additional buffer (so the global threshold can be higher).
420 * This method was developed by Playstation EDGE MLAA team, and used in
421 * Killzone 3, by using the light accumulation buffer. More information here:
422 * http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx
424 #ifndef SMAA_PREDICATION
425 #define SMAA_PREDICATION 0
429 * Threshold to be used in the additional predication buffer.
431 * Range: depends on the input, so you'll have to find the magic number that
434 #ifndef SMAA_PREDICATION_THRESHOLD
435 #define SMAA_PREDICATION_THRESHOLD 0.01
439 * How much to scale the global threshold used for luma or color edge
440 * detection when using predication.
444 #ifndef SMAA_PREDICATION_SCALE
445 #define SMAA_PREDICATION_SCALE 2.0
449 * How much to locally decrease the threshold.
453 #ifndef SMAA_PREDICATION_STRENGTH
454 #define SMAA_PREDICATION_STRENGTH 0.4
458 * Temporal reprojection allows to remove ghosting artifacts when using
459 * temporal supersampling. We use the CryEngine 3 method which also introduces
460 * velocity weighting. This feature is of extreme importance for totally
461 * removing ghosting. More information here:
462 * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
464 * Note that you'll need to setup a velocity buffer for enabling reprojection.
465 * For static geometry, saving the previous depth buffer is a viable
468 #ifndef SMAA_REPROJECTION
469 #define SMAA_REPROJECTION 0
473 * Temporal reprojection allows to remove ghosting artifacts when using
474 * temporal supersampling. However, the default reprojection requires a velocity buffer
475 * in order to function properly.
477 * A velocity buffer might not always be available (hi Unity 5!). To handle such cases
478 * we provide a UV-based approximation for calculating motion vectors on the fly.
480 #ifndef SMAA_UV_BASED_REPROJECTION
481 #define SMAA_UV_BASED_REPROJECTION 0
485 * SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows to
486 * remove ghosting trails behind the moving object, which are not removed by
487 * just using reprojection. Using low values will exhibit ghosting, while using
488 * high values will disable temporal supersampling under motion.
490 * Behind the scenes, velocity weighting removes temporal supersampling when
491 * the velocity of the subsamples differs (meaning they are different objects).
495 #ifndef SMAA_REPROJECTION_WEIGHT_SCALE
496 #define SMAA_REPROJECTION_WEIGHT_SCALE 30.0
500 * On some compilers, discard cannot be used in vertex shaders. Thus, they need
501 * to be compiled separately.
503 #ifndef SMAA_INCLUDE_VS
504 #define SMAA_INCLUDE_VS 1
506 #ifndef SMAA_INCLUDE_PS
507 #define SMAA_INCLUDE_PS 1
510 //-----------------------------------------------------------------------------
511 // Texture Access Defines
513 #ifndef SMAA_AREATEX_SELECT
514 #if defined(SMAA_HLSL_3)
515 #define SMAA_AREATEX_SELECT(sample) sample.ra
517 #define SMAA_AREATEX_SELECT(sample) sample.rg
521 #ifndef SMAA_SEARCHTEX_SELECT
522 #define SMAA_SEARCHTEX_SELECT(sample) sample.r
525 #ifndef SMAA_DECODE_VELOCITY
526 #define SMAA_DECODE_VELOCITY(sample) sample.rg
529 //-----------------------------------------------------------------------------
530 // Non-Configurable Defines
532 #define SMAA_AREATEX_MAX_DISTANCE 16
533 #define SMAA_AREATEX_MAX_DISTANCE_DIAG 20
534 #define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0))
535 #define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0)
536 #define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0)
537 #define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0)
538 #define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0)
540 //-----------------------------------------------------------------------------
543 #if defined(SMAA_HLSL_3)
544 #define SMAATexture2D(tex) sampler2D tex
545 #define SMAATexturePass2D(tex) tex
546 #define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
547 #define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
548 #define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0))
549 #define SMAASample(tex, coord) tex2D(tex, coord)
550 #define SMAASamplePoint(tex, coord) tex2D(tex, coord)
551 #define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy)
552 //#define SMAA_FLATTEN [flatten]
553 //#define SMAA_BRANCH [branch]
557 #if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1)
558 //SamplerState LinearSampler { Filter = MIN_MAG_LINEAR_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
559 //SamplerState PointSampler { Filter = MIN_MAG_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
560 #define SMAATexture2D(tex) Texture2D tex
561 #define SMAATexturePass2D(tex) tex
562 #define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0)
563 #define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0)
564 #define SMAASampleLevelZeroOffset(tex, coord, offset) tex.SampleLevel(LinearSampler, coord, 0, offset)
565 #define SMAASample(tex, coord) tex.Sample(LinearSampler, coord)
566 #define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord)
567 #define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset)
568 #define SMAA_FLATTEN [flatten]
569 #define SMAA_BRANCH [branch]
570 #define SMAATexture2DMS2(tex) Texture2DMS<float4, 2> tex
571 #define SMAALoad(tex, pos, sample) tex.Load(pos, sample)
572 #if defined(SMAA_HLSL_4_1)
573 #define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0)
576 #if defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4)
577 #define SMAATexture2D(tex) sampler2D tex
578 #define SMAATexturePass2D(tex) tex
579 #define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0)
580 #define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0)
581 #define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset)
582 #define SMAASample(tex, coord) texture(tex, coord)
583 #define SMAASamplePoint(tex, coord) texture(tex, coord)
584 #define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset)
587 #define lerp(a, b, t) mix(a, b, t)
588 #define saturate(a) clamp(a, 0.0, 1.0)
589 #if defined(SMAA_GLSL_4)
590 #define mad(a, b, c) fma(a, b, c)
591 #define SMAAGather(tex, coord) textureGather(tex, coord)
593 #define mad(a, b, c) (a * b + c)
606 #if !defined(SMAA_HLSL_3) && !defined(SMAA_HLSL_4) && !defined(SMAA_HLSL_4_1) && !defined(SMAA_GLSL_3) && !defined(SMAA_GLSL_4) && !defined(SMAA_CUSTOM_SL)
607 #error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL
610 //-----------------------------------------------------------------------------
614 * Gathers current pixel, and the top-left neighbors.
616 float3 SMAAGatherNeighbours(float2 texcoord,
618 SMAATexture2D(tex)) {
620 return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb;
622 float P = SMAASamplePoint(tex, texcoord).r;
623 float Pleft = SMAASamplePoint(tex, offset[0].xy).r;
624 float Ptop = SMAASamplePoint(tex, offset[0].zw).r;
625 return float3(P, Pleft, Ptop);
630 * Adjusts the threshold by means of predication.
632 float2 SMAACalculatePredicatedThreshold(float2 texcoord,
634 SMAATexture2D(predicationTex)) {
635 float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex));
636 float2 delta = abs(neighbours.xx - neighbours.yz);
637 float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta);
638 return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges);
644 void SMAAMovc(bool2 cond, inout float2 variable, float2 value) {
645 SMAA_FLATTEN if (cond.x) variable.x = value.x;
646 SMAA_FLATTEN if (cond.y) variable.y = value.y;
649 void SMAAMovc(bool4 cond, inout float4 variable, float4 value) {
650 SMAAMovc(cond.xy, variable.xy, value.xy);
651 SMAAMovc(cond.zw, variable.zw, value.zw);
656 //-----------------------------------------------------------------------------
660 * Edge Detection Vertex Shader
662 void SMAAEdgeDetectionVS(float2 texcoord,
663 out float4 offset[3]) {
664 offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy);
665 offset[1] = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
666 offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy);
670 * Blend Weight Calculation Vertex Shader
672 void SMAABlendingWeightCalculationVS(float2 texcoord,
674 out float4 offset[3]) {
675 pixcoord = texcoord * SMAA_RT_METRICS.zw;
677 // We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
678 offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy);
679 offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy);
681 // And these for the searches, they indicate the ends of the loops:
682 offset[2] = mad(SMAA_RT_METRICS.xxyy,
683 float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
684 float4(offset[0].xz, offset[1].yw));
688 * Neighborhood Blending Vertex Shader
690 void SMAANeighborhoodBlendingVS(float2 texcoord,
692 offset = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
694 #endif // SMAA_INCLUDE_VS
697 //-----------------------------------------------------------------------------
698 // Edge Detection Pixel Shaders (First Pass)
701 * Luma Edge Detection
703 * IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and
704 * thus 'colorTex' should be a non-sRGB texture.
706 float2 SMAALumaEdgeDetectionPS(float2 texcoord,
708 SMAATexture2D(colorTex)
710 , SMAATexture2D(predicationTex)
713 // Calculate the threshold:
715 float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, SMAATexturePass2D(predicationTex));
717 float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
721 float3 weights = float3(0.2126, 0.7152, 0.0722);
722 float L = dot(SMAASamplePoint(colorTex, texcoord).rgb, weights);
724 float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgb, weights);
725 float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgb, weights);
727 // We do the usual threshold:
729 delta.xy = abs(L - float2(Lleft, Ltop));
730 float2 edges = step(threshold, delta.xy);
732 // Then discard if there is no edge:
733 if (dot(edges, float2(1.0, 1.0)) == 0.0)
736 // Calculate right and bottom deltas:
737 float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgb, weights);
738 float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgb, weights);
739 delta.zw = abs(L - float2(Lright, Lbottom));
741 // Calculate the maximum delta in the direct neighborhood:
742 float2 maxDelta = max(delta.xy, delta.zw);
744 // Calculate left-left and top-top deltas:
745 float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgb, weights);
746 float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgb, weights);
747 delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop));
749 // Calculate the final maximum delta:
750 maxDelta = max(maxDelta.xy, delta.zw);
751 float finalDelta = max(maxDelta.x, maxDelta.y);
753 // Local contrast adaptation:
754 #if !defined(SHADER_API_OPENGL)
755 edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
762 * Color Edge Detection
764 * IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and
765 * thus 'colorTex' should be a non-sRGB texture.
767 float2 SMAAColorEdgeDetectionPS(float2 texcoord,
769 SMAATexture2D(colorTex)
771 , SMAATexture2D(predicationTex)
774 // Calculate the threshold:
776 float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
778 float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
781 // Calculate color deltas:
783 float3 C = SMAASamplePoint(colorTex, texcoord).rgb;
785 float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb;
786 float3 t = abs(C - Cleft);
787 delta.x = max(max(t.r, t.g), t.b);
789 float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb;
791 delta.y = max(max(t.r, t.g), t.b);
793 // We do the usual threshold:
794 float2 edges = step(threshold, delta.xy);
796 // Then discard if there is no edge:
797 if (dot(edges, float2(1.0, 1.0)) == 0.0)
800 // Calculate right and bottom deltas:
801 float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb;
803 delta.z = max(max(t.r, t.g), t.b);
805 float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb;
806 t = abs(C - Cbottom);
807 delta.w = max(max(t.r, t.g), t.b);
809 // Calculate the maximum delta in the direct neighborhood:
810 float2 maxDelta = max(delta.xy, delta.zw);
812 // Calculate left-left and top-top deltas:
813 float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb;
814 t = abs(Cleft - Cleftleft);
815 delta.z = max(max(t.r, t.g), t.b);
817 float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb;
818 t = abs(Ctop - Ctoptop);
819 delta.w = max(max(t.r, t.g), t.b);
821 // Calculate the final maximum delta:
822 maxDelta = max(maxDelta.xy, delta.zw);
823 float finalDelta = max(maxDelta.x, maxDelta.y);
825 // Local contrast adaptation:
826 #if !defined(SHADER_API_OPENGL)
827 edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
834 * Depth Edge Detection
836 float2 SMAADepthEdgeDetectionPS(float2 texcoord,
838 SMAATexture2D(depthTex)) {
839 float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex));
840 float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z));
841 float2 edges = step(SMAA_DEPTH_THRESHOLD, delta);
843 if (dot(edges, float2(1.0, 1.0)) == 0.0)
849 //-----------------------------------------------------------------------------
850 // Diagonal Search Functions
852 #if !defined(SMAA_DISABLE_DIAG_DETECTION)
855 * Allows to decode two binary values from a bilinear-filtered access.
857 float2 SMAADecodeDiagBilinearAccess(float2 e) {
858 // Bilinear access for fetching 'e' have a 0.25 offset, and we are
859 // interested in the R and G edges:
865 // Then, if one of these edge is enabled:
866 // Red: (0.75 * X + 0.25 * 1) => 0.25 or 1.0
867 // Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0
869 // This function will unpack the values (mad + mul + round):
870 // wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1
871 e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
875 float4 SMAADecodeDiagBilinearAccess(float4 e) {
876 e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
881 * These functions allows to perform diagonal pattern searches.
883 float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
884 float4 coord = float4(texcoord, -1.0, 1.0);
885 float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
886 while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
888 coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
889 e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
890 coord.w = dot(e, float2(0.5, 0.5));
895 float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
896 float4 coord = float4(texcoord, -1.0, 1.0);
897 coord.x += 0.25 * SMAA_RT_METRICS.x; // See @SearchDiag2Optimization
898 float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
899 while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
901 coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
903 // @SearchDiag2Optimization
904 // Fetch both edges at once using bilinear filtering:
905 e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
906 e = SMAADecodeDiagBilinearAccess(e);
908 // Non-optimized version:
909 // e.g = SMAASampleLevelZero(edgesTex, coord.xy).g;
910 // e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r;
912 coord.w = dot(e, float2(0.5, 0.5));
918 * Similar to SMAAArea, this calculates the area corresponding to a certain
919 * diagonal distance and crossing edges 'e'.
921 float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset) {
922 float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist);
924 // We do a scale and bias for mapping to texel space:
925 texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
927 // Diagonal areas are on the second half of the texture:
930 // Move to proper place, according to the subpixel offset:
931 texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
934 return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
938 * This searches for diagonal patterns and returns the corresponding weights.
940 float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex), SMAATexture2D(areaTex), float2 texcoord, float2 e, float4 subsampleIndices) {
941 float2 weights = float2(0.0, 0.0);
943 // Search for the line ends:
947 d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end);
948 d.x += float(end.y > 0.9);
950 d.xz = float2(0.0, 0.0);
951 d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end);
954 if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
955 // Fetch the crossing edges:
956 float4 coords = mad(float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
958 c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg;
959 c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).rg;
960 c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw);
962 // Non-optimized version:
963 // float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
965 // c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
966 // c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, 0)).r;
967 // c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).g;
968 // c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r;
970 // Merge crossing edges at each side into a single value:
971 float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
973 // Remove the crossing edge if we didn't found the end of the line:
974 SMAAMovc(bool2(step(float2(0.9, 0.9), d.zw)), cc, float2(0.0, 0.0));
976 // Fetch the areas for this line:
977 weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z);
980 // Search for the line ends:
981 d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end);
982 if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) {
983 d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end);
984 d.y += float(end.y > 0.9);
986 d.yw = float2(0.0, 0.0);
989 if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
990 // Fetch the crossing edges:
991 float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
993 c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
994 c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, -1)).r;
995 c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).gr;
996 float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
998 // Remove the crossing edge if we didn't found the end of the line:
999 SMAAMovc(bool2(step(float2(0.9, 0.9), d.zw)), cc, float2(0.0, 0.0));
1001 // Fetch the areas for this line:
1002 weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr;
1009 //-----------------------------------------------------------------------------
1010 // Horizontal/Vertical Search Functions
1013 * This allows to determine how much length should we add in the last step
1014 * of the searches. It takes the bilinearly interpolated edge (see
1015 * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and
1016 * crossing edges are active.
1018 float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset) {
1019 // The texture is flipped vertically, with left and right cases taking half
1020 // of the space horizontally:
1021 float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0);
1022 float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0);
1024 // Scale and bias to access texel centers:
1025 scale += float2(-1.0, 1.0);
1026 bias += float2( 0.5, -0.5);
1028 // Convert from pixel coordinates to texcoords:
1029 // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped)
1030 scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
1031 bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
1033 // Lookup the search texture:
1034 return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias)));
1038 * Horizontal/vertical search functions for the 2nd pass.
1040 float SMAASearchXLeft(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
1043 * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
1044 * sample between edge, thus fetching four edges in a row.
1045 * Sampling with different offsets in each direction allows to disambiguate
1046 * which edges are active from the four fetched ones.
1048 float2 e = float2(0.0, 1.0);
1049 while (texcoord.x > end &&
1050 e.g > 0.8281 && // Is there some edge not activated?
1051 e.r == 0.0) { // Or is there a crossing edge that breaks the line?
1052 e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1053 texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
1056 float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25);
1057 return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
1059 // Non-optimized version:
1060 // We correct the previous (-0.25, -0.125) offset we applied:
1061 // texcoord.x += 0.25 * SMAA_RT_METRICS.x;
1063 // The searches are bias by 1, so adjust the coords accordingly:
1064 // texcoord.x += SMAA_RT_METRICS.x;
1066 // Disambiguate the length added by the last step:
1067 // texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step
1068 // texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) * SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0);
1069 // return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
1072 float SMAASearchXRight(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
1073 float2 e = float2(0.0, 1.0);
1074 while (texcoord.x < end &&
1075 e.g > 0.8281 && // Is there some edge not activated?
1076 e.r == 0.0) { // Or is there a crossing edge that breaks the line?
1077 e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1078 texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
1080 float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25);
1081 return mad(-SMAA_RT_METRICS.x, offset, texcoord.x);
1084 float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
1085 float2 e = float2(1.0, 0.0);
1086 while (texcoord.y > end &&
1087 e.r > 0.8281 && // Is there some edge not activated?
1088 e.g == 0.0) { // Or is there a crossing edge that breaks the line?
1089 e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1090 texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
1092 float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25);
1093 return mad(SMAA_RT_METRICS.y, offset, texcoord.y);
1096 float SMAASearchYDown(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
1097 float2 e = float2(1.0, 0.0);
1098 while (texcoord.y < end &&
1099 e.r > 0.8281 && // Is there some edge not activated?
1100 e.g == 0.0) { // Or is there a crossing edge that breaks the line?
1101 e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1102 texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
1104 float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25);
1105 return mad(-SMAA_RT_METRICS.y, offset, texcoord.y);
1109 * Ok, we have the distance and both crossing edges. So, what are the areas
1110 * at each side of current edge?
1112 float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset) {
1113 // Rounding prevents precision errors of bilinear filtering:
1114 float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), round(4.0 * float2(e1, e2)), dist);
1116 // We do a scale and bias for mapping to texel space:
1117 texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
1119 // Move to proper place, according to the subpixel offset:
1120 texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y);
1123 return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
1126 //-----------------------------------------------------------------------------
1127 // Corner Detection Functions
1129 void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
1130 #if !defined(SMAA_DISABLE_CORNER_DETECTION)
1131 float2 leftRight = step(d.xy, d.yx);
1132 float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
1134 rounding /= leftRight.x + leftRight.y; // Reduce blending for pixels in the center of a line.
1136 float2 factor = float2(1.0, 1.0);
1137 factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r;
1138 factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r;
1139 factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r;
1140 factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r;
1142 weights *= saturate(factor);
1146 void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
1147 #if !defined(SMAA_DISABLE_CORNER_DETECTION)
1148 float2 leftRight = step(d.xy, d.yx);
1149 float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
1151 rounding /= leftRight.x + leftRight.y;
1153 float2 factor = float2(1.0, 1.0);
1154 factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2( 1, 0)).g;
1155 factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2( 1, 1)).g;
1156 factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g;
1157 factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g;
1159 weights *= saturate(factor);
1164 //-----------------------------------------------------------------------------
1165 // Blending Weight Calculation Pixel Shader (Second Pass)
1167 float4 SMAABlendingWeightCalculationPS(float2 texcoord,
1170 SMAATexture2D(edgesTex),
1171 SMAATexture2D(areaTex),
1172 SMAATexture2D(searchTex),
1173 float4 subsampleIndices) { // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES.
1174 float4 weights = float4(0.0, 0.0, 0.0, 0.0);
1176 float2 e = SMAASample(edgesTex, texcoord).rg;
1179 if (e.g > 0.0) { // Edge at north
1180 #if !defined(SMAA_DISABLE_DIAG_DETECTION)
1181 // Diagonals have both north and west edges, so searching for them in
1182 // one of the boundaries is enough.
1183 weights.rg = SMAACalculateDiagWeights(SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices);
1185 // We give priority to diagonals, so if we find a diagonal we skip
1186 // horizontal/vertical processing.
1188 if (weights.r == -weights.g) { // weights.r + weights.g == 0.0
1193 // Find the distance to the left:
1195 coords.x = SMAASearchXLeft(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x);
1196 coords.y = offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET)
1199 // Now fetch the left crossing edges, two at a time using bilinear
1200 // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
1201 // discern what value each edge has:
1202 float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r;
1204 // Find the distance to the right:
1205 coords.z = SMAASearchXRight(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y);
1208 // We want the distances to be in pixel units (doing this here allow to
1209 // better interleave arithmetic and memory accesses):
1210 d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx)));
1212 // SMAAArea below needs a sqrt, as the areas texture is compressed
1214 float2 sqrt_d = sqrt(d);
1216 // Fetch the right crossing edges:
1217 float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r;
1219 // Ok, we know how this pattern looks like, now it is time for getting
1221 weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y);
1224 coords.y = texcoord.y;
1225 SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d);
1227 #if !defined(SMAA_DISABLE_DIAG_DETECTION)
1229 e.r = 0.0; // Skip vertical processing.
1234 if (e.r > 0.0) { // Edge at west
1237 // Find the distance to the top:
1239 coords.y = SMAASearchYUp(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z);
1240 coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x;
1243 // Fetch the top crossing edges:
1244 float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g;
1246 // Find the distance to the bottom:
1247 coords.z = SMAASearchYDown(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w);
1250 // We want the distances to be in pixel units:
1251 d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy)));
1253 // SMAAArea below needs a sqrt, as the areas texture is compressed
1255 float2 sqrt_d = sqrt(d);
1257 // Fetch the bottom crossing edges:
1258 float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g;
1260 // Get the area for this direction:
1261 weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x);
1264 coords.x = texcoord.x;
1265 SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d);
1271 //-----------------------------------------------------------------------------
1272 // UV-based reprojection functions
1274 #if SMAA_UV_BASED_REPROJECTION
1275 float2 SMAAReproject(float2 texcoord)
1277 // UV to clip-position:
1278 // -- This must be sampled at exactly mip 0 due to possible gradient divergence
1279 // -- as this function is called within a control flow block down below.
1280 float depth = SMAASampleLevelZero(_CameraDepthTexture, texcoord).r;
1281 float3 clipPosition = float3(2. * texcoord - 1., depth);
1284 float4 previousClipPosition = mul(_ReprojectionMatrix, float4(clipPosition, 1.));
1285 previousClipPosition.xyz /= previousClipPosition.w;
1287 // Clip-position to UV
1288 return (.5 * previousClipPosition.xy + .5);
1292 //-----------------------------------------------------------------------------
1293 // Neighborhood Blending Pixel Shader (Third Pass)
1295 float4 SMAANeighborhoodBlendingPS(float2 texcoord,
1297 SMAATexture2D(colorTex),
1298 SMAATexture2D(blendTex)
1299 #if SMAA_REPROJECTION
1300 , SMAATexture2D(velocityTex)
1303 // Fetch the blending weights for current pixel:
1305 a.x = SMAASample(blendTex, offset.xy).a; // Right
1306 a.y = SMAASample(blendTex, offset.zw).g; // Top
1307 a.wz = SMAASample(blendTex, texcoord).xz; // Bottom / Left
1309 // Is there any blending weight with a value greater than 0.0?
1311 if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) {
1312 float4 color = SMAASampleLevelZero(colorTex, texcoord);
1314 #if SMAA_REPROJECTION
1315 float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord));
1316 #elif SMAA_UV_BASED_REPROJECTION
1317 float2 velocity = texcoord - SMAAReproject(texcoord);
1320 #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
1321 // Pack velocity into the alpha channel:
1322 color.a = sqrt(5.0 * length(velocity));
1327 bool h = max(a.x, a.z) > max(a.y, a.w); // max(horizontal) > max(vertical)
1329 // Calculate the blending offsets:
1330 float4 blendingOffset = float4(0.0, a.y, 0.0, a.w);
1331 float2 blendingWeight = a.yw;
1332 SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0));
1333 SMAAMovc(bool2(h, h), blendingWeight, a.xz);
1334 blendingWeight /= dot(blendingWeight, float2(1.0, 1.0));
1336 // Calculate the texture coordinates:
1337 float4 blendingCoord = mad(blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy);
1339 // We exploit bilinear filtering to mix current pixel with the chosen
1341 float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy);
1342 color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw);
1344 #if SMAA_REPROJECTION
1345 // Antialias velocity for proper reprojection in a later stage:
1346 float2 velocity = blendingWeight.x * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy));
1347 velocity += blendingWeight.y * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw));
1348 #elif SMAA_UV_BASED_REPROJECTION
1349 // Antialias velocity for proper reprojection in a later stage:
1350 float2 velocity = blendingWeight.x * (blendingCoord.xy - SMAAReproject(blendingCoord.xy));
1351 velocity += blendingWeight.y * (blendingCoord.zw - SMAAReproject(blendingCoord.zw));
1354 #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
1355 // Pack velocity into the alpha channel:
1356 color.a = sqrt(5.0 * length(velocity));
1363 //-----------------------------------------------------------------------------
1364 // Temporal Resolve Pixel Shader (Optional Pass)
1366 float4 SMAAResolvePS(float2 texcoord,
1367 SMAATexture2D(currentColorTex),
1368 SMAATexture2D(previousColorTex)
1369 #if SMAA_REPROJECTION
1370 , SMAATexture2D(velocityTex)
1373 #if SMAA_REPROJECTION
1374 // Velocity is assumed to be calculated for motion blur, so we need to
1375 // inverse it for reprojection:
1376 float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg);
1377 #elif SMAA_UV_BASED_REPROJECTION
1378 float2 velocity = SMAAReproject(texcoord) - texcoord;
1381 #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
1382 // Fetch current pixel:
1383 float4 current = SMAASamplePoint(currentColorTex, texcoord);
1385 // Reproject current coordinates and fetch previous pixel:
1386 float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity);
1388 // Attenuate the previous pixel if the velocity is different:
1389 float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0;
1390 float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE);
1392 // Blend the pixels according to the calculated weight:
1393 // return lerp(current, previous, weight);
1396 // Contributed by pommak
1397 float4 n0 = SMAASampleOffset(currentColorTex, texcoord, float2(-1, -1));
1398 float4 n1 = SMAASampleOffset(currentColorTex, texcoord, float2(+1, -1));
1399 float4 n2 = SMAASampleOffset(currentColorTex, texcoord, float2(-1, +1));
1400 float4 n3 = SMAASampleOffset(currentColorTex, texcoord, float2(+1, +1));
1401 float4 cmax = max(n0, max(n1, max(n2, n3)));
1402 float4 cmin = min(n0, min(n1, min(n2, n3)));
1403 float4 avg = 0.25 * (n0+n1+n2+n3);
1404 float4 wk = abs(avg - current);
1405 float blend = saturate(lerp(0.35, 0.85, wk));
1407 // Clamp previous to neighbours colors
1408 float4 previousClamped = clamp(previous, cmin, cmax);
1410 float4 color = lerp(lerp(current, previousClamped, 0.5*weight), previousClamped, weight);
1413 // Just blend the pixels:
1414 float4 current = SMAASamplePoint(currentColorTex, texcoord);
1415 float4 previous = SMAASamplePoint(previousColorTex, texcoord);
1416 return lerp(current, previous, 0.5);
1420 //-----------------------------------------------------------------------------
1421 // Separate Multisamples Pixel Shader (Optional Pass)
1424 void SMAASeparatePS(float4 position,
1428 SMAATexture2DMS2(colorTexMS)) {
1429 int2 pos = int2(position.xy);
1430 target0 = SMAALoad(colorTexMS, pos, 0);
1431 target1 = SMAALoad(colorTexMS, pos, 1);
1435 //-----------------------------------------------------------------------------
1436 #endif // SMAA_INCLUDE_PS