ConvolutionShader.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import {
  2. Vector2
  3. } from 'three';
  4. /**
  5. * Convolution shader
  6. * ported from o3d sample to WebGL / GLSL
  7. */
  8. const ConvolutionShader = {
  9. defines: {
  10. 'KERNEL_SIZE_FLOAT': '25.0',
  11. 'KERNEL_SIZE_INT': '25'
  12. },
  13. uniforms: {
  14. 'tDiffuse': { value: null },
  15. 'uImageIncrement': { value: new Vector2( 0.001953125, 0.0 ) },
  16. 'cKernel': { value: [] }
  17. },
  18. vertexShader: /* glsl */`
  19. uniform vec2 uImageIncrement;
  20. varying vec2 vUv;
  21. void main() {
  22. vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;
  23. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  24. }`,
  25. fragmentShader: /* glsl */`
  26. uniform float cKernel[ KERNEL_SIZE_INT ];
  27. uniform sampler2D tDiffuse;
  28. uniform vec2 uImageIncrement;
  29. varying vec2 vUv;
  30. void main() {
  31. vec2 imageCoord = vUv;
  32. vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );
  33. for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {
  34. sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];
  35. imageCoord += uImageIncrement;
  36. }
  37. gl_FragColor = sum;
  38. }`,
  39. buildKernel: function ( sigma ) {
  40. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  41. const kMaxKernelSize = 25;
  42. let kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  43. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  44. const halfWidth = ( kernelSize - 1 ) * 0.5;
  45. const values = new Array( kernelSize );
  46. let sum = 0.0;
  47. for ( let i = 0; i < kernelSize; ++ i ) {
  48. values[ i ] = gauss( i - halfWidth, sigma );
  49. sum += values[ i ];
  50. }
  51. // normalize the kernel
  52. for ( let i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
  53. return values;
  54. }
  55. };
  56. function gauss( x, sigma ) {
  57. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  58. }
  59. export { ConvolutionShader };