SobelOperatorShader.js 2.5 KB

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