You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

140 lines
3.5 KiB

  1. import argparse
  2. import pathlib
  3. import subprocess
  4. import sys
  5. import tempfile
  6. from typing import NoReturn
  7. from PIL import Image
  8. GREEN = (0, 255, 0)
  9. RED = (255, 0, 0)
  10. def abort(msg: str) -> NoReturn:
  11. print(msg, file=sys.stderr)
  12. sys.exit(1)
  13. def generate_coll_map(in_path: pathlib.Path, width: int, height: int) -> str:
  14. png = Image.open(in_path).convert("RGB")
  15. if png.width % 8 != 0 or png.height % 8 != 0:
  16. abort(f"file '{in_path}' has invalid dimensions (should be multiple of 8)")
  17. if png.width // 8 != width or png.height // 8 != height:
  18. abort(f"file '{in_path}' has different size from map")
  19. out_bytes = []
  20. bits = []
  21. for y in range(png.height // 8):
  22. for x in range(png.width // 8):
  23. pixel = png.getpixel((x * 8, y * 8))
  24. bit = None
  25. if pixel == RED:
  26. bit = 1
  27. elif pixel == GREEN:
  28. bit = 0
  29. else:
  30. abort(f"unsupported pixel in collision map: {pixel}")
  31. bits.append(bit)
  32. if len(bits) == 8:
  33. byte = sum([bit << i for i, bit in enumerate(bits)])
  34. out_bytes.append(byte)
  35. bits = []
  36. png.close()
  37. lines = []
  38. for line_no in range(0, len(out_bytes), 16):
  39. line = out_bytes[line_no : line_no + 16]
  40. lines.append(" DB " + ", ".join(["$%02X" % b for b in line]))
  41. return "\n".join(lines)
  42. def format_bytes(data: bytes) -> str:
  43. lines = []
  44. for line_no in range(0, len(data), 16):
  45. line = data[line_no : line_no + 16]
  46. lines.append(" DB " + ", ".join(["$%02X" % b for b in line]))
  47. return "\n".join(lines)
  48. def generate_map(pngfile: str) -> None:
  49. pngpath = pathlib.Path(pngfile).resolve()
  50. incpath = pngpath.parent / pngpath.name.replace(".png", ".inc")
  51. spath = pngpath.parent / pngpath.name.replace(".png", ".s")
  52. png = Image.open(pngpath)
  53. if png.width % 8 != 0 or png.height % 8 != 0:
  54. abort(f"file '{pngfile}' has invalid dimensions (should be multiple of 8)")
  55. width = png.width // 8
  56. height = png.height // 8
  57. png.close()
  58. with tempfile.NamedTemporaryFile() as tilef, tempfile.NamedTemporaryFile() as mapf:
  59. subprocess.run(
  60. [
  61. "rgbgfx",
  62. "-u",
  63. "-t",
  64. tilef.name,
  65. "-o",
  66. mapf.name,
  67. pngfile,
  68. ]
  69. )
  70. map_data = format_bytes(tilef.read())
  71. tile_data = format_bytes(mapf.read())
  72. section = pngpath.name.replace(".png", "")
  73. collpath = pngpath.parent / pngpath.name.replace(".png", "_coll.png")
  74. coll_map = generate_coll_map(collpath, width, height)
  75. with open(incpath, "w") as outf:
  76. outf.write(
  77. f"""DEF {section}_WIDTH EQU {width}
  78. DEF {section}_HEIGHT EQU {height}
  79. DEF {section}_NUM_TILES EQUS "({section}_TILES_end - {section}_TILES)"
  80. DEF {section}_MAP_SIZE EQUS "({section}_MAP_end - {section}_MAP)"
  81. ASSERT {section}_MAP_SIZE == {section}_WIDTH * {section}_HEIGHT
  82. """
  83. )
  84. with open(spath, "w") as outf:
  85. outf.write(
  86. f"""SECTION "MAP - {section}", ROMX
  87. {section}_MAP::
  88. {map_data}
  89. {section}_MAP_end::
  90. {section}_TILES::
  91. {tile_data}
  92. {section}_TILES_end::
  93. {section}_COLLISION::
  94. {coll_map}
  95. {section}_COLLISION_end::
  96. """
  97. )
  98. def main() -> None:
  99. parser = argparse.ArgumentParser("generate_map")
  100. parser.add_argument("png")
  101. args = parser.parse_args()
  102. generate_map(args.png)
  103. if __name__ == "__main__":
  104. main()