opengl_smaa.glsl 52 KB

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