ConvolutionShader.js 1.9 KB

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