Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

docs(architecture): the document of record catches up to three dimensions

yhhf1408efdac28
diff --git a/CMakeLists.txt b/CMakeLists.txt
index a5801c19c..a2c5b627f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -264,10 +264,11 @@ if(ES_ENABLE_BITMAP_TEXT)
target_compile_definitions(esengine PUBLIC ES_ENABLE_BITMAP_TEXT)
endif()
-# ESEngine is a web-only engine: it targets Emscripten (WebGL2 / GLES3) and ships
-# as wasm for web, WeChat MiniGame, and the Tauri desktop shell. There is no native
-# GPU/runtime build. (The header-only / MockGfxDevice unit tests under tests/ still
-# compile on any C++20 toolchain — they don't link this target.)
+# THIS target is the Emscripten one (WebGL2 / GLES3 or WebGPU), shipped as wasm for
+# web, WeChat MiniGame and playable ads. The same sources also build ahead of time
+# for desktop / Android / iOS against an embedded Dawn — that is native/CMakeLists.txt,
+# a separate tree, and `tools/check-native-build.mjs` compiles this library through it
+# so a header reached only under `__EMSCRIPTEN__` cannot pass for portable.
target_compile_options(esengine PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS})
target_compile_definitions(esengine PUBLIC ES_PLATFORM_WEB)
if(ES_BUILD_WXGAME)
diff --git a/README.md b/README.md
index c0ccb7c55..f151a02aa 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
# Estella
-**A fast 2D game engine powered by WebAssembly and ECS**
+**A fast 2D/3D game engine powered by WebAssembly and ECS**
[![CI](https://github.com/esengine/estella/actions/workflows/build.yml/badge.svg)](https://github.com/esengine/estella/actions/workflows/build.yml)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
@@ -21,7 +21,7 @@
## What is Estella?
-Estella is a **2D game engine** with a TypeScript SDK driven by a high-performance **C++/WebAssembly** backend. It outputs games that run in **web browsers**, on the **desktop**, in **WeChat MiniGames**, as single-file **playable ads**, and as native **Android / iOS** apps. A visual editor is available as a separate, free download.
+Estella is a **2D/3D game engine** with a TypeScript SDK driven by a high-performance **C++** core — as WebAssembly on the web, and compiled ahead of time on native platforms. It outputs games that run in **web browsers**, on the **desktop**, in **WeChat MiniGames**, as single-file **playable ads**, and as native **Android / iOS** apps. A visual editor is available as a separate, free download.
<div align="center">
<img src="docs/assets/editor-hero-c5bfd2f3.png" alt="An action-RPG scene open in the Estella editor" width="900" />
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 98c3fe51d..c25c39a1e 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# Estella Architecture
-This document describes the architecture and design decisions of the Estella 2D
+This document describes the architecture and design decisions of the Estella
game engine. It is **descriptive of the current code**. For the
*target* architecture, the root-cause rationale behind the current design, and
the forward roadmap, see the architecture-of-record companions:
@@ -12,9 +12,20 @@ the forward roadmap, see the architecture-of-record companions:
## Overview
-Estella is a 2D game engine with a **TypeScript SDK** driven by a
-**C++/WebAssembly** backend. It targets web browsers and WeChat MiniGames and
-ships with an Electron-based visual editor.
+Estella is a game engine with a **TypeScript SDK** driven by a **C++** core. Its
+world is three-dimensional — `Transform` is a `vec3` position, a quaternion and a
+`vec3` scale, and a flat game is the corner of that space where z is 0 and the
+camera is orthographic. It ships through **two hosts** built from the same core:
+
+- **wasm** (Emscripten) for the web, WeChat MiniGames and single-file playable
+ ads, rendering through WebGL2 or WebGPU.
+- **native** (`native/`) for desktop, Android and iOS — the same C++ compiled
+ ahead of time against an embedded Dawn (Metal / Vulkan), with the same SDK
+ bundle driving it on QuickJS. Not a WebView.
+
+The visual editor is a separate, private product, mounted at `desktop/` as an
+**optional** submodule. Nothing in this repository requires it to exist: the
+engine builds, tests, gates and verifies its own renderer without a checkout.
The architecture rests on two non-negotiable principles (see `REARCHITECTURE.md`):
@@ -28,19 +39,33 @@ The architecture rests on two non-negotiable principles (see `REARCHITECTURE.md`
compile or fail a CI guard.
```
-┌────────────────────────────────────────────────────────────────────┐
-│ TypeScript SDK (sdk/src) │
-│ App · World · Schedule · Plugins · Query/Commands/Res/Events │
-│ rendering submit · physics · spine · tilemap · ui · audio · scene │
+┌──────────────────────────────────────────────────────────────────────┐
+│ TypeScript SDK (sdk/src) │
+│ App · World · Schedule · Plugins · Query/Commands/Res/Events │
+│ render submit · physics(2D) · physics3d · ai/nav · skeletal · │
+│ tilemap · ui · audio · scene · prefab · net · postprocess · video │
└───────────────┬──────────────────────────────────────────────────────┘
- │ WasmBridge (single boundary; EHT-generated layout/ABI)
+ │ one boundary, one generated layout (EHT: offsets, enums, ABI hash)
+ │ wasm: WasmBridge + embind native: QuickJS `es_*` bindings
┌───────────────▼──────────────────────────────────────────────────────┐
-│ C++ / WebAssembly (src/esengine) │
-│ Registry (SparseSet) · RenderFrame → GfxDevice · ResourceManager │
-│ particle · tilemap · text · animation · platform │
-└────────────────────────────────────────────────────────────────────┘
+│ C++ core (src/esengine) │
+│ Registry (SparseSet) · RenderFrame → GfxDevice · ResourceManager │
+│ particle · tilemap · text · animation · math · platform │
+└───────────────┬──────────────────────────────────────────────────────┘
+ │ GfxDevice — the only GPU door
+ ┌─────────┴──────────┬─────────────────────┐
+ GLDevice WebGPUDevice WebGPUDevice
+ (WebGL2) (browser WebGPU) (embedded Dawn → Metal/Vulkan)
+ └── wasm host: web · WeChat · playable ──┘ └── native host: desktop/iOS/Android
```
+On the wasm host these are side modules — wasm of their own, fetched only by a
+project that uses one: Box2D (2D physics), Jolt (3D physics), Spine, DragonBones,
+Basis/KTX2, video. The native host links them in instead, since there is no
+download to defer. `pipeline/` (`@estella/pipeline`) cooks a project into a shipped
+build with no window and no editor; `editor-api/` is the plugin type surface, so
+a plugin author builds against the contract without private code.
+
## Core Modules (`src/esengine/`)
### Core (`core/`)
@@ -163,11 +188,23 @@ Key facts:
painter's order deliberately beats batching inside a y-sorted layer, every other
layer keeps its key bit-for-bit.
- **`RenderFrame`** owns transient buffers (`TransientBufferPool`), frustum
- culling, render-to-texture (`RenderTarget`), masking (`RenderFrameMask`:
- scissor + stencil), optional post-processing (`PostProcessPipeline`,
- ping-pong FBOs), material UBOs (`MaterialStore`), and 2D lighting
- (`LightStore` / `LightConstants`, up to 16 dynamic lights with a Lit2D shader
- domain). `ImmediateDraw` provides debug/shape primitives on the same buffers.
+ culling, render-to-texture (`RenderTarget`, which a `Camera.renderTarget` now
+ names), masking (`RenderFrameMask`: scissor + stencil), optional
+ post-processing (`PostProcessPipeline`, ping-pong FBOs), material UBOs
+ (`MaterialStore`), skinning palettes (`SkinConstants`) and lighting
+ (`LightStore` / `LightConstants`). `ImmediateDraw` provides debug/shape
+ primitives on the same buffers.
+- **Lighting is one model, not a flat one and a solid one.** Up to
+ `MAX_LIGHTS` = 16 dynamic lights reach the GPU as one `GpuLight` record, read
+ by both the flat model (`applyLighting2D`) and PBR (`applyLightingPBR`) under
+ the single `Lit` shader domain — `Lit2D` / `Unlit2D` are still *read* as `Lit`
+ / `Unlit`, normalized at the parser, because a `.esshader` carries no version
+ to migrate by. Shadows are a tiled atlas (`ShadowAtlas`, `MAX_SHADOW_TILES`):
+ a spot resolves one cone, a point light six faces (`SHADOW_CUBE_FACES`), a sun
+ up to `MAX_SHADOW_CASCADES` = 4 cascades, with a real penumbra from
+ `Light.shadowSoftness` / `sourceAngle`. `MAX_OCCLUDERS_2D` = 8 AABB occluders
+ (`ShadowCaster2D`) shadow content that has no mesh to rasterize — a sprite —
+ which is complementary to the maps, not a second strategy.
### Resource pipeline (`resource/`)
@@ -190,15 +227,17 @@ Key facts:
### Other C++ subsystems
-`particle/` (CPU simulation, GPU-instanced rendering), `tilemap/`, `text/`
-(SDF/glyph), `animation/`, `data/`, `math/` (glm-backed), `platform/`.
+`particle/` (CPU simulation, GPU-instanced rendering, simulated in three axes and
+drawn on a billboard that faces the viewer), `tilemap/`, `text/` (SDF/glyph),
+`animation/`, `data/`, `math/` (glm-backed), `platform/`.
-## SDK / WASM boundary (`sdk/src/`)
+## SDK / engine boundary (`sdk/src/`)
The SDK is the authored surface: `defineComponent`, `defineSystem`, `Query`,
`Commands`, `Res`, events, `Schedule`, and `Plugin`-based composition (`App`).
-Subsystems (asset, physics, spine, tilemap, ui, audio, scene, prefab, camera,
-particle, postprocess, timeline, net) are plugins.
+Subsystems (asset, physics, physics3d, ai — FSM / behaviour tree / perception /
+navigation, skeletal, spine, dragonbones, tilemap, ui, audio, video, scene,
+prefab, camera, particle, trail, postprocess, timeline, net) are plugins.
- **One WASM boundary**: `WasmBridge<M>` (`sdk/src/WasmBridge.ts:57`) is the
single base class — one loader, one ready promise, one missing-binding policy,
@@ -227,10 +266,29 @@ JavaScript (SDK) C++ (WASM)
render() ────────────────────► RenderFrame → GfxDevice
```
-- **Web/Emscripten** — WebGL2 context, HTML5 events, canvas management.
+- **Web/Emscripten** — WebGL2 or WebGPU context, HTML5 events, canvas management.
- **WeChat MiniGame** — a platform adapter (`sdk/src/platform/wechat`) wraps
`wx.*` APIs (`WXWebAssembly`, sync file I/O, storage, a dedicated audio
- backend) behind the same `PlatformAdapter` interface used by web.
+ backend) behind the same `PlatformAdapter` interface used by web. The wechat
+ and playable variants carry the GL backend only, so neither pays for WebGPU
+ glue it cannot use.
+- **Playable ad** — one self-contained HTML file; assets are inlined and reached
+ through the same logical-path resolution every other export uses.
+- **Native (`native/`)** — desktop, Android and iOS. The engine C++ is compiled
+ ahead of time and renders through an embedded Dawn (Metal on iOS, Vulkan on
+ Android); the game runs on QuickJS-ng driving **the real SDK bundle**
+ (`dist/index.native.bundled.js`), so what boots is an editor export, not a
+ parallel content path. One host with a platform seam (`eshost::Platform`),
+ not one host per OS. Dawn and QuickJS are fetched, not vendored, and nothing
+ here is compiled by the web build.
+- **Node** — `esengine/node` runs the same wasm and the same gameplay code with
+ no DOM, for an authoritative headless server (see Networking).
+
+Both hosts reach the C++ through one generated layout. On wasm that is embind
+plus the EHT pointer accessors; natively it is a QuickJS `es_*` surface whose
+per-component half (`es_set_<C>`, `es_<C>_buffer`, `_has`, `_remove`) is
+generated from the same reflection, with only what cannot be generated — the
+registry surface, which the web build reaches as an embind class — hand-written.
## Scene Management (SDK)
@@ -282,9 +340,13 @@ The correctness and foundation campaigns are **complete**. Landed:
- **RC1–RC5** (correctness root causes): generated layout + ABI handshake (RC1),
single storage core (RC2), always-on C++ boundary validation via `boundarySpan`
(RC3), domain TypeIds (RC4), single render path + `GfxDevice` + u32 index (RC5).
-- **F1–F4** (foundation): native seam closed by deletion — the engine is a pure
- Emscripten target (F1); single `WasmBridge` base class (F2); per-App resources
- (F3); this document is the F4 rewrite.
+- **F1–F4** (foundation): the platform seam (F1) was recorded in 2026-07 as
+ "closed by deletion — a pure Emscripten target", and that **is no longer
+ true**: `native/` builds the same core ahead of time against an embedded Dawn
+ for desktop, Android and iOS. The seam is real and load-bearing again, and the
+ gate `check-native-build` compiles the engine off emscripten before a push.
+ Single `WasmBridge` base class (F2); per-App resources (F3); this document is
+ the F4 rewrite, re-baselined here for the 3D / two-host / two-backend reality.
- **RHI modernization + WGSL/WebGPU**: `GfxDevice` is a backend-neutral RHI with
a real `WebGPUDevice` beside `GLDevice`; dual-backend pixel verification runs
in CI on every push.
@@ -293,10 +355,23 @@ The correctness and foundation campaigns are **complete**. Landed:
KTX2 compression, texture + audio residency with SDK-exposed VRAM budget + LRU.
- **RC11** (networking): server-authoritative replication + headless Node server.
- **T2/T3/T4 parity, landed**: animation state machines + 1D blend + Spine driver;
- 2D shadows (hard/soft/directional) + normal maps + extended post-processing
+ shadows (hard/soft/directional) + normal maps + extended post-processing
(color grade, tonemap, FXAA, distortion, pixelate, LUT); pixel-perfect camera +
4-renderable parallax + per-layer y-sort; SDK math library; i18n; save
versioning; hex tilemaps; Tiled object layers; single `.tmj` parser.
+- **The third dimension** (0.52–0.56): `Transform` is `vec3` + quaternion;
+ `MeshRenderer` draws imported glTF with GPU skinning, PBR, an environment
+ probe and a sky; a `Light` casts spot cones, point cubes and sun cascades into
+ one shadow atlas; particles simulate and billboard in three axes; navigation
+ bakes a polygon navmesh (areas, links, doors, agent avoidance) beside the flat
+ grid; 3D physics is a Jolt side module (`RigidBody3D` + box/sphere/capsule/mesh
+ colliders, joints, character controllers). `Light2D` / `Mesh2D` dropped the
+ plane from their names (they are the only light and the only mesh renderer);
+ `ShadowCaster2D` keeps it, because it shadows what has no mesh to rasterize.
+ Physics is the one place where two worlds really do exist, and the unsuffixed
+ names — `RigidBody`, `BoxCollider`, `CircleCollider`, `CapsuleCollider` — are
+ still the **flat** ones. That reads backwards in a 3D-first engine and is
+ slated to be suffixed; see `REARCHITECTURE.md`.
Remaining capability work (see `REARCH_2D_PARITY.md`, gitignored):
- [ ] T2 — editor keyframe/curve editing UI; particle visual editor; native 2D
@@ -304,3 +379,11 @@ Remaining capability work (see `REARCH_2D_PARITY.md`, gitignored):
- [ ] T3 — GPU particles / trails (transform-feedback or compute).
- [ ] T4 — one-way platforms + remaining Box2D joints; editor multi-atlas painting;
tile-gid objects in tilemaps.
+- [ ] Flat-physics naming — the `2D` suffix decided above.
+- [ ] Two pixel gates still run on one backend: `camera-render-target` (a frame
+ holding both an offscreen and a surface pass returns nothing from the
+ WebGPU readback) and `device-loss`. The other 121 assert on both.
+- [ ] A point light runs six cube-face collects and draws whether or not any mesh
+ falls in a face; the frustum is already extracted per tile, so skipping an
+ empty one is cheap — unmeasured, because nothing in the corpus has several
+ point lights.
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index a1dcf61ea..8600049ee 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -214,12 +214,33 @@ TS 驱动的主 pass clear 退出边界,`clear` 家族退出公共 RHI:
- **F2 单一 `WasmBridge` 基类 + abort 守卫下沉(keystone)— ✅ 已落地**(`ac390f7d` + RM 闭环 `41bea17a`,五套桥接全部收敛,abort 守卫全子系统覆盖)。
- **F3 全 per-App 资源 — ✅ 已落地**(分支 `rearch/f3-per-app`):Camera(`CameraView`)、Timeline(`Timeline`)、PostProcess(拆 god-object + 管线注入 + 删 sync.ts)、SpriteAnimator(`SpriteAnimation`)全部 per-App;模块绑定单例在单模块运行时下无需改(B4 关闭)。
- **F4 重写 `ARCHITECTURE.md` — ✅ 已落地**:`docs/ARCHITECTURE.md` 重写为当前现实(`RenderFrame`+`GfxDevice`/`GLDevice` 单一 GPU 边界、单一 `SparseSet`+`version()`、按域 TypeId、per-App 资源 + `WasmBridge` 基类、`ResourcePool` LRU/预算),删除对已删除的 `Renderer`/`BatchRenderer2D` 的描述。
-- F1 平台后端接缝 — ✅ **以删除收口(2026-07-08 记账)**:引擎已是纯 Emscripten 目标(`CMakeLists.txt` 明示 "There is no native GPU/runtime build",全仓已无 glfw/glad/native 窗口路径),native 面只剩可在任意 C++20 工具链编译的 header-only 单元测试——"隔离"由构建结构本身保证,无独立工作项残留。
+- F1 平台后端接缝 — ⚠️ **2026-07-08 那条"以删除收口"的记账已作废(2026-08-23 更正)**:当时写的是"引擎已是纯 Emscripten 目标,全仓已无 native 路径"。现在 `native/` 是一等目标——同一份引擎 C++ 提前编译、链接内嵌 Dawn(iOS Metal / Android Vulkan),游戏脚本跑在 QuickJS-ng 上驱动**真正的 SDK bundle**,desktop/Android/iOS 三分支各有平台实现(`native/host/platform/`)。接缝重新成立且承重:`GfxDevice` 是两个后端三种宿主的唯一 GPU 门,per-component 的 `es_*` 绑定与 web 的 embind 出自同一份反射,门禁 `check-native-build` 在 push 前把引擎编译一遍 off-emscripten。`CMakeLists.txt` 里那句 "There is no native GPU/runtime build" 已随本次更正改写。
执行先于 RC6。
> **能力对标路线**:RC1–RC5 修正确性、F/RC6 修地基与平台错配之外,"能力缺口对标"(交付管线 / 内容创作闭环 / 渲染深度 / 完整度)的优先级与执行顺序见 [`REARCH_2D_PARITY.md`](./REARCH_2D_PARITY.md)(本地 gitignore)。
+### RC12 三维化 — 🟡 已落地并出货(0.52–0.56),余一处命名割裂(2026-08-23 补记)
+这条主线在 2026-07-08 之后走完,而本文的 living status 停在那一天,所以补记于此。逐条改了什么在
+CHANGELOG 和提交信息里,这里只写**从那里读不出来的结构性结论**。
+
+- **世界本来就是三维的,不是加了一层 3D。** `Transform` 是 `vec3` + 四元数 + `vec3` 缩放,平面游戏
+ 是这个空间里 z=0、相机正交的那个角。同一条推论反复用在每个子系统上:粒子的 billboard 正视时
+ 两轴退化成 (1,0,0)/(0,1,0),就是平面场景一直在画的那个 quad——billboard 不是第二条路径,平面
+ quad 是它的一个角。
+- **"唯一的那个"就不带平面名。** `Light2D`→`Light`、`Mesh2D`→`MeshRenderer`、`Lit2D`/`Unlit2D`
+ 域→`Lit`/`Unlit`(`.esshader` 无版本可迁,故老拼写在 parser 归一化后仍可读)。场景/预制体靠
+ loader 自升级,格式 v2;旧引擎**拒绝** v2 而不是把 `Light` 当没听说过的组件读成一关没有灯。
+- **验证面**:123 个像素门禁中 121 个双后端断言;`tools/render-host/` 让 100 个门禁在**引擎自己的**
+ 无头宿主上跑,而不是经编辑器——门禁断言的是出货游戏看到的渲染器。
+- **仍开着的一处**:物理是唯一真有两个世界的地方,而无后缀的名字(`RigidBody` / `BoxCollider` /
+ `CircleCollider` / `CapsuleCollider`)现在归了**平面**那套,3D 那套反而带 `3D` 后缀。在一个默认
+ 世界是三维的引擎里这是反的:用户给 mesh 挂 `BoxCollider` 拿到的是平面盒子,`CapsuleCollider`
+ 与 `CapsuleCollider3D` 并排尤其危险。**已拍板:给平面那套加 `2D` 后缀**(`RigidBody2D` /
+ `BoxCollider2D` / `CircleCollider2D` / `CapsuleCollider2D`),走 `Light`/`MeshRenderer` 同款做法——
+ loader 升级旧名、场景格式版本再进一格、SDK 破坏性改名进 CHANGELOG。SDK 面同时收口:2D 有
+ `Physics` facade 而 3D 是 `Physics3DQueries`,两者从同一个 `esengine` 面导出却不同形。
+
### RC6 资产管线 — 📋 已立项(设计文档)
见 [`REARCH_RC6_ASSETS.md`](./REARCH_RC6_ASSETS.md):面向微信/移动端的资产管线根治——GPU 压缩纹理(keystone)、内容寻址身份、显存预算 + LRU 驱逐、运行时分包/流式 + 微信分包映射。属"能力/平台错配"根治,区别于 RC1–RC5 的"正确性根因"。
diff --git a/package.json b/package.json
index aefbf8376..42a0eb28f 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"version": "0.56.0",
"private": true,
"type": "module",
- "description": "Estella - A fast 2D game engine powered by WebAssembly and ECS",
+ "description": "Estella - A fast 2D/3D game engine powered by WebAssembly and ECS",
"license": "Apache-2.0",
"scripts": {
"build": "node build-tools/cli.js build",
diff --git a/sdk/package.json b/sdk/package.json
index d596a0bf8..bc73394dc 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -3,7 +3,7 @@
"version": "0.12.0",
"private": true,
"type": "module",
- "description": "Estella SDK - A fast 2D game engine for Web and WeChat MiniGames",
+ "description": "Estella SDK - A fast 2D/3D game engine for Web, WeChat MiniGames and native platforms",
"sideEffects": [
"./dist/index.js",
"./dist/index.wechat.js",
diff --git a/tools/check-architecture-doc.mjs b/tools/check-architecture-doc.mjs
new file mode 100644
index 000000000..b048679f9
--- /dev/null
+++ b/tools/check-architecture-doc.mjs
@@ -0,0 +1,121 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-architecture-doc.mjs
+ * @brief The document that says what the engine IS names things that exist.
+ * @details `docs/ARCHITECTURE.md` calls itself descriptive of the current code,
+ * and nothing checked that. It drifted for six weeks: it described a 2D
+ * engine shipping only to browsers and WeChat, said the native seam had
+ * been closed by deletion while `native/` was building for three
+ * platforms, and named `Lit2D` and `Light2D` after both were renamed.
+ *
+ * Every convention in this repo that survives has a gate. This one takes
+ * the checkable half: every path in a backtick exists, and every code
+ * identifier in a backtick is somewhere in the sources. Prose it cannot
+ * judge, but a doc naming only live symbols is a doc someone maintained.
+ *
+ * REARCHITECTURE.md is deliberately NOT a subject: a plan names what does
+ * not exist yet, which is the whole point of it.
+ *
+ * Run: node tools/check-architecture-doc.mjs (exit 1 on a dead name)
+ */
+import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const DOC = path.join(ROOT, 'docs', 'ARCHITECTURE.md');
+
+/** Where a name is allowed to live. A symbol anywhere in these is alive. */
+const SOURCES = ['src', 'sdk/src', 'native', 'pipeline/src', 'editor-api', 'tools', 'build-tools', 'tests'];
+const SOURCE_EXT = /\.(cpp|hpp|h|ts|tsx|mjs|js|json|cmake|txt|py)$/;
+
+/** A bare `foo/` in this doc is a subdirectory of one of these. */
+const DIR_ROOTS = ['src/esengine', 'sdk/src', 'docs', '.'];
+
+/**
+ * Paths the doc may name that are not in this checkout: the companion plans that
+ * are gitignored on purpose, the optional editor, a build output, and a package
+ * entry specifier that is not a path at all.
+ */
+const ABSENT_BY_DESIGN = new Set([
+ 'REARCH_2D_PARITY.md', 'REARCH_WGSL.md', 'desktop/',
+ 'dist/index.native.bundled.js', 'esengine/node',
+]);
+
+/**
+ * Names the doc mentions BECAUSE they are gone. Asserted in the other direction:
+ * if one comes back, the sentence saying it was deleted has quietly become false.
+ */
+const GONE = new Set(['getTypeId', 'DynamicComponentPool', 'SchemaComponentPool', 'BatchRenderer2D']);
+
+const SELF = path.join(ROOT, 'tools', 'check-architecture-doc.mjs');
+
+function walk(dir, out = []) {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ if (e.name === 'node_modules' || e.name === 'dist' || e.name === 'build') continue;
+ // This file names every dead symbol on purpose; reading it would revive them all.
+ if (path.join(dir, e.name) === SELF) continue;
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) walk(p, out);
+ else if (SOURCE_EXT.test(e.name)) out.push(p);
+ }
+ return out;
+}
+
+const haystack = SOURCES
+ .filter((d) => existsSync(path.join(ROOT, d)))
+ .flatMap((d) => walk(path.join(ROOT, d)))
+ .map((f) => readFileSync(f, 'utf8'))
+ .join('\n');
+
+const doc = readFileSync(DOC, 'utf8');
+const problems = [];
+const lineOf = (index) => doc.slice(0, index).split('\n').length;
+
+for (const m of doc.matchAll(/`([^`\n]+)`/g)) {
+ const raw = m[1].trim();
+ // A path: what it points at has to be there. Line suffixes are how this repo
+ // cites code, and a range of them is still one file.
+ if (/^[\w./-]+\/[\w./-]*$/.test(raw) || /^[\w-]+\.(md|ts|mjs|cpp|hpp|json|esshader)$/.test(raw)) {
+ const bare = raw.replace(/:[\d,\-\s]+$/, '');
+ if (ABSENT_BY_DESIGN.has(bare) || ABSENT_BY_DESIGN.has(`${bare}/`)) continue;
+ if (existsSync(path.join(ROOT, bare))) continue;
+ if (DIR_ROOTS.some((r) => existsSync(path.join(ROOT, r, bare)))) continue;
+ // A bare filename is cited without its directory all over the doc.
+ if (!bare.includes('/') && haystack.includes(bare)) continue;
+ problems.push(`${lineOf(m.index)}: \`${raw}\` — no such path`);
+ continue;
+ }
+ // An identifier: CamelCase or snake_case, nothing a sentence would contain.
+ const bare = raw.replace(/^[&*]+/, '').replace(/[(<].*$/, '').replace(/^.*::/, '');
+ if (!/^[A-Za-z_][A-Za-z0-9_]{2,}$/.test(bare)) continue;
+ if (!/[a-z][A-Z]|_/.test(bare)) continue;
+ if (GONE.has(bare)) continue;
+ if (haystack.includes(bare)) continue;
+ problems.push(`${lineOf(m.index)}: \`${raw}\` — names nothing in the sources`);
+}
+
+// The other direction: a name the doc says is gone, that is back.
+for (const name of GONE) {
+ if (!doc.includes(name)) {
+ problems.push(`GONE lists \`${name}\`, which the doc no longer mentions — drop it from the list`);
+ // Declared or called, not merely named: a comment recalling why something went
+ // is exactly the trace a deletion leaves behind.
+ } else if (new RegExp(`\\b(class|struct|interface|enum|type)\\s+${name}\\b|\\b${name}\\s*[(<]`).test(haystack)) {
+ problems.push(`\`${name}\` is in the sources again; the doc says it was removed`);
+ }
+}
+
+if (problems.length > 0) {
+ console.error('docs/ARCHITECTURE.md describes code that is not there:\n');
+ for (const p of problems) console.error(` ${p}`);
+ console.error('\nThe file says it is descriptive of the current code. Update it, or'
+ + ' move the claim to REARCHITECTURE.md, where a plan belongs.');
+ process.exit(1);
+}
+
+const names = (doc.match(/`[^`\n]+`/g) ?? []).length;
+console.log(`check-architecture-doc: ${names} name(s) in docs/ARCHITECTURE.md — every path exists`
+ + ' and every identifier is in the sources.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index fc47ca5a3..6c95ea2ba 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -35,6 +35,7 @@ export const GATES = [
{ id: 'engine-exports', run: 'node tools/check-engine-exports.mjs' },
{ id: 'fixture-scenes', run: 'node tools/check-fixture-scenes.mjs' },
{ id: 'doc-imports', run: 'node tools/check-doc-imports.mjs' },
+ { id: 'architecture-doc', run: 'node tools/check-architecture-doc.mjs' },
{
id: 'native-bindings',
run: 'node tools/check-native-bindings.mjs',