SMAA.h 54 KB

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