hashBlur.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { float, Fn, vec2, uv, sin, rand, degrees, cos, Loop, vec4, premultiplyAlpha, unpremultiplyAlpha, convertToTexture, nodeObject } from 'three/tsl';
  2. /**
  3. * Applies a hash blur effect to the given texture node.
  4. *
  5. * The approach of this blur is different compared to Gaussian and box blur since
  6. * it does not rely on a kernel to apply a convolution. Instead, it reads the base
  7. * texture multiple times in a random pattern and then averages the samples. A
  8. * typical artifact of this technique is a slightly noisy appearance of the blur which
  9. * can be mitigated by increasing the number of iterations (see `repeats` parameter).
  10. * Compared to Gaussian blur, hash blur requires just a single pass.
  11. *
  12. * Reference: {@link https://www.shadertoy.com/view/4lXXWn}.
  13. *
  14. * @function
  15. * @param {Node<vec4>} textureNode - The texture node that should be blurred.
  16. * @param {Node<float>} [bluramount=float(0.1)] - This node determines the amount of blur.
  17. * @param {Object} [options={}] - Additional options for the hash blur effect.
  18. * @param {Node<float>} [options.repeats=float(45)] - The number of iterations for the blur effect.
  19. * @param {boolean} [options.premultipliedAlpha=false] - Whether to use premultiplied alpha for the blur effect.
  20. * @return {Node<vec4>} The blurred texture node.
  21. */
  22. export const hashBlur = /*#__PURE__*/ Fn( ( [ textureNode, bluramount = float( 0.1 ), options = {} ] ) => {
  23. textureNode = convertToTexture( textureNode );
  24. const repeats = nodeObject( options.size ) || float( 45 );
  25. const premultipliedAlpha = options.premultipliedAlpha || false;
  26. const tap = ( uv ) => {
  27. const sample = textureNode.sample( uv );
  28. return premultipliedAlpha ? premultiplyAlpha( sample ) : sample;
  29. };
  30. const targetUV = textureNode.uvNode || uv();
  31. const blurred_image = vec4( 0. );
  32. Loop( { start: 0., end: repeats, type: 'float' }, ( { i } ) => {
  33. const q = vec2( vec2( cos( degrees( i.div( repeats ).mul( 360. ) ) ), sin( degrees( i.div( repeats ).mul( 360. ) ) ) ).mul( rand( vec2( i, targetUV.x.add( targetUV.y ) ) ).add( bluramount ) ) );
  34. const uv2 = vec2( targetUV.add( q.mul( bluramount ) ) );
  35. blurred_image.addAssign( tap( uv2 ) );
  36. } );
  37. blurred_image.divAssign( repeats );
  38. return premultipliedAlpha ? unpremultiplyAlpha( blurred_image ) : blurred_image;
  39. } );
粤ICP备19079148号