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