1/**
2 * Copyright (C) 2013 Jorge Jimenez <jorge@iryoku.com>
3 * Copyright (C) 2013 Jose I. Echevarria <joseignacioechevarria@gmail.com>
4 * Copyright (C) 2013 Belen Masia <bmasia@unizar.es>
5 * Copyright (C) 2013 Fernando Navarro <fernandn@microsoft.com>
6 * Copyright (C) 2013 Diego Gutierrez <diegog@unizar.es>
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * this software and associated documentation files (the "Software"), to deal in
10 * the Software without restriction, including without limitation the rights to
11 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12 * of the Software, and to permit persons to whom the Software is furnished to
13 * do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software. As clarification, there
17 * is no requirement that the copyright notice and permission be included in
18 * binary distributions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 * SOFTWARE.
27 */
28
29/**
30 *                  _______  ___  ___       ___           ___
31 *                 /       ||   \/   |     /   \         /   \
32 *                |   (---- |  \  /  |    /  ^  \       /  ^  \
33 *                 \   \    |  |\/|  |   /  /_\  \     /  /_\  \
34 *              ----)   |   |  |  |  |  /  _____  \   /  _____  \
35 *             |_______/    |__|  |__| /__/     \__\ /__/     \__\
36 *
37 *                               E N H A N C E D
38 *       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
39 *
40 *                         http://www.iryoku.com/smaa/
41 *
42 * Hi, welcome aboard!
43 *
44 * Here you'll find instructions to get the shader up and running as fast as
45 * possible.
46 *
47 * IMPORTANTE NOTICE: when updating, remember to update both this file and the
48 * precomputed textures! They may change from version to version.
49 *
50 * The shader has three passes, chained together as follows:
51 *
52 *                           |input|------------------�
53 *                              v                     |
54 *                    [ SMAA*EdgeDetection ]          |
55 *                              v                     |
56 *                          |edgesTex|                |
57 *                              v                     |
58 *              [ SMAABlendingWeightCalculation ]     |
59 *                              v                     |
60 *                          |blendTex|                |
61 *                              v                     |
62 *                [ SMAANeighborhoodBlending ] <------�
63 *                              v
64 *                           |output|
65 *
66 * Note that each [pass] has its own vertex and pixel shader. Remember to use
67 * oversized triangles instead of quads to avoid overshading along the
68 * diagonal.
69 *
70 * You've three edge detection methods to choose from: luma, color or depth.
71 * They represent different quality/performance and anti-aliasing/sharpness
72 * tradeoffs, so our recommendation is for you to choose the one that best
73 * suits your particular scenario:
74 *
75 * - Depth edge detection is usually the fastest but it may miss some edges.
76 *
77 * - Luma edge detection is usually more expensive than depth edge detection,
78 *   but catches visible edges that depth edge detection can miss.
79 *
80 * - Color edge detection is usually the most expensive one but catches
81 *   chroma-only edges.
82 *
83 * For quickstarters: just use luma edge detection.
84 *
85 * The general advice is to not rush the integration process and ensure each
86 * step is done correctly (don't try to integrate SMAA T2x with predicated edge
87 * detection from the start!). Ok then, let's go!
88 *
89 *  1. The first step is to create two RGBA temporal render targets for holding
90 *     |edgesTex| and |blendTex|.
91 *
92 *     In DX10 or DX11, you can use a RG render target for the edges texture.
93 *     In the case of NVIDIA GPUs, using RG render targets seems to actually be
94 *     slower.
95 *
96 *     On the Xbox 360, you can use the same render target for resolving both
97 *     |edgesTex| and |blendTex|, as they aren't needed simultaneously.
98 *
99 *  2. Both temporal render targets |edgesTex| and |blendTex| must be cleared
100 *     each frame. Do not forget to clear the alpha channel!
101 *
102 *  3. The next step is loading the two supporting precalculated textures,
103 *     'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as
104 *     C++ headers, and also as regular DDS files. They'll be needed for the
105 *     'SMAABlendingWeightCalculation' pass.
106 *
107 *     If you use the C++ headers, be sure to load them in the format specified
108 *     inside of them.
109 *
110 *     You can also compress 'areaTex' and 'searchTex' using BC5 and BC4
111 *     respectively, if you have that option in your content processor pipeline.
112 *     When compressing then, you get a non-perceptible quality decrease, and a
113 *     marginal performance increase.
114 *
115 *  4. All samplers must be set to linear filtering and clamp.
116 *
117 *     After you get the technique working, remember that 64-bit inputs have
118 *     half-rate linear filtering on GCN.
119 *
120 *     If SMAA is applied to 64-bit color buffers, switching to point filtering
121 *     when accesing them will increase the performance. Search for
122 *     'SMAASamplePoint' to see which textures may benefit from point
123 *     filtering, and where (which is basically the color input in the edge
124 *     detection and resolve passes).
125 *
126 *  5. All texture reads and buffer writes must be non-sRGB, with the exception
127 *     of the input read and the output write in
128 *     'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in
129 *     this last pass are not possible, the technique will work anyway, but
130 *     will perform antialiasing in gamma space.
131 *
132 *     IMPORTANT: for best results the input read for the color/luma edge
133 *     detection should *NOT* be sRGB.
134 *
135 *  6. Before including SMAA.h you'll have to setup the render target metrics,
136 *     the target and any optional configuration defines. Optionally you can
137 *     use a preset.
138 *
139 *     You have the following targets available:
140 *         SMAA_HLSL_3
141 *         SMAA_HLSL_4
142 *         SMAA_HLSL_4_1
143 *         SMAA_GLSL_3 *
144 *         SMAA_GLSL_4 *
145 *
146 *         * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below).
147 *
148 *     And four presets:
149 *         SMAA_PRESET_LOW          (%60 of the quality)
150 *         SMAA_PRESET_MEDIUM       (%80 of the quality)
151 *         SMAA_PRESET_HIGH         (%95 of the quality)
152 *         SMAA_PRESET_ULTRA        (%99 of the quality)
153 *
154 *     For example:
155 *         #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0)
156 *         #define SMAA_HLSL_4
157 *         #define SMAA_PRESET_HIGH
158 *         #include "SMAA.h"
159 *
160 *     Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a
161 *     uniform variable. The code is designed to minimize the impact of not
162 *     using a constant value, but it is still better to hardcode it.
163 *
164 *     Depending on how you encoded 'areaTex' and 'searchTex', you may have to
165 *     add (and customize) the following defines before including SMAA.h:
166 *          #define SMAA_AREATEX_SELECT(sample) sample.rg
167 *          #define SMAA_SEARCHTEX_SELECT(sample) sample.r
168 *
169 *     If your engine is already using porting macros, you can define
170 *     SMAA_CUSTOM_SL, and define the porting functions by yourself.
171 *
172 *  7. Then, you'll have to setup the passes as indicated in the scheme above.
173 *     You can take a look into SMAA.fx, to see how we did it for our demo.
174 *     Checkout the function wrappers, you may want to copy-paste them!
175 *
176 *  8. It's recommended to validate the produced |edgesTex| and |blendTex|.
177 *     You can use a screenshot from your engine to compare the |edgesTex|
178 *     and |blendTex| produced inside of the engine with the results obtained
179 *     with the reference demo.
180 *
181 *  9. After you get the last pass to work, it's time to optimize. You'll have
182 *     to initialize a stencil buffer in the first pass (discard is already in
183 *     the code), then mask execution by using it the second pass. The last
184 *     pass should be executed in all pixels.
185 *
186 *
187 * After this point you can choose to enable predicated thresholding,
188 * temporal supersampling and motion blur integration:
189 *
190 * a) If you want to use predicated thresholding, take a look into
191 *    SMAA_PREDICATION; you'll need to pass an extra texture in the edge
192 *    detection pass.
193 *
194 * b) If you want to enable temporal supersampling (SMAA T2x):
195 *
196 * 1. The first step is to render using subpixel jitters. I won't go into
197 *    detail, but it's as simple as moving each vertex position in the
198 *    vertex shader, you can check how we do it in our DX10 demo.
199 *
200 * 2. Then, you must setup the temporal resolve. You may want to take a look
201 *    into SMAAResolve for resolving 2x modes. After you get it working, you'll
202 *    probably see ghosting everywhere. But fear not, you can enable the
203 *    CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro.
204 *    Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded.
205 *
206 * 3. The next step is to apply SMAA to each subpixel jittered frame, just as
207 *    done for 1x.
208 *
209 * 4. At this point you should already have something usable, but for best
210 *    results the proper area textures must be set depending on current jitter.
211 *    For this, the parameter 'subsampleIndices' of
212 *    'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x
213 *    mode:
214 *
215 *    @SUBSAMPLE_INDICES
216 *
217 *    | S# |  Camera Jitter   |  subsampleIndices    |
218 *    +----+------------------+---------------------+
219 *    |  0 |  ( 0.25, -0.25)  |  float4(1, 1, 1, 0)  |
220 *    |  1 |  (-0.25,  0.25)  |  float4(2, 2, 2, 0)  |
221 *
222 *    These jitter positions assume a bottom-to-top y axis. S# stands for the
223 *    sample number.
224 *
225 * More information about temporal supersampling here:
226 *    http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
227 *
228 * c) If you want to enable spatial multisampling (SMAA S2x):
229 *
230 * 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be
231 *    created with:
232 *      - DX10:     see below (*)
233 *      - DX10.1:   D3D10_STANDARD_MULTISAMPLE_PATTERN or
234 *      - DX11:     D3D11_STANDARD_MULTISAMPLE_PATTERN
235 *
236 *    This allows to ensure that the subsample order matches the table in
237 *    @SUBSAMPLE_INDICES.
238 *
239 *    (*) In the case of DX10, we refer the reader to:
240 *      - SMAA::detectMSAAOrder and
241 *      - SMAA::msaaReorder
242 *
243 *    These functions allow to match the standard multisample patterns by
244 *    detecting the subsample order for a specific GPU, and reordering
245 *    them appropriately.
246 *
247 * 2. A shader must be run to output each subsample into a separate buffer
248 *    (DX10 is required). You can use SMAASeparate for this purpose, or just do
249 *    it in an existing pass (for example, in the tone mapping pass, which has
250 *    the advantage of feeding tone mapped subsamples to SMAA, which will yield
251 *    better results).
252 *
253 * 3. The full SMAA 1x pipeline must be run for each separated buffer, storing
254 *    the results in the final buffer. The second run should alpha blend with
255 *    the existing final buffer using a blending factor of 0.5.
256 *    'subsampleIndices' must be adjusted as in the SMAA T2x case (see point
257 *    b).
258 *
259 * d) If you want to enable temporal supersampling on top of SMAA S2x
260 *    (which actually is SMAA 4x):
261 *
262 * 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is
263 *    to calculate SMAA S2x for current frame. In this case, 'subsampleIndices'
264 *    must be set as follows:
265 *
266 *    | F# | S# |   Camera Jitter    |    Net Jitter     |   subsampleIndices   |
267 *    +----+----+--------------------+-------------------+----------------------+
268 *    |  0 |  0 |  ( 0.125,  0.125)  |  ( 0.375, -0.125) |  float4(5, 3, 1, 3)  |
269 *    |  0 |  1 |  ( 0.125,  0.125)  |  (-0.125,  0.375) |  float4(4, 6, 2, 3)  |
270 *    +----+----+--------------------+-------------------+----------------------+
271 *    |  1 |  2 |  (-0.125, -0.125)  |  ( 0.125, -0.375) |  float4(3, 5, 1, 4)  |
272 *    |  1 |  3 |  (-0.125, -0.125)  |  (-0.375,  0.125) |  float4(6, 4, 2, 4)  |
273 *
274 *    These jitter positions assume a bottom-to-top y axis. F# stands for the
275 *    frame number. S# stands for the sample number.
276 *
277 * 2. After calculating SMAA S2x for current frame (with the new subsample
278 *    indices), previous frame must be reprojected as in SMAA T2x mode (see
279 *    point b).
280 *
281 * e) If motion blur is used, you may want to do the edge detection pass
282 *    together with motion blur. This has two advantages:
283 *
284 * 1. Pixels under heavy motion can be omitted from the edge detection process.
285 *    For these pixels we can just store "no edge", as motion blur will take
286 *    care of them.
287 * 2. The center pixel tap is reused.
288 *
289 * Note that in this case depth testing should be used instead of stenciling,
290 * as we have to write all the pixels in the motion blur pass.
291 *
292 * That's it!
293 */
294
295//-----------------------------------------------------------------------------
296// SMAA Presets
297
298/**
299 * Note that if you use one of these presets, the following configuration
300 * macros will be ignored if set in the "Configurable Defines" section.
301 */
302
303#if defined(SMAA_PRESET_LOW)
304#  define SMAA_THRESHOLD 0.15
305#  define SMAA_MAX_SEARCH_STEPS 4
306#  define SMAA_DISABLE_DIAG_DETECTION
307#  define SMAA_DISABLE_CORNER_DETECTION
308#elif defined(SMAA_PRESET_MEDIUM)
309#  define SMAA_THRESHOLD 0.1
310#  define SMAA_MAX_SEARCH_STEPS 8
311#  define SMAA_DISABLE_DIAG_DETECTION
312#  define SMAA_DISABLE_CORNER_DETECTION
313#elif defined(SMAA_PRESET_HIGH)
314#  define SMAA_THRESHOLD 0.1
315#  define SMAA_MAX_SEARCH_STEPS 16
316#  define SMAA_MAX_SEARCH_STEPS_DIAG 8
317#  define SMAA_CORNER_ROUNDING 25
318#elif defined(SMAA_PRESET_ULTRA)
319#  define SMAA_THRESHOLD 0.05
320#  define SMAA_MAX_SEARCH_STEPS 32
321#  define SMAA_MAX_SEARCH_STEPS_DIAG 16
322#  define SMAA_CORNER_ROUNDING 25
323#endif
324
325//-----------------------------------------------------------------------------
326// Configurable Defines
327
328/**
329 * SMAA_THRESHOLD specifies the threshold or sensitivity to edges.
330 * Lowering this value you will be able to detect more edges at the expense of
331 * performance.
332 *
333 * Range: [0, 0.5]
334 *   0.1 is a reasonable value, and allows to catch most visible edges.
335 *   0.05 is a rather overkill value, that allows to catch 'em all.
336 *
337 *   If temporal supersampling is used, 0.2 could be a reasonable value, as low
338 *   contrast edges are properly filtered by just 2x.
339 */
340#ifndef SMAA_THRESHOLD
341#  define SMAA_THRESHOLD 0.1
342#endif
343
344/**
345 * SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection.
346 *
347 * Range: depends on the depth range of the scene.
348 */
349#ifndef SMAA_DEPTH_THRESHOLD
350#  define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD)
351#endif
352
353/**
354 * SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the
355 * horizontal/vertical pattern searches, at each side of the pixel.
356 *
357 * In number of pixels, it's actually the double. So the maximum line length
358 * perfectly handled by, for example 16, is 64 (by perfectly, we meant that
359 * longer lines won't look as good, but still antialiased).
360 *
361 * Range: [0, 112]
362 */
363#ifndef SMAA_MAX_SEARCH_STEPS
364#  define SMAA_MAX_SEARCH_STEPS 16
365#endif
366
367/**
368 * SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the
369 * diagonal pattern searches, at each side of the pixel. In this case we jump
370 * one pixel at time, instead of two.
371 *
372 * Range: [0, 20]
373 *
374 * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16
375 * steps), but it can have a significant impact on older machines.
376 *
377 * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing.
378 */
379#ifndef SMAA_MAX_SEARCH_STEPS_DIAG
380#  define SMAA_MAX_SEARCH_STEPS_DIAG 8
381#endif
382
383/**
384 * SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded.
385 *
386 * Range: [0, 100]
387 *
388 * Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing.
389 */
390#ifndef SMAA_CORNER_ROUNDING
391#  define SMAA_CORNER_ROUNDING 25
392#endif
393
394/**
395 * If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times
396 * bigger contrast than current edge, current edge will be discarded.
397 *
398 * This allows to eliminate spurious crossing edges, and is based on the fact
399 * that, if there is too much contrast in a direction, that will hide
400 * perceptually contrast in the other neighbors.
401 */
402#ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
403#  define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0
404#endif
405
406/**
407 * Predicated thresholding allows to better preserve texture details and to
408 * improve performance, by decreasing the number of detected edges using an
409 * additional buffer like the light accumulation buffer, object ids or even the
410 * depth buffer (the depth buffer usage may be limited to indoor or short range
411 * scenes).
412 *
413 * It locally decreases the luma or color threshold if an edge is found in an
414 * additional buffer (so the global threshold can be higher).
415 *
416 * This method was developed by Playstation EDGE MLAA team, and used in
417 * Killzone 3, by using the light accumulation buffer. More information here:
418 *     http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx
419 */
420#ifndef SMAA_PREDICATION
421#  define SMAA_PREDICATION 0
422#endif
423
424/**
425 * Threshold to be used in the additional predication buffer.
426 *
427 * Range: depends on the input, so you'll have to find the magic number that
428 * works for you.
429 */
430#ifndef SMAA_PREDICATION_THRESHOLD
431#  define SMAA_PREDICATION_THRESHOLD 0.01
432#endif
433
434/**
435 * How much to scale the global threshold used for luma or color edge
436 * detection when using predication.
437 *
438 * Range: [1, 5]
439 */
440#ifndef SMAA_PREDICATION_SCALE
441#  define SMAA_PREDICATION_SCALE 2.0
442#endif
443
444/**
445 * How much to locally decrease the threshold.
446 *
447 * Range: [0, 1]
448 */
449#ifndef SMAA_PREDICATION_STRENGTH
450#  define SMAA_PREDICATION_STRENGTH 0.4
451#endif
452
453/**
454 * Temporal reprojection allows to remove ghosting artifacts when using
455 * temporal supersampling. We use the CryEngine 3 method which also introduces
456 * velocity weighting. This feature is of extreme importance for totally
457 * removing ghosting. More information here:
458 *    http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
459 *
460 * Note that you'll need to setup a velocity buffer for enabling reprojection.
461 * For static geometry, saving the previous depth buffer is a viable
462 * alternative.
463 */
464#ifndef SMAA_REPROJECTION
465#  define SMAA_REPROJECTION 0
466#endif
467
468/**
469 * SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows to
470 * remove ghosting trails behind the moving object, which are not removed by
471 * just using reprojection. Using low values will exhibit ghosting, while using
472 * high values will disable temporal supersampling under motion.
473 *
474 * Behind the scenes, velocity weighting removes temporal supersampling when
475 * the velocity of the subsamples differs (meaning they are different objects).
476 *
477 * Range: [0, 80]
478 */
479#ifndef SMAA_REPROJECTION_WEIGHT_SCALE
480#  define SMAA_REPROJECTION_WEIGHT_SCALE 30.0
481#endif
482
483/**
484 * On some compilers, discard cannot be used in vertex shaders. Thus, they need
485 * to be compiled separately.
486 */
487#ifndef SMAA_INCLUDE_VS
488#  define SMAA_INCLUDE_VS 1
489#endif
490#ifndef SMAA_INCLUDE_PS
491#  define SMAA_INCLUDE_PS 1
492#endif
493
494//-----------------------------------------------------------------------------
495// Texture Access Defines
496
497#ifndef SMAA_AREATEX_SELECT
498#  if defined(SMAA_HLSL_3)
499#    define SMAA_AREATEX_SELECT(sample) sample.ra
500#  else
501#    define SMAA_AREATEX_SELECT(sample) sample.rg
502#  endif
503#endif
504
505#ifndef SMAA_SEARCHTEX_SELECT
506#  define SMAA_SEARCHTEX_SELECT(sample) sample.r
507#endif
508
509#ifndef SMAA_DECODE_VELOCITY
510#  define SMAA_DECODE_VELOCITY(sample) sample.rg
511#endif
512
513//-----------------------------------------------------------------------------
514// Non-Configurable Defines
515
516#define SMAA_AREATEX_MAX_DISTANCE 16
517#define SMAA_AREATEX_MAX_DISTANCE_DIAG 20
518#define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0))
519#define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0)
520#define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0)
521#define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0)
522#define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0)
523
524//-----------------------------------------------------------------------------
525// Porting Functions
526
527#if defined(SMAA_HLSL_3)
528#  define SMAATexture2D(tex) sampler2D tex
529#  define SMAATexturePass2D(tex) tex
530#  define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
531#  define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
532/* clang-format off */
533#  define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0))
534/* clang-format on */
535#  define SMAASample(tex, coord) tex2D(tex, coord)
536#  define SMAASamplePoint(tex, coord) tex2D(tex, coord)
537#  define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy)
538#  define SMAA_FLATTEN [flatten]
539#  define SMAA_BRANCH [branch]
540#endif
541#if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1)
542SamplerState LinearSampler
543{
544  Filter = MIN_MAG_LINEAR_MIP_POINT;
545  AddressU = Clamp;
546  AddressV = Clamp;
547};
548SamplerState PointSampler
549{
550  Filter = MIN_MAG_MIP_POINT;
551  AddressU = Clamp;
552  AddressV = Clamp;
553};
554#  define SMAATexture2D(tex) Texture2D tex
555#  define SMAATexturePass2D(tex) tex
556#  define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0)
557#  define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0)
558/* clang-format off */
559#  define SMAASampleLevelZeroOffset(tex, coord, offset) tex.SampleLevel(LinearSampler, coord, 0, offset)
560/* clang-format on */
561#  define SMAASample(tex, coord) tex.Sample(LinearSampler, coord)
562#  define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord)
563#  define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset)
564#  define SMAA_FLATTEN [flatten]
565#  define SMAA_BRANCH [branch]
566#  define SMAATexture2DMS2(tex) Texture2DMS<float4, 2> tex
567#  define SMAALoad(tex, pos, sample) tex.Load(pos, sample)
568#  if defined(SMAA_HLSL_4_1)
569#    define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0)
570#  endif
571#endif
572#if defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4)
573#  define SMAATexture2D(tex) sampler2D tex
574#  define SMAATexturePass2D(tex) tex
575#  define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0)
576#  define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0)
577#  define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset)
578#  define SMAASample(tex, coord) texture(tex, coord)
579#  define SMAASamplePoint(tex, coord) texture(tex, coord)
580#  define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset)
581#  define SMAA_FLATTEN
582#  define SMAA_BRANCH
583#  define lerp(a, b, t) mix(a, b, t)
584#  define saturate(a) clamp(a, 0.0, 1.0)
585#  if defined(SMAA_GLSL_4)
586#    define mad(a, b, c) fma(a, b, c)
587#    define SMAAGather(tex, coord) textureGather(tex, coord)
588#  else
589#    define mad(a, b, c) (a * b + c)
590#  endif
591#  define float2 vec2
592#  define float3 vec3
593#  define float4 vec4
594#  define int2 ivec2
595#  define int3 ivec3
596#  define int4 ivec4
597#  define bool2 bvec2
598#  define bool3 bvec3
599#  define bool4 bvec4
600#endif
601
602/* clang-format off */
603#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)
604#  error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL
605#endif
606/* clang-format on */
607
608//-----------------------------------------------------------------------------
609// Misc functions
610
611/**
612 * Gathers current pixel, and the top-left neighbors.
613 */
614float3 SMAAGatherNeighbours(float2 texcoord, float4 offset[3], SMAATexture2D(tex))
615{
616#ifdef SMAAGather
617  return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb;
618#else
619  float P = SMAASamplePoint(tex, texcoord).r;
620  float Pleft = SMAASamplePoint(tex, offset[0].xy).r;
621  float Ptop = SMAASamplePoint(tex, offset[0].zw).r;
622  return float3(P, Pleft, Ptop);
623#endif
624}
625
626/**
627 * Adjusts the threshold by means of predication.
628 */
629float2 SMAACalculatePredicatedThreshold(float2 texcoord,
630                                        float4 offset[3],
631                                        SMAATexture2D(predicationTex))
632{
633  float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex));
634  float2 delta = abs(neighbours.xx - neighbours.yz);
635  float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta);
636  return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges);
637}
638
639/**
640 * Conditional move:
641 */
642void SMAAMovc(bool2 cond, inout float2 variable, float2 value)
643{
644  SMAA_FLATTEN if (cond.x) variable.x = value.x;
645  SMAA_FLATTEN if (cond.y) variable.y = value.y;
646}
647
648void SMAAMovc(bool4 cond, inout float4 variable, float4 value)
649{
650  SMAAMovc(cond.xy, variable.xy, value.xy);
651  SMAAMovc(cond.zw, variable.zw, value.zw);
652}
653
654#if SMAA_INCLUDE_VS
655//-----------------------------------------------------------------------------
656// Vertex Shaders
657
658/**
659 * Edge Detection Vertex Shader
660 */
661void SMAAEdgeDetectionVS(float2 texcoord, out float4 offset[3])
662{
663  offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy);
664  offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
665  offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy);
666}
667
668/**
669 * Blend Weight Calculation Vertex Shader
670 */
671void SMAABlendingWeightCalculationVS(float2 texcoord, out float2 pixcoord, out float4 offset[3])
672{
673  pixcoord = texcoord * SMAA_RT_METRICS.zw;
674
675  // We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
676  offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy);
677  offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy);
678
679  // And these for the searches, they indicate the ends of the loops:
680  offset[2] = mad(SMAA_RT_METRICS.xxyy,
681                  float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
682                  float4(offset[0].xz, offset[1].yw));
683}
684
685/**
686 * Neighborhood Blending Vertex Shader
687 */
688void SMAANeighborhoodBlendingVS(float2 texcoord, out float4 offset)
689{
690  offset = mad(SMAA_RT_METRICS.xyxy, float4(1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
691}
692#endif  // SMAA_INCLUDE_VS
693
694#if SMAA_INCLUDE_PS
695//-----------------------------------------------------------------------------
696// Edge Detection Pixel Shaders (First Pass)
697
698#  ifndef SMAA_LUMA_WEIGHT
699#    define SMAA_LUMA_WEIGHT float4(0.2126, 0.7152, 0.0722, 0.0)
700#  endif
701
702/**
703 * Luma Edge Detection
704 *
705 * IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and
706 * thus 'colorTex' should be a non-sRGB texture.
707 */
708float2 SMAALumaEdgeDetectionPS(float2 texcoord,
709                               float4 offset[3],
710                               SMAATexture2D(colorTex)
711#  if SMAA_PREDICATION
712                                   ,
713                               SMAATexture2D(predicationTex)
714#  endif
715)
716{
717// Calculate the threshold:
718#  if SMAA_PREDICATION
719  float2 threshold = SMAACalculatePredicatedThreshold(
720      texcoord, offset, SMAATexturePass2D(predicationTex));
721#  else
722  float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
723#  endif
724
725  // Calculate lumas:
726  // float4 weights = float4(0.2126, 0.7152, 0.0722, 0.0);
727  float4 weights = SMAA_LUMA_WEIGHT;
728  float L = dot(SMAASamplePoint(colorTex, texcoord).rgba, weights);
729
730  float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgba, weights);
731  float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgba, weights);
732
733  // We do the usual threshold:
734  float4 delta;
735  delta.xy = abs(L - float2(Lleft, Ltop));
736  float2 edges = step(threshold, delta.xy);
737
738#  ifndef SMAA_NO_DISCARD
739  // Then discard if there is no edge:
740  if (dot(edges, float2(1.0, 1.0)) == 0.0)
741    discard;
742#  endif
743
744  // Calculate right and bottom deltas:
745  float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgba, weights);
746  float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgba, weights);
747  delta.zw = abs(L - float2(Lright, Lbottom));
748
749  // Calculate the maximum delta in the direct neighborhood:
750  float2 maxDelta = max(delta.xy, delta.zw);
751
752  // Calculate left-left and top-top deltas:
753  float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgba, weights);
754  float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgba, weights);
755  delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop));
756
757  // Calculate the final maximum delta:
758  maxDelta = max(maxDelta.xy, delta.zw);
759  float finalDelta = max(maxDelta.x, maxDelta.y);
760
761  // Local contrast adaptation:
762#  if !defined(SHADER_API_OPENGL)
763  edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
764#  endif
765
766  return edges;
767}
768
769/**
770 * Color Edge Detection
771 *
772 * IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and
773 * thus 'colorTex' should be a non-sRGB texture.
774 */
775float2 SMAAColorEdgeDetectionPS(float2 texcoord,
776                                float4 offset[3],
777                                SMAATexture2D(colorTex)
778#  if SMAA_PREDICATION
779                                    ,
780                                SMAATexture2D(predicationTex)
781#  endif
782)
783{
784// Calculate the threshold:
785#  if SMAA_PREDICATION
786  float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
787#  else
788  float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
789#  endif
790
791  // Calculate color deltas:
792  float4 delta;
793  float3 C = SMAASamplePoint(colorTex, texcoord).rgb;
794
795  float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb;
796  float3 t = abs(C - Cleft);
797  delta.x = max(max(t.r, t.g), t.b);
798
799  float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb;
800  t = abs(C - Ctop);
801  delta.y = max(max(t.r, t.g), t.b);
802
803  // We do the usual threshold:
804  float2 edges = step(threshold, delta.xy);
805
806#  ifndef SMAA_NO_DISCARD
807  // Then discard if there is no edge:
808  if (dot(edges, float2(1.0, 1.0)) == 0.0)
809    discard;
810#  endif
811
812  // Calculate right and bottom deltas:
813  float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb;
814  t = abs(C - Cright);
815  delta.z = max(max(t.r, t.g), t.b);
816
817  float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb;
818  t = abs(C - Cbottom);
819  delta.w = max(max(t.r, t.g), t.b);
820
821  // Calculate the maximum delta in the direct neighborhood:
822  float2 maxDelta = max(delta.xy, delta.zw);
823
824  // Calculate left-left and top-top deltas:
825  float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb;
826  t = abs(C - Cleftleft);
827  delta.z = max(max(t.r, t.g), t.b);
828
829  float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb;
830  t = abs(C - Ctoptop);
831  delta.w = max(max(t.r, t.g), t.b);
832
833  // Calculate the final maximum delta:
834  maxDelta = max(maxDelta.xy, delta.zw);
835  float finalDelta = max(maxDelta.x, maxDelta.y);
836
837  // Local contrast adaptation:
838#  if !defined(SHADER_API_OPENGL)
839  edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
840#  endif
841
842  return edges;
843}
844
845/**
846 * Depth Edge Detection
847 */
848float2 SMAADepthEdgeDetectionPS(float2 texcoord, float4 offset[3], SMAATexture2D(depthTex))
849{
850  float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex));
851  float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z));
852  float2 edges = step(SMAA_DEPTH_THRESHOLD, delta);
853
854  if (dot(edges, float2(1.0, 1.0)) == 0.0)
855    discard;
856
857  return edges;
858}
859
860//-----------------------------------------------------------------------------
861// Diagonal Search Functions
862
863#  if !defined(SMAA_DISABLE_DIAG_DETECTION)
864
865/**
866 * Allows to decode two binary values from a bilinear-filtered access.
867 */
868float2 SMAADecodeDiagBilinearAccess(float2 e)
869{
870  // Bilinear access for fetching 'e' have a 0.25 offset, and we are
871  // interested in the R and G edges:
872  //
873  // +---G---+-------+
874  // |   x o R   x   |
875  // +-------+-------+
876  //
877  // Then, if one of these edge is enabled:
878  //   Red:   (0.75 * X + 0.25 * 1) => 0.25 or 1.0
879  //   Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0
880  //
881  // This function will unpack the values (mad + mul + round):
882  // wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1
883  e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
884  return round(e);
885}
886
887float4 SMAADecodeDiagBilinearAccess(float4 e)
888{
889  e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
890  return round(e);
891}
892
893/**
894 * These functions allows to perform diagonal pattern searches.
895 */
896float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e)
897{
898  float4 coord = float4(texcoord, -1.0, 1.0);
899  float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
900  while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9) {
901    coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
902    e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
903    coord.w = dot(e, float2(0.5, 0.5));
904  }
905  return coord.zw;
906}
907
908float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e)
909{
910  float4 coord = float4(texcoord, -1.0, 1.0);
911  coord.x += 0.25 * SMAA_RT_METRICS.x;  // See @SearchDiag2Optimization
912  float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
913  while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9) {
914    coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
915
916    // @SearchDiag2Optimization
917    // Fetch both edges at once using bilinear filtering:
918    e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
919    e = SMAADecodeDiagBilinearAccess(e);
920
921    // Non-optimized version:
922    // e.g = SMAASampleLevelZero(edgesTex, coord.xy).g;
923    // e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r;
924
925    coord.w = dot(e, float2(0.5, 0.5));
926  }
927  return coord.zw;
928}
929
930/**
931 * Similar to SMAAArea, this calculates the area corresponding to a certain
932 * diagonal distance and crossing edges 'e'.
933 */
934float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset)
935{
936  float2 texcoord = mad(
937      float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist);
938
939  // We do a scale and bias for mapping to texel space:
940  texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
941
942  // Diagonal areas are on the second half of the texture:
943  texcoord.x += 0.5;
944
945  // Move to proper place, according to the subpixel offset:
946  texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
947
948  // Do it!
949  return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
950}
951
952/**
953 * This searches for diagonal patterns and returns the corresponding weights.
954 */
955float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex),
956                                SMAATexture2D(areaTex),
957                                float2 texcoord,
958                                float2 e,
959                                float4 subsampleIndices)
960{
961  float2 weights = float2(0.0, 0.0);
962
963  // Search for the line ends:
964  float4 d;
965  float2 end;
966  if (e.r > 0.0) {
967    d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end);
968    d.x += float(end.y > 0.9);
969  }
970  else
971    d.xz = float2(0.0, 0.0);
972  d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end);
973
974  SMAA_BRANCH
975  if (d.x + d.y > 2.0) {  // d.x + d.y + 1 > 3
976    // Fetch the crossing edges:
977    float4 coords = mad(
978        float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
979    float4 c;
980    c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg;
981    c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2(1, 0)).rg;
982    c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw);
983
984    // Non-optimized version:
985    // float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
986    // float4 c;
987    // c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1,  0)).g;
988    // c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0,  0)).r;
989    // c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1,  0)).g;
990    // c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r;
991
992    // Merge crossing edges at each side into a single value:
993    float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
994
995    // Remove the crossing edge if we didn't found the end of the line:
996    SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0));
997
998    // Fetch the areas for this line:
999    weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z);
1000  }
1001
1002  // Search for the line ends:
1003  d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end);
1004  if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) {
1005    d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end);
1006    d.y += float(end.y > 0.9);
1007  }
1008  else
1009    d.yw = float2(0.0, 0.0);
1010
1011  SMAA_BRANCH
1012  if (d.x + d.y > 2.0) {  // d.x + d.y + 1 > 3
1013    // Fetch the crossing edges:
1014    float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
1015    float4 c;
1016    c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
1017    c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(0, -1)).r;
1018    c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2(1, 0)).gr;
1019    float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
1020
1021    // Remove the crossing edge if we didn't found the end of the line:
1022    SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0));
1023
1024    // Fetch the areas for this line:
1025    weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr;
1026  }
1027
1028  return weights;
1029}
1030#  endif
1031
1032//-----------------------------------------------------------------------------
1033// Horizontal/Vertical Search Functions
1034
1035/**
1036 * This allows to determine how much length should we add in the last step
1037 * of the searches. It takes the bilinearly interpolated edge (see
1038 * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and
1039 * crossing edges are active.
1040 */
1041float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset)
1042{
1043  // The texture is flipped vertically, with left and right cases taking half
1044  // of the space horizontally:
1045  float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0);
1046  float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0);
1047
1048  // Scale and bias to access texel centers:
1049  scale += float2(-1.0, 1.0);
1050  bias += float2(0.5, -0.5);
1051
1052  // Convert from pixel coordinates to texcoords:
1053  // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped)
1054  scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
1055  bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
1056
1057  // Lookup the search texture:
1058  return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias)));
1059}
1060
1061/**
1062 * Horizontal/vertical search functions for the 2nd pass.
1063 */
1064float SMAASearchXLeft(SMAATexture2D(edgesTex),
1065                      SMAATexture2D(searchTex),
1066                      float2 texcoord,
1067                      float end)
1068{
1069  /**
1070   * @PSEUDO_GATHER4
1071   * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
1072   * sample between edge, thus fetching four edges in a row.
1073   * Sampling with different offsets in each direction allows to disambiguate
1074   * which edges are active from the four fetched ones.
1075   */
1076  float2 e = float2(0.0, 1.0);
1077  while (texcoord.x > end && e.g > 0.8281 &&  // Is there some edge not activated?
1078         e.r == 0.0) {                        // Or is there a crossing edge that breaks the line?
1079    e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1080    texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
1081  }
1082
1083  float offset = mad(
1084      -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25);
1085  return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
1086
1087  // Non-optimized version:
1088  // We correct the previous (-0.25, -0.125) offset we applied:
1089  // texcoord.x += 0.25 * SMAA_RT_METRICS.x;
1090
1091  // The searches are bias by 1, so adjust the coords accordingly:
1092  // texcoord.x += SMAA_RT_METRICS.x;
1093
1094  // Disambiguate the length added by the last step:
1095  // texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step
1096  // texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) *
1097  // SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0); return mad(SMAA_RT_METRICS.x, offset,
1098  // texcoord.x);
1099}
1100
1101float SMAASearchXRight(SMAATexture2D(edgesTex),
1102                       SMAATexture2D(searchTex),
1103                       float2 texcoord,
1104                       float end)
1105{
1106  float2 e = float2(0.0, 1.0);
1107  while (texcoord.x < end && e.g > 0.8281 &&  // Is there some edge not activated?
1108         e.r == 0.0) {                        // Or is there a crossing edge that breaks the line?
1109    e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1110    texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
1111  }
1112  float offset = mad(
1113      -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25);
1114  return mad(-SMAA_RT_METRICS.x, offset, texcoord.x);
1115}
1116
1117float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end)
1118{
1119  float2 e = float2(1.0, 0.0);
1120  while (texcoord.y > end && e.r > 0.8281 &&  // Is there some edge not activated?
1121         e.g == 0.0) {                        // Or is there a crossing edge that breaks the line?
1122    e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1123    texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
1124  }
1125  float offset = mad(
1126      -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25);
1127  return mad(SMAA_RT_METRICS.y, offset, texcoord.y);
1128}
1129
1130float SMAASearchYDown(SMAATexture2D(edgesTex),
1131                      SMAATexture2D(searchTex),
1132                      float2 texcoord,
1133                      float end)
1134{
1135  float2 e = float2(1.0, 0.0);
1136  while (texcoord.y < end && e.r > 0.8281 &&  // Is there some edge not activated?
1137         e.g == 0.0) {                        // Or is there a crossing edge that breaks the line?
1138    e = SMAASampleLevelZero(edgesTex, texcoord).rg;
1139    texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
1140  }
1141  float offset = mad(
1142      -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25);
1143  return mad(-SMAA_RT_METRICS.y, offset, texcoord.y);
1144}
1145
1146/**
1147 * Ok, we have the distance and both crossing edges. So, what are the areas
1148 * at each side of current edge?
1149 */
1150float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset)
1151{
1152  // Rounding prevents precision errors of bilinear filtering:
1153  float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE),
1154                        round(4.0 * float2(e1, e2)),
1155                        dist);
1156
1157  // We do a scale and bias for mapping to texel space:
1158  texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
1159
1160  // Move to proper place, according to the subpixel offset:
1161  texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y);
1162
1163  // Do it!
1164  return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
1165}
1166
1167//-----------------------------------------------------------------------------
1168// Corner Detection Functions
1169
1170void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex),
1171                                       inout float2 weights,
1172                                       float4 texcoord,
1173                                       float2 d)
1174{
1175#  if !defined(SMAA_DISABLE_CORNER_DETECTION)
1176  float2 leftRight = step(d.xy, d.yx);
1177  float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
1178
1179  rounding /= leftRight.x + leftRight.y;  // Reduce blending for pixels in the center of a line.
1180
1181  float2 factor = float2(1.0, 1.0);
1182  factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r;
1183  factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r;
1184  factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r;
1185  factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r;
1186
1187  weights *= saturate(factor);
1188#  endif
1189}
1190
1191void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex),
1192                                     inout float2 weights,
1193                                     float4 texcoord,
1194                                     float2 d)
1195{
1196#  if !defined(SMAA_DISABLE_CORNER_DETECTION)
1197  float2 leftRight = step(d.xy, d.yx);
1198  float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
1199
1200  rounding /= leftRight.x + leftRight.y;
1201
1202  float2 factor = float2(1.0, 1.0);
1203  factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(1, 0)).g;
1204  factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).g;
1205  factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g;
1206  factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g;
1207
1208  weights *= saturate(factor);
1209#  endif
1210}
1211
1212//-----------------------------------------------------------------------------
1213// Blending Weight Calculation Pixel Shader (Second Pass)
1214
1215float4 SMAABlendingWeightCalculationPS(float2 texcoord,
1216                                       float2 pixcoord,
1217                                       float4 offset[3],
1218                                       SMAATexture2D(edgesTex),
1219                                       SMAATexture2D(areaTex),
1220                                       SMAATexture2D(searchTex),
1221                                       float4 subsampleIndices)
1222{  // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES.
1223  float4 weights = float4(0.0, 0.0, 0.0, 0.0);
1224
1225  float2 e = SMAASample(edgesTex, texcoord).rg;
1226
1227  SMAA_BRANCH
1228  if (e.g > 0.0) {  // Edge at north
1229#  if !defined(SMAA_DISABLE_DIAG_DETECTION)
1230    // Diagonals have both north and west edges, so searching for them in
1231    // one of the boundaries is enough.
1232    weights.rg = SMAACalculateDiagWeights(
1233        SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices);
1234
1235    // We give priority to diagonals, so if we find a diagonal we skip
1236    // horizontal/vertical processing.
1237    SMAA_BRANCH
1238    if (weights.r == -weights.g) {  // weights.r + weights.g == 0.0
1239#  endif
1240
1241      float2 d;
1242
1243      // Find the distance to the left:
1244      float3 coords;
1245      coords.x = SMAASearchXLeft(
1246          SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x);
1247      coords.y =
1248          offset[1].y;  // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET)
1249      d.x = coords.x;
1250
1251      // Now fetch the left crossing edges, two at a time using bilinear
1252      // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
1253      // discern what value each edge has:
1254      float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r;
1255
1256      // Find the distance to the right:
1257      coords.z = SMAASearchXRight(
1258          SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y);
1259      d.y = coords.z;
1260
1261      // We want the distances to be in pixel units (doing this here allow to
1262      // better interleave arithmetic and memory accesses):
1263      d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx)));
1264
1265      // SMAAArea below needs a sqrt, as the areas texture is compressed
1266      // quadratically:
1267      float2 sqrt_d = sqrt(d);
1268
1269      // Fetch the right crossing edges:
1270      float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r;
1271
1272      // Ok, we know how this pattern looks like, now it is time for getting
1273      // the actual area:
1274      weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y);
1275
1276      // Fix corners:
1277      coords.y = texcoord.y;
1278      SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d);
1279
1280#  if !defined(SMAA_DISABLE_DIAG_DETECTION)
1281    }
1282    else
1283      e.r = 0.0;  // Skip vertical processing.
1284#  endif
1285  }
1286
1287  SMAA_BRANCH
1288  if (e.r > 0.0) {  // Edge at west
1289    float2 d;
1290
1291    // Find the distance to the top:
1292    float3 coords;
1293    coords.y = SMAASearchYUp(
1294        SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z);
1295    coords.x = offset[0].x;  // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x;
1296    d.x = coords.y;
1297
1298    // Fetch the top crossing edges:
1299    float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g;
1300
1301    // Find the distance to the bottom:
1302    coords.z = SMAASearchYDown(
1303        SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w);
1304    d.y = coords.z;
1305
1306    // We want the distances to be in pixel units:
1307    d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy)));
1308
1309    // SMAAArea below needs a sqrt, as the areas texture is compressed
1310    // quadratically:
1311    float2 sqrt_d = sqrt(d);
1312
1313    // Fetch the bottom crossing edges:
1314    float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g;
1315
1316    // Get the area for this direction:
1317    weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x);
1318
1319    // Fix corners:
1320    coords.x = texcoord.x;
1321    SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d);
1322  }
1323
1324  return weights;
1325}
1326
1327//-----------------------------------------------------------------------------
1328// Neighborhood Blending Pixel Shader (Third Pass)
1329
1330float4 SMAANeighborhoodBlendingPS(float2 texcoord,
1331                                  float4 offset,
1332                                  SMAATexture2D(colorTex),
1333                                  SMAATexture2D(blendTex)
1334#  if SMAA_REPROJECTION
1335                                      ,
1336                                  SMAATexture2D(velocityTex)
1337#  endif
1338)
1339{
1340  // Fetch the blending weights for current pixel:
1341  float4 a;
1342  a.x = SMAASample(blendTex, offset.xy).a;   // Right
1343  a.y = SMAASample(blendTex, offset.zw).g;   // Top
1344  a.wz = SMAASample(blendTex, texcoord).xz;  // Bottom / Left
1345
1346  // Is there any blending weight with a value greater than 0.0?
1347  SMAA_BRANCH
1348  if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) {
1349    float4 color = SMAASampleLevelZero(colorTex, texcoord);
1350
1351#  if SMAA_REPROJECTION
1352    float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord));
1353
1354    // Pack velocity into the alpha channel:
1355    color.a = sqrt(5.0 * length(velocity));
1356#  endif
1357
1358    return color;
1359  }
1360  else {
1361    bool h = max(a.x, a.z) > max(a.y, a.w);  // max(horizontal) > max(vertical)
1362
1363    // Calculate the blending offsets:
1364    float4 blendingOffset = float4(0.0, a.y, 0.0, a.w);
1365    float2 blendingWeight = a.yw;
1366    SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0));
1367    SMAAMovc(bool2(h, h), blendingWeight, a.xz);
1368    blendingWeight /= dot(blendingWeight, float2(1.0, 1.0));
1369
1370    // Calculate the texture coordinates:
1371    float4 blendingCoord = mad(
1372        blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy);
1373
1374    // We exploit bilinear filtering to mix current pixel with the chosen
1375    // neighbor:
1376    float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy);
1377    color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw);
1378
1379#  if SMAA_REPROJECTION
1380    // Antialias velocity for proper reprojection in a later stage:
1381    float2 velocity = blendingWeight.x *
1382                      SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy));
1383    velocity += blendingWeight.y *
1384                SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw));
1385
1386    // Pack velocity into the alpha channel:
1387    color.a = sqrt(5.0 * length(velocity));
1388#  endif
1389
1390    return color;
1391  }
1392}
1393
1394//-----------------------------------------------------------------------------
1395// Temporal Resolve Pixel Shader (Optional Pass)
1396
1397float4 SMAAResolvePS(float2 texcoord,
1398                     SMAATexture2D(currentColorTex),
1399                     SMAATexture2D(previousColorTex)
1400#  if SMAA_REPROJECTION
1401                         ,
1402                     SMAATexture2D(velocityTex)
1403#  endif
1404)
1405{
1406#  if SMAA_REPROJECTION
1407  // Velocity is assumed to be calculated for motion blur, so we need to
1408  // inverse it for reprojection:
1409  float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg);
1410
1411  // Fetch current pixel:
1412  float4 current = SMAASamplePoint(currentColorTex, texcoord);
1413
1414  // Reproject current coordinates and fetch previous pixel:
1415  float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity);
1416
1417  // Attenuate the previous pixel if the velocity is different:
1418  float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0;
1419  float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE);
1420
1421  // Blend the pixels according to the calculated weight:
1422  return lerp(current, previous, weight);
1423#  else
1424  // Just blend the pixels:
1425  float4 current = SMAASamplePoint(currentColorTex, texcoord);
1426  float4 previous = SMAASamplePoint(previousColorTex, texcoord);
1427  return lerp(current, previous, 0.5);
1428#  endif
1429}
1430
1431//-----------------------------------------------------------------------------
1432// Separate Multisamples Pixel Shader (Optional Pass)
1433
1434#  ifdef SMAALoad
1435void SMAASeparatePS(float4 position,
1436                    float2 texcoord,
1437                    out float4 target0,
1438                    out float4 target1,
1439                    SMAATexture2DMS2(colorTexMS))
1440{
1441  int2 pos = int2(position.xy);
1442  target0 = SMAALoad(colorTexMS, pos, 0);
1443  target1 = SMAALoad(colorTexMS, pos, 1);
1444}
1445#  endif
1446
1447//-----------------------------------------------------------------------------
1448#endif  // SMAA_INCLUDE_PS
1449