Download bench_builder/render_kit/__init__.py from CharlieDreemur/Recreate-AAA: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/bench_builder/render_kit/__init__.py
- Command line
-
hf download hf://CharlieDreemur/Recreate-AAA/bench_builder/render_kit/__init__.py
-
curl -L -o __init__.py https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/bench_builder/render_kit/__init__.py
17.4 kB
| """Render kit: a physically based rendering module and CC0 PBR library for browser builds. | |
| The ``render_kit`` builder feature installs ``web/`` into the candidate as ``lib/render-kit/`` | |
| (the kit plus the three.js postprocessing addons it uses, rewritten to import the game's own | |
| three.js through a one-line ``three.js`` shim), copies the PBR texture library into | |
| ``assets/pbr/`` and tells the builder how to use it. | |
| The library's images are not in the repository. ``library.json`` pins every file by URL and | |
| SHA-256; they are fetched once into a local cache (``fetch`` below, or automatically on install). | |
| uv run python -m bench_builder.render_kit fetch | |
| uv run python -m bench_builder.render_kit install PATH/TO/candidate | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import ssl | |
| import sys | |
| import urllib.request | |
| from collections.abc import Callable | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Any | |
| PACKAGE_ROOT = Path(__file__).resolve().parent | |
| WEB_ROOT = PACKAGE_ROOT / "web" | |
| LIBRARY_PATH = PACKAGE_ROOT / "library.json" | |
| DEFAULT_CACHE = PACKAGE_ROOT.parents[1] / "runs" / "asset-library" / "pbr-library" | |
| KIT_RELATIVE = Path("lib") / "render-kit" | |
| ASSETS_RELATIVE = Path("assets") | |
| _USER_AGENT = "gamedev-bench-render-kit" | |
| _REVISION = re.compile(r"REVISION\s*=\s*['\"](\d+)") | |
| class RenderKitError(RuntimeError): | |
| """The render kit could not be installed.""" | |
| class InstallReport: | |
| kit_dir: Path | |
| three: str # where the shim points, relative to lib/render-kit | |
| three_revision: str # the game's three.js REVISION, "" when unknown | |
| addons_revision: str # the REVISION the vendored addons came from | |
| materials: list[str] = field(default_factory=list) | |
| environments: list[str] = field(default_factory=list) | |
| missing: list[str] = field(default_factory=list) # library files neither cached nor fetched | |
| notes: list[str] = field(default_factory=list) | |
| def load_library() -> dict[str, Any]: | |
| return json.loads(LIBRARY_PATH.read_text(encoding="utf-8")) | |
| def cache_root() -> Path: | |
| override = os.environ.get("GAMEDEVBENCH_PBR_CACHE") | |
| return Path(override).expanduser() if override else DEFAULT_CACHE | |
| def library_files(library: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]: | |
| """Every library file by its path under ``assets/`` -> {url, sha256, bytes}.""" | |
| library = library or load_library() | |
| files: dict[str, dict[str, Any]] = {} | |
| for entry in library["materials"].values(): | |
| files.update(entry["files"]) | |
| for entry in library["environments"].values(): | |
| files[entry["hdr"]] = {key: entry[key] for key in ("url", "sha256", "bytes")} | |
| return files | |
| def _sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1 << 20), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def _download(url: str) -> bytes: | |
| try: | |
| import certifi | |
| context = ssl.create_default_context(cafile=certifi.where()) | |
| except ImportError: # pragma: no cover - certifi ships with the project's dependencies | |
| context = ssl.create_default_context() | |
| request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT}) | |
| with urllib.request.urlopen(request, timeout=60, context=context) as response: | |
| return response.read() | |
| def fetch(cache: Path | None = None, *, download: Callable[[str], bytes] = _download) -> dict[str, list[str]]: | |
| """Fill the cache from the pinned URLs; a file whose hash differs is refetched.""" | |
| root = cache or cache_root() | |
| fetched, failed = [], [] | |
| for relative, info in library_files().items(): | |
| target = root / relative | |
| if target.is_file() and _sha256(target) == info["sha256"]: | |
| continue | |
| try: | |
| data = download(info["url"]) | |
| except OSError as exc: | |
| failed.append(f"{relative}: {exc}") | |
| continue | |
| if hashlib.sha256(data).hexdigest() != info["sha256"]: | |
| failed.append(f"{relative}: checksum mismatch") | |
| continue | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_bytes(data) | |
| fetched.append(relative) | |
| return {"fetched": fetched, "failed": failed} | |
| def _three_revision(path: Path) -> str: | |
| try: | |
| match = _REVISION.search(path.read_text(encoding="utf-8", errors="replace")) | |
| except OSError: | |
| return "" | |
| return match.group(1) if match else "" | |
| def _install_three(candidate: Path, report_notes: list[str]) -> tuple[str, str]: | |
| """Point the kit at the game's three.js; vendor the toolchain's copy into lib/ if absent.""" | |
| lib = candidate / "lib" | |
| if not (lib / "three.module.js").is_file(): | |
| build = candidate / "node_modules" / "three" / "build" | |
| if (build / "three.module.js").is_file(): | |
| lib.mkdir(parents=True, exist_ok=True) | |
| for name in ("three.module.js", "three.core.js"): | |
| if (build / name).is_file(): | |
| shutil.copy2(build / name, lib / name) | |
| report_notes.append("Copied three.js into lib/ (lib/three.module.js); import it from there.") | |
| else: | |
| raise RenderKitError("no three.js in lib/ or node_modules/three to point the render kit at") | |
| revision = _three_revision(lib / "three.core.js") or _three_revision(lib / "three.module.js") | |
| return "../three.module.js", revision | |
| def _write_three_shim(kit_dir: Path, three_path: str) -> None: | |
| (kit_dir / "three.js").write_text( | |
| "// Generated by the render kit installer: the game's own three.js, so the kit and the game\n" | |
| "// share one module instance. Change this line only if the game moves its three.js.\n" | |
| f"export * from '{three_path}';\n", | |
| encoding="utf-8", | |
| ) | |
| def install_spatial(candidate: Path) -> Path: | |
| """Install only ``spatial.js`` (and the three.js shim it imports) into ``lib/render-kit/``. | |
| Video builds get the spatial helpers and scene probe even when the ``render_kit`` feature (the | |
| PBR library and postprocessing) is off. Other files in the folder are left alone, so this is | |
| idempotent and safe before or after a full ``install`` (which also ships ``spatial.js``). | |
| Returns the installed ``spatial.js``. | |
| """ | |
| candidate = candidate.resolve() | |
| if not candidate.is_dir(): | |
| raise RenderKitError(f"candidate does not exist: {candidate}") | |
| kit_dir = candidate / KIT_RELATIVE | |
| if kit_dir.is_symlink(): | |
| raise RenderKitError("lib/render-kit must not be a link") | |
| three_path, _ = _install_three(candidate, []) | |
| kit_dir.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(WEB_ROOT / "spatial.js", kit_dir / "spatial.js") | |
| _write_three_shim(kit_dir, three_path) | |
| if not (kit_dir / "README.md").is_file(): | |
| shutil.copy2(WEB_ROOT / "README.md", kit_dir / "README.md") | |
| return kit_dir / "spatial.js" | |
| def install(candidate: Path, *, cache: Path | None = None, allow_fetch: bool = True, | |
| download: Callable[[str], bytes] = _download) -> InstallReport: | |
| """Install (or refresh, on Continue) the kit and the PBR library into ``candidate``.""" | |
| candidate = candidate.resolve() | |
| if not candidate.is_dir(): | |
| raise RenderKitError(f"candidate does not exist: {candidate}") | |
| kit_dir = candidate / KIT_RELATIVE | |
| if kit_dir.is_symlink(): | |
| raise RenderKitError("lib/render-kit must not be a link") | |
| if kit_dir.exists(): | |
| shutil.rmtree(kit_dir) | |
| shutil.copytree(WEB_ROOT, kit_dir) | |
| notes: list[str] = [] | |
| three_path, revision = _install_three(candidate, notes) | |
| _write_three_shim(kit_dir, three_path) | |
| addons_revision = json.loads((WEB_ROOT / "jsm" / "VERSION.json").read_text(encoding="utf-8"))["three"] | |
| if revision and not addons_revision.startswith(f"0.{revision}."): | |
| notes.append(f"The game's three.js is r{revision} but the kit's addons come from {addons_revision}; " | |
| "keep them on the same release.") | |
| library = load_library() | |
| root = cache or cache_root() | |
| if allow_fetch: | |
| fetch(root, download=download) | |
| assets = candidate / ASSETS_RELATIVE | |
| available: set[str] = set() | |
| missing: list[str] = [] | |
| for relative, info in library_files(library).items(): | |
| source, target = root / relative, assets / relative | |
| if target.is_file() and _sha256(target) == info["sha256"]: | |
| available.add(relative) | |
| elif source.is_file() and _sha256(source) == info["sha256"]: | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(source, target) | |
| available.add(relative) | |
| else: | |
| missing.append(relative) | |
| materials = { | |
| name: {"use": entry["use"], "maps": entry["maps"]} | |
| for name, entry in library["materials"].items() | |
| if all(path in available for path in entry["maps"].values()) | |
| } | |
| environments = { | |
| name: {"use": entry["use"], "hdr": entry["hdr"]} | |
| for name, entry in library["environments"].items() | |
| if entry["hdr"] in available | |
| } | |
| # Continue refreshes managed assets, but must retain a game's additional library entries. | |
| # Keep their individual license metadata instead of relabelling them as library CC0 assets. | |
| manifest = assets / "pbr" / "library.json" | |
| existing = json.loads(manifest.read_text(encoding="utf-8")) if manifest.is_file() else {} | |
| custom = False | |
| for category, entries in (("materials", materials), ("environments", environments)): | |
| for name, entry in existing.get(category, {}).items(): | |
| if name not in library[category]: | |
| entries[name] = entry | |
| custom = True | |
| if custom: | |
| notes.append("Preserved candidate-defined library entries and their license metadata.") | |
| for category, entries in (("materials", materials), ("environments", environments)): | |
| for name in library[category]: | |
| if name in entries: | |
| entries[name]["license"] = library["license"] | |
| (assets / "pbr").mkdir(parents=True, exist_ok=True) | |
| manifest.write_text(json.dumps({ | |
| "schema": library["schema"], "source": library["source"], | |
| "license": "See per-entry licenses" if custom else library["license"], | |
| "materials": materials, "environments": environments, | |
| }, indent=1) + "\n", encoding="utf-8") | |
| return InstallReport(kit_dir=kit_dir, three=three_path, three_revision=revision, | |
| addons_revision=addons_revision, | |
| materials=sorted(set(materials) & library["materials"].keys()), | |
| environments=sorted(set(environments) & library["environments"].keys()), | |
| missing=missing, notes=notes) | |
| def builder_instructions(report: InstallReport) -> str: | |
| library = load_library() | |
| materials = "\n".join(f" - `{name}`: {library['materials'][name]['use']}" for name in report.materials) | |
| environments = "\n".join(f" - `{name}`: {library['environments'][name]['use']}" for name in report.environments) | |
| notes = "".join(f"\n- {note}" for note in report.notes) | |
| missing = (f"\n- {len(report.missing)} library files could not be fetched; `assets/pbr/library.json` " | |
| "lists only the complete sets." if report.missing else "") | |
| return f""" | |
| ## Render kit (physically based look) | |
| The host installed `lib/render-kit/render-kit.js` (read `lib/render-kit/README.md`) and a CC0 texture | |
| library in `assets/pbr/`. Select components that address a demonstrated visual gap: image-based | |
| lighting, tone mapping, ambient occlusion, restrained bloom, anti-aliasing or PBR texture sets | |
| with world-scale UVs. Full composer adoption is not an acceptance requirement. Existing rendering | |
| may be retained when matched evidence is stronger; individual library textures can also be used | |
| with the existing renderer. The kit works on the main thread and in a worker (no DOM use). | |
| ```js | |
| import {{ createRenderKit, qualityFromQuery }} from '../lib/render-kit/render-kit.js'; | |
| const kit = await createRenderKit({{ | |
| renderer, scene, camera, width, height, maxPixelRatio: devicePixelRatio, | |
| assetBase: new URL('../assets/', import.meta.url).href, | |
| quality: qualityFromQuery(location.search), // ?render=auto|off|low|medium|high|ultra, default auto | |
| environment: '<environment id>', // lighting only; the game's sky stays the background | |
| }}); | |
| kit.standardize(scene); // Lambert/Phong -> MeshStandardMaterial | |
| wall.material = kit.pbr('<material id>', {{ tileMeters: 3, tint: 0xd8cdb8 }}); | |
| kit.worldUV(wall); // constant texel size on boxes of any scale | |
| kit.configureSun(sun, {{ extent: 60 }}); // then kit.followSun(sun, player.position) per frame | |
| kit.addOverlay(viewmodelScene, viewmodelCamera); // first-person weapon or markers drawn after AO | |
| // frame: kit.render(dt) resize: kit.setSize(w, h, devicePixelRatio) camera swap: kit.setCamera(c) | |
| ``` | |
| - Materials (`assets/pbr/textures`, 1k, colour/normal/roughness/AO): | |
| {materials} | |
| - Environments (`assets/pbr/hdri`): | |
| {environments} | |
| - In a worker, send the page's `location.search` and `devicePixelRatio` with the canvas and pass them | |
| to `qualityFromQuery` and `maxPixelRatio`. | |
| - Match the reference, not a generic look: tint albedo to each surface's colour, set `exposure` and | |
| `environmentIntensity` so matched frames read with the same brightness, keep AO and bloom subtle. | |
| Keep an existing colour grade with `lut: '<url>.cube'` (applied after tone mapping). | |
| - `auto` preserves the same high profile on desktop and software rendering. First measure a short | |
| isolated trial at the existing viewport and drawing-buffer resolution. If software rendering | |
| cannot sustain it, retain the verified playable and investigate performance or the replay backend; | |
| do not lower quality to pass. An explicitly selected low profile is a separate diagnostic result, | |
| never evidence that the high profile passed. Record backend, resolved profile and resolution. | |
| - The environment is the ambient light: lower or remove existing hemisphere/ambient lights. | |
| - Before retrying a rejected integration, read its checkpoint and identify a changed cause | |
| (for example a measured bottleneck fix or a separately labelled backend experiment). Do not | |
| repeat the same chain after session rollover. Correct route, camera and major scene geometry | |
| before treating postprocessing as the solution to composition errors. | |
| - Compare a frozen pre-integration build with the trial at matched timestamps before keeping a change. | |
| `?render=off` alone is not the original look if integration also changes materials, UVs or lights. | |
| Preserve authored GLB materials and UVs; apply library materials to selected procedural surfaces. | |
| After integrating, run one full replay and check that max input lateness and | |
| dark-frame counts are no worse than before. | |
| - `lib/render-kit/` is reinstalled on every build round: configure it through options, do not edit | |
| its files. Record any texture you add yourself in `assets/pbr/library.json` with its licence.{notes}{missing} | |
| ### Matching the reference's look: fitted, not hand-tuned | |
| `lib/render-kit/look.js` (`createLook`, same options as `createRenderKit` plus `look: 'look.json'`) keeps | |
| sun direction, sky, haze, exposure, grade and every surface's colour, roughness, dirt and wetness in one | |
| parameter object. You make the discrete choices: indoors or outdoors (`sky.mode`), and what each surface | |
| is (`look.surface('road', {{ type: 'asphalt', color }})`, or `look.adopt(scene)` for the rest). Then | |
| `mcp__reference_replay__look_fit` finds the numbers: it renders your build from a replay's camera poses, | |
| compares with the reference at the same moments and searches the parameters until the frames agree, | |
| writing `look.json` and a reference/before/after sheet. Do not spend turns nudging light colours, | |
| exposure or material tints by eye: get geometry and surface types right, run `look_fit`, replay, read the | |
| scorecard's `look`. The defaults add no haze, grain or dirt, so nothing appears that the reference does | |
| not show. Details and the parameter list: the look section of `lib/render-kit/README.md`. | |
| """ | |
| def prepare_render_kit(prompt: str, *, candidate: Path, cache: Path | None = None) -> str: | |
| """Install the kit for a build round and append its instructions to the builder prompt.""" | |
| return prompt + builder_instructions(install(candidate, cache=cache)) | |
| def _main(argv: list[str]) -> int: | |
| if argv[:1] == ["fetch"]: | |
| result = fetch() | |
| print(json.dumps({"fetched": len(result["fetched"]), "failed": result["failed"]}, indent=1)) | |
| return 1 if result["failed"] else 0 | |
| if len(argv) == 2 and argv[0] == "install": | |
| report = install(Path(argv[1])) | |
| print(json.dumps({"kit": str(report.kit_dir), "three": report.three, "revision": report.three_revision, | |
| "materials": len(report.materials), "environments": len(report.environments), | |
| "missing": report.missing, "notes": report.notes}, indent=1)) | |
| return 0 | |
| print(__doc__) | |
| return 2 | |
| if __name__ == "__main__": | |
| raise SystemExit(_main(sys.argv[1:])) | |