derivative.glsl 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. uniform sampler2D tex;
  2. uniform int operation;
  3. uniform float width;
  4. uniform float height;
  5. #define CORRECTION 2.25
  6. #define SIZE_ADDITION 3
  7. vec4 get_texture_at_position(vec2 position) {
  8. vec2 raw_position = position + vec2(CORRECTION, CORRECTION);
  9. vec2 raw_uv = raw_position / vec2(width + SIZE_ADDITION, height + SIZE_ADDITION);
  10. return texture2D(tex, raw_uv);
  11. }
  12. vec4 try_get_texture_at_position(vec2 position, inout int count) {
  13. if (any(greaterThanEqual(position, vec2(width, height))) ||
  14. any(lessThan(position, vec2(0, 0)))) {
  15. return vec4(0);
  16. } else {
  17. count++;
  18. return get_texture_at_position(position);
  19. }
  20. }
  21. ivec2 get_corrected_position() {
  22. vec2 raw_uv = cogl_tex_coord0_in.st;
  23. vec2 raw_position = raw_uv * vec2(width + SIZE_ADDITION, height + SIZE_ADDITION);
  24. return ivec2(raw_position - vec2(CORRECTION, CORRECTION));
  25. }
  26. void main() {
  27. ivec2 corrected_position = get_corrected_position();
  28. // 1-step derivative
  29. if (operation == 0) {
  30. vec4 color = vec4(0);
  31. int c = 0;
  32. color += try_get_texture_at_position(corrected_position + vec2(0, 1), c);
  33. color -= try_get_texture_at_position(corrected_position + vec2(0, 0), c);
  34. color += try_get_texture_at_position(corrected_position + vec2(1, 0), c);
  35. color -= try_get_texture_at_position(corrected_position + vec2(0, 0), c);
  36. if (c < 4) {
  37. color = vec4(0);
  38. }
  39. cogl_color_out = vec4(color.xyz, 1);
  40. } else
  41. // 2-step derivative
  42. if (operation == 1) {
  43. vec4 color = vec4(0);
  44. int c = 0;
  45. color += try_get_texture_at_position(corrected_position + vec2(0, 1), c);
  46. color -= try_get_texture_at_position(corrected_position + vec2(0, -1), c);
  47. color += try_get_texture_at_position(corrected_position + vec2(1, 0), c);
  48. color -= try_get_texture_at_position(corrected_position + vec2(-1, 0), c);
  49. if (c < 4) {
  50. color = vec4(0);
  51. }
  52. cogl_color_out = vec4(color.xyz / 2, 1);
  53. } else
  54. // laplacian
  55. if (operation == 2) {
  56. vec4 color = vec4(0);
  57. color = -4 * get_texture_at_position(corrected_position);
  58. color += get_texture_at_position(corrected_position + vec2(0, 1));
  59. color += get_texture_at_position(corrected_position + vec2(0, -1));
  60. color += get_texture_at_position(corrected_position + vec2(1, 0));
  61. color += get_texture_at_position(corrected_position + vec2(-1, 0));
  62. cogl_color_out = vec4(color.xyz, 1);
  63. }
  64. }