GaussianBlurNode.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import { RenderTarget, Vector2, NodeMaterial, RendererUtils, QuadMesh, TempNode, NodeUpdateType } from 'three/webgpu';
  2. import { 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 material for the blur pass.
  86. *
  87. * @private
  88. * @type {?NodeMaterial}
  89. */
  90. this._material = null;
  91. /**
  92. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  93. * its effect once per frame in `updateBefore()`.
  94. *
  95. * @type {string}
  96. * @default 'frame'
  97. */
  98. this.updateBeforeType = NodeUpdateType.FRAME;
  99. /**
  100. * The resolution scale.
  101. *
  102. * @type {number}
  103. * @default (1)
  104. */
  105. this.resolutionScale = options.resolutionScale || 1;
  106. /**
  107. * Whether the effect should use premultiplied alpha or not. Set this to `true`
  108. * if you are going to blur texture input with transparency.
  109. *
  110. * @type {boolean}
  111. * @default false
  112. */
  113. this.premultipliedAlpha = options.premultipliedAlpha || false;
  114. /**
  115. * This flag can be used for type testing.
  116. *
  117. * @type {boolean}
  118. * @default true
  119. * @readonly
  120. */
  121. this.isGaussianBlurNode = true;
  122. }
  123. /**
  124. * Sets the size of the effect.
  125. *
  126. * @param {number} width - The width of the effect.
  127. * @param {number} height - The height of the effect.
  128. */
  129. setSize( width, height ) {
  130. width = Math.max( Math.round( width * this.resolutionScale ), 1 );
  131. height = Math.max( Math.round( height * this.resolutionScale ), 1 );
  132. this._invSize.value.set( 1 / width, 1 / height );
  133. this._horizontalRT.setSize( width, height );
  134. this._verticalRT.setSize( width, height );
  135. }
  136. /**
  137. * This method is used to render the effect once per frame.
  138. *
  139. * @param {NodeFrame} frame - The current node frame.
  140. */
  141. updateBefore( frame ) {
  142. const { renderer } = frame;
  143. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  144. //
  145. const textureNode = this.textureNode;
  146. const map = textureNode.value;
  147. const currentTexture = textureNode.value;
  148. _quadMesh.material = this._material;
  149. this.setSize( map.image.width, map.image.height );
  150. const textureType = map.type;
  151. this._horizontalRT.texture.type = textureType;
  152. this._verticalRT.texture.type = textureType;
  153. // horizontal
  154. renderer.setRenderTarget( this._horizontalRT );
  155. this._passDirection.value.set( 1, 0 );
  156. _quadMesh.name = 'Gaussian Blur [ Horizontal Pass ]';
  157. _quadMesh.render( renderer );
  158. // vertical
  159. textureNode.value = this._horizontalRT.texture;
  160. renderer.setRenderTarget( this._verticalRT );
  161. this._passDirection.value.set( 0, 1 );
  162. _quadMesh.name = 'Gaussian Blur [ Vertical Pass ]';
  163. _quadMesh.render( renderer );
  164. // restore
  165. textureNode.value = currentTexture;
  166. RendererUtils.restoreRendererState( renderer, _rendererState );
  167. }
  168. /**
  169. * Returns the result of the effect as a texture node.
  170. *
  171. * @return {PassTextureNode} A texture node that represents the result of the effect.
  172. */
  173. getTextureNode() {
  174. return this._textureNode;
  175. }
  176. /**
  177. * This method is used to setup the effect's TSL code.
  178. *
  179. * @param {NodeBuilder} builder - The current node builder.
  180. * @return {PassTextureNode}
  181. */
  182. setup( builder ) {
  183. const textureNode = this.textureNode;
  184. //
  185. const uvNode = uv();
  186. const directionNode = vec2( this.directionNode || 1 );
  187. let sampleTexture, output;
  188. if ( this.premultipliedAlpha ) {
  189. // https://lisyarus.github.io/blog/posts/blur-coefficients-generator.html
  190. sampleTexture = ( uv ) => premultiplyAlpha( textureNode.sample( uv ) );
  191. output = ( color ) => unpremultiplyAlpha( color );
  192. } else {
  193. sampleTexture = ( uv ) => textureNode.sample( uv );
  194. output = ( color ) => color;
  195. }
  196. const blur = Fn( () => {
  197. const kernelSize = 3 + ( 2 * this.sigma );
  198. const gaussianCoefficients = this._getCoefficients( kernelSize );
  199. const invSize = this._invSize;
  200. const direction = directionNode.mul( this._passDirection );
  201. const diffuseSum = vec4( sampleTexture( uvNode ).mul( gaussianCoefficients[ 0 ] ) ).toVar();
  202. for ( let i = 1; i < kernelSize; i ++ ) {
  203. const x = float( i );
  204. const w = float( gaussianCoefficients[ i ] );
  205. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  206. const sample1 = sampleTexture( uvNode.add( uvOffset ) );
  207. const sample2 = sampleTexture( uvNode.sub( uvOffset ) );
  208. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  209. }
  210. return output( diffuseSum );
  211. } );
  212. //
  213. const material = this._material || ( this._material = new NodeMaterial() );
  214. material.fragmentNode = blur().context( builder.getSharedContext() );
  215. material.name = 'Gaussian_blur';
  216. material.needsUpdate = true;
  217. //
  218. const properties = builder.getNodeProperties( this );
  219. properties.textureNode = textureNode;
  220. //
  221. return this._textureNode;
  222. }
  223. /**
  224. * Frees internal resources. This method should be called
  225. * when the effect is no longer required.
  226. */
  227. dispose() {
  228. this._horizontalRT.dispose();
  229. this._verticalRT.dispose();
  230. if ( this._material !== null ) this._material.dispose();
  231. }
  232. /**
  233. * Computes gaussian coefficients depending on the given kernel radius.
  234. *
  235. * @private
  236. * @param {number} kernelRadius - The kernel radius.
  237. * @return {Array<number>}
  238. */
  239. _getCoefficients( kernelRadius ) {
  240. const coefficients = [];
  241. const sigma = kernelRadius / 3;
  242. for ( let i = 0; i < kernelRadius; i ++ ) {
  243. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( sigma * sigma ) ) / sigma );
  244. }
  245. return coefficients;
  246. }
  247. /**
  248. * The resolution scale.
  249. *
  250. * @deprecated
  251. * @type {Vector2}
  252. * @default {(1,1)}
  253. */
  254. get resolution() {
  255. console.warn( 'THREE.GaussianBlurNode: The "resolution" property has been renamed to "resolutionScale" and is now of type `number`.' ); // @deprecated r180
  256. return new Vector2( this.resolutionScale, this.resolutionScale );
  257. }
  258. set resolution( value ) {
  259. console.warn( 'THREE.GaussianBlurNode: The "resolution" property has been renamed to "resolutionScale" and is now of type `number`.' ); // @deprecated r180
  260. this.resolutionScale = value.x;
  261. }
  262. }
  263. export default GaussianBlurNode;
  264. /**
  265. * TSL function for creating a gaussian blur node for post processing.
  266. *
  267. * @tsl
  268. * @function
  269. * @param {Node<vec4>} node - The node that represents the input of the effect.
  270. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  271. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  272. * @param {Object} [options={}] - Additional options for the gaussian blur effect.
  273. * @param {boolean} [options.premultipliedAlpha=false] - Whether to use premultiplied alpha for the blur effect.
  274. * @param {number} [options.resolutionScale=1] - The resolution of the effect. 0.5 means half the resolution of the texture node.
  275. * @returns {GaussianBlurNode}
  276. */
  277. export const gaussianBlur = ( node, directionNode, sigma, options = {} ) => new GaussianBlurNode( convertToTexture( node ), directionNode, sigma, options );
  278. /**
  279. * TSL function for creating a gaussian blur node for post processing with enabled premultiplied alpha.
  280. *
  281. * @tsl
  282. * @function
  283. * @deprecated since r180. Use `gaussianBlur()` with `premultipliedAlpha: true` option instead.
  284. * @param {Node<vec4>} node - The node that represents the input of the effect.
  285. * @param {Node<vec2|float>} directionNode - Defines the direction and radius of the blur.
  286. * @param {number} sigma - Controls the kernel of the blur filter. Higher values mean a wider blur radius.
  287. * @returns {GaussianBlurNode}
  288. */
  289. export function premultipliedGaussianBlur( node, directionNode, sigma ) {
  290. console.warn( 'THREE.TSL: "premultipliedGaussianBlur()" is deprecated. Use "gaussianBlur()" with "premultipliedAlpha: true" option instead.' ); // deprecated, r180
  291. return gaussianBlur( node, directionNode, sigma, { premultipliedAlpha: true } );
  292. }
粤ICP备19079148号