TRAAPassNode.js 12 KB

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