TRAANode.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. import { HalfFloatType, Vector2, RenderTarget, RendererUtils, QuadMesh, NodeMaterial, TempNode, NodeUpdateType, Matrix4, DepthTexture, FloatType } from 'three/webgpu';
  2. import { add, float, If, Fn, max, texture, uniform, uv, vec2, vec4, luminance, convertToTexture, passTexture, velocity, getViewPosition, viewZToPerspectiveDepth, struct, ivec2, mix, logarithmicDepthToViewZ, viewZToOrthographicDepth } 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. * Note: MSAA must be disabled when TRAA is in use.
  14. *
  15. * @augments TempNode
  16. * @three_import import { traa } from 'three/addons/tsl/display/TRAANode.js';
  17. */
  18. class TRAANode extends TempNode {
  19. static get type() {
  20. return 'TRAANode';
  21. }
  22. /**
  23. * Constructs a new TRAA node.
  24. *
  25. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  26. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  27. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  28. * @param {Camera} camera - The camera the scene is rendered with.
  29. */
  30. constructor( beautyNode, depthNode, velocityNode, camera ) {
  31. super( 'vec4' );
  32. /**
  33. * This flag can be used for type testing.
  34. *
  35. * @type {boolean}
  36. * @readonly
  37. * @default true
  38. */
  39. this.isTRAANode = true;
  40. /**
  41. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  42. * its effect once per frame in `updateBefore()`.
  43. *
  44. * @type {string}
  45. * @default 'frame'
  46. */
  47. this.updateBeforeType = NodeUpdateType.FRAME;
  48. /**
  49. * The texture node that represents the input of the effect.
  50. *
  51. * @type {TextureNode}
  52. */
  53. this.beautyNode = beautyNode;
  54. /**
  55. * A node that represents the scene's velocity.
  56. *
  57. * @type {TextureNode}
  58. */
  59. this.depthNode = depthNode;
  60. /**
  61. * A node that represents the scene's velocity.
  62. *
  63. * @type {TextureNode}
  64. */
  65. this.velocityNode = velocityNode;
  66. /**
  67. * The camera the scene is rendered with.
  68. *
  69. * @type {Camera}
  70. */
  71. this.camera = camera;
  72. /**
  73. * When the difference between the current and previous depth goes above this threshold,
  74. * the history is considered invalid.
  75. *
  76. * @type {number}
  77. * @default 0.0005
  78. */
  79. this.depthThreshold = 0.0005;
  80. /**
  81. * The depth difference within the 3×3 neighborhood to consider a pixel as an edge.
  82. *
  83. * @type {number}
  84. * @default 0.001
  85. */
  86. this.edgeDepthDiff = 0.001;
  87. /**
  88. * The history becomes invalid as the pixel length of the velocity approaches this value.
  89. *
  90. * @type {number}
  91. * @default 128
  92. */
  93. this.maxVelocityLength = 128;
  94. /**
  95. * Whether to decrease the weight on the current frame when the velocity is more subpixel.
  96. * This reduces blurriness under motion, but can introduce a square pattern artifact.
  97. *
  98. * @type {boolean}
  99. * @default true
  100. */
  101. this.useSubpixelCorrection = true;
  102. /**
  103. * The jitter index selects the current camera offset value.
  104. *
  105. * @private
  106. * @type {number}
  107. * @default 0
  108. */
  109. this._jitterIndex = 0;
  110. /**
  111. * A uniform node holding the inverse resolution value.
  112. *
  113. * @private
  114. * @type {UniformNode<vec2>}
  115. */
  116. this._invSize = uniform( new Vector2() );
  117. /**
  118. * The render target that represents the history of frame data.
  119. *
  120. * @private
  121. * @type {?RenderTarget}
  122. */
  123. this._historyRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType, depthTexture: new DepthTexture() } );
  124. this._historyRenderTarget.texture.name = 'TRAANode.history';
  125. /**
  126. * The render target for the resolve.
  127. *
  128. * @private
  129. * @type {?RenderTarget}
  130. */
  131. this._resolveRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, type: HalfFloatType } );
  132. this._resolveRenderTarget.texture.name = 'TRAANode.resolve';
  133. /**
  134. * Material used for the resolve step.
  135. *
  136. * @private
  137. * @type {NodeMaterial}
  138. */
  139. this._resolveMaterial = new NodeMaterial();
  140. this._resolveMaterial.name = 'TRAA.resolve';
  141. /**
  142. * The result of the effect is represented as a separate texture node.
  143. *
  144. * @private
  145. * @type {PassTextureNode}
  146. */
  147. this._textureNode = passTexture( this, this._resolveRenderTarget.texture );
  148. /**
  149. * Used to save the original/unjittered projection matrix.
  150. *
  151. * @private
  152. * @type {Matrix4}
  153. */
  154. this._originalProjectionMatrix = new Matrix4();
  155. /**
  156. * A uniform node holding the camera's near and far.
  157. *
  158. * @private
  159. * @type {UniformNode<vec2>}
  160. */
  161. this._cameraNearFar = uniform( new Vector2() );
  162. /**
  163. * A uniform node holding the camera world matrix.
  164. *
  165. * @private
  166. * @type {UniformNode<mat4>}
  167. */
  168. this._cameraWorldMatrix = uniform( new Matrix4() );
  169. /**
  170. * A uniform node holding the camera world matrix inverse.
  171. *
  172. * @private
  173. * @type {UniformNode<mat4>}
  174. */
  175. this._cameraWorldMatrixInverse = uniform( new Matrix4() );
  176. /**
  177. * A uniform node holding the camera projection matrix inverse.
  178. *
  179. * @private
  180. * @type {UniformNode<mat4>}
  181. */
  182. this._cameraProjectionMatrixInverse = uniform( new Matrix4() );
  183. /**
  184. * A uniform node holding the previous frame's view matrix.
  185. *
  186. * @private
  187. * @type {UniformNode<mat4>}
  188. */
  189. this._previousCameraWorldMatrix = uniform( new Matrix4() );
  190. /**
  191. * A uniform node holding the previous frame's projection matrix inverse.
  192. *
  193. * @private
  194. * @type {UniformNode<mat4>}
  195. */
  196. this._previousCameraProjectionMatrixInverse = uniform( new Matrix4() );
  197. /**
  198. * A texture node for the previous depth buffer.
  199. *
  200. * @private
  201. * @type {TextureNode}
  202. */
  203. this._previousDepthNode = texture( new DepthTexture( 1, 1 ) );
  204. /**
  205. * Sync the post processing stack with the TRAA node.
  206. *
  207. * @private
  208. * @type {boolean}
  209. */
  210. this._needsPostProcessingSync = false;
  211. /**
  212. * The node used to render the scene's velocity.
  213. *
  214. * @private
  215. * @type {?VelocityNode}
  216. */
  217. this._velocityNode = null;
  218. }
  219. /**
  220. * Returns the result of the effect as a texture node.
  221. *
  222. * @return {PassTextureNode} A texture node that represents the result of the effect.
  223. */
  224. getTextureNode() {
  225. return this._textureNode;
  226. }
  227. /**
  228. * Sets the size of the effect.
  229. *
  230. * @param {number} width - The width of the effect.
  231. * @param {number} height - The height of the effect.
  232. */
  233. setSize( width, height ) {
  234. this._historyRenderTarget.setSize( width, height );
  235. this._resolveRenderTarget.setSize( width, height );
  236. this._invSize.value.set( 1 / width, 1 / height );
  237. }
  238. /**
  239. * Defines the TRAA's current jitter as a view offset
  240. * to the scene's camera.
  241. *
  242. * @param {number} width - The width of the effect.
  243. * @param {number} height - The height of the effect.
  244. */
  245. setViewOffset( width, height ) {
  246. // save original/unjittered projection matrix for velocity pass
  247. this.camera.updateProjectionMatrix();
  248. this._originalProjectionMatrix.copy( this.camera.projectionMatrix );
  249. this._velocityNode.setProjectionMatrix( this._originalProjectionMatrix );
  250. //
  251. const viewOffset = {
  252. fullWidth: width,
  253. fullHeight: height,
  254. offsetX: 0,
  255. offsetY: 0,
  256. width: width,
  257. height: height
  258. };
  259. const jitterOffset = _haltonOffsets[ this._jitterIndex ];
  260. this.camera.setViewOffset(
  261. viewOffset.fullWidth, viewOffset.fullHeight,
  262. viewOffset.offsetX + jitterOffset[ 0 ] - 0.5, viewOffset.offsetY + jitterOffset[ 1 ] - 0.5,
  263. viewOffset.width, viewOffset.height
  264. );
  265. }
  266. /**
  267. * Clears the view offset from the scene's camera.
  268. */
  269. clearViewOffset() {
  270. this.camera.clearViewOffset();
  271. this._velocityNode.setProjectionMatrix( null );
  272. // update jitter index
  273. this._jitterIndex ++;
  274. this._jitterIndex = this._jitterIndex % ( _haltonOffsets.length - 1 );
  275. }
  276. /**
  277. * This method is used to render the effect once per frame.
  278. *
  279. * @param {NodeFrame} frame - The current node frame.
  280. */
  281. updateBefore( frame ) {
  282. const { renderer } = frame;
  283. // store previous frame matrices before updating current ones
  284. this._previousCameraWorldMatrix.value.copy( this._cameraWorldMatrix.value );
  285. this._previousCameraProjectionMatrixInverse.value.copy( this._cameraProjectionMatrixInverse.value );
  286. // update camera matrices uniforms
  287. this._cameraNearFar.value.set( this.camera.near, this.camera.far );
  288. this._cameraWorldMatrix.value.copy( this.camera.matrixWorld );
  289. this._cameraWorldMatrixInverse.value.copy( this.camera.matrixWorldInverse );
  290. this._cameraProjectionMatrixInverse.value.copy( this.camera.projectionMatrixInverse );
  291. // keep the TRAA in sync with the dimensions of the beauty node
  292. const beautyRenderTarget = ( this.beautyNode.isRTTNode ) ? this.beautyNode.renderTarget : this.beautyNode.passNode.renderTarget;
  293. const width = beautyRenderTarget.texture.width;
  294. const height = beautyRenderTarget.texture.height;
  295. //
  296. if ( this._needsPostProcessingSync === true ) {
  297. this.setViewOffset( width, height );
  298. this._needsPostProcessingSync = false;
  299. }
  300. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  301. //
  302. const needsRestart = this._historyRenderTarget.width !== width || this._historyRenderTarget.height !== height;
  303. this.setSize( width, height );
  304. // every time when the dimensions change we need fresh history data
  305. if ( needsRestart === true ) {
  306. // make sure render targets are initialized after the resize which triggers a dispose()
  307. renderer.initRenderTarget( this._historyRenderTarget );
  308. renderer.initRenderTarget( this._resolveRenderTarget );
  309. // make sure to reset the history with the contents of the beauty buffer otherwise subsequent frames after the
  310. // resize will fade from a darker color to the correct one because the history was cleared with black.
  311. renderer.copyTextureToTexture( beautyRenderTarget.texture, this._historyRenderTarget.texture );
  312. }
  313. // resolve
  314. renderer.setRenderTarget( this._resolveRenderTarget );
  315. _quadMesh.material = this._resolveMaterial;
  316. _quadMesh.name = 'TRAA';
  317. _quadMesh.render( renderer );
  318. renderer.setRenderTarget( null );
  319. // update history
  320. renderer.copyTextureToTexture( this._resolveRenderTarget.texture, this._historyRenderTarget.texture );
  321. // Copy current depth to previous depth buffer
  322. const size = renderer.getDrawingBufferSize( _size );
  323. // only allow the depth copy if the dimensions of the history render target match with the drawing
  324. // render buffer and thus the depth texture of the scene. For some reasons, there are timing issues
  325. // with WebGPU resulting in different size of the drawing buffer and the beauty render target when
  326. // resizing the browser window. This does not happen with the WebGL backend
  327. if ( this._historyRenderTarget.height === size.height && this._historyRenderTarget.width === size.width ) {
  328. const currentDepth = this.depthNode.value;
  329. renderer.copyTextureToTexture( currentDepth, this._historyRenderTarget.depthTexture );
  330. this._previousDepthNode.value = this._historyRenderTarget.depthTexture;
  331. }
  332. // restore
  333. RendererUtils.restoreRendererState( renderer, _rendererState );
  334. }
  335. /**
  336. * This method is used to setup the effect's render targets and TSL code.
  337. *
  338. * @param {NodeBuilder} builder - The current node builder.
  339. * @return {PassTextureNode}
  340. */
  341. setup( builder ) {
  342. const renderPipeline = builder.context.renderPipeline;
  343. if ( renderPipeline ) {
  344. this._needsPostProcessingSync = true;
  345. renderPipeline.context.onBeforeRenderPipeline = () => {
  346. const size = builder.renderer.getDrawingBufferSize( _size );
  347. this.setViewOffset( size.width, size.height );
  348. };
  349. renderPipeline.context.onAfterRenderPipeline = () => {
  350. this.clearViewOffset();
  351. };
  352. }
  353. if ( builder.renderer.reversedDepthBuffer === true ) {
  354. this._historyRenderTarget.depthTexture.type = FloatType;
  355. }
  356. if ( builder.context.velocity !== undefined ) {
  357. this._velocityNode = builder.context.velocity;
  358. } else {
  359. this._velocityNode = velocity;
  360. }
  361. const logarithmicToPerspectiveDepth = ( depth ) => {
  362. const { x: near, y: far } = this._cameraNearFar;
  363. const viewZ = logarithmicDepthToViewZ( depth, near, far );
  364. return viewZToPerspectiveDepth( viewZ, near, far );
  365. };
  366. const currentDepthStruct = struct( {
  367. closestDepth: 'float',
  368. closestPositionTexel: 'vec2',
  369. farthestDepth: 'float',
  370. } );
  371. // Samples 3×3 neighborhood pixels and returns the closest and farthest depths.
  372. const sampleCurrentDepth = Fn( ( [ positionTexel ] ) => {
  373. const closestDepth = float( 2 ).toVar();
  374. const closestPositionTexel = vec2( 0 ).toVar();
  375. const farthestDepth = float( - 1 ).toVar();
  376. for ( let x = - 1; x <= 1; ++ x ) {
  377. for ( let y = - 1; y <= 1; ++ y ) {
  378. const neighbor = positionTexel.add( vec2( x, y ) ).toVar();
  379. let depth = this.depthNode.load( neighbor ).r;
  380. if ( builder.renderer.reversedDepthBuffer ) depth = depth.oneMinus();
  381. if ( builder.renderer.logarithmicDepthBuffer ) depth = logarithmicToPerspectiveDepth( depth );
  382. depth = depth.toVar();
  383. If( depth.lessThan( closestDepth ), () => {
  384. closestDepth.assign( depth );
  385. closestPositionTexel.assign( neighbor );
  386. } );
  387. If( depth.greaterThan( farthestDepth ), () => {
  388. farthestDepth.assign( depth );
  389. } );
  390. }
  391. }
  392. return currentDepthStruct( closestDepth, closestPositionTexel, farthestDepth );
  393. } );
  394. // Samples a previous depth and reproject it using the current camera matrices.
  395. const samplePreviousDepth = ( uv ) => {
  396. let depth = this._previousDepthNode.sample( uv ).r;
  397. if ( builder.renderer.logarithmicDepthBuffer ) depth = logarithmicToPerspectiveDepth( depth );
  398. const positionView = getViewPosition( uv, depth, this._previousCameraProjectionMatrixInverse );
  399. const positionWorld = this._previousCameraWorldMatrix.mul( vec4( positionView, 1 ) ).xyz;
  400. const viewZ = this._cameraWorldMatrixInverse.mul( vec4( positionWorld, 1 ) ).z;
  401. return this.camera.isOrthographicCamera
  402. ? viewZToOrthographicDepth( viewZ, this._cameraNearFar.x, this._cameraNearFar.y )
  403. : viewZToPerspectiveDepth( viewZ, this._cameraNearFar.x, this._cameraNearFar.y );
  404. };
  405. // Optimized version of AABB clipping.
  406. // Reference: https://github.com/playdeadgames/temporal
  407. const clipAABB = Fn( ( [ currentColor, historyColor, minColor, maxColor ] ) => {
  408. const pClip = maxColor.rgb.add( minColor.rgb ).mul( 0.5 );
  409. const eClip = maxColor.rgb.sub( minColor.rgb ).mul( 0.5 ).add( 1e-7 );
  410. const vClip = historyColor.sub( vec4( pClip, currentColor.a ) );
  411. const vUnit = vClip.xyz.div( eClip );
  412. const absUnit = vUnit.abs();
  413. const maxUnit = max( absUnit.x, absUnit.y, absUnit.z );
  414. return maxUnit.greaterThan( 1 ).select(
  415. vec4( pClip, currentColor.a ).add( vClip.div( maxUnit ) ),
  416. historyColor
  417. );
  418. } ).setLayout( {
  419. name: 'clipAABB',
  420. type: 'vec4',
  421. inputs: [
  422. { name: 'currentColor', type: 'vec4' },
  423. { name: 'historyColor', type: 'vec4' },
  424. { name: 'minColor', type: 'vec4' },
  425. { name: 'maxColor', type: 'vec4' }
  426. ]
  427. } );
  428. // Performs variance clipping.
  429. // See: https://developer.download.nvidia.com/gameworks/events/GDC2016/msalvi_temporal_supersampling.pdf
  430. const varianceClipping = Fn( ( [ positionTexel, currentColor, historyColor, gamma ] ) => {
  431. const offsets = [
  432. [ - 1, - 1 ],
  433. [ - 1, 1 ],
  434. [ 1, - 1 ],
  435. [ 1, 1 ],
  436. [ 1, 0 ],
  437. [ 0, - 1 ],
  438. [ 0, 1 ],
  439. [ - 1, 0 ]
  440. ];
  441. const moment1 = currentColor.toVar();
  442. const moment2 = currentColor.pow2().toVar();
  443. for ( const [ x, y ] of offsets ) {
  444. // Use max() to prevent NaN values from propagating.
  445. const neighbor = this.beautyNode.offset( ivec2( x, y ) ).load( positionTexel ).max( 0 );
  446. moment1.addAssign( neighbor );
  447. moment2.addAssign( neighbor.pow2() );
  448. }
  449. const N = float( offsets.length + 1 );
  450. const mean = moment1.div( N );
  451. const variance = moment2.div( N ).sub( mean.pow2() ).max( 0 ).sqrt().mul( gamma );
  452. const minColor = mean.sub( variance );
  453. const maxColor = mean.add( variance );
  454. return clipAABB( mean.clamp( minColor, maxColor ), historyColor, minColor, maxColor );
  455. } );
  456. // Returns the amount of subpixel (expressed within [0, 1]) in the velocity.
  457. const subpixelCorrection = Fn( ( [ velocityUV, textureSize ] ) => {
  458. const velocityTexel = velocityUV.mul( textureSize );
  459. const phase = velocityTexel.fract().abs();
  460. const weight = max( phase, phase.oneMinus() );
  461. return weight.x.mul( weight.y ).oneMinus().div( 0.75 );
  462. } ).setLayout( {
  463. name: 'subpixelCorrection',
  464. type: 'float',
  465. inputs: [
  466. { name: 'velocityUV', type: 'vec2' },
  467. { name: 'textureSize', type: 'ivec2' }
  468. ]
  469. } );
  470. // Flicker reduction based on luminance weighing.
  471. const flickerReduction = Fn( ( [ currentColor, historyColor, currentWeight ] ) => {
  472. const historyWeight = currentWeight.oneMinus();
  473. const compressedCurrent = currentColor.mul( float( 1 ).div( ( max( currentColor.r, currentColor.g, currentColor.b ).add( 1 ) ) ) );
  474. const compressedHistory = historyColor.mul( float( 1 ).div( ( max( historyColor.r, historyColor.g, historyColor.b ).add( 1 ) ) ) );
  475. const luminanceCurrent = luminance( compressedCurrent.rgb );
  476. const luminanceHistory = luminance( compressedHistory.rgb );
  477. currentWeight.mulAssign( float( 1 ).div( luminanceCurrent.add( 1 ) ) );
  478. historyWeight.mulAssign( float( 1 ).div( luminanceHistory.add( 1 ) ) );
  479. return add( currentColor.mul( currentWeight ), historyColor.mul( historyWeight ) ).div( max( currentWeight.add( historyWeight ), 0.00001 ) ).toVar();
  480. } );
  481. const historyNode = texture( this._historyRenderTarget.texture );
  482. const resolve = Fn( () => {
  483. const uvNode = uv();
  484. const textureSize = this.beautyNode.size(); // Assumes all the buffers share the same size.
  485. const positionTexel = uvNode.mul( textureSize );
  486. // sample the closest and farthest depths in the current buffer
  487. const currentDepth = sampleCurrentDepth( positionTexel );
  488. const closestDepth = currentDepth.get( 'closestDepth' );
  489. const closestPositionTexel = currentDepth.get( 'closestPositionTexel' );
  490. const farthestDepth = currentDepth.get( 'farthestDepth' );
  491. // convert the NDC offset to UV offset
  492. const offsetUV = this.velocityNode.load( closestPositionTexel ).xy.mul( vec2( 0.5, - 0.5 ) );
  493. // sample the previous depth
  494. const historyUV = uvNode.sub( offsetUV );
  495. const previousDepth = samplePreviousDepth( historyUV );
  496. // history is considered valid when the UV is in range and there's no disocclusion except on edges
  497. const isValidUV = historyUV.greaterThanEqual( 0 ).all().and( historyUV.lessThanEqual( 1 ).all() );
  498. const isEdge = farthestDepth.sub( closestDepth ).greaterThan( this.edgeDepthDiff );
  499. const isDisocclusion = closestDepth.sub( previousDepth ).greaterThan( this.depthThreshold );
  500. const hasValidHistory = isValidUV.and( isEdge.or( isDisocclusion.not() ) );
  501. // sample the current and previous colors
  502. const currentColor = this.beautyNode.sample( uvNode );
  503. const historyColor = historyNode.sample( uvNode.sub( offsetUV ) );
  504. // increase the weight towards the current frame under motion
  505. const motionFactor = uvNode.sub( historyUV ).mul( textureSize ).length().div( this.maxVelocityLength ).saturate();
  506. const currentWeight = float( 0.05 ).toVar(); // A minimum weight
  507. if ( this.useSubpixelCorrection ) {
  508. // Increase the minimum weight towards the current frame when the velocity is more subpixel.
  509. currentWeight.addAssign( subpixelCorrection( offsetUV, textureSize ).mul( 0.25 ) );
  510. }
  511. currentWeight.assign( hasValidHistory.select( currentWeight.add( motionFactor ).saturate(), 1 ) );
  512. // Perform neighborhood clipping/clamping. We use variance clipping here.
  513. const varianceGamma = mix( 0.5, 1, motionFactor.oneMinus().pow2() ); // Reasonable gamma range is [0.75, 2]
  514. const clippedHistoryColor = varianceClipping( positionTexel, currentColor, historyColor, varianceGamma );
  515. // flicker reduction based on luminance weighing
  516. const output = flickerReduction( currentColor, clippedHistoryColor, currentWeight );
  517. return output;
  518. } );
  519. // materials
  520. this._resolveMaterial.colorNode = resolve();
  521. return this._textureNode;
  522. }
  523. /**
  524. * Frees internal resources. This method should be called
  525. * when the effect is no longer required.
  526. */
  527. dispose() {
  528. this._historyRenderTarget.dispose();
  529. this._resolveRenderTarget.dispose();
  530. this._resolveMaterial.dispose();
  531. }
  532. }
  533. export default TRAANode;
  534. function _halton( index, base ) {
  535. let fraction = 1;
  536. let result = 0;
  537. while ( index > 0 ) {
  538. fraction /= base;
  539. result += fraction * ( index % base );
  540. index = Math.floor( index / base );
  541. }
  542. return result;
  543. }
  544. const _haltonOffsets = /*@__PURE__*/ Array.from(
  545. { length: 32 },
  546. ( _, index ) => [ _halton( index + 1, 2 ), _halton( index + 1, 3 ) ]
  547. );
  548. /**
  549. * TSL function for creating a TRAA node for Temporal Reprojection Anti-Aliasing.
  550. *
  551. * @tsl
  552. * @function
  553. * @param {TextureNode} beautyNode - The texture node that represents the input of the effect.
  554. * @param {TextureNode} depthNode - A node that represents the scene's depth.
  555. * @param {TextureNode} velocityNode - A node that represents the scene's velocity.
  556. * @param {Camera} camera - The camera the scene is rendered with.
  557. * @returns {TRAANode}
  558. */
  559. export const traa = ( beautyNode, depthNode, velocityNode, camera ) => new TRAANode( convertToTexture( beautyNode ), depthNode, velocityNode, camera );
粤ICP备19079148号