GaussianBlurNode.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { RenderTarget, Vector2, NodeMaterial, RendererUtils, QuadMesh, TempNode, NodeUpdateType } from 'three/webgpu';
  2. import { nodeObject, Fn, float, uv, uniform, convertToTexture, vec2, vec4, passTexture, premultiplyAlpha, unpremultiplyAlpha } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. let _rendererState;
  5. /**
  6. * Post processing node for creating a gaussian blur effect.
  7. *
  8. * @augments TempNode
  9. * @three_import import { gaussianBlur, premultipliedGaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
  10. */
  11. class GaussianBlurNode extends TempNode {
  12. static get type() {
  13. return 'GaussianBlurNode';
  14. }
  15. /**
  16. * Constructs a new gaussian blur node.
  17. *
  18. * @param {TextureNode} textureNode - The texture node that represents the input of the effect.
  19. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  20. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  21. * @param {Object} [options={}] - Additional options for the gaussian blur effect.
  22. * @param {boolean} [options.premultipliedAlpha=false] - Whether to use premultiplied alpha for the blur effect.
  23. * @param {number} [options.resolutionScale=1] - The resolution of the effect. 0.5 means half the resolution of the texture node.
  24. */
  25. constructor( textureNode, directionNode = null, sigma = 4, options = {} ) {
  26. super( 'vec4' );
  27. /**
  28. * The texture node that represents the input of the effect.
  29. *
  30. * @type {TextureNode}
  31. */
  32. this.textureNode = textureNode;
  33. /**
  34. * Defines the direction and radius of the blur.
  35. *
  36. * @type {Node<vec2|float>}
  37. */
  38. this.directionNode = directionNode;
  39. /**
  40. * Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  41. *
  42. * @type {number}
  43. */
  44. this.sigma = sigma;
  45. /**
  46. * A uniform node holding the inverse resolution value.
  47. *
  48. * @private
  49. * @type {UniformNode<vec2>}
  50. */
  51. this._invSize = uniform( new Vector2() );
  52. /**
  53. * Gaussian blur is applied in two passes (horizontal, vertical).
  54. * This node controls the direction of each pass.
  55. *
  56. * @private
  57. * @type {UniformNode<vec2>}
  58. */
  59. this._passDirection = uniform( new Vector2() );
  60. /**
  61. * The render target used for the horizontal pass.
  62. *
  63. * @private
  64. * @type {RenderTarget}
  65. */
  66. this._horizontalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  67. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  68. /**
  69. * The render target used for the vertical pass.
  70. *
  71. * @private
  72. * @type {RenderTarget}
  73. */
  74. this._verticalRT = new RenderTarget( 1, 1, { depthBuffer: false } );
  75. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  76. /**
  77. * The result of the effect is represented as a separate texture node.
  78. *
  79. * @private
  80. * @type {PassTextureNode}
  81. */
  82. this._textureNode = passTexture( this, this._verticalRT.texture );
  83. this._textureNode.uvNode = textureNode.uvNode;
  84. /**
  85. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  86. * its effect once per frame in `updateBefore()`.
  87. *
  88. * @type {string}
  89. * @default 'frame'
  90. */
  91. this.updateBeforeType = NodeUpdateType.FRAME;
  92. /**
  93. * The resolution scale.
  94. *
  95. * @type {number}
  96. * @default (1)
  97. */
  98. this.resolutionScale = options.resolutionScale || 1;
  99. /**
  100. * Whether the effect should use premultiplied alpha or not. Set this to `true`
  101. * if you are going to blur texture input with transparency.
  102. *
  103. * @type {boolean}
  104. * @default false
  105. */
  106. this.premultipliedAlpha = options.premultipliedAlpha || false;
  107. }
  108. /**
  109. * Sets the size of the effect.
  110. *
  111. * @param {number} width - The width of the effect.
  112. * @param {number} height - The height of the effect.
  113. */
  114. setSize( width, height ) {
  115. width = Math.max( Math.round( width * this.resolutionScale ), 1 );
  116. height = Math.max( Math.round( height * this.resolutionScale ), 1 );
  117. this._invSize.value.set( 1 / width, 1 / height );
  118. this._horizontalRT.setSize( width, height );
  119. this._verticalRT.setSize( width, height );
  120. }
  121. /**
  122. * This method is used to render the effect once per frame.
  123. *
  124. * @param {NodeFrame} frame - The current node frame.
  125. */
  126. updateBefore( frame ) {
  127. const { renderer } = frame;
  128. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  129. //
  130. const textureNode = this.textureNode;
  131. const map = textureNode.value;
  132. const currentTexture = textureNode.value;
  133. _quadMesh.material = this._material;
  134. this.setSize( map.image.width, map.image.height );
  135. const textureType = map.type;
  136. this._horizontalRT.texture.type = textureType;
  137. this._verticalRT.texture.type = textureType;
  138. // horizontal
  139. renderer.setRenderTarget( this._horizontalRT );
  140. this._passDirection.value.set( 1, 0 );
  141. _quadMesh.name = 'Gaussian Blur [ Horizontal Pass ]';
  142. _quadMesh.render( renderer );
  143. // vertical
  144. textureNode.value = this._horizontalRT.texture;
  145. renderer.setRenderTarget( this._verticalRT );
  146. this._passDirection.value.set( 0, 1 );
  147. _quadMesh.name = 'Gaussian Blur [ Vertical Pass ]';
  148. _quadMesh.render( renderer );
  149. // restore
  150. textureNode.value = currentTexture;
  151. RendererUtils.restoreRendererState( renderer, _rendererState );
  152. }
  153. /**
  154. * Returns the result of the effect as a texture node.
  155. *
  156. * @return {PassTextureNode} A texture node that represents the result of the effect.
  157. */
  158. getTextureNode() {
  159. return this._textureNode;
  160. }
  161. /**
  162. * This method is used to setup the effect's TSL code.
  163. *
  164. * @param {NodeBuilder} builder - The current node builder.
  165. * @return {PassTextureNode}
  166. */
  167. setup( builder ) {
  168. const textureNode = this.textureNode;
  169. //
  170. const uvNode = uv();
  171. const directionNode = vec2( this.directionNode || 1 );
  172. let sampleTexture, output;
  173. if ( this.premultipliedAlpha ) {
  174. // https://lisyarus.github.io/blog/posts/blur-coefficients-generator.html
  175. sampleTexture = ( uv ) => premultiplyAlpha( textureNode.sample( uv ) );
  176. output = ( color ) => unpremultiplyAlpha( color );
  177. } else {
  178. sampleTexture = ( uv ) => textureNode.sample( uv );
  179. output = ( color ) => color;
  180. }
  181. const blur = Fn( () => {
  182. const kernelSize = 3 + ( 2 * this.sigma );
  183. const gaussianCoefficients = this._getCoefficients( kernelSize );
  184. const invSize = this._invSize;
  185. const direction = directionNode.mul( this._passDirection );
  186. const diffuseSum = vec4( sampleTexture( uvNode ).mul( gaussianCoefficients[ 0 ] ) ).toVar();
  187. for ( let i = 1; i < kernelSize; i ++ ) {
  188. const x = float( i );
  189. const w = float( gaussianCoefficients[ i ] );
  190. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  191. const sample1 = sampleTexture( uvNode.add( uvOffset ) );
  192. const sample2 = sampleTexture( uvNode.sub( uvOffset ) );
  193. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  194. }
  195. return output( diffuseSum );
  196. } );
  197. //
  198. const material = this._material || ( this._material = new NodeMaterial() );
  199. material.fragmentNode = blur().context( builder.getSharedContext() );
  200. material.name = 'Gaussian_blur';
  201. material.needsUpdate = true;
  202. //
  203. const properties = builder.getNodeProperties( this );
  204. properties.textureNode = textureNode;
  205. //
  206. return this._textureNode;
  207. }
  208. /**
  209. * Frees internal resources. This method should be called
  210. * when the effect is no longer required.
  211. */
  212. dispose() {
  213. this._horizontalRT.dispose();
  214. this._verticalRT.dispose();
  215. }
  216. /**
  217. * Computes gaussian coefficients depending on the given kernel radius.
  218. *
  219. * @private
  220. * @param {number} kernelRadius - The kernel radius.
  221. * @return {Array<number>}
  222. */
  223. _getCoefficients( kernelRadius ) {
  224. const coefficients = [];
  225. const sigma = kernelRadius / 3;
  226. for ( let i = 0; i < kernelRadius; i ++ ) {
  227. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
  228. }
  229. return coefficients;
  230. }
  231. /**
  232. * The resolution scale.
  233. *
  234. * @deprecated
  235. * @type {Vector2}
  236. * @default {(1,1)}
  237. */
  238. get resolution() {
  239. console.warn( 'THREE.GaussianBlurNode: The "resolution" property has been renamed to "resolutionScale" and is now of type `number`.' ); // @deprecated r180
  240. return new Vector2( this.resolutionScale, this.resolutionScale );
  241. }
  242. set resolution( value ) {
  243. console.warn( 'THREE.GaussianBlurNode: The "resolution" property has been renamed to "resolutionScale" and is now of type `number`.' ); // @deprecated r180
  244. this.resolutionScale = value.x;
  245. }
  246. }
  247. export default GaussianBlurNode;
  248. /**
  249. * TSL function for creating a gaussian blur node for post processing.
  250. *
  251. * @tsl
  252. * @function
  253. * @param {Node<vec4>} node - The node that represents the input of the effect.
  254. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  255. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  256. * @param {Object} [options={}] - Additional options for the gaussian blur effect.
  257. * @param {boolean} [options.premultipliedAlpha=false] - Whether to use premultiplied alpha for the blur effect.
  258. * @param {number} [options.resolutionScale=1] - The resolution of the effect. 0.5 means half the resolution of the texture node.
  259. * @returns {GaussianBlurNode}
  260. */
  261. export const gaussianBlur = ( node, directionNode, sigma, options = {} ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma, options ) );
  262. /**
  263. * TSL function for creating a gaussian blur node for post processing with enabled premultiplied alpha.
  264. *
  265. * @tsl
  266. * @function
  267. * @deprecated since r180. Use `gaussianBlur()` with `premultipliedAlpha: true` option instead.
  268. * @param {Node<vec4>} node - The node that represents the input of the effect.
  269. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  270. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  271. * @returns {GaussianBlurNode}
  272. */
  273. export function premultipliedGaussianBlur( node, directionNode, sigma ) {
  274. console.warn( 'THREE.TSL: "premultipliedGaussianBlur()" is deprecated. Use "gaussianBlur()" with "premultipliedAlpha: true" option instead.' ); // deprecated, r180
  275. return gaussianBlur( node, directionNode, sigma, { premultipliedAlpha: true } );
  276. }
粤ICP备19079148号