ConvolutionShader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. *
  4. * Convolution shader
  5. * ported from o3d sample to WebGL / GLSL
  6. * http://o3d.googlecode.com/svn/trunk/samples/convolution.html
  7. */
  8. THREE.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 THREE.Vector2( 0.001953125, 0.0 ) },
  16. "cKernel": { value: [] }
  17. },
  18. vertexShader: [
  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. ].join( "\n" ),
  26. fragmentShader: [
  27. "uniform float cKernel[ KERNEL_SIZE_INT ];",
  28. "uniform sampler2D tDiffuse;",
  29. "uniform vec2 uImageIncrement;",
  30. "varying vec2 vUv;",
  31. "void main() {",
  32. "vec2 imageCoord = vUv;",
  33. "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );",
  34. "for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {",
  35. "sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];",
  36. "imageCoord += uImageIncrement;",
  37. "}",
  38. "gl_FragColor = sum;",
  39. "}"
  40. ].join( "\n" ),
  41. buildKernel: function ( sigma ) {
  42. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  43. function gauss( x, sigma ) {
  44. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  45. }
  46. var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  47. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  48. halfWidth = ( kernelSize - 1 ) * 0.5;
  49. values = new Array( kernelSize );
  50. sum = 0.0;
  51. for ( i = 0; i < kernelSize; ++ i ) {
  52. values[ i ] = gauss( i - halfWidth, sigma );
  53. sum += values[ i ];
  54. }
  55. // normalize the kernel
  56. for ( i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
  57. return values;
  58. }
  59. };