ThreeKingdomsSlingshot/Tools/map_bounds.py

398 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""맵 경계 충돌 · 가림층 도구(PD 2026-11-26 「게임에 보이는 배경 오브젝트에 유닛들이 튕겨지게 · 성채는 부술 수 없는 맵 경계 ·
깃발이나 성채처럼 유닛을 가릴 수 있는 배경 오브젝트는 가려진 유닛을 실루엣으로 · 새 맵이 추가될 때도 같은 규칙이 기본 사양」).
표(SOT · 손으로 적음) = Assets/Resources/Board/board_bounds.csv
s_file,n_w,n_h,s_kind,s_id,s_points,f_base,s_cut,Memo
· s_file = Resources/Board 바닥 그림 이름 · n_w,n_h = 그 그림 원본 px(좌표 기준 · 임포트 축소와 무관)
· s_points = 「x y;x y;…」 원본 px(왼쪽 위 = 0,0)
· s_kind walk = 걸을 수 있는 땅의 테두리(맵 1장에 1개) — 밖 = 부술 수 없는 벽(BoardWall · 유닛이 튕김) · 유닛 자리 보정(Board.ClampInside)도 이 안으로
wall = 안쪽의 막힌 구조물 바닥(다각형 · BoardWall)
cover = 유닛을 가리는 구조물(깃발 · 목책 · 천막 …) 대략 영역 — 도구가 그 안에서 구조물 모양만 오려 「가림층」 그림을 만든다.
f_base = 그 구조물이 땅에 닿는 줄(px y · 이보다 위(작은 y)에 발이 있는 유닛 = 뒤 = 가려지고 실루엣) · 빈칸 = 영역 맨 아래
s_cut = shape(기본 · 바닥과 이어진 밝은 땅을 빼고 외곽선으로 닫힌 구조물만) | poly(영역 그대로)
생성(이 도구가 씀 · 손대지 않음) = Assets/Resources/Board/Covers/<그림>__<id>.png · Assets/Resources/Board/board_covers.csv
python -I Tools/map_bounds.py bake [그림 …] 가림층 그림 + board_covers.csv 다시 만들기(이름 없으면 표 전부)
python -I Tools/map_bounds.py preview <폴더> [그림 …] [--grid 200] 검수 그림(걷는 땅 초록 · 벽 빨강 · 가림층 분홍 · 전장 노랑 · 배치 점(아군 파랑 · 적 빨강) · 기믹 하늘색 · --grid = 원본 px 눈금)
python -I Tools/map_bounds.py check 전투에 쓰는 모든 바닥 그림에 walk 줄이 있는가 + 배치 자리가 걷는 땅 안인가
"""
import csv
import math
import os
import re
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
from scipy import ndimage
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BOARD = os.path.join(ROOT, "Assets", "Resources", "Board")
BOUNDS = os.path.join(BOARD, "board_bounds.csv")
COVERS_CSV = os.path.join(BOARD, "board_covers.csv")
COVERS_DIR = os.path.join(BOARD, "Covers")
MARGIN = os.path.join(BOARD, "bg_margin.csv")
CONFIG = os.path.join(ROOT, "Assets", "Resources", "BalanceConfig.asset")
SC_PROPS = os.path.join(ROOT, "Assets", "Resources", "Scenario", "scenario_props.csv")
SC_LAYOUT = os.path.join(ROOT, "Assets", "Resources", "ContentModes", "scenario_layout.csv")
THEME_FILES = os.path.join(BOARD, "bg_theme_files.csv")
# 오려 내기 값(도구 조작값 · 게임 데이터 아님): 외곽선 = 밝기 < OUTLINE_LUM(이 화풍 외곽선 22~40 · 바닥 180 대 · 2026-11-26 실측)
OUTLINE_LUM = 70
SPECK_PX = 900 # 이보다 작은 닫힌 조각(바닥 자갈 테두리 등) = 구조물 아님(원본 px 넓이)
GROW_PX = 2 # 외곽선 바깥 번짐 포함
IMPORT_MAX = 2048 # Board 그림 임포트 최대 크기(.meta maxTextureSize) — 가림층도 같은 선명도로 줄여 굽는다
def read_csv(path):
if not os.path.exists(path):
return []
with open(path, encoding="utf-8-sig", newline="") as f:
return list(csv.DictReader(f))
def pts(s):
out = []
for p in (s or "").split(";"):
p = p.strip()
if not p:
continue
x, y = p.split()
out.append((float(x), float(y)))
return out
def rows_by_file(names=None):
by = {}
for r in read_csv(BOUNDS):
f = r["s_file"].strip()
if not f or (names and f not in names):
continue
by.setdefault(f, []).append(r)
return by
def poly_mask(size, poly):
m = Image.new("L", size, 0)
ImageDraw.Draw(m).polygon([tuple(p) for p in poly], fill=255)
return np.asarray(m) > 0
def cut_shape(rgb, region, top_rows):
"""region 안에서 바닥(영역 윗변과 밝은 픽셀로 이어진 땅)을 뺀 구조물 마스크."""
lum = (rgb[..., 0] * 299 + rgb[..., 1] * 587 + rgb[..., 2] * 114) // 1000
passable = region & (lum >= OUTLINE_LUM)
lab, n = ndimage.label(passable)
seeds = np.unique(lab[top_rows][lab[top_rows] > 0])
ground = np.isin(lab, seeds)
solid = region & ~ground
lab2, n2 = ndimage.label(solid)
if n2:
area = ndimage.sum(np.ones_like(lab2), lab2, index=np.arange(1, n2 + 1))
keep = np.zeros(n2 + 1, bool)
keep[1:] = area >= SPECK_PX
solid = keep[lab2]
if GROW_PX > 0:
solid = ndimage.binary_dilation(solid, iterations=GROW_PX) & region
return solid
def bake(names=None):
by = rows_by_file(names)
old = [r for r in read_csv(COVERS_CSV) if names and r["s_file"] not in names]
out = list(old)
os.makedirs(COVERS_DIR, exist_ok=True)
if names:
for f in os.listdir(COVERS_DIR):
if f.endswith(".png") and f.split("__")[0] in names:
os.remove(os.path.join(COVERS_DIR, f))
else:
for f in os.listdir(COVERS_DIR):
if f.endswith(".png"):
os.remove(os.path.join(COVERS_DIR, f))
for name, rows in sorted(by.items()):
covers = [r for r in rows if r["s_kind"].strip() == "cover"]
if not covers:
continue
src = os.path.join(BOARD, name + ".png")
im = Image.open(src).convert("RGB")
W, H = im.size
if (W, H) != (int(covers[0]["n_w"]), int(covers[0]["n_h"])):
sys.exit("[map_bounds] %s 크기 %dx%d ≠ 표 n_w,n_h %s,%s" % (name, W, H, covers[0]["n_w"], covers[0]["n_h"]))
rgb = np.asarray(im).astype(np.int32)
scale = min(1.0, IMPORT_MAX / float(max(W, H)))
for r in covers:
poly = pts(r["s_points"])
region = poly_mask((W, H), poly)
ys = np.where(region.any(axis=1))[0]
top = np.zeros_like(region)
top[ys[0]:ys[0] + 3] = region[ys[0]:ys[0] + 3]
mode = (r.get("s_cut") or "shape").strip() or "shape"
m = cut_shape(rgb, region, top) if mode == "shape" else region
if not m.any():
print("[map_bounds] %s/%s 오려 낸 구조물 없음 — 건너뜀" % (name, r["s_id"]))
continue
yy, xx = np.where(m)
x0, x1, y0, y1 = int(xx.min()), int(xx.max()) + 1, int(yy.min()), int(yy.max()) + 1
alpha = Image.fromarray((m[y0:y1, x0:x1] * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.8))
tile = im.crop((x0, y0, x1, y1)).convert("RGBA")
tile.putalpha(alpha)
if scale < 1.0:
tile = tile.resize((max(1, round(tile.width * scale)), max(1, round(tile.height * scale))), Image.LANCZOS)
fn = "%s__%s.png" % (name, r["s_id"])
tile.save(os.path.join(COVERS_DIR, fn))
base = r.get("f_base", "").strip()
base = float(base) if base else max(p[1] for p in poly)
out.append({"s_file": name, "s_id": r["s_id"], "n_x": x0, "n_y": y0, "n_w": x1 - x0, "n_h": y1 - y0,
"f_base": base, "n_img_w": W, "n_img_h": H,
"Memo": "생성 = Tools/map_bounds.py bake(손대지 않음) · 원본 px"})
print("[map_bounds] %s %d×%d px(원본) → %d×%d" % (fn, x1 - x0, y1 - y0, tile.width, tile.height))
cols = ["s_file", "s_id", "n_x", "n_y", "n_w", "n_h", "f_base", "n_img_w", "n_img_h", "Memo"]
with open(COVERS_CSV, "w", encoding="utf-8-sig", newline="") as f:
w = csv.DictWriter(f, fieldnames=cols)
w.writeheader()
for r in sorted(out, key=lambda r: (r["s_file"], r["s_id"])):
w.writerow({k: r.get(k, "") for k in cols})
# ---------- 전장 ↔ 그림 px (Board.FitArt 와 같은 식) ----------
def board_size():
t = open(CONFIG, encoding="utf-8").read()
m = re.search(r"boardSize: \{x: ([\d.]+), y: ([\d.]+)\}", t)
return float(m.group(1)), float(m.group(2))
def fit(name, W, H):
"""그림 px → 전장 월드 변환(Board.FitArt) · 반환 = (px→월드, 월드→px)."""
bw, bh = board_size()
l = r = t = b = 0.0
for m in read_csv(MARGIN):
if m["s_file"] == name and float(m["n_w"] or 0) > 0:
mw, mh = float(m["n_w"]), float(m["n_h"])
l, r, t, b = float(m["n_left"]) / mw, float(m["n_right"]) / mw, float(m["n_top"]) / mh, float(m["n_bottom"]) / mh
artW, artH = bw / max(0.05, 1 - l - r), bh / max(0.05, 1 - t - b)
cx, cy = (r - l) * 0.5 * artW, (t - b) * 0.5 * artH
xmin, ymax = cx - artW / 2, cy + artH / 2
def to_w(px, py):
return xmin + px / W * artW, ymax - py / H * artH
def to_px(x, y):
return (x - xmin) / artW * W, (ymax - y) / artH * H
return to_w, to_px
def inside(poly, x, y):
c = False
n = len(poly)
for i in range(n):
x1, y1 = poly[i]
x2, y2 = poly[(i + 1) % n]
if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
c = not c
return c
def edge_dist(poly, x, y):
best = 1e9
n = len(poly)
for i in range(n):
ax, ay = poly[i]
bx, by = poly[(i + 1) % n]
dx, dy = bx - ax, by - ay
L = dx * dx + dy * dy
t = 0 if L == 0 else max(0, min(1, ((x - ax) * dx + (y - ay) * dy) / L))
best = min(best, math.hypot(x - ax - t * dx, y - ay - t * dy))
return best
def used_maps():
"""전투에 쓰는 바닥 그림 → 그 위에 놓이는 배치(연의 편 id 목록)."""
used = {}
t = open(CONFIG, encoding="utf-8").read()
m = re.search(r"boardArt: (\S+)", t)
if m:
used.setdefault(m.group(1), set()).add("(출정 · 기본)")
for r in read_csv(THEME_FILES):
f = r["s_file"].strip()
if os.path.exists(os.path.join(BOARD, f + ".png")):
used.setdefault(f, set()).add("(출정 테마 " + r["s_theme_id"] + ")")
for r in read_csv(SC_PROPS):
if r["s_prop_id"] == "_bg":
used.setdefault(r["s_art"], set()).add("%s/%s" % (r["s_battle_id"], r["n_stage"]))
return used
def layout_points(battle_act):
"""연의 편의 유닛 · 기믹 자리(scenario_layout · ref 아닌 행만)."""
b, act = battle_act.split("/")
units, gims = [], []
for r in read_csv(SC_LAYOUT):
if r["s_battle"] != b or r["n_act"] != act or not r["f_x"]:
continue
x, y = float(r["f_x"]), float(r["f_y"])
if r["e_side"] == "gimmick":
w = float(r["f_w_or_r"] or 0)
h = float(r["f_h"] or 0)
gims.append((r["s_gimmick_id"], r["e_shape"], x, y, w, h, r["s_unit_id"]))
elif r["e_side"] in ("ally", "enemy", "player", "npc"):
units.append((r["e_side"], x, y))
return units, gims
def formation_points():
t = open(CONFIG, encoding="utf-8").read()
sp = re.search(r"playerSpawnPoints:\n((?: - \{x: [-\d.]+, y: [-\d.]+\}\n)+)", t)
pl = [(float(a), float(b)) for a, b in re.findall(r"x: ([-\d.]+), y: ([-\d.]+)", sp.group(1))] if sp else []
rows = {}
for k in ("frontY", "middleY", "rearY", "commandY", "colGap", "rowGap"):
m = re.search(r"\n %s: ([-\d.]+)" % k, t)
rows[k] = float(m.group(1)) if m else 0
return pl, rows
def preview(outdir, names=None, grid=0, width=600):
os.makedirs(outdir, exist_ok=True)
by = rows_by_file(names)
used = used_maps()
pl, rows = formation_points()
targets = sorted(set(names or []) | set(by.keys())) if names else sorted(set(by.keys()) | set(used.keys()))
covers = {(r["s_file"], r["s_id"]): r for r in read_csv(COVERS_CSV)}
for name in targets:
src = os.path.join(BOARD, name + ".png")
if not os.path.exists(src):
continue
im = Image.open(src).convert("RGBA")
W, H = im.size
to_w, to_px = fit(name, W, H)
ov = Image.new("RGBA", im.size, (0, 0, 0, 0))
d = ImageDraw.Draw(ov)
bw, bh = board_size()
a, b = to_px(-bw / 2, bh / 2), to_px(bw / 2, -bh / 2)
d.rectangle([a, b], outline=(255, 230, 0, 255), width=6)
for (f, cid), c in covers.items():
if f != name:
continue
p = os.path.join(COVERS_DIR, "%s__%s.png" % (f, cid))
if os.path.exists(p):
t = Image.open(p).convert("RGBA").resize((int(c["n_w"]), int(c["n_h"])))
tint = Image.new("RGBA", t.size, (255, 0, 200, 0))
tint.putalpha(t.getchannel("A").point(lambda v: v * 110 // 255))
ov.alpha_composite(tint, (int(c["n_x"]), int(c["n_y"])))
by_ = float(c["f_base"])
d.line([(int(c["n_x"]), by_), (int(c["n_x"]) + int(c["n_w"]), by_)], fill=(255, 0, 200, 255), width=4)
for r in by.get(name, []):
P = pts(r["s_points"])
if r["s_kind"] == "walk":
d.line(P + [P[0]], fill=(0, 255, 60, 255), width=8)
elif r["s_kind"] == "wall":
d.polygon(P, fill=(255, 0, 0, 90), outline=(255, 0, 0, 255))
# 배치: 출정 판(기본 그림) = 아군 시작 자리 + 적 줄 · 연의 편 = 표 자리
dots = []
if any(k.startswith("(") for k in used.get(name, [])):
dots += [("ally", x, y) for x, y in pl]
for k in ("frontY", "middleY", "rearY", "commandY"):
y = rows[k]
for i in range(-2, 3):
dots.append(("enemy", i * rows["colGap"], y))
gims = []
for k in used.get(name, []):
if "/" in k:
u, g = layout_points(k)
dots += u
gims += g
for gid, shape, x, y, w, h, uid in gims:
if shape == "circle":
c0, c1 = to_px(x - w, y + w), to_px(x + w, y - w)
d.ellipse([c0, c1], outline=(60, 140, 255, 255), width=5)
else:
c0, c1 = to_px(x - w / 2, y + h / 2), to_px(x + w / 2, y - h / 2)
d.rectangle([c0, c1], outline=(60, 140, 255, 255), width=5)
for side, x, y in dots:
cx, cy = to_px(x, y)
rr = to_px(0.45, 0)[0] - to_px(0, 0)[0]
col = (40, 120, 255, 255) if side in ("ally", "player") else (255, 40, 40, 255) if side == "enemy" else (255, 255, 255, 255)
d.ellipse([cx - rr, cy - rr, cx + rr, cy + rr], outline=col, width=6)
if grid:
try:
from PIL import ImageFont
font = ImageFont.truetype("arial.ttf", max(24, W // 40))
except Exception:
font = None
for gx in range(grid, W, grid):
d.line([(gx, 0), (gx, H)], fill=(0, 255, 255, 140), width=3)
d.text((gx + 6, 6), str(gx), fill=(0, 0, 0, 255), font=font)
for gy in range(grid, H, grid):
d.line([(0, gy), (W, gy)], fill=(0, 255, 255, 140), width=3)
d.text((6, gy + 6), str(gy), fill=(0, 0, 0, 255), font=font)
out = Image.alpha_composite(im, ov).convert("RGB")
out = out.resize((width, H * width // W))
out.save(os.path.join(outdir, name + ".png"))
print("[map_bounds] 검수 그림", os.path.join(outdir, name + ".png"))
def check():
by = rows_by_file()
used = used_maps()
pl, rows = formation_points()
bad = 0
for name, who in sorted(used.items()):
walk = [r for r in by.get(name, []) if r["s_kind"] == "walk"]
if not walk:
print("[map_bounds] 누락: %s 에 walk 줄 없음(쓰는 곳 %s)" % (name, ", ".join(sorted(who))))
bad += 1
continue
W, H = int(walk[0]["n_w"]), int(walk[0]["n_h"])
if os.path.exists(os.path.join(BOARD, name + ".png")):
iw, ih = Image.open(os.path.join(BOARD, name + ".png")).size
if (iw, ih) != (W, H):
print("[map_bounds] 크기 불일치: %s 그림 %dx%d ≠ 표 %dx%d" % (name, iw, ih, W, H))
bad += 1
to_w, to_px = fit(name, W, H)
poly = [to_w(x, y) for x, y in pts(walk[0]["s_points"])]
walls = [[to_w(x, y) for x, y in pts(r["s_points"])] for r in by.get(name, []) if r["s_kind"] == "wall"]
dots = []
if any(k.startswith("(") for k in who):
dots += [("아군 시작", x, y) for x, y in pl]
for k in ("frontY", "middleY", "rearY", "commandY"):
for i in range(-2, 3):
dots.append(("적 " + k, i * rows["colGap"], rows[k]))
for k in who:
if "/" in k:
u, _ = layout_points(k)
dots += [("%s %s" % (k, s), x, y) for s, x, y in u]
for lab, x, y in dots:
if not inside(poly, x, y) or edge_dist(poly, x, y) < 0.45:
print("[map_bounds] 걷는 땅 밖(또는 테두리 0.45 안): %s · %s (%.2f, %.2f)" % (name, lab, x, y))
bad += 1
elif any(inside(w, x, y) or edge_dist(w, x, y) < 0.45 for w in walls):
print("[map_bounds] 막힌 구조물 안(또는 0.45 안): %s · %s (%.2f, %.2f)" % (name, lab, x, y))
bad += 1
print("[map_bounds] check 끝 · 문제 %d 건" % bad)
return bad
if __name__ == "__main__":
a = sys.argv[1:]
if not a:
print(__doc__)
sys.exit(1)
if a[0] == "bake":
bake(a[1:] or None)
elif a[0] == "preview":
grid = 0
rest = a[2:]
if "--grid" in rest:
i = rest.index("--grid")
grid = int(rest[i + 1])
rest = rest[:i] + rest[i + 2:]
preview(a[1], rest or None, grid, 700 if grid else 600)
elif a[0] == "check":
sys.exit(1 if check() else 0)
else:
print(__doc__)
sys.exit(1)