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.

The npm packages: @threert/scene, @threert/gameplay, @threert/voxel as npm gets them, and a workflow that publishes them (#46)

Evan (Yifeng) Wang5b6e2a2e3d1d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7c45d4c..89e9196 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -81,6 +81,8 @@ jobs:
- run: npm ci
- run: npm run typecheck
- run: npm test
+ # The npm packages as they are published: built, installed into an empty project, typechecked and run there.
+ - run: node tools/npm-pack.ts
renderer:
name: "renderer: release build"
diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml
new file mode 100644
index 0000000..c42b386
--- /dev/null
+++ b/.github/workflows/npm.yml
@@ -0,0 +1,40 @@
+# Publishes @threert/scene, @threert/gameplay and @threert/voxel to npm, when asked (Actions -> npm -> Run workflow),
+# from main: the version in the root package.json, built and checked by tools/npm-pack.ts. A package whose version npm
+# already has is skipped, so a run after a failed one finishes it, and a second run changes nothing. To release:
+# raise "version" in the root package.json in a PR, merge it, run this.
+#
+# No token: npm trusts this workflow of this repository (each package's Settings -> Trusted publishing on npmjs.com:
+# meshy-dev/ThreeRT, npm.yml), and signs what it publishes with where it was built (provenance). That needs a
+# GitHub-hosted runner and `id-token: write`.
+name: npm
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: "dist-tag: latest, or next for a preview"
+ default: latest
+
+permissions:
+ contents: read
+ id-token: write
+
+concurrency: npm
+
+jobs:
+ publish:
+ name: "publish @threert/*"
+ if: github.ref == 'refs/heads/main'
+ runs-on: ubuntu-26.04
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ registry-url: https://registry.npmjs.org
+ - run: npm ci
+ - run: npm test
+ - run: node tools/npm-pack.ts --publish --tag "$TAG"
+ env:
+ TAG: ${{ inputs.tag }}
diff --git a/docs/WORKFLOW.md b/docs/WORKFLOW.md
index 5bb840e..9909b35 100644
--- a/docs/WORKFLOW.md
+++ b/docs/WORKFLOW.md
@@ -127,8 +127,16 @@ highest tier any of its changes needs.
What landed changes do together beyond these checks is the scheduled suites' to catch.
7. **Visuals:** the supervisor opens the crops and checks that the conclusion matches the pictures.
-PRs are merged with `gh pr merge --merge`, which keeps one merge commit per PR on main's first-parent line. Branches
-are kept.
+PRs are merged with `gh pr merge --squash` (the repository allows nothing else), which keeps one commit per PR on
+main. Branches are kept.
+
+## The npm packages
+
+`@threert/scene`, `@threert/gameplay` and `@threert/voxel` are published from `packages/` with one version, the root
+`package.json`'s. In the repository they are their sources (no build step); `node tools/npm-pack.ts` builds what npm
+gets (JavaScript and declarations, in `out/npm/`) and checks it in an empty project, and CI runs it on every PR. To
+release: raise the version in a PR, merge it, and run the `npm` workflow (Actions → npm → Run workflow). It publishes
+the packages whose version npm does not have yet, without a token (npm trusts that workflow of this repository).
## Scheduled suites on main (after merging)
@@ -162,7 +170,7 @@ a later run compares against the previous one.
builds alternately (a warm launch each, then 5 launches each, a then b), and counts only if the medians still
differ by more than the floor. Measured hours apart, first frames drift with the machine's state: 0ee18d2 against
fa83cef read Bistro 2.07 → 2.50 s and the district 2.10 → 2.70 s; alternated, 2.47 / 2.38 and 2.56 / 2.57 s.
- - **When one is found:** the suite bisects the batch's first-parent merge commits with the same measurement (two or
+ - **When one is found:** the suite bisects the batch's first-parent commits with the same measurement (two or
three steps for a batch of four).
- **Culprit:** the author fixes it forward from main. If main is still over budget at the next check, the
supervisor merges a revert PR.
diff --git a/package-lock.json b/package-lock.json
index 750d44a..9cd2f85 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,10 +1,12 @@
{
"name": "threert",
+ "version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "threert",
+ "version": "0.1.0",
"license": "MIT",
"workspaces": [
"packages/*"
diff --git a/package.json b/package.json
index 4ac0b66..24e9e4c 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,6 @@
{
"name": "threert",
+ "version": "0.1.0",
"private": true,
"license": "MIT",
"type": "module",
@@ -12,7 +13,8 @@
"scenes": "node tools/build-scenes.ts",
"test:render": "node tools/test-render.ts",
"test:layer-b": "node tools/test-layer-b.ts",
- "runtime": "node tools/build-runtime.ts"
+ "runtime": "node tools/build-runtime.ts",
+ "npm:pack": "node tools/npm-pack.ts"
},
"devDependencies": {
"@types/node": "^24.0.0",
diff --git a/packages/gameplay/README.md b/packages/gameplay/README.md
new file mode 100644
index 0000000..f8b212e
--- /dev/null
+++ b/packages/gameplay/README.md
@@ -0,0 +1,75 @@
+# @threert/gameplay
+
+Game logic for [ThreeRT](https://threert.dev), the hardware ray-traced engine with a three.js-style API: state, handlers that change it as transactions, and a frame script that shows it in the scene.
+
+[![npm](https://img.shields.io/npm/v/@threert/gameplay?color=f97316)](https://www.npmjs.com/package/@threert/gameplay)
+[![license](https://img.shields.io/npm/l/@threert/gameplay)](https://github.com/meshy-dev/ThreeRT/blob/main/LICENSE)
+
+## Install
+
+```bash
+npm install @threert/scene @threert/gameplay
+```
+
+## A game
+
+`defineGame` takes the initial state, a `setup` that builds the scene with [`@threert/scene`](https://www.npmjs.com/package/@threert/scene), handlers that change the state, and a `frame` script that derives the scene from the state every frame.
+
+```ts
+import { Scene, PerspectiveCamera, Mesh, SphereGeometry, MeshStandardMaterial, DirectionalLight, SkyAtmosphere } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+
+export default defineGame({
+ state: { lit: {} as Record<string, boolean>, night: false },
+
+ setup() {
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 80000).setSunAngles(32, 35);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+ const orb = new Mesh(new SphereGeometry(0.4), new MeshStandardMaterial({ color: 0xffffff, emissive: 0xffc890 }));
+ orb.id = "orb_0"; // what handlers and the frame script find it by
+ orb.position.set(0, 1, 0);
+ scene.add(orb);
+ const camera = new PerspectiveCamera(40, 16 / 9, 0.1, 200);
+ camera.position.set(0, 1.4, 5);
+ scene.add(camera);
+ return { scene, camera };
+ },
+
+ // Handlers change the state, and only the state.
+ handlers: {
+ click(tx, ev) {
+ tx.decide(ev.target.startsWith("orb_"), `nothing happens when you click ${ev.target}`);
+ tx.state.lit[ev.target] = !tx.state.lit[ev.target];
+ },
+ night(tx) {
+ tx.state.night = !tx.state.night;
+ },
+ },
+ keys: { L: "night" },
+
+ // The frame script derives the scene from the state, every frame.
+ frame(f) {
+ const orb = f.object("orb_0") as Mesh;
+ orb.material.emissiveIntensity = f.state.lit.orb_0 ? 2500 : 0;
+ orb.position.y = 1 + 0.08 * Math.sin(f.time * 2);
+ },
+});
+```
+
+- **Handlers are transactions.** A click reaches the game as a `click` event whose `target` is the object under the cursor. `tx.decide` refuses an event, and nothing is half-written.
+- **Deterministic and replayable.** Events are logged with what they read and wrote; `replayLog` and `verifyLog` rebuild a world from its log, and seeded randomness (`seededRandom`) gives the same result on every machine.
+- **World handlers** (`on`) reach the engine's own world: physics, a ray cast into the scene, objects added and removed as an event arrives.
+
+How scene code runs in the engine is in [RUNTIME.md](https://github.com/meshy-dev/ThreeRT/blob/main/docs/RUNTIME.md).
+
+## Running it
+
+The game runs inside a ThreeRT client, which path-traces the scene on the device's GPU: [ThreeRT for macOS and iPhone](https://threert.dev/download/), with `threert dev` for the edit-and-reload loop ([getting started](https://threert.dev/docs/)), or `threert-render play` built from [the engine's source](https://github.com/meshy-dev/ThreeRT). The same game runs as three.js in a browser.
+
+## Links
+
+[threert.dev](https://threert.dev) · [Docs](https://threert.dev/docs/) · [Showcase](https://threert.dev/showcase/) · [GitHub](https://github.com/meshy-dev/ThreeRT)
+
+three.js is an independent open-source project; ThreeRT is not affiliated with it. MIT licence.
diff --git a/packages/gameplay/package.json b/packages/gameplay/package.json
index 2c5979e..739c017 100644
--- a/packages/gameplay/package.json
+++ b/packages/gameplay/package.json
@@ -2,7 +2,9 @@
"name": "@threert/gameplay",
"private": true,
"license": "MIT",
+ "description": "Game logic for ThreeRT: state, transactional handlers, world handlers and per-frame scripts on top of @threert/scene; deterministic and replayable.",
+ "keywords": ["threert", "three.js", "threejs", "game engine", "gameplay", "game state", "transactions", "deterministic", "replay", "ray tracing", "typescript"],
"type": "module",
- "exports": { ".": "./src/index.ts" },
- "dependencies": { "@threert/scene": "*" }
+ "exports": {".": "./src/index.ts"},
+ "dependencies": {"@threert/scene": "*"}
}
diff --git a/packages/scene/README.md b/packages/scene/README.md
new file mode 100644
index 0000000..cb1d0c9
--- /dev/null
+++ b/packages/scene/README.md
@@ -0,0 +1,76 @@
+# @threert/scene
+
+The scene API of [ThreeRT](https://threert.dev): three.js-style code, hardware ray traced.
+
+[![npm](https://img.shields.io/npm/v/@threert/scene?color=f97316)](https://www.npmjs.com/package/@threert/scene)
+[![license](https://img.shields.io/npm/l/@threert/scene)](https://github.com/meshy-dev/ThreeRT/blob/main/LICENSE)
+
+| three.js, as written | ThreeRT, every setting at its default |
+|---|---|
+| ![The scene below in three.js](https://threert.dev/media/hello/material-grid-three.webp) | ![The same scene path-traced by ThreeRT](https://threert.dev/media/hello/material-grid-rt.webp) |
+
+You write a scene the way you would in three.js: meshes, geometries, `MeshStandardMaterial`, lights, glTF models. ThreeRT path-traces it in real time with the GPU's hardware ray tracing, so the sky light, the soft shadows, the bounce light and the reflections come from the scene itself, not from settings. The same file also runs as plain three.js in any browser.
+
+## Install
+
+```bash
+npm install @threert/scene
+```
+
+## A scene
+
+```ts
+import { Scene, PerspectiveCamera, Mesh, SphereGeometry, PlaneGeometry, MeshStandardMaterial, DirectionalLight, SkyAtmosphere, Color } from "@threert/scene";
+
+export default function build() {
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 80000).setSunAngles(32, 35); // lux
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+
+ const ground = new Mesh(new PlaneGeometry(60, 60), new MeshStandardMaterial({ color: 0x7a7a7a, roughness: 0.85 }));
+ ground.rotation.x = -Math.PI / 2;
+ scene.add(ground);
+
+ const rows = [{ color: new Color(0xe8e8e8), metalness: 0 }, { color: new Color(0xc81e1e), metalness: 0 }, { color: new Color().setRGB(1.0, 0.766, 0.336), metalness: 1 }];
+ const sphere = new SphereGeometry(0.42, 96, 64);
+ rows.forEach((row, r) => {
+ [0.05, 0.2, 0.35, 0.5, 0.7, 0.9].forEach((roughness, c) => {
+ const ball = new Mesh(sphere, new MeshStandardMaterial({ color: row.color, metalness: row.metalness, roughness }));
+ ball.position.set((c - 2.5) * 1.05, 0.42, (r - 1) * 1.15);
+ scene.add(ball);
+ });
+ });
+
+ const camera = new PerspectiveCamera(36, 16 / 9, 0.1, 500);
+ camera.position.set(0, 3.4, 7.6);
+ camera.lookAt(0, 0.25, 0.1);
+ scene.add(camera);
+ return { scene, camera };
+}
+```
+
+Light is in physical units: the sun above is 80,000 lux, and an emissive surface is a light source. There are no shadow maps, light probes or lightmaps to set up.
+
+## Seeing it
+
+This package builds the scene. A ThreeRT client draws it:
+
+- **ThreeRT for macOS and iPhone** ([download](https://threert.dev/download/)). The Mac app carries the `threert` command line: `threert create my-game && cd my-game && threert dev` bundles the file on every save and serves it to the clients on your network. [Getting started](https://threert.dev/docs/).
+- **The engine from source**: `threert-render` in [meshy-dev/ThreeRT](https://github.com/meshy-dev/ThreeRT) (Rust and wgpu) renders a bundle to an image or plays it in a window.
+- **three.js**: the dev server and `threert pack` also give the scene as a three.js page, for screens without ray tracing.
+
+## What is in it
+
+- **The three.js names you know**: `Scene`, `Group`, `Mesh`, `InstancedMesh`, `BufferGeometry` and the standard geometries, `MeshStandardMaterial` and `MeshPhysicalMaterial`, the lights, `PerspectiveCamera`, `Raycaster`, `Vector3`, `Quaternion`, `Matrix4`, `Color`.
+- **Models and environments**: `GLTFModel`, `HDRIEnvironment`, `SkyAtmosphere` (a physical sky lit by the sun), height fog.
+- **What a path tracer adds**: emissive surfaces that light the room, `RectAreaLight`, volumes (`FogVolume`, `Fireball`, smoke), water, material functions (a WGSL body run at every hit) and procedural geometry.
+- **Physics**: `mesh.physics = "dynamic"`, joints as objects, `Raycaster.intersectPhysics`, `Shapecaster`.
+
+Games add state and input with [`@threert/gameplay`](https://www.npmjs.com/package/@threert/gameplay); destructible voxel worlds use [`@threert/voxel`](https://www.npmjs.com/package/@threert/voxel).
+
+## Links
+
+[threert.dev](https://threert.dev) · [Docs](https://threert.dev/docs/) · [Showcase](https://threert.dev/showcase/) · [GitHub](https://github.com/meshy-dev/ThreeRT)
+
+three.js is an independent open-source project; ThreeRT is not affiliated with it. MIT licence.
diff --git a/packages/scene/package.json b/packages/scene/package.json
index da711da..c18d36a 100644
--- a/packages/scene/package.json
+++ b/packages/scene/package.json
@@ -2,6 +2,8 @@
"name": "@threert/scene",
"private": true,
"license": "MIT",
+ "description": "The ThreeRT scene API: three.js-style meshes, PBR materials, lights and glTF models, in physical units, for a hardware ray-traced renderer.",
+ "keywords": ["threert", "three.js", "threejs", "ray tracing", "path tracing", "raytracing", "real-time", "renderer", "webgpu", "3d", "scene graph", "game engine", "typescript"],
"type": "module",
- "exports": { ".": "./src/index.ts" }
+ "exports": {".": "./src/index.ts"}
}
diff --git a/packages/voxel/README.md b/packages/voxel/README.md
new file mode 100644
index 0000000..846a952
--- /dev/null
+++ b/packages/voxel/README.md
@@ -0,0 +1,53 @@
+# @threert/voxel
+
+The voxel engine of [ThreeRT](https://threert.dev), the hardware ray-traced engine with a three.js-style API: destructible voxel levels whose pieces break off, fall and collide, traced in real time.
+
+[![npm](https://img.shields.io/npm/v/@threert/voxel?color=f97316)](https://www.npmjs.com/package/@threert/voxel)
+[![license](https://img.shields.io/npm/l/@threert/voxel)](https://github.com/meshy-dev/ThreeRT/blob/main/LICENSE)
+
+## Install
+
+```bash
+npm install @threert/scene @threert/voxel
+```
+
+## What it does
+
+Scene code describes the level and sends the edits. The voxels are loaded, edited, split and meshed in ThreeRT's native renderer (a Rust core that also builds for WebAssembly), never in the scene's JavaScript.
+
+```ts
+import { voxelLevel, voxelExplode, voxelCarve, voxelBodies } from "@threert/voxel";
+
+// In setup: the level, from MagicaVoxel .vox files on one lattice.
+voxelLevel({
+ route: "mesh",
+ palette: [
+ { name: "air", color: [0, 0, 0], roughness: 1, metalness: 0 },
+ { name: "brick", color: [0.55, 0.2, 0.15], roughness: 0.9, metalness: 0, hardness: "medium" },
+ ],
+ objects: [{ name: "wall", uri: "assets/wall.vox", position: [0, 0, 0], anchor: true }],
+});
+
+// In a world handler: a 2 m blast. What it cuts loose becomes rigid bodies.
+voxelExplode(4, 1.5, 0, 2);
+voxelCarve({ box: [0, 0, 0, 1, 3, 0.2] }); // a cut, whatever the hardness
+for (const body of voxelBodies()) console.log(body.position);
+```
+
+- **Edits**: `voxelExplode`, `voxelCarve`, `voxelPaint`, `voxelAdd`, as shapes in world metres. They are applied in fixed point, so the same commands give the same voxels on every machine (`voxelHash`).
+- **Destruction**: after an edit, what no chain of voxels joins to an anchor is cut loose as a rigid body (`VoxelBody`) of the physics world. It tumbles, lands and can be carved again.
+- **Collision**: the level is a collider without being asked, so `Raycaster.intersectPhysics`, shape casts and the game's own bodies meet it.
+- **Fire and smoke**: `Explosions` adds fireballs, their light and smoke to a blast.
+- **In JavaScript too**: `VoxelGrid` (sparse 8³ bricks), `parseVox` / `encodeVox` for MagicaVoxel files, and `greedyMesh` / `voxelMesh` for meshing a grid as ordinary geometry.
+
+The native functions need a ThreeRT client or the engine built from source; they throw elsewhere. The design and its measurements are in [VOXEL.md](https://github.com/meshy-dev/ThreeRT/blob/main/docs/VOXEL.md).
+
+## Running it
+
+A voxel game runs inside a ThreeRT client: [ThreeRT for macOS and iPhone](https://threert.dev/download/), with `threert dev` for the edit-and-reload loop ([getting started](https://threert.dev/docs/)), or `threert-render play` built from [the engine's source](https://github.com/meshy-dev/ThreeRT).
+
+## Links
+
+[threert.dev](https://threert.dev) · [Docs](https://threert.dev/docs/) · [Showcase](https://threert.dev/showcase/) · [GitHub](https://github.com/meshy-dev/ThreeRT)
+
+MIT licence.
diff --git a/packages/voxel/package.json b/packages/voxel/package.json
index 5b37492..d3d503b 100644
--- a/packages/voxel/package.json
+++ b/packages/voxel/package.json
@@ -2,7 +2,9 @@
"name": "@threert/voxel",
"private": true,
"license": "MIT",
+ "description": "The voxel engine for ThreeRT: destructible voxel levels, explosions and rigid bodies cut loose, meshed and ray-traced by the native renderer.",
+ "keywords": ["threert", "voxel", "voxels", "destructible", "magicavoxel", "three.js", "threejs", "game engine", "ray tracing", "physics", "typescript"],
"type": "module",
- "exports": { ".": "./src/index.ts" },
- "dependencies": { "@threert/scene": "*" }
+ "exports": {".": "./src/index.ts"},
+ "dependencies": {"@threert/scene": "*"}
}
diff --git a/tools/npm-pack.ts b/tools/npm-pack.ts
new file mode 100644
index 0000000..3d43632
--- /dev/null
+++ b/tools/npm-pack.ts
@@ -0,0 +1,169 @@
+// The npm packages: @threert/scene, @threert/gameplay and @threert/voxel as they are published, in out/npm/<name>/.
+// node tools/npm-pack.ts build and check all three
+// node tools/npm-pack.ts --publish [--tag t] then publish the ones whose version npm does not have yet
+// node tools/npm-pack.ts --version x.y.z another version than the root package.json's (a trial; not written back)
+//
+// In this repository the packages are their sources: `exports` names src/index.ts, and the tools, the tests and the
+// clients' SDK bundle from there, with no build step. npm gets JavaScript and declarations instead. For each package:
+// out/npm/<name>/dist/ tsc's output of src/ (one .js and one .d.ts a source file; .ts specifiers become .js)
+// out/npm/<name>/package.json the package's own, without `private`, with the version (the root package.json's:
+// the three are released together), `exports` on dist/, and @threert/scene as a peer of
+// the other two: the scene classes are one copy in a program (instanceof, the engine)
+// README.md, LICENSE the package's README and the repository's licence
+// @threert/scene reads the render presets from presets/*.json, outside the package; here they become modules of the
+// package (src/presets/<name>.ts), so the published code and its declarations are whole.
+//
+// The check: the three tarballs installed into an empty project, a scene and a game built from them in Node, and a
+// file that uses them typechecked without skipLibCheck (what a user's tsc reads of the declarations), with a bundler's
+// module resolution and with Node's.
+import { execFileSync } from "node:child_process";
+import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+const root = join(import.meta.dirname, "..");
+const out = join(root, "out/npm");
+const args = process.argv.slice(2);
+const opt = (k: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
+const version: string = opt("--version") ?? JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version;
+if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version ?? "")) throw new Error(`version ${version}: the root package.json's "version" (or --version) is x.y.z`);
+const NAMES = ["scene", "gameplay", "voxel"]; // scene first: the others are built against its declarations
+const REPO = "https://github.com/meshy-dev/ThreeRT";
+const run = (cmd: string, argv: string[], cwd: string, stdio: "inherit" | "pipe" = "inherit") => execFileSync(cmd, argv, { cwd, stdio: stdio === "pipe" ? ["ignore", "pipe", "pipe"] : "inherit", encoding: "utf8" });
+/** A step whose own output says what went wrong: no stack on top of it. */
+const step = (what: string, cmd: string, argv: string[], cwd: string) => {
+ try { run(cmd, argv, cwd); } catch { console.error(`npm-pack: ${what} failed`); process.exit(1); }
+};
+const tsc = join(root, "node_modules/typescript/bin/tsc");
+
+function build(name: string): string {
+ const src = join(root, "packages", name);
+ const dir = join(out, name);
+ rmSync(dir, { recursive: true, force: true });
+ mkdirSync(dir, { recursive: true });
+ const stage = join(dir, "src");
+ cpSync(join(src, "src"), stage, { recursive: true });
+
+ if (name === "scene") {
+ // The presets: JSON outside the package, as modules inside it.
+ const file = join(stage, "presets.ts");
+ let text = readFileSync(file, "utf8");
+ const imports = [...text.matchAll(/from "\.\.\/\.\.\/\.\.\/presets\/([a-z-]+)\.json" with \{ type: "json" \};/g)];
+ const presets = readdirSync(join(root, "presets")).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5));
+ if (imports.length === 0 || imports.length !== presets.length) throw new Error(`packages/scene/src/presets.ts imports ${imports.length} presets, presets/ has ${presets.length}: tools/npm-pack.ts follows the imports' form`);
+ mkdirSync(join(stage, "presets"));
+ for (const m of imports) {
+ writeFileSync(join(stage, "presets", `${m[1]}.ts`), `// presets/${m[1]}.json\nexport default ${readFileSync(join(root, "presets", `${m[1]}.json`), "utf8").trim()};\n`);
+ text = text.replace(m[0], `from "./presets/${m[1]}.ts";`);
+ }
+ writeFileSync(file, text);
+ }
+
+ writeFileSync(join(dir, "tsconfig.json"), JSON.stringify({
+ compilerOptions: {
+ target: "es2023", module: "esnext", moduleResolution: "bundler", lib: ["es2023"], types: ["node"], // console, TextEncoder, structuredClone: every host has them
+ strict: true, skipLibCheck: true, verbatimModuleSyntax: true, erasableSyntaxOnly: true, isolatedModules: true,
+ allowImportingTsExtensions: true, rewriteRelativeImportExtensions: true,
+ declaration: true, rootDir: "src", outDir: "dist",
+ // The other packages: against the scene package as published (built before them).
+ paths: name === "scene" ? undefined : { "@threert/scene": ["../scene/dist/index.d.ts"] },
+ },
+ include: ["src"],
+ }, null, 2));
+ step(`${name}: tsc`, process.execPath, [tsc, "-p", dir], root);
+ // tsc turns the sources' ".ts" specifiers into ".js" in the JavaScript and leaves them in the declarations.
+ for (const f of readdirSync(join(dir, "dist"), { recursive: true }) as string[]) {
+ if (!f.endsWith(".d.ts")) continue;
+ const file = join(dir, "dist", f);
+ writeFileSync(file, readFileSync(file, "utf8").replace(/(\bfrom\s+|\bimport\(\s*|^import\s+)"(\.{1,2}\/[^"]+)\.ts"/gm, '$1"$2.js"'));
+ }
+ rmSync(stage, { recursive: true });
+ rmSync(join(dir, "tsconfig.json"));
+
+ const own = JSON.parse(readFileSync(join(src, "package.json"), "utf8"));
+ const peers = Object.keys(own.dependencies ?? {});
+ for (const p of peers) if (!NAMES.includes(p.replace("@threert/", ""))) throw new Error(`${own.name} depends on ${p}: only the packages released with it are handled here`);
+ const pkg = {
+ name: own.name,
+ version,
+ description: own.description,
+ keywords: own.keywords,
+ license: own.license,
+ homepage: "https://threert.dev",
+ repository: { type: "git", url: `git+${REPO}.git`, directory: `packages/${name}` },
+ bugs: `${REPO}/issues`,
+ type: "module",
+ exports: { ".": { types: "./dist/index.d.ts", default: "./dist/index.js" } },
+ main: "./dist/index.js",
+ types: "./dist/index.d.ts",
+ files: ["dist"],
+ peerDependencies: peers.length ? Object.fromEntries(peers.map((p) => [p, `^${version}`])) : undefined,
+ publishConfig: { access: "public" },
+ };
+ for (const k of ["description", "keywords", "license"] as const) if (!pkg[k]) throw new Error(`packages/${name}/package.json has no ${k}`);
+ writeFileSync(join(dir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
+ for (const [from, to] of [[join(src, "README.md"), "README.md"], [join(root, "LICENSE"), "LICENSE"]]) {
+ if (!existsSync(from)) throw new Error(`${from} is missing`);
+ cpSync(from, join(dir, to));
+ }
+ const files = readdirSync(join(dir, "dist"), { recursive: true }).length;
+ console.log(`${own.name}@${version}: ${files} files in dist/`);
+ return dir;
+}
+
+/** The tarballs in an empty project: imported in Node, and typechecked the way a user's project would. */
+function check(dirs: string[]): void {
+ const project = join(out, "check");
+ rmSync(project, { recursive: true, force: true });
+ mkdirSync(project, { recursive: true });
+ const tarballs = dirs.map((d) => join(project, run("npm", ["pack", d, "--pack-destination", project, "--silent"], project, "pipe").trim().split("\n").pop()!));
+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "check", private: true, type: "module" }));
+ run("npm", ["install", "--silent", "--no-audit", "--no-fund", "--ignore-scripts", ...tarballs], project);
+ writeFileSync(join(project, "use.ts"), `import { Scene, PerspectiveCamera, Mesh, BoxGeometry, MeshStandardMaterial, DirectionalLight, SkyAtmosphere, resolvePreset } from "@threert/scene";
+import { defineGame, describeGame, type GameDefinition } from "@threert/gameplay";
+import { VoxelGrid } from "@threert/voxel";
+
+const game = defineGame({
+ state: { lit: false },
+ setup() {
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 80000).setSunAngles(32, 35);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun });
+ const box = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ color: 0xc81e1e, roughness: 0.4 }));
+ box.id = "box";
+ scene.add(box);
+ const camera = new PerspectiveCamera(36, 16 / 9, 0.1, 500);
+ camera.position.set(0, 2, 6);
+ scene.add(camera);
+ return { scene, camera };
+ },
+ handlers: { click(tx) { tx.state.lit = !tx.state.lit; } },
+});
+const about = describeGame(game as GameDefinition<unknown>);
+const built = game.setup({} as Parameters<typeof game.setup>[0]);
+if (!about.handlers.includes("click") || !(built.scene instanceof Scene) || typeof resolvePreset("preview") !== "object" || new VoxelGrid(0.1).size !== 0.1) throw new Error("the packages did not load as expected");
+`);
+ // What a user's compiler makes of the declarations: strict, nothing skipped, no Node or DOM types given; resolved
+ // as a bundler does, and as Node does.
+ for (const [module, moduleResolution] of [["esnext", "bundler"], ["nodenext", "nodenext"]]) {
+ writeFileSync(join(project, "tsconfig.json"), JSON.stringify({ compilerOptions: { target: "es2023", module, moduleResolution, lib: ["es2023"], types: [], strict: true, noEmit: true, skipLibCheck: false, erasableSyntaxOnly: true }, include: ["use.ts"] }));
+ step(`the check's typecheck (${moduleResolution})`, process.execPath, [tsc, "-p", project], project);
+ }
+ step("the check's run", process.execPath, ["use.ts"], project);
+ console.log("check: the tarballs install, typecheck (strict, no skipLibCheck, no Node or DOM types) and build a scene and a game in Node");
+}
+
+const dirs = NAMES.map(build);
+check(dirs);
+
+if (args.includes("--publish")) {
+ const tag = opt("--tag") ?? "latest";
+ for (const dir of dirs) {
+ const { name } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
+ let published = "";
+ try { published = run("npm", ["view", `${name}@${version}`, "version"], dir, "pipe").trim(); } catch { /* E404: not there yet */ }
+ if (published === version) { console.log(`${name}@${version}: already on npm`); continue; }
+ run("npm", ["publish", "--access", "public", "--tag", tag], dir);
+ console.log(`${name}@${version}: published (${tag})`);
+ }
+} else console.log(`out/npm/{${NAMES.join(",")}}: built and checked; --publish sends them`);