core.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Obstacle JSON editing, independent of Tk and the game runtime."""
  2. import datetime
  3. import json
  4. import os
  5. from pathlib import Path
  6. import re
  7. import shutil
  8. import tempfile
  9. from client_local.utils.transparent_range import contains_point, normalize_ranges
  10. def find_project_root(path):
  11. start = Path(path).resolve()
  12. if start.is_file():
  13. start = start.parent
  14. for parent in (start,) + tuple(start.parents):
  15. if (parent / "res/img/mapElem").is_dir() and (parent / "game/frame").is_dir():
  16. return parent
  17. return None
  18. def frame_entries(data):
  19. result = []
  20. for state in ("STAND", "PUSH", "DIE", "TRIGGER", "TYPE_LEN"):
  21. frames = data.get(state, {})
  22. if not isinstance(frames, dict):
  23. continue
  24. for i, name in enumerate(frames.get("IMG", [])):
  25. try:
  26. cx, cy = frames["CX"][i], frames["CY"][i]
  27. except (KeyError, IndexError, TypeError):
  28. raise ValueError("%s 第 %d 帧缺少 CX/CY" % (state, i + 1))
  29. result.append(dict(label="%s [%d] %s" % (state, i, name), image=name, cx=cx, cy=cy))
  30. if not result:
  31. raise ValueError("JSON 没有可预览的 STAND / PUSH / DIE / TRIGGER / TYPE_LEN 图片帧")
  32. return result
  33. def replace_field(text, field, value):
  34. """Replace just the field's value, preserving all other text and fields."""
  35. data = json.loads(text)
  36. if not isinstance(data, dict):
  37. raise ValueError("障碍物 JSON 顶层必须是字典")
  38. replacement = json.dumps(value, ensure_ascii=False, separators=(", ", ": "))
  39. decoder = json.JSONDecoder()
  40. index = text.index("{") + 1
  41. while True:
  42. while text[index].isspace():
  43. index += 1
  44. if text[index] == "}":
  45. break
  46. key, end = decoder.raw_decode(text, index)
  47. index = end
  48. while text[index].isspace():
  49. index += 1
  50. index += 1 # Colon: json.loads above has already validated the syntax.
  51. while text[index].isspace():
  52. index += 1
  53. value_start = index
  54. _, index = decoder.raw_decode(text, index)
  55. if key == field:
  56. return text[:value_start] + replacement + text[index:]
  57. while text[index].isspace():
  58. index += 1
  59. if text[index] == ",":
  60. index += 1
  61. newline = "\r\n" if "\r\n" in text else "\n"
  62. match = re.search(r'(?m)^([ \t]+)"', text)
  63. indent = match.group(1) if match else " "
  64. end = text.rfind("}")
  65. prefix = text[:end].rstrip()
  66. return prefix + ("," if data else "") + newline + indent + json.dumps(field) + ': ' + replacement + newline + text[end:]
  67. def replace_ranges(text, ranges):
  68. return replace_field(text, "TRANSPARENT_RANGE", normalize_ranges(ranges))
  69. class ObstacleDocument:
  70. def __init__(self, path, project_root=None):
  71. self.path = Path(path).resolve()
  72. self.original_bytes = self.path.read_bytes()
  73. self.bom = self.original_bytes.startswith(b"\xef\xbb\xbf")
  74. self.text = self.original_bytes.decode("utf-8-sig")
  75. self.data = json.loads(self.text)
  76. if not isinstance(self.data, dict):
  77. raise ValueError("障碍物 JSON 顶层必须是字典")
  78. self.ranges = normalize_ranges(self.data.get("TRANSPARENT_RANGE"))
  79. self.frames = frame_entries(self.data)
  80. self.project_root = Path(project_root).resolve() if project_root else find_project_root(self.path)
  81. def image_path(self, frame):
  82. if self.project_root is None:
  83. raise ValueError("找不到工程目录,请先选择含 game 和 res 的工程目录")
  84. library = self.data.get("TYPE", self.path.parent.name)
  85. return self.project_root / "res/img/mapElem" / library / frame["image"]
  86. def save(self, ranges, top_update=None):
  87. ranges = normalize_ranges(ranges)
  88. if self.path.read_bytes() != self.original_bytes:
  89. raise ValueError("文件已被其他程序修改,请重新打开后再保存")
  90. text = replace_ranges(self.text, ranges)
  91. if top_update is not None:
  92. if not isinstance(top_update, bool):
  93. raise ValueError("TOP_UPDATE 必须是 true 或 false")
  94. if top_update != bool(self.data.get("TOP_UPDATE", False)):
  95. text = replace_field(text, "TOP_UPDATE", top_update)
  96. payload = (b"\xef\xbb\xbf" if self.bom else b"") + text.encode("utf-8")
  97. if payload == self.original_bytes:
  98. return None
  99. backup = self.path.with_name(self.path.name + "." + datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") + ".bak")
  100. fd, temporary = tempfile.mkstemp(prefix=".transparent_", suffix=".tmp", dir=str(self.path.parent))
  101. try:
  102. with os.fdopen(fd, "wb") as stream:
  103. stream.write(payload)
  104. stream.flush()
  105. os.fsync(stream.fileno())
  106. shutil.copy2(str(self.path), str(backup))
  107. os.replace(temporary, str(self.path))
  108. finally:
  109. if os.path.exists(temporary):
  110. os.unlink(temporary)
  111. self.original_bytes = payload
  112. self.text = text
  113. self.data["TRANSPARENT_RANGE"] = ranges
  114. if top_update is not None and (top_update or "TOP_UPDATE" in self.data):
  115. self.data["TOP_UPDATE"] = top_update
  116. self.ranges = ranges
  117. return backup