Recreate-AAA / scripts /splat_build.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
26 kB
"""Rebuild a recording's place by reconstruction instead of by hand: solve the camera, optimise Gaussian
splats against the frames, and walk the result with the recording's own controller.
uv run python -m scripts.splat_build SESSION --out BUILD [--seconds N] [--steps 30000] [--eye-height 1.6]
[--fps 10] [--trainer "COMMAND {data} {out} {steps}"] [--retrain] [--reconstruct] [--view third] [--characters [N]] [--opponent T,X,Y ...]
Why (docs/direct-build.md): a builder that models a street by hand from footage reaches "recognisably the same
street" and stops there; the detail of a scene is in its pixels, and an optimiser takes it from them. On the
Bistro street the hand-built version (an hour of an agent plus a round) and this (about fifteen minutes of
this machine, no agent) are compared in the write-up.
Steps, each a file in scripts/splat/:
1. the controller's numbers from the recording and its inputs (bench_builder.controller_fit_worker);
2. cameras.py matches the frames (COLMAP, in the CV runtime), puts the cameras on the path the inputs imply,
triangulates from there and adjusts, so the camera is checked against the pictures, not searched for; the
adjusted cameras then correct the controller's numbers (lens, picture lead, turn rates, walking speed);
3. depth.py marks the sky in each frame and estimates depth (a single-image depth model) and exposure.py takes
a changing exposure out of the frames; Brush (https://github.com/ArthurBrussee/brush, $GBB_BRUSH or
runs/splat-tools/.../brush_app) trains the splats, or ``--trainer`` (or $GBB_SPLAT_TRAINER) runs any command that
leaves {out}/splat.ply, such as scripts/splat/train_cuda.py on a GPU; with $GBB_SPLAT_SEGMENT, moving.py finds
what moves in the recording and a second training leaves it out;
4. pack.py lays the reconstruction over the controller's path (metres, the game's frame) and packs it, walls.py
maps what stands in a walker's way, and moving.py cuts out what moves, to be stood back up where it was;
overlays.py cuts out what the recording drew on the screen (a HUD, a counter, a banner), with when each was there;
5. page.html is the place as a three.js scene: splats.js draws the splats as one object in it (sorted every
frame), controller.js moves the camera as the recorded inputs do. A game is built by adding to that scene;
6. the page is replayed as the judge replays it, to find by how many frames it has to run ahead to be in
step with the recording.
``--view third`` is for a recording whose camera follows the player's figure from behind: the controller then
moves the figure, and the camera goes round it (cameras.py measures how far behind, how high and how far to the
side). ``--characters [N]`` gives the figures among what moves a body (N of them at most, 6 unless said: the player's
first, then the ones that have most to do with the player): people.py finds the people in the frames, actors.py
reads each one's motion from its pictures (a pose model) and who each is to the player, scripts.model has Tripo
make a rigged model from its best picture (about 60 credits a figure, 90 for the player, who also gets clips to
walk and run with), and actors.js moves the model's bones as the recording's figure moved: the player's by the
situation the keys are in, an opponent's by how far the player is from it once the player has left the recording's
path. Without a key, or for a thing that is not a figure, the flat pictures stay, and such a thing can be an
opponent all the same. ``--opponent T,X,Y`` (as often as needed) points at what the player is up against, for
what neither a detector nor geometry finds: the thing at X, Y of the picture (0 to 1, from the top left) at T
seconds is followed, kept and taken for an opponent.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def log(message: str) -> None:
print(time.strftime("%H:%M:%S"), message, flush=True)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("session", type=Path)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--seconds", type=float, default=None)
parser.add_argument("--steps", type=int, default=30000)
parser.add_argument("--fps", type=float, default=10.0)
parser.add_argument("--eye-height", type=float, default=1.6)
parser.add_argument("--trainer", default=os.environ.get("GBB_SPLAT_TRAINER"))
parser.add_argument("--retrain", action="store_true")
parser.add_argument("--reconstruct", action="store_true")
parser.add_argument("--view", choices=("first", "third", "vehicle"), default="first", help="third: the camera follows the player's figure; vehicle: the inputs are pedals and a wheel")
parser.add_argument("--cuts", action="store_true", help="the picture jumps (a trailer, a respawn): the cameras take by take, each take a scene of its own (scripts/splat/cuts.py says what is checked; its `join`, which lays takes of one place together, put a take in the wrong place the one time it ran and is not offered here)")
parser.add_argument("--characters", type=int, nargs="?", const=6, default=0, help="give up to this many figures (6) a body")
parser.add_argument("--opponent", action="append", default=[], metavar="T,X,Y", help="what the player is up against: the thing at X, Y of the picture (0 to 1) at T seconds")
args = parser.parse_args(argv)
from scripts import direct_build
session, build = args.session.resolve(), args.out.resolve()
brush = Path(os.environ.get("GBB_BRUSH") or next(iter(sorted(ROOT.glob("runs/splat-tools/*/brush_app"))), "brush_app"))
work = build / ".splat"
if not (args.retrain and (work / "data" / "poses.json").is_file()):
if build.exists():
shutil.rmtree(build)
work.mkdir(parents=True)
seen = direct_build.session_copy(session, work / "seen", args.seconds)
seen_session = next(p for p in (seen / "public-inputs" / "recordings").iterdir() if p.is_dir())
for item in ("recording.mp4", "input.jsonl"):
shutil.copy2(seen_session / item, build / item)
if (seen_session / "frame_timestamps.jsonl").is_file(): # which game step each video frame shows, when the recorder says
shutil.copy2(seen_session / "frame_timestamps.jsonl", build / "frame_timestamps.jsonl")
(build / ".run").write_text(str(seen) + "\n", encoding="utf-8")
log("measuring the controller")
direct_build.controller(seen_session, build, args.eye_height)
# The camera is not searched for: the inputs already say where it was, to a degree or so. A search loses it
# where the camera turns on the spot or the place repeats itself.
log("placing the cameras on the path the inputs imply and adjusting")
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/cameras.py"), str(build), str(work / "data"), "--fps", str(args.fps),
*(["--view", args.view] if args.view != "first" else []), *(["--cuts", "apart"] if args.cuts else [])], text=True, capture_output=True, cwd=ROOT)
for line in [line for line in done.stdout.splitlines() if line and not line.startswith(("I2", "W2", "E2"))] or [done.stderr[-300:]]:
log(line)
if not (work / "data" / "poses.json").is_file():
return 1
if args.characters or args.view == "third" or args.opponent: # the people in the frames, and what was pointed at: what moves is then followed from them too
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/people.py"), str(work / "data"),
*(part for point in args.opponent for part in ("--point", point))], text=True, capture_output=True, cwd=ROOT)
log((done.stdout.strip().splitlines() or [done.stderr[-300:]])[-1])
# The cameras need processors and are found here. What follows needs a graphics card: $GBB_SPLAT_REMOTE (scripts/splat/remote.sh)
# is a command that does it on another machine, with this same script, and brings the build back.
if os.environ.get("GBB_SPLAT_REMOTE") and not args.reconstruct:
log("depths, splats and what moves: on another machine")
subprocess.run([*os.environ["GBB_SPLAT_REMOTE"].split(), str(build), "--steps", str(args.steps)], check=True, cwd=ROOT)
return page(build, work, args.characters)
if not (work / "data" / "depth").is_dir():
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/depth.py"), str(work / "data"), "--build", str(build)],
text=True, capture_output=True)
for line in (done.stdout.strip().splitlines() or [done.stderr[-300:]])[-2:]:
log(line)
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/exposure.py"), str(work / "data"), "--build", str(build)],
text=True, capture_output=True) # a recording whose exposure changes: taken out of the frames
log((done.stdout.strip().splitlines() or [done.stderr[-300:]])[-1])
for stale in (work / "train", work / "splat", work / "data" / "moved"):
shutil.rmtree(stale, ignore_errors=True)
(build / "walls.json").unlink(missing_ok=True)
log(f"training the splats ({args.steps} steps)")
if args.trainer:
train = lambda: subprocess.run(args.trainer.format(data=work / "data", out=work / "splat", steps=args.steps), shell=True, check=True, cwd=ROOT)
train()
# What moves in the recording: one still scene cannot explain it, so the frames differ there from the splats'
# own renders of them. Those pixels are left out of a second training, which gives the place without the
# smear; after packing, the things are cut out against it and stood back up where they were (moving.py).
if (work / "splat" / "renders").is_dir() and os.environ.get("GBB_SPLAT_SEGMENT"):
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/moving.py"), str(work / "data"), str(work / "splat" / "renders"),
str(build / "recording.mp4")],
text=True, capture_output=True)
for line in done.stdout.strip().splitlines() or [done.stderr[-300:]]: # each thing followed, and why it was kept or left
log(line)
if any((work / "data" / "moved").glob("*.png")):
log("training again without what moves")
shutil.rmtree(work / "splat"); train()
ply = work / "splat" / "splat.ply"
else:
# Brush gets a folder of its own (it reads any camera model it finds): the frames, the cameras and
# points, and masks/ where something is fixed on the screen, always or in that frame (black is ignored). Where the recording
# has sky, the frames carry it as transparency, which Brush matches (merely ignored, splats spill into
# the sky as streaks); frames without sky stay as they are, since the transparent kind costs sharpness.
import numpy as np
from PIL import Image
data, train = work / "data", work / "train"
(train / "images").mkdir(parents=True); (train / "sparse" / "0").mkdir(parents=True)
cameras = json.loads((data / "poses.json").read_text()); sky = any((data / "sky").glob("*.png"))
hud = Image.open(data / "mask.png").getextrema()[0] == 0 or any((data / "ignore").glob("*.png"))
lines = []
for number, frame in enumerate(cameras["poses"], 1):
stem = Path(frame["name"]).stem; name = stem + (".png" if sky else ".jpg")
if sky:
marked = data / "sky" / (stem + ".png"); picture = np.asarray(Image.open(data / "images" / frame["name"]).convert("RGB"))
alpha = 255 - np.asarray(Image.open(marked).convert("L")) if marked.is_file() else np.full(picture.shape[:2], 255, np.uint8)
Image.fromarray(np.dstack([picture, alpha])).save(train / "images" / name, compress_level=1)
else:
os.link(data / "images" / frame["name"], train / "images" / name)
if hud: # (a frame showing a banner that is there only part of the time has a mask of its own)
(train / "masks").mkdir(exist_ok=True); own = data / "ignore" / (stem + ".png")
if own.is_file():
both = np.minimum(np.asarray(Image.open(data / "mask.png").convert("L")), np.asarray(Image.open(own).convert("L")))
Image.fromarray(both).save(train / "masks" / (stem + ".png"))
else:
os.link(data / "mask.png", train / "masks" / (stem + ".png"))
R = np.array(frame["rotation"]).T; t = -R @ np.array(frame["centre"]) # camera from world
w = math.sqrt(max(0.0, 1 + R[0, 0] + R[1, 1] + R[2, 2])) / 2
x, y, z = ((R[2, 1] - R[1, 2]) / (4 * w), (R[0, 2] - R[2, 0]) / (4 * w), (R[1, 0] - R[0, 1]) / (4 * w)) if w > 1e-6 else (1.0, 0.0, 0.0)
lines.append(f"{number} {w} {x} {y} {z} {t[0]} {t[1]} {t[2]} 1 {name}\n\n")
if sky:
points = np.load(data / "points.npz")
(train / "sparse/0/cameras.txt").write_text(f"1 SIMPLE_PINHOLE {cameras['width']} {cameras['height']} {cameras['focal']} "
f"{cameras['width'] / 2} {cameras['height'] / 2}\n")
(train / "sparse/0/images.txt").write_text("".join(lines))
(train / "sparse/0/points3D.txt").write_text("".join(
f"{n + 1} {p[0]} {p[1]} {p[2]} {c[0]} {c[1]} {c[2]} 0\n" for n, (p, c) in enumerate(zip(points["points"], points["colours"]))))
else:
shutil.copytree(data / "sparse" / "0", train / "sparse" / "0", dirs_exist_ok=True)
subprocess.run([str(brush), str(train), "--total-steps", str(args.steps), "--sh-degree", "0", "--max-splats", "1500000",
"--export-every", str(args.steps), "--export-path", str(work / "splat")], check=True, capture_output=True)
ply = sorted((work / "splat").glob("export_*.ply"))[-1]
done = subprocess.run([sys.executable, str(ROOT / "scripts/splat/pack.py"), str(ply), str(work / "data"), str(build)], text=True,
capture_output=True, cwd=ROOT)
log((done.stdout.strip().splitlines() or [done.stderr[-300:]])[-1])
done = subprocess.run([sys.executable, str(ROOT / "scripts/splat/walls.py"), str(work / "data"), str(build)], text=True, capture_output=True)
log((done.stdout.strip().splitlines() or [done.stderr[-300:]])[-1]) # what stands in a walker's way
if any((work / "data" / "moved").glob("*.png")):
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/moving.py"), str(work / "data"), str(work / "splat" / "renders"),
str(build / "recording.mp4"), "--build", str(build)], text=True, capture_output=True)
for line in done.stdout.strip().splitlines() or [done.stderr[-300:]]: # each thing: part of the place after all, or cut out
log(line)
return 0 if args.reconstruct else page(build, work, args.characters)
def tint(model: Path, picture: Path) -> list[float]:
"""What a model's colours are to be scaled by to be the colours its figure has in the recording."""
import io
import struct
import numpy as np
from PIL import Image
raw = model.read_bytes(); n = struct.unpack("<I", raw[12:16])[0]; told = json.loads(raw[20:20 + n]); rest = raw[20 + n + 8:]
paint = told["textures"][told["materials"][0]["pbrMetallicRoughness"]["baseColorTexture"]["index"]]
view = told["bufferViews"][told["images"][(paint.get("extensions") or {}).get("EXT_texture_webp", paint).get("source")]["bufferView"]]
light = lambda image: (np.asarray(image, np.float64) / 255) ** 2.2
own = light(Image.open(io.BytesIO(rest[view.get("byteOffset", 0):view.get("byteOffset", 0) + view["byteLength"]])).convert("RGB")).reshape(-1, 3).mean(0)
cut = Image.open(picture).convert("RGBA"); seen = light(cut.convert("RGB"))[np.asarray(cut.getchannel("A")) > 127].mean(0)
return np.clip(seen / np.maximum(0.8 * own, 1e-4), 0.3, 3.0).round(2).tolist() # (actors.js lights a surface at about 0.8 of its colour)
def characters(build: Path, most: int = 6) -> None:
"""The figures among what moves, each given a body: actors.py reads their motion, scripts.model has Tripo make the model.
In a place full of figures, `most` of them: the player's, then those that have most to do with the player."""
from bench_builder.tripo_tools import TripoError
from scripts import model
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/actors.py"), str(build)], text=True, capture_output=True, cwd=ROOT)
for line in [line for line in done.stdout.strip().splitlines() if line[:6] in ("thing ", "the pl", "the vi") or " figures " in line] or [done.stderr[-300:]]:
log(line)
listed = json.loads((build / "actors.json").read_text()) if (build / "actors.json").is_file() else {"actors": []}
if not listed["actors"]:
return
if not model.ready():
log("no Tripo key ($TRIPO_API_KEY): the figures have their motion but no body, and stay flat pictures")
return
# (who gets a body: the player's figure, then the opponents, then whoever had most to do with the player, `most` of them;
# or exactly those BUILD/decisions.json names, {"bodies": [thing, ...]})
ranked = sorted((actor for actor in listed["actors"] if not actor.get("flat")), key=lambda actor: (actor["role"] != "player", actor["role"] != "opponent", -actor.get("engaged", 0.0)))
chosen = (json.loads((build / "decisions.json").read_text()).get("bodies") if (build / "decisions.json").is_file() else None)
if chosen is not None:
ranked, most = [actor for number in chosen for actor in ranked if actor["thing"] == number], len(chosen)
for actor in ranked[most:]:
log(f"thing {actor['thing']}: a figure, left as flat pictures (a body for {most} figures at most; `--characters N` for more)")
for actor in ranked[:most]:
try: # the player's figure is walked about by the keys: clips to stand, walk and run with
made = model.make(build, f"figure-{actor['thing']}", build / actor["ref"], rig=True, clips=("idle", "walk", "run") if actor["role"] == "player" else ())
actor["model"], actor["clips"] = made["model"], made["clips"]
try: # its colours as the recording has them, where the model's paint can be read
actor["tint"] = tint(build / made["model"], build / actor["ref"])
except Exception:
pass
log(f"thing {actor['thing']}: a body for it ({made['model']}, {(build / made['model']).stat().st_size / 1e6:.1f} MB"
f"{', clips ' + ' '.join(made['clips']) if made['clips'] else ''}); Tripo credits on this build so far: {made['credits']}")
except TripoError as error:
log(f"thing {actor['thing']}: no body made ({str(error)[:160]}); it stays a flat picture")
(build / "actors.json").write_text(json.dumps(listed) + "\n")
def findings(build: Path, work: Path, figures: int = 0, fresh: bool = True) -> Path:
"""What is read off the recording once the place is made, and the page: the figures, what is drawn on the screen, what
happens. All of it can be done again at any time (scripts.decide), after BUILD/decisions.json has been changed."""
run = Path((build / ".run").read_text().strip()); (build / ".data").write_text(str(work / "data") + "\n")
if figures:
characters(build, figures)
if (work / "data" / "poses.json").is_file(): # what the recording drew on the screen: a HUD, a counter, a banner, with when
done = subprocess.run([str(ROOT / "runs/cv-runtime/bin/python"), str(ROOT / "scripts/splat/overlays.py"), str(build), str(work / "data")], text=True, capture_output=True, cwd=ROOT)
log((done.stdout.strip().splitlines() or [done.stderr[-300:]])[-1])
# What happens in the recording, as a list a game can be held to: something comes up on the screen, a thing that was
# there is gone while still in view. The page says when each happens in it (window.__gameBeats), and the judge's
# replay grades them on time, early, late or missing as part of `control`: so a round that breaks one is not kept.
events = []
drawn = json.loads((build / "overlays.json").read_text())["elements"] if (build / "overlays.json").is_file() else []
for n, element in enumerate(drawn):
if element["from"] > 0:
events.append({"id": f"overlay-{n}", "kind": "notification", "t": element["from"], "what": f"what is drawn at {element['box']} of the picture comes up"}
| ({"after": element["after"]} if element.get("after") else {}))
things = json.loads((build / "moving.json").read_text())["things"] if (build / "moving.json").is_file() else []
length = max([row["t"] for thing in things for row in thing["seen"]] + [element["to"] or 0 for element in drawn] + [0.0])
for n, thing in enumerate(things):
last = thing["seen"][-1]; box = last.get("box")
if box and last["t"] < length - 1.0 and min(box[0], box[1]) > 0.02 and max(box[2], box[3]) < 0.98 and not thing.get("player"):
events.append({"id": f"thing-{n}-gone", "kind": "interaction", "t": last["t"], "what": f"thing {n} of moving.json is gone, {last.get('far', 0):.1f} m from the camera, while still in view"})
events.sort(key=lambda event: event["t"])
(build / "events.json").write_text(json.dumps({"events": events}, indent=1) + "\n")
if fresh: # what the judge holds a page to (not written again when a builder decides otherwise: events.json is the builder's, this list the judge's)
(run / "public-inputs" / "beat_timeline.json").write_text(json.dumps({"schema": "gamedevbench.beat-timeline.v1", "checkpoints": [], "notes": [], "beats": [
{"id": event["id"], "kind": event["kind"], "text": "", "texts": [], "label": event["what"], "t_ref": event["t"], "window_s": [round(event["t"] - 1.0, 3), round(event["t"] + 1.0, 3)],
"requirement_ids": [], "checkpoint_id": None} for event in events]}) + "\n")
if events:
log(f"{len(events)} things happen in the recording that the page is held to: {', '.join(event['id'] for event in events[:8])}{' ...' if len(events) > 8 else ''}")
if json.loads((build / "controller.json").read_text()).get("inferred"): # no input trace came with it: the judge replays the one read from the picture
pad = next(p for p in (run / "public-inputs" / "recordings").iterdir() if p.is_dir()) / "nitrogen"
pad.mkdir(exist_ok=True); shutil.copy2(build / "gamepad.jsonl", pad / "gamepad.jsonl")
if fresh or not (build / "index.html").is_file(): # (done again in a build a builder has worked on, its page is the builder's)
shutil.copy2(ROOT / "scripts/splat/page.html", build / "index.html")
three = sorted(ROOT.glob("runs/agent-toolchain/*/node_modules/three/build"))[-1]
(build / "lib").mkdir(exist_ok=True)
for source in (ROOT / "scripts/splat/splats.js", ROOT / "scripts/splat/controller.js", ROOT / "scripts/splat/moving.js", ROOT / "scripts/splat/actors.js", ROOT / "scripts/splat/overlays.js"):
shutil.copy2(source, build / source.name)
for item in ("three.module.js", "three.core.js"):
shutil.copy2(three / item, build / "lib" / item)
for item in ("loaders/GLTFLoader.js", "utils/BufferGeometryUtils.js", "utils/SkeletonUtils.js"): # what reads a figure's model
(build / "lib" / item).parent.mkdir(exist_ok=True); shutil.copy2(three.parent / "examples/jsm" / item, build / "lib" / item)
return run
def page(build: Path, work: Path, figures: int = 0) -> int:
"""The place as a page, in step with the judge's clock."""
from scripts import direct_build
run = findings(build, work, figures)
# Replayed by the judge, a page runs a whole number of frames behind or ahead of the recording: how the
# replay clock meets the page's loop, not a property of the recording. Like the colours, it is found by
# replaying: the lag that makes the pictures most alike is kept.
tried: dict[int, float] = {}
def alike(lag: int) -> float:
numbers = json.loads((build / "controller.json").read_text())
numbers["page_lead_frames"] = lag
(build / "controller.json").write_text(json.dumps(numbers, indent=1) + "\n", encoding="utf-8")
tried[lag] = direct_build.judge(build, run, work / "lag" / str(lag)).get("scene") or 0.0
return tried[lag]
step = 1 if alike(1) > alike(0) else -1
lag = step if step == 1 else (-1 if alike(-1) > tried[0] else 0)
while lag and abs(lag) < 3 and alike(lag + step) > tried[lag]:
lag += step
lag = max(tried, key=tried.get)
numbers = json.loads((build / "controller.json").read_text())
numbers["page_lead_frames"] = lag
(build / "controller.json").write_text(json.dumps(numbers, indent=1) + "\n", encoding="utf-8")
log(f"the page is shown {lag} frame(s) ahead to meet the judge's clock (scene by lag: {tried})")
log(f"done: {build / 'index.html'}")
return 0
if __name__ == "__main__":
sys.exit(main())