Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Files and store: the player's files, the game's storage, user: assets (#109)

Evan (Yifeng) Wang6ef135174384
diff --git a/.gitignore b/.gitignore
index 8302ae5..d630595 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,6 +8,8 @@ dist/
out/
target/
+# A game's store in `threert-render play` (`--store`, by default under the asset root).
+.threert/
/assets
playground/vendor/
diff --git a/README.md b/README.md
index 9421b99..7ce6b98 100644
--- a/README.md
+++ b/README.md
@@ -180,6 +180,7 @@ npm run test:render # the r
- [`docs/RUNTIME.md`](docs/RUNTIME.md): how scene code runs in the engine: setup, handlers, world handlers, frame scripts, physics
- [`docs/MATERIAL_FUNCTIONS.md`](docs/MATERIAL_FUNCTIONS.md): a WGSL body on a material, run by the path tracer at every hit
- [`docs/VOXEL.md`](docs/VOXEL.md): the voxel engine, measured on a destructible level
+- [`docs/PORTS.md`](docs/PORTS.md): a game written once for ThreeRT, and ports of it to devices the engine does not run on
- [`docs/COMPARE.md`](docs/COMPARE.md): three.js at its strongest against ThreeRT, in frame rate and image quality
- [`docs/PARITY.md`](docs/PARITY.md): Kabukichō against the same brief built in UE 5.8, and what the engine gained from it
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), [`docs/REPORT.md`](docs/REPORT.md): the serverless gameplay and rendering runtime the engine was built for
diff --git a/docs/PORTS.md b/docs/PORTS.md
new file mode 100644
index 0000000..a0753ec
--- /dev/null
+++ b/docs/PORTS.md
@@ -0,0 +1,113 @@
+# Ports: RT-first games on devices the engine does not run on
+
+A game for ThreeRT is written once, and that version is the game. Devices the engine cannot run on get a port: a
+build of the same game for that device, made by its own engine, which follows the canonical game and says how far.
+This document is the convention for such ports: where they live, how a game's manifest lists them, what they take
+from the canonical game, and how to add a device.
+
+## The canonical game
+
+A game is written once for ThreeRT: TypeScript on `@threert/scene` and `@threert/gameplay`. That version is
+canonical. Its rules, its tables (weapons, rounds, economy, anything with numbers in it) and its maps are the game;
+everything else follows them.
+
+From the same code it runs:
+
+- **path traced** in the ThreeRT clients;
+- **raster, rays off**, on GPUs without ray tracing (the same scene and the same engine, with the rays switched off);
+- **as three.js** in a browser (`tools/three/view.ts`), with the engine's own physics as wasm.
+
+So "the RT version" and "the non-RT version" are not two games: they share every line of the game's code, and a
+change to the game is a change to all three at once. Nothing in this document is about them.
+
+## Ports
+
+Some devices cannot run the engine at all: the PSP, the PS Vita, the Nintendo 3DS, old phones, anything without a
+GPU the engine can drive or the memory a JavaScript runtime needs. Such a device gets a **port**: an engine made for
+that device, typically generated for it by an agent, that plays the game there.
+
+- A port lives in the game's own repository, in `ports/<engine>/`: `ports/pocket3d/` holds the Pocket3D builds of a
+ game. One directory per engine, whatever devices that engine reaches.
+- A port may have a gameplay implementation of its own (in Rust, in C, in whatever its device needs). It does not
+ have to share code with the canonical game, and usually cannot.
+- The canonical game decides. Tables and rules are ported from it, not invented for the port; where the two
+ disagree, the port is wrong. A port that has to change a rule for its device (fewer players, a smaller map, a
+ coarser tick) says so.
+- Every port's `README.md` says which version of the canonical game it follows (a tag or a commit of the
+ repository) and what it leaves out.
+
+## The manifest: `ports` in `threert.config.json`
+
+A game lists its ports in its `threert.config.json`, under `ports`:
+
+```json
+{
+ "ports": [
+ {
+ "id": "pocket3d-psp",
+ "title": "PSP",
+ "platforms": ["psp"],
+ "dir": "ports/pocket3d",
+ "engine": "pocket3d",
+ "build": "make psp",
+ "artifact": "build/psp/EBOOT.PBP",
+ "status": "playable",
+ "notes": "Two players over ad hoc Wi-Fi; no bots."
+ }
+ ]
+}
+```
+
+| field | | |
+| --- | --- | --- |
+| `id` | string | the port's name, unique in the game |
+| `title` | string | what a store page shows ("PSP", "PS Vita", "3DS") |
+| `platforms` | string[] | the devices it runs on |
+| `dir` | string | its directory, relative to the game's root (`ports/<engine>`) |
+| `engine` | string | the engine that builds it |
+| `build` | string, optional | a command, run in `dir`, that builds it |
+| `artifact` | string, optional | the path of the downloadable build, relative to `dir` |
+| `status` | `"playable"` \| `"experimental"` \| `"retired"` | how far it is |
+| `notes` | string, optional | anything else a player should know |
+
+The field is descriptive. It is for tools and store pages, to show where else the game runs, and later to offer the
+builds for download. The ThreeRT CLI reads it and lists a game's ports; publishing a game does not upload its ports
+yet. Nothing in the engine reads it.
+
+## What a port reuses
+
+A port reuses what it can of the canonical game, so that the two stay one game:
+
+- **Maps in their source form.** A port cooks maps itself, for its own device, from what the canonical game cooks
+ them from: when a game plays maps from the player's own files (BSPs from their copy of another game), the port's
+ own cooker reads the same files. It does not take the canonical game's converted output, which is made for another
+ renderer.
+- **Assets whose licences allow it.** Models, textures and sounds under licences that permit redistribution and
+ modification may be reduced for the device (fewer triangles, smaller textures, lower sample rates). Anything else
+ stays out.
+- **Exported tables.** Where the port's language allows, it reads the tables the canonical game exports as JSON
+ (weapons, damage, prices, timings) rather than copying the numbers by hand, so a change to the game reaches the port
+ at its next build.
+- **The same names** for weapons, modes and maps, so that a player and a server speak of the same things on every
+ device.
+
+## Adding a device
+
+- **One directory per engine** (`ports/<engine>/`), with everything that engine needs inside it.
+- **Its own toolchain, pinned inside it**: the SDK's version, the compiler's, a container or a setup script, so the
+ port builds the same in a year as it does today, and the rest of the repository needs none of it.
+- **Its own CI workflow**, with path filters on its directory (and on the tables it reads), so a change to the port
+ runs the port's checks and a change elsewhere does not.
+- **A README** with the steps to build it, to run it in an emulator, and to run it on the device, and with the
+ version of the canonical game it follows and what it leaves out.
+- **Goldens from an emulator** where one exists: frames of known scenes and the results of scripted rounds, checked in
+ CI, so a port is held to numbers rather than to someone's impression of it.
+- **No copyrighted game data, ever**, neither in the repository nor in a published build. A port that plays content
+ from another game cooks it at build time from the player's own copy, on the player's machine.
+
+## Player content
+
+Importing content the player owns happens on the device, inside the game's sandbox: the player picks the files, the
+game reads and converts them there, and keeps the result in its own storage on that device. It never leaves the
+device. In ThreeRT this is the host channel's `files.*` and `store.*` and `user:` assets ([`RUNTIME.md`,
+"Files"](RUNTIME.md#files)); a port does the same with what its device offers, by the same rule.
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 06a2024..c5b4b79 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -388,6 +388,7 @@ Messages a game posts:
| `net.fetch` | `id`, `url`, `method?`, `headers?`, `body?` | one HTTP request (`GET` unless `method`); answers `net.fetched` |
| `hud` | `hud` | draws the HUD it describes ("HUD", below). `hud.set` posts it; a game does not post it by hand |
| `audio.*` | below | plays sound ("Sound", below), with the engine's `audio` module. `audio.play` and the rest post them |
+| `files.*`, `store.*` | below | reads what the player picked, keeps the game's files on the device ("Files", below); each request answered once |
Messages an app sends:
@@ -397,7 +398,8 @@ Messages an app sends:
| `net.messages` | `id`, `list: string[]` | the text messages that arrived on `id` since the last frame, in order: one batch a socket a frame |
| `net.closed` | `id`, `code`, `reason` | the socket closed (the close frame's code; 1005 without one), or failed (1006, `reason` says why) |
| `net.fetched` | `id`, `status`, `body`, `error?` | the response's status and body as text; `status` 0 and `error` when the request failed |
-| `launch` | `params: { room?, name?, ... }` | once, after setup: how the app opened the game. Kept as `host.launch` (`{}` before it comes, and for an app that sends none) |
+| `launch` | `params: { room?, name?, ... }`, `caps?: string[]` | once, after setup: how the app opened the game. Kept as `host.launch` (`{}` before it comes, and for an app that sends none); `caps`, the families of requests the app answers (`"files"`, `"store"`), as `host.caps` (`[]` before, and for an app that lists none) |
+| `files.picked`, `files.data`, `store.*` | below | the answers to `files.*` and `store.*` ("Files", below) |
| `input` | below | once a frame, before the frame script, to a game that asked for input. The node host keeps it; it has no listeners |
`id` is the game's own name for a socket or a request (a string); the app's answers carry it back. Messages are text:
@@ -405,7 +407,8 @@ a binary WebSocket frame is dropped. Which addresses a game may reach is the app
**What an app does** (Rust: whoever holds the `GameSession`; `renderer/src/view.rs` is the example to read):
-1. After the scene is built: `session.host_messages(&mut core, &[host::launch_message(params)])`.
+1. After the scene is built: `session.host_messages(&mut core, &[host::launch_message(params)])`, or
+ `launch_message_with_caps(params, &services.caps())` for an app that answers `files.*` / `store.*`.
2. Every frame, before `session.frame`: one `host_messages` with the frame's `input` message (if the game asked:
`session.host.pointer()` is `Some("look")` or `Some("free")`) and what its services have for the game (a
`net.messages` batch a socket, answers). An empty batch is no entry at all.
@@ -419,11 +422,11 @@ a binary WebSocket frame is dropped. Which addresses a game may reach is the app
The apps in this repository:
-| app | input | `net.*` | `launch` | HUD | sound |
-| --- | --- | --- | --- | --- | --- |
-| `threert-render play` (`view.rs`) | keys by physical position, mouse buttons, wheel; the pointer captured for `"look"` (a click; Esc lets go, Esc again quits) | WebSockets and HTTP on a thread each (`src/net.rs`: tungstenite and ureq on rustls; text frames of at most 1 MiB, bodies of at most 4 MiB, 16 sockets, 32 requests at once), any address | `--launch '{"room":"K7Q4MZ"}'` | not drawn; `--hud-log` prints each description | played (`audio` feature) |
-| `threert-render live` (`live/session.rs`) | whatever the driver sends | none: the driver is the app | `--launch` | on stdout with every other post | on stdout: the driver's |
-| the three.js view (`tools/three/view.ts`, `host.ts`, `hud.ts`) | keyboard, mouse, the Pointer Lock API | `WebSocket`, `fetch` (the browser's rules: same-origin policy, CORS) | the page's query (`?room=K7Q4MZ&name=Ada`) | DOM over the canvas | Web Audio by the same rules (`audio.ts`) |
+| app | input | `net.*` | `launch` | HUD | sound | files, store |
+| --- | --- | --- | --- | --- | --- | --- |
+| `threert-render play` (`view.rs`) | keys by physical position, mouse buttons, wheel; the pointer captured for `"look"` (a click; Esc lets go, Esc again quits) | WebSockets and HTTP on a thread each (`src/net.rs`: tungstenite and ureq on rustls; text frames of at most 1 MiB, bodies of at most 4 MiB, 16 sockets, 32 requests at once), any address | `--launch '{"room":"K7Q4MZ"}'`; `caps: ["files", "store"]` | not drawn; `--hud-log` prints each description | played (`audio` feature) | `--pick` and `--store` (`src/userfiles.rs`) |
+| `threert-render live` (`live/session.rs`) | whatever the driver sends | none: the driver is the app | `--launch`, `--caps files,store` | on stdout with every other post | on stdout: the driver's | the driver's; `--store` is where `user:` assets are |
+| the three.js view (`tools/three/view.ts`, `host.ts`, `hud.ts`) | keyboard, mouse, the Pointer Lock API | `WebSocket`, `fetch` (the browser's rules: same-origin policy, CORS) | the page's query (`?room=K7Q4MZ&name=Ada`); no `caps` | DOM over the canvas | Web Audio by the same rules (`audio.ts`) | none |
- `live` speaks the channel as JSON lines, so a game's use of it is testable without a window: on stdin
`{"cmd":"host","messages":[{"t":"net.opened","id":"room"}, ...]}`, on stdout one line `{"host":[...]}` with what
@@ -437,7 +440,8 @@ The apps in this repository:
natively, without the renderer and without wasm-bindgen), which `node tools/three/open.ts <game>` builds for a
game whose source names the physics. Bodies move and `intersectPhysics` / `Shapecaster` answer as in the renderer.
Without the module the view is the baseline it was: bodies stay where the scene put them.
-- Checked: `packages/gameplay/test/host.test.ts` (the channel, input, the HUD's change detection, in Node);
+- Checked: `packages/gameplay/test/host.test.ts` (the channel, input, the HUD's change detection, in Node),
+ `files.test.ts` (files, store, caps, base64, `sliced`);
`renderer/src/host.rs` and `script.rs` tests (the queue's bounds, a batch's delivery, the input message);
`node tools/host-echo.ts` (`games/host/echo.game.ts` in `live` with the script as the app, in `play` against a
WebSocket and HTTP server on the machine, and in the three.js view in Chrome); `node tools/fps-arena.ts` and
@@ -606,6 +610,144 @@ frame(f) {
`tools/three/test/audio.test.ts`; its low pass is a biquad, the one difference), resumed on the page's first key or
click as browsers require. The engine's library in a browser (wasm32) has no `audio` module.
+### Files
+
+A game may let its player bring content they own: OpenStrikeRT, for one, plays Counter-Strike 1.x maps from the
+player's own copy of that game, converted to RT maps. Such files never leave the player's device. The player picks
+them, the game reads and converts them inside its sandbox, keeps the result in the app's storage on that device, and
+shows it as an asset. Nothing is uploaded, published or sent to other players.
+
+```ts
+import { GLTFModel } from "@threert/scene";
+import { files, host, sliced, store } from "@threert/gameplay";
+
+host.on("launch", () => { canImport = files.available() && store.available(); }); // the app's caps
+
+async function importMaps() { // from the frame script (a menu's button)
+ const picked = await files.pick({ mode: "folder", accept: [".bsp", ".wad"], title: "Your Counter-Strike folder" });
+ if (!picked) return; // the player closed the picker
+ for (const e of picked.entries.filter((e) => e.path.endsWith(".bsp"))) {
+ const bsp = await files.read(picked.pick, e.path); // Uint8Array, the whole file
+ jobs.push({ name: e.path, job: sliced(convert(bsp)) }); // convert: a generator, it yields often
+ }
+}
+function frame() { // the game's frame script
+ const r = jobs[0]?.job.step(8); // 8 ms of conversion this frame
+ if (r?.done) { void store.write(`maps/${slug}/map.glb`, r.value as Uint8Array); jobs.shift(); }
+}
+scene.add(new GLTFModel(store.uri("maps/de_x/map.glb"))); // "user:maps/de_x/map.glb"
+```
+
+Two families of requests on the host channel (`packages/gameplay/src/files.ts` wraps them as promises). Binary data
+travels as base64 strings. `id` is the game's name for the request; every request gets exactly one answer with the
+same `id`.
+
+- **Capabilities.** An app that answers them lists them in the `launch` message: `{ t: "launch", params, caps:
+ ["files", "store"] }`. `host.caps` is that list: `[]` until launch, and for an app that sends none. A game must not
+ wait for an answer of a family the app did not list: `files.available()` / `store.available()` say whether it did,
+ and the package refuses a request of an unlisted family at once (a `HostRequestError` with `reason:
+ "unsupported"`), without posting it. `caps` comes after setup, so a game asks in its `launch` listener or later.
+
+**`files.*`: what the player picked (read only).**
+
+| game → app | app → game |
+| --- | --- |
+| `{ t: "files.pick", id, mode: "folder" \| "files", accept?: string[], title?: string }` | `{ t: "files.picked", id, ok: true, pick, name, entries: [{ path, size }] }` or `{ t: "files.picked", id, ok: false, reason }` |
+| `{ t: "files.read", id, pick, path }` | `{ t: "files.data", id, ok: true, data, size }` or `{ ..., ok: false, reason }` |
+
+- `accept`: lower-case extensions with the dot (`[".bsp", ".wad", ".rad"]`); a file matches without regard to case.
+ No `accept`: every file.
+- `mode: "folder"`: the player chooses a folder; `entries` are the matching files under it, recursively (at most 6
+ levels, at most 4,000 entries, hidden files and directories left out), `path` relative to the folder with `/`
+ separators. `mode: "files"`: the player chooses one or more files; `entries` are those, `path` = the file's name.
+- `pick` is an opaque string naming the grant; `name` is what to show (the folder's or the file's name). A grant
+ lasts for the game session (until the game is closed or reloaded).
+- `reason`: `"canceled"` (the player closed the picker), `"busy"` (a picker is already open), `"unsupported"`,
+ `"denied"`, or a sentence.
+- `files.read`: `path` must be one of the grant's entries (anything else: `ok: false, reason: "denied"`). `data` is
+ the whole file in base64. Files larger than 64 MiB are refused (`reason: "too large"`).
+- `files.pick(o)` resolves to `{ pick, name, entries }`, or `null` when the player canceled; `files.read(pick, path)`
+ to the file's bytes. Any other `ok: false` rejects with a `HostRequestError` whose `reason` is the app's.
+
+**`store.*`: the app's own storage for this game (read and write, persistent, local).**
+
+| game → app | app → game |
+| --- | --- |
+| `{ t: "store.write", id, path, data?: base64, text?: string }` | `{ t: "store.done", id, ok, reason? }` |
+| `{ t: "store.read", id, path, as: "text" \| "base64" }` | `{ t: "store.data", id, ok: true, text? / data?, size }` or `{ ..., ok: false, reason: "absent" \| ... }` |
+| `{ t: "store.list", id, prefix?: string }` | `{ t: "store.listed", id, ok: true, entries: [{ path, size }] }` |
+| `{ t: "store.remove", id, path }` | `{ t: "store.done", id, ok, reason? }`: a file, or a directory and everything in it |
+
+- `path`: relative, `/`-separated, segments of `[A-Za-z0-9._-]`, no `.` or `..` segment, no leading `/`, at most 200
+ characters. Directories are made as needed. The package checks a path before it posts anything (a `TypeError`);
+ the app checks it again (`ok: false`).
+- `store.write` takes `data` (bytes in base64) or `text` (written as UTF-8), a file of at most 64 MiB. Writes are
+ atomic: a temporary file beside the file, renamed over it, so a reader sees the old file or the new one.
+ `store.read` with `as: "text"` answers `reason: "not text"` for a file that is not UTF-8. `store.list` lists the
+ files (not directories) whose path starts with `prefix` (a plain string: `"maps/"` is everything under maps),
+ sorted by path. `store.remove` of nothing is `ok: true`.
+- One storage per game identity: a published app by its name (`openstrike`), a development project by its project
+ id. It survives app updates and new versions of the game, is never uploaded, and is removed with the game's data.
+- Quota: 1 GiB per game (a write past it: `ok: false, reason: "quota"`).
+- `store.write(path, bytes | text)`, `store.read(path)` (bytes, or `null` when absent), `store.readText(path)`,
+ `store.list(prefix?)`, `store.remove(path)`; `store.uri(path)` is `"user:" + path`.
+
+**Assets from the store: `user:` URIs.** A stored file is an asset of the scene under the URI `user:<path>`:
+`new GLTFModel("user:maps/de_dust2/map.glb")`, a texture's file, a procedural asset, a voxel level's objects, a sound
+(`audio.play("user:sounds/x.wav")`) likewise. The engine resolves `user:` against the store's directory the app gave
+it (`threert_render::files::set_user_root`, before the scene is built; `files::asset_path` is the one place every
+reader of a scene's files goes through), and a path after `user:` must be a store path, so nothing outside the store
+is reached. Without a user root a `user:` asset is missing, as a missing file is. `GameSession::files()` lists `user:`
+assets with the rest: an app that fetches a scene's files from elsewhere (a browser page, a client that downloads a
+package) leaves them out, they are on the device. The browser builds have no store: a `user:` asset is missing there.
+
+**Large messages.** A `store.write` carries a whole file: its post may be up to 96 MiB of JSON text (any other message
+stops at 1 MiB), and the queue holds at most 192 MiB. In the engine's runtime the package's base64 is native
+(`__host_base64_encode` / `__host_base64_decode`, in `script.rs`): a 64 MiB `files.data` reaches a listener and is
+decoded in about 130 ms of an entry's 1 s (measured on a Mac by `script.rs` `files_cross_the_host_channel_as_base64`). In Node it
+is `Buffer`'s, in a page `atob` / `btoa`.
+
+**Long work: `sliced(job)`.** A conversion takes longer than a frame. `sliced(iterator)` runs a generator's work a
+slice at a time: `job.step(ms)` calls `next()` until `ms` milliseconds have passed (at least once) or the job has
+ended, and returns `{ done, value }`: the last value yielded (its progress) while it runs, the value it returned once
+it is done (and from then on). A job that throws ends; its step throws. Steps are timed by the runtime's monotonic
+clock (`performance.now()`), not `Date.now()`, which is the event's fixed time inside listeners and handlers. A step
+stops only between two `yield`s: yield often.
+
+- **Requests are presentation**, as sound is: post them from the frame script and from host listeners (and the code
+ after their `await`s), never from a handler, which is replayed and verified. What the player picked and what the
+ game stored are this device's; nothing of it is state a room agrees on.
+
+**The apps.** `threert-render play` answers both families for development and tests (`src/userfiles.rs`: the work on
+a thread of its own, one request after another in the order they were posted, the answers taken once a frame):
+
+```sh
+threert-render play game.js --assets games/openstrike \
+ --store /tmp/openstrike-store \
+ --pick "$HOME/Games/cstrike,$HOME/Downloads/de_x.bsp"
+```
+
+- `--store <dir>`: the game's store (default `<assets>/.threert/store`), also the user root of `user:` assets.
+- `--pick <dir|file>[,<dir|file>...]` answers `files.pick` requests in order with those paths instead of a dialog: a
+ folder for `mode: "folder"`; a file, or a folder standing for the files in it (not below), for `mode: "files"`.
+ After the last one each pick is `"canceled"`; with no `--pick` at all each is `"unsupported"`. The launch lists
+ `caps: ["files", "store"]` either way.
+- On stdout (`{"type":"host","messages":[...]}`) a `store.write`'s `data` / `text` is its length (`dataLength`).
+- `threert-render live` is driven by a program that is the app: `--caps files,store` lists what that program answers
+ (it answers on stdin with `{"cmd":"host","messages":[...]}`), and `--store <dir>` is where the engine reads `user:`
+ assets from.
+- An app that embeds the engine's library can take `threert_render::userfiles` as it is: `Store` (paths, quota,
+ atomic writes), `Grant` (a folder's or files' entries; reads inside it), `Requests` (the messages' answers, with a
+ `Picker` that asks the player) and `UserFiles` (all of it as `HostServices`, on its thread), and
+ `files::set_user_root` with the game's store directory.
+- Checked: `renderer/src/userfiles.rs` tests (paths refused: `..`, absolute, bad characters, too long; the quota;
+ atomic writes under a concurrent reader; `--pick` answers in order; `files.read` refused outside the grant; hidden
+ files, depth and count bounds), `files.rs` (`user:` models and sounds from the store, never outside it, missing
+ without a root), `script.rs` (base64 natively, the size bounds, a 64 MiB file within a budget), `host.rs` (caps in
+ `launch`, services as one), `packages/gameplay/test/files.test.ts`; and `games/host/files.game.ts` in `play`
+ (picked a folder, read a model from it, converted it across frames, stored it, shown from the store; a second run
+ shows it from the store without asking).
+
## The runtime's shape: Rust owns the world, the script engine is a guest
Decided by the user on 2026-11-10, with the measurements below.
diff --git a/games/host/files.game.ts b/games/host/files.game.ts
new file mode 100644
index 0000000..1ac24b0
--- /dev/null
+++ b/games/host/files.game.ts
@@ -0,0 +1,103 @@
+// The player's files and the game's store in one small game (docs/RUNTIME.md "Files"): the player picks a folder, the
+// game reads a model from it, "converts" it a slice a frame (a copy, standing for a real conversion), keeps the result
+// in its store, and shows it from there as a `user:` asset. Nothing leaves the device.
+//
+// - Only where the app answers both families (`host.caps`, from the launch message): elsewhere the game says so on
+// its HUD and shows the cube alone.
+// - A second run finds the model in the store already and shows it without asking.
+//
+// node tools/bundle-game.ts games/host/files.game.ts -o out/bundles/host-files.js
+// renderer/target/release/threert-render play out/bundles/host-files.js --assets . \
+// --store /tmp/host-files-store --pick <a folder with a .glb or .gltf in it>
+import { BoxGeometry, DirectionalLight, GLTFModel, Mesh, MeshStandardMaterial, PerspectiveCamera, Scene, SkyAtmosphere } from "@threert/scene";
+import { defineGame, files, host, HostRequestError, hud, sliced, store, type Sliced } from "@threert/gameplay";
+
+const STORED = "models/imported.glb";
+let status = "no files here";
+let scene: Scene | null = null;
+let job: Sliced<Uint8Array> | null = null;
+
+/** The stand-in for a conversion: the bytes copied 64 KiB a step. */
+function* convert(bytes: Uint8Array): Generator<number, Uint8Array> {
+ const out = new Uint8Array(bytes.length);
+ for (let i = 0; i < bytes.length; i += 1 << 16) {
+ out.set(bytes.subarray(i, i + (1 << 16)), i);
+ yield i / bytes.length;
+ }
+ return out;
+}
+
+function show() {
+ const model = new GLTFModel(store.uri(STORED));
+ scene?.add(model);
+ status = "shown from the store";
+ console.log(`files: shown ${store.uri(STORED)}`);
+}
+
+async function begin() {
+ const kept = await store.list("models/");
+ console.log(`files: the store has ${JSON.stringify(kept)}`);
+ if (kept.some((e) => e.path === STORED)) return show();
+ status = "picking";
+ const picked = await files.pick({ mode: "folder", accept: [".glb", ".gltf"], title: "A folder with a model" });
+ if (!picked) {
+ status = "canceled";
+ return;
+ }
+ console.log(`files: picked ${picked.name}: ${JSON.stringify(picked.entries)}`);
+ const first = picked.entries[0];
+ if (!first) {
+ status = "no model in it";
+ return;
+ }
+ const bytes = await files.read(picked.pick, first.path);
+ console.log(`files: read ${first.path}, ${bytes.length} bytes`);
+ status = "converting";
+ job = sliced(convert(bytes));
+}
+
+async function keep(bytes: Uint8Array) {
+ await store.write(STORED, bytes);
+ await store.write("models/imported.json", JSON.stringify({ from: "picked", bytes: bytes.length }));
+ console.log(`files: stored ${await store.readText("models/imported.json")}`);
+ show();
+}
+
+host.on("launch", () => {
+ console.log(`files: caps ${JSON.stringify(host.caps)}`);
+ if (files.available() && store.available()) begin().catch((e: unknown) => (status = e instanceof HostRequestError && e.reason === "unsupported" ? "nothing to pick from" : `failed: ${String(e)}`));
+});
+
+export default defineGame({
+ state: {},
+ setup: () => {
+ scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 90000);
+ sun.setSunAngles(50, 215);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+ const camera = new PerspectiveCamera(45, 16 / 9, 0.1, 100);
+ camera.position.set(3, 2.5, 6);
+ camera.lookAt(0, 1, 0);
+ camera.setManualExposure(14);
+ const ground = new Mesh(new BoxGeometry(12, 0.2, 12), new MeshStandardMaterial({ name: "ground", color: 0x6f7468, roughness: 0.95 }));
+ ground.position.y = -0.1;
+ const cube = new Mesh(new BoxGeometry(0.5, 0.5, 0.5), new MeshStandardMaterial({ name: "cube", color: 0x3d7ec8, roughness: 0.6 }));
+ cube.position.set(-1.5, 0.25, 0);
+ scene.add(camera, ground, cube);
+ return { scene, camera, options: { name: "host-files", width: 1280, height: 720, preset: "cinematic" as const } };
+ },
+ handlers: {},
+ frame() {
+ if (job) {
+ const r = job.step(4);
+ if (r.done) {
+ const out = r.value!;
+ job = null;
+ status = "storing";
+ keep(out).catch((e: unknown) => (status = `failed: ${String(e)}`));
+ } else status = `converting ${Math.round((r.value as unknown as number) * 100)} %`;
+ }
+ hud.set({ items: [{ type: "text", anchor: "top-left", label: "Files", text: status }] });
+ },
+});
diff --git a/packages/gameplay/README.md b/packages/gameplay/README.md
index 0019248..318f150 100644
--- a/packages/gameplay/README.md
+++ b/packages/gameplay/README.md
@@ -63,6 +63,7 @@ export default defineGame({
- **World handlers** (`on`) reach the engine's own world: physics, a ray cast into the scene, objects added and removed as an event arrives.
- **Input, a HUD and the app.** A game with `pointer: "look"` reads the keys and the mouse every frame (`f.input.move`, `f.input.look`, `f.input.pressed("Space")`); `hud.set(...)` describes a crosshair, figures, bars and a scoreboard for the app to draw; `host.post` / `host.on` reach what the app owns (a WebSocket, an HTTP request, how the game was opened).
- **Sound.** `audio.play("assets/sounds/shot.ogg", { at: muzzle, pitch: 1.04 })` plays a file of the game at a place in the world (or, without `at`, in the player's head); the engine decodes, places and mixes it the same way on every platform, with the camera as the ears. `audio.preload`, `audio.stop(key)` and `audio.move(key, at)` for the rest.
+- **The player's files.** Where the app allows it (`files.available()`), `files.pick({ mode: "folder", accept: [".bsp"] })` lets the player choose content they own and `files.read(pick, path)` reads it; `store.write` / `read` / `list` / `remove` keep what the game made of it on the device, and `store.uri(path)` (`"user:maps/x.glb"`) shows it as a model or a texture. Nothing leaves the device. `sliced(generator)` runs a long conversion a few milliseconds a frame.
How scene code runs in the engine is in [RUNTIME.md](https://github.com/meshy-dev/ThreeRT/blob/main/docs/RUNTIME.md).
diff --git a/packages/gameplay/src/files.ts b/packages/gameplay/src/files.ts
new file mode 100644
index 0000000..7b013cd
--- /dev/null
+++ b/packages/gameplay/src/files.ts
@@ -0,0 +1,357 @@
+// Files: what the player picked (read only) and the game's own storage on this device (read and write). A game may let
+// its player bring content they own (a map from their copy of another game): the player picks it, the game reads and
+// converts it in its sandbox, keeps the result in its store, and shows it as an asset (`user:` URIs). Nothing leaves
+// the device. docs/RUNTIME.md "Files" is the contract; these are requests on the host channel (host.ts), each
+// answered once, wrapped as promises.
+//
+// host.on("launch", () => { canImport = files.available() && store.available(); }); // host.caps, after launch
+// const picked = await files.pick({ mode: "folder", accept: [".bsp", ".wad"], title: "Your Counter-Strike folder" });
+// if (picked) for (const e of picked.entries) if (e.path.endsWith(".bsp")) {
+// const bsp = await files.read(picked.pick, e.path); // Uint8Array
+// const job = sliced(convert(bsp)); // a generator: a little work a step
+// ... frame(f) { const r = job.step(8); if (r.done) await store.write("maps/de_x/map.glb", r.value); }
+// }
+// scene.add(new GLTFModel(store.uri("maps/de_x/map.glb"))); // "user:maps/de_x/map.glb"
+//
+// - An app lists what it answers in the `launch` message (`host.caps`). Before launch, and in an app that answers
+// neither, `available()` is false and a request is refused at once (an Error with `reason: "unsupported"`): a game
+// offers the import only where it can be done.
+// - Files cross the channel as base64: natively encoded and decoded in the engine's runtime, by Buffer in Node, by
+// atob / btoa in a page. One file is at most 64 MiB either way.
+// - Requests are presentation, like sound: make them from the frame script and host listeners (and the code after
+// their awaits), never from a handler, which is replayed.
+// - `sliced(job)` runs long work (a conversion) a few milliseconds a frame, so the game goes on while it runs.
+
+import { host } from "./host.ts";
+
+/** A file the player picked: its path in the pick (`maps/de_dust2.bsp`; a file's name for picked files), its size. */
+export interface FileEntry {
+ path: string;
+ size: number;
+}
+
+/** What a pick allowed: `pick` names the grant for `files.read`, `name` is the folder's or the file's name to show. */
+export interface Picked {
+ pick: string;
+ name: string;
+ entries: FileEntry[];
+}
+
+export interface PickOptions {
+ /** A folder (its matching files, to 6 levels, at most 4,000) or one or more files. */
+ mode: "folder" | "files";
+ /** Lower-case extensions with the dot (`[".bsp", ".wad"]`), matched without case; none: every file. */
+ accept?: string[];
+ /** What the picker says it is for. */
+ title?: string;
+}
+
+/** A request the app answered with `ok: false` (`reason`: "denied", "too large", "quota", "unsupported", a sentence). */
+export class HostRequestError extends Error {
+ readonly reason: string;
+ constructor(request: string, reason: string) {
+ super(`${request}: ${reason}`);
+ this.name = "HostRequestError";
+ this.reason = reason;
+ }
+}
+
+export interface Files {
+ /** The app answers `files.*` (its `launch` listed "files"). */
+ available(): boolean;
+ /** Asks the player; null when they closed the picker. */
+ pick(options: PickOptions): Promise<Picked | null>;
+ /** A file of a pick: one of its entries, the whole file. */
+ read(pick: string, path: string): Promise<Uint8Array>;
+}
+
+export interface UserStore {
+ /** The app answers `store.*` (its `launch` listed "store"). */
+ available(): boolean;
+ /** Writes the file `path` whole (bytes: a Uint8Array or any view's; a string as UTF-8), atomically; directories
+ * are made as needed. */
+ write(path: string, data: Uint8Array | ArrayBufferView | string): Promise<void>;
+ /** The file's bytes; null when there is none. */
+ read(path: string): Promise<Uint8Array | null>;
+ /** The file as UTF-8 text; null when there is none. */
+ readText(path: string): Promise<string | null>;
+ /** The files whose path starts with `prefix` (`"maps/"`: everything under maps), sorted by path. */
+ list(prefix?: string): Promise<FileEntry[]>;
+ /** Removes the file, or the directory and everything in it (nothing there is not an error). */
+ remove(path: string): Promise<void>;
+ /** The asset URI of a stored file, for a model or a texture: `"user:" + path`. */
+ uri(path: string): string;
+}
+
+/** The most bytes of a file, either way. */
+export const MAX_FILE = 64 << 20;
+
+/** Why `path` is not a store path (relative, `/`-separated, segments of A-Z a-z 0-9 . _ -, no `.` / `..`, at most 200
+ * characters), or null. */
+export function storePathError(path: unknown): string | null {
+ if (typeof path !== "string" || path === "") return "a store path is a non-empty string";
+ if (path.length > 200) return "a store path is at most 200 characters";
+ for (const seg of path.split("/")) {
+ if (seg === "" || seg === "." || seg === "..") return `"${path}": a store path is relative, with no empty, "." or ".." segment`;
+ if (!/^[A-Za-z0-9._-]+$/.test(seg)) return `"${path}": a store path's segments are of A-Z a-z 0-9 . _ -`;
+ }
+ return null;
+}
+
+// ------------------------------------------------------------------------------------------------ base64
+
+type Natives = {
+ __host_base64_encode?: (bytes: Uint8Array) => string;
+ __host_base64_decode?: (text: string) => Uint8Array;
+ Buffer?: { from(a: ArrayBufferLike | string, offset?: number | string, length?: number): Uint8Array & { toString(enc: string): string } };
+ btoa?: (s: string) => string;
+ atob?: (s: string) => string;
+};
+
+const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+/** Bytes as base64: natively where the runtime has it, else in script. */
+export function toBase64(bytes: Uint8Array, natives: Natives = globalThis as Natives): string {
+ if (natives.__host_base64_encode) return natives.__host_base64_encode(bytes);
+ if (natives.Buffer) return natives.Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
+ if (natives.btoa) {
+ let s = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return natives.btoa(s);
+ }
+ let out = "";
+ for (let i = 0; i < bytes.length; i += 3) {
+ const n = (bytes[i]! << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
+ out += ALPHABET[n >> 18]! + ALPHABET[(n >> 12) & 63]! + (i + 1 < bytes.length ? ALPHABET[(n >> 6) & 63]! : "=") + (i + 2 < bytes.length ? ALPHABET[n & 63]! : "=");
+ }
+ return out;
+}
+
+/** Base64 as bytes. */
+export function fromBase64(text: string, natives: Natives = globalThis as Natives): Uint8Array {
+ if (natives.__host_base64_decode) return natives.__host_base64_decode(text);
+ if (natives.Buffer) {
+ const b = natives.Buffer.from(text, "base64");
+ return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
+ }
+ if (natives.atob) {
+ const s = natives.atob(text);
+ const out = new Uint8Array(s.length);
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
+ return out;
+ }
+ const clean = text.replace(/=+$/, "");
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
+ let buf = 0, bits = 0, k = 0;
+ for (let i = 0; i < clean.length; i++) {
+ const v = ALPHABET.indexOf(clean[i]!);
+ if (v < 0) throw new Error("base64: not a base64 character");
+ buf = ((buf << 6) | v) & 0xffffff;
+ bits += 6;
+ if (bits >= 8) {
+ bits -= 8;
+ out[k++] = (buf >> bits) & 255;
+ }
+ }
+ return out;
+}
+
+// ------------------------------------------------------------------------------------------------ requests
+
+type Pending = { request: string; resolve: (m: Answer) => void; reject: (e: Error) => void };
+type Answer = { t: string; id: string; ok?: boolean; reason?: string; [k: string]: unknown };
+
+/** One table of requests a runtime (a second copy of this module finds the first's, as the channel does). */
+const shared = globalThis as { __threert_requests?: { n: number; pending: Map<string, Pending>; listening: Set<string> } };
+const state = (shared.__threert_requests ??= { n: 0, pending: new Map(), listening: new Set() });
+
+function listen(answer: string) {
+ if (state.listening.has(answer)) return;
+ state.listening.add(answer);
+ host.on(answer, (m) => {
+ const id = String((m as Answer).id);
+ const p = state.pending.get(id);
+ if (!p) return;
+ state.pending.delete(id);
+ const a = m as Answer;
+ if (a.ok === false) p.reject(new HostRequestError(p.request, typeof a.reason === "string" ? a.reason : "failed"));
+ else p.resolve(a);
+ });
+}
+
+/** Posts a request of `family` and waits for its answer (`answer` is its type). */
+function request(family: "files" | "store", t: string, answer: string, fields: Record<string, unknown>): Promise<Answer> {
+ if (!has(family)) return Promise.reject(new HostRequestError(t, "unsupported"));
+ listen(answer);
+ const id = `${family}-${++state.n}`;
+ return new Promise<Answer>((resolve, reject) => {
+ state.pending.set(id, { request: t, resolve, reject });
+ if (!host.post({ t, id, ...fields })) {
+ state.pending.delete(id);
+ reject(new HostRequestError(t, "unsupported"));
+ }
+ });
+}
+
+/** The app listed `family` (a channel made by an older copy of this package has no `caps`: none). */
+const has = (family: string) => (host.caps ?? []).includes(family);
+
+const pathOf = (path: unknown): string => {
+ const e = storePathError(path);
+ if (e) throw new TypeError(`store: ${e}`);
+ return path as string;
+};
+
+const reject = (f: () => unknown): Promise<never> | null => {
+ try {
+ f();
+ return null;
+ } catch (e) {
+ return Promise.reject(e);
+ }
+};
+
+function bytesOf(data: Uint8Array | ArrayBufferView): Uint8Array {
+ return data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+}
+
+export const files: Files = {
+ available: () => has("files"),
+
+ async pick(o) {
+ if (!o || (o.mode !== "folder" && o.mode !== "files")) throw new TypeError('files.pick: mode is "folder" or "files"');
+ const fields: Record<string, unknown> = { mode: o.mode };
+ if (o.accept !== undefined) {
+ if (!Array.isArray(o.accept) || !o.accept.every((a) => typeof a === "string" && a.startsWith(".") && a.length > 1)) throw new TypeError('files.pick: accept is a list of extensions with the dot, as ".bsp"');
+ fields.accept = o.accept.map((a) => a.toLowerCase());
+ }
+ if (o.title !== undefined) fields.title = String(o.title);
+ try {
+ const a = await request("files", "files.pick", "files.picked", fields);
+ return { pick: String(a.pick), name: String(a.name ?? ""), entries: ((a.entries as FileEntry[] | undefined) ?? []).map((e) => ({ path: String(e.path), size: Number(e.size) })) };
+ } catch (e) {
+ if (e instanceof HostRequestError && e.reason === "canceled") return null;
+ throw e;
+ }
+ },
+
+ async read(pick, path) {
+ if (typeof pick !== "string" || typeof path !== "string") throw new TypeError("files.read(pick, path): two strings");
+ const a = await request("files", "files.read", "files.data", { pick, path });
+ return fromBase64(String(a.data ?? ""));
+ },
+};
+
+export const store: UserStore = {
+ available: () => has("store"),
+
+ write(path, data) {
+ let fields: Record<string, unknown> = {};
+ const bad = reject(() => {
+ pathOf(path);
+ if (typeof data === "string") fields = { text: data };
+ else if (ArrayBuffer.isView(data)) {
+ const bytes = bytesOf(data);
+ if (bytes.byteLength > MAX_FILE) throw new RangeError(`store.write(${path}): ${bytes.byteLength} bytes (at most ${MAX_FILE})`);
+ fields = { data: toBase64(bytes) };
+ } else throw new TypeError(`store.write(${path}): data is a Uint8Array or a string`);
+ });
+ return bad ?? request("store", "store.write", "store.done", { path, ...fields }).then(() => undefined);
+ },
+
+ read(path) {
+ return (
+ reject(() => pathOf(path)) ??
+ request("store", "store.read", "store.data", { path, as: "base64" }).then(
+ (a) => fromBase64(String(a.data ?? "")),
+ (e: unknown) => {
+ if (e instanceof HostRequestError && e.reason === "absent") return null;
+ throw e;
+ },
+ )
+ );
+ },
+
+ readText(path) {
+ return (
+ reject(() => pathOf(path)) ??
+ request("store", "store.read", "store.data", { path, as: "text" }).then(
+ (a) => String(a.text ?? ""),
+ (e: unknown) => {
+ if (e instanceof HostRequestError && e.reason === "absent") return null;
+ throw e;
+ },
+ )
+ );
+ },
+
+ list(prefix = "") {
+ if (typeof prefix !== "string") return Promise.reject(new TypeError("store.list(prefix): a string"));
+ return request("store", "store.list", "store.listed", prefix ? { prefix } : {}).then((a) =>
+ ((a.entries as FileEntry[] | undefined) ?? []).map((e) => ({ path: String(e.path), size: Number(e.size) })),
+ );
+ },
+
+ remove(path) {
+ return reject(() => pathOf(path)) ?? request("store", "store.remove", "store.done", { path }).then(() => undefined);
+ },
+
+ uri: (path) => `user:${pathOf(path)}`,
+};
+
+// ------------------------------------------------------------------------------------------------ sliced
+
+/** What a step leaves: `done` and the job's return value, or not yet and the last value it yielded (its progress). */
+export interface SliceResult<T = unknown> {
+ done: boolean;
+ value: T | undefined;
+}
+
+export interface Sliced<T = unknown> {
+ /** Runs the job for about `ms` milliseconds (at least one step of it); after it ended, its result again. */
+ step(ms?: number): SliceResult<T>;
+ /** The job has ended (returned, or thrown: the step that ran it threw). */
+ readonly done: boolean;
+}
+
+/** The clock steps are timed by: the runtime's monotonic one, or `Date.now` as this module found it (a handler's and a
+ * listener's `Date` is their event's fixed time). */
+const clock: () => number = (() => {
+ const p = (globalThis as { performance?: { now?: () => number } }).performance;
+ if (p && typeof p.now === "function") return () => p.now!();
+ const now = Date.now;
+ return () => now();
+})();
+
+/**
+ * Long work across frames: `job` is an iterator (a generator function's), and each `step(ms)` runs it until it has
+ * spent `ms` milliseconds or ended. Yield often (every few hundred faces of a map, every texture): a step can only
+ * stop between two yields.
+ *
+ * function* convert(bsp: Uint8Array) { ...; for (const face of faces) { ...; yield done / faces.length; } return glb; }
+ * const job = sliced(convert(bsp));
+ * frame(f) { const r = job.step(8); bar.value = r.done ? 1 : (r.value as number); if (r.done) save(r.value); }
+ */
+export function sliced<T = unknown>(job: Iterator<unknown, T>): Sliced<T> {
+ if (!job || typeof job.next !== "function") throw new TypeError("sliced: an iterator (call the generator function)");
+ let last: SliceResult<T> = { done: false, value: undefined };
+ return {
+ get done() {
+ return last.done;
+ },
+ step(ms = 8) {
+ if (last.done) return last;
+ const t0 = clock();
+ try {
+ do {
+ const r = job.next();
+ last = { done: !!r.done, value: r.value as T | undefined };
+ } while (!last.done && clock() - t0 < ms);
+ } catch (e) {
+ last = { done: true, value: undefined };
+ throw e;
+ }
+ return last;
+ },
+ };
+}
diff --git a/packages/gameplay/src/host.ts b/packages/gameplay/src/host.ts
index 97d03b0..99fcf06 100644
--- a/packages/gameplay/src/host.ts
+++ b/packages/gameplay/src/host.ts
@@ -21,8 +21,10 @@
// - The same object is `globalThis.__threert_host`, for a library that does not import this package.
//
// The message families an app may implement are in docs/RUNTIME.md ("The host channel"): `net.*` (sockets and HTTP
-// the app owns), `hud` (hud.ts), `audio.*` (audio.ts: played by the engine's mixer), `launch` (how the game was
-// opened), and `input` (input.ts), which the node host takes itself.
+// the app owns), `hud` (hud.ts), `audio.*` (audio.ts: played by the engine's mixer), `files.*` and `store.*` (files.ts:
+// what the player picked, the game's own storage on the device; docs/RUNTIME.md "Files"), `launch` (how the game was
+// opened, and `caps`: the families of requests the app answers, kept as `host.caps`), and `input` (input.ts), which
+// the node host takes itself.
import type { WorldContext } from "./world.ts";
@@ -56,8 +58,8 @@ export interface HostEvents {
"net.closed": { t: "net.closed"; id: string; code: number; reason: string };
/** A `net.fetch`'s answer. `status` 0: the request failed (`error`). */
"net.fetched": { t: "net.fetched"; id: string; status: number; body: string; error?: string };
- /** Once after setup. */
- launch: { t: "launch"; params: LaunchParams };
+ /** Once after setup. `caps`: the families of requests the app answers (`"files"`, `"store"`); none: `[]`. */
+ launch: { t: "launch"; params: LaunchParams; caps?: string[] };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -74,6 +76,11 @@ export interface Host {
on(type: string, fn: HostListener<HostMessage>): () => void;
/** The `launch` message's `params`; `{}` until the app has sent one (and for an app that never does). */
readonly launch: Readonly<LaunchParams>;
+ /**
+ * The `launch` message's `caps`: the families of requests the app answers (`"files"`, `"store"`: files.ts). `[]`
+ * until the app has sent it, and for an app that lists none. A game waits for no answer of a family not listed.
+ */
+ readonly caps: readonly string[];
}
/** The node host's side of the channel (node-host.ts). */
@@ -82,12 +89,13 @@ export interface HostChannel extends Host {
listens(type: string): boolean;
/** Hands `message` to its listeners. Returns the errors of those that threw. */
deliver(message: HostMessage, world: WorldContext<unknown>): string[];
- setLaunch(params: unknown): void;
+ setLaunch(params: unknown, caps?: unknown): void;
}
function makeHost(): HostChannel {
const listeners = new Map<string, HostListener[]>();
let launch: Readonly<LaunchParams> = Object.freeze({});
+ let caps: readonly string[] = Object.freeze([]);
return {
post(message) {
if (!message || typeof message !== "object" || typeof message.t !== "string" || !message.t) throw new TypeError('host.post: a message is an object with a string "t"');
@@ -111,6 +119,9 @@ function makeHost(): HostChannel {
get launch() {
return launch;
},
+ get caps() {
+ return caps;
+ },
listens: (type) => (listeners.get(type)?.length ?? 0) > 0,
deliver(message, world) {
const errors: string[] = [];
@@ -125,8 +136,9 @@ function makeHost(): HostChannel {
}
return errors;
},
- setLaunch(params) {
+ setLaunch(params, list) {
launch = Object.freeze(params && typeof params === "object" && !Array.isArray(params) ? { ...(params as LaunchParams) } : {});
+ caps = Object.freeze(Array.isArray(list) ? [...new Set(list.filter((c): c is string => typeof c === "string"))] : []);
},
};
}
diff --git a/packages/gameplay/src/index.ts b/packages/gameplay/src/index.ts
index d1261cb..b095cd9 100644
--- a/packages/gameplay/src/index.ts
+++ b/packages/gameplay/src/index.ts
@@ -8,6 +8,8 @@ export { host } from "./host.ts";
export type { Host, HostEvents, HostListener, HostMessage, LaunchParams, NetPost } from "./host.ts";
export { InputState } from "./input.ts";
export type { Input, InputMessage } from "./input.ts";
+export { files, HostRequestError, sliced, store } from "./files.ts";
+export type { FileEntry, Files, Picked, PickOptions, Sliced, SliceResult, UserStore } from "./files.ts";
export { audio } from "./audio.ts";
export type { Audio, AudioPoint, AudioPost, PlayOptions } from "./audio.ts";
export { hud } from "./hud.ts";
diff --git a/packages/gameplay/src/node-host.ts b/packages/gameplay/src/node-host.ts
index aa4c838..428747c 100644
--- a/packages/gameplay/src/node-host.ts
+++ b/packages/gameplay/src/node-host.ts
@@ -195,7 +195,7 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):
input.apply(m as unknown as InputMessage);
continue;
}
- if (m.t === "launch") channel.setLaunch(m.params);
+ if (m.t === "launch") channel.setLaunch(m.params, m.caps);
if (!channel.listens(m.t)) continue;
ctx ??= worldContext(frames, store.seed, { id: ++eventId, ts });
const { world, random } = ctx;
diff --git a/packages/gameplay/test/files.test.ts b/packages/gameplay/test/files.test.ts
new file mode 100644
index 0000000..690b0f2
--- /dev/null
+++ b/packages/gameplay/test/files.test.ts
@@ -0,0 +1,256 @@
+// Files (src/files.ts): what the player picked and the game's store, as requests on the host channel that the app
+// answers once each (docs/RUNTIME.md "Files"); `host.caps` from the launch message; base64 both ways; `sliced`.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { BoxGeometry, Mesh, MeshStandardMaterial, PerspectiveCamera, RecordingEngine, Scene } from "@threert/scene";
+import { defineGame, files, host, HostRequestError, sliced, store, type GameDefinition } from "../src/index.ts";
+import * as gameplay from "../src/index.ts";
+import { fromBase64, storePathError, toBase64 } from "../src/files.ts";
+
+type Msg = { t: string; id?: string; [k: string]: unknown };
+
+function scene() {
+ const scene = new Scene(), camera = new PerspectiveCamera(50, 16 / 9);
+ scene.add(camera, new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ name: "m" })));
+ return { scene, camera };
+}
+
+/** An app with a store in memory and one folder for the player to pick: it answers what the game posted when pumped. */
+function app(caps: string[]) {
+ const posts: Msg[] = [];
+ const g = globalThis as { __host_post?: (text: string) => unknown };
+ g.__host_post = (text) => void posts.push(JSON.parse(text));
+ const h = gameplay.installNodeHost(defineGame({ state: {}, setup: scene, handlers: {} }) as GameDefinition<unknown>, new RecordingEngine());
+ h.setup("node");
+ const disk = new Map<string, Uint8Array>();
+ const folder = new Map<string, Uint8Array>([["maps/de_x.bsp", new Uint8Array([30, 0, 0, 0, 7])], ["cstrike.wad", new Uint8Array([87, 65, 68, 51])]]);
+ let picks = 0;
+ const answer = (m: Msg): Msg | null => {
+ const { id } = m;
+ const no = (t: string, reason: string) => ({ t, id, ok: false, reason });
+ switch (m.t) {
+ case "files.pick":
+ if (picks++ > 0) return no("files.picked", "canceled");
+ return { t: "files.picked", id, ok: true, pick: "pick-1", name: "cstrike", entries: [...folder].map(([path, b]) => ({ path, size: b.length })) };
+ case "files.read": {
+ const b = m.pick === "pick-1" ? folder.get(m.path as string) : undefined;
+ return b ? { t: "files.data", id, ok: true, data: Buffer.from(b).toString("base64"), size: b.length } : no("files.data", "denied");
+ }
+ case "store.write":
+ disk.set(m.path as string, m.data !== undefined ? Buffer.from(m.data as string, "base64") : Buffer.from(m.text as string));
+ return { t: "store.done", id, ok: true };
+ case "store.read": {
+ const b = disk.get(m.path as string);
+ if (!b) return no("store.data", "absent");
+ return m.as === "text" ? { t: "store.data", id, ok: true, text: Buffer.from(b).toString("utf8"), size: b.length } : { t: "store.data", id, ok: true, data: Buffer.from(b).toString("base64"), size: b.length };
+ }
+ case "store.list":
+ return { t: "store.listed", id, ok: true, entries: [...disk].filter(([p]) => p.startsWith((m.prefix as string) ?? "")).sort().map(([path, b]) => ({ path, size: b.length })) };
+ case "store.remove":
+ for (const p of [...disk.keys()]) if (p === m.path || p.startsWith(`${m.path}/`)) disk.delete(p);
+ return { t: "store.done", id, ok: true };
+ }
+ return null;
+ };
+ return {
+ posts, disk,
+ launch: () => h.hostMessages(JSON.stringify([{ t: "launch", params: {}, caps }]), 1000),
+ /** Answers everything posted so far, as one batch (a frame's). Promise jobs run after the entry: awaited here. */
+ async pump() {
+ const batch = posts.splice(0).map(answer).filter((a): a is Msg => a !== null);
+ if (batch.length) h.hostMessages(JSON.stringify(batch), 1000);
+ await new Promise((r) => setImmediate(r));
+ },
+ close: () => void delete g.__host_post,
+ };
+}
+
+/** Runs `p` with the app answering until it settles. */
+async function settle<T>(a: ReturnType<typeof app>, p: Promise<T>): Promise<T> {
+ let out: { ok: true; value: T } | { ok: false; error: unknown } | null = null;
+ p.then((value) => (out = { ok: true, value }), (error: unknown) => (out = { ok: false, error }));
+ for (let i = 0; i < 20 && !out; i++) await a.pump();
+ const r = out as { ok: true; value: T } | { ok: false; error: unknown } | null;
+ if (!r) throw new Error("no answer");
+ if (!r.ok) throw r.error;
+ return r.value;
+}
+
+test("caps come with the launch message: [] before it and from an app that lists none", () => {
+ const a = app([]);
+ try {
+ assert.deepEqual(host.caps, []);
+ assert.equal(files.available(), false);
+ a.launch();
+ assert.deepEqual(host.caps, []);
+ const b = app(["files", "store", "files", 7 as never]);
+ b.launch();
+ assert.deepEqual(host.caps, ["files", "store"]);
+ assert.equal(files.available() && store.available(), true);
+ assert.throws(() => (host.caps as string[]).push("x"), TypeError, "frozen");
+ // A launch without caps (an app from before them).
+ gameplay.installNodeHost(defineGame({ state: {}, setup: scene, handlers: {} }) as GameDefinition<unknown>, new RecordingEngine()).setup("n");
+ (globalThis as { __threert?: gameplay.NodeHost }).__threert!.hostMessages(JSON.stringify([{ t: "launch", params: { room: "R" } }]), 1);
+ assert.deepEqual([host.caps, host.launch], [[], { room: "R" }]);
+ } finally {
+ a.close();
+ }
+});
+
+test("without the family listed, a request is refused at once and nothing is posted", async () => {
+ const a = app(["store"]);
+ try {
+ a.launch();
+ await assert.rejects(files.pick({ mode: "folder" }), (e: unknown) => e instanceof HostRequestError && e.reason === "unsupported");
+ await assert.rejects(files.read("pick-1", "a.bsp"), /unsupported/);
+ assert.deepEqual(a.posts, []);
+ } finally {
+ a.close();
+ }
+});
+
+test("pick a folder, read its files, convert, store, read back, list, remove", async () => {
+ const a = app(["files", "store"]);
+ try {
+ a.launch();
+ const picked = await settle(a, files.pick({ mode: "folder", accept: [".BSP", ".wad"], title: "Your Counter-Strike folder" }));
+ assert.deepEqual(picked, { pick: "pick-1", name: "cstrike", entries: [{ path: "maps/de_x.bsp", size: 5 }, { path: "cstrike.wad", size: 4 }] });
+ const bsp = await settle(a, files.read(picked!.pick, "maps/de_x.bsp"));
+ assert.deepEqual([...bsp], [30, 0, 0, 0, 7]);
+ await assert.rejects(settle(a, files.read(picked!.pick, "../secret")), (e: unknown) => e instanceof HostRequestError && e.reason === "denied");
+ // The player closes the picker: null.
+ assert.equal(await settle(a, files.pick({ mode: "files" })), null);
+ // What the game posted, as the contract has it.
+ await settle(a, store.write("maps/de_x/map.glb", bsp.subarray(1, 4)));
+ await settle(a, store.write("maps/de_x/info.json", JSON.stringify({ name: "de_x" })));
+ assert.deepEqual([...a.disk.get("maps/de_x/map.glb")!], [0, 0, 0]);
+ assert.deepEqual([...((await settle(a, store.read("maps/de_x/map.glb"))) ?? [])], [0, 0, 0]);
+ assert.deepEqual(JSON.parse((await settle(a, store.readText("maps/de_x/info.json")))!), { name: "de_x" });
+ assert.equal(await settle(a, store.read("nothing")), null);
+ assert.equal(await settle(a, store.readText("nothing")), null);
+ assert.deepEqual(await settle(a, store.list("maps/")), [{ path: "maps/de_x/info.json", size: 15 }, { path: "maps/de_x/map.glb", size: 3 }]);
+ await settle(a, store.remove("maps"));
+ assert.deepEqual(await settle(a, store.list()), []);
+ assert.equal(store.uri("maps/de_x/map.glb"), "user:maps/de_x/map.glb");
+ } finally {
+ a.close();
+ }
+});
+
+test("the messages are the contract's", async () => {
+ const a = app(["files", "store"]);
+ try {
+ a.launch();
+ const seen: Msg[] = [];
+ const take = () => seen.push(...a.posts.map((m) => ({ ...m, id: m.id ? "ID" : undefined })));
+ void files.pick({ mode: "folder", accept: [".bsp"] }); take(); await a.pump();
+ void store.write("a/b.bin", new Uint16Array([1, 256])); take(); await a.pump();
+ void store.write("t.txt", "é"); take(); await a.pump();
+ void store.readText("t.txt"); take(); await a.pump();
+ void store.list(); take(); await a.pump();
+ void store.remove("a"); take(); await a.pump();
+ assert.deepEqual(seen, [
+ { t: "files.pick", id: "ID", mode: "folder", accept: [".bsp"] },
+ { t: "store.write", id: "ID", path: "a/b.bin", data: "AQAAAQ==" },
+ { t: "store.write", id: "ID", path: "t.txt", text: "é" },
+ { t: "store.read", id: "ID", path: "t.txt", as: "text" },
+ { t: "store.list", id: "ID" },
+ { t: "store.remove", id: "ID", path: "a" },
+ ]);
+ // Every request its own id.
+ void store.list(); void store.list();
+ const [x, y] = a.posts.splice(0);
+ assert.notEqual(x!.id, y!.id);
+ } finally {
+ a.close();
+ }
+});
+
+test("store paths are checked before anything is posted", async () => {
+ const a = app(["store"]);
+ try {
+ a.launch();
+ for (const bad of ["", "/abs", "../up", "a/../b", "a//b", "a/", "./a", "a b", "é", "c:x", "a~", "x".repeat(201)]) {
+ assert.ok(storePathError(bad), bad);
+ await assert.rejects(store.write(bad, "x"), TypeError, bad);
+ await assert.rejects(store.read(bad), TypeError);
+ await assert.rejects(store.remove(bad), TypeError);
+ assert.throws(() => store.uri(bad), TypeError);
+ }
+ for (const good of ["a", "maps/de_dust2/map.glb", ".hidden", "A-b_c.9", "x".repeat(200)]) assert.equal(storePathError(good), null, good);
+ await assert.rejects(store.write("a", 5 as never), TypeError);
+ await assert.rejects(files.pick({ mode: "all" } as never), TypeError);
+ await assert.rejects(files.pick({ mode: "files", accept: ["bsp"] }), TypeError);
+ assert.deepEqual(a.posts, []);
+ } finally {
+ a.close();
+ }
+});
+
+test("base64: native, Buffer, atob / btoa and script all agree", () => {
+ const bytes = new Uint8Array(1000).map((_, i) => (i * 7919) & 255);
+ const views = [bytes, bytes.subarray(1), bytes.subarray(2), bytes.subarray(0, 0)];
+ const ways = {
+ buffer: { Buffer },
+ browser: { btoa, atob },
+ script: {},
+ };
+ for (const v of views) {
+ const want = Buffer.from(v).toString("base64");
+ for (const [name, n] of Object.entries(ways)) {
+ assert.equal(toBase64(v, n as never), want, name);
+ assert.deepEqual([...fromBase64(want, n as never)], [...v], name);
+ }
+ }
+ assert.throws(() => fromBase64("**", {}), /base64/);
+ const native = { __host_base64_encode: () => "N", __host_base64_decode: () => new Uint8Array([1]) };
+ assert.equal(toBase64(bytes, native), "N");
+ assert.deepEqual([...fromBase64("x", native)], [1]);
+});
+
+test("sliced runs a job a few milliseconds a step, then keeps its result", () => {
+ let n = 0;
+ function* job(): Generator<number, string> {
+ for (let i = 0; i < 50; i++) {
+ n++;
+ const t = performance.now();
+ while (performance.now() - t < 1);
+ yield i / 50;
+ }
+ return "glb";
+ }
+ const w = sliced(job());
+ const t0 = performance.now();
+ const r = w.step(5);
+ const took = performance.now() - t0;
+ assert.equal(r.done, false);
+ // (Steps of 1 ms in a slice of 5: about 5 of them, fewer on a busy machine, and the slice ends after the step that
+ // passes it.)
+ assert.ok(n >= 1 && n <= 6 && took >= 5, `${n} steps of 1 ms in ${took.toFixed(1)} ms`);
+ assert.equal(r.value, (n - 1) / 50, "the last progress");
+ let last = r;
+ for (let k = 0; k < 100 && !last.done; k++) last = w.step(5);
+ assert.deepEqual(last, { done: true, value: "glb" });
+ assert.equal(w.done, true);
+ assert.equal(n, 50);
+ assert.deepEqual(w.step(5), { done: true, value: "glb" });
+ // At least one step a call, however small the slice.
+ const one = sliced([1, 2, 3][Symbol.iterator]());
+ assert.deepEqual(one.step(0), { done: false, value: 1 });
+ // A job that throws: the step throws, and the job is over.
+ const bad = sliced((function* () { yield 1; throw new Error("broken map"); })());
+ assert.throws(() => bad.step(50), /broken map/);
+ assert.equal(bad.done, true);
+ // Inside a listener Date.now() is the event's time: steps are timed by the runtime's clock all the same.
+ const RealDate = Date;
+ globalThis.Date = class extends RealDate { static override now() { return 0; } } as DateConstructor;
+ try {
+ const frozen = sliced(job());
+ n = 0;
+ frozen.step(3);
+ assert.ok(n < 50, "a step ended by time");
+ } finally {
+ globalThis.Date = RealDate;
+ }
+ assert.throws(() => sliced(5 as never), TypeError);
+});
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index 81b7abd..5a3c6f3 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -3205,6 +3205,7 @@ name = "threert-render"
version = "0.1.0"
dependencies = [
"anyhow",
+ "base64 0.23.1",
"bytemuck",
"cpal",
"glam 0.30.10",
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index 9b03272..72df7ab 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -41,6 +41,9 @@ winit = "0.30"
oidn = { version = "2.5", optional = true }
# Scene runtime of the render node (game bundles run in the renderer process, src/script.rs).
rquickjs = "0.12"
+# Files on the host channel are base64 (docs/RUNTIME.md "Files"): the script runtime's codec (src/script.rs) and the
+# app side of `files.*` / `store.*` (src/userfiles.rs).
+base64 = "0.23"
# The `threert-render` binary's sockets and HTTP, for the games its window runs (src/net.rs: the `net.*` messages of
# the host channel, docs/RUNTIME.md). Only the binary uses them, and only with the `net` feature: the library has no
diff --git a/renderer/src/audio/mod.rs b/renderer/src/audio/mod.rs
index 907f329..1f4faf0 100644
--- a/renderer/src/audio/mod.rs
+++ b/renderer/src/audio/mod.rs
@@ -22,6 +22,8 @@ mod mix;
mod out;
pub use decode::{decode, EXTENSIONS};
+#[cfg(test)]
+pub(crate) use decode::tests_wav;
pub use mix::{pan_gains, place, Listener, Sound, DEFAULT_FALLOFF, MAX_COPIES, MAX_VOICES};
use glam::Vec3;
@@ -220,7 +222,7 @@ impl Audio {
}
/// The decoded sound `name`, decoded now if it is not yet (None: missing or unreadable, said once).
- fn sound(&mut self, name: &str) -> Option<Arc<Sound>> {
+ pub(crate) fn sound(&mut self, name: &str) -> Option<Arc<Sound>> {
self.poll();
if let Some(s) = self.sounds.get(name) {
return s.clone();
@@ -260,6 +262,11 @@ impl Audio {
fn path(&self, name: &str) -> Result<PathBuf, String> {
let root = self.root.as_ref().ok_or_else(|| format!("{name}: no game is open"))?;
+ // A sound the game keeps in its store (docs/RUNTIME.md "Files"): `user:<store path>`.
+ if let Some(rel) = name.strip_prefix(crate::files::USER_SCHEME) {
+ crate::files::check_store_path(rel).map_err(|e| format!("{name}: {e}"))?;
+ return crate::files::user_root().map(|r| r.join(rel)).ok_or_else(|| format!("{name}: the app gave the game no store"));
+ }
let rel = Path::new(name.trim_start_matches("./"));
if name.is_empty() || !rel.components().all(|c| matches!(c, Component::Normal(_))) {
return Err(format!("{name}: a sound is a path inside the game's package"));
diff --git a/renderer/src/files.rs b/renderer/src/files.rs
index 62c973e..5ee603f 100644
--- a/renderer/src/files.rs
+++ b/renderer/src/files.rs
@@ -3,9 +3,66 @@
//! page fetches what a scene names (`World::files`) and hands the bytes over with `provide` before the scene is built,
//! and the two presets are compiled in. The paths are the ones the native build would open (asset root joined with
//! the scene's uri), so the same scene code names the same files on both.
+//!
+//! An asset is a file of the game's package (`models/car.glb`, under the asset root) or one the game keeps in its
+//! store (`user:maps/de_dust2/map.glb`: docs/RUNTIME.md "Files"), under the directory the app names with
+//! `set_user_root`. `asset_path` is where either is; every reader of a scene's files goes through it.
use anyhow::Result;
-use std::path::Path;
+use std::path::{Path, PathBuf};
+use std::sync::RwLock;
+
+/// The scheme of an asset in the game's store.
+pub const USER_SCHEME: &str = "user:";
+
+/// The longest path in a game's store.
+pub const MAX_STORE_PATH: usize = 200;
+
+static USER_ROOT: RwLock<Option<PathBuf>> = RwLock::new(None);
+
+/// The directory `user:` assets resolve against: the store of the game the app runs (`None`: no store, and a `user:`
+/// asset is missing as a missing file is). One a process; an app sets it before it builds the game's scene.
+pub fn set_user_root(root: Option<&Path>) {
+ *USER_ROOT.write().unwrap_or_else(|e| e.into_inner()) = root.map(Path::to_path_buf);
+}
+
+/// The directory `set_user_root` named.
+pub fn user_root() -> Option<PathBuf> {
+ USER_ROOT.read().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// A path in a game's store: relative, `/`-separated, segments of `[A-Za-z0-9._-]`, no `.` or `..` segment, at most
+/// 200 characters. The error says what is wrong with it.
+pub fn check_store_path(path: &str) -> std::result::Result<(), String> {
+ if path.is_empty() {
+ return Err("a store path is not empty".into());
+ }
+ if path.len() > MAX_STORE_PATH {
+ return Err(format!("a store path is at most {MAX_STORE_PATH} characters"));
+ }
+ for seg in path.split('/') {
+ if seg.is_empty() || seg == "." || seg == ".." {
+ return Err(format!("\"{path}\": a store path is relative, with no empty, \".\" or \"..\" segment"));
+ }
+ if !seg.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) {
+ return Err(format!("\"{path}\": a store path's segments are of A-Z a-z 0-9 . _ -"));
+ }
+ }
+ Ok(())
+}
+
+/// Where the asset `uri` is: under `assets` for a file of the game's package, under the user root for `user:<path>`.
+/// A `user:` asset without a user root, or with a path that is not a store path, is a path that is not there
+/// (`user:/missing`: it is missing, as a missing file is, and never outside the store).
+pub fn asset_path(assets: &Path, uri: &str) -> PathBuf {
+ match uri.strip_prefix(USER_SCHEME) {
+ Some(rel) => match (user_root(), check_store_path(rel)) {
+ (Some(root), Ok(())) => root.join(rel),
+ _ => PathBuf::from("user:/missing"),
+ },
+ None => assets.join(uri),
+ }
+}
#[cfg(target_arch = "wasm32")]
thread_local! {
@@ -75,3 +132,68 @@ pub fn preset(dir: &Path, name: &str) -> std::io::Result<Vec<u8>> {
}
}
}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod tests {
+ use super::*;
+
+ /// A one-triangle glTF with its buffer inline.
+ fn triangle_gltf() -> String {
+ use base64::Engine;
+ let mut buf: Vec<u8> = [0f32, 0., 0., 1., 0., 0., 0., 1., 0.].iter().flat_map(|v| v.to_le_bytes()).collect();
+ buf.extend([0u16, 1, 2, 0].iter().flat_map(|v| v.to_le_bytes()));
+ let data = base64::engine::general_purpose::STANDARD.encode(&buf);
+ format!(
+ r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
+ "meshes":[{{"primitives":[{{"attributes":{{"POSITION":0}},"indices":1}}]}}],
+ "buffers":[{{"byteLength":44,"uri":"data:application/octet-stream;base64,{data}"}}],
+ "bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":36}},{{"buffer":0,"byteOffset":36,"byteLength":6}}],
+ "accessors":[{{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3","min":[0,0,0],"max":[1,1,0]}},
+ {{"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"}}]}}"#
+ )
+ }
+
+ /// `user:` assets (docs/RUNTIME.md "Files"): a scene names a file of the game's store, and the engine reads it from
+ /// the directory the app gave, never outside it; without one the asset is missing. (One test: the user root is the
+ /// process's.)
+ #[test]
+ fn user_assets_resolve_against_the_store() {
+ let dir = std::env::temp_dir().join(format!("threert-user-assets-{}", std::process::id()));
+ let (assets, store) = (dir.join("game"), dir.join("store"));
+ std::fs::create_dir_all(assets.join("models")).unwrap();
+ std::fs::create_dir_all(store.join("maps/de_x")).unwrap();
+ std::fs::write(store.join("maps/de_x/map.gltf"), triangle_gltf()).unwrap();
+ std::fs::write(assets.join("models/tri.gltf"), triangle_gltf()).unwrap();
+ // The scene's paths: a store path after `user:`, nothing else.
+ for ok in ["user:maps/de_x/map.gltf", "models/tri.gltf"] {
+ assert!(crate::world::check_uri(ok).is_ok(), "{ok}");
+ }
+ for bad in ["user:../game/models/tri.gltf", "user:/etc/passwd", "user:", "user:a b", "other:x", "../x", "/abs"] {
+ assert!(crate::world::check_uri(bad).is_err(), "{bad}");
+ }
+ set_user_root(None);
+ assert_eq!(asset_path(&assets, "models/tri.gltf"), assets.join("models/tri.gltf"));
+ assert!(!asset_path(&assets, "user:maps/de_x/map.gltf").exists(), "no store: missing");
+ assert!(crate::scene::model_gltf("user:maps/de_x/map.gltf", &assets).is_err());
+ set_user_root(Some(&store));
+ assert_eq!(asset_path(&assets, "user:maps/de_x/map.gltf"), store.join("maps/de_x/map.gltf"));
+ assert_eq!(asset_path(&assets, "user:../game/models/tri.gltf"), PathBuf::from("user:/missing"), "never outside the store");
+ let m = crate::scene::model_gltf("user:maps/de_x/map.gltf", &assets).unwrap();
+ assert_eq!(m.triangles(glam::Mat4::IDENTITY, None, None).unwrap().len(), 1);
+ assert_eq!(crate::scene::model_gltf("models/tri.gltf", &assets).unwrap().triangles(glam::Mat4::IDENTITY, None, None).unwrap().len(), 1);
+ // A sound from the store too.
+ #[cfg(feature = "audio")]
+ {
+ let samples: Vec<i16> = (0..2205).map(|i| ((i as f32 * 0.1).sin() * 8000.0) as i16).collect();
+ std::fs::write(store.join("maps/de_x/ambient.wav"), crate::audio::tests_wav(22_050, &samples)).unwrap();
+ let mut a = crate::audio::Audio::new();
+ a.open(&assets);
+ assert!(a.sound("user:maps/de_x/ambient.wav").is_some());
+ assert!(a.sound("user:maps/de_x/missing.wav").is_none());
+ assert!(a.sound("user:../game/x.wav").is_none());
+ assert_eq!(a.take_log().len(), 2);
+ }
+ set_user_root(None);
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}
diff --git a/renderer/src/host.rs b/renderer/src/host.rs
index 25b5b28..f7bc118 100644
--- a/renderer/src/host.rs
+++ b/renderer/src/host.rs
@@ -15,6 +15,33 @@ pub trait HostServices {
fn post(&mut self, message: &Value);
/// The messages for the game since the last call, in order.
fn poll(&mut self) -> Vec<Value>;
+ /// The families of requests these services answer, for the `launch` message's `caps` (`"files"`, `"store"`): a
+ /// game waits for no answer of a family that is not listed. Services that answer none list nothing.
+ fn caps(&self) -> Vec<&'static str> {
+ vec![]
+ }
+}
+
+/// Several services as one: each is handed every post (and ignores what is not its own), their answers come in the
+/// order of the list, and their families are listed together.
+impl HostServices for Vec<Box<dyn HostServices>> {
+ fn post(&mut self, message: &Value) {
+ for s in self.iter_mut() {
+ s.post(message);
+ }
+ }
+ fn poll(&mut self) -> Vec<Value> {
+ self.iter_mut().flat_map(|s| s.poll()).collect()
+ }
+ fn caps(&self) -> Vec<&'static str> {
+ let mut caps: Vec<&'static str> = vec![];
+ for c in self.iter().flat_map(|s| s.caps()) {
+ if !caps.contains(&c) {
+ caps.push(c);
+ }
+ }
+ caps
+ }
}
/// An app without services: posts go nowhere, nothing comes back.
@@ -31,9 +58,16 @@ impl HostServices for NoServices {
/// point of a macOS pointer, a CSS pixel in a browser). 1,000 counts turn 143 degrees.
pub const LOOK_RADIANS: f32 = 0.0025;
-/// The `launch` message: how the app opened the game.
+/// The `launch` message: how the app opened the game. An app that answers requests of some families lists them
+/// with `launch_message_with_caps`.
pub fn launch_message(params: Option<&Value>) -> Value {
- json!({ "t": "launch", "params": params.filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})) })
+ launch_message_with_caps(params, &[])
+}
+
+/// The `launch` message with the families of requests the app answers (`caps`: `HostServices::caps`, `"files"`,
+/// `"store"`).
+pub fn launch_message_with_caps(params: Option<&Value>, caps: &[&str]) -> Value {
+ json!({ "t": "launch", "params": params.filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})), "caps": caps })
}
/// A window's keys and pointer between two frames, and the `input` message of a frame.
@@ -169,8 +203,36 @@ mod tests {
#[test]
fn the_launch_message() {
- assert_eq!(launch_message(None), json!({ "t": "launch", "params": {} }));
- assert_eq!(launch_message(Some(&json!({ "room": "K7Q4MZ" }))), json!({ "t": "launch", "params": { "room": "K7Q4MZ" } }));
+ assert_eq!(launch_message(None), json!({ "t": "launch", "params": {}, "caps": [] }));
+ assert_eq!(launch_message_with_caps(Some(&json!({ "room": "K7Q4MZ" })), &["files", "store"]), json!({ "t": "launch", "params": { "room": "K7Q4MZ" }, "caps": ["files", "store"] }));
assert_eq!(launch_message(Some(&json!("x")))["params"], json!({}));
}
+
+ /// Services that answer a family and services that answer none, as the window's one list.
+ struct Echo(&'static str, Vec<Value>);
+ impl HostServices for Echo {
+ fn post(&mut self, m: &Value) {
+ if m["t"].as_str().is_some_and(|t| t.starts_with(self.0)) {
+ self.1.push(json!({ "t": format!("{}answer", self.0), "id": m["id"] }));
+ }
+ }
+ fn poll(&mut self) -> Vec<Value> {
+ std::mem::take(&mut self.1)
+ }
+ fn caps(&self) -> Vec<&'static str> {
+ vec![self.0.trim_end_matches('.'), "store"]
+ }
+ }
+
+ #[test]
+ fn services_as_one() {
+ let mut all: Vec<Box<dyn HostServices>> = vec![Box::new(NoServices), Box::new(Echo("files.", vec![])), Box::new(Echo("net.", vec![]))];
+ assert_eq!(all.caps(), vec!["files", "store", "net"]);
+ all.post(&json!({ "t": "net.open", "id": 1 }));
+ all.post(&json!({ "t": "files.pick", "id": 2 }));
+ all.post(&json!({ "t": "hud" }));
+ assert_eq!(all.poll(), vec![json!({ "t": "files.answer", "id": 2 }), json!({ "t": "net.answer", "id": 1 })]);
+ assert!(all.poll().is_empty());
+ assert!(NoServices.caps().is_empty());
+ }
}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 9243f53..fdbe6e0 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -28,6 +28,8 @@ pub mod sample;
pub mod sky;
pub mod tables;
pub mod units;
+#[cfg(not(target_arch = "wasm32"))]
+pub mod userfiles;
#[cfg(test)]
mod units_cost;
pub mod texpack;
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 91a2195..f0d40f5 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -83,6 +83,11 @@ pub struct LiveOpts {
pub display_scale: f32,
/// `--launch`: the `params` of the host channel's `launch` message (docs/RUNTIME.md "The host channel").
pub launch: Option<serde_json::Value>,
+ /// `--caps files,store`: the families of requests the driver answers, listed in the `launch` message.
+ pub caps: Vec<String>,
+ /// `--store <dir>`: the game's store, where `user:` assets resolve (docs/RUNTIME.md "Files"). The driver answers
+ /// `store.*` itself; this is only where the engine reads what it wrote.
+ pub store: Option<PathBuf>,
}
/// Lowest dynamic-resolution scale (UE r.DynamicRes.MinScreenPercentage default) of a view whose pixels are the
diff --git a/renderer/src/live/session.rs b/renderer/src/live/session.rs
index 54447ff..23bac3d 100644
--- a/renderer/src/live/session.rs
+++ b/renderer/src/live/session.rs
@@ -8,10 +8,13 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
let (w, h) = (opts.width, opts.height);
let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();
spawn_stdin_reader(cmd_tx);
+ if let Some(store) = &opts.store {
+ crate::files::set_user_root(Some(store));
+ }
let (mut game, mut core) = crate::script::GameSession::start(&opts.bundle, &opts.room, &opts.assets, gpu::Gpu::new()?, presets, w, h)?;
// The host channel: this runner is the app. How the game was opened, once after setup; what the game posts goes
// out on stdout (`emit_posts`), and whoever drives the runner answers with `{"cmd":"host"}`.
- if let Err(e) = game.host_messages(&mut core, &[crate::host::launch_message(opts.launch.as_ref())]) {
+ if let Err(e) = game.host_messages(&mut core, &[crate::host::launch_message_with_caps(opts.launch.as_ref(), &opts.caps.iter().map(String::as_str).collect::<Vec<_>>())]) {
eprintln!("live: launch: {e:#}");
}
emit_posts(&mut game);
@@ -296,6 +299,8 @@ pub fn parse_opts(args: &[String]) -> Result<LiveOpts> {
frame_log: flag("--frame-log").map(PathBuf::from),
display_scale: flag("--display-scale").map(|v| v.parse::<f32>()).transpose()?.unwrap_or(1.0),
launch: parse_launch(flag("--launch").as_deref())?,
+ caps: flag("--caps").map(|c| c.split(',').map(str::trim).filter(|c| !c.is_empty()).map(String::from).collect()).unwrap_or_default(),
+ store: flag("--store").map(PathBuf::from),
})
}
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index fd824b1..31f1e18 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -228,8 +228,13 @@ fn main() -> Result<()> {
}
"view" | "play" => {
// The window is the app of the game's host channel: its `net.*` messages are this binary's sockets and
- // HTTP (src/net.rs; a build without the `net` feature answers that it has none).
- view::run(view::parse_args(&args, &presets)?, Box::new(net::Net::new()))?;
+ // HTTP (src/net.rs; a build without the `net` feature answers that it has none), its `files.*` and
+ // `store.*` the paths of `--pick` and the store directory (`--store`, where `user:` assets are too).
+ let a = view::parse_args(&args, &presets)?;
+ threert_render::files::set_user_root(Some(&a.store));
+ let files = threert_render::userfiles::UserFiles::new(Some(a.store.clone()), Some(threert_render::userfiles::queued_picks(a.pick.clone())));
+ let services: Vec<Box<dyn threert_render::host::HostServices>> = vec![Box::new(net::Net::new()), Box::new(files)];
+ view::run(a, Box::new(services))?;
}
"setup" => {
// Setup cost of a game bundle in the embedded runtime (as on a render node).
@@ -379,7 +384,7 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u
host.settle_physics((start.max(0.0) * 60.0).round() as u32);
let mut w = host.world.borrow_mut();
w.take_changes();
- let missing: Vec<String> = w.files().into_iter().filter(|f| !job.game.assets.join(f).is_file()).collect();
+ let missing: Vec<String> = w.files().into_iter().filter(|f| !threert_render::files::asset_path(&job.game.assets, f).is_file()).collect();
if !missing.is_empty() {
return Err(MissingFiles(missing).into());
}
@@ -449,7 +454,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
let mut sc = {
let mut w = host.world.borrow_mut();
w.take_changes();
- let missing: Vec<String> = w.files().into_iter().filter(|f| !job.game.assets.join(f).is_file()).collect();
+ let missing: Vec<String> = w.files().into_iter().filter(|f| !threert_render::files::asset_path(&job.game.assets, f).is_file()).collect();
if !missing.is_empty() {
return Err(MissingFiles(missing).into());
}
diff --git a/renderer/src/procasset.rs b/renderer/src/procasset.rs
index 6cb70b6..38f1f48 100644
--- a/renderer/src/procasset.rs
+++ b/renderer/src/procasset.rs
@@ -160,7 +160,7 @@ impl ProcBlob {
/// An asset file under the asset root (the path already checked by the world), parsed once per file version.
pub fn load(uri: &str, assets: &Path) -> Result<Arc<ProcBlob>> {
static CACHE: std::sync::Mutex<Option<std::collections::HashMap<String, Arc<ProcBlob>>>> = std::sync::Mutex::new(None);
- let path = assets.join(uri);
+ let path = crate::files::asset_path(assets, uri);
let key = crate::scene::file_key(&path);
if let Some(b) = CACHE.lock().unwrap().as_ref().and_then(|c| c.get(&key)) {
return Ok(b.clone());
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 3a8e23e..df696ee 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -776,7 +776,7 @@ fn bytes_key(kind: &str, bytes: &[u8]) -> String {
fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image::RgbaImage>)> {
match &t.source {
world::TextureSource::File(uri) => {
- let path = assets.join(uri);
+ let path = crate::files::asset_path(assets, uri);
let key = file_key(&path);
Ok((key.clone(), cached_image(&key, || crate::files::image(&path).with_context(|| format!("texture {uri}")))?))
}
@@ -793,7 +793,7 @@ fn texture_image(t: &world::Texture, assets: &Path) -> Result<(String, Arc<image
/// A model file (cached per file version).
pub fn model_gltf(uri: &str, assets: &Path) -> Result<Arc<skin::Model>> {
- let path = assets.join(uri);
+ let path = crate::files::asset_path(assets, uri);
cached_gltf(&file_key(&path), || skin::Model::new(import_gltf(&path).with_context(|| format!("asset {uri}"))?))
}
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index 5447d58..3edb43a 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -92,6 +92,34 @@ const FRAME_MS: u64 = 50;
/// drains, a render node's, keeps the first of them and drops the rest), and the most bytes of one.
const MAX_POSTS: usize = 1024;
const MAX_POST_BYTES: usize = 1 << 20;
+/// A `store.write` carries a file (docs/RUNTIME.md "Files": at most 64 MiB, in base64): the most bytes of one, and of
+/// the whole queue.
+const MAX_STORE_WRITE_BYTES: usize = 96 << 20;
+const MAX_QUEUE_BYTES: usize = 192 << 20;
+
+/// `__host_base64_encode(bytes: Uint8Array): string`.
+fn base64_encode<'js>(ctx: Ctx<'js>, bytes: Value<'js>) -> rquickjs::Result<String> {
+ use base64::Engine;
+ let a = TypedArray::<u8>::from_value(bytes).ok();
+ let b = a.as_ref().and_then(|a| a.as_bytes()).ok_or_else(|| Exception::throw_type(&ctx, "__host_base64_encode: a Uint8Array"))?;
+ Ok(base64::engine::general_purpose::STANDARD.encode(b))
+}
+
+/// `__host_base64_decode(text: string): Uint8Array`.
+fn base64_decode<'js>(ctx: Ctx<'js>, text: String) -> rquickjs::Result<TypedArray<'js, u8>> {
+ use base64::Engine;
+ let bytes = base64::engine::general_purpose::STANDARD.decode(text.as_bytes()).map_err(|e| Exception::throw_type(&ctx, &format!("__host_base64_decode: {e}")))?;
+ TypedArray::new(ctx, bytes)
+}
+
+/// The type of a message's JSON text, read without building the rest of it.
+fn post_type(text: &str) -> Option<String> {
+ #[derive(serde::Deserialize)]
+ struct Typed {
+ t: String,
+ }
+ serde_json::from_str::<Typed>(text).ok().map(|m| m.t)
+}
/// The most engine time one entry into the script (a frame, an event, setup) is lent, µs: past it the time the engine
/// spends in voxel calls counts against the script's budget again. 250 ms: the largest single edit measured on the
@@ -471,16 +499,21 @@ impl ScriptHost {
// The host channel, script to app: a message's JSON text onto the queue the app drains. False when the
// queue is full (nobody drains it); a message past the size bound is the script's error.
g.set("__host_post", Function::new(ctx.clone(), move |ctx: Ctx, text: String| -> rquickjs::Result<bool> {
- if text.len() > MAX_POST_BYTES {
- return Err(Exception::throw_range(&ctx, &format!("host.post: a message of {} bytes (at most {MAX_POST_BYTES})", text.len())));
+ if text.len() > MAX_POST_BYTES && (text.len() > MAX_STORE_WRITE_BYTES || post_type(&text).as_deref() != Some("store.write")) {
+ let most = if text.len() > MAX_STORE_WRITE_BYTES { MAX_STORE_WRITE_BYTES } else { MAX_POST_BYTES };
+ return Err(Exception::throw_range(&ctx, &format!("host.post: a message of {} bytes (at most {most}; a store.write {MAX_STORE_WRITE_BYTES})", text.len())));
}
let mut q = posts.borrow_mut();
- let room = q.len() < MAX_POSTS;
+ let room = q.len() < MAX_POSTS && q.iter().map(String::len).sum::<usize>() + text.len() <= MAX_QUEUE_BYTES;
if room {
q.push(text);
}
Ok(room)
})?)?;
+ // Bytes as base64 and back, natively: what the host channel carries a file as (docs/RUNTIME.md "Files"),
+ // tens of megabytes that the script would take seconds over. packages/gameplay/src/files.ts uses them.
+ g.set("__host_base64_encode", Function::new(ctx.clone(), base64_encode)?)?;
+ g.set("__host_base64_decode", Function::new(ctx.clone(), base64_decode)?)?;
install_engine(ctx, &w, &v, &ph, &d2)?;
ctx.eval::<(), _>(PRELUDE)?;
code(ctx)?;
@@ -1269,6 +1302,43 @@ mod tests {
assert!(old.take_posts().is_empty());
}
+ /// Files on the channel (docs/RUNTIME.md "Files"): base64 both ways, natively; a `store.write` may carry a file of
+ /// 64 MiB where other messages stop at 1 MiB; and the largest file `files.read` answers with reaches the game and
+ /// is decoded within an entry's budget.
+ #[test]
+ fn files_cross_the_host_channel_as_base64() {
+ use base64::Engine;
+ let b64 = base64::engine::general_purpose::STANDARD;
+ let game = GAME.replace(
+ "frame: (dt) => { frames++; },",
+ "frame: (dt) => { frames++; }, hostMessages: (list, ts) => { for (const m of JSON.parse(list)) if (m.t === 'files.data') { const b = __host_base64_decode(m.data); __host_post(JSON.stringify({ t: 'got', n: b.length, first: b[0], last: b[b.length - 1] })); } },",
+ );
+ let h = ScriptHost::new(&game).unwrap();
+ let text: String = h.call(1000, |ctx| ctx.eval("__host_base64_encode(new Uint8Array([9, 0, 1, 2, 255]).subarray(1))")).unwrap();
+ assert_eq!(text, "AAEC/w==", "a view's own bytes");
+ let back: Vec<u8> = h.call(1000, |ctx| ctx.eval::<TypedArray<u8>, _>("__host_base64_decode('AAEC/w==')").map(|a| a.as_bytes().unwrap().to_vec())).unwrap();
+ assert_eq!(back, [0, 1, 2, 255]);
+ assert!(h.call(1000, |ctx| ctx.eval::<(), _>("__host_base64_decode('**')")).is_err());
+ assert!(h.call(1000, |ctx| ctx.eval::<(), _>("__host_base64_encode([1, 2])")).is_err());
+ // A file of 64 MiB the game stores: one post (its text, 85 MiB) where any other message stops at 1 MiB.
+ let t0 = Instant::now();
+ let ok: bool = h.call(EVENT_MS, |ctx| ctx.eval("const big = new Uint8Array(64 << 20); big[0] = 7; __host_post(JSON.stringify({ t: 'store.write', id: 1, path: 'maps/a.glb', data: __host_base64_encode(big) }))")).unwrap();
+ assert!(ok);
+ let posts = h.take_posts();
+ assert_eq!((posts[0]["t"].as_str(), b64.decode(posts[0]["data"].as_str().unwrap()).unwrap().len()), (Some("store.write"), 64 << 20));
+ eprintln!("a 64 MiB store.write posted and taken in {:.0} ms", t0.elapsed().as_secs_f64() * 1e3);
+ assert!(h.call(1000, |ctx| ctx.eval::<bool, _>("__host_post(JSON.stringify({ t: 'net.send', id: 'a', data: 'x'.repeat(2 << 20) }))")).is_err());
+ assert!(h.call(1000, |ctx| ctx.eval::<bool, _>("__host_post(JSON.stringify({ t: 'store.write', id: 2, path: 'a', data: 'x'.repeat(100 << 20) }))")).is_err());
+ // The largest file the app reads for the game, delivered in one batch and decoded under an event's budget.
+ let mut file = vec![0u8; 64 << 20];
+ (file[0], file[(64 << 20) - 1]) = (3, 5);
+ let m = serde_json::json!({ "t": "files.data", "id": "r", "ok": true, "data": b64.encode(&file), "size": file.len() });
+ let t0 = Instant::now();
+ h.host_messages(&[m]).unwrap();
+ eprintln!("a 64 MiB files.data delivered and decoded in {:.0} ms (an entry's budget: {EVENT_MS} ms)", t0.elapsed().as_secs_f64() * 1e3);
+ assert_eq!(h.take_posts(), vec![serde_json::json!({ "t": "got", "n": 64 << 20, "first": 3, "last": 5 })]);
+ }
+
// The game above with what a game written with promises leaves behind in each entry: a `.then` chain and an
// `async` function (`left`), and a request the app answers in a later message (`ask`: the host channel's
// `net.fetch` as a library wraps it). `sync` is the node host's: the engine follows what the jobs changed.
diff --git a/renderer/src/userfiles.rs b/renderer/src/userfiles.rs
new file mode 100644
index 0000000..e04b3c6
--- /dev/null
+++ b/renderer/src/userfiles.rs
@@ -0,0 +1,670 @@
+//! The app's side of `files.*` and `store.*` (docs/RUNTIME.md "Files"): the files the player picked, read only, and
+//! the game's own storage on this device. A game has no I/O; it asks the app, and the app answers with what the player
+//! allowed (a grant: the folder or files picked) or with what is under the game's store directory, and nothing else.
+//!
+//! - [`Store`]: one game's store, a directory: paths checked (`files::check_store_path`), writes atomic (a temporary
+//! file beside the file, renamed over it), a quota.
+//! - [`Grant`]: what a pick allowed: the folder's matching files (to 6 levels, at most 4,000, hidden ones left out) or
+//! the files picked; `files.read` reads those and nothing else.
+//! - [`UserFiles`]: both as `HostServices` for a window. The work (a walk of a folder, reading and writing tens of
+//! megabytes, base64) is done on a thread of its own, one request after another in the order they were posted; the
+//! answers wait in a queue the window empties once a frame. Who asks the player is a [`Picker`]: `threert-render
+//! play` answers with the paths of its `--pick` flag ([`queued_picks`]), an app with a dialog.
+
+use crate::files::check_store_path;
+use crate::host::HostServices;
+use base64::Engine;
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::mpsc;
+
+/// The largest file `files.read` and `store.read` answer with, and `store.write` takes.
+pub const MAX_FILE: u64 = 64 << 20;
+/// A game's store holds at most this many bytes.
+pub const QUOTA: u64 = 1 << 30;
+/// A folder's entries: how deep (a file at depth 6 is `a/b/c/d/e/f.bsp`), how many.
+pub const MAX_DEPTH: usize = 6;
+pub const MAX_ENTRIES: usize = 4000;
+
+fn b64() -> base64::engine::GeneralPurpose {
+ base64::engine::general_purpose::STANDARD
+}
+
+// ------------------------------------------------------------------------------------------------ the store
+
+/// A game's store: a directory of its own on this device.
+pub struct Store {
+ root: PathBuf,
+ quota: u64,
+ /// Bytes under the root, once counted (kept as writes and removes change it).
+ used: Option<u64>,
+ /// Names of temporary files.
+ seq: u64,
+}
+
+impl Store {
+ /// The store in `root` (made when first written to).
+ pub fn new(root: impl Into<PathBuf>) -> Store {
+ Store { root: root.into(), quota: QUOTA, used: None, seq: 0 }
+ }
+
+ /// The same with another quota (bytes).
+ pub fn with_quota(root: impl Into<PathBuf>, quota: u64) -> Store {
+ Store { quota, ..Store::new(root) }
+ }
+
+ pub fn root(&self) -> &Path {
+ &self.root
+ }
+
+ /// Bytes under the root (every file, also the ones that are not the game's: a temporary file a crash left).
+ pub fn used(&mut self) -> u64 {
+ if let Some(u) = self.used {
+ return u;
+ }
+ let mut n = 0;
+ walk_all(&self.root, &mut |_, len| n += len);
+ self.used = Some(n);
+ n
+ }
+
+ fn file(&self, path: &str) -> Result<PathBuf, String> {
+ check_store_path(path)?;
+ Ok(self.root.join(path))
+ }
+
+ /// Writes the file `path` (a whole file, atomically: one who reads it sees the old bytes or the new ones).
+ /// `"quota"` when the store would hold more than its quota.
+ pub fn write(&mut self, path: &str, bytes: &[u8]) -> Result<(), String> {
+ let file = self.file(path)?;
+ if bytes.len() as u64 > MAX_FILE {
+ return Err("too large".into());
+ }
+ let old = match std::fs::symlink_metadata(&file) {
+ Ok(m) if m.is_dir() => return Err(format!("{path}: a directory is there")),
+ Ok(m) => m.len(),
+ Err(_) => 0,
+ };
+ let used = self.used();
+ if used - old.min(used) + bytes.len() as u64 > self.quota {
+ return Err("quota".into());
+ }
+ let dir = file.parent().expect("a store path has a parent: the root");
+ std::fs::create_dir_all(dir).map_err(|e| format!("{path}: {e}"))?;
+ // (A name a store path cannot have: `~` is not among its characters, so it is never a game's file, and `list`
+ // leaves it out if a crash leaves it behind.)
+ self.seq += 1;
+ let tmp = dir.join(format!("{}~{}-{}.tmp", file.file_name().unwrap().to_string_lossy(), std::process::id(), self.seq));
+ let written = (|| -> std::io::Result<()> {
+ let mut f = std::fs::File::create(&tmp)?;
+ f.write_all(bytes)?;
+ f.sync_all()?;
+ std::fs::rename(&tmp, &file)
+ })();
+ if let Err(e) = written {
+ let _ = std::fs::remove_file(&tmp);
+ self.used = None;
+ return Err(format!("{path}: {e}"));
+ }
+ self.used = Some(used - old.min(used) + bytes.len() as u64);
+ Ok(())
+ }
+
+ /// The file `path`. `"absent"` when there is none.
+ pub fn read(&self, path: &str) -> Result<Vec<u8>, String> {
+ let file = self.file(path)?;
+ match std::fs::symlink_metadata(&file) {
+ Ok(m) if m.is_file() && m.len() > MAX_FILE => Err("too large".into()),
+ Ok(m) if m.is_file() => std::fs::read(&file).map_err(|e| format!("{path}: {e}")),
+ _ => Err("absent".into()),
+ }
+ }
+
+ /// The files whose path starts with `prefix` (a plain string: `"maps/"` is everything under maps), sorted.
+ pub fn list(&self, prefix: &str) -> Vec<(String, u64)> {
+ let mut out = vec![];
+ walk_all(&self.root, &mut |rel, len| {
+ if rel.starts_with(prefix) && check_store_path(rel).is_ok() {
+ out.push((rel.to_string(), len));
+ }
+ });
+ out.sort();
+ out
+ }
+
+ /// Removes the file `path`, or the directory `path` and everything in it. Nothing there is not an error.
+ pub fn remove(&mut self, path: &str) -> Result<(), String> {
+ let file = self.file(path)?;
+ let r = match std::fs::symlink_metadata(&file) {
+ Ok(m) if m.is_dir() => std::fs::remove_dir_all(&file),
+ Ok(_) => std::fs::remove_file(&file),
+ Err(_) => return Ok(()),
+ };
+ self.used = None;
+ r.map_err(|e| format!("{path}: {e}"))
+ }
+}
+
+/// Every file under `root` with its path relative to it (`/`-separated), symbolic links left out.
+fn walk_all(root: &Path, f: &mut dyn FnMut(&str, u64)) {
+ fn go(dir: &Path, rel: &str, f: &mut dyn FnMut(&str, u64)) {
+ let Ok(list) = std::fs::read_dir(dir) else { return };
+ for e in list.flatten() {
+ let Ok(m) = e.file_type() else { continue };
+ let name = e.file_name().to_string_lossy().into_owned();
+ let path = if rel.is_empty() { name } else { format!("{rel}/{name}") };
+ if m.is_dir() {
+ go(&e.path(), &path, f);
+ } else if m.is_file() {
+ f(&path, e.metadata().map_or(0, |m| m.len()));
+ }
+ }
+ }
+ go(root, "", f)
+}
+
+// ------------------------------------------------------------------------------------------------ picks
+
+/// How the player picks: a folder (its matching files are the grant) or files.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PickMode {
+ Folder,
+ Files,
+}
+
+/// What the game asked the player for (`files.pick`).
+#[derive(Clone, Debug)]
+pub struct PickRequest {
+ pub mode: PickMode,
+ /// Lower-case extensions with the dot; empty: every file.
+ pub accept: Vec<String>,
+ pub title: Option<String>,
+}
+
+/// Asks the player: the folder (one path) or the files they chose, or why there are none (`"canceled"`, `"busy"`,
+/// `"unsupported"`, `"denied"`, a sentence).
+pub type Picker = Box<dyn FnMut(&PickRequest) -> Result<Vec<PathBuf>, String> + Send>;
+
+/// `threert-render play --pick a,b`: the first `files.pick` is answered with `a`, the second with `b`, then each is
+/// `"canceled"`. Without paths every pick is `"unsupported"`.
+pub fn queued_picks(paths: Vec<PathBuf>) -> Picker {
+ let none = paths.is_empty();
+ let mut queue = std::collections::VecDeque::from(paths);
+ Box::new(move |_| match queue.pop_front() {
+ Some(p) => Ok(vec![p]),
+ None => Err(if none { "unsupported" } else { "canceled" }.into()),
+ })
+}
+
+/// What a pick allowed.
+#[derive(Clone, Debug)]
+pub struct Grant {
+ /// The folder's name, or the file's.
+ pub name: String,
+ /// Paths as the game names them (relative to the folder, `/`-separated; a file's name) and their sizes, sorted.
+ pub entries: Vec<(String, u64)>,
+ files: HashMap<String, PathBuf>,
+}
+
+fn accepted(name: &str, accept: &[String]) -> bool {
+ let lower = name.to_ascii_lowercase();
+ accept.is_empty() || accept.iter().any(|a| lower.ends_with(a.as_str()))
+}
+
+fn name_of(p: &Path) -> String {
+ p.file_name().map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into_owned())
+}
+
+impl Grant {
+ /// A folder: its files that match `accept`, at most `MAX_DEPTH` levels down and `MAX_ENTRIES` of them, hidden
+ /// files and directories and symbolic links left out.
+ pub fn folder(dir: &Path, accept: &[String]) -> Result<Grant, String> {
+ let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
+ if !dir.is_dir() {
+ return Err(format!("{} is not a folder", name_of(&dir)));
+ }
+ let mut g = Grant { name: name_of(&dir), entries: vec![], files: HashMap::new() };
+ fn go(g: &mut Grant, dir: &Path, rel: &str, depth: usize, accept: &[String]) {
+ let Ok(list) = std::fs::read_dir(dir) else { return };
+ let mut list: Vec<_> = list.flatten().collect();
+ list.sort_by_key(|e| e.file_name());
+ for e in list {
+ if g.entries.len() >= MAX_ENTRIES {
+ return;
+ }
+ let name = e.file_name().to_string_lossy().into_owned();
+ let Ok(t) = e.file_type() else { continue };
+ if name.starts_with('.') {
+ continue;
+ }
+ let path = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };
+ if t.is_dir() && depth < MAX_DEPTH {
+ go(g, &e.path(), &path, depth + 1, accept);
+ } else if t.is_file() && accepted(&name, accept) {
+ g.entries.push((path.clone(), e.metadata().map_or(0, |m| m.len())));
+ g.files.insert(path, e.path());
+ }
+ }
+ }
+ go(&mut g, &dir, "", 1, accept);
+ g.entries.sort();
+ Ok(g)
+ }
+
+ /// Files the player chose: each by its name (the first of two of one name). A folder among them stands for the
+ /// files in it (not below).
+ pub fn files(paths: &[PathBuf], accept: &[String]) -> Result<Grant, String> {
+ let mut g = Grant { name: paths.first().map(|p| name_of(p)).unwrap_or_default(), entries: vec![], files: HashMap::new() };
+ let mut add = |p: PathBuf| {
+ let name = name_of(&p);
+ if !name.starts_with('.') && accepted(&name, accept) && !g.files.contains_key(&name) {
+ if let Some(m) = std::fs::metadata(&p).ok().filter(|m| m.is_file()) {
+ g.entries.push((name.clone(), m.len()));
+ g.files.insert(name, p);
+ }
+ }
+ };
+ for p in paths {
+ if p.is_dir() {
+ let mut list: Vec<PathBuf> = std::fs::read_dir(p).map_err(|e| format!("{}: {e}", p.display()))?.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_file())).map(|e| e.path()).collect();
+ list.sort();
+ list.into_iter().for_each(&mut add);
+ } else if p.is_file() {
+ add(p.clone());
+ } else {
+ return Err(format!("{}: no such file", name_of(p)));
+ }
+ }
+ g.entries.sort();
+ Ok(g)
+ }
+
+ /// The file `path` of the grant: `"denied"` for one that is not among its entries.
+ pub fn read(&self, path: &str) -> Result<Vec<u8>, String> {
+ let file = self.files.get(path).ok_or("denied")?;
+ let len = std::fs::metadata(file).map_err(|e| format!("{path}: {e}"))?.len();
+ if len > MAX_FILE {
+ return Err("too large".into());
+ }
+ std::fs::read(file).map_err(|e| format!("{path}: {e}"))
+ }
+}
+
+// ------------------------------------------------------------------------------------------------ the services
+
+/// The requests' side that does the work: the store, the grants of the session, the picker.
+pub struct Requests {
+ pub store: Option<Store>,
+ picker: Option<Picker>,
+ grants: HashMap<String, Grant>,
+}
+
+impl Requests {
+ pub fn new(store: Option<Store>, picker: Option<Picker>) -> Requests {
+ Requests { store, picker, grants: HashMap::new() }
+ }
+
+ /// The families answered: `"files"` with a picker, `"store"` with a store.
+ pub fn caps(&self) -> Vec<&'static str> {
+ let mut c = vec![];
+ if self.picker.is_some() {
+ c.push("files");
+ }
+ if self.store.is_some() {
+ c.push("store");
+ }
+ c
+ }
+
+ /// Whether a message is a request of these families (`files.pick`, `files.read`, `store.*`).
+ pub fn takes(m: &Value) -> bool {
+ matches!(m["t"].as_str(), Some("files.pick" | "files.read" | "store.write" | "store.read" | "store.list" | "store.remove"))
+ }
+
+ /// The answer to a request (`None`: not one of these families').
+ pub fn answer(&mut self, m: &Value) -> Option<Value> {
+ let id = m["id"].clone();
+ let fail = |t: &str, reason: String| json!({ "t": t, "id": id, "ok": false, "reason": reason });
+ let t = m["t"].as_str()?;
+ Some(match t {
+ "files.pick" => match self.pick(m) {
+ Ok((pick, g)) => json!({ "t": "files.picked", "id": id, "ok": true, "pick": pick, "name": g.name, "entries": entries(&g.entries) }),
+ Err(e) => fail("files.picked", e),
+ },
+ "files.read" => {
+ let r = match (m["pick"].as_str().and_then(|p| self.grants.get(p)), m["path"].as_str()) {
+ (Some(g), Some(path)) => g.read(path),
+ _ => Err("denied".into()),
+ };
+ match r {
+ Ok(b) => json!({ "t": "files.data", "id": id, "ok": true, "data": b64().encode(&b), "size": b.len() }),
+ Err(e) => fail("files.data", e),
+ }
+ }
+ "store.write" | "store.read" | "store.list" | "store.remove" => {
+ let answer = match t {
+ "store.read" => "store.data",
+ "store.list" => "store.listed",
+ _ => "store.done",
+ };
+ let Some(store) = self.store.as_mut() else { return Some(fail(answer, "unsupported".into())) };
+ let path = m["path"].as_str().unwrap_or("");
+ match t {
+ "store.write" => {
+ let bytes = match (m["data"].as_str(), m["text"].as_str()) {
+ (Some(d), _) => b64().decode(d).map_err(|e| format!("data is not base64: {e}")),
+ (None, Some(text)) => Ok(text.as_bytes().to_vec()),
+ (None, None) => Err("no data and no text".into()),
+ };
+ match bytes.and_then(|b| store.write(path, &b)) {
+ Ok(()) => json!({ "t": answer, "id": id, "ok": true }),
+ Err(e) => fail(answer, e),
+ }
+ }
+ "store.read" => match store.read(path) {
+ Ok(b) if m["as"] == "text" => match String::from_utf8(b) {
+ Ok(text) => json!({ "t": answer, "id": id, "ok": true, "size": text.len(), "text": text }),
+ Err(_) => fail(answer, "not text".into()),
+ },
+ Ok(b) => json!({ "t": answer, "id": id, "ok": true, "size": b.len(), "data": b64().encode(&b) }),
+ Err(e) => fail(answer, e),
+ },
+ "store.list" => json!({ "t": answer, "id": id, "ok": true, "entries": entries(&store.list(m["prefix"].as_str().unwrap_or(""))) }),
+ _ => match store.remove(path) {
+ Ok(()) => json!({ "t": answer, "id": id, "ok": true }),
+ Err(e) => fail(answer, e),
+ },
+ }
+ }
+ _ => return None,
+ })
+ }
+
+ fn pick(&mut self, m: &Value) -> Result<(String, Grant), String> {
+ let mode = match m["mode"].as_str() {
+ Some("folder") => PickMode::Folder,
+ Some("files") => PickMode::Files,
+ _ => return Err("mode is \"folder\" or \"files\"".into()),
+ };
+ let accept = m["accept"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).map(|x| x.to_ascii_lowercase()).collect()).unwrap_or_default();
+ let req = PickRequest { mode, accept, title: m["title"].as_str().map(String::from) };
+ let picker = self.picker.as_mut().ok_or("unsupported")?;
+ let paths = picker(&req)?;
+ let g = match mode {
+ PickMode::Folder => Grant::folder(paths.first().ok_or("canceled")?, &req.accept)?,
+ PickMode::Files => Grant::files(&paths, &req.accept)?,
+ };
+ let pick = format!("pick-{}", self.grants.len() + 1);
+ self.grants.insert(pick.clone(), g.clone());
+ Ok((pick, g))
+ }
+}
+
+fn entries(list: &[(String, u64)]) -> Value {
+ list.iter().map(|(path, size)| json!({ "path": path, "size": size })).collect()
+}
+
+/// `files.*` and `store.*` for a window: [`Requests`] on a thread of its own.
+pub struct UserFiles {
+ caps: Vec<&'static str>,
+ tx: mpsc::Sender<Value>,
+ rx: mpsc::Receiver<Value>,
+}
+
+impl UserFiles {
+ /// The store in `store` (none: no `store.*`), the player asked by `picker` (none: no `files.*`).
+ pub fn new(store: Option<PathBuf>, picker: Option<Picker>) -> UserFiles {
+ let mut r = Requests::new(store.map(Store::new), picker);
+ let caps = r.caps();
+ let (tx, requests) = mpsc::channel::<Value>();
+ let (answers, rx) = mpsc::channel();
+ std::thread::Builder::new()
+ .name("threert-userfiles".into())
+ .spawn(move || {
+ for m in requests {
+ if let Some(a) = r.answer(&m) {
+ if answers.send(a).is_err() {
+ break;
+ }
+ }
+ }
+ })
+ .expect("a thread for the user's files");
+ UserFiles { caps, tx, rx }
+ }
+}
+
+impl HostServices for UserFiles {
+ fn post(&mut self, m: &Value) {
+ if Requests::takes(m) {
+ let _ = self.tx.send(m.clone());
+ }
+ }
+ fn poll(&mut self) -> Vec<Value> {
+ self.rx.try_iter().collect()
+ }
+ fn caps(&self) -> Vec<&'static str> {
+ self.caps.clone()
+ }
+}
+
+/// A post as the window shows it on stdout: a `store.write`'s bytes as their count.
+pub fn without_payload(m: &Value) -> Value {
+ if m["t"] != "store.write" {
+ return m.clone();
+ }
+ let mut m = m.clone();
+ if let Some(o) = m.as_object_mut() {
+ for k in ["data", "text"] {
+ if let Some(v) = o.remove(k) {
+ o.insert(format!("{k}Length"), v.as_str().map_or(0, str::len).into());
+ }
+ }
+ }
+ m
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("threert-userfiles-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ fn ask(r: &mut Requests, m: Value) -> Value {
+ r.answer(&m).expect("an answer")
+ }
+
+ #[test]
+ fn store_paths_are_checked() {
+ for bad in ["", "/abs", "a//b", "a/", "./a", "a/./b", "..", "a/../b", "a b", "a\\b", "maps/é.bsp", "c:x", "a~b", &"x".repeat(201)] {
+ assert!(check_store_path(bad).is_err(), "{bad:?} is refused");
+ }
+ for good in ["a", "maps/de_dust2/map.glb", ".hidden", "a.b-c_d/E9", &"x".repeat(200)] {
+ assert!(check_store_path(good).is_ok(), "{good:?} is a store path");
+ }
+ let root = temp("paths");
+ let mut r = Requests::new(Some(Store::new(&root)), None);
+ for bad in ["../outside", "/etc/passwd", "a/../../b", "x y"] {
+ let a = ask(&mut r, json!({ "t": "store.write", "id": 1, "path": bad, "text": "no" }));
+ assert_eq!((a["t"].as_str(), a["ok"].as_bool()), (Some("store.done"), Some(false)), "{bad}: {a}");
+ let a = ask(&mut r, json!({ "t": "store.read", "id": 2, "path": bad, "as": "text" }));
+ assert_eq!(a["ok"], false, "{a}");
+ let a = ask(&mut r, json!({ "t": "store.remove", "id": 3, "path": bad }));
+ assert_eq!(a["ok"], false, "{a}");
+ }
+ assert!(!root.parent().unwrap().join("outside").exists());
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn the_store_writes_reads_lists_and_removes() {
+ let root = temp("store");
+ let mut r = Requests::new(Some(Store::new(root.join("game"))), None);
+ assert_eq!(r.caps(), vec!["store"]);
+ let a = ask(&mut r, json!({ "t": "store.write", "id": "w1", "path": "maps/de_x/map.glb", "data": b64().encode([0u8, 1, 2, 255]) }));
+ assert_eq!(a, json!({ "t": "store.done", "id": "w1", "ok": true }));
+ ask(&mut r, json!({ "t": "store.write", "id": "w2", "path": "maps/de_x/info.json", "text": "{\"name\":\"x\"}" }));
+ ask(&mut r, json!({ "t": "store.write", "id": "w3", "path": "settings.json", "text": "é" }));
+ let a = ask(&mut r, json!({ "t": "store.read", "id": "r1", "path": "maps/de_x/map.glb", "as": "base64" }));
+ assert_eq!(a, json!({ "t": "store.data", "id": "r1", "ok": true, "size": 4, "data": "AAEC/w==" }));
+ let a = ask(&mut r, json!({ "t": "store.read", "id": "r2", "path": "settings.json", "as": "text" }));
+ assert_eq!((a["text"].as_str(), a["size"].as_u64()), (Some("é"), Some(2)));
+ let a = ask(&mut r, json!({ "t": "store.read", "id": "r3", "path": "maps/de_x/map.glb", "as": "text" }));
+ assert_eq!(a["reason"], "not text");
+ let a = ask(&mut r, json!({ "t": "store.read", "id": "r4", "path": "nothing.here", "as": "text" }));
+ assert_eq!(a, json!({ "t": "store.data", "id": "r4", "ok": false, "reason": "absent" }));
+ let a = ask(&mut r, json!({ "t": "store.list", "id": "l1" }));
+ assert_eq!(a["entries"], json!([{ "path": "maps/de_x/info.json", "size": 12 }, { "path": "maps/de_x/map.glb", "size": 4 }, { "path": "settings.json", "size": 2 }]));
+ let a = ask(&mut r, json!({ "t": "store.list", "id": "l2", "prefix": "maps/" }));
+ assert_eq!(a["entries"].as_array().unwrap().len(), 2);
+ // A leftover temporary file (a crash in a write) is not the game's.
+ std::fs::write(root.join("game/maps/map.glb~1-1.tmp"), "x").unwrap();
+ assert_eq!(ask(&mut r, json!({ "t": "store.list", "id": "l3", "prefix": "maps/" }))["entries"].as_array().unwrap().len(), 2);
+ // Overwritten whole.
+ ask(&mut r, json!({ "t": "store.write", "id": "w4", "path": "settings.json", "text": "{}" }));
+ assert_eq!(ask(&mut r, json!({ "t": "store.read", "id": "r5", "path": "settings.json", "as": "text" }))["text"], "{}");
+ // A directory and what is in it; then nothing there, which is no error.
+ assert_eq!(ask(&mut r, json!({ "t": "store.remove", "id": "d1", "path": "maps" })), json!({ "t": "store.done", "id": "d1", "ok": true }));
+ assert_eq!(ask(&mut r, json!({ "t": "store.remove", "id": "d2", "path": "maps" }))["ok"], true);
+ assert_eq!(ask(&mut r, json!({ "t": "store.list", "id": "l4" }))["entries"], json!([{ "path": "settings.json", "size": 2 }]));
+ // Not base64, nothing to write, a directory in the way.
+ assert_eq!(ask(&mut r, json!({ "t": "store.write", "id": "w5", "path": "a", "data": "**" }))["ok"], false);
+ assert_eq!(ask(&mut r, json!({ "t": "store.write", "id": "w6", "path": "a" }))["ok"], false);
+ ask(&mut r, json!({ "t": "store.write", "id": "w7", "path": "dir/f", "text": "x" }));
+ assert_eq!(ask(&mut r, json!({ "t": "store.write", "id": "w8", "path": "dir", "text": "x" }))["ok"], false);
+ // Messages of other families are not these services'.
+ assert!(r.answer(&json!({ "t": "net.open", "id": 1 })).is_none());
+ // Without a store: every store request says so.
+ let mut none = Requests::new(None, None);
+ assert!(none.caps().is_empty());
+ assert_eq!(ask(&mut none, json!({ "t": "store.list", "id": 9 })), json!({ "t": "store.listed", "id": 9, "ok": false, "reason": "unsupported" }));
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn writes_are_atomic_and_held_to_the_quota() {
+ let root = temp("quota");
+ let mut s = Store::with_quota(&root, 1000);
+ s.write("a.bin", &[1; 600]).unwrap();
+ assert_eq!(s.write("b.bin", &[2; 500]), Err("quota".into()));
+ assert!(!root.join("b.bin").exists(), "a refused write leaves nothing");
+ // Replacing a file counts its new size, not both.
+ s.write("a.bin", &[3; 900]).unwrap();
+ assert_eq!(s.read("a.bin").unwrap(), vec![3; 900]);
+ assert_eq!(s.used(), 900);
+ s.remove("a.bin").unwrap();
+ s.write("b.bin", &[2; 1000]).unwrap();
+ assert_eq!(s.used(), 1000);
+ // The count is the disk's: a store opened anew counts what is there.
+ assert_eq!(Store::with_quota(&root, 1000).write("c", b"x"), Err("quota".into()));
+ // No temporary file is left beside a written one.
+ let names: Vec<String> = std::fs::read_dir(&root).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
+ assert_eq!(names, vec!["b.bin".to_string()]);
+ // A write that fails (its directory is a file) leaves the old file and no temporary one.
+ std::fs::write(root.join("f"), "file").unwrap();
+ let mut s = Store::new(&root);
+ assert!(s.write("f/g", b"x").is_err());
+ assert_eq!(std::fs::read_dir(&root).unwrap().count(), 2);
+ // A reader sees the old bytes or the new ones, never a part (the rename): many writes while a thread reads.
+ let reader = {
+ let path = root.join("big.bin");
+ std::fs::write(&path, vec![0u8; 1 << 20]).unwrap();
+ std::thread::spawn(move || {
+ for _ in 0..200 {
+ let b = std::fs::read(&path).unwrap();
+ assert_eq!(b.len(), 1 << 20);
+ assert!(b.iter().all(|&x| x == b[0]), "a whole file");
+ }
+ })
+ };
+ for k in 1..40u8 {
+ s.write("big.bin", &vec![k; 1 << 20]).unwrap();
+ }
+ reader.join().unwrap();
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn picks_answer_from_the_queue_and_reads_stay_inside_the_grant() {
+ let root = temp("picks");
+ let game = root.join("cstrike");
+ for (p, body) in [("maps/de_x.bsp", "BSP"), ("maps/DE_Y.BSP", "BSP2"), ("maps/readme.txt", "no"), ("cstrike.wad", "WAD"), (".hidden/z.bsp", "no"), ("a/b/c/d/e/f.bsp", "deep6"), ("a/b/c/d/e/f/g.bsp", "deep7")] {
+ std::fs::create_dir_all(game.join(p).parent().unwrap()).unwrap();
+ std::fs::write(game.join(p), body).unwrap();
+ }
+ std::fs::write(root.join("secret.bsp"), "outside").unwrap();
+ let picker = queued_picks(vec![game.clone(), game.join("maps/de_x.bsp")]);
+ let mut r = Requests::new(None, Some(picker));
+ assert_eq!(r.caps(), vec!["files"]);
+ let a = ask(&mut r, json!({ "t": "files.pick", "id": "p1", "mode": "folder", "accept": [".bsp", ".WAD"], "title": "Your Counter-Strike folder" }));
+ assert_eq!(a["ok"], true, "{a}");
+ assert_eq!(a["name"], "cstrike");
+ assert_eq!(a["entries"], json!([{ "path": "a/b/c/d/e/f.bsp", "size": 5 }, { "path": "cstrike.wad", "size": 3 }, { "path": "maps/DE_Y.BSP", "size": 4 }, { "path": "maps/de_x.bsp", "size": 3 }]));
+ let pick = a["pick"].as_str().unwrap().to_string();
+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r1", "pick": pick, "path": "maps/de_x.bsp" }));
+ assert_eq!(a, json!({ "t": "files.data", "id": "r1", "ok": true, "data": b64().encode("BSP"), "size": 3 }));
+ for denied in ["maps/readme.txt", "../secret.bsp", "/etc/passwd", ".hidden/z.bsp", "a/b/c/d/e/f/g.bsp", "maps/../../secret.bsp"] {
+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r2", "pick": pick, "path": denied }));
+ assert_eq!(a, json!({ "t": "files.data", "id": "r2", "ok": false, "reason": "denied" }), "{denied}");
+ }
+ assert_eq!(ask(&mut r, json!({ "t": "files.read", "id": "r3", "pick": "pick-9", "path": "maps/de_x.bsp" }))["reason"], "denied");
+ // The second answer: one file.
+ let a = ask(&mut r, json!({ "t": "files.pick", "id": "p2", "mode": "files", "accept": [".bsp"] }));
+ assert_eq!((a["name"].as_str(), a["entries"].clone()), (Some("de_x.bsp"), json!([{ "path": "de_x.bsp", "size": 3 }])));
+ let a = ask(&mut r, json!({ "t": "files.read", "id": "r4", "pick": a["pick"], "path": "de_x.bsp" }));
+ assert_eq!(a["data"], b64().encode("BSP"));
+ // The queue is empty: the player closed the picker.
+ assert_eq!(ask(&mut r, json!({ "t": "files.pick", "id": "p3", "mode": "folder" })), json!({ "t": "files.picked", "id": "p3", "ok": false, "reason": "canceled" }));
+ assert_eq!(ask(&mut r, json!({ "t": "files.pick", "id": "p4", "mode": "everything" }))["ok"], false);
+ // Without `--pick`: unsupported. Without a picker at all: the same.
+ let mut r = Requests::new(None, Some(queued_picks(vec![])));
+ assert_eq!(ask(&mut r, json!({ "t": "files.pick", "id": 1, "mode": "folder" }))["reason"], "unsupported");
+ let mut r = Requests::new(None, None);
+ assert_eq!(ask(&mut r, json!({ "t": "files.pick", "id": 1, "mode": "folder" }))["reason"], "unsupported");
+ // A folder asked for, a file given.
+ let mut r = Requests::new(None, Some(queued_picks(vec![root.join("secret.bsp")])));
+ assert_eq!(ask(&mut r, json!({ "t": "files.pick", "id": 1, "mode": "folder" }))["ok"], false);
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn a_folder_has_at_most_its_entries() {
+ let root = temp("many");
+ for i in 0..MAX_ENTRIES + 10 {
+ std::fs::write(root.join(format!("{i:05}.bsp")), "").unwrap();
+ }
+ assert_eq!(Grant::folder(&root, &[]).unwrap().entries.len(), MAX_ENTRIES);
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn the_services_answer_on_their_thread_in_order() {
+ let root = temp("thread");
+ std::fs::write(root.join("x.bsp"), "BSP").unwrap();
+ let mut s = UserFiles::new(Some(root.join("store")), Some(queued_picks(vec![root.clone()])));
+ assert_eq!(s.caps(), vec!["files", "store"]);
+ s.post(&json!({ "t": "store.write", "id": 1, "path": "a.txt", "text": "one" }));
+ s.post(&json!({ "t": "store.read", "id": 2, "path": "a.txt", "as": "text" }));
+ s.post(&json!({ "t": "files.pick", "id": 3, "mode": "folder", "accept": [".bsp"] }));
+ s.post(&json!({ "t": "net.open", "id": 4, "url": "wss://example.org" }));
+ let mut got = vec![];
+ let t0 = std::time::Instant::now();
+ while got.len() < 3 && t0.elapsed().as_secs() < 10 {
+ got.extend(s.poll());
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ assert_eq!(got.iter().map(|m| m["id"].as_u64().unwrap()).collect::<Vec<_>>(), vec![1, 2, 3]);
+ assert_eq!(got[1]["text"], "one");
+ assert_eq!(got[2]["entries"], json!([{ "path": "x.bsp", "size": 3 }]));
+ let w = without_payload(&json!({ "t": "store.write", "id": 1, "path": "a", "data": "AAAA" }));
+ assert_eq!(w, json!({ "t": "store.write", "id": 1, "path": "a", "dataLength": 4 }));
+ let _ = std::fs::remove_dir_all(root);
+ }
+}
diff --git a/renderer/src/view.rs b/renderer/src/view.rs
index bb9d080..a3e4ad5 100644
--- a/renderer/src/view.rs
+++ b/renderer/src/view.rs
@@ -2,6 +2,7 @@
//! denoise + UE post) presented straight to a vsync'd swapchain at 60 fps. No encoding, no network.
//!
//! threert-render play <game bundle.js> [--assets <dir>] [--room id] [--width 1280 --height 720 --fps 60]
+//! [--launch '{..}'] [--store <dir>] [--pick <dir|file>[,...]]
//!
//! The game runs in this process (script.rs): its code builds the scene, key bindings and clicks run its handlers, its
//! frame script animates. `view` is the same window.
@@ -12,7 +13,9 @@
//! Esc again quits. The window is the app of the host channel: `--launch '{"room":"K7Q4MZ"}'` is the `launch`
//! message, `--sensitivity 1.5` scales the look, `--hud-log` prints the HUD the game describes (the window draws
//! none), the game's `net.*` messages are the binary's sockets and HTTP (src/net.rs), and its `audio.*` messages are
-//! played (src/audio, the `audio` feature: the ears are the camera of each frame).
+//! played (src/audio, the `audio` feature: the ears are the camera of each frame). Its `files.*` and `store.*` are
+//! answered from `--pick <dir|file>[,...]` (the player's picks, in order) and `--store <dir>` (the game's storage,
+//! `<assets>/.threert/store` by default; `user:` assets resolve there): src/userfiles.rs.
//!
//! Controls: left-drag orbit · right/shift-drag pan · wheel zoom · WASD/QE fly · R reset camera · 1/2/4/8 cap spp,
//! 0 adaptive · P snapshot · Esc quit. Scripted over stdio:
@@ -22,7 +25,7 @@
//! | {"type":"host","messages":[..]} (what the game posted)
use crate::gpu;
-use crate::host::{launch_message, HostServices, InputTracker};
+use crate::host::{launch_message_with_caps, HostServices, InputTracker};
use crate::live::{next_spp, parse_cmd, parse_scale, save_bgra, Camera, Cmd, LiveCore};
use crate::script::GameSession;
use anyhow::Result;
@@ -57,6 +60,11 @@ pub struct ViewArgs {
pub hud_log: bool,
/// `--sensitivity`: scales the pointer's motion into the game's look (1: `host::LOOK_RADIANS` a count).
pub sensitivity: f32,
+ /// `--store <dir>`: the game's store (`store.*`, `user:` assets; docs/RUNTIME.md "Files"); `<assets>/.threert/store`
+ /// by default.
+ pub store: PathBuf,
+ /// `--pick a,b`: what the player picks, in order, for the game's `files.pick` requests (none: `"unsupported"`).
+ pub pick: Vec<PathBuf>,
}
/// Editor-style orbit camera around a target point.
@@ -212,7 +220,7 @@ impl App {
let (vw, vh) = (config.width, config.height);
let (mut game, mut core) = GameSession::start(&a.bundle, &a.room, &a.assets, g, &a.presets, vw, vh)?;
// The host channel: how the game was opened, once after setup.
- if let Err(e) = game.host_messages(&mut core, &[launch_message(a.launch.as_ref())]) {
+ if let Err(e) = game.host_messages(&mut core, &[launch_message_with_caps(a.launch.as_ref(), &self.services.caps())]) {
eprintln!("game: launch: {e:#}");
}
let pointer = game.host.pointer().map(String::from);
@@ -572,7 +580,8 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServi
}
}
if !posts.is_empty() {
- emit(serde_json::json!({ "type": "host", "messages": posts }));
+ // (A file the game stores is its length here, not tens of megabytes of base64.)
+ emit(serde_json::json!({ "type": "host", "messages": posts.iter().map(crate::userfiles::without_payload).collect::<Vec<_>>() }));
}
// A game that reads input has the camera to itself (the view follows it with every commit); any other game is
// looked at through the window's orbit camera, which follows the game's when a handler moves it.
@@ -775,5 +784,7 @@ pub fn parse_args(args: &[String], presets: &Path) -> Result<ViewArgs> {
launch: crate::live::parse_launch(flag("--launch").as_deref())?,
hud_log: args.iter().any(|a| a == "--hud-log"),
sensitivity: flag("--sensitivity").map(|v| v.parse::<f32>()).transpose()?.filter(|v| v.is_finite()).unwrap_or(1.0),
+ store: flag("--store").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(flag("--assets").unwrap_or_else(|| ".".into())).join(".threert/store")),
+ pick: flag("--pick").map(|p| p.split(',').filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default(),
})
}
diff --git a/renderer/src/world.rs b/renderer/src/world.rs
index 655498a..ad2a588 100644
--- a/renderer/src/world.rs
+++ b/renderer/src/world.rs
@@ -420,8 +420,12 @@ fn light_class(l: &desc::Light) -> (u8, bool, bool) {
}
}
-/// Asset paths are relative to the asset root and stay inside it (game code is untrusted on render nodes).
+/// Asset paths are relative to the asset root and stay inside it (game code is untrusted on render nodes), or name a
+/// file of the game's store (`user:<store path>`, which stays inside the store: files.rs `asset_path`).
pub(crate) fn check_uri(uri: &str) -> Result<()> {
+ if let Some(rel) = uri.strip_prefix(crate::files::USER_SCHEME) {
+ return crate::files::check_store_path(rel).map_err(|e| anyhow!("asset path \"{uri}\": {e}"));
+ }
let p = std::path::Path::new(uri);
let inside = !uri.is_empty() && !uri.contains(':') && p.components().all(|c| matches!(c, std::path::Component::Normal(_)));
if !inside {
diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.lock
index ded1b0b..9274ca3 100644
--- a/renderer/web/Cargo.lock
+++ b/renderer/web/Cargo.lock
@@ -207,6 +207,12 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -851,7 +857,7 @@ version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"
dependencies = [
- "base64",
+ "base64 0.13.1",
"byteorder",
"gltf-json",
"image",
@@ -2670,6 +2676,7 @@ name = "threert-render"
version = "0.1.0"
dependencies = [
"anyhow",
+ "base64 0.23.1",
"bytemuck",
"glam 0.30.10",
"gltf",