TRAAPassNode.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import { Color, Vector2, NearestFilter, Matrix4, PostProcessingUtils, PassNode, QuadMesh, NodeMaterial } from 'three/webgpu';
  2. import { add, float, If, Loop, int, Fn, min, max, clamp, nodeObject, texture, uniform, uv, vec2, vec4, luminance } from 'three/tsl';
  3. /** @module TRAAPassNode **/
  4. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  5. const _size = /*@__PURE__*/ new Vector2();
  6. let _rendererState;
  7. /**
  8. * A special render pass node that renders the scene with TRAA (Temporal Reprojection Anti-Aliasing).
  9. *
  10. * Note: The current implementation does not yet support MRT setups.
  11. *
  12. * References:
  13. * - {@link https://alextardif.com/TAA.html}
  14. * - {@link https://www.elopezr.com/temporal-aa-and-the-quest-for-the-holy-trail/}
  15. *
  16. * @augments PassNode
  17. */
  18. class TRAAPassNode extends PassNode {
  19. static get type() {
  20. return 'TRAAPassNode';
  21. }
  22. /**
  23. * Constructs a new TRAA pass node.
  24. *
  25. * @param {Scene} scene - The scene to render.
  26. * @param {Camera} camera - The camera to render the scene with.
  27. */
  28. constructor( scene, camera ) {
  29. super( PassNode.COLOR, scene, camera );
  30. /**
  31. * This flag can be used for type testing.
  32. *
  33. * @type {Boolean}
  34. * @readonly
  35. * @default true
  36. */
  37. this.isTRAAPassNode = true;
  38. /**
  39. * The clear color of the pass.
  40. *
  41. * @type {Color}
  42. * @default 0x000000
  43. */
  44. this.clearColor = new Color( 0x000000 );
  45. /**
  46. * The clear alpha of the pass.
  47. *
  48. * @type {Number}
  49. * @default 0
  50. */
  51. this.clearAlpha = 0;
  52. /**
  53. * The jitter index selects the current camera offset value.
  54. *
  55. * @private
  56. * @type {Number}
  57. * @default 0
  58. */
  59. this._jitterIndex = 0;
  60. /**
  61. * Used to save the original/unjittered projection matrix.
  62. *
  63. * @private
  64. * @type {Matrix4}
  65. */
  66. this._originalProjectionMatrix = new Matrix4();
  67. /**
  68. * A uniform node holding the inverse resolution value.
  69. *
  70. * @private
  71. * @type {UniformNode<vec2>}
  72. */
  73. this._invSize = uniform( new Vector2() );
  74. /**
  75. * The render target that holds the current sample.
  76. *
  77. * @private
  78. * @type {RenderTarget?}
  79. */
  80. this._sampleRenderTarget = null;
  81. /**
  82. * The render target that represents the history of frame data.
  83. *
  84. * @private
  85. * @type {RenderTarget?}
  86. */
  87. this._historyRenderTarget = null;
  88. /**
  89. * Material used for the resolve step.
  90. *
  91. * @private
  92. * @type {NodeMaterial}
  93. */
  94. this._resolveMaterial = new NodeMaterial();
  95. this._resolveMaterial.name = 'TRAA.Resolve';
  96. }
  97. /**
  98. * Sets the size of the effect.
  99. *
  100. * @param {Number} width - The width of the effect.
  101. * @param {Number} height - The height of the effect.
  102. * @return {Boolean} Whether the TRAA needs a restart or not. That is required after a resize since buffer data with different sizes can't be resolved.
  103. */
  104. setSize( width, height ) {
  105. super.setSize( width, height );
  106. let needsRestart = false;
  107. if ( this.renderTarget.width !== this._sampleRenderTarget.width || this.renderTarget.height !== this._sampleRenderTarget.height ) {
  108. this._sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
  109. this._historyRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
  110. this._invSize.value.set( 1 / this.renderTarget.width, 1 / this.renderTarget.height );
  111. needsRestart = true;
  112. }
  113. return needsRestart;
  114. }
  115. /**
  116. * This method is used to render the effect once per frame.
  117. *
  118. * @param {NodeFrame} frame - The current node frame.
  119. */
  120. updateBefore( frame ) {
  121. const { renderer } = frame;
  122. const { scene, camera } = this;
  123. _rendererState = PostProcessingUtils.resetRendererAndSceneState( renderer, scene, _rendererState );
  124. //
  125. this._pixelRatio = renderer.getPixelRatio();
  126. const size = renderer.getSize( _size );
  127. const needsRestart = this.setSize( size.width, size.height );
  128. // save original/unjittered projection matrix for velocity pass
  129. camera.updateProjectionMatrix();
  130. this._originalProjectionMatrix.copy( camera.projectionMatrix );
  131. // camera configuration
  132. this._cameraNear.value = camera.near;
  133. this._cameraFar.value = camera.far;
  134. // configure jitter as view offset
  135. const viewOffset = {
  136. fullWidth: this.renderTarget.width,
  137. fullHeight: this.renderTarget.height,
  138. offsetX: 0,
  139. offsetY: 0,
  140. width: this.renderTarget.width,
  141. height: this.renderTarget.height
  142. };
  143. const originalViewOffset = Object.assign( {}, camera.view );
  144. if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
  145. const jitterOffset = _JitterVectors[ this._jitterIndex ];
  146. camera.setViewOffset(
  147. viewOffset.fullWidth, viewOffset.fullHeight,
  148. viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
  149. viewOffset.width, viewOffset.height
  150. );
  151. // configure velocity
  152. const mrt = this.getMRT();
  153. const velocityOutput = mrt.get( 'velocity' );
  154. if ( velocityOutput !== undefined ) {
  155. velocityOutput.setProjectionMatrix( this._originalProjectionMatrix );
  156. } else {
  157. throw new Error( 'THREE:TRAAPassNode: Missing velocity output in MRT configuration.' );
  158. }
  159. // render sample
  160. renderer.setMRT( mrt );
  161. renderer.setClearColor( this.clearColor, this.clearAlpha );
  162. renderer.setRenderTarget( this._sampleRenderTarget );
  163. renderer.render( scene, camera );
  164. renderer.setRenderTarget( null );
  165. renderer.setMRT( null );
  166. // every time when the dimensions change we need fresh history data. Copy the sample
  167. // into the history and final render target (no AA happens at that point).
  168. if ( needsRestart === true ) {
  169. // bind and clear render target to make sure they are initialized after the resize which triggers a dispose()
  170. renderer.setRenderTarget( this._historyRenderTarget );
  171. renderer.clear();
  172. renderer.setRenderTarget( this.renderTarget );
  173. renderer.clear();
  174. renderer.setRenderTarget( null );
  175. renderer.copyTextureToTexture( this._sampleRenderTarget.texture, this._historyRenderTarget.texture );
  176. renderer.copyTextureToTexture( this._sampleRenderTarget.texture, this.renderTarget.texture );
  177. } else {
  178. // resolve
  179. renderer.setRenderTarget( this.renderTarget );
  180. _quadMesh.material = this._resolveMaterial;
  181. _quadMesh.render( renderer );
  182. renderer.setRenderTarget( null );
  183. // update history
  184. renderer.copyTextureToTexture( this.renderTarget.texture, this._historyRenderTarget.texture );
  185. }
  186. // copy depth
  187. renderer.copyTextureToTexture( this._sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
  188. // update jitter index
  189. this._jitterIndex ++;
  190. this._jitterIndex = this._jitterIndex % ( _JitterVectors.length - 1 );
  191. // restore
  192. if ( originalViewOffset.enabled ) {
  193. camera.setViewOffset(
  194. originalViewOffset.fullWidth, originalViewOffset.fullHeight,
  195. originalViewOffset.offsetX, originalViewOffset.offsetY,
  196. originalViewOffset.width, originalViewOffset.height
  197. );
  198. } else {
  199. camera.clearViewOffset();
  200. }
  201. velocityOutput.setProjectionMatrix( null );
  202. PostProcessingUtils.restoreRendererAndSceneState( renderer, scene, _rendererState );
  203. }
  204. /**
  205. * This method is used to setup the effect's render targets and TSL code.
  206. *
  207. * @param {NodeBuilder} builder - The current node builder.
  208. * @return {PassTextureNode}
  209. */
  210. setup( builder ) {
  211. if ( this._sampleRenderTarget === null ) {
  212. this._sampleRenderTarget = this.renderTarget.clone();
  213. this._historyRenderTarget = this.renderTarget.clone();
  214. this._sampleRenderTarget.texture.minFiler = NearestFilter;
  215. this._sampleRenderTarget.texture.magFilter = NearestFilter;
  216. const velocityTarget = this._sampleRenderTarget.texture.clone();
  217. velocityTarget.isRenderTargetTexture = true;
  218. velocityTarget.name = 'velocity';
  219. this._sampleRenderTarget.textures.push( velocityTarget ); // for MRT
  220. }
  221. // textures
  222. const historyTexture = texture( this._historyRenderTarget.texture );
  223. const sampleTexture = texture( this._sampleRenderTarget.textures[ 0 ] );
  224. const velocityTexture = texture( this._sampleRenderTarget.textures[ 1 ] );
  225. const depthTexture = texture( this._sampleRenderTarget.depthTexture );
  226. const resolve = Fn( () => {
  227. const uvNode = uv();
  228. const minColor = vec4( 10000 ).toVar();
  229. const maxColor = vec4( - 10000 ).toVar();
  230. const closestDepth = float( 1 ).toVar();
  231. const closestDepthPixelPosition = vec2( 0 ).toVar();
  232. // sample a 3x3 neighborhood to create a box in color space
  233. // clamping the history color with the resulting min/max colors mitigates ghosting
  234. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'x' }, ( { x } ) => {
  235. Loop( { start: int( - 1 ), end: int( 1 ), type: 'int', condition: '<=', name: 'y' }, ( { y } ) => {
  236. const uvNeighbor = uvNode.add( vec2( float( x ), float( y ) ).mul( this._invSize ) ).toVar();
  237. const colorNeighbor = max( vec4( 0 ), sampleTexture.sample( uvNeighbor ) ).toVar(); // use max() to avoid propagate garbage values
  238. minColor.assign( min( minColor, colorNeighbor ) );
  239. maxColor.assign( max( maxColor, colorNeighbor ) );
  240. const currentDepth = depthTexture.sample( uvNeighbor ).r.toVar();
  241. // find the sample position of the closest depth in the neighborhood (used for velocity)
  242. If( currentDepth.lessThan( closestDepth ), () => {
  243. closestDepth.assign( currentDepth );
  244. closestDepthPixelPosition.assign( uvNeighbor );
  245. } );
  246. } );
  247. } );
  248. // sampling/reprojection
  249. const offset = velocityTexture.sample( closestDepthPixelPosition ).xy.mul( vec2( 0.5, - 0.5 ) ); // NDC to uv offset
  250. const currentColor = sampleTexture.sample( uvNode );
  251. const historyColor = historyTexture.sample( uvNode.sub( offset ) );
  252. // clamping
  253. const clampedHistoryColor = clamp( historyColor, minColor, maxColor );
  254. // flicker reduction based on luminance weighing
  255. const currentWeight = float( 0.05 ).toVar();
  256. const historyWeight = currentWeight.oneMinus().toVar();
  257. const compressedCurrent = currentColor.mul( float( 1 ).div( ( max( max( currentColor.r, currentColor.g ), currentColor.b ).add( 1.0 ) ) ) );
  258. const compressedHistory = clampedHistoryColor.mul( float( 1 ).div( ( max( max( clampedHistoryColor.r, clampedHistoryColor.g ), clampedHistoryColor.b ).add( 1.0 ) ) ) );
  259. const luminanceCurrent = luminance( compressedCurrent.rgb );
  260. const luminanceHistory = luminance( compressedHistory.rgb );
  261. currentWeight.mulAssign( float( 1.0 ).div( luminanceCurrent.add( 1 ) ) );
  262. historyWeight.mulAssign( float( 1.0 ).div( luminanceHistory.add( 1 ) ) );
  263. return add( currentColor.mul( currentWeight ), clampedHistoryColor.mul( historyWeight ) ).div( max( currentWeight.add( historyWeight ), 0.00001 ) );
  264. } );
  265. // materials
  266. this._resolveMaterial.fragmentNode = resolve();
  267. return super.setup( builder );
  268. }
  269. /**
  270. * Frees internal resources. This method should be called
  271. * when the effect is no longer required.
  272. */
  273. dispose() {
  274. super.dispose();
  275. if ( this._sampleRenderTarget !== null ) {
  276. this._sampleRenderTarget.dispose();
  277. this._historyRenderTarget.dispose();
  278. }
  279. this._resolveMaterial.dispose();
  280. }
  281. }
  282. export default TRAAPassNode;
  283. // These jitter vectors are specified in integers because it is easier.
  284. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  285. // before being used, thus these integers need to be scaled by 1/16.
  286. //
  287. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  288. const _JitterVectors = [
  289. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  290. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  291. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  292. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  293. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  294. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  295. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  296. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  297. ];
  298. /**
  299. * TSL function for creating a TRAA pass node for Temporal Reprojection Anti-Aliasing.
  300. *
  301. * @function
  302. * @param {Scene} scene - The scene to render.
  303. * @param {Camera} camera - The camera to render the scene with.
  304. * @returns {TRAAPassNode}
  305. */
  306. export const traaPass = ( scene, camera ) => nodeObject( new TRAAPassNode( scene, camera ) );
粤ICP备19079148号