ConvolutionShader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. import {
  9. Vector2
  10. } from "../../../build/three.module.js";
  11. var ConvolutionShader = {
  12. defines: {
  13. "KERNEL_SIZE_FLOAT": "25.0",
  14. "KERNEL_SIZE_INT": "25"
  15. },
  16. uniforms: {
  17. "tDiffuse": { value: null },
  18. "uImageIncrement": { value: new Vector2( 0.001953125, 0.0 ) },
  19. "cKernel": { value: [] }
  20. },
  21. vertexShader: [
  22. "uniform vec2 uImageIncrement;",
  23. "varying vec2 vUv;",
  24. "void main() {",
  25. "vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;",
  26. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  27. "}"
  28. ].join( "\n" ),
  29. fragmentShader: [
  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. ].join( "\n" ),
  44. buildKernel: function ( sigma ) {
  45. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  46. function gauss( x, sigma ) {
  47. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  48. }
  49. var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  50. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  51. halfWidth = ( kernelSize - 1 ) * 0.5;
  52. values = new Array( kernelSize );
  53. sum = 0.0;
  54. for ( i = 0; i < kernelSize; ++ i ) {
  55. values[ i ] = gauss( i - halfWidth, sigma );
  56. sum += values[ i ];
  57. }
  58. // normalize the kernel
  59. for ( i = 0; i < kernelSize; ++ i ) values[ i ] /= sum;
  60. return values;
  61. }
  62. };
  63. export { ConvolutionShader };