ConvolutionShader.js 1.9 KB

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