#!/usr/bin/env python3 """teaser · 5 秒视频内的世界编辑:「改地图 → 世界跟着变」(神笔马良:画什么就有什么)。 在已有 teaser rollout(outputs/teaser/roll//)的程序化地图上做**随时间变化**的语义编辑:用同一个 (源 clip, 主题, seed) 确定性重建 procmap.World(启动时抽 3 帧与 maps//ids.npz 逐位对拍),编辑 = 每帧一个世界状态(加 / 删物体、改类、地面图层、 角色胶囊),逐帧射线求交渲染 81 帧 parts 语义 id。编辑前(f < 编辑起始帧)的条件与原版逐位相同。然后交给 rollout.py(双向教师、 同首帧、同种子 0、--compile —— 与原版 rollout 的设置一致)生成编辑版,与原版 outputs/teaser/roll//gen.mp4 对照。 注意双向教师一次看全部 81 帧条件 ⇒ 编辑前的画面也可能有细微差别(因果 DMD 学生才逐帧不变)。 编辑类型(--edit;params 见各 prep_*,没给的自动选) add 第 k 帧起在玩家附近、画面里「出现」一个物体 obj ∈ OBJS(tower 塔 / house 房子 / wall 城墙 / tree 大树 / boulder 巨石 / props 箱桶堆 / statue 雕像 / crystal 水晶簇 / pillar 柱 / stone 立石)。位置:只看帧 ≥ k 的角色足迹净空、不压已有物体、 帧 k..80 都在画面里、不挡玩家(≤ 10 %)/ Boss(≤ 35 %),离玩家 90–340 px。anim=pop(默认)| rise | scale。 delete 第 k 帧起删掉画面里最显眼的物体(帧 k / 中 / 80 可见像素的最小值最大的那个);mode=pop 一下子没了 | sink 帧 k..k+dur 沉进地里 | class = 删掉画面里某一类的全部物体(cls 自动 = 物体像素最多的类)。 swap 第 k 帧起把一类换成另一类:pair ∈ PAIRS(veg2rock、arch2veg、pave2grass、grass2pave、rock2veg、arch2rock、veg2arch、 prop2veg、pave2veg);wave>0 ⇒ 以帧 k 的玩家为圆心、wave 帧内扩到全屏的圆("画笔改材质"的波),0 = 一下子全换。 grow 同 add 的物体,帧 k..k+dur 从地里升起(rise,默认)或等比长大(scale,树 / 巨石默认)。 paint 跟着玩家逐帧画出一条路(地面 seg 图层随帧延伸,宽 ≈ 0.11 视野宽);lead>0 ⇒ 路铺到玩家前面 lead 帧; cls 自动:玩家脚下多是 paving ⇒ 画 terrain(草 / 土路),否则画 paving。 write 地上逐笔写字 / 画符号(text ∈ 任意串(中文走 Droid 字体)或 SHAPES 的 star / heart / …):位置 = 帧 k..80 一直在画面里、 少压角色路径的框;mode=paint ⇒ 地面 sdf 图层,按每个连通笔画从左上起的测地距离逐笔揭开(dur 帧写完); mode=raise ⇒ 立体字块(hedge = vegetation / wall = architecture)按书写顺序从地里升起。 spawn 周围逐个冒出一圈 obj(默认 tree;pillar / stone / crystal / tower …):圆心 = 帧 k..k+16 玩家均值,半径 ≈ 0.28 视野, 每 dt 帧一个、各自 rise 帧升起;压角色路径(帧 ≥ k)的位置跳过。 trap 第 k 帧起在 Boss 周围升起一圈墙(cls:arch 默认 / veg 树篱 / rock 石墙),圈住 Boss 帧 k..80 的活动范围;玩家路径处断开。 boss_del 第 k 帧起删掉 Boss(只画玩家胶囊)。 boss_clone 第 k 帧起复制出第二个 Boss(胶囊整体平移 v 到净空处:帧 ≥ k 不穿模、离两个角色 ≥ 2.5 m、≥ 90 % 帧在画面里),动作与原 Boss 同步。 编辑区域 = 逐帧「编辑版 ≠ 原版」的像素(mask.npz),合成视频时高亮。 产物 /cases//(同一个目录也是 rollout.py 的 out/name ⇒ 推完就是自包含的结果目录) ids.npz(编辑后 81 帧条件;rollout 写回同一份)· mask.npz(bits = np.packbits(编辑版 ≠ 原版) + shape)· first.png(首帧 = 原版首帧)· prompts.json / actions.npy(源 clip 的按键,编辑不改动作)· edit.json(编辑类型 / 起止帧 / 参数实际取值 / 底子来源 / 区域统计 / 标签)· cond_sheet.jpg(原版 / 编辑版语义图对照,编辑区域白描边)· 推完再有 rollout.py 的 gen.mp4 / side.mp4 / sheet.jpg / frames.npz / meta.json(job.tags = edit.json 的摘要)。name = __E-<变体>-k。 usage($PY = SPEC §0 的 env + .venv/bin/python;在 $M 下运行;CUDA_VISIBLE_DEVICES 选卡) $PY scripts/teaser/edits.py one --base --edit add --k 32 --params '{"obj": "tower"}' [--out DIR] [--no_job] $PY scripts/teaser/edits.py run --plan outputs/teaser/edit/e81/plan.jsonl --gpus 0,1,2 --procs_per_gpu 4 # 多进程建 case, 每建好一个往 /jobs.jsonl 追加 rollout 任务(rollout.py --jobs /jobs.jsonl --watch 同时吃) $PY scripts/teaser/edits.py status [--plan P] $PY scripts/teaser/edits.py finalize [--out DIR] # 推完后:edit.json 并进 meta.json["edit"],写 /cases_index.jsonl plan.jsonl 每行 {"name"?, "base", "edit", "k", "params"?, "prio"?};同一 base 的行由一个 worker 连着做(底子只重建一次)。 """ from __future__ import annotations import argparse import collections import fcntl import itertools import json import math import os import shutil import subprocess import sys import time import traceback import cv2 import numpy as np M = "/opt/dlami/nvme/zhiyangdeng/maliang" HERE = os.path.dirname(os.path.abspath(__file__)) for _p in (f"{M}/code/gc25d", f"{M}/code/arope", HERE): if _p not in sys.path: sys.path.insert(0, _p) import capsules as CAP # noqa: E402 import geometry as GEO # noqa: E402 import model as GM # noqa: E402 import procmap as PM # noqa: E402 import themes_ext as TE # noqa: E402 from procmap import (ARCH, CLEAR_CM, GRID_CM, PAVING, PROP, ROCK, SKY, TERRAIN, VEG, _dir, _ngon, _rect, box, # noqa: E402 cyl, ell, gable, prism) H, W, F = PM.H, PM.W, PM.F OUT = f"{M}/outputs/teaser/edit/e81" ROLL = f"{M}/outputs/teaser/roll" FPS = 16 CLS_EN = {0: "Sky", 1: "Terrain", 2: "Paving", 3: "Architecture", 4: "Rock", 5: "Vegetation", 6: "Prop"} CLS_SHORT = {"sky": 0, "terrain": 1, "grass": 1, "paving": 2, "pave": 2, "arch": 3, "rock": 4, "veg": 5, "prop": 6} OBJS = ("tower", "house", "wall", "tree", "boulder", "props", "statue", "crystal", "pillar", "stone") OBJ_EN = {"tower": "Tower", "house": "House", "wall": "Wall", "tree": "Tree", "boulder": "Boulder", "props": "Crates", "statue": "Statue", "crystal": "Crystals", "pillar": "Pillar", "stone": "Standing Stone"} PAIRS = {"veg2rock": (VEG, ROCK, "prims"), "arch2veg": (ARCH, VEG, "prims"), "pave2grass": (PAVING, TERRAIN, "ground"), "grass2pave": (TERRAIN, PAVING, "ground"), "rock2veg": (ROCK, VEG, "prims"), "arch2rock": (ARCH, ROCK, "prims"), "veg2arch": (VEG, ARCH, "prims"), "prop2veg": (PROP, VEG, "prims"), "pave2veg": (PAVING, VEG, "ground"), "terrain2veg": (TERRAIN, VEG, "ground")} SHAPES = TE.SHAPES def plural(obj: str) -> str: n = OBJ_EN[obj] return n if n.endswith("s") else n + "s" FONT_CJK = "/usr/share/fonts/google-droid-sans-fonts/DroidSansFallbackFull.ttf" FONT_LAT = "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf" _YS, _XS = PM._YS, PM._XS class EditFail(RuntimeError): """这个底子做不了这种编辑(找不到位置 / 没有 Boss / 没有可删的物体 …)。""" def rp(p: str) -> str: return p if os.path.isabs(p) else os.path.join(M, p) def log(msg: str) -> None: print(f"{time.strftime('%H:%M:%S')} {msg}", flush=True) def smooth01(a: float) -> float: a = min(max(a, 0.0), 1.0) return a * a * (3 - 2 * a) # ---------------------------------------------------------------------------- # 图元变换 / 包围盒 # ---------------------------------------------------------------------------- def p_move(p: dict, v) -> dict: v = np.asarray(v, float) q = dict(p) if p["kind"] == "poly": P = p["planes"].copy() P[:, 3] = P[:, 3] + P[:, :3] @ v q["planes"] = P elif p["kind"] == "ell": q["c"] = p["c"] + v else: q["c"] = p["c"] + v[:2] q["z0"], q["z1"] = p["z0"] + v[2], p["z1"] + v[2] return q def p_scale(p: dict, C, s: float) -> dict: """绕 3D 点 C 等比缩放 s。""" C = np.asarray(C, float) q = dict(p) if p["kind"] == "poly": P = p["planes"].copy() nC = P[:, :3] @ C P[:, 3] = s * (P[:, 3] - nC) + nC q["planes"] = P elif p["kind"] == "ell": q["c"] = C + s * (p["c"] - C) q["r"] = p["r"] * s else: q["c"] = C[:2] + s * (p["c"] - C[:2]) q["r"] = p["r"] * s q["z0"], q["z1"] = C[2] + s * (p["z0"] - C[2]), C[2] + s * (p["z1"] - C[2]) return q def _poly_vertices(planes: np.ndarray) -> np.ndarray: n, d = planes[:, :3], planes[:, 3] tol = 1e-6 * (1 + np.abs(d).max()) V = [] for i, j, k in itertools.combinations(range(len(planes)), 3): A = n[[i, j, k]] if abs(np.linalg.det(A)) < 1e-9: continue x = np.linalg.solve(A, d[[i, j, k]]) if (n @ x - d <= tol).all(): V.append(x) return np.asarray(V) if V else np.zeros((0, 3)) def prims_bbox(prims) -> tuple[np.ndarray, np.ndarray]: lo, hi = np.full(3, np.inf), np.full(3, -np.inf) for p in prims: if p["kind"] == "poly": V = _poly_vertices(p["planes"]) if not len(V): continue a, b = V.min(0), V.max(0) elif p["kind"] == "ell": r = p["r"].max() a, b = p["c"] - [r, r, p["r"][2]], p["c"] + [r, r, p["r"][2]] else: a = np.r_[p["c"] - p["r"], p["z0"]] b = np.r_[p["c"] + p["r"], p["z1"]] lo, hi = np.minimum(lo, a), np.maximum(hi, b) return lo, hi # ---------------------------------------------------------------------------- # 物体模板(返回 (prims, fp);S = 视野尺度) # ---------------------------------------------------------------------------- def make_obj(B, kind: str, p, S: float, rng, yaw: float | None = None): z0 = B.z0 p = np.asarray(p, float) yaw = B.yaw_screen if yaw is None else yaw if kind == "tower": r, h = rng.uniform(95, 115) * S, rng.uniform(480, 600) * S R, hc = r * 1.3, r * rng.uniform(1.7, 2.1) zt = z0 + h pr = [cyl(p, r, z0 - 10, zt, ARCH), cyl(p, R, zt - 5, zt + 30 * S, ARCH), prism(_ngon(p, R, 12), zt + 25 * S, zt + 25 * S + hc, ARCH, taper=R / hc)] return pr, [_ngon(p, R + 10, 12)] if kind == "house": wid, dep, h = rng.uniform(400, 470) * S, rng.uniform(310, 360) * S, rng.uniform(240, 290) * S pr = [box(p, wid, dep, h, yaw, z0 - 20, ARCH), gable(p, wid, dep, yaw, z0 + h, 0.55 * dep, 35 * S, ARCH)] return pr, [_rect(p, wid + 80 * S, dep + 80 * S, yaw)] if kind == "wall": L, t, h = rng.uniform(600, 760) * S, 65 * S, rng.uniform(210, 260) * S pr = [box(p, L, t, h, yaw, z0 - 20, ARCH)] for s in np.linspace(-L / 2 + 40 * S, L / 2 - 40 * S, max(3, int(L / (110 * S)))): pr.append(box(p + _dir(yaw) * s, 50 * S, t + 10 * S, 50 * S, yaw, z0 + h - 5, ARCH)) return pr, [_rect(p, L + 20, t + 20, yaw)] if kind == "tree": B.w.rng = rng pr, fp, _ = PM.tree(B.w, p, "conifer" if rng.random() < 0.3 else "broad", scale=0.85 * S) return pr, fp if kind == "boulder": rx = rng.uniform(180, 230) * S r = np.array([rx, rx * rng.uniform(0.75, 0.95), rx * rng.uniform(0.6, 0.75)]) return [ell(np.r_[p, z0 + 0.15 * r[2]], r, rng.uniform(0, np.pi), ROCK)], [_ngon(p, rx + 10)] if kind == "props": pr, pts = [], [] for _ in range(40): if len(pts) >= 7: break q = p + rng.normal(0, 75 * S, 2) if pts and min(np.linalg.norm(q - a) for a in pts) < 75 * S: continue pts.append(q) if rng.random() < 0.5: s, yy = rng.uniform(70, 95) * S, rng.uniform(0, np.pi) pr.append(box(q, s, s, s, yy, z0 - 5, PROP)) if rng.random() < 0.45: pr.append(box(q, s * 0.85, s * 0.85, s * 0.85, yy + 0.3, z0 + s - 5, PROP)) else: r = rng.uniform(30, 40) * S pr.append(cyl(q, r, z0 - 5, z0 + rng.uniform(85, 110) * S, PROP)) return pr, [TE.hull(np.concatenate([_ngon(a, 75 * S, 8) for a in pts]))] if kind == "statue": s, hb = rng.uniform(150, 180) * S, rng.uniform(110, 140) * S pr = [box(p, s, s, hb, yaw, z0 - 10, ARCH), box(p, s * 0.8, s * 0.8, 20 * S, yaw, z0 + hb - 5, ARCH), cyl(p, s * 0.2, z0 + hb, z0 + hb + 190 * S, ARCH), ell(np.r_[p, z0 + hb + 230 * S], [s * 0.24] * 3, 0, ARCH), TE.limb(np.r_[p, z0 + hb + 150 * S], np.r_[p + _dir(yaw) * 90 * S, z0 + hb + 210 * S], 16 * S, ARCH)] return pr, [_rect(p, s + 20, s + 20, yaw)] if kind == "crystal": B.w.rng = rng return TE.crystal_cluster(B.w, p, 430 * S, ROCK) if kind == "pillar": return TE.column(B.w, p, 42 * S, 420 * S, ARCH) if kind == "stone": a, b, h = rng.uniform(100, 130) * S, rng.uniform(50, 65) * S, rng.uniform(260, 320) * S yy = yaw + rng.uniform(-0.4, 0.4) return [prism(_rect(p, a, b, yy), z0 - 20, z0 + h, ROCK, taper=0.06)], [_rect(p, a + 10, b + 10, yy)] raise ValueError(f"未知物体 {kind!r}(可选 {OBJS})") # ---------------------------------------------------------------------------- # 底子:重建 World + 渲染器 # ---------------------------------------------------------------------------- def base_info(name: str) -> dict: rd = os.path.join(ROLL, name) meta = json.load(open(os.path.join(rd, "meta.json"))) j = meta["job"] map_dir = os.path.dirname(rp(j["ids"])) s = json.load(open(os.path.join(map_dir, "source.json"))) return dict(name=name, roll=rd, first=rp(j["first"]), ids=rp(j["ids"]), prompts=rp(j["prompts"]), map_dir=map_dir, map_case=os.path.basename(map_dir), clip_id=s["clip_id"], theme=s["theme"], seed=int(s["seed"]), scene=j.get("scene"), map=j.get("map"), label=j.get("label"), ortho=bool(s["ortho"]), roll_seed=int(meta.get("seed", 0)), roll_compile=bool(meta.get("compile")), roll_ckpt=meta.get("ckpt")) def proj_dst(meta, f: int, P3) -> np.ndarray: return GEO.src_to_dst(GEO.proj(meta["world_to_clip"][f].reshape(4, 4), np.asarray(P3, float).reshape(-1, 3))) class Base: """一条已有 rollout 的地图世界(与 maps//ids.npz 逐位一致)+ 编辑要用的缓存。""" def __init__(self, name: str, dev: str = "cuda", check: bool = True): t0 = time.time() self.name, self.dev, self.info = name, dev, base_info(name) self.src = PM.load_source(self.info["clip_id"]) self.meta = self.src["meta"] w = PM.World(self.src, self.info["seed"]) PM.THEME_FN[self.info["theme"]](w) TE.g2(w) self.cache = [PM.char_rays(self.meta, f) for f in range(F)] PM.control_occlusion(w, dev, self.cache) self.w, self.z0 = w, w.z0 self.prims = w.prims() self.prim_obj = np.array([p["obj"] for p in self.prims] + [-1], np.int64) self.layers0 = list(w.ground.layers) self.ids0 = np.load(self.info["ids"])["ids"] self._dist = {} sf = TE.screen_frame(w, 0) self.yaw_screen = math.atan2(sf["r"][1], sf["r"][0]) self.R = Renderer(self) self.check = None if check: bad = {f: int((self.R.frame(f, self.base_state(f)) != self.ids0[f]).sum()) for f in (0, 40, 80)} self.check = bad if any(bad.values()): raise RuntimeError(f"{name}:重建的世界与 maps ids.npz 不一致(不同像素数 {bad})") self.build_sec = round(time.time() - t0, 1) def base_state(self, f: int) -> dict: return dict(pk=(), prims=self.prims, gk=-1, layers=self.layers0, swap=None, caps=self.meta["capsules"][f]) def player(self, f: int) -> np.ndarray: return np.asarray(self.meta["actor_pos"][f, 0], float) def boss(self, f: int) -> np.ndarray: return np.asarray(self.meta["actor_pos"][f, 1], float) def sf(self, f: int) -> dict: return TE.screen_frame(self.w, f) def scale(self, f: int) -> float: return float(np.clip(self.sf(f)["vw"] / 1500.0, 0.6, 1.6)) def dist_after(self, f0: int, roles=(0, 1)) -> np.ndarray: """帧 f0..80 的角色胶囊 XY 足迹(含半径)的距离场(cm,World 网格);roles = (0,) 只算玩家。""" key = (f0, tuple(roles)) if key not in self._dist: w = self.w ch = np.zeros((w.ny, w.nx), np.uint8) caps = self.meta["capsules"][f0:, list(roles)].reshape(-1, 7) caps = caps[np.isfinite(caps).all(1)] for a in caps: pa, pb, r = w.px(a[:2]), w.px(a[3:5]), max(1, int(round(a[6] / GRID_CM))) cv2.line(ch, tuple(pa.round().astype(int)), tuple(pb.round().astype(int)), 1, 2 * r + 1) for q in (pa, pb): cv2.circle(ch, tuple(q.round().astype(int)), r, 1, -1) self._dist[key] = cv2.distanceTransform((ch == 0).astype(np.uint8), cv2.DIST_L2, 5) * GRID_CM return self._dist[key] def free_after(self, fp, f0: int, margin: float = CLEAR_CM, roles=(0, 1)) -> bool: a = self.w._raster(fp) if a is None: return False rs, cs, m = a return not ((self.dist_after(f0, roles)[rs, cs] <= margin) & m).any() def overlaps(self, fp, gap: float = 40.0) -> bool: b = self.w._raster(fp, gap) return b is not None and bool((self.w.occ[b[0], b[1]] & b[2]).any()) def vis_frac(self, P3, frames, margin: float = 30.0) -> float: n = 0 for f in frames: d = proj_dst(self.meta, f, P3) n += bool(((d[:, 0] >= margin) & (d[:, 0] < W - margin) & (d[:, 1] >= margin) & (d[:, 1] < H - margin)).all()) return n / max(1, len(frames)) def char_occ(self, prims, frames) -> dict: """新图元挡住玩家 / Boss 的像素比例(只算这些图元,逐帧取最大)。""" cs = PM.Caster(prims, self.dev) out = {"player_occ_max": 0.0, "boss_occ_max": 0.0} for f in frames: ys, xs, raw, tcap, ro, rd = self.cache[f] if not len(ys): continue t, _ = cs.cast(ro, rd) occ = t < tcap role = GM.collapse_parts(raw) for cid, key in ((GEO.PLAYER_ID, "player_occ_max"), (GEO.BOSS_ID, "boss_occ_max")): sel = role == cid if sel.sum() >= 50: out[key] = max(out[key], float((occ & sel).sum() / sel.sum())) return {k: round(v, 4) for k, v in out.items()} class Renderer: def __init__(self, B: Base): self.B, self._cs, self._g = B, {}, {} def caster(self, key, prims): if key not in self._cs: if len(self._cs) > 6: self._cs.pop(next(iter(self._cs))) self._cs[key] = (PM.Caster(prims, self.B.dev), np.array([p["cls"] for p in prims] or [SKY], np.uint8)) return self._cs[key] def ground(self, key, layers): if key not in self._g: if len(self._g) > 6: self._g.pop(next(iter(self._g))) self._g[key] = TE.Ground2(layers) return self._g[key] def frame(self, f: int, st: dict, want: bool = False): B = self.B Mf, Vf = B.meta["world_to_clip"][f], B.meta["world_to_view"][f] ro, rd = CAP.dst_pixel_rays(Mf, Vf, _XS, _YS) cs, cls_of = self.caster(st["pk"], st["prims"]) tp, k = cs.cast(ro, rd) with np.errstate(divide="ignore", invalid="ignore"): tg = (B.z0 - ro[:, 2]) / rd[:, 2] tg = np.where(np.isfinite(tg) & (tg > 0), tg, np.inf) fin = np.isfinite(tg) gcls = self.ground(st["gk"], st["layers"]).classify(ro[:, :2] + rd[:, :2] * np.where(fin, tg, 0)[:, None], B.dev) pcls = np.where(k >= 0, cls_of[np.maximum(k, 0)], SKY).astype(np.uint8) on_p = tp < tg static = np.where(on_p, pcls, np.where(fin, gcls, SKY)).astype(np.uint8) sw = st.get("swap") if sw: if sw["on"] == "prims": tgt = on_p elif sw["on"] == "ground": tgt = ~on_p & fin else: tgt = np.ones_like(on_p) if math.isfinite(sw["r"]): t = np.minimum(tp, tg) P = ro[:, :2] + rd[:, :2] * np.where(np.isfinite(t), t, 0)[:, None] tgt = tgt & (np.hypot(P[:, 0] - sw["c"][0], P[:, 1] - sw["c"][1]) < sw["r"]) src = static.copy() for a, b in sw["map"].items(): static[(src == a) & tgt] = b caps = CAP.capsules_from_array(st["caps"]) ids = CAP.render_capsules(static.reshape(H, W), Mf, Vf, caps, static_depth=tp.reshape(H, W)) if want: return ids, dict(k=k.reshape(H, W), on_p=on_p.reshape(H, W), static=static.reshape(H, W)) return ids # ---------------------------------------------------------------------------- # 编辑 # ---------------------------------------------------------------------------- class Edit: def __init__(self, B: Base, kind: str, k: int, params: dict | None = None, seed: int = 0): self.B, self.kind, self.k, self.params = B, kind, int(k), dict(params or {}) self.rng = np.random.default_rng(seed) self.adds, self.removes, self.swap, self.gsteps = [], {}, None, [] self.caps_fn, self.caps_t0 = None, None self.info: dict = {} self.label, self.t_end = "", int(k) def first_frame(self) -> int: ts = [a["t0"] for a in self.adds] + [r["t0"] for r in self.removes.values()] + [t for t, _ in self.gsteps] ts += [self.swap["t0"]] if self.swap else [] ts += [self.caps_t0] if self.caps_fn is not None else [] return int(min(ts)) if ts else F def state(self, f: int) -> dict: B = self.B prims, key = [], [] for p in B.prims: r = self.removes.get(p["obj"]) if r is not None and f >= r["t0"]: if r["mode"] == "pop" or f >= r["t1"]: continue a = smooth01((f - r["t0"] + 1) / (r["t1"] - r["t0"] + 1)) prims.append(p_move(p, (0, 0, -a * (r["H"] + 40)))) continue prims.append(p) for o, r in sorted(self.removes.items()): if f >= r["t0"]: key.append(("r", o, f if (r["mode"] == "sink" and f < r["t1"]) else -1)) for i, ad in enumerate(self.adds): if f < ad["t0"]: continue a = 1.0 if (ad["mode"] == "pop" or f >= ad["t1"]) else smooth01((f - ad["t0"] + 1) / (ad["t1"] - ad["t0"] + 1)) if ad["mode"] == "drop" and f < ad["t1"]: # 从天上掉下来:自由落体 z = h0·(1 − u²) a = ((f - ad["t0"] + 1) / (ad["t1"] - ad["t0"] + 1)) ** 2 if a >= 1: prims += ad["prims"] elif ad["mode"] == "drop": prims += [p_move(p, (0, 0, (1 - a) * ad.get("drop_h", 900.0))) for p in ad["prims"]] elif ad["mode"] == "rise": prims += [p_move(p, (0, 0, -(1 - a) * (ad["H"] + 40))) for p in ad["prims"]] else: prims += [p_scale(p, ad["C"], max(a, 0.06)) for p in ad["prims"]] key.append(("a", i, round(a, 4))) layers, gk = B.layers0, -1 for i, (t, L) in enumerate(self.gsteps): if t <= f: layers, gk = B.layers0 + L, i sw = None if self.swap and f >= self.swap["t0"]: s = self.swap a = 1.0 if (s["t1"] <= s["t0"] or f >= s["t1"]) else (f - s["t0"] + 1) / (s["t1"] - s["t0"] + 1) sw = dict(s, r=(math.inf if (a >= 1 or not s.get("rmax")) else a * s["rmax"])) caps = B.meta["capsules"][f] if self.caps_fn is not None and f >= self.caps_t0: caps = self.caps_fn(f, caps) return dict(pk=tuple(key), prims=prims, gk=gk, layers=layers, swap=sw, caps=caps) def render(self) -> np.ndarray: B = self.B B.R = Renderer(B) # 缓存的 key 只在一个编辑内有意义:每个编辑换新的渲染器 ids = B.ids0.copy() for f in range(self.first_frame(), F): ids[f] = B.R.frame(f, self.state(f)) return ids # ---- 位置搜索 ---- def find_spot(B: Base, k: int, make, rng, frames, dmin=90.0, dmax=340.0, need_vis=0.85, occ_gap=40.0, margin=80.0, max_try=80, center="player"): """帧 k 画面里离玩家 dmin..dmax px 的地面点里,找一个放得下 make(p, rng) 的位置 → (p, prims, fp, 统计)。""" w, meta = B.w, B.meta gx, gy = np.meshgrid(np.arange(48, W - 48, 14.0), np.arange(40, H - 40, 14.0)) sp = np.stack([gx.ravel(), gy.ravel()], 1) g = TE.ground_at(w, sp, f=k) ok = np.isfinite(g).all(1) sp, g = sp[ok], g[ok] ref = proj_dst(meta, k, B.player(k)[None])[0] if center == "player" else np.array([W / 2, H / 2]) d = np.hypot(*(sp - ref).T) dist = B.dist_after(k) c, r = w.px(g).round().astype(int).T inb = (r >= 0) & (r < w.ny) & (c >= 0) & (c < w.nx) cd = np.full(len(g), 0.0) cd[inb] = dist[r[inb], c[inb]] pr0, fp0 = make(np.zeros(2), np.random.default_rng(0)) r_fp = float(np.max(np.hypot(*np.concatenate(fp0).T))) # 足迹外接半径(粗筛用) sel = np.flatnonzero((d >= dmin) & (d <= dmax) & (cd > margin + 0.8 * r_fp)) if not len(sel): return None P3 = np.c_[g[sel], np.full(len(sel), B.z0 + 100)] vis = np.zeros(len(sel)) for f in frames: q = proj_dst(meta, f, P3) vis += (q[:, 0] >= 50) & (q[:, 0] < W - 50) & (q[:, 1] >= 50) & (q[:, 1] < H - 50) vis /= max(1, len(frames)) # 帧 k 上物体投影范围里原来是空地(地面类、非角色)的比例:放在空地上 ⇒ 新物体和原有物体不糊在一起 if not hasattr(B, "_gnd") or B._gnd[0] != k: _, aux = B.R.frame(k, B.base_state(k), want=True) B._gnd = (k, (~aux["on_p"] & (B.ids0[k] < 10)).astype(np.float32)) r_px = max(6, int(r_fp / (B.sf(k)["vw"] / W))) gf = cv2.blur(B._gnd[1], (2 * r_px + 1, 2 * r_px + 1)) spi = sp[sel].round().astype(int) gfrac = gf[spi[:, 1].clip(0, H - 1), spi[:, 0].clip(0, W - 1)] cen = np.hypot((spi[:, 0] - W / 2) / W, (spi[:, 1] - H / 2) / H) score = vis + 0.6 * gfrac - np.abs(d[sel] - 0.5 * (dmin + dmax)) / 900 - 0.4 * cen + rng.uniform(0, 0.05, len(sel)) order = np.argsort(-score) tries = 0 for i in order: if tries >= max_try: break if vis[i] < need_vis: continue p = g[sel[i]] pr, fp = make(p, np.random.default_rng(int(rng.integers(1 << 31)))) if not B.free_after(fp, k, margin): continue if occ_gap is not None and B.overlaps(fp, occ_gap): continue tries += 1 lo, hi = prims_bbox(pr) v = B.vis_frac(np.array([[p[0], p[1], B.z0], [p[0], p[1], hi[2]]]), frames, 20) if v < need_vis: continue oc = B.char_occ(pr, frames) if oc["player_occ_max"] > 0.10 or oc["boss_occ_max"] > 0.35: continue return p, pr, fp, dict(vis=round(v, 3), d_player_px=round(float(d[sel[i]]), 1), ground_frac=round(float(gfrac[i]), 3), **oc) return None def _frames(a: int, b: int = F - 1, step: int = 2) -> list[int]: return list(range(int(a), int(b) + 1, step)) or [int(b)] def default_anim(obj: str) -> str: return "scale" if obj in ("tree", "boulder", "props", "statue") else "rise" # ---- add / grow ---- OBJ_CLS = {"tower": ARCH, "house": ARCH, "wall": ARCH, "statue": ARCH, "pillar": ARCH, "tree": VEG, "boulder": ROCK, "crystal": ROCK, "stone": ROCK, "props": PROP} def auto_obj(B: Base, k: int, rng, grow: bool = False) -> str: """选和画面反差大的物体:帧 k..80 里占比最小的那类(architecture / rock / vegetation)。""" coll = GM.collapse_parts(B.ids0[k::8]) frac = np.bincount(coll.ravel(), minlength=12)[:7] / coll.size c = min((ARCH, ROCK, VEG), key=lambda c: frac[c] + rng.uniform(0, 0.02)) pool = {ARCH: ["tower", "house", "statue"] if not grow else ["tower", "wall"], ROCK: ["boulder", "crystal"] if not grow else ["crystal", "stone"], VEG: ["tree"]}[c] return str(rng.choice(pool)) def prep_add(E: Edit, grow: bool = False) -> None: B, k, P = E.B, E.k, E.params obj = P.get("obj") or auto_obj(B, k, E.rng, grow) anim = P.get("anim") or (default_anim(obj) if grow else "pop") dur = int(P.get("dur", 16 if grow else 0)) if anim != "pop" else 0 S = B.scale(k) * float(P.get("size", 1.0)) frames = _frames(k) res = None for dmax, gap, nv in ((340.0, 40.0, 0.85), (420.0, 40.0, 0.7), (420.0, None, 0.7), (480.0, None, 0.6)): # 先要求帧 k..80 的 85 % 都在画面里;放不下就放宽距离 / 可见率,最后允许压住已有物体 res = find_spot(B, k, lambda p, r: make_obj(B, obj, p, S, r), E.rng, frames, dmax=dmax, occ_gap=gap, need_vis=float(P.get("need_vis", nv))) if res is not None: res[3]["overlap_ok"] = gap is None break if res is None: raise EditFail(f"{obj}:帧 {k} 附近找不到净空且一直在画面里的位置") p, pr, fp, st = res lo, hi = prims_bbox(pr) if anim == "drop" and not dur: dur = int(P.get("dur", 8)) E.adds.append(dict(prims=pr, t0=k, t1=k + dur, mode=anim, H=float(hi[2] - B.z0), C=np.r_[p, B.z0], name=obj, drop_h=float(P.get("drop_h", 900.0)) * B.scale(k))) E.info.update(obj=obj, anim=anim, dur=dur, pos=[round(float(x), 1) for x in p], size_scale=round(S, 3), height_cm=round(float(hi[2] - B.z0), 1), **st) E.t_end = k + dur if anim == "drop": E.label = f"{OBJ_EN[obj]} {'Drop' if obj == 'props' else 'Drops'} In @ {k / FPS:.1f} s" elif grow: E.label = f"{'Growing' if anim == 'scale' else 'Rising'} {OBJ_EN[obj]} {k / FPS:.1f}–{(k + dur) / FPS:.1f} s" else: E.label = f"+ {OBJ_EN[obj]} @ {k / FPS:.1f} s" # ---- delete ---- def prep_delete(E: Edit) -> None: B, k, P = E.B, E.k, E.params mode = P.get("mode", "pop") frames = [k, (k + F - 1) // 2, F - 1] n_obj = len(B.w.objs) C, CLS = [], np.zeros((n_obj, 7)) for f in frames: _, aux = B.R.frame(f, B.base_state(f), want=True) on = aux["on_p"] objs = B.prim_obj[aux["k"][on]] C.append(np.bincount(objs, minlength=n_obj)[:n_obj]) np.add.at(CLS, (objs, aux["static"][on]), 1) C = np.stack(C) cls_of = CLS.argmax(1) if mode == "class": tot = np.zeros(7) big = C.max(0) < 0.3 * H * W for c in (ARCH, ROCK, VEG, PROP): tot[c] = C.sum(0)[(cls_of == c) & big].sum() cls = CLS_SHORT[P["cls"]] if P.get("cls") else int(tot.argmax()) objs = [int(o) for o in np.flatnonzero((cls_of == cls) & (C.max(0) >= 150) & (C.max(0) < 0.3 * H * W))] if not objs or tot[cls] < 6000: raise EditFail("画面里没有够多的同类物体") for o in objs: E.removes[o] = dict(t0=k, t1=k, mode="pop", H=0.0) E.info.update(mode=mode, cls=CLS_EN[cls], n_objs=len(objs), px_frames=[int(C[:, objs].sum(1)[i]) for i in range(3)]) E.label = f"− All {CLS_EN[cls]} @ {k / FPS:.1f} s" return minc = C.min(0) ok = (minc >= float(P.get("min_px", 1200))) & (C.max(0) < 0.3 * H * W) if not ok.any(): # 退一档:帧 k / 中间可见就行(帧 80 可能已出画) minc = C[:2].min(0) ok = (minc >= float(P.get("min_px", 1200)) * 1.5) & (C.max(0) < 0.3 * H * W) if not ok.any(): raise EditFail(f"帧 {frames} 都看得见(≥ {P.get('min_px', 1500)} px)的物体没有") o = int(np.argmax(np.where(ok, minc, -1))) dur = int(P.get("dur", 14)) if mode == "sink" else 0 hi = prims_bbox(B.w.objs[o]["prims"])[1] E.removes[o] = dict(t0=k, t1=k + dur, mode=mode, H=float(hi[2] - B.z0)) nm = B.w.objs[o]["name"] E.info.update(mode=mode, obj=o, obj_name=nm, cls=CLS_EN[int(cls_of[o])], dur=dur, px_frames=C[:, o].tolist(), height_cm=round(float(hi[2] - B.z0), 1)) E.t_end = k + dur pretty = nm.replace("_", " ").title() if nm else CLS_EN[int(cls_of[o])] E.label = (f"Sinking {pretty} {k / FPS:.1f}–{(k + dur) / FPS:.1f} s" if mode == "sink" else f"− {pretty} @ {k / FPS:.1f} s") # ---- swap ---- def prep_swap(E: Edit) -> None: B, k, P = E.B, E.k, E.params coll = GM.collapse_parts(B.ids0[k:]) frac = np.bincount(coll.ravel(), minlength=12)[:7] / coll.size pair = P.get("pair") if not pair: cand = [(frac[a], n) for n, (a, b, on) in PAIRS.items() if frac[a] >= 0.08 and n not in ("pave2veg", "prop2veg")] if not cand: raise EditFail("没有占比 ≥ 8 % 的可换类") cand.sort(reverse=True) pair = cand[0][1] a, b, on = PAIRS[pair] if frac[a] < 0.03: raise EditFail(f"{pair}:类 {a} 只占 {frac[a]:.3f}") wave = int(P.get("wave", 0)) c = B.player(k)[:2] rmax = None if wave: pts = np.concatenate([PM.frame_ground_poly(B.meta["world_to_clip"][f], B.meta["world_to_view"][f], B.z0) for f in _frames(k, step=8)]) rmax = float(np.hypot(*(pts - c).T).max()) * 1.05 E.swap = dict(map={a: b}, t0=k, t1=k + wave, c=c, rmax=rmax, on=on) E.info.update(pair=pair, src=CLS_EN[a], dst=CLS_EN[b], on=on, wave=wave, center=[round(float(x), 1) for x in c], rmax_cm=None if rmax is None else round(rmax, 1), src_frac=round(float(frac[a]), 4)) E.t_end = k + wave E.label = f"{CLS_EN[a]} → {CLS_EN[b]} @ {k / FPS:.1f} s" # ---- paint ---- def _smooth_path(P, sigma=2.0): x = np.arange(-3 * int(math.ceil(sigma)), 3 * int(math.ceil(sigma)) + 1) kk = np.exp(-0.5 * (x / sigma) ** 2) kk /= kk.sum() Pp = np.pad(P, ((len(x) // 2,) * 2, (0, 0)), mode="edge") return np.stack([np.convolve(Pp[:, i], kk, mode="valid") for i in range(P.shape[1])], 1) def prep_trail3d(E: Edit) -> None: """paint 的 mode=trail3d:玩家身后一路冒出小物体(bush 花丛 / crystal 水晶 / stone 石块 / pillar 小柱),落后玩家 lag 帧、 间距 ≈ 0.07 视野宽,各自 rise 帧长出来(地面图层的「画路」模型基本不画,见报告;立体的小物体它会画)。""" B, k, P = E.B, E.k, E.params obj = P.get("obj", "bush") lag, rise = int(P.get("lag", 5)), int(P.get("rise", 4)) Pp = _smooth_path(np.asarray(B.meta["actor_pos"][:, 0, :2], float), 2.0) vw = B.sf(k)["vw"] L = float(np.linalg.norm(np.diff(Pp[k:], axis=0), axis=1).sum()) if L < max(300.0, 0.3 * vw): raise EditFail(f"帧 {k} 之后玩家只走了 {L:.0f} cm") S = B.scale(k) * float(P.get("size", 1.0)) step = float(P.get("spacing", 0.07)) * vw last, el, side = None, [], 1 for f in range(k, F - lag): q = Pp[f] if last is not None and np.linalg.norm(q - last) < step: continue t = f + lag u = Pp[min(F - 1, f + 2)] - Pp[max(0, f - 2)] nrm = np.array([-u[1], u[0]]) / max(np.linalg.norm(u), 1e-6) rng = np.random.default_rng(int(E.rng.integers(1 << 31))) for off in (0.0, 0.25 * step * side, -0.25 * step * side): p = q + off * nrm if obj == "bush": r = np.array([rng.uniform(40, 60), 0, rng.uniform(30, 45)]) * S r[1] = r[0] * rng.uniform(0.75, 1.0) pr, fp = [ell(np.r_[p, B.z0 + 0.2 * r[2]], r, rng.uniform(0, np.pi), VEG)], [_ngon(p, r[0] + 5)] elif obj == "crystal": B.w.rng = rng pr, fp = TE.crystal_cluster(B.w, p, 170 * S, ROCK) elif obj == "stone": rx = rng.uniform(40, 60) * S pr, fp = [ell(np.r_[p, B.z0], [rx, rx * 0.8, rx * 0.6], rng.uniform(0, np.pi), ROCK)], [_ngon(p, rx + 5)] else: pr, fp = TE.column(B.w, p, 18 * S, 140 * S, ARCH) if B.free_after(fp, t, 10.0, roles=(0,)): # 只躲玩家(Boss 常沿同一条路追过来,踩过花丛无妨) el.append((t, p, pr)) last = q side = -side break if len(el) < 6: raise EditFail(f"路上只放得下 {len(el)} 个 {obj}") for t, p, pr in el: hi = prims_bbox(pr)[1] E.adds.append(dict(prims=pr, t0=t, t1=t + rise, mode="scale" if obj in ("bush", "stone") else "rise", H=float(hi[2] - B.z0), C=np.r_[p, B.z0], name=obj)) oc = B.char_occ([q for e in el for q in e[2]], _frames(k)) E.t_end = F - 1 E.info.update(obj=obj, mode="trail3d", n=len(el), lag=lag, rise=rise, spacing_cm=round(step, 1), path_cm=round(L, 1), **oc) E.label = {"bush": "Flowers Bloom", "crystal": "Crystals Grow", "stone": "Stones Appear", "pillar": "Pillars Rise"}.get(obj, obj) + f" in the Hero's Footsteps from {k / FPS:.1f} s" def prep_paint(E: Edit) -> None: B, k, P = E.B, E.k, E.params if P.get("mode") == "trail3d": return prep_trail3d(E) lead = int(P.get("lead", 0)) Pp = np.asarray(B.meta["actor_pos"][:, 0, :2], float) if not np.isfinite(Pp).all(): raise EditFail("玩家轨迹有 NaN") Pp = _smooth_path(Pp, 2.0) L = float(np.linalg.norm(np.diff(Pp[k:], axis=0), axis=1).sum()) vw = B.sf(k)["vw"] if L < max(250.0, 0.25 * vw): raise EditFail(f"帧 {k} 之后玩家只走了 {L:.0f} cm") width = float(P.get("width") or np.clip(0.11 * vw, 140, 420)) under = collections.Counter(TE.gcls(B.w, Pp[f]) for f in range(k, F)) if P.get("cls"): cls = CLS_SHORT[P["cls"]] else: cls = VEG if under.most_common(1)[0][0] == PAVING else PAVING # 铺装上画草 / 花径,土地上画石板路 for f in range(k, F): e = min(F - 1, f + lead) pts = [Pp[k]] for q in Pp[k + 1:e + 1]: if np.linalg.norm(q - pts[-1]) >= 8: pts.append(q) if len(pts) < 2: pts.append(pts[-1] + 1.0) pts = np.asarray(pts) E.gsteps.append((f, [("seg", cls, np.concatenate([pts[:-1], pts[1:]], 1), np.full(len(pts) - 1, width / 2))])) E.info.update(cls=CLS_EN[cls], width_cm=round(width, 1), lead=lead, path_cm=round(L, 1), under=CLS_EN[under.most_common(1)[0][0]]) E.t_end = F - 1 E.label = f"Paint {CLS_EN[cls]} Trail from {k / FPS:.1f} s" # ---- write ---- def text_mask_full(text: str, cx: float, cy: float, bw: float, bh: float, k: int = 2, bold: float = 0.0) -> np.ndarray: """帧屏幕空间(W·k × H·k)里,以 (cx, cy)(1× px)为中心、bw × bh 框内写 text(或 SHAPES 的符号)→ uint8 掩码。""" from PIL import Image, ImageDraw, ImageFont if text in SHAPES: S = min(bw * 0.55, bh * 0.5) * k return TE._shape_img(text, k, cx * k, cy * k, S, S * 0.2) cjk = any(ord(ch) >= 0x2E80 for ch in text) path = FONT_CJK if cjk else FONT_LAT img = Image.new("L", (W * k, H * k), 0) d = ImageDraw.Draw(img) lo, hi = 8, 600 while hi - lo > 2: mid = (lo + hi) // 2 fnt = ImageFont.truetype(path, mid) sw = max(2, int(mid / ((16 if cjk else 22) / (1 + bold)))) x0, y0, x1, y1 = d.textbbox((0, 0), text, font=fnt, stroke_width=sw) if x1 - x0 <= bw * k and y1 - y0 <= bh * k: lo = mid else: hi = mid fnt = ImageFont.truetype(path, lo) sw = max(2, int(lo / ((16 if cjk else 22) / (1 + bold)))) x0, y0, x1, y1 = d.textbbox((0, 0), text, font=fnt, stroke_width=sw) d.text((cx * k - (x0 + x1) / 2, cy * k - (y0 + y1) / 2), text, font=fnt, fill=255, stroke_width=sw, stroke_fill=255) return np.asarray(img, np.uint8).copy() def reveal_times(mask: np.ndarray, t0: float, dur: float, gap: float = 1.5) -> np.ndarray: """1× 屏幕掩码 → 每像素被「写到」的时刻(帧,float;掩码外 inf):连通笔画按从左到右、再从上到下排序,每个笔画从它最左上的 像素起按测地距离(8 邻域 BFS)匀速揭开,笔画用时 ∝ 它的测地长度,笔画之间留 gap 帧。""" n, lab = cv2.connectedComponents(mask.astype(np.uint8), connectivity=8) T = np.full(mask.shape, np.inf) comps = [] for i in range(1, n): ys, xs = np.nonzero(lab == i) if len(ys) < 12: continue comps.append((xs.mean(), ys.mean(), i, ys, xs)) if not comps: return T # 中文:先按字(x 分 bin)再按上下;拉丁字母 / 符号:从左到右 comps.sort(key=lambda c: (round(c[0] / (W * 0.08)), c[1])) geo, lens = [], [] for _, _, i, ys, xs in comps: s = int(np.argmin(xs + ys)) D = np.full(mask.shape, -1, np.int32) q = collections.deque([(ys[s], xs[s])]) D[ys[s], xs[s]] = 0 m = lab == i while q: y, x = q.popleft() dv = D[y, x] + 1 for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)): yy, xx = y + dy, x + dx if 0 <= yy < mask.shape[0] and 0 <= xx < mask.shape[1] and m[yy, xx] and D[yy, xx] < 0: D[yy, xx] = dv q.append((yy, xx)) geo.append(D) lens.append(max(1, D.max())) total = dur - gap * (len(comps) - 1) per = np.asarray(lens, float) / sum(lens) * max(total, dur * 0.5) t = t0 for (_, _, i, ys, xs), D, L, pd in zip(comps, geo, lens, per): dd = D[ys, xs] ok = dd >= 0 T[ys[ok], xs[ok]] = t + dd[ok] / L * pd t += pd + gap return T def pick_box(B: Base, k: int, fw: int, frames, sizes=((0.62, 0.42), (0.5, 0.36), (0.4, 0.3)), prefer=None): """帧 fw 屏幕上选一个写字框:四角的地面点在 frames 里一直在画面里(vis 高)、框里压角色路径(帧 ≥ k)的地面点少。""" w = B.w dist = B.dist_after(k) _, aux = B.R.frame(fw, B.base_state(fw), want=True) onp = aux["on_p"] | (B.ids0[fw] >= 10) # 被物体 / 角色盖住的像素(地面字在那里看不见) best = None for fx, fy in sizes: bw, bh = W * fx, H * fy for cy in np.linspace(bh / 2 + 16, H - bh / 2 - 16, 5): for cx in np.linspace(bw / 2 + 16, W - bw / 2 - 16, 5): cor = np.array([[cx - bw / 2, cy - bh / 2], [cx + bw / 2, cy - bh / 2], [cx + bw / 2, cy + bh / 2], [cx - bw / 2, cy + bh / 2]]) g = TE.ground_at(w, cor, fw) if not np.isfinite(g).all(): continue v = B.vis_frac(np.c_[g, np.full(4, B.z0)], frames, 6) ix, iy = np.meshgrid(np.linspace(cx - bw / 2, cx + bw / 2, 9), np.linspace(cy - bh / 2, cy + bh / 2, 7)) gi = TE.ground_at(w, np.stack([ix.ravel(), iy.ravel()], 1), fw) c, r = w.px(gi).round().astype(int).T inb = np.isfinite(gi).all(1) & (r >= 0) & (r < w.ny) & (c >= 0) & (c < w.nx) ch = np.mean(dist[r[inb], c[inb]] < 60) if inb.any() else 1.0 cov = float(onp[int(cy - bh / 2):int(cy + bh / 2), int(cx - bw / 2):int(cx + bw / 2)].mean()) sc = v - 1.5 * ch - 1.2 * cov + 0.15 * fx if prefer is not None and inb.any(): # 地面字写在 prefer 类(如 paving)上更显眼 sc += 0.6 * float(np.mean([TE.gcls(w, q) == prefer for q in gi[inb]])) if best is None or sc > best[0]: best = (sc, cx, cy, bw, bh, v, ch, cov) if best is not None and best[5] >= 0.9 and best[6] < 0.08 and best[7] < 0.15: break return best def prep_write(E: Edit) -> None: B, k, P = E.B, E.k, E.params text = P.get("text", "马良") mode = P.get("mode", "paint") dur = int(P.get("dur", 32)) fw = min(F - 1, k + dur) frames = _frames(k, step=4) big = float(P.get("big", 1.0)) sizes = tuple((min(0.92, fx * big), min(0.8, fy * big)) for fx, fy in ((0.62, 0.42), (0.5, 0.36), (0.4, 0.3))) bx = pick_box(B, k, fw, frames, sizes, prefer=PAVING if (P.get("cls") == "veg" and mode == "paint") else None) if bx is None: raise EditFail("没有合适的写字框") sc, cx, cy, bw, bh, v, ch, cov = bx if v < (0.5 if mode == "raise" else 0.6): raise EditFail(f"写字框在帧 {k}..80 的可见率只有 {v:.2f}") m2 = text_mask_full(text, cx, cy, bw, bh, 2, float(P.get("bold", 0.0))) m1 = cv2.resize(m2, (W, H), interpolation=cv2.INTER_AREA) > 100 T = reveal_times(m1, k, dur) w = B.w g = TE.ground_at(w, np.array([[cx - bw / 2, cy - bh / 2], [cx + bw / 2, cy - bh / 2], [cx + bw / 2, cy + bh / 2], [cx - bw / 2, cy + bh / 2]]), fw) ux, uy = np.nonzero(m1)[1], np.nonzero(m1)[0] gi = TE.ground_at(w, np.stack([ux, uy], 1).astype(float)[::7], fw) under = collections.Counter(TE.gcls(w, q) for q in gi[np.isfinite(gi).all(1)]) base_under = under.most_common(1)[0][0] if under else TERRAIN if mode == "paint": cls = CLS_SHORT[P["cls"]] if P.get("cls") else (TERRAIN if base_under == PAVING else PAVING) res = float(np.clip(B.sf(fw)["vw"] / W * 1.0, 1.2, 4.0)) lo, hi = g.min(0) - 100, g.max(0) + 100 nx, ny = int(math.ceil((hi[0] - lo[0]) / res)), int(math.ceil((hi[1] - lo[1]) / res)) yy, xx = np.mgrid[0:ny, 0:nx] XY = np.stack([lo[0] + (xx.ravel() + 0.5) * res, lo[1] + (yy.ravel() + 0.5) * res], 1) d = TE.to_screen(w, XY, fw) mx = ((d[:, 0] + 0.5) * 2 - 0.5).reshape(ny, nx).astype(np.float32) my = ((d[:, 1] + 0.5) * 2 - 0.5).reshape(ny, nx).astype(np.float32) inside = cv2.remap(m2, mx, my, cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0) > 127 Tn = cv2.remap(np.where(np.isfinite(T), T, 1e9).astype(np.float32), d[:, 0].reshape(ny, nx).astype(np.float32), d[:, 1].reshape(ny, nx).astype(np.float32), cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=1e9) # 掩码边缘(线性插值出来的)上没有揭开时刻的像素:取 5×5 邻域最小值 Tn = np.minimum(Tn, cv2.erode(Tn, np.ones((5, 5), np.uint8))) Tc = np.where(inside, Tn, np.inf) for f in range(k, fw + 1): mf = (Tc <= f + 0.5).astype(np.uint8) if not mf.any(): continue din = cv2.distanceTransform(mf, cv2.DIST_L2, 5) dout = cv2.distanceTransform(1 - mf, cv2.DIST_L2, 5) sdf = (np.where(mf > 0, -(din - 0.5), dout - 0.5) * res).astype(np.float32) sdf = cv2.GaussianBlur(sdf, (0, 0), 1.0) E.gsteps.append((f, [("sdf", int(cls), float(lo[0]), float(lo[1]), res, sdf)])) E.info.update(cls=CLS_EN[cls]) else: cls = CLS_SHORT[P.get("cls", "veg")] hgt = float(P.get("h", 120)) * B.scale(fw) cell = int(P.get("cell", 8)) gsm = cv2.resize(m1.astype(np.uint8) * 255, (W // cell, H // cell), interpolation=cv2.INTER_AREA) > 90 Tg = cv2.resize(np.where(np.isfinite(T), T, 1e9).astype(np.float32), (W // cell, H // cell), interpolation=cv2.INTER_NEAREST) Tmin = -cv2.dilate(-np.where(np.isfinite(T), T, 1e9).astype(np.float32), np.ones((cell, cell), np.uint8)) nb = 0 for i0, i1, j0, j1 in TE.rects_from_mask(gsm, int(P.get("max_run", 3))): q = TE.ground_at(w, [[j0 * cell, i0 * cell], [j1 * cell, i0 * cell], [j1 * cell, i1 * cell], [j0 * cell, i1 * cell]], fw) if not np.isfinite(q).all() or not B.free_after([q], k, 70.0): continue shrink = float(P.get("shrink", 1.0)) # < 1 ⇒ 块之间留缝(点阵字,更好认) if shrink < 1: q = q.mean(0) + (q - q.mean(0)) * shrink tt = float(min(Tmin[i0 * cell:i1 * cell, j0 * cell:j1 * cell].min(), Tg[i0:i1, j0:j1].min())) if tt > 1e8: continue pr = [prism(q, B.z0 - 20, B.z0 + hgt, cls)] t0 = int(round(tt)) E.adds.append(dict(prims=pr, t0=t0, t1=t0 + 6, mode="rise", H=hgt, C=np.r_[q.mean(0), B.z0], name="glyph")) nb += 1 if nb < 6: raise EditFail(f"立体字只放下 {nb} 块") occ = B.char_occ([p for a in E.adds for p in a["prims"]], frames) E.info.update(cls=CLS_EN[cls], n_blocks=nb, height_cm=round(hgt, 1), **occ) E.info.update(text=text, mode=mode, dur=dur, frame_layout=fw, box_px=[round(cx, 1), round(cy, 1), round(bw, 1), round(bh, 1)], box_vis=round(v, 3), box_char_frac=round(float(ch), 3), box_covered=round(cov, 3), under=CLS_EN[base_under]) E.t_end = fw what = text if text not in SHAPES else text.title() E.label = f"Write “{what}” {k / FPS:.1f}–{fw / FPS:.1f} s" if mode == "paint" else f"Raise “{what}” {k / FPS:.1f}–{fw / FPS:.1f} s" # ---- spawn ---- def prep_avenue(E: Edit) -> None: """spawn 的 mode=avenue:玩家走到哪,路两边就逐个冒出 obj(每 dt 帧一个,左右交替,放在玩家当前位置前方 ahead 帧处的两侧)。""" B, k, P = E.B, E.k, E.params obj = P.get("obj", "tree") dt, rise = int(P.get("dt", 4)), int(P.get("rise", 6)) anim = P.get("anim") or default_anim(obj) S = B.scale(k) * float(P.get("size", 0.7)) Pp = _smooth_path(np.asarray(B.meta["actor_pos"][:, 0, :2], float), 3.0) L = float(np.linalg.norm(np.diff(Pp[k:], axis=0), axis=1).sum()) vw = B.sf(k)["vw"] if L < max(300.0, 0.3 * vw): raise EditFail(f"帧 {k} 之后玩家只走了 {L:.0f} cm") ahead = int(P.get("ahead", 8)) side_d = float(P.get("side", 0.16)) * vw el, side = [], 1 for t in range(k, F - rise // 2, dt): f2 = min(F - 1, t + ahead) u = Pp[min(F - 1, f2 + 3)] - Pp[max(0, f2 - 3)] if np.linalg.norm(u) < 20: continue u = u / np.linalg.norm(u) nrm = np.array([-u[1], u[0]]) ok = False for sd in (side, -side): for dd in (1.0, 1.3, 0.8, 1.6): p = Pp[f2] + sd * dd * side_d * nrm pr, fp = make_obj(B, obj, p, S, np.random.default_rng(int(E.rng.integers(1 << 31))), yaw=math.atan2(u[1], u[0])) if not B.free_after(fp, t, 50.0): continue if any(np.linalg.norm(p - e[1]) < 0.1 * vw for e in el): continue if B.vis_frac(np.array([[p[0], p[1], B.z0 + 50]]), _frames(t + rise, min(F - 1, t + rise + 16), 4), 15) < 0.75: continue el.append((t, p, pr, fp)) ok = True break if ok: break side = -side if len(el) < 4: raise EditFail(f"路两边只放得下 {len(el)} 个 {obj}") oc = B.char_occ([q for e in el for q in e[2]], _frames(k)) for t, p, pr, fp in el: hi = prims_bbox(pr)[1] E.adds.append(dict(prims=pr, t0=t, t1=t + rise, mode=anim, H=float(hi[2] - B.z0), C=np.r_[p, B.z0], name=obj)) E.t_end = el[-1][0] + rise E.info.update(obj=obj, mode="avenue", anim=anim, n=len(el), dt=dt, rise=rise, ahead=ahead, side_cm=round(side_d, 1), path_cm=round(L, 1), size_scale=round(S, 3), **oc) E.label = f"{plural(obj)} Sprout Along the Way {k / FPS:.1f}–{E.t_end / FPS:.1f} s" def prep_spawn(E: Edit) -> None: B, k, P = E.B, E.k, E.params if P.get("mode") == "avenue": return prep_avenue(E) loose = bool(P.get("loose")) obj = P.get("obj", "tree") n, dt, rise = int(P.get("n", 10)), int(P.get("dt", 3)), int(P.get("rise", 6)) anim = P.get("anim") or default_anim(obj) S = B.scale(k) * float(P.get("size", 0.8)) c = np.mean([B.player(f)[:2] for f in range(k, min(F, k + 17))], 0) sf = B.sf(k) frames_v = _frames(k, step=4) a0 = float(E.rng.uniform(0, 2 * np.pi)) base_r = min(sf["vw"], sf["vh"]) el, radii = [], [] for i in range(n): # 每个方向从内到外找第一个放得下、一直在画面里的半径 a = a0 + 2 * np.pi * i / n for Rf in ((0.24, 0.30, 0.36, 0.43, 0.50) + ((0.57, 0.65) if loose else ())): p = c + Rf * base_r * _dir(a) if B.vis_frac(np.array([[p[0], p[1], B.z0 + 50]]), frames_v, 25) < (0.6 if loose else 0.75): continue pr, fp = make_obj(B, obj, p, S, np.random.default_rng(int(E.rng.integers(1 << 31))), yaw=a + np.pi / 2) if not B.free_after(fp, k, 50.0 if loose else 70.0) or (not loose and B.overlaps(fp, 20.0)): continue if any(np.linalg.norm(p - e[1]) < 0.12 * base_r for e in el): continue el.append((a, p, pr, fp)) radii.append(Rf * base_r) break R = float(np.mean(radii)) if radii else 0.0 if len(el) < 5: raise EditFail(f"圈上只放得下 {len(el)} 个 {obj}") frames = _frames(k) allp = [p for e in el for p in e[2]] oc = B.char_occ(allp, frames) while oc["player_occ_max"] > 0.12 and len(el) > 4: # 挡玩家 ⇒ 去掉离玩家路径最近的一个 dists = [min(np.linalg.norm(B.player(f)[:2] - e[1]) for f in frames) for e in el] el.pop(int(np.argmin(dists))) oc = B.char_occ([p for e in el for p in e[2]], frames) for j, (a, p, pr, fp) in enumerate(el): t0 = k + j * dt hi = prims_bbox(pr)[1] E.adds.append(dict(prims=pr, t0=t0, t1=t0 + rise, mode=anim, H=float(hi[2] - B.z0), C=np.r_[p, B.z0], name=obj)) E.t_end = k + (len(el) - 1) * dt + rise vis = np.mean([B.vis_frac(np.array([[e[1][0], e[1][1], B.z0 + 50]]), frames, 10) for e in el]) E.info.update(obj=obj, anim=anim, n=len(el), n_try=n, radius_cm=round(R, 1), center=[round(float(x), 1) for x in c], dt=dt, rise=rise, size_scale=round(S, 3), mean_vis=round(float(vis), 3), **oc) E.label = f"Ring of {plural(obj)} {k / FPS:.1f}–{E.t_end / FPS:.1f} s" # ---- trap ---- def prep_trap(E: Edit) -> None: """在 k、k+8、k−8、k+16 里找第一个能圈住的编辑帧(玩家常贴着 Boss 打,墙圈会被玩家路径切断)。""" k0, err = E.k, None for k in (k0, k0 + 8, k0 - 8, k0 + 16, k0 + 24, k0 - 12): if not 16 <= k <= 60: continue E.k, E.adds = k, [] try: _prep_trap(E) E.info["k_planned"] = k0 return except EditFail as e: err = e E.k = k0 raise err def _prep_trap(E: Edit) -> None: B, k, P = E.B, E.k, E.params bp = np.asarray(B.meta["actor_pos"][k:, 1, :2], float) bp = bp[np.isfinite(bp).all(1)] coll = GM.collapse_parts(B.ids0[k:]) bpx = (coll == GEO.BOSS_ID).sum((1, 2)) if len(bp) < 0.8 * (F - k) or np.median(bpx) < 800: raise EditFail(f"帧 {k} 之后 Boss 不够显眼(像素中位 {np.median(bpx):.0f})") cls = CLS_SHORT[P.get("cls", "arch")] rise = int(P.get("rise", 12)) S = B.scale(k) c = (bp.min(0) + bp.max(0)) / 2 Rneed = float(np.hypot(*(bp - c).T).max()) vw = B.sf(k)["vw"] R = max(Rneed + 220.0, 0.13 * vw) * float(P.get("rscale", 1.0)) if R > 0.55 * vw: raise EditFail(f"Boss 活动范围太大(需要半径 {R:.0f} cm,视野宽 {vw:.0f})") thick, hgt = 55 * S, float(P.get("h", 200)) * S n = max(12, int(round(2 * np.pi * R / (130 * S)))) pieces, kept = [], 0 for i in range(n): a0, a1 = 2 * np.pi * i / n, 2 * np.pi * (i + 1) / n p, q = c + R * _dir(a0), c + R * _dir(a1) m, L = (p + q) / 2, float(np.linalg.norm(q - p)) + 8 yaw = math.atan2(q[1] - p[1], q[0] - p[0]) fp = [_rect(m, L, thick, yaw)] if not B.free_after(fp, k, 35.0): continue pr = [box(m, L, thick, hgt, yaw, B.z0 - 20, cls)] if cls == ARCH: pr.append(box(m, L * 0.45, thick + 8, 40 * S, yaw, B.z0 + hgt - 5, cls)) pieces.append((i, pr)) kept += 1 if kept < float(P.get("min_keep", 0.55)) * n: raise EditFail(f"墙圈只有 {kept}/{n} 段放得下(玩家路径穿过太多)") for i, pr in pieces: t0 = k + int(round((i / n) * min(6, rise))) E.adds.append(dict(prims=pr, t0=t0, t1=t0 + rise, mode="rise", H=hgt, C=np.r_[c, B.z0], name="trap_wall")) frames = _frames(k) oc = B.char_occ([p for a in E.adds for p in a["prims"]], frames) if oc["player_occ_max"] > 0.2: raise EditFail(f"墙挡玩家 {oc['player_occ_max']:.2f}") E.t_end = k + min(6, rise) + rise E.info.update(cls=CLS_EN[cls], radius_cm=round(R, 1), boss_range_cm=round(Rneed, 1), n_pieces=kept, n_ring=n, height_cm=round(hgt, 1), center=[round(float(x), 1) for x in c], rise=rise, **oc) E.label = f"Trap the Boss {k / FPS:.1f}–{E.t_end / FPS:.1f} s" # ---- Boss ---- def prep_boss_del(E: Edit) -> None: B, k = E.B, E.k coll = GM.collapse_parts(B.ids0[k:]) bpx = (coll == GEO.BOSS_ID).sum((1, 2)) if np.median(bpx) < float(E.params.get("min_px", 1000)): raise EditFail(f"帧 {k} 之后 Boss 像素中位只有 {np.median(bpx):.0f}") def fn(f, arr): a = np.array(arr, np.float32, copy=True) a[1] = np.nan return a E.caps_fn, E.caps_t0 = fn, k E.info.update(boss_px_median=int(np.median(bpx))) E.label = f"− Boss @ {k / FPS:.1f} s" def prep_boss_clone(E: Edit) -> None: B, k, P = E.B, E.k, E.params meta = B.meta coll = GM.collapse_parts(B.ids0[k:]) bpx = (coll == GEO.BOSS_ID).sum((1, 2)) if np.median(bpx) < 800: raise EditFail(f"帧 {k} 之后 Boss 像素中位只有 {np.median(bpx):.0f}") caps = np.asarray(meta["capsules"], np.float64) fr = _frames(k) bpos = np.asarray(meta["actor_pos"][:, 1], float) ppos = np.asarray(meta["actor_pos"][:, 0], float) s = np.linspace(0, 1, 5) pts = [] for f in fr: c = caps[f, 1] c = c[np.isfinite(c).all(1)] pts.append((c[:, None, :3] * (1 - s[:, None]) + c[:, None, 3:6] * s[:, None]).reshape(-1, 3)) pts = np.concatenate(pts) rad = np.concatenate([np.repeat(caps[f, 1][np.isfinite(caps[f, 1]).all(1)][:, 6], len(s)) for f in fr]) best = None sep_min = float(P.get("sep", 250.0)) for mag in (300.0, 380.0, 460.0, 560.0, 680.0, 820.0): for ang in np.linspace(0, 2 * np.pi, 24, endpoint=False): v = mag * _dir(ang) cl = bpos[fr, :2] + v if not np.isfinite(cl).all(): continue sep = min(np.hypot(*(cl - ppos[fr, :2]).T).min(), np.hypot(*(cl - bpos[fr, :2]).T).min()) if sep < sep_min: continue q = np.concatenate([proj_dst(meta, f, (bpos[f] + np.r_[v, 0])[None]) for f in fr]) inside = (q[:, 0] >= 50) & (q[:, 0] < W - 50) & (q[:, 1] >= 50) & (q[:, 1] < H - 50) if inside.mean() < 0.9: continue P3 = pts + np.r_[v, 0] cl_d = np.full(len(P3), np.inf) for p in B.prims: cl_d = np.minimum(cl_d, PM.sdf_lower(p, P3)) if (cl_d - rad).min() < 15: continue dc = np.hypot(*(q - [W / 2, H / 2]).T).mean() sc = mag / 100 + dc / 60 if best is None or sc < best[0]: best = (sc, v, float(sep), float(inside.mean()), float((cl_d - rad).min())) if best is not None: break if best is None: raise EditFail("找不到放第二个 Boss 的净空") _, v, sep, vis, clr = best off = np.r_[v, 0.0, v, 0.0, 0.0].astype(np.float32) def fn(f, arr): a = np.asarray(arr, np.float32) return np.concatenate([a, (a[1] + off)[None]], 0) E.caps_fn, E.caps_t0 = fn, k E.info.update(offset_cm=[round(float(x), 1) for x in v], sep_cm=round(sep, 1), vis=round(vis, 3), clearance_cm=round(clr, 1), boss_px_median=int(np.median(bpx))) E.label = f"+ Boss Clone @ {k / FPS:.1f} s" PREP = {"add": prep_add, "grow": lambda E: prep_add(E, grow=True), "delete": prep_delete, "swap": prep_swap, "paint": prep_paint, "write": prep_write, "spawn": prep_spawn, "trap": prep_trap, "boss_del": prep_boss_del, "boss_clone": prep_boss_clone} def variant_of(edit: str, params: dict) -> str: p = params or {} if edit == "add" and p.get("anim") == "drop": return f"drop-{p.get('obj', 'auto')}" if edit == "spawn": return ("avenue-" if p.get("mode") == "avenue" else "") + p.get("obj", "tree") + ("-loose" if p.get("loose") else "") if edit in ("add", "grow"): return p.get("obj", "auto") if edit == "delete": return p.get("mode", "pop") if edit == "swap": return (p.get("pair") or "auto") + (f"-w{p['wave']}" if p.get("wave") else "") if edit == "paint": if p.get("mode") == "trail3d": return f"trail3d-{p.get('obj', 'bush')}" return (p.get("cls") or "auto") + (f"-lead{p['lead']}" if p.get("lead") else "") if edit == "write": t = p.get("text", "马良") t = {"马良": "maliang-cn"}.get(t, t).replace(" ", "_").lower() return (f"{p.get('mode', 'paint')}-{t}" + ("-bold" if p.get("bold") else "") + ("-big" if p.get("big") else "") + ("-dots" if p.get("shrink") else "") + (f"-{p['cls']}" if p.get("cls") else "")) if edit == "trap": return p.get("cls", "arch") + ("-loose" if p.get("min_keep") else "") return "x" def case_name(base: str, edit: str, k: int, params: dict) -> str: return f"{base}__E{edit}-{variant_of(edit, params)}-k{int(k)}" # ---------------------------------------------------------------------------- # 出 case # ---------------------------------------------------------------------------- def outline(mask: np.ndarray) -> np.ndarray: m = mask.astype(np.uint8) return (cv2.dilate(m, np.ones((3, 3), np.uint8)) - m) > 0 def cond_sheet(path: str, ids0: np.ndarray, ids1: np.ndarray, diff: np.ndarray, idx, title: str) -> None: import compose as CP from PIL import Image, ImageDraw tw, th = W // 2, H // 2 rows = [] for ids, lab in ((ids0, "original"), (ids1, "edited")): tiles = [] for f in idx: im = CP.sem_panel(ids[f], tw, th) if lab == "edited": d = cv2.resize(diff[f].astype(np.uint8), (tw, th), interpolation=cv2.INTER_NEAREST) > 0 o = outline(cv2.dilate(d.astype(np.uint8), np.ones((3, 3), np.uint8))) im[o] = (255, 255, 255) cv2.putText(im, f"{lab} f{f} {f / FPS:.2f}s", (6, th - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 3, cv2.LINE_AA) cv2.putText(im, f"{lab} f{f} {f / FPS:.2f}s", (6, th - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 1, cv2.LINE_AA) tiles.append(im) rows.append(np.concatenate(tiles, 1)) body = np.concatenate(rows, 0) head = Image.new("RGB", (body.shape[1], 28), CP.BG) CP.draw_text(ImageDraw.Draw(head), 8, 5, title, 15, CP.FG, "SemiBold") cv2.imwrite(path, cv2.cvtColor(np.concatenate([np.asarray(head), body], 0), cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90]) def _json_default(o): if isinstance(o, (np.integer,)): return int(o) if isinstance(o, (np.floating,)): return float(o) if isinstance(o, np.ndarray): return o.tolist() raise TypeError(type(o)) def build_case(B: Base, edit: str, k: int, params: dict | None = None, name: str | None = None, out: str = OUT, seed: int = 0) -> dict: t0 = time.time() params = dict(params or {}) name = name or case_name(B.name, edit, k, params) od = os.path.join(out, "cases", name) E = Edit(B, edit, k, params, seed=seed) PREP[edit](E) ids = E.render() assert set(np.unique(ids).tolist()) <= GM.valid_raw_ids("parts"), np.unique(ids) diff = ids != B.ids0 f1 = E.first_frame() n_px = diff.sum((1, 2)) after = n_px[max(f1, E.t_end):] if E.t_end < F else n_px[-1:] c0, c1 = GM.collapse_parts(B.ids0), GM.collapse_parts(ids) pl0, pl1 = (c0 == GEO.PLAYER_ID).sum((1, 2)), (c1 == GEO.PLAYER_ID).sum((1, 2)) bs0, bs1 = (c0 == GEO.BOSS_ID).sum((1, 2)), (c1 == GEO.BOSS_ID).sum((1, 2)) ratio = lambda a, b: float(np.min(np.where(a[f1:] > 50, b[f1:] / np.maximum(a[f1:], 1), 1.0))) if f1 < F else 1.0 stats = dict(first_changed_frame=int(np.argmax(n_px > 0)) if n_px.any() else None, edit_frame=f1, edit_end=int(E.t_end), identical_before=bool(not diff[:f1].any()), px_mean_after=round(float(after.mean()), 1), px_min_after=int(after.min()), px_max=int(n_px.max()), frac_mean_after=round(float(after.mean()) / (H * W), 4), frames_ge500=int((n_px >= 500).sum()), player_px_ratio_min=round(ratio(pl0, pl1), 3), boss_px_ratio_min=round(ratio(bs0, bs1), 3)) weak = stats["px_mean_after"] < 800 * GEO.AREA_VS_480 and edit not in ("boss_del",) os.makedirs(od, exist_ok=True) np.savez_compressed(os.path.join(od, "ids.npz"), ids=ids) np.savez_compressed(os.path.join(od, "mask.npz"), bits=np.packbits(diff.ravel()), shape=np.array(diff.shape), px=n_px.astype(np.int32)) shutil.copyfile(B.info["first"], os.path.join(od, "first.png")) shutil.copyfile(B.info["prompts"], os.path.join(od, "prompts.json")) act = os.path.join(B.info["map_dir"], "actions.npy") if os.path.exists(act): shutil.copyfile(act, os.path.join(od, "actions.npy")) idx = sorted({0, max(0, f1 - 1), min(F - 1, f1 + 4), min(F - 1, (f1 + E.t_end) // 2 + 2), min(F - 1, max(E.t_end, f1 + 12)), F - 1}) cond_sheet(os.path.join(od, "cond_sheet.jpg"), B.ids0, ids, diff, idx, f"{name} · {E.label}") meta = dict(kind="teaser_edit", name=name, edit=edit, variant=variant_of(edit, params), label=E.label, k=int(k), edit_frame=f1, edit_end=int(E.t_end), edit_time_s=round(f1 / FPS, 3), params=params, resolved=E.info, stats=stats, weak=bool(weak), base=dict(B.info, check_px=B.check), seed_edit=seed, rollout=dict(seed=B.info["roll_seed"], compile=B.info["roll_compile"], ckpt=B.info["roll_ckpt"]), orig=dict(roll=B.info["roll"], gen=os.path.join(B.info["roll"], "gen.mp4"), ids=B.info["ids"]), files=dict(ids="ids.npz", mask="mask.npz", first="first.png", prompts="prompts.json", actions="actions.npy", cond_sheet="cond_sheet.jpg"), sec=round(time.time() - t0, 1), generator="scripts/teaser/edits.py", t=time.time()) tmp = os.path.join(od, ".edit.json.tmp") json.dump(meta, open(tmp, "w"), ensure_ascii=False, indent=1, default=_json_default) os.replace(tmp, os.path.join(od, "edit.json")) return meta def job_row(meta: dict, out: str = OUT, prio: float = 0.0) -> dict: od = os.path.join(out, "cases", meta["name"]) b = meta["base"] return dict(name=meta["name"], first=os.path.join(od, "first.png"), ids=os.path.join(od, "ids.npz"), prompts=os.path.join(od, "prompts.json"), out=os.path.join(out, "cases"), seed=meta["rollout"]["seed"], prio=prio, scene=b.get("scene"), map=b.get("map"), label=meta["label"], title=b.get("label"), tags=dict(edit=meta["edit"], variant=meta["variant"], k=meta["k"], edit_frame=meta["edit_frame"], edit_end=meta["edit_end"], label=meta["label"], base=b["name"], weak=meta["weak"])) def append_jsonl(path: str, row: dict) -> None: os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "a") as fh: fcntl.flock(fh, fcntl.LOCK_EX) fh.write(json.dumps(row, ensure_ascii=False, default=_json_default) + "\n") fh.flush() fcntl.flock(fh, fcntl.LOCK_UN) # ---------------------------------------------------------------------------- # CLI # ---------------------------------------------------------------------------- def cmd_one(a) -> None: B = Base(a.base) log(f"底子 {a.base} 重建 {B.build_sec}s(对拍 {B.check})") params = json.loads(a.params) if a.params else {} try: m = build_case(B, a.edit, a.k, params, a.name, a.out) except EditFail as e: log(f"[skip] {a.edit}: {e}") return log(f"{m['name']}: {m['label']} · {json.dumps(m['stats'])} · {m['sec']}s") if not a.no_job: append_jsonl(os.path.join(a.out, "jobs.jsonl"), job_row(m, a.out, a.prio)) def read_plan(path: str) -> list[dict]: rows, seen = [], set() for ln in open(path): ln = ln.strip() if not ln or ln.startswith("#"): continue r = json.loads(ln) r.setdefault("params", {}) r.setdefault("name", case_name(r["base"], r["edit"], r["k"], r["params"])) if r["name"] in seen: continue seen.add(r["name"]) rows.append(r) return rows def case_state(out: str, name: str) -> str: if os.path.exists(os.path.join(out, "cases", name, "edit.json")): return "done" if os.path.exists(os.path.join(out, "_fail", name + ".json")): return "fail" return "pending" def cmd_worker(a) -> None: rows = read_plan(a.plan) groups = collections.OrderedDict() for r in rows: groups.setdefault(r["base"], []).append(r) lk = os.path.join(a.out, "_locks") os.makedirs(lk, exist_ok=True) os.makedirs(os.path.join(a.out, "_fail"), exist_ok=True) for base, rs in groups.items(): todo = [r for r in rs if case_state(a.out, r["name"]) == "pending"] if not todo: continue key = os.path.join(lk, base.replace("/", "_")) try: os.mkdir(key) except FileExistsError: continue try: B = Base(base) log(f"[w{a.rank}] 底子 {base}:重建 {B.build_sec}s") except Exception: # noqa: BLE001 err = traceback.format_exc() log(f"[w{a.rank}] 底子 {base} 重建失败:{err.strip().splitlines()[-1]}") for r in todo: json.dump(dict(row=r, error=err), open(os.path.join(a.out, "_fail", r["name"] + ".json"), "w"), indent=1) continue for r in todo: if case_state(a.out, r["name"]) != "pending": continue try: m = build_case(B, r["edit"], r["k"], r["params"], r["name"], a.out, int(r.get("seed", 0))) if not a.no_job and not (m["weak"] and not r.get("keep_weak")): append_jsonl(os.path.join(a.out, "jobs.jsonl"), job_row(m, a.out, float(r.get("prio", 0)))) log(f"[w{a.rank}] {r['name']}: {m['label']} · px {m['stats']['px_mean_after']} · " f"{'WEAK ' if m['weak'] else ''}{m['sec']}s") except EditFail as e: json.dump(dict(row=r, error=f"EditFail: {e}"), open(os.path.join(a.out, "_fail", r["name"] + ".json"), "w"), ensure_ascii=False, indent=1) log(f"[w{a.rank}] [skip] {r['name']}: {e}") except Exception: # noqa: BLE001 err = traceback.format_exc() json.dump(dict(row=r, error=err), open(os.path.join(a.out, "_fail", r["name"] + ".json"), "w"), ensure_ascii=False, indent=1) log(f"[w{a.rank}] [FAIL] {r['name']}: {err.strip().splitlines()[-1]}") def cmd_run(a) -> None: gpus = [g for g in a.gpus.split(",") if g] N = len(gpus) * a.procs_per_gpu logs = f"{M}/outputs/teaser/logs/edit" os.makedirs(logs, exist_ok=True) shutil.rmtree(os.path.join(a.out, "_locks"), ignore_errors=True) procs = [] for r in range(N): env = dict(os.environ, CUDA_VISIBLE_DEVICES=gpus[r % len(gpus)], OMP_NUM_THREADS="4", MKL_NUM_THREADS="4", OPENBLAS_NUM_THREADS="4", PYTHONUNBUFFERED="1") lf = open(os.path.join(logs, f"edits_w{r:02d}.log"), "a") cmd = [sys.executable, os.path.abspath(__file__), "worker", "--plan", a.plan, "--out", a.out, "--rank", str(r)] if a.no_job: cmd.append("--no_job") procs.append(subprocess.Popen(cmd, env=env, stdout=lf, stderr=subprocess.STDOUT)) time.sleep(0.5) log(f"{N} 个 worker(GPU {gpus}),pids {[p.pid for p in procs]}") for p in procs: p.wait() log("全部 worker 结束") cmd_status(a) def cmd_status(a) -> None: if a.plan and os.path.exists(a.plan): rows = read_plan(a.plan) st = collections.Counter(case_state(a.out, r["name"]) for r in rows) by = collections.defaultdict(collections.Counter) for r in rows: by[r["edit"]][case_state(a.out, r["name"])] += 1 print(f"plan {len(rows)}:{dict(st)}") for e, c in sorted(by.items()): print(f" {e:11s} {dict(c)}") cd = os.path.join(a.out, "cases") if os.path.isdir(cd): names = [n for n in os.listdir(cd) if os.path.exists(os.path.join(cd, n, "edit.json"))] rolled = [n for n in names if os.path.exists(os.path.join(cd, n, "meta.json"))] print(f"cases {len(names)} · 已推理 {len(rolled)}") def cmd_finalize(a) -> None: """推完的 case:把 edit.json 并进 rollout 的 meta.json(键 "edit"),写 /cases_index.jsonl(一行一条结果)。""" cd = os.path.join(a.out, "cases") rows = [] for n in sorted(os.listdir(cd)): d = os.path.join(cd, n) mp, ep = os.path.join(d, "meta.json"), os.path.join(d, "edit.json") if not (os.path.isfile(mp) and os.path.isfile(ep)): continue meta, e = json.load(open(mp)), json.load(open(ep)) if meta.get("edit", {}).get("t") != e.get("t"): meta["edit"] = e tmp = os.path.join(d, f".meta.{os.getpid()}.tmp") json.dump(meta, open(tmp, "w"), ensure_ascii=False, indent=1, default=_json_default) os.replace(tmp, mp) rows.append(dict(name=n, dir=d, edit=e["edit"], variant=e["variant"], label=e["label"], edit_frame=e["edit_frame"], edit_end=e["edit_end"], base=e["base"]["name"], theme=e["base"]["theme"], scene=e["base"]["scene"], gen=os.path.join(d, "gen.mp4"), orig_gen=e["orig"]["gen"], ids=os.path.join(d, "ids.npz"), mask=os.path.join(d, "mask.npz"), first=os.path.join(d, "first.png"), actions=os.path.join(d, "actions.npy"), prompts=os.path.join(d, "prompts.json"))) with open(os.path.join(a.out, "cases_index.jsonl"), "w") as fh: for r in rows: fh.write(json.dumps(r, ensure_ascii=False) + "\n") print(f"finalize:{len(rows)} 条 → {a.out}/cases_index.jsonl") def build_parser() -> argparse.ArgumentParser: ap = argparse.ArgumentParser(description="teaser 世界编辑 case(语义条件)") ap.add_argument("cmd", choices=["one", "run", "worker", "status", "finalize"]) ap.add_argument("--base", default=None) ap.add_argument("--edit", choices=sorted(PREP), default="add") ap.add_argument("--k", type=int, default=32) ap.add_argument("--params", default="") ap.add_argument("--name", default=None) ap.add_argument("--out", default=OUT) ap.add_argument("--plan", default=os.path.join(OUT, "plan.jsonl")) ap.add_argument("--gpus", default="0,1,2") ap.add_argument("--procs_per_gpu", type=int, default=4) ap.add_argument("--rank", type=int, default=0) ap.add_argument("--prio", type=float, default=0.0) ap.add_argument("--no_job", action="store_true", help="不往 jobs.jsonl 追加 rollout 任务") return ap def main(argv=None) -> None: a = build_parser().parse_args(argv) dict(one=cmd_one, run=cmd_run, worker=cmd_worker, status=cmd_status, finalize=cmd_finalize)[a.cmd](a) if __name__ == "__main__": main()