srgb_lut.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. from functools import lru_cache
  5. if __name__ == '__main__' and not __package__:
  6. import __main__
  7. __main__.__package__ = 'gen'
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. def to_linear(a: float) -> float:
  10. if a <= 0.04045:
  11. return a / 12.92
  12. else:
  13. return float(pow((a + 0.055) / 1.055, 2.4))
  14. @lru_cache
  15. def generate_srgb_lut(line_prefix: str = ' ') -> list[str]:
  16. values: list[str] = []
  17. lines: list[str] = []
  18. for i in range(256):
  19. values.append(f'{to_linear(i / 255.0):1.5f}f')
  20. for i in range(16):
  21. lines.append(line_prefix + ', '.join(values[i * 16:(i + 1) * 16]) + ',')
  22. lines[-1] = lines[-1].rstrip(',')
  23. return lines
  24. def generate_srgb_gamma(declaration: str = 'static const GLfloat srgb_lut[256] = {', close: str = '};') -> str:
  25. lines: list[str] = []
  26. a = lines.append
  27. a('// Generated by gen-srgb-lut.py DO NOT edit')
  28. a('')
  29. a(declaration)
  30. lines += generate_srgb_lut()
  31. a(close)
  32. return "\n".join(lines)
  33. def main(args: list[str]=sys.argv) -> None:
  34. c = generate_srgb_gamma()
  35. with open(os.path.join('kitty', 'srgb_gamma.h'), 'w') as f:
  36. f.write(f'{c}\n')
  37. if __name__ == '__main__':
  38. import runpy
  39. m = runpy.run_path(os.path.dirname(os.path.abspath(__file__)))
  40. m['main']([sys.executable, 'srgb-lut'])