DenoiseNode.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import { DataTexture, RepeatWrapping, Vector2, Vector3, TempNode } from 'three/webgpu';
  2. import { texture, getNormalFromDepth, getViewPosition, convertToTexture, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, luminance, vec2, vec3, vec4, uniformArray, int, dot, max, pow, abs, If, textureSize, sin, cos, mat2, PI, property } from 'three/tsl';
  3. import { SimplexNoise } from '../../math/SimplexNoise.js';
  4. /**
  5. * Post processing node for denoising data like raw screen-space ambient occlusion output.
  6. * Denoise can noticeably improve the quality of ambient occlusion but also add quite some
  7. * overhead to the post processing setup. It's best to make its usage optional (e.g. via
  8. * graphic settings).
  9. *
  10. * Reference: {@link https://openaccess.thecvf.com/content/WACV2021/papers/Khademi_Self-Supervised_Poisson-Gaussian_Denoising_WACV_2021_paper.pdf}.
  11. *
  12. * @augments TempNode
  13. * @three_import import { denoise } from 'three/addons/tsl/display/DenoiseNode.js';
  14. */
  15. class DenoiseNode extends TempNode {
  16. static get type() {
  17. return 'DenoiseNode';
  18. }
  19. /**
  20. * Constructs a new denoise node.
  21. *
  22. * @param {TextureNode} textureNode - The texture node that represents the input of the effect (e.g. AO).
  23. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  24. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  25. * @param {Camera} camera - The camera the scene is rendered with.
  26. */
  27. constructor( textureNode, depthNode, normalNode, camera ) {
  28. super( 'vec4' );
  29. /**
  30. * The texture node that represents the input of the effect (e.g. AO).
  31. *
  32. * @type {TextureNode}
  33. */
  34. this.textureNode = textureNode;
  35. /**
  36. * A node that represents the scene's depth.
  37. *
  38. * @type {Node<float>}
  39. */
  40. this.depthNode = depthNode;
  41. /**
  42. * A node that represents the scene's normals. If no normals are passed to the
  43. * constructor (because MRT is not available), normals can be automatically
  44. * reconstructed from depth values in the shader.
  45. *
  46. * @type {?Node<vec3>}
  47. */
  48. this.normalNode = normalNode;
  49. /**
  50. * The node represents the internal noise texture.
  51. *
  52. * @type {TextureNode}
  53. */
  54. this.noiseNode = texture( generateDefaultNoise() );
  55. /**
  56. * The luma Phi value.
  57. *
  58. * @type {UniformNode<float>}
  59. */
  60. this.lumaPhi = uniform( 5 );
  61. /**
  62. * The depth Phi value.
  63. *
  64. * @type {UniformNode<float>}
  65. */
  66. this.depthPhi = uniform( 5 );
  67. /**
  68. * The normal Phi value.
  69. *
  70. * @type {UniformNode<float>}
  71. */
  72. this.normalPhi = uniform( 5 );
  73. /**
  74. * The radius.
  75. *
  76. * @type {UniformNode<float>}
  77. */
  78. this.radius = uniform( 5 );
  79. /**
  80. * The index.
  81. *
  82. * @type {UniformNode<float>}
  83. */
  84. this.index = uniform( 0 );
  85. /**
  86. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node updates
  87. * its internal uniforms once per frame in `updateBefore()`.
  88. *
  89. * @type {string}
  90. * @default 'frame'
  91. */
  92. this.updateBeforeType = NodeUpdateType.FRAME;
  93. /**
  94. * The resolution of the effect.
  95. *
  96. * @private
  97. * @type {UniformNode<vec2>}
  98. */
  99. this._resolution = uniform( new Vector2() );
  100. /**
  101. * An array of sample vectors.
  102. *
  103. * @private
  104. * @type {UniformArrayNode<vec3>}
  105. */
  106. this._sampleVectors = uniformArray( generateDenoiseSamples( 16, 2, 1 ) );
  107. /**
  108. * Represents the inverse projection matrix of the scene's camera.
  109. *
  110. * @private
  111. * @type {UniformNode<mat4>}
  112. */
  113. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  114. }
  115. /**
  116. * This method is used to update internal uniforms once per frame.
  117. *
  118. * @param {NodeFrame} frame - The current node frame.
  119. */
  120. updateBefore() {
  121. const map = this.textureNode.value;
  122. this._resolution.value.set( map.image.width, map.image.height );
  123. }
  124. /**
  125. * This method is used to setup the effect's TSL code.
  126. *
  127. * @param {NodeBuilder} builder - The current node builder.
  128. * @return {ShaderCallNodeInternal}
  129. */
  130. setup( /* builder */ ) {
  131. const uvNode = uv();
  132. const sampleTexture = ( uv ) => this.textureNode.sample( uv );
  133. const sampleDepth = ( uv ) => this.depthNode.sample( uv ).x;
  134. const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.sample( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this._cameraProjectionMatrixInverse );
  135. const sampleNoise = ( uv ) => this.noiseNode.sample( uv );
  136. const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  137. const texel = sampleTexture( sampleUv ).toVar();
  138. const depth = sampleDepth( sampleUv ).toVar();
  139. const normal = sampleNormal( sampleUv ).toVar();
  140. const neighborColor = texel.rgb;
  141. const viewPos = getViewPosition( sampleUv, depth, this._cameraProjectionMatrixInverse ).toVar();
  142. const normalDiff = dot( viewNormal, normal ).toVar();
  143. const normalSimilarity = pow( max( normalDiff, 0 ), this.normalPhi ).toVar();
  144. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  145. const lumaSimilarity = max( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  146. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  147. const depthSimilarity = max( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  148. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  149. return vec4( neighborColor.mul( w ), w );
  150. } );
  151. const denoise = Fn( ( [ uvNode ] ) => {
  152. const depth = sampleDepth( uvNode ).toVar();
  153. const viewNormal = sampleNormal( uvNode ).toVar();
  154. const texel = sampleTexture( uvNode ).toVar();
  155. const result = property( 'vec4' );
  156. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  157. result.assign( texel );
  158. } ).Else( () => {
  159. const center = vec3( texel.rgb );
  160. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toConst();
  161. const noiseResolution = textureSize( this.noiseNode, 0 );
  162. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  163. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  164. const noiseTexel = sampleNoise( noiseUv ).toVar();
  165. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  166. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  167. const noiseVec = vec2( x, y );
  168. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  169. const totalWeight = float( 1.0 ).toVar();
  170. const denoised = vec3( texel.rgb ).toVar();
  171. Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  172. const sampleDir = this._sampleVectors.element( i );
  173. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution );
  174. const sampleUv = uvNode.add( offset );
  175. const sampleResult = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  176. denoised.addAssign( sampleResult.xyz );
  177. totalWeight.addAssign( sampleResult.w );
  178. } );
  179. If( totalWeight.greaterThan( float( 0 ) ), () => {
  180. denoised.divAssign( totalWeight );
  181. } );
  182. result.assign( vec4( denoised, texel.a ) );
  183. } );
  184. return result;
  185. }/*, { uv: 'vec2', return: 'vec4' }*/ );
  186. const output = Fn( () => {
  187. return denoise( uvNode );
  188. } );
  189. const outputNode = output();
  190. return outputNode;
  191. }
  192. }
  193. export default DenoiseNode;
  194. /**
  195. * Generates denoise samples based on the given parameters.
  196. *
  197. * @param {number} numSamples - The number of samples.
  198. * @param {number} numRings - The number of rings.
  199. * @param {number} radiusExponent - The radius exponent.
  200. * @return {Array<Vector3>} The denoise samples.
  201. */
  202. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  203. const samples = [];
  204. for ( let i = 0; i < numSamples; i ++ ) {
  205. const angle = 2 * Math.PI * numRings * i / numSamples;
  206. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  207. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  208. }
  209. return samples;
  210. }
  211. /**
  212. * Generates a default noise texture for the given size.
  213. *
  214. * @param {number} [size=64] - The texture size.
  215. * @return {DataTexture} The generated noise texture.
  216. */
  217. function generateDefaultNoise( size = 64 ) {
  218. const simplex = new SimplexNoise();
  219. const arraySize = size * size * 4;
  220. const data = new Uint8Array( arraySize );
  221. for ( let i = 0; i < size; i ++ ) {
  222. for ( let j = 0; j < size; j ++ ) {
  223. const x = i;
  224. const y = j;
  225. data[ ( i * size + j ) * 4 ] = ( simplex.noise( x, y ) * 0.5 + 0.5 ) * 255;
  226. data[ ( i * size + j ) * 4 + 1 ] = ( simplex.noise( x + size, y ) * 0.5 + 0.5 ) * 255;
  227. data[ ( i * size + j ) * 4 + 2 ] = ( simplex.noise( x, y + size ) * 0.5 + 0.5 ) * 255;
  228. data[ ( i * size + j ) * 4 + 3 ] = ( simplex.noise( x + size, y + size ) * 0.5 + 0.5 ) * 255;
  229. }
  230. }
  231. const noiseTexture = new DataTexture( data, size, size );
  232. noiseTexture.wrapS = RepeatWrapping;
  233. noiseTexture.wrapT = RepeatWrapping;
  234. noiseTexture.needsUpdate = true;
  235. return noiseTexture;
  236. }
  237. /**
  238. * TSL function for creating a denoise effect.
  239. *
  240. * @tsl
  241. * @function
  242. * @param {Node} node - The node that represents the input of the effect (e.g. AO).
  243. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  244. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  245. * @param {Camera} camera - The camera the scene is rendered with.
  246. * @returns {DenoiseNode}
  247. */
  248. export const denoise = ( node, depthNode, normalNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), camera ) );