ConvolutionShader.js 1.8 KB

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