SubpixelMorphologicalAntialiasing.hlsl 56 KB

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