BilateralBlurNode.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { RenderTarget, Vector2, NodeMaterial, RendererUtils, QuadMesh, TempNode, NodeUpdateType } from 'three/webgpu';
  2. import { Fn, float, uv, uniform, convertToTexture, vec2, vec4, passTexture, luminance, abs, exp, max } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. let _rendererState;
  5. /**
  6. * Post processing node for creating a bilateral blur effect.
  7. *
  8. * Bilateral blur smooths an image while preserving sharp edges. Unlike a
  9. * standard Gaussian blur which blurs everything equally, bilateral blur
  10. * analyzes the intensity/color of neighboring pixels. If a neighbor is too
  11. * different from the center pixel (indicating an edge), it is excluded
  12. * from the blurring process.
  13. *
  14. * Reference: {@link https://en.wikipedia.org/wiki/Bilateral_filter}
  15. *
  16. * @augments TempNode
  17. * @three_import import { bilateralBlur } from 'three/addons/tsl/display/BilateralBlurNode.js';
  18. */
  19. class BilateralBlurNode extends TempNode {
  20. static get type() {
  21. return 'BilateralBlurNode';
  22. }
  23. /**
  24. * Constructs a new bilateral blur node.
  25. *
  26. * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
  27. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  28. * @param {number} sigma - Controls the spatial kernel of the blur filter. Higher values mean a wider blur radius.
  29. * @param {number} sigmaColor - Controls the intensity kernel. Higher values allow more color difference to be blurred together.
  30. */
  31. constructor( textureNode, directionNode = null, sigma = 4, sigmaColor = 0.1 ) {
  32. super( 'vec4' );
  33. /**
  34. * The texture node that represents the input of the effect.
  35. *
  36. * @type {TextureNode}
  37. */
  38. this.textureNode = textureNode;
  39. /**
  40. * Defines the direction and radius of the blur.
  41. *
  42. * @type {Node<vec2|float>}
  43. */
  44. this.directionNode = directionNode;
  45. /**
  46. * Controls the spatial kernel of the blur filter. Higher values mean a wider blur radius.
  47. *
  48. * @type {number}
  49. */
  50. this.sigma = sigma;
  51. /**
  52. * Controls the color/intensity kernel. Higher values allow more color difference
  53. * to be blurred together. Lower values preserve edges more strictly.
  54. *
  55. * @type {number}
  56. */
  57. this.sigmaColor = sigmaColor;
  58. /**
  59. * A uniform node holding the inverse resolution value.
  60. *
  61. * @private
  62. * @type {UniformNode<vec2>}
  63. */
  64. this._invSize = uniform( new Vector2() );
  65. /**
  66. * Bilateral blur is applied in two passes (horizontal, vertical).
  67. * This node controls the direction of each pass.
  68. *
  69. * @private
  70. * @type {UniformNode<vec2>}
  71. */
  72. this._passDirection = uniform( new Vector2() );
  73. /**
  74. * The render target used for the horizontal pass.
  75. *
  76. * @private
  77. * @type {RenderTarget}
  78. */
  79. this._horizontalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  80. this._horizontalRT.texture.name = 'BilateralBlurNode.horizontal';
  81. /**
  82. * The render target used for the vertical pass.
  83. *
  84. * @private
  85. * @type {RenderTarget}
  86. */
  87. this._verticalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  88. this._verticalRT.texture.name = 'BilateralBlurNode.vertical';
  89. /**
  90. * The result of the effect is represented as a separate texture node.
  91. *
  92. * @private
  93. * @type {PassTextureNode}
  94. */
  95. this._textureNode = passTexture( this, this._verticalRT.texture );
  96. this._textureNode.uvNode = textureNode.uvNode;
  97. /**
  98. * The material for the blur pass.
  99. *
  100. * @private
  101. * @type {?NodeMaterial}
  102. */
  103. this._material = null;
  104. /**
  105. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  106. * its effect once per frame in `updateBefore()`.
  107. *
  108. * @type {string}
  109. * @default 'frame'
  110. */
  111. this.updateBeforeType = NodeUpdateType.FRAME;
  112. /**
  113. * The resolution scale.
  114. *
  115. * @type {number}
  116. * @default 1
  117. */
  118. this.resolutionScale = 1;
  119. }
  120. /**
  121. * Sets the size of the effect.
  122. *
  123. * @param {number} width - The width of the effect.
  124. * @param {number} height - The height of the effect.
  125. */
  126. setSize( width, height ) {
  127. width = Math.max( Math.round( width * this.resolutionScale ), 1 );
  128. height = Math.max( Math.round( height * this.resolutionScale ), 1 );
  129. this._invSize.value.set( 1 / width, 1 / height );
  130. this._horizontalRT.setSize( width, height );
  131. this._verticalRT.setSize( width, height );
  132. }
  133. /**
  134. * This method is used to render the effect once per frame.
  135. *
  136. * @param {NodeFrame} frame - The current node frame.
  137. */
  138. updateBefore( frame ) {
  139. const { renderer } = frame;
  140. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  141. //
  142. const textureNode = this.textureNode;
  143. const map = textureNode.value;
  144. const currentTexture = textureNode.value;
  145. _quadMesh.material = this._material;
  146. this.setSize( map.image.width, map.image.height );
  147. const textureType = map.type;
  148. this._horizontalRT.texture.type = textureType;
  149. this._verticalRT.texture.type = textureType;
  150. // horizontal
  151. renderer.setRenderTarget( this._horizontalRT );
  152. this._passDirection.value.set( 1, 0 );
  153. _quadMesh.name = 'Bilateral Blur [ Horizontal Pass ]';
  154. _quadMesh.render( renderer );
  155. // vertical
  156. textureNode.value = this._horizontalRT.texture;
  157. renderer.setRenderTarget( this._verticalRT );
  158. this._passDirection.value.set( 0, 1 );
  159. _quadMesh.name = 'Bilateral Blur [ Vertical Pass ]';
  160. _quadMesh.render( renderer );
  161. // restore
  162. textureNode.value = currentTexture;
  163. RendererUtils.restoreRendererState( renderer, _rendererState );
  164. }
  165. /**
  166. * Returns the result of the effect as a texture node.
  167. *
  168. * @return {PassTextureNode} A texture node that represents the result of the effect.
  169. */
  170. getTextureNode() {
  171. return this._textureNode;
  172. }
  173. /**
  174. * This method is used to setup the effect's TSL code.
  175. *
  176. * @param {NodeBuilder} builder - The current node builder.
  177. * @return {PassTextureNode}
  178. */
  179. setup( builder ) {
  180. const textureNode = this.textureNode;
  181. //
  182. const uvNode = uv();
  183. const directionNode = vec2( this.directionNode || 1 );
  184. const sampleTexture = ( uv ) => textureNode.sample( uv );
  185. const blur = Fn( () => {
  186. const kernelSize = this.sigma * 2 + 3;
  187. const spatialCoefficients = this._getSpatialCoefficients( kernelSize );
  188. const invSize = this._invSize;
  189. const direction = directionNode.mul( this._passDirection );
  190. // Sample center pixel
  191. const centerColor = sampleTexture( uvNode ).toVar();
  192. const centerLuminance = luminance( centerColor.rgb ).toVar();
  193. // Accumulate weighted samples
  194. const weightSum = float( spatialCoefficients[ 0 ] ).toVar();
  195. const colorSum = vec4( centerColor.mul( spatialCoefficients[ 0 ] ) ).toVar();
  196. // Precompute color sigma factor: -0.5 / (sigmaColor^2)
  197. const colorSigmaFactor = float( - 0.5 ).div( float( this.sigmaColor * this.sigmaColor ) ).toConst();
  198. for ( let i = 1; i < kernelSize; i ++ ) {
  199. const x = float( i );
  200. const spatialWeight = float( spatialCoefficients[ i ] );
  201. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  202. // Sample in both directions (+/-)
  203. const sampleUv1 = uvNode.add( uvOffset );
  204. const sampleUv2 = uvNode.sub( uvOffset );
  205. const sample1 = sampleTexture( sampleUv1 );
  206. const sample2 = sampleTexture( sampleUv2 );
  207. // Compute luminance difference for edge detection
  208. const lum1 = luminance( sample1.rgb );
  209. const lum2 = luminance( sample2.rgb );
  210. const diff1 = abs( lum1.sub( centerLuminance ) );
  211. const diff2 = abs( lum2.sub( centerLuminance ) );
  212. // Compute color-based weights using Gaussian function
  213. const colorWeight1 = exp( diff1.mul( diff1 ).mul( colorSigmaFactor ) ).toVar();
  214. const colorWeight2 = exp( diff2.mul( diff2 ).mul( colorSigmaFactor ) ).toVar();
  215. // Combined bilateral weight = spatial weight * color weight
  216. const bilateralWeight1 = spatialWeight.mul( colorWeight1 );
  217. const bilateralWeight2 = spatialWeight.mul( colorWeight2 );
  218. colorSum.addAssign( sample1.mul( bilateralWeight1 ) );
  219. colorSum.addAssign( sample2.mul( bilateralWeight2 ) );
  220. weightSum.addAssign( bilateralWeight1 );
  221. weightSum.addAssign( bilateralWeight2 );
  222. }
  223. // Normalize by the total weight
  224. return colorSum.div( max( weightSum, 0.0001 ) );
  225. } );
  226. //
  227. const material = this._material || ( this._material = new NodeMaterial() );
  228. material.fragmentNode = blur().context( builder.getSharedContext() );
  229. material.name = 'Bilateral_blur';
  230. material.needsUpdate = true;
  231. //
  232. const properties = builder.getNodeProperties( this );
  233. properties.textureNode = textureNode;
  234. //
  235. return this._textureNode;
  236. }
  237. /**
  238. * Frees internal resources. This method should be called
  239. * when the effect is no longer required.
  240. */
  241. dispose() {
  242. this._horizontalRT.dispose();
  243. this._verticalRT.dispose();
  244. if ( this._material !== null ) this._material.dispose();
  245. }
  246. /**
  247. * Computes spatial (Gaussian) coefficients depending on the given kernel radius.
  248. * These coefficients are used for the spatial component of the bilateral filter.
  249. *
  250. * @private
  251. * @param {number} kernelRadius - The kernel radius.
  252. * @return {Array<number>}
  253. */
  254. _getSpatialCoefficients( kernelRadius ) {
  255. const coefficients = [];
  256. const sigma = kernelRadius / 3;
  257. for ( let i = 0; i < kernelRadius; i ++ ) {
  258. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
  259. }
  260. return coefficients;
  261. }
  262. }
  263. export default BilateralBlurNode;
  264. /**
  265. * TSL function for creating a bilateral blur node for post processing.
  266. *
  267. * Bilateral blur smooths an image while preserving sharp edges by considering
  268. * both spatial distance and color/intensity differences between pixels.
  269. *
  270. * @tsl
  271. * @function
  272. * @param {Node<vec4>} node - The node that represents the input of the effect.
  273. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  274. * @param {number} sigma - Controls the spatial kernel of the blur filter. Higher values mean a wider blur radius.
  275. * @param {number} sigmaColor - Controls the intensity kernel. Higher values allow more color difference to be blurred together.
  276. * @returns {BilateralBlurNode}
  277. */
  278. export const bilateralBlur = ( node, directionNode, sigma, sigmaColor ) => new BilateralBlurNode( convertToTexture( node ), directionNode, sigma, sigmaColor );
粤ICP备19079148号