EdgeShader2.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @author zz85 / https://github.com/zz85 | https://www.lab4games.net/zz85/blog
  3. *
  4. * Edge Detection Shader using Sobel filter
  5. * Based on http://rastergrid.com/blog/2011/01/frei-chen-edge-detector
  6. *
  7. * aspect: vec2 of (1/width, 1/height)
  8. */
  9. THREE.EdgeShader2 = {
  10. uniforms: {
  11. "tDiffuse": { value: null },
  12. "aspect": { value: new THREE.Vector2( 512, 512 ) }
  13. },
  14. vertexShader: [
  15. "varying vec2 vUv;",
  16. "void main() {",
  17. "vUv = uv;",
  18. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  19. "}"
  20. ].join( "\n" ),
  21. fragmentShader: [
  22. "uniform sampler2D tDiffuse;",
  23. "varying vec2 vUv;",
  24. "uniform vec2 aspect;",
  25. "vec2 texel = vec2(1.0 / aspect.x, 1.0 / aspect.y);",
  26. "mat3 G[2];",
  27. "const mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );",
  28. "const mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );",
  29. "void main(void)",
  30. "{",
  31. "mat3 I;",
  32. "float cnv[2];",
  33. "vec3 sample;",
  34. "G[0] = g0;",
  35. "G[1] = g1;",
  36. /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */
  37. "for (float i=0.0; i<3.0; i++)",
  38. "for (float j=0.0; j<3.0; j++) {",
  39. "sample = texture2D( tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb;",
  40. "I[int(i)][int(j)] = length(sample);",
  41. "}",
  42. /* calculate the convolution values for all the masks */
  43. "for (int i=0; i<2; i++) {",
  44. "float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);",
  45. "cnv[i] = dp3 * dp3; ",
  46. "}",
  47. "gl_FragColor = vec4(0.5 * sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]));",
  48. "} "
  49. ].join( "\n" )
  50. };