colour_palette.gdshader 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. shader_type canvas_item;
  2. uniform sampler2D screen_texture : hint_screen_texture, filter_nearest;
  3. uniform sampler2D palette_texture;
  4. uniform vec4 shadow_colour : source_color;
  5. uniform float y_offset : hint_range(0, 2);
  6. uniform int palette_size = 8;
  7. uniform bool is_debug = false;
  8. int get_palette_index(vec4 color) {
  9. ivec4 quantized_color = ivec4(floor(color * 255.0 + 0.5)); // Quantize the color
  10. for (int i = 0; i < palette_size; i++) {
  11. float index = (float(i) + 0.5) / float(palette_size); // Sample at the center of each color slot
  12. vec4 palette_color = texture(palette_texture, vec2(index, 0.0));
  13. ivec4 quantized_palette = ivec4(floor(palette_color * 255.0 + 0.5)); // Quantize the palette color
  14. if (quantized_color == quantized_palette) {
  15. return i; // Found exact match
  16. }
  17. }
  18. return -1; // No match found
  19. }
  20. void fragment() {
  21. vec4 screen_color = texture(screen_texture, SCREEN_UV);
  22. // Check if the color is close to the shadow colo
  23. int palette_index;
  24. palette_index = get_palette_index(screen_color);
  25. // Normalize the palette index for UV lookup
  26. if (palette_index != -1) {
  27. float palette_uv_x = (float(palette_index) + 0.5) / float(palette_size);
  28. float palette_uv_y = (float(y_offset) + 0.5) / float(3);
  29. COLOR = texture(palette_texture, vec2(palette_uv_x, palette_uv_y));
  30. } else {
  31. // Fallback if no match (this should only happen if no matching palette index is found)
  32. if (is_debug)
  33. {
  34. COLOR = texture(palette_texture, vec2(float(palette_size), 0.0));
  35. } else
  36. {
  37. COLOR = screen_color;
  38. }
  39. }
  40. }