SobelOperatorShader.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  3. *
  4. * As mentioned in the video the Sobel operator expects a grayscale image as input.
  5. *
  6. */
  7. THREE.SobelOperatorShader = {
  8. uniforms: {
  9. 'tDiffuse': { value: null },
  10. 'resolution': { value: new THREE.Vector2() }
  11. },
  12. vertexShader: [
  13. 'varying vec2 vUv;',
  14. 'void main() {',
  15. ' vUv = uv;',
  16. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  17. '}'
  18. ].join( '\n' ),
  19. fragmentShader: [
  20. 'uniform sampler2D tDiffuse;',
  21. 'uniform vec2 resolution;',
  22. 'varying vec2 vUv;',
  23. 'void main() {',
  24. ' vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );',
  25. // kernel definition (in glsl matrices are filled in column-major order)
  26. ' const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 );', // x direction kernel
  27. ' const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 );', // y direction kernel
  28. // fetch the 3x3 neighbourhood of a fragment
  29. // first column
  30. ' float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;',
  31. ' float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r;',
  32. ' float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r;',
  33. // second column
  34. ' float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r;',
  35. ' float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r;',
  36. ' float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r;',
  37. // third column
  38. ' float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r;',
  39. ' float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r;',
  40. ' float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r;',
  41. // gradient value in x direction
  42. ' float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + ',
  43. ' Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + ',
  44. ' Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; ',
  45. // gradient value in y direction
  46. ' float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + ',
  47. ' Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + ',
  48. ' Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; ',
  49. // magnitute of the total gradient
  50. ' float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );',
  51. ' gl_FragColor = vec4( vec3( G ), 1 );',
  52. '}'
  53. ].join( '\n' )
  54. };