SmaaEdge.glsl 55 KB

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