header_builders.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import os.path
  2. ## See https://github.com/godotengine/godot/blob/master/glsl_builders.py
  3. def build_raw_header(source_filename: str, constant_name: str) -> None:
  4. # Read the source file content.
  5. with open(source_filename, "r") as source_file:
  6. source_content = source_file.read()
  7. constant_name = constant_name.replace(".", "_")
  8. # Build header content using a C raw string literal.
  9. header_content = (
  10. "/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n"
  11. "#pragma once\n\n"
  12. f"inline constexpr const char *{constant_name}"
  13. " = "
  14. f'R"<!>({source_content})<!>"'
  15. ";\n"
  16. )
  17. # Write the header to the provided file name with a ".gen.h" suffix.
  18. header_filename = f"{source_filename}.gen.h"
  19. with open(header_filename, "w") as header_file:
  20. header_file.write(header_content)
  21. def build_raw_headers_action(target, source, env):
  22. env.NoCache(target)
  23. for src in source:
  24. source_filename = str(src)
  25. # To match Godot, replace ".glsl" with "_shader_glsl". Does nothing for non-GLSL files.
  26. constant_name = os.path.basename(source_filename).replace(".glsl", "_shader_glsl")
  27. build_raw_header(source_filename, constant_name)
  28. def escape_svg(filename: str) -> str:
  29. with open(filename, encoding="utf-8", newline="\n") as svg_file:
  30. svg_content = svg_file.read()
  31. return f'R"<!>({svg_content})<!>"'
  32. ## See https://github.com/godotengine/godot/blob/master/editor/icons/editor_icons_builders.py
  33. ## See https://github.com/godotengine/godot/blob/master/scene/theme/icons/default_theme_icons_builders.py
  34. def make_svg_icons_action(target, source, env):
  35. destination = str(target[0])
  36. constant_prefix = os.path.basename(destination).replace(".gen.h", "")
  37. svg_icons = [str(x) for x in source]
  38. # Convert the SVG icons to escaped strings and convert their names to C strings.
  39. icon_names = [f'"{os.path.basename(fname)[:-4]}"' for fname in svg_icons]
  40. icon_sources = [escape_svg(fname) for fname in svg_icons]
  41. # Join them as indented comma-separated items for use in an array initializer.
  42. icon_names_str = ",\n\t".join(icon_names)
  43. icon_sources_str = ",\n\t".join(icon_sources)
  44. # Write the file to disk.
  45. with open(destination, "w", encoding="utf-8", newline="\n") as destination_file:
  46. destination_file.write(
  47. f"""\
  48. /* THIS FILE IS GENERATED. EDITS WILL BE LOST. */
  49. #pragma once
  50. inline constexpr int {constant_prefix}_count = {len(icon_names)};
  51. inline constexpr const char *{constant_prefix}_sources[] = {{
  52. {icon_sources_str}
  53. }};
  54. inline constexpr const char *{constant_prefix}_names[] = {{
  55. {icon_names_str}
  56. }};
  57. """
  58. )