Download scripts/splat/pack.py from CharlieDreemur/Recreate-AAA: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/splat/pack.py
- Command line
-
hf download hf://CharlieDreemur/Recreate-AAA/scripts/splat/pack.py
-
curl -L -o pack.py https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/splat/pack.py
14 kB
| """Put a trained splat into the game's own frame and pack it for the page. | |
| uv run python scripts/splat/pack.py SPLAT.ply DATA BUILD | |
| DATA is the cameras.py output (poses.json), BUILD the game folder (controller.json, input.jsonl, recording.mp4). | |
| The splat lives in the reconstruction's arbitrary frame and scale; the game's camera lives in metres, starting | |
| at the origin and looking along -z, driven by the inputs. The reconstruction's camera centres are laid over the | |
| controller's path at the same moments (scale, turn, shift), and every splat is moved with them; where the two part | |
| ways (something stopped the player) it is placed by the headings, the length of free steps and the first second. | |
| Each splat also gets the mean direction it was filmed from (the last block of splats.bin): a splat is only | |
| known to look right from about there, and the page can let it fade when looked at from elsewhere. | |
| Where exposure.py took a changing brightness out of the training frames (BUILD/exposure.json), each splat gets | |
| back the brightness of the moments it was filmed: a place that is only ever seen lit is drawn lit. | |
| Writes BUILD/splats.bin, BUILD/splats.json and, where the frames show sky, BUILD/sky.jpg.""" | |
| import json, struct, sys | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[2])) | |
| from scripts import probe # noqa: E402 | |
| ply, data, build = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) | |
| def read_ply(path: Path) -> dict[str, np.ndarray]: | |
| raw = path.read_bytes() | |
| end = raw.index(b"end_header\n") + len(b"end_header\n") | |
| names, count = [], 0 | |
| for line in raw[:end].decode("ascii", "replace").splitlines(): | |
| parts = line.split() | |
| if parts[:2] == ["element", "vertex"]: | |
| count = int(parts[2]) | |
| elif parts[:1] == ["property"]: | |
| names.append((parts[2], {"float": "<f4", "double": "<f8", "uchar": "u1", "int": "<i4"}[parts[1]])) | |
| table = np.frombuffer(raw, dtype=np.dtype(names), count=count, offset=end) | |
| return {name: table[name] for name, _kind in names} | |
| def quaternion(R: np.ndarray) -> np.ndarray: | |
| w = np.sqrt(max(0.0, 1 + R[0, 0] + R[1, 1] + R[2, 2])) / 2 | |
| x = np.sqrt(max(0.0, 1 + R[0, 0] - R[1, 1] - R[2, 2])) / 2 * np.sign(R[2, 1] - R[1, 2] or 1) | |
| y = np.sqrt(max(0.0, 1 - R[0, 0] + R[1, 1] - R[2, 2])) / 2 * np.sign(R[0, 2] - R[2, 0] or 1) | |
| z = np.sqrt(max(0.0, 1 - R[0, 0] - R[1, 1] + R[2, 2])) / 2 * np.sign(R[1, 0] - R[0, 1] or 1) | |
| return np.array([w, x, y, z]) | |
| def multiply(q: np.ndarray, r: np.ndarray) -> np.ndarray: | |
| """Quaternion product q * r for one q (4,) and many r (N, 4), both w, x, y, z.""" | |
| w, x, y, z = q | |
| rw, rx, ry, rz = r.T | |
| return np.stack([w * rw - x * rx - y * ry - z * rz, w * rx + x * rw + y * rz - z * ry, | |
| w * ry - x * rz + y * rw + z * rx, w * rz + x * ry - y * rx + z * rw], 1) | |
| sfm = json.loads((data / "poses.json").read_text()) | |
| times = np.array([p["t"] for p in sfm["poses"]]) | |
| centres = np.array([p["centre"] for p in sfm["poses"]]) | |
| _numbers, rows = probe.poses(build, float(times.max()) + 1) | |
| rows = np.array(rows) | |
| game = np.stack([np.interp(times, rows[:, 0], rows[:, k]) for k in (1, 2, 3)], 1) | |
| # The reconstruction is laid into the game's frame one of two ways. Over the controller's whole path (the nearest fit of | |
| # the camera centres to it) is right while the controller's path is about the camera's: its small errors are spread out. | |
| # It is wrong once something stopped the player, for the controller walks on through: a recording made to run into walls | |
| # came out 7.5% too large and two metres off. So the other way uses what does not depend on where the controller thinks the | |
| # player is: the turn from the headings, the size from steps half a second long (held back, the camera's step is shorter | |
| # than the controller's and never longer: the middle ratio where the controller walks at speed is the free one), the place | |
| # from the first second. Of the two, the one that leaves the best-fitted quarter of the cameras nearer the controller's | |
| # path is kept: a fit that is right has a good part of the recording exact, a compromise has none. | |
| def nearest(a: np.ndarray, b: np.ndarray) -> tuple[float, np.ndarray, np.ndarray]: | |
| """Scale, rotation and shift taking points ``a`` nearest to ``b`` (Umeyama).""" | |
| ma, mb = a.mean(0), b.mean(0) | |
| A, B = a - ma, b - mb | |
| U, S, Vt = np.linalg.svd(B.T @ A / len(a)) | |
| E = np.diag([1.0, 1.0, np.sign(np.linalg.det(U @ Vt))]) | |
| R = U @ E @ Vt | |
| s = float((S * np.diag(E)).sum() / (A ** 2).sum() * len(a)) | |
| return s, R, mb - s * R @ ma | |
| off = lambda laid: np.linalg.norm((laid[0] * (laid[1] @ centres.T)).T + laid[2] - game, axis=1) | |
| whole = nearest(centres, game); agree = off(whole) <= 3 * np.median(off(whole)) + 1e-6 # (a jump, a stumble: fitted on the frames that agree) | |
| whole = nearest(centres[agree], game[agree]) | |
| yaw = np.interp(times, rows[:, 0], rows[:, 4]); pitch = np.interp(times, rows[:, 0], rows[:, 5]) | |
| ahead = np.stack([np.sin(yaw) * np.cos(pitch), np.sin(pitch), -np.cos(yaw) * np.cos(pitch)], 1); right = np.stack([np.cos(yaw), 0 * yaw, np.sin(yaw)], 1) | |
| looks = np.stack([right, np.cross(ahead, right), ahead], 2) # the controller's camera at each frame: right, down, ahead as columns | |
| U, _S, Vt = np.linalg.svd(sum(look @ np.array(p["rotation"]).T for look, p in zip(looks, sfm["poses"]))) | |
| turned = U @ np.diag([1.0, 1.0, np.sign(np.linalg.det(U @ Vt))]) @ Vt | |
| apart = max(1, int(round(0.5 / np.median(np.diff(times))))) | |
| mine, theirs = np.linalg.norm(game[apart:] - game[:-apart], axis=1), np.linalg.norm(centres[apart:] - centres[:-apart], axis=1) | |
| walking = (mine > 0.5 * np.percentile(mine, 90)) & (theirs > 1e-6) | |
| size = float(np.median(mine[walking] / theirs[walking])) if walking.any() else 1.0 | |
| begun = times < times.min() + 1.0 | |
| start = (size, turned, (game[begun] - size * (turned @ centres[begun].T).T).mean(0)) | |
| by_start = np.percentile(off(start), 25) < np.percentile(off(whole), 25) | |
| scale, R, shift = start if by_start else whole | |
| residual = off((scale, R, shift)) | |
| # The reconstruction's cameras look along their +z; the controller's along -z at yaw 0: compare headings as a check. | |
| forward = np.array([np.array(p["rotation"])[:, 2] for p in sfm["poses"]]) @ R.T | |
| angle = np.degrees(np.arccos(np.clip((forward * ahead).sum(1), -1, 1))) | |
| P = read_ply(ply) | |
| alpha = 1 / (1 + np.exp(-P["opacity"].astype(np.float64))) | |
| scales = np.exp(np.stack([P[f"scale_{i}"] for i in range(3)], 1).astype(np.float64)) * scale | |
| position = (scale * (R @ np.stack([P["x"], P["y"], P["z"]], 1).astype(np.float64).T)).T + shift | |
| keep = (alpha > 0.005) & (scales.max(1) < 8.0) # faint splats add up: only what the trainer itself would not draw goes | |
| rotation = np.stack([P[f"rot_{i}"] for i in range(4)], 1).astype(np.float64) | |
| rotation /= np.linalg.norm(rotation, axis=1, keepdims=True) | |
| rotation = multiply(quaternion(R), rotation) | |
| colour = np.clip(0.5 + 0.28209479177387814 * np.stack([P[f"f_dc_{i}"] for i in range(3)], 1), 0, 1) | |
| kept_all = len(alpha) | |
| position, scales, rotation, colour, alpha = position[keep], scales[keep], rotation[keep], colour[keep], alpha[keep] | |
| n = len(position) | |
| # From where each splat was filmed: the mean direction from the cameras that had it in view, and the widest | |
| # angle any of them made with that mean. Stored as one vector: the mean direction, its length (1 + cos of that | |
| # angle) / 2, so 1 means always from the same side and 0 from all round. | |
| half = np.array([sfm["width"], sfm["height"]]) / 2 / sfm["focal"] | |
| looks = [(scale * R @ np.array(pose["centre"]) + shift, R @ np.array(pose["rotation"])) for pose in sfm["poses"][::2]] | |
| def filmed_from(eye, turn, start, depth=None): | |
| to = position[start:start + 200000] - eye; cam = to @ turn | |
| seen = (cam[:, 2] > 0.1) & (np.abs(cam[:, 0]) < half[0] * cam[:, 2]) & (np.abs(cam[:, 1]) < half[1] * cam[:, 2]) | |
| if depth is None: | |
| return seen, to[seen] / np.linalg.norm(to[seen], axis=1, keepdims=True) | |
| # ... and not behind something: at the depth the frame has at its pixel (the frame's depth map, in the reconstruction's units) | |
| z = cam[seen, 2] / scale | |
| col = np.clip(((cam[seen, 0] / cam[seen, 2] / half[0] + 1) / 2 * depth.shape[1]).astype(int), 0, depth.shape[1] - 1) | |
| row = np.clip(((cam[seen, 1] / cam[seen, 2] / half[1] + 1) / 2 * depth.shape[0]).astype(int), 0, depth.shape[0] - 1) | |
| return seen, np.abs(depth[row, col] - z) < 0.1 * z | |
| # The brightness each splat was filmed at: the mean (of the logs) of the gains of the frames that show it. In view is | |
| # not shown: a pier seen lit from close by also lies, behind a wall or far off, in the view of frames from | |
| # before the lamps came on. Frames with a depth map say which splats they really show; a splat none of them | |
| # shows goes by the frames that had it in view. | |
| gains = json.loads((build / "exposure.json").read_text())["gains"] if (build / "exposure.json").is_file() else [] | |
| gains = np.log([g for _t, g in gains])[::2] if len(gains) == len(sfm["poses"]) else None | |
| lit, shown_by, lit_in_view, in_view = np.zeros(n), np.zeros(n), np.zeros(n), np.zeros(n) | |
| mean, widest = np.zeros((n, 3)), np.ones(n) | |
| for number, (eye, turn) in enumerate(looks): | |
| depth = data / "depth" / (Path(sfm["poses"][::2][number]["name"]).stem + ".npy") | |
| depth = np.load(depth).astype(np.float32) if gains is not None and depth.is_file() else None | |
| for start in range(0, n, 200000): | |
| seen, way = filmed_from(eye, turn, start); mean[start:start + 200000][seen] += way | |
| if gains is not None: | |
| lit_in_view[start:start + 200000][seen] += gains[number]; in_view[start:start + 200000][seen] += 1 | |
| if depth is not None: | |
| shown = np.flatnonzero(seen)[filmed_from(eye, turn, start, depth)[1]] + start | |
| lit[shown] += gains[number]; shown_by[shown] += 1 | |
| mean /= np.maximum(np.linalg.norm(mean, axis=1, keepdims=True), 1e-9) | |
| for eye, turn in looks: | |
| for start in range(0, n, 200000): | |
| seen, way = filmed_from(eye, turn, start); part = widest[start:start + 200000] | |
| part[seen] = np.minimum(part[seen], (way * mean[start:start + 200000][seen]).sum(1)) | |
| filmed = mean * ((1 + widest) / 2)[:, None] | |
| brightness = np.exp(np.where(shown_by > 0, lit / np.maximum(shown_by, 1), lit_in_view / np.maximum(in_view, 1))) | |
| rgba = np.round(np.column_stack([np.clip(colour * brightness[:, None], 0, 1), alpha]) * 255).astype(np.uint8) | |
| with open(build / "splats.bin", "wb") as out: | |
| out.write(struct.pack("<I", n)) | |
| for block in (position.astype("<f4"), scales.astype("<f4"), rotation.astype("<f4"), rgba, filmed.astype("<f4")): | |
| out.write(block.tobytes()) | |
| trained = json.loads((ply.parent / "stats.json").read_text()) if (ply.parent / "stats.json").is_file() else {} | |
| (build / "splats.json").write_text(json.dumps({"count": n, "scale": scale, "width": sfm["width"], "focal": sfm["focal"], "antialiased": bool(trained.get("antialiased")), | |
| "turn": R.round(8).tolist(), "shift": shift.round(6).tolist(), # game = scale * turn @ reconstruction + shift | |
| "bounds": [position.min(0).round(2).tolist(), position.max(0).round(2).tolist()]})) | |
| # The sky: every frame's sky pixels laid by direction into one picture around the place (three.js's | |
| # equirectangular layout, in the game's frame), gaps filled from what is next to them. | |
| from PIL import Image | |
| wide, tall = 1024, 512 | |
| total, count = np.zeros((tall, wide, 3)), np.zeros((tall, wide)) | |
| focal = sfm["focal"]; v, u = np.mgrid[0:sfm["height"]:2, 0:sfm["width"]:2] | |
| rays = np.stack([(u - sfm["width"] / 2) / focal, (v - sfm["height"] / 2) / focal, np.ones(u.shape)], -1) | |
| for pose in sfm["poses"][::2]: | |
| marked = data / "sky" / (Path(pose["name"]).stem + ".png") | |
| if not marked.is_file(): | |
| continue | |
| sky = np.asarray(Image.open(marked).convert("L"))[::2, ::2] > 127 | |
| own = data / "ignore" / (Path(pose["name"]).stem + ".png") # a banner drawn over this frame is not sky | |
| if own.is_file(): | |
| sky &= np.asarray(Image.open(own).convert("L"))[::2, ::2] > 127 | |
| picture = np.asarray(Image.open(data / ("images_as_filmed" if (data / "images_as_filmed").is_dir() else "images") / pose["name"]).convert("RGB"))[::2, ::2] | |
| way = rays[sky] @ (R @ np.array(pose["rotation"])).T; way /= np.linalg.norm(way, axis=1, keepdims=True) | |
| col = ((np.arctan2(way[:, 2], way[:, 0]) / (2 * np.pi) + 0.5) * wide).astype(int) % wide | |
| row = np.clip(((0.5 - np.arcsin(np.clip(way[:, 1], -1, 1)) / np.pi) * tall).astype(int), 0, tall - 1) | |
| np.add.at(total, (row, col), picture[sky]); np.add.at(count, (row, col), 1) | |
| if count.any(): | |
| levels = [(total, count)] | |
| while levels[-1][1].shape[0] > 1: # sums and counts at halved sizes ... | |
| t, k = levels[-1]; levels.append((t.reshape(t.shape[0] // 2, 2, t.shape[1] // 2, 2, 3).sum((1, 3)), k.reshape(k.shape[0] // 2, 2, k.shape[1] // 2, 2).sum((1, 3)))) | |
| filled = levels[-1][0] / np.maximum(levels[-1][1], 1)[..., None] | |
| for t, k in levels[-2::-1]: # ... and back up: an empty cell takes the coarser level's colour | |
| filled = np.where(k[..., None] > 0, t / np.maximum(k, 1)[..., None], filled.repeat(2, 0).repeat(2, 1)) | |
| Image.fromarray(np.clip(filled, 0, 255).astype(np.uint8)).save(build / "sky.jpg", quality=92) | |
| how = " (by the start: the controller's path and the cameras part ways)" if by_start else "" | |
| print(f"{n} of {kept_all} splats kept | reconstruction to game{how}: scale {scale:.4f}, cameras off the controller's path by mean " | |
| f"{residual.mean():.3f} m (max {residual.max():.3f}), headings off by mean {angle.mean():.2f} deg (max {angle.max():.2f}) | " | |
| f"{(build / 'splats.bin').stat().st_size / 1e6:.1f} MB" | |
| + (f" | brightness as filmed: splats at {np.percentile(brightness, 5):.2f} to {np.percentile(brightness, 95):.2f} of the usual" if gains is not None else "")) | |