TRAANode.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import { HalfFloatType, Vector2, RenderTarget, RendererUtils, QuadMesh, NodeMaterial, TempNode, NodeUpdateType, Matrix4 } from 'three/webgpu';
  2. import { add, float, If, Loop, int, Fn, min, max, clamp, nodeObject, texture, uniform, uv, vec2, vec4, luminance, convertToTexture, passTexture, velocity } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. const _size = /*@__PURE__*/ new Vector2();
  5. let _rendererState;
  6. /**
  7. * A special node that applies TRAA (Temporal Reprojection Anti-Aliasing).
  8. *
  9. * References:
  10. * - {@link https://alextardif.com/TAA.html}
  11. * - {@link https://www.elopezr.com/temporal-aa-and-the-quest-for-the-holy-trail/}
  12. *
  13. * @augments TempNode
  14. * @three_import import { traa } from 'three/addons/tsl/display/TRAANode.js';
  15. */
  16. class TRAANode extends TempNode {
  17. static get type() {
  18. return 'TRAANode';
  19. }
  20. /**
  21. * Constructs a new TRAA node.
  22. *
  23. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  24. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  25. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  26. * @param {Camera} camera - The camera the scene is rendered with.
  27. */
  28. constructor( beautyNode, depthNode, velocityNode, camera ) {
  29. super( 'vec4' );
  30. /**
  31. * This flag can be used for type testing.
  32. *
  33. * @type {boolean}
  34. * @readonly
  35. * @default true
  36. */
  37. this.isTRAANode = true;
  38. /**
  39. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  40. * its effect once per frame in `updateBefore()`.
  41. *
  42. * @type {string}
  43. * @default 'frame'
  44. */
  45. this.updateBeforeType = NodeUpdateType.FRAME;
  46. /**
  47. * The texture node that represents the input of the effect.
  48. *
  49. * @type {TextureNode}
  50. */
  51. this.beautyNode = beautyNode;
  52. /**
  53. * A node that represents the scene's velocity.
  54. *
  55. * @type {TextureNode}
  56. */
  57. this.depthNode = depthNode;
  58. /**
  59. * A node that represents the scene's velocity.
  60. *
  61. * @type {TextureNode}
  62. */
  63. this.velocityNode = velocityNode;
  64. /**
  65. * The camera the scene is rendered with.
  66. *
  67. * @type {TextureNode}
  68. */
  69. this.camera = camera;
  70. /**
  71. * The jitter index selects the current camera offset value.
  72. *
  73. * @private
  74. * @type {number}
  75. * @default 0
  76. */
  77. this._jitterIndex = 0;
  78. /**
  79. * A uniform node holding the inverse resolution value.
  80. *
  81. * @private
  82. * @type {UniformNode<vec2>}
  83. */
  84. this._invSize = uniform( new Vector2() );
  85. /**
  86. * The render target that represents the history of frame data.
  87. *
  88. * @private
  89. * @type {?RenderTarget}
  90. */
  91. this._historyRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  92. this._historyRenderTarget.texture.name = 'TRAANode.history';
  93. /**
  94. * The render target for the resolve.
  95. *
  96. * @private
  97. * @type {?RenderTarget}
  98. */
  99. this._resolveRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  100. this._resolveRenderTarget.texture.name = 'TRAANode.resolve';
  101. /**
  102. * Material used for the resolve step.
  103. *
  104. * @private
  105. * @type {NodeMaterial}
  106. */
  107. this._resolveMaterial = new NodeMaterial();
  108. this._resolveMaterial.name = 'TRAA.resolve';
  109. /**
  110. * The result of the effect is represented as a separate texture node.
  111. *
  112. * @private
  113. * @type {PassTextureNode}
  114. */
  115. this._textureNode = passTexture( this, this._resolveRenderTarget.texture );
  116. /**
  117. * Used to save the original/unjittered projection matrix.
  118. *
  119. * @private
  120. * @type {Matrix4}
  121. */
  122. this._originalProjectionMatrix = new Matrix4();
  123. /**
  124. * Sync the post processing stack with the TRAA node.
  125. * @private
  126. * @type {boolean}
  127. */
  128. this._needsPostProcessingSync = false;
  129. }
  130. /**
  131. * Returns the result of the effect as a texture node.
  132. *
  133. * @return {PassTextureNode} A texture node that represents the result of the effect.
  134. */
  135. getTextureNode() {
  136. return this._textureNode;
  137. }
  138. /**
  139. * Sets the size of the effect.
  140. *
  141. * @param {number} width - The width of the effect.
  142. * @param {number} height - The height of the effect.
  143. */
  144. setSize( width, height ) {
  145. this._historyRenderTarget.setSize( width, height );
  146. this._resolveRenderTarget.setSize( width, height );
  147. this._invSize.value.set( 1 / width, 1 / height );
  148. }
  149. /**
  150. * Defines the TRAA's current jitter as a view offset
  151. * to the scene's camera.
  152. *
  153. * @param {number} width - The width of the effect.
  154. * @param {number} height - The height of the effect.
  155. */
  156. setViewOffset( width, height ) {
  157. // save original/unjittered projection matrix for velocity pass
  158. this.camera.updateProjectionMatrix();
  159. this._originalProjectionMatrix.copy( this.camera.projectionMatrix );
  160. velocity.setProjectionMatrix( this._originalProjectionMatrix );
  161. //
  162. const viewOffset = {
  163. fullWidth: width,
  164. fullHeight: height,
  165. offsetX: 0,
  166. offsetY: 0,
  167. width: width,
  168. height: height
  169. };
  170. const jitterOffset = _JitterVectors[ this._jitterIndex ];
  171. this.camera.setViewOffset(
  172. viewOffset.fullWidth, viewOffset.fullHeight,
  173. viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
  174. viewOffset.width, viewOffset.height
  175. );
  176. }
  177. /**
  178. * Clears the view offset from the scene's camera.
  179. */
  180. clearViewOffset() {
  181. this.camera.clearViewOffset();
  182. velocity.setProjectionMatrix( null );
  183. // update jitter index
  184. this._jitterIndex ++;
  185. this._jitterIndex = this._jitterIndex % ( _JitterVectors.length - 1 );
  186. }
  187. /**
  188. * This method is used to render the effect once per frame.
  189. *
  190. * @param {NodeFrame} frame - The current node frame.
  191. */
  192. updateBefore( frame ) {
  193. const { renderer } = frame;
  194. // keep the TRAA in sync with the dimensions of the beauty node
  195. const beautyRenderTarget = ( this.beautyNode.isRTTNode ) ? this.beautyNode.renderTarget : this.beautyNode.passNode.renderTarget;
  196. const width = beautyRenderTarget.texture.width;
  197. const height = beautyRenderTarget.texture.height;
  198. //
  199. if ( this._needsPostProcessingSync === true ) {
  200. this.setViewOffset( width, height );
  201. this._needsPostProcessingSync = false;
  202. }
  203. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  204. //
  205. const needsRestart = this._historyRenderTarget.width !== width || this._historyRenderTarget.height !== height;
  206. this.setSize( width, height );
  207. // every time when the dimensions change we need fresh history data
  208. if ( needsRestart === true ) {
  209. // bind and clear render target to make sure they are initialized after the resize which triggers a dispose()
  210. renderer.setRenderTarget( this._historyRenderTarget );
  211. renderer.clear();
  212. renderer.setRenderTarget( this._resolveRenderTarget );
  213. renderer.clear();
  214. // make sure to reset the history with the contents of the beauty buffer otherwise subsequent frames after the
  215. // resize will fade from a darker color to the correct one because the history was cleared with black.
  216. renderer.copyTextureToTexture( beautyRenderTarget.texture, this._historyRenderTarget.texture );
  217. }
  218. // resolve
  219. renderer.setRenderTarget( this._resolveRenderTarget );
  220. _quadMesh.material = this._resolveMaterial;
  221. _quadMesh.render( renderer );
  222. renderer.setRenderTarget( null );
  223. // update history
  224. renderer.copyTextureToTexture( this._resolveRenderTarget.texture, this._historyRenderTarget.texture );
  225. // restore
  226. RendererUtils.restoreRendererState( renderer, _rendererState );
  227. }
  228. /**
  229. * This method is used to setup the effect's render targets and TSL code.
  230. *
  231. * @param {NodeBuilder} builder - The current node builder.
  232. * @return {PassTextureNode}
  233. */
  234. setup( builder ) {
  235. const postProcessing = builder.context.postProcessing;
  236. if ( postProcessing ) {
  237. this._needsPostProcessingSync = true;
  238. postProcessing.context.onBeforePostProcessing = () => {
  239. const size = builder.renderer.getDrawingBufferSize( _size );
  240. this.setViewOffset( size.width, size.height );
  241. };
  242. postProcessing.context.onAfterPostProcessing = () => {
  243. this.clearViewOffset();
  244. };
  245. }
  246. const historyTexture = texture( this._historyRenderTarget.texture );
  247. const sampleTexture = this.beautyNode;
  248. const depthTexture = this.depthNode;
  249. const velocityTexture = this.velocityNode;
  250. const resolve = Fn( () => {
  251. const uvNode = uv();
  252. const minColor = vec4( 10000 ).toVar();
  253. const maxColor = vec4( - 10000 ).toVar();
  254. const closestDepth = float( 1 ).toVar();
  255. const closestDepthPixelPosition = vec2( 0 ).toVar();
  256. // sample a 3x3 neighborhood to create a box in color space
  257. // clamping the history color with the resulting min/max colors mitigates ghosting
  258. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'x' }, ( { x } ) => {
  259. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'y' }, ( { y } ) => {
  260. const uvNeighbor = uvNode.add( vec2( float( x ), float( y ) ).mul( this._invSize ) ).toVar();
  261. const colorNeighbor = max( vec4( 0 ), sampleTexture.sample( uvNeighbor ) ).toVar(); // use max() to avoid propagate garbage values
  262. minColor.assign( min( minColor, colorNeighbor ) );
  263. maxColor.assign( max( maxColor, colorNeighbor ) );
  264. const currentDepth = depthTexture.sample( uvNeighbor ).r.toVar();
  265. // find the sample position of the closest depth in the neighborhood (used for velocity)
  266. If( currentDepth.lessThan( closestDepth ), () => {
  267. closestDepth.assign( currentDepth );
  268. closestDepthPixelPosition.assign( uvNeighbor );
  269. } );
  270. } );
  271. } );
  272. // sampling/reprojection
  273. const offset = velocityTexture.sample( closestDepthPixelPosition ).xy.mul( vec2( 0.5, - 0.5 ) ); // NDC to uv offset
  274. const currentColor = sampleTexture.sample( uvNode );
  275. const historyColor = historyTexture.sample( uvNode.sub( offset ) );
  276. // clamping
  277. const clampedHistoryColor = clamp( historyColor, minColor, maxColor );
  278. // flicker reduction based on luminance weighing
  279. const currentWeight = float( 0.05 ).toVar();
  280. const historyWeight = currentWeight.oneMinus().toVar();
  281. const compressedCurrent = currentColor.mul( float( 1 ).div( ( max( currentColor.r, currentColor.g, currentColor.b ).add( 1.0 ) ) ) );
  282. const compressedHistory = clampedHistoryColor.mul( float( 1 ).div( ( max( clampedHistoryColor.r, clampedHistoryColor.g, clampedHistoryColor.b ).add( 1.0 ) ) ) );
  283. const luminanceCurrent = luminance( compressedCurrent.rgb );
  284. const luminanceHistory = luminance( compressedHistory.rgb );
  285. currentWeight.mulAssign( float( 1.0 ).div( luminanceCurrent.add( 1 ) ) );
  286. historyWeight.mulAssign( float( 1.0 ).div( luminanceHistory.add( 1 ) ) );
  287. return add( currentColor.mul( currentWeight ), clampedHistoryColor.mul( historyWeight ) ).div( max( currentWeight.add( historyWeight ), 0.00001 ) );
  288. } );
  289. // materials
  290. this._resolveMaterial.colorNode = resolve();
  291. return this._textureNode;
  292. }
  293. /**
  294. * Frees internal resources. This method should be called
  295. * when the effect is no longer required.
  296. */
  297. dispose() {
  298. this._historyRenderTarget.dispose();
  299. this._resolveRenderTarget.dispose();
  300. this._resolveMaterial.dispose();
  301. }
  302. }
  303. export default TRAANode;
  304. // These jitter vectors are specified in integers because it is easier.
  305. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  306. // before being used, thus these integers need to be scaled by 1/16.
  307. //
  308. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  309. const _JitterVectors = [
  310. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  311. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  312. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  313. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  314. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  315. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  316. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  317. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  318. ];
  319. /**
  320. * TSL function for creating a TRAA node for Temporal Reprojection Anti-Aliasing.
  321. *
  322. * @tsl
  323. * @function
  324. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  325. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  326. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  327. * @param {Camera} camera - The camera the scene is rendered with.
  328. * @returns {TRAANode}
  329. */
  330. export const traa = ( beautyNode, depthNode, velocityNode, camera ) => nodeObject( new TRAANode( convertToTexture( beautyNode ), depthNode, velocityNode, camera ) );
粤ICP备19079148号