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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(sdk): 2D physics declares where its declarations end
esengine08521e176cdb
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex 7e0589ed8..fe8d0170c 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -55,6 +55,7 @@ export default defineConfig(['index.wechat.lean': 'src/index.wechat.lean.ts','index.minigame': 'src/index.minigame.ts','index.native': 'src/index.native.ts',+ 'physics/components': 'src/physics/components.ts','physics/index': 'src/physics/index.ts','physics3d/index': 'src/physics3d/index.ts','spine/index': 'src/spine/index.ts',diff --git a/sdk/src/physics/CharacterController2D.ts b/sdk/src/physics/CharacterController2D.tsindex f858e6198..c6bda91cf 100644--- a/sdk/src/physics/CharacterController2D.ts+++ b/sdk/src/physics/CharacterController2D.ts@@ -20,22 +20,8 @@* Units: `velocity`/positions are world pixels (matching `Transform`); collider* dimensions are meters and are scaled to pixels via `Physics2DAPI.getPixelsPerUnit()`.*/-import type { App } from '../app/app';-import type { Entity, Vec2 } from '../types';-import { defineComponent, Transform, type TransformData } from '../ecs/component';-import { Schedule, defineSystem, GetWorld } from '../ecs/system';-import { Query, Mut } from '../ecs/query';-import { Res, Time, type TimeData } from '../ecs/resource';-import { playModeOnly } from '../ecs/env';-import { Physics2D, type Physics2DAPI } from './Physics2D';-import { readPixelsPerUnit } from './PhysicsSystem';-import { BoxCollider2D, CircleCollider2D, CapsuleCollider2D, activeCollider } from './PhysicsComponents';-import { log } from '../util/logger';-import type {- BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,-} from './PhysicsComponents';-import type { MoverResult } from './PhysicsTypes';-import type { World } from '../ecs/world';+import type { Vec2 } from '../types';+import { defineComponent } from '../ecs/component';// =============================================================================// Component@@ -236,154 +222,3 @@ export function moveAndSlide(p: MoveAndSlideParams, cast: SlideCast): MoveAndSlifloorNormalX: fnX, floorNormalY: fnY,};}--// =============================================================================-// System-// =============================================================================--/** The character's cast shape, in pixels, resolved from its collider. */-type CastShape =- | { kind: 'box'; hx: number; hy: number; ox: number; oy: number }- | { kind: 'circle'; r: number; ox: number; oy: number }- | { kind: 'capsule'; r: number; halfH: number; ox: number; oy: number };--/** Read the entity's collider into a pixel-space cast shape, or null if it has no- * enabled one — a disabled collider is no collider, here as everywhere. */-function resolveCastShape(world: World, entity: Entity, ppu: number): CastShape | null {- const box = activeCollider(world, entity, BoxCollider2D) as BoxCollider2DData | null;- if (box) {- return { kind: 'box', hx: box.halfExtents.x * ppu, hy: box.halfExtents.y * ppu, ox: box.offset.x * ppu, oy: box.offset.y * ppu };- }- const circle = activeCollider(world, entity, CircleCollider2D) as CircleCollider2DData | null;- if (circle) {- return { kind: 'circle', r: circle.radius * ppu, ox: circle.offset.x * ppu, oy: circle.offset.y * ppu };- }- const capsule = activeCollider(world, entity, CapsuleCollider2D) as CapsuleCollider2DData | null;- if (capsule) {- return { kind: 'capsule', r: capsule.radius * ppu, halfH: capsule.halfHeight * ppu, ox: capsule.offset.x * ppu, oy: capsule.offset.y * ppu };- }- return null;-}--/** The capsule the native mover sweeps, derived from the collider (pixels). A box- * becomes a capsule inscribed along its longer axis; a circle a zero-length capsule. */-interface MoverCapsule { c1: Vec2; c2: Vec2; radius: number }--function moverCapsuleFromShape(s: CastShape): MoverCapsule {- if (s.kind === 'circle') {- return { c1: { x: s.ox, y: s.oy }, c2: { x: s.ox, y: s.oy }, radius: s.r };- }- if (s.kind === 'capsule') {- return { c1: { x: s.ox, y: s.oy + s.halfH }, c2: { x: s.ox, y: s.oy - s.halfH }, radius: s.r };- }- // Box: place the capsule spine along the longer axis, radius = shorter half-extent.- if (s.hy >= s.hx) {- const half = s.hy - s.hx;- return { c1: { x: s.ox, y: s.oy + half }, c2: { x: s.ox, y: s.oy - half }, radius: s.hx };- }- const half = s.hx - s.hy;- return { c1: { x: s.ox + half, y: s.oy }, c2: { x: s.ox - half, y: s.oy }, radius: s.hy };-}--function isFiniteMove(r: MoverResult): boolean {- return Number.isFinite(r.dx) && Number.isFinite(r.dy)- && Number.isFinite(r.velX) && Number.isFinite(r.velY);-}--let warnedNonFiniteMove = false;--function warnNonFiniteMove(entity: Entity, ppu: number, dt: number): void {- if (warnedNonFiniteMove) return;- warnedNonFiniteMove = true;- log.error('physics', `CharacterController2D move on entity ${entity} resolved to a non-finite pose `- + `(ppu=${ppu}, dt=${dt}); the Transform was left where it was. Check the entity's collider, `- + 'velocity and the Canvas pixelsPerUnit.');-}--/**- * Register the character-controller system. Runs in FixedUpdate ahead of the- * physics step so the resolved Transform is what gets pushed into a kinematic body.- * Movement is delegated to Box2D's native kinematic mover (collide-into-planes +- * depenetrating slide), which — unlike a generic shape cast — resolves a character- * resting on the ground with valid contact normals instead of wedging on it.- */-export function registerCharacterController2DSystem(app: App): void {- warnedNonFiniteMove = false;- app.addSystemToSchedule(- Schedule.FixedUpdate,- defineSystem(- [Query(Mut(CharacterController2D)), Res(Time), Res(Physics2D), GetWorld()],- (- query: Iterable<[Entity, CharacterController2DData]>,- time: TimeData,- physics: Physics2DAPI,- world: World,- ) => {- const dt = time.fixedDelta;- if (dt <= 0) return;- // Push before reading: this runs ahead of PhysicsStepSystem, the other- // caller, so on the first fixed step nobody has pushed one yet.- physics.setPixelsPerUnit(readPixelsPerUnit(app));- const ppu = physics.getPixelsPerUnit();- const invDt = 1 / dt;-- for (const [entity, cc] of query) {- const shape = resolveCastShape(world, entity, ppu);- if (!shape) continue;- const mover = moverCapsuleFromShape(shape);-- // Transform is C++-backed: get() yields a converted copy, so the- // resolved pose must be written back with set() (mutating the copy- // alone would not persist).- const transform = world.get(entity, Transform) as TransformData;- const startX = transform.position.x;- const startY = transform.position.y;-- const r = physics.moveCharacter(- transform.position, mover.c1, mover.c2, mover.radius,- cc.velocity, dt, cc.up, Math.cos(cc.floorMaxAngle),- cc.maskBits, entity,- cc.skinWidth, cc.maxSlides, cc.snapLength, cc.slideOnCeiling,- ppu,- );- if (!r) continue;- // A non-finite move is not survivable: the next move starts from the- // position this writes, so one NaN frame kills the character for the- // session. Keep the last good pose and say so once.- if (!isFiniteMove(r)) { warnNonFiniteMove(entity, ppu, dt); continue; }-- // Write both local and world position: PhysicsStepSystem runs next- // in this same FixedUpdate and pushes worldPosition into a kinematic- // body, before TransformSystem re-derives world from local.- transform.position.x = startX + r.dx;- transform.position.y = startY + r.dy;- transform.worldPosition.x = transform.position.x;- transform.worldPosition.y = transform.position.y;- world.set(entity, Transform, transform);-- cc.velocity.x = r.velX;- cc.velocity.y = r.velY;- cc.isOnFloor = r.isOnFloor;- cc.isOnWall = r.isOnWall;- cc.isOnCeiling = r.isOnCeiling;- cc.floorNormal.x = r.floorNormalX;- cc.floorNormal.y = r.floorNormalY;- cc.realVelocity.x = r.dx * invDt;- cc.realVelocity.y = r.dy * invDt;- }- },- {- name: 'CharacterController2DSystem',- runBefore: ['PhysicsStepSystem'],- // The World is how it reaches the collider (whichever of the three- // a character has) and the pose it resolves; the solver's contacts- // are physics-side state, not components.- touches: {- reads: [BoxCollider2D._name, CircleCollider2D._name, CapsuleCollider2D._name],- writes: [Transform._name],- },- },- ),- { runIf: playModeOnly },- );-}diff --git a/sdk/src/physics/CharacterController2DSystem.ts b/sdk/src/physics/CharacterController2DSystem.tsnew file mode 100644index 000000000..d29e8cf4c--- /dev/null+++ b/sdk/src/physics/CharacterController2DSystem.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file CharacterController2DSystem.ts — the controller's wiring into a running+ * 2D world, split off at the line the file already drew.+ *+ * The component and `moveAndSlide` are data and arithmetic that any reader of a+ * scene needs; this reaches the solver. Together they put `Physics2D`,+ * `PhysicsSystem` and `Physics2DDebugDraw` in the declaration closure, and from+ * there into every package — see tools/check-core-carries-options.mjs.+ */+import type { App } from '../app/app';+import type { Entity, Vec2 } from '../types';+import { Transform, type TransformData } from '../ecs/component';+import { Schedule, defineSystem, GetWorld } from '../ecs/system';+import { Query, Mut } from '../ecs/query';+import { Res, Time, type TimeData } from '../ecs/resource';+import { playModeOnly } from '../ecs/env';+import { Physics2D, type Physics2DAPI } from './Physics2D';+import { readPixelsPerUnit } from './PhysicsSystem';+import {+ BoxCollider2D, CircleCollider2D, CapsuleCollider2D, activeCollider,+ type BoxCollider2DData, type CircleCollider2DData, type CapsuleCollider2DData,+} from './PhysicsComponents';+import { log } from '../util/logger';+import type { MoverResult } from './PhysicsTypes';+import type { World } from '../ecs/world';+import {+ CharacterController2D, moveAndSlide,+ type CharacterController2DData, type SlideHit,+} from './CharacterController2D';++// =============================================================================+// System+// =============================================================================++/** The character's cast shape, in pixels, resolved from its collider. */+type CastShape =+ | { kind: 'box'; hx: number; hy: number; ox: number; oy: number }+ | { kind: 'circle'; r: number; ox: number; oy: number }+ | { kind: 'capsule'; r: number; halfH: number; ox: number; oy: number };++/** Read the entity's collider into a pixel-space cast shape, or null if it has no+ * enabled one — a disabled collider is no collider, here as everywhere. */+function resolveCastShape(world: World, entity: Entity, ppu: number): CastShape | null {+ const box = activeCollider(world, entity, BoxCollider2D) as BoxCollider2DData | null;+ if (box) {+ return { kind: 'box', hx: box.halfExtents.x * ppu, hy: box.halfExtents.y * ppu, ox: box.offset.x * ppu, oy: box.offset.y * ppu };+ }+ const circle = activeCollider(world, entity, CircleCollider2D) as CircleCollider2DData | null;+ if (circle) {+ return { kind: 'circle', r: circle.radius * ppu, ox: circle.offset.x * ppu, oy: circle.offset.y * ppu };+ }+ const capsule = activeCollider(world, entity, CapsuleCollider2D) as CapsuleCollider2DData | null;+ if (capsule) {+ return { kind: 'capsule', r: capsule.radius * ppu, halfH: capsule.halfHeight * ppu, ox: capsule.offset.x * ppu, oy: capsule.offset.y * ppu };+ }+ return null;+}++/** The capsule the native mover sweeps, derived from the collider (pixels). A box+ * becomes a capsule inscribed along its longer axis; a circle a zero-length capsule. */+interface MoverCapsule { c1: Vec2; c2: Vec2; radius: number }++function moverCapsuleFromShape(s: CastShape): MoverCapsule {+ if (s.kind === 'circle') {+ return { c1: { x: s.ox, y: s.oy }, c2: { x: s.ox, y: s.oy }, radius: s.r };+ }+ if (s.kind === 'capsule') {+ return { c1: { x: s.ox, y: s.oy + s.halfH }, c2: { x: s.ox, y: s.oy - s.halfH }, radius: s.r };+ }+ // Box: place the capsule spine along the longer axis, radius = shorter half-extent.+ if (s.hy >= s.hx) {+ const half = s.hy - s.hx;+ return { c1: { x: s.ox, y: s.oy + half }, c2: { x: s.ox, y: s.oy - half }, radius: s.hx };+ }+ const half = s.hx - s.hy;+ return { c1: { x: s.ox + half, y: s.oy }, c2: { x: s.ox - half, y: s.oy }, radius: s.hy };+}++function isFiniteMove(r: MoverResult): boolean {+ return Number.isFinite(r.dx) && Number.isFinite(r.dy)+ && Number.isFinite(r.velX) && Number.isFinite(r.velY);+}++let warnedNonFiniteMove = false;++function warnNonFiniteMove(entity: Entity, ppu: number, dt: number): void {+ if (warnedNonFiniteMove) return;+ warnedNonFiniteMove = true;+ log.error('physics', `CharacterController2D move on entity ${entity} resolved to a non-finite pose `+ + `(ppu=${ppu}, dt=${dt}); the Transform was left where it was. Check the entity's collider, `+ + 'velocity and the Canvas pixelsPerUnit.');+}++/**+ * Register the character-controller system. Runs in FixedUpdate ahead of the+ * physics step, so the resolved Transform is what reaches a kinematic body.+ * Movement goes through Box2D's kinematic mover, which — unlike a generic shape+ * cast — rests a character on the ground instead of wedging it there.+ */+export function registerCharacterController2DSystem(app: App): void {+ warnedNonFiniteMove = false;+ app.addSystemToSchedule(+ Schedule.FixedUpdate,+ defineSystem(+ [Query(Mut(CharacterController2D)), Res(Time), Res(Physics2D), GetWorld()],+ (+ query: Iterable<[Entity, CharacterController2DData]>,+ time: TimeData,+ physics: Physics2DAPI,+ world: World,+ ) => {+ const dt = time.fixedDelta;+ if (dt <= 0) return;+ // Push before reading: this runs ahead of PhysicsStepSystem, the other+ // caller, so on the first fixed step nobody has pushed one yet.+ physics.setPixelsPerUnit(readPixelsPerUnit(app));+ const ppu = physics.getPixelsPerUnit();+ const invDt = 1 / dt;++ for (const [entity, cc] of query) {+ const shape = resolveCastShape(world, entity, ppu);+ if (!shape) continue;+ const mover = moverCapsuleFromShape(shape);++ // Transform is C++-backed: get() yields a converted copy, so the+ // resolved pose must be written back with set() (mutating the copy+ // alone would not persist).+ const transform = world.get(entity, Transform) as TransformData;+ const startX = transform.position.x;+ const startY = transform.position.y;++ const r = physics.moveCharacter(+ transform.position, mover.c1, mover.c2, mover.radius,+ cc.velocity, dt, cc.up, Math.cos(cc.floorMaxAngle),+ cc.maskBits, entity,+ cc.skinWidth, cc.maxSlides, cc.snapLength, cc.slideOnCeiling,+ ppu,+ );+ if (!r) continue;+ // A non-finite move is not survivable: the next move starts from the+ // position this writes, so one NaN frame kills the character for the+ // session. Keep the last good pose and say so once.+ if (!isFiniteMove(r)) { warnNonFiniteMove(entity, ppu, dt); continue; }++ // Write both local and world position: PhysicsStepSystem runs next+ // in this same FixedUpdate and pushes worldPosition into a kinematic+ // body, before TransformSystem re-derives world from local.+ transform.position.x = startX + r.dx;+ transform.position.y = startY + r.dy;+ transform.worldPosition.x = transform.position.x;+ transform.worldPosition.y = transform.position.y;+ world.set(entity, Transform, transform);++ cc.velocity.x = r.velX;+ cc.velocity.y = r.velY;+ cc.isOnFloor = r.isOnFloor;+ cc.isOnWall = r.isOnWall;+ cc.isOnCeiling = r.isOnCeiling;+ cc.floorNormal.x = r.floorNormalX;+ cc.floorNormal.y = r.floorNormalY;+ cc.realVelocity.x = r.dx * invDt;+ cc.realVelocity.y = r.dy * invDt;+ }+ },+ {+ name: 'CharacterController2DSystem',+ runBefore: ['PhysicsStepSystem'],+ // The World is how it reaches the collider (whichever of the three+ // a character has) and the pose it resolves; the solver's contacts+ // are physics-side state, not components.+ touches: {+ reads: [BoxCollider2D._name, CircleCollider2D._name, CapsuleCollider2D._name],+ writes: [Transform._name],+ },+ },+ ),+ { runIf: playModeOnly },+ );+}diff --git a/sdk/src/physics/Physics2DPlugin.ts b/sdk/src/physics/Physics2DPlugin.tsindex 83236d683..bb47373c4 100644--- a/sdk/src/physics/Physics2DPlugin.ts+++ b/sdk/src/physics/Physics2DPlugin.ts@@ -22,7 +22,7 @@ import { PhysicsBridge } from './PhysicsBridge';import { Physics2DRuntime } from './Physics2DRuntime';import { Physics2DAPI, Physics2D } from './Physics2D';import { registerPhysics2DSystem } from './PhysicsSystem';-import { registerCharacterController2DSystem } from './CharacterController2D';+import { registerCharacterController2DSystem } from './CharacterController2DSystem';import { registerPhysics2DEventBridge } from './PhysicsEventBridge';import {Physics2DEvents,diff --git a/sdk/src/physics/components.ts b/sdk/src/physics/components.tsnew file mode 100644index 000000000..a301704e2--- /dev/null+++ b/sdk/src/physics/components.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file components.ts — 2D physics as a scene DECLARES it: components, shapes+ * and the arithmetic over them. No solver.+ *+ * Its own entry point because a chunk is what a bundler can act on: with the+ * declarations and the solver in one chunk, a core that needs `RigidBody2D`+ * takes Box2D with it into every package. Reading a scene needs this half;+ * simulating it needs `esengine/physics`.+ */+export * from './PhysicsComponents';+export * from './ColliderShape2D';+export * from './polygonHull2D';+export * from './polygonDecompose2D';+export {+ CharacterController2D, moveAndSlide,+ type CharacterController2DData, type SlideHit, type SlideCast,+ type MoveAndSlideParams, type MoveAndSlideResult,+} from './CharacterController2D';diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.tsindex e5858a058..8bbd9df97 100644--- a/sdk/src/physics/index.ts+++ b/sdk/src/physics/index.ts@@ -106,13 +106,13 @@ export {export {CharacterController2D,moveAndSlide,- registerCharacterController2DSystem,type CharacterController2DData,type MoveAndSlideParams,type MoveAndSlideResult,type SlideCast,type SlideHit,} from './CharacterController2D';+export { registerCharacterController2DSystem } from './CharacterController2DSystem';// Importing this subpath INSTALLS 2D physics — see spine/index.ts. No entry// plugin: the scene load builds it with the world config the project declared.diff --git a/sdk/tests/schedule-declared.test.ts b/sdk/tests/schedule-declared.test.tsindex c457edc69..dc91dc1fd 100644--- a/sdk/tests/schedule-declared.test.ts+++ b/sdk/tests/schedule-declared.test.ts@@ -18,7 +18,7 @@ import { App } from '../src/app/app';import { Schedule, defineSystem, GetWorld } from '../src/ecs/system';import { simulationBasePlugins } from '../src/app/pluginSets';import { StatsPlugin } from '../src/stats';-import { registerCharacterController2DSystem } from '../src/physics/CharacterController2D';+import { registerCharacterController2DSystem } from '../src/physics/CharacterController2DSystem';import { setPlatform } from '../src/platform/base';import { webAdapter } from '../src/platform/web';diff --git a/tools/baselines/core-carries-options.json b/tools/baselines/core-carries-options.jsonindex cab998b82..705d22ef3 100644--- a/tools/baselines/core-carries-options.json+++ b/tools/baselines/core-carries-options.json@@ -1,3 +1,28 @@{- "edges": []+ "edges": [+ "ai/nav/NavPlugin.ts -> ../../physics3d/Physics3DComponents",+ "ai/nav/navGeometry.ts -> ../../physics3d/ColliderShape3D",+ "ai/nav/navGeometry.ts -> ../../physics3d/Physics3DComponents",+ "ai/perception/PerceptionPlugin.ts -> ../../physics",+ "ai/perception/PerceptionPlugin.ts -> ../../physics3d/Physics3DPlugin",+ "app/app.ts -> ../physics/Physics2DRuntime",+ "app/pluginSets.ts -> ../video",+ "asset/Assets.ts -> ../spine/prepareSpine",+ "asset/loaders/SpineAssetLoader.ts -> ../../spine/prepareSpine",+ "ecs/bridge/nativeRuntime.ts -> ../../dragonbones",+ "ecs/bridge/nativeRuntime.ts -> ../../spine",+ "gameplay/GameplayPlugin.ts -> ../physics3d/Physics3DComponents",+ "gameplay/GameplayPlugin.ts -> ../physics3d/Physics3DPlugin",+ "gameplay/Hunter.ts -> ../physics3d/Physics3DComponents",+ "platform/minigame/adapter.ts -> ../../video/WasmVideoBackend",+ "platform/native/adapter.ts -> ../../video/WasmVideoBackend",+ "platform/nativeModuleRegistry.ts -> ../dragonbones",+ "platform/nativeModuleRegistry.ts -> ../physics",+ "platform/nativeModuleRegistry.ts -> ../physics3d",+ "platform/nativeModuleRegistry.ts -> ../spine",+ "platform/web.ts -> ../video/WebVideoBackend",+ "runtime/packagedRuntime.ts -> ../video/VideoAPI",+ "runtime/playRealmRuntime.ts -> ../video/VideoAPI",+ "runtime/playableRuntime.ts -> ../video/VideoAPI"+ ]}diff --git a/tools/check-core-carries-options.mjs b/tools/check-core-carries-options.mjsindex 0a3e87fe6..0cf25ac0c 100644--- a/tools/check-core-carries-options.mjs+++ b/tools/check-core-carries-options.mjs@@ -1,93 +1,116 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file check-core-carries-options.mjs — the core runtime does not grow new- * static dependencies on optional subsystems.+ * @file check-core-carries-options.mjs — what the non-optional half of the SDK+ * drags in from the optional subsystems.** A mini-game inlines the SDK, and a bundler can only drop a chunk nothing- * reaches. `runtime/webAppFactory.ts` and `runtime/runtimeLoader.ts` are in every- * package there is, so every subsystem they `import` by value is too: measured on- * examples/hello-world, that is 259KB of spine, physics, 3D physics, dragonbones- * and video in a project using none of them.+ * reaches. So every value import from outside a subsystem into its SOLVER is a+ * subsystem every package carries, whatever the project contains.*- * A ratchet, not a demand for zero — untangling those is the rest of RM-069, and- * this exists so the number cannot quietly go up while that is being done. A- * `import type` is free (TypeScript erases it) and is not counted.+ * An earlier version of this watched two files and read zero — while+ * `ai/perception`, `gameplay` and `app` reached the solvers the whole time. It+ * watches the whole of `sdk/src` now, which is the only scope that can answer+ * the question it is asking.+ *+ * DECLARATIONS vs SOLVER is not a list kept here: a subsystem draws that line+ * itself, in the entry point named below, and anything it does not export is+ * solver. A subsystem with no such entry is solver all the way through.+ *+ * A ratchet, not a demand for zero — some of these are real features (navigation+ * reads 3D collider shapes). New ones are what it refuses.** node tools/check-core-carries-options.mjs* node tools/check-core-carries-options.mjs --update # bank the current state*/-import { readFileSync, writeFileSync, existsSync } from 'node:fs';+import { readFileSync, writeFileSync, existsSync, readdirSync, 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 SRC = path.join(ROOT, 'sdk', 'src');const BASELINE = path.join(ROOT, 'tools', 'baselines', 'core-carries-options.json');-/**- * The files that are in EVERY package: what a runtime must build an app with,- * and what it must load a scene with. Named rather than derived — a reachability- * walk would answer the same question and be the thing most likely to break- * silently — and a rename fails this loudly below rather than reporting zero.- */-const CORE = ['sdk/src/runtime/webAppFactory.ts', 'sdk/src/runtime/runtimeLoader.ts'];--/**- * Which source directory each optional module's code lives in. The IDS are not- * ours — they are checked against SIDE_MODULES below, so renaming one there- * fails here instead of silently dropping a subsystem from this check.- */-const DIR_OF = {- physics: 'physics',- physics3d: 'physics3d',- dragonbones: 'dragonbones',- videodec: 'video',- basis: 'basis',- 'spine:4.3': 'spine',+/** The optional subsystems, and the entry each uses to say which of its modules+ * are DECLARATIONS. A missing entry means the whole subsystem is solver. */+const SUBSYSTEMS = {+ physics: 'components.ts',+ physics3d: null,+ spine: null,+ dragonbones: null,+ video: null,};-const registry = readFileSync(path.join(ROOT, 'sdk/src/sideModules/registry.ts'), 'utf8');-const declared = new Set(- [...registry.matchAll(/^\s{4}'?([a-z0-9:.]+)'?:\s*\{\s*file:/gim)].map((m) => m[1]),+/** The ids above are checked against SIDE_MODULES, so renaming one there fails+ * here rather than silently dropping a subsystem from what this watches. */+const registry = readFileSync(path.join(SRC, 'sideModules/registry.ts'), 'utf8');+const declaredIds = new Set(+ [...registry.matchAll(/^\s{4}'?([a-z0-9:.]+)'?:\s*\{\s*file:/gim)].map((m) => m[1].split(':')[0]),);-const unknown = Object.keys(DIR_OF).filter((id) => !declared.has(id));+// `video` ships as the `videodec` module and `spine` as `spine:<version>`; both+// are the subsystem's directory name, which is what an import path spells.+const ALIAS = { video: 'videodec' };+const unknown = Object.keys(SUBSYSTEMS).filter((id) => !declaredIds.has(ALIAS[id] ?? id));if (unknown.length > 0) {- console.error('check-core-carries-options: these ids are no longer in SIDE_MODULES —'- + ` the map above is stale: ${unknown.join(', ')}`);+ console.error(`check-core-carries-options: not in SIDE_MODULES any more: ${unknown.join(', ')}`);process.exit(1);}-/** Value imports (not `import type`) out of @p file, as source-relative paths. */-function valueImports(file) {- const src = readFileSync(path.join(ROOT, file), 'utf8');- const out = [];- for (const m of src.matchAll(/^import\s+(type\s+)?([^;]*?)\s*from\s*['"]([^'"]+)['"]/gim)) {- if (m[1]) continue;- // `import { type X, Y }` still pulls Y; `import { type X }` alone does not.- const clause = m[2] ?? '';- const named = clause.match(/\{([^}]*)\}/);- if (named && named[1].split(',').every((s) => s.trim() === '' || /^type\s/.test(s.trim()))) continue;- out.push(m[3]);+/** The modules a subsystem's declaration entry re-exports — its public "data" half. */+function declarationsOf(dir, entry) {+ if (!entry) return new Set();+ const file = path.join(SRC, dir, entry);+ if (!existsSync(file)) {+ console.error(`check-core-carries-options: ${dir}/${entry} is gone — the subsystem`+ + ' no longer says where its declarations end.');+ process.exit(1);}- return out;+ const src = readFileSync(file, 'utf8');+ return new Set([...src.matchAll(/from\s*'\.\/([A-Za-z0-9]+)'/g)].map((m) => m[1]));}-const found = [];-for (const file of CORE) {- if (!existsSync(path.join(ROOT, file))) {- console.error(`check-core-carries-options: ${file} is not there — the core moved,`- + ' and this check is reporting about a file that no longer exists.');- process.exit(1);+const DECLARATIONS = Object.fromEntries(+ Object.entries(SUBSYSTEMS).map(([dir, entry]) => [dir, declarationsOf(dir, entry)]),+);++/** Every .ts under sdk/src, as paths relative to it. */+function sources(dir = SRC, out = []) {+ for (const name of readdirSync(dir)) {+ const full = path.join(dir, name);+ if (statSync(full).isDirectory()) { sources(full, out); continue; }+ if (name.endsWith('.ts') && !name.endsWith('.d.ts')) out.push(path.relative(SRC, full));}- for (const spec of valueImports(file)) {- for (const [id, dir] of Object.entries(DIR_OF)) {- if (new RegExp(`(^|/)\\.\\./${dir}(/|$)`).test(spec)) found.push({ file, dir, spec, id });+ return out;+}++/** The installer's whole job is to reach them, so it is not a finding. It is the+ * one file an entry imports to decide it ships them — see runtime/optionalPlugins. */+const INSTALLER = path.join('runtime', 'optionalPlugins.ts');++const edges = [];+for (const rel of sources()) {+ if (rel === INSTALLER) continue;+ const owner = rel.split(path.sep)[0];+ // A subsystem reaching its own solver is the subsystem, not the core.+ const src = readFileSync(path.join(SRC, rel), 'utf8');+ for (const m of src.matchAll(/^import\s+(type\s+)?([^;]*?)\s*from\s*'([^']+)'/gim)) {+ if (m[1]) continue;+ const clause = m[2] ?? '';+ const named = clause.match(/\{([^}]*)\}/);+ // `import { type X }` alone erases; `import { type X, Y }` still pulls Y.+ if (named && named[1].split(',').every((s) => s.trim() === '' || /^type\s/.test(s.trim()))) continue;+ for (const [dir, decls] of Object.entries(DECLARATIONS)) {+ const hit = new RegExp(`(^|/)${dir}(/([A-Za-z0-9]+))?$`).exec(m[3]);+ if (!hit || owner === dir) continue;+ // The barrel itself is solver: importing it installs the subsystem.+ const module = hit[3];+ if (module && decls.has(module)) continue;+ edges.push(`${rel.split(path.sep).join('/')} -> ${m[3]}`);}}}-const key = (r) => `${r.file} -> ${r.spec}`;-const now = found.map(key).sort();+const now = [...new Set(edges)].sort();if (process.argv.includes('--update')) {writeFileSync(BASELINE, `${JSON.stringify({ edges: now }, null, 2)}\n`);@@ -104,18 +127,14 @@ const added = now.filter((e) => !before.has(e));const gone = [...before].filter((e) => !now.includes(e));if (added.length > 0) {- console.error(`check-core-carries-options: ${added.length} new static dependency(ies)`- + ' from the core runtime onto an optional subsystem:\n');+ console.error(`check-core-carries-options: ${added.length} new reach(es) into an optional`+ + ' subsystem\'s solver:\n');for (const e of added) console.error(` ${e}`);- console.error('\nEvery package carries the core, so it now carries these too. Reach them'- + ' through the plugin set the runtime is BUILT with, or bank this with --update'- + ' and say why in the commit.');+ console.error('\nEvery package carries the reaching side, so it now carries that solver too.'+ + ' Reach it through a seam (runtime/sceneOptionals), take only what the subsystem'+ + ' declares, or bank this with --update and say why in the commit.');process.exit(1);}-const byDir = new Map();-for (const r of found) byDir.set(r.dir, (byDir.get(r.dir) ?? 0) + 1);-const spread = [...byDir.entries()].sort((a, b) => b[1] - a[1]).map(([d, n]) => `${d} ×${n}`);-console.log(`check-core-carries-options: ${now.length} edge(s) onto ${byDir.size} optional`- + ` subsystem(s) — ${spread.join(', ')}`- + `${gone.length > 0 ? `; ${gone.length} fewer than banked (run --update to keep it down)` : ''}`);+console.log(`check-core-carries-options: ${now.length} reach(es) into optional solvers`+ + `${gone.length > 0 ? `, ${gone.length} fewer than banked (run --update)` : ''}`);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex f36398a3b..78d9aef58 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,9 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'refactor(sdk): 2D physics declares where its declarations end':+ { internal: 'Where the same code lives; behaviour and the public surface are unchanged.' },+'feat(export): a mini-game carries the optional subsystems its project uses':{ note: 'A WeChat mini-game now carries only the optional subsystems its project uses.' },