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.

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