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
feat: defaults follow the project's units; Particle.emitAt; first-person jump feel
yhh809bb7a58f31
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa7721b3a..2c10a83ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,9 @@ published separately; it ships inside the editor.- **The sky lights the scene.** Sky Atmosphere's **Light the Scene** makes the sky the scene's environment: every Ambient light that names no environment of its own lights with it, its diffuse light from the dome and the clouds and its reflection on metal and wet ground, scaled by the light's colour and intensity as an imported one is. The sky is worked out again as it changes (the sun moving, a weather coming in, clouds drifting), at most once a second; with clouds that takes about 20 ms on a desktop. The sun's disc is left out, since the directional light the sky follows is its direct light. Off by default, so a scene already lit by hand looks as it did.- **Rooms stay dark under a sky that changes (sky occlusion).** With **Sky occlusion** on in the Lighting settings (`BakedLighting.skyOcclusion`), a probe bake keeps how much of the sky each probe sees instead of the sky itself: the probes hold the lights and their bounces, and the sky the frame has now (a live Sky Atmosphere, a weather, an environment) is added through what each probe sees of it, to the diffuse light and to the sky's reflection. A ball inside a roofed room measured 119 where the baked sky gave it 150, and a ball outside kept its light. A `.esprobes` baked this way carries `skyVisibility`; one without it lights as before. Probes are read per object, as Unity's light probes are: one large mesh spanning indoors and out takes one value.+- **Defaults follow the project's units.** Every default that is a length, a speed or an acceleration — a character's capsule, a first-person walk and jump, a view model's near plane, a nav volume's cells, a perceiver's range, a particle's size and speed — is written at 100 units a metre and scaled by the project's units per metre (Project Settings → Physics → 3D). A centimetre project gets exactly the defaults it had; a metre project (an imported glTF scene) now gets metres instead of values 100 times too big. A value a scene states is never scaled. A component declares its own with `worldUnitFields`.+- **`Particle.emitAt(emitter, count, position, { normal, velocity })` spawns a burst where something happened, now** — an impact's sparks, a muzzle's flash — from the emitter's own settings, its shape turned onto the normal, without moving the emitter or replaying it (Unity's `ParticleSystem.Emit`). CPU-simulated emitters.+- **A first-person player has its own jump feel.** `FirstPersonController.gravityScale` (the player's gravity as a share of the world's), `coyoteTime` (a jump just after walking off an edge still takes off) and `jumpBuffer` (a jump pressed just before landing takes off as it lands).- **A UI node can stand over a point in the 3D world.** `UIWorldAnchor` puts its UINode at the screen position of an entity (plus an offset) or a world point every frame: an objective marker, a name over a head, a health bar. `clampToEdges` keeps an off-screen or behind-the-camera marker on the screen's edge in its true direction; `onScreen`, `behind` and `distance` read back. It is placed from the camera's pose at the end of Update, so a marker does not trail a first-person view that turned this frame. Saltline's relay and boat markers are four of them.- **Perceivers hear.** `Perceiver.hearingRange` and a `Noise` event (where, how loud, who made it): a perceiver hears a noise within `hearingRange * loudness`, through walls, as Unreal's hearing sense does, and `Perception` keeps `heard`, where the last noise came from and `sinceHeard`. Saltline's machines come to a gunshot within 45 m.- **A ray can meet characters.** `Physics3D.raycast(origin, direction, layers, { characters: true })` stops on a `CharacterController3D`'s capsule where it is now, on Jolt and on PhysX alike; a plain ray still passes them, which line of sight and a camera's boom rely on. Before, nothing could shoot a character that walks.@@ -33,6 +36,8 @@ published separately; it ships inside the editor.### Fixed+- **A character controller or a 3D collider added with its defaults is a real size.** Their defaults were metres (a 0.3 radius, a 0.5 box) under a world that reads centimetres unless told otherwise: a 3 mm character, a 5 mm crate. They are a 1.6 m person and a 1 m box now, in whatever units the project uses. Every example and template stated its sizes, so none changes.+- **A model's import no longer calls it tiny in a metre project.** The note read every model as if a world unit were a design pixel; it now measures the model in metres by the project's units per metre and suggests that as the Scale.- **Navigation bakes an imported level.** The bake took only bodies with a static RigidBody3D, so a level of mesh colliders (static by themselves) baked to no ground; and it placed every collider at its LOCAL pose and unscaled, so one under a parent landed elsewhere. It now takes what the solver builds, where the solver builds it.- **Perception senses from where things are in the world.** It read each entity's own position, so a perceiver on a head bone or a target on a player's eye camera sensed from near the origin; sight measured feet to feet was also cut by every kerb.- **A first-person view model no longer hides the world in a linear or tone-mapped project.** A camera that keeps the colour under it (clears depth only, as the held-gun camera of `FirstPersonViewModel` does) still draws through a capture of its own when the frame is linear or has an output transform; that capture started black and was copied over the camera beneath, so the world went black around the gun. It is now laid over by coverage. Gate: overlay-camera-linear.diff --git a/desktop b/desktopindex 8235baeb9..c2f4330f0 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 8235baeb992b87c58ee0fdced1d7a5ad1f06ce7c+Subproject commit c2f4330f0360018c4e4fa456a6f5d3a672314315diff --git a/docs/astro/src/content/docs/ui/overview.mdx b/docs/astro/src/content/docs/ui/overview.mdxindex a639cd228..a913d24eb 100644--- a/docs/astro/src/content/docs/ui/overview.mdx+++ b/docs/astro/src/content/docs/ui/overview.mdx@@ -299,6 +299,30 @@ parts — the clipped box, the oversized child — without the one fact that it**+ Add → Create entity… → ScrollView** gives you all three already assembled.</Aside>+### `UIWorldAnchor` — UI over a point in the world++A HUD often marks something in the 3D world: an objective, a name over a head, a health bar. `UIWorldAnchor`+puts its UI node at the screen position of an entity (plus `offset`) or of a world point, every frame. The node+is placed Absolute by its left/top insets in its parent, which should cover the screen (a screen Canvas root or+a full-screen panel); centre it on the point with negative margins of half its size.++- `clampToEdges` keeps a marker that is off screen, or behind the camera, on the screen's edge in the point's+ real direction — the usual objective marker. Without it, a point behind the camera hides the node.+- `onScreen`, `behind` and `distance` (world units from the camera) read back, for a "34m" label.+- The camera is the one on screen (the active camera that clears colour with the highest priority), or the one+ `camera` names.++It projects from the camera's pose at the end of Update, so a marker does not trail a first-person view that+turned this frame. It only hides a node while the point is behind the camera, and shows again only a node it+hid itself: a marker the game hides (an objective done) stays hidden.++```typescript+import { UIWorldAnchor, UINode } from 'esengine';++world.insert(marker, UINode, { width: px(60), height: px(40), marginLeft: px(-30), marginTop: px(-20) });+world.insert(marker, UIWorldAnchor, { target: relay, offset: { x: 0, y: 2.5, z: 0 }, clampToEdges: true });+```+## Editor or codediff --git a/docs/astro/src/content/docs/zh-cn/ui/overview.mdx b/docs/astro/src/content/docs/zh-cn/ui/overview.mdxindex dec8ccbb5..76d504a4e 100644--- a/docs/astro/src/content/docs/zh-cn/ui/overview.mdx+++ b/docs/astro/src/content/docs/zh-cn/ui/overview.mdx@@ -191,6 +191,27 @@ world.insert(banner, RectAnchors, {});```+### `UIWorldAnchor` —— 立在世界某一点上的 UI++HUD 常要标出 3D 世界里的东西:目标点、头顶的名字、血条。`UIWorldAnchor` 每帧把所在的 UI 节点放到一个实体+(加 `offset`)或一个世界坐标点在屏幕上的位置。节点按 Absolute 定位,用左/上内边距放在父节点里,父节点应铺满+屏幕(屏幕 Canvas 根或全屏面板);用一半尺寸的负外边距让它以该点为中心。++- `clampToEdges`:点在屏幕外或摄像机背后时,标记停在屏幕边缘、指向点的真实方向——常见的目标标记。不开时,+ 点在摄像机背后就隐藏节点。+- `onScreen`、`behind`、`distance`(离摄像机的世界单位)可读回,用来显示“34m”。+- 摄像机是屏幕上那台(清颜色、优先级最高的激活摄像机),或 `camera` 指定的那台。++它在 Update 结束时按摄像机的位姿投影,所以第一人称视角本帧转动时标记不会滞后一帧。它只在点位于摄像机背后时+隐藏节点,也只重新显示它自己隐藏的节点:游戏自己隐藏的标记(目标已完成)会保持隐藏。++```typescript+import { UIWorldAnchor, UINode } from 'esengine';++world.insert(marker, UINode, { width: px(60), height: px(40), marginLeft: px(-30), marginTop: px(-20) });+world.insert(marker, UIWorldAnchor, { target: relay, offset: { x: 0, y: 2.5, z: 0 }, clampToEdges: true });+```+### `UIPages` —— 用到才存在的页面一个有很多页面的界面不需要把它们同时放进世界。`UIPages` 把每个页面存成预制体,第一次打开时才构建:diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 05bb45c12..11280a1c0 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -127,6 +127,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {UIMask: { category: 'ui', summary: "Clips descendants to this node's rect, with an optional alpha cutoff.", doc: 'ui/lists', anchor: 'clipping--uimask', anchorZh: '裁剪--uimask' },ContentRect: { category: 'ui', summary: 'The rectangle world content occupies — a size and the pivot the transform sits on — that its sprite, text and clip mask follow.', doc: 'ui/overview', anchor: 'contentrect--a-rectangle-for-world-content', anchorZh: 'contentrect--世界内容的矩形' },RectAnchors: { category: 'ui', summary: 'Pins content placed by its transform to the edges or the centre of its parent\'s ContentRect, or of the screen: each axis stretched, pinned to an edge, or centred, with margins in units or as a fraction.', doc: 'ui/overview', anchor: 'rectanchors--world-content-that-follows-its-parent', anchorZh: 'rectanchors--跟随父级的世界内容' },+ UIWorldAnchor: { category: 'ui', summary: 'Stands a UI node over a point in the 3D world — an objective marker, a name over a head — and keeps it on the screen\'s edge when the point is out of view.', doc: 'ui/overview', anchor: 'uiworldanchor--ui-over-a-point-in-the-world', anchorZh: 'uiworldanchor--立在世界某一点上的-ui' },UIScroll: { category: 'ui', summary: 'Scrollable content inside a clipped viewport, with momentum and scrollbars.', doc: 'ui/overview', anchor: 'scrolling', anchorZh: '滚动' },FlexContainer: { category: 'ui', summary: 'Lays children out along an axis — direction, justification, alignment, wrapping and gaps.', doc: 'ui/layout', anchor: 'flexcontainer--laying-out-children', anchorZh: 'flexcontainer排布子项' },Interactable: { category: 'ui', summary: 'Makes a UI node hit-testable, so pointer events can land on it.', doc: 'ui/interaction', anchor: 'hit-testing-interactable--uiinteraction', anchorZh: '命中测试interactable--uiinteraction' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 58fe6621a..ab46a75c1 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -556,7 +556,7 @@{"key": "halfExtents","type": "Vec3",- "default": "(0.5, 0.5, 0.5)"+ "default": "(50, 50, 50)"},{"key": "center",@@ -836,13 +836,13 @@{"key": "radius","type": "number",- "default": "0.3",+ "default": "30","range": "≥ 0"},{"key": "halfHeight","type": "number",- "default": "0.5",+ "default": "50","range": "≥ 0"},{@@ -1112,13 +1112,13 @@{"key": "radius","type": "number",- "default": "0.3",+ "default": "30","range": "≥ 0"},{"key": "halfHeight","type": "number",- "default": "0.5",+ "default": "50","range": "≥ 0"},{@@ -1138,14 +1138,14 @@{"key": "stepHeight","type": "number",- "default": "0.4",+ "default": "40","range": "≥ 0, step 0.05","advanced": true},{"key": "snapDown","type": "number",- "default": "0.5",+ "default": "50","range": "≥ 0, step 0.05","advanced": true},@@ -1895,6 +1895,29 @@"doc": "Upward speed a jump starts with. 0 = cannot jump.","range": "≥ 0"},+ {+ "key": "gravityScale",+ "type": "number",+ "default": "1",+ "doc": "The player's gravity as a share of the world's. Above 1 falls faster and jumps feel snappier.",+ "range": "≥ 0, step 0.05"+ },+ {+ "key": "coyoteTime",+ "type": "number",+ "default": "0.1",+ "doc": "How long after walking off an edge a jump still works.",+ "range": "≥ 0, step 0.01",+ "advanced": true+ },+ {+ "key": "jumpBuffer",+ "type": "number",+ "default": "0.12",+ "doc": "How long a jump pressed just before landing is kept.",+ "range": "≥ 0, step 0.01",+ "advanced": true+ },{"key": "lookSensitivity","type": "number",@@ -2009,6 +2032,24 @@"type": "number","default": "0","readonly": true+ },+ {+ "key": "airTime",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "jumpHeld",+ "type": "number",+ "default": "0",+ "readonly": true+ },+ {+ "key": "jumped",+ "type": "boolean",+ "default": "false",+ "readonly": true}],"animatable": [@@ -2019,6 +2060,9 @@"deceleration","airControl","jumpSpeed",+ "gravityScale",+ "coyoteTime",+ "jumpBuffer","lookSensitivity","touchSensitivity","pitchMin",@@ -2033,7 +2077,9 @@"pitch","standHalfHeight","eye",- "rebuild"+ "rebuild",+ "airTime",+ "jumpHeld"]},{@@ -5139,12 +5185,20 @@"doc": "3D layer mask the sight ray may hit; 0 = every layer.","range": "≥ 0","advanced": true+ },+ {+ "key": "hearingRange",+ "type": "number",+ "default": "0",+ "doc": "How far a noise of loudness 1 is heard, through walls; 0 = deaf.",+ "range": "≥ 0"}],"animatable": ["range","fovDegrees",- "losLayers"+ "losLayers",+ "hearingRange"]},{@@ -5192,6 +5246,31 @@"key": "dirZ","type": "number","default": "0"+ },+ {+ "key": "heard",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "noiseX",+ "type": "number",+ "default": "0"+ },+ {+ "key": "noiseY",+ "type": "number",+ "default": "0"+ },+ {+ "key": "noiseZ",+ "type": "number",+ "default": "0"+ },+ {+ "key": "sinceHeard",+ "type": "number",+ "default": "-1"}],"transient": true,@@ -5202,7 +5281,11 @@"targetZ","dirX","dirY",- "dirZ"+ "dirZ",+ "noiseX",+ "noiseY",+ "noiseZ",+ "sinceHeard"]},{@@ -7011,7 +7094,7 @@{"key": "radius","type": "number",- "default": "0.5",+ "default": "50","range": "≥ 0"},{@@ -9788,6 +9871,80 @@"fillAmount"]},+ {+ "name": "UIWorldAnchor",+ "source": "ts",+ "fields": [+ {+ "key": "target",+ "type": "Entity",+ "default": "none",+ "doc": "The entity to stand over. Empty: stand over the world point Offset."+ },+ {+ "key": "offset",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Added to the target's position (world units): above a head, at a door. The point itself with no target."+ },+ {+ "key": "camera",+ "type": "Entity",+ "default": "none",+ "doc": "The camera that looks. Empty: the camera on screen.",+ "advanced": true+ },+ {+ "key": "clampToEdges",+ "type": "boolean",+ "default": "false",+ "doc": "Off screen, stand at the edge in its direction instead of leaving it."+ },+ {+ "key": "edgeMargin",+ "type": "number",+ "default": "24",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "hideWhenBehind",+ "type": "boolean",+ "default": "true",+ "advanced": true+ },+ {+ "key": "onScreen",+ "type": "boolean",+ "default": "false",+ "readonly": true,+ "advanced": true+ },+ {+ "key": "behind",+ "type": "boolean",+ "default": "false",+ "readonly": true,+ "advanced": true+ },+ {+ "key": "distance",+ "type": "number",+ "default": "0",+ "readonly": true,+ "advanced": true+ }+ ],+ "animatable": [+ "target",+ "offset.x",+ "offset.y",+ "offset.z",+ "camera",+ "edgeMargin",+ "distance"+ ]+ },{"name": "Velocity","source": "cpp",diff --git a/pipeline/src/assets/importModelFile.ts b/pipeline/src/assets/importModelFile.tsindex 91033f75a..dc25397d8 100644--- a/pipeline/src/assets/importModelFile.ts+++ b/pipeline/src/assets/importModelFile.ts@@ -20,6 +20,7 @@ import {type ImportedMesh, type ImportedNode, type SpecularMapReading,} from './modelImport';import { modelStem, readModelSource } from './readModelSource';+import { parseManifest } from '../project/format';export interface ModelImportSettings {scale: number;@@ -103,6 +104,18 @@ function collectNodeMeshes(nodes: ImportedNode[], meshFiles: string[], out: Map<* Import `absSource` into `destDir` of the project at `root`, writing the meshes, the images it carries, the materials, the clips and the* prefab that assembles them.*/+/** The project's units per metre (`features.physics.world3d.unitsPerMeter`), or the engine's 100 when it states none or is no project. */+function projectUnitsPerMeter(root: string): number {+ try {+ const file = path.join(root, 'project.esproject');+ if (!existsSync(file)) return 100;+ const text = readFileSync(file, 'utf8');+ return parseManifest(JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text)).features?.physics?.world3d?.unitsPerMeter ?? 100;+ } catch {+ return 100;+ }+}+export async function importModelFile(opts: ImportModelOptions): Promise<ImportedModel> {const { root, destDir, absSource } = opts;const absDir = destDir ? resolveInside(root, destDir, 'model destination') : path.resolve(root);@@ -259,11 +272,15 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importeif (meshes.length > 0) {const prefab = assembleModelPrefab(stem, meshes, { refs, nodes, scale, timeline: firstClip });prefabRef = await write(`${stem}.esprefab`, `${JSON.stringify(prefab, null, 2)}\n`);- // Models are authored in metres and a world unit is a design pixel, so a real-world model arrives a few pixels across. Said, not- // guessed at: the scale is the user's, and this is where they find out they have one.+ // A model is authored in metres; what it measures in this project depends on the project's units per metre (Project Settings →+ // Physics → 3D: 100 unless set, 1 in a metre project). Under 8 cm in real terms, it is almost always a model whose Scale does not+ // match the project — said, not guessed at: the scale is the user's, and this is where they find out they have one.const extent = Math.max(...meshes.flatMap((m) => m.data.aabbMax.map((v, i) => v - (m.data.aabbMin[i] ?? 0))));- if (scale === 1 && extent < 8) {- warnings.push(`the model is ${extent.toFixed(2)} units across — set Scale in its import settings and reimport if it should be bigger`);+ const unitsPerMeter = projectUnitsPerMeter(root);+ const metres = (extent * scale) / unitsPerMeter;+ if (metres < 0.08 && scale !== unitsPerMeter) {+ warnings.push(`the model is ${metres.toFixed(3)} m across in this project (${unitsPerMeter} units a metre) — `+ + `set Scale to ${unitsPerMeter} in its import settings and reimport if it is a real-world size`);}}diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex 9d60bc1e6..83cecd8d3 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -216,7 +216,8 @@ const MODEL: ImporterFieldSpec[] = [key: 'scale', label: 'Scale', type: 'number', default: 1, min: 0.0001, step: 0.1,category: 'Import',tooltip: 'Uniform scale on the imported prefab\u0027s root. A model is authored in metres '- + 'and a world unit is a design pixel, so a real-world model arrives a few pixels across.',+ + 'whose real size in this project is set by its units per metre (Project Settings, Physics, 3D): '+ + 'a Scale of 100 by default, 1 in a metre project, brings it in at real size.',},{key: 'lightmapUV', label: 'Generate Lightmap UVs', type: 'bool', default: false,diff --git a/sdk/src/ai/nav/NavAgent.ts b/sdk/src/ai/nav/NavAgent.tsindex 85c8cb54f..7d170791e 100644--- a/sdk/src/ai/nav/NavAgent.ts+++ b/sdk/src/ai/nav/NavAgent.ts@@ -51,6 +51,8 @@ export const NavAgent = defineComponent<NavAgentData>('NavAgent', {targetZ: 0,arrived: false,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['speed', 'radius', 'arriveRadius'],fields: {speed: { min: 0, unit: 'px/s', category: 'Navigation' },radius: { min: 0, unit: 'px', category: 'Navigation' },diff --git a/sdk/src/ai/nav/NavArea.ts b/sdk/src/ai/nav/NavArea.tsindex a6642b0f1..174255307 100644--- a/sdk/src/ai/nav/NavArea.ts+++ b/sdk/src/ai/nav/NavArea.ts@@ -34,6 +34,8 @@ export const NavArea = defineComponent<NavAreaData>('NavArea', {cost: 3,enabled: true,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['halfExtents'],fields: {halfExtents: { unit: 'px', category: 'Navigation' },cost: { min: 0, category: 'Navigation', tooltip: 'What crossing it costs against 1 for open ground.' },diff --git a/sdk/src/ai/nav/NavLink.ts b/sdk/src/ai/nav/NavLink.tsindex 630670661..010ad0812 100644--- a/sdk/src/ai/nav/NavLink.ts+++ b/sdk/src/ai/nav/NavLink.ts@@ -39,6 +39,8 @@ export const NavLink = defineComponent<NavLinkData>('NavLink', {radius: 50,enabled: true,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['end', 'radius'],fields: {start: { unit: 'px', category: 'Navigation' },end: { unit: 'px', category: 'Navigation' },diff --git a/sdk/src/ai/nav/NavObstacle.ts b/sdk/src/ai/nav/NavObstacle.tsindex 17e6dfa04..3d518654c 100644--- a/sdk/src/ai/nav/NavObstacle.ts+++ b/sdk/src/ai/nav/NavObstacle.ts@@ -29,6 +29,8 @@ export const NavObstacle = defineComponent<NavObstacleData>('NavObstacle', {halfExtents: { x: 50, y: 100, z: 50 },enabled: true,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['halfExtents'],fields: {halfExtents: { unit: 'px', category: 'Navigation' },enabled: { category: 'Navigation', tooltip: 'Whether it blocks right now — a door that opens.' },diff --git a/sdk/src/ai/nav/NavVolume.ts b/sdk/src/ai/nav/NavVolume.tsindex 68a661819..d0340ea4d 100644--- a/sdk/src/ai/nav/NavVolume.ts+++ b/sdk/src/ai/nav/NavVolume.ts@@ -49,6 +49,8 @@ export const NavVolume = defineComponent<NavVolumeData>('NavVolume', {stepHeight: 40,layers: 0,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['halfExtents', 'cellSize', 'cellHeight', 'agentHeight', 'agentRadius', 'stepHeight'],fields: {halfExtents: { unit: 'px', category: 'Navigation' },cellSize: { min: 1, unit: 'px', category: 'Navigation' },diff --git a/sdk/src/ai/perception/components.ts b/sdk/src/ai/perception/components.tsindex 4c055fb83..fa6a1ceba 100644--- a/sdk/src/ai/perception/components.ts+++ b/sdk/src/ai/perception/components.ts@@ -41,6 +41,8 @@ export const Perceiver = defineComponent<PerceiverData>('Perceiver', {losLayers: 0,hearingRange: 0,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['range', 'hearingRange'],fields: {range: { min: 0, unit: 'px', category: 'Perception' },fovDegrees: { min: 0, max: 360, unit: '°', category: 'Perception' },diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex caa7cdef6..c73cad3d8 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -331,6 +331,7 @@ export {type WeChatSideModuleFactories,} from './sideModules';export { DEFAULT_PHYSICS3D_WORLD, physics3DPluginConfigOf, physics3DInstallConfig, type Physics3DWorldConfig } from './physics3d/worldConfig';+export { setWorldUnitsPerMeter, worldUnitsPerMeter, worldUnitScale, REFERENCE_UNITS_PER_METER } from './ecs/worldUnits';// =============================================================================// Playable Runtimediff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex f01ee52f7..4e09e26be 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -92,6 +92,7 @@ export interface NativeEngineApi {particle_collisionSetBudget?(queries: number, events: number, debug: boolean): void;particle_collisionStats?(): number;particle_collisionStatsCount?(): number;+ particle_emitAt?(registry: unknown, entity: number, count: number, px: number, py: number, pz: number, nx: number, ny: number, nz: number, vx: number, vy: number, vz: number): number;particle_getAliveCount?(entity: number): number;particle_play?(registry: unknown, entity: number): void;particle_reset?(registry: unknown, entity: number): void;@@ -436,6 +437,7 @@ export function createNativeEngineApi(bind('particle_collisionSetBudget', 'es_particle_collisionSetBudget', false);bind('particle_collisionStats', 'es_particle_collisionStats', false);bind('particle_collisionStatsCount', 'es_particle_collisionStatsCount', false);+ bind('particle_emitAt', 'es_particle_emitAt', true);bind('particle_getAliveCount', 'es_particle_getAliveCount', false);bind('particle_play', 'es_particle_play', true);bind('particle_reset', 'es_particle_reset', true);diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 2f822c53d..0d277caf7 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -160,7 +160,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {},BoxCollider3D: {defaults: {- halfExtents: { x: 0.5, y: 0.5, z: 0.5 },+ halfExtents: { x: 50, y: 50, z: 50 },center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0,@@ -256,8 +256,8 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {},CapsuleCollider3D: {defaults: {- radius: 0.3,- halfHeight: 0.5,+ radius: 30,+ halfHeight: 50,center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0,@@ -278,11 +278,11 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {CharacterController3D: {defaults: {velocity: { x: 0, y: 0, z: 0 },- radius: 0.3,- halfHeight: 0.5,+ radius: 30,+ halfHeight: 50,maxSlope: 0.87,- stepHeight: 0.4,- snapDown: 0.5,+ stepHeight: 40,+ snapDown: 50,mass: 70,pushForce: 5000,enabled: true,@@ -1103,7 +1103,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {},SphereCollider3D: {defaults: {- radius: 0.5,+ radius: 50,center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0,diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.tsindex e41550401..7fe0d5fbb 100644--- a/sdk/src/ecs/component.ts+++ b/sdk/src/ecs/component.ts@@ -6,6 +6,7 @@*/import { Entity, Vec2, Vec3, Color, Quat } from '../types';+import { worldUnitDefaults, BUILTIN_WORLD_UNIT_FIELDS } from './worldUnits';import { deepClone } from '../util/deepClone';import { hasOwn, setOwn } from '../util/ownProperties';import { COMPONENT_META, type AssetFieldMeta, type SkeletalFieldMeta } from './component.generated';@@ -135,6 +136,12 @@ export interface FieldMeta {* @public*/export interface ComponentMetadata {+ /**+ * Fields that are world lengths, speeds or accelerations (a radius, a walk speed, gravity): their defaults are+ * written at the reference 100 units a metre and scale with the project's units per metre (ecs/worldUnits.ts).+ * A value a scene states is never scaled.+ */+ worldUnitFields?: string[];assetFields?: AssetFieldMeta[];skeletalFields?: SkeletalFieldMeta;entityFields?: string[];@@ -347,6 +354,10 @@ function createComponentDef<T extends object>(}const keyInfo = classifyKeys(defaults);const defaultsRec = defaults as Record<string, unknown>;+ for (const f of metadata?.worldUnitFields ?? []) {+ if (!hasOwn(defaultsRec, f)) throw new Error(`Component "${name}": worldUnitFields names unknown field "${f}"`);+ }+ const currentDefaults = worldUnitDefaults(defaults, metadata?.worldUnitFields ?? []);// A replicated name that matches no field would silently sync nothing — the// drift class this metadata exists to kill, so it fails loud (same spirit as// EHT rejecting a malformed known annotation).@@ -366,7 +377,8 @@ function createComponentDef<T extends object>(return {_id: componentId(name),_name: name,- _default: defaults,+ // In the project's units: what a default fills in follows its units per metre.+ get _default() { return currentDefaults(); },_builtin: false as const,assetFields: metadata?.assetFields ?? [],skeletalFields: metadata?.skeletalFields,@@ -380,9 +392,10 @@ function createComponentDef<T extends object>(transient: metadata?.transient ?? false,renderableField: renderableField ?? null,create(data?: Partial<T>): T {+ const now = currentDefaults();// Flat defaults have nothing to merge into, so they take the cheap path.- if (keyInfo) return mergeIntoDefaults(defaults, data);- return data ? { ...defaults, ...data } : { ...defaults };+ if (keyInfo) return mergeIntoDefaults(now, data);+ return data ? { ...now, ...data } : { ...now };}};}@@ -767,12 +780,14 @@ export function defineBuiltin<T>(name: string, defaults: T, metadata?: Component}const meta = COMPONENT_META[name];+ const currentDefaults = worldUnitDefaults(defaults, metadata?.worldUnitFields ?? BUILTIN_WORLD_UNIT_FIELDS[name] ?? []);const def: BuiltinComponentDef<T> = {_id: Symbol(`Builtin_${name}`),_name: name,_cppName: name,_builtin: true,- _default: defaults,+ // In the project's units: what a default fills in follows its units per metre.+ get _default() { return currentDefaults(); },assetFields: metadata?.assetFields ?? meta?.assetFields ?? [],skeletalFields: metadata?.skeletalFields ?? meta?.skeletal,entityFields: metadata?.entityFields ?? meta?.entityFields ?? [],diff --git a/sdk/src/ecs/worldUnits.ts b/sdk/src/ecs/worldUnits.tsnew file mode 100644index 000000000..395ea94fe--- /dev/null+++ b/sdk/src/ecs/worldUnits.ts@@ -0,0 +1,95 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file worldUnits.ts+ * @brief What one world unit is, and the defaults that follow it.+ *+ * @details A 3D project says how many world units make a metre (Project Settings → Physics → 3D, `world3d.unitsPerMeter`):+ * 100 — a unit is a centimetre — unless it says otherwise, and 1 for a scene in metres such as an imported glTF.+ * Every default that is a length, a speed or an acceleration is written once, at that reference of 100 a metre,+ * and is scaled by the project's own: a character controller is a 1.6 m person, a first-person walk 3.2 m/s and a+ * particle half a metre across in either kind of project. Before, those defaults were written in whichever unit+ * their author had in mind — the character's in metres under a solver that reads centimetres, a 3 mm capsule; the+ * first person's in centimetres in a metre scene, a 3.2 km/s walk.+ *+ * A value a scene states is never scaled: only what a default fills in is.+ */++/** The scale every world-unit default is written at: 100 units a metre, a unit a centimetre. */+export const REFERENCE_UNITS_PER_METER = 100;++let unitsPerMeter = REFERENCE_UNITS_PER_METER;+let epoch = 0;++/**+ * Set the project's units per metre. Called before a scene loads (by the runtime from the project's config, by the+ * editor when a project opens or the setting changes), so the defaults it fills in are the project's.+ */+export function setWorldUnitsPerMeter(value: number): void {+ const v = Number.isFinite(value) && value > 0 ? value : REFERENCE_UNITS_PER_METER;+ if (v === unitsPerMeter) return;+ unitsPerMeter = v;+ epoch++;+}++/** The project's units per metre. */+export function worldUnitsPerMeter(): number {+ return unitsPerMeter;+}++/** What a reference-scale default is multiplied by: 1 in a centimetre project, 0.01 in a metre one. */+export function worldUnitScale(): number {+ return unitsPerMeter / REFERENCE_UNITS_PER_METER;+}++/** Bumped on every change, so a cache of scaled defaults knows it is stale. */+export function worldUnitEpoch(): number {+ return epoch;+}++/**+ * The world-unit fields of the engine's own components whose defaults come from C++ (generated), so cannot carry+ * the flag in their TS definition. A component defined in TS names its own in `ComponentMetadata.worldUnitFields`.+ */+export const BUILTIN_WORLD_UNIT_FIELDS: Readonly<Record<string, readonly string[]>> = {+ CharacterController3D: ['radius', 'halfHeight', 'stepHeight', 'snapDown'],+ BoxCollider3D: ['halfExtents', 'center'],+ SphereCollider3D: ['radius', 'center'],+ CapsuleCollider3D: ['radius', 'halfHeight', 'center'],+ ParticleEmitter: [+ 'shapeRadius', 'shapeSize', 'speedMin', 'speedMax', 'startSizeMin', 'startSizeMax', 'endSizeMin', 'endSizeMax',+ 'gravity', 'addedVelocityMin', 'addedVelocityMax', 'speedLimit', 'noiseStrength', 'trailWidth', 'trailMinDistance',+ 'collisionThickness', 'collisionMaxDistance',+ ],+};++type Rec = Record<string, unknown>;++/** `defaults` with each named field multiplied by `scale` (a number, or each axis of a vector). */+export function scaleWorldUnitFields<T>(defaults: T, fields: readonly string[], scale: number): T {+ if (scale === 1 || fields.length === 0) return defaults;+ const out = { ...(defaults as Rec) };+ for (const f of fields) {+ const v = out[f];+ if (typeof v === 'number') out[f] = v * scale;+ else if (v !== null && typeof v === 'object' && !Array.isArray(v)) {+ const axes = { ...(v as Rec) };+ for (const k of ['x', 'y', 'z', 'w']) if (typeof axes[k] === 'number') axes[k] = (axes[k] as number) * scale;+ out[f] = axes;+ }+ }+ return out as T;+}++/**+ * The defaults a component hands out now: its reference-scale ones, scaled to the project's units. Cached until the+ * scale changes; at the reference scale the very object it was defined with.+ */+export function worldUnitDefaults<T>(raw: T, fields: readonly string[]): () => T {+ let cached: T = raw, at = -1;+ return () => {+ if (fields.length === 0 || worldUnitScale() === 1) return raw;+ if (at !== epoch) { cached = scaleWorldUnitFields(raw, fields, worldUnitScale()); at = epoch; }+ return cached;+ };+}diff --git a/sdk/src/gameplay/FirstPersonController.ts b/sdk/src/gameplay/FirstPersonController.tsindex 207d5ef89..c61a491cd 100644--- a/sdk/src/gameplay/FirstPersonController.ts+++ b/sdk/src/gameplay/FirstPersonController.ts@@ -32,6 +32,16 @@ export interface FirstPersonControllerData {airControl: number;/** Upward speed a jump starts with; 0 disables jumping. */jumpSpeed: number;+ /**+ * The player's own gravity, as a share of the world's: 1 falls as everything else does; a game that wants a+ * snappier arc than the world's bodies (Saltline's 21 m/s² against 9.81) sets more. The controller carries its own+ * vertical speed while airborne then.+ */+ gravityScale: number;+ /** Seconds after walking off an edge in which a jump still takes off ("coyote time"). */+ coyoteTime: number;+ /** Seconds a jump pressed before landing is kept, so it takes off on the frame the player lands. */+ jumpBuffer: number;/** Degrees of turn for each pixel the pointer moves. */lookSensitivity: number;/** Degrees of turn for each pixel a finger drags. */@@ -67,6 +77,12 @@ export interface FirstPersonControllerData {eye: number;/** A rebuild of the capsule in progress: 0 none, 1 the old one is let go and the new one made on the next step. */rebuild: number;+ /** Seconds since the character last stood on the floor; set by the controller. */+ airTime: number;+ /** Seconds the last jump press has left to take off in; set by the controller. */+ jumpHeld: number;+ /** Whether the jump this airborne spell started with has been used; set by the controller. */+ jumped: boolean;}/**@@ -76,13 +92,16 @@ export interface FirstPersonControllerData {*/export const FirstPersonController: ComponentDef<FirstPersonControllerData> = defineComponent<FirstPersonControllerData>('FirstPersonController', {moveSpeed: 320, sprintMultiplier: 1.6, crouchMultiplier: 0.5, acceleration: 2400, deceleration: 3200, airControl: 0.3, jumpSpeed: 420,+ gravityScale: 1, coyoteTime: 0.1, jumpBuffer: 0.12,lookSensitivity: 0.12, touchSensitivity: 0.2, pitchMin: -85, pitchMax: 85,eyeHeight: 70, crouchEyeHeight: 28, crouchHalfHeight: 45, eyeSpeed: 400,camera: 0 as Entity, pointerLock: true, touchLook: true, touchLookFrom: 480, enabled: true,- yaw: 0, pitch: 0, crouching: false, standHalfHeight: 0, eye: -1, rebuild: 0,+ yaw: 0, pitch: 0, crouching: false, standHalfHeight: 0, eye: -1, rebuild: 0, airTime: 0, jumpHeld: 0, jumped: false,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['moveSpeed', 'acceleration', 'deceleration', 'jumpSpeed', 'eyeHeight', 'crouchEyeHeight', 'crouchHalfHeight', 'eyeSpeed'],entityFields: ['camera'],- readonlyFields: ['crouching', 'standHalfHeight', 'eye', 'rebuild'],+ readonlyFields: ['crouching', 'standHalfHeight', 'eye', 'rebuild', 'airTime', 'jumpHeld', 'jumped'],fields: {moveSpeed: { min: 0, category: 'Movement' },sprintMultiplier: { min: 1, step: 0.05, category: 'Movement' },@@ -91,6 +110,9 @@ export const FirstPersonController: ComponentDef<FirstPersonControllerData> = dedeceleration: { min: 0, category: 'Movement', advanced: true },airControl: { min: 0, max: 1, step: 0.05, category: 'Movement', advanced: true },jumpSpeed: { min: 0, category: 'Movement', tooltip: 'Upward speed a jump starts with. 0 = cannot jump.' },+ gravityScale: { min: 0, step: 0.05, category: 'Movement', tooltip: 'The player\'s gravity as a share of the world\'s. Above 1 falls faster and jumps feel snappier.' },+ coyoteTime: { min: 0, step: 0.01, unit: 's', category: 'Movement', advanced: true, tooltip: 'How long after walking off an edge a jump still works.' },+ jumpBuffer: { min: 0, step: 0.01, unit: 's', category: 'Movement', advanced: true, tooltip: 'How long a jump pressed just before landing is kept.' },lookSensitivity: { min: 0, step: 0.01, unit: '°/px', category: 'Look' },touchSensitivity: { min: 0, step: 0.01, unit: '°/px', category: 'Look' },pitchMin: { min: -90, max: 0, unit: '°', category: 'Look' },@@ -127,6 +149,8 @@ export interface FirstPersonViewModelData {export const FirstPersonViewModel: ComponentDef<FirstPersonViewModelData> = defineComponent<FirstPersonViewModelData>('FirstPersonViewModel', {layer: 20, fov: 60, nearPlane: 1, farPlane: 1000,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['nearPlane', 'farPlane'],fields: {layer: { min: 0, max: 31, category: 'View model', tooltip: 'The sorting layer the held thing is on: put it on its renderers, under this camera.' },fov: { min: 1, max: 170, unit: '°', category: 'View model', tooltip: 'The held thing\'s own field of view, so it does not stretch with a wide view of the world.' },diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.tsindex 8e69eee34..e9fcfe5a6 100644--- a/sdk/src/gameplay/GameplayPlugin.ts+++ b/sdk/src/gameplay/GameplayPlugin.ts@@ -18,7 +18,7 @@ import { playModeOnly } from '../ecs/env';import { Input, type InputState } from '../input/input';import { Transform, type TransformData } from '../ecs/component';import { CharacterController3D, type CharacterController3DData } from '../physics3d/Physics3DComponents';-import { Physics3D } from '../physics3d/Physics3DPlugin';+import { Physics3D, Physics3DRuntime } from '../physics3d/Physics3DPlugin';import type { Physics3DQueries } from '../physics3d/Physics3DQueries';import { Animator, AnimatorController, type AnimatorControllerAPI } from '../animation/Animator';import {@@ -342,7 +342,9 @@ export class GameplayPlugin implements Plugin {[Res(Time), Res(Input)],(time: TimeData, input: InputState) => {const queries = app.hasResource(Physics3D) ? app.getResource(Physics3D) : null;- moveFirstPerson(world, input, queries, time.fixedDelta);+ // The world's gravity in world units per second squared, for a player whose own differs from it.+ const config = app.hasResource(Physics3DRuntime) ? app.getResource(Physics3DRuntime).config : null;+ moveFirstPerson(world, input, queries, time.fixedDelta, config ? config.gravity.y * config.pixelsPerUnit : 0);},{ name: 'FirstPersonControllerSystem' },), { runIf: playModeOnly });diff --git a/sdk/src/gameplay/Hunter.ts b/sdk/src/gameplay/Hunter.tsindex c8c486067..4c69f16e2 100644--- a/sdk/src/gameplay/Hunter.ts+++ b/sdk/src/gameplay/Hunter.ts@@ -71,6 +71,8 @@ export const Hunter: ComponentDef<HunterData> = defineComponent<HunterData>('Hunstate: 'idle',cooldown: 0,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['attackRange', 'idleThreshold'],readonlyFields: ['state', 'cooldown'],fields: {attackRange: { min: 0, tooltip: 'How close it gets before it swings.' },diff --git a/sdk/src/gameplay/MeleeAttack.ts b/sdk/src/gameplay/MeleeAttack.tsindex 7ecfd3d20..6097720c7 100644--- a/sdk/src/gameplay/MeleeAttack.ts+++ b/sdk/src/gameplay/MeleeAttack.ts@@ -69,6 +69,8 @@ export const MeleeAttack: ComponentDef<MeleeAttackData> =attackId: 0,hitCount: 0,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['radius'],entityFields: ['anchor'],readonlyFields: ['attackId', 'hitCount'],fields: {diff --git a/sdk/src/gameplay/ThirdPersonCamera.ts b/sdk/src/gameplay/ThirdPersonCamera.tsindex 369759e1e..fbffe2c3d 100644--- a/sdk/src/gameplay/ThirdPersonCamera.ts+++ b/sdk/src/gameplay/ThirdPersonCamera.ts@@ -67,6 +67,8 @@ export const ThirdPersonCamera: ComponentDef<ThirdPersonCameraData> =obstructionLayers: 0,enabled: true,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['distance', 'targetOffset', 'obstructionRadius'],entityFields: ['target'],fields: {target: { tooltip: 'The transform this camera orbits.' },diff --git a/sdk/src/gameplay/ThirdPersonController.ts b/sdk/src/gameplay/ThirdPersonController.tsindex 16efcde4c..4430fad9f 100644--- a/sdk/src/gameplay/ThirdPersonController.ts+++ b/sdk/src/gameplay/ThirdPersonController.ts@@ -68,6 +68,8 @@ export const ThirdPersonController: ComponentDef<ThirdPersonControllerData> =idleThreshold: 8,enabled: true,}, {+ // World lengths and speeds: written at 100 units a metre, scaled to the project (ecs/worldUnits.ts).+ worldUnitFields: ['moveSpeed', 'acceleration', 'deceleration', 'jumpSpeed', 'idleThreshold'],entityFields: ['camera'],fields: {camera: { tooltip: 'Whose forward the stick is read against.' },diff --git a/sdk/src/gameplay/firstPersonSystems.ts b/sdk/src/gameplay/firstPersonSystems.tsindex aaebb6bce..190dc7a57 100644--- a/sdk/src/gameplay/firstPersonSystems.ts+++ b/sdk/src/gameplay/firstPersonSystems.ts@@ -101,7 +101,7 @@ export function look(world: World, input: InputState, dt: number, touch: TouchLo}/** Before the physics step: what the player asks of the character, and the height it asks to be. */-export function move(world: World, input: InputState, queries: Physics3DQueries | null, dt: number): void {+export function move(world: World, input: InputState, queries: Physics3DQueries | null, dt: number, gravity = 0): void {for (const entity of world.getEntitiesWithComponents([FirstPersonController, CharacterController3D])) {const data = world.get(entity, FirstPersonController) as FirstPersonControllerData;if (!data.enabled) continue;@@ -144,9 +144,29 @@ export function move(world: World, input: InputState, queries: Physics3DQueriesconst authority = character.isOnFloor ? 1 : Math.max(0, Math.min(1, data.airControl));const next = approachVelocity({ x: character.velocity.x, z: character.velocity.z }, { x: direction.x * speed, z: direction.z * speed },data.acceleration * authority, data.deceleration * authority, dt);- const jumping = data.jumpSpeed > 0 && character.isOnFloor && !data.crouching && input.isKeyDown('Space');+ // Coyote time and a jump buffer: a jump just after walking off an edge, or pressed just before landing, still+ // takes off. Holding the key on the floor jumps as it always did.+ const airTime = character.isOnFloor ? 0 : (data.airTime ?? 0) + dt;+ const pressed = input.isKeyPressed('Space');+ const jumpHeld = pressed ? (data.jumpBuffer ?? 0) : Math.max(0, (data.jumpHeld ?? 0) - dt);+ const grounded = character.isOnFloor || (!data.jumped && airTime <= (data.coyoteTime ?? 0));+ const wants = (character.isOnFloor && input.isKeyDown('Space')) || pressed || jumpHeld > 0;+ const jumping = data.jumpSpeed > 0 && grounded && !data.crouching && wants;+ // The player's own gravity: in the air at a scale other than 1, the vertical speed is carried here (the solver+ // takes a non-zero one as given), from what the character really moved at the last step.+ const scale = data.gravityScale ?? 1;+ let vy = jumping ? data.jumpSpeed : 0;+ if (!jumping && !character.isOnFloor && scale !== 1 && gravity !== 0) {+ vy = character.realVelocity.y + gravity * scale * dt;+ if (vy === 0) vy = gravity * scale * dt;+ }world.update(entity, CharacterController3D, (c: CharacterController3DData) => {- c.velocity.x = next.x; c.velocity.z = next.z; c.velocity.y = jumping ? data.jumpSpeed : 0;+ c.velocity.x = next.x; c.velocity.z = next.z; c.velocity.y = vy;+ });+ world.update(entity, FirstPersonController, (c: FirstPersonControllerData) => {+ c.airTime = airTime;+ c.jumpHeld = jumping ? 0 : jumpHeld;+ c.jumped = jumping ? true : character.isOnFloor ? false : c.jumped;});}}diff --git a/sdk/src/particle/ParticleAPI.ts b/sdk/src/particle/ParticleAPI.tsindex 1aa002379..1d9caa5f2 100644--- a/sdk/src/particle/ParticleAPI.ts+++ b/sdk/src/particle/ParticleAPI.ts@@ -63,6 +63,19 @@ export class ParticleAPI {this.module_.particle_reset?.(this.registry_, entity as number);}+ /**+ * Spawn `count` of `entity`'s particles at a world point, now — an impact's sparks, a muzzle's flash — without moving+ * the emitter or replaying it (Unity's `ParticleSystem.Emit`). The emitter's own settings make them; its shape's +Y (a+ * cone's or hemisphere's axis) points along `options.normal` when given, else as the entity is turned, and+ * `options.velocity` is added to each. CPU-simulated emitters only. Returns how many were spawned.+ */+ emitAt(entity: Entity, count: number, position: { x: number; y: number; z: number },+ options: { normal?: { x: number; y: number; z: number }; velocity?: { x: number; y: number; z: number } } = {}): number {+ const n = options.normal ?? { x: 0, y: 0, z: 0 }, v = options.velocity ?? { x: 0, y: 0, z: 0 };+ return this.module_.particle_emitAt?.(this.registry_, entity as number, Math.max(0, Math.floor(count)),+ position.x, position.y, position.z, n.x, n.y, n.z, v.x, v.y, v.z) ?? 0;+ }+getAliveCount(entity: Entity): number {return this.module_.particle_getAliveCount?.(entity as number) ?? 0;}diff --git a/sdk/src/physics3d/Physics3DComponents.ts b/sdk/src/physics3d/Physics3DComponents.tsindex cd34e81bb..3480699e3 100644--- a/sdk/src/physics3d/Physics3DComponents.ts+++ b/sdk/src/physics3d/Physics3DComponents.ts@@ -38,7 +38,8 @@ export const RigidBody3D = defineBuiltin<RigidBody3DData>('RigidBody3D', {});export const BoxCollider3D = defineBuiltin<BoxCollider3DData>('BoxCollider3D', {- halfExtents: { x: 0.5, y: 0.5, z: 0.5 },+ // World units at the reference 100 a metre (a 1 m box), scaled by the project's units per metre.+ halfExtents: { x: 50, y: 50, z: 50 },center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0.0,@@ -47,7 +48,7 @@ export const BoxCollider3D = defineBuiltin<BoxCollider3DData>('BoxCollider3D', {});export const SphereCollider3D = defineBuiltin<SphereCollider3DData>('SphereCollider3D', {- radius: 0.5,+ radius: 50,center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0.0,@@ -56,8 +57,8 @@ export const SphereCollider3D = defineBuiltin<SphereCollider3DData>('SphereColli});export const CapsuleCollider3D = defineBuiltin<CapsuleCollider3DData>('CapsuleCollider3D', {- radius: 0.3,- halfHeight: 0.5,+ radius: 30,+ halfHeight: 50,center: { x: 0, y: 0, z: 0 },friction: 0.3,restitution: 0.0,@@ -104,12 +105,13 @@ export const ConvexCollider3D = defineBuiltin<ConvexCollider3DData>('ConvexColliexport const CharacterController3D = defineBuiltin<CharacterController3DData>('CharacterController3D', {velocity: { x: 0, y: 0, z: 0 },- radius: 0.3,- halfHeight: 0.5,+ // World units at the reference 100 a metre (a 1.6 m person), scaled by the project's units per metre.+ radius: 30,+ halfHeight: 50,maxSlope: 0.87,layer: 0,- stepHeight: 0.4,- snapDown: 0.5,+ stepHeight: 40,+ snapDown: 50,mass: 70,pushForce: 5000,enabled: true,diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 2fc151bc5..8692d7a1c 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -62,6 +62,7 @@ import type { AddressableManifest, ManifestModel } from '../asset/AddressableManimport type { Catalog } from '../asset/Catalog';import { physics3dModuleId, type Physics3DBackend } from '../sideModules/registry';import { physics3DInstallConfig, type Physics3DWorldConfig } from '../physics3d/worldConfig';+import { setWorldUnitsPerMeter, REFERENCE_UNITS_PER_METER } from '../ecs/worldUnits';// =============================================================================// Public Interface@@ -830,6 +831,9 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {flushPendingRegistrations(app);+ // Before any scene: what a component's default fills in is in the project's units (ecs/worldUnits.ts).+ setWorldUnitsPerMeter(config.physics3dWorld?.unitsPerMeter ?? REFERENCE_UNITS_PER_METER);+// First: the asset timeouts and cache budgets are read by the very first load below.if (config.runtime) applyBuildRuntimeConfig(app, config.runtime);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 127d9d2da..868dc0149 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -638,6 +638,8 @@ export interface ESEngineModule {particle_collisionResolve?(registry: CppRegistry, ptr: number, count: number): void;particle_collisionSetBudget?(queries: number, events: number, debug: boolean): void;particle_play?(registry: CppRegistry, entity: number): void;+ particle_emitAt?(registry: CppRegistry, entity: number, count: number, px: number, py: number, pz: number,+ nx: number, ny: number, nz: number, vx: number, vy: number, vz: number): number;particle_stop?(registry: CppRegistry, entity: number): void;particle_reset?(registry: CppRegistry, entity: number): void;particle_getAliveCount?(entity: number): number;diff --git a/sdk/tests/first-person.test.ts b/sdk/tests/first-person.test.tsindex 67cbcd3c4..832d21636 100644--- a/sdk/tests/first-person.test.ts+++ b/sdk/tests/first-person.test.ts@@ -70,10 +70,12 @@ describe('crouching', () => {});/** An input that holds the keys it is told to, and a pointer that has moved by what it is told. */-function fakeInput(keys: string[] = [], mouse = { x: 0, y: 0 }) {+function fakeInput(keys: string[] = [], mouse = { x: 0, y: 0 }, pressedKeys: string[] = []) {const down = new Set(keys);+ const pressed = new Set(pressedKeys);return {isKeyDown: (k: string) => down.has(k),+ isKeyPressed: (k: string) => pressed.has(k),isMouseButtonDown: (b: number) => b === 0,isMouseButtonPressed: () => false,getMouseDelta: () => mouse,@@ -164,6 +166,45 @@ describe.skipIf(!HAS_WASM)('a first-person player in the engine world', () => {expect((world.get(body, FirstPersonController) as FirstPersonControllerData).crouching).toBe(true);});+ // The original's feel (Saltline: coyote 0.12 s, buffer 0.13 s, a player falling at 21 m/s² in a 9.81 world).+ const airborne = (body: number, over: Partial<FirstPersonControllerData>) => {+ world.update(body, CharacterController3D, (c: { isOnFloor: boolean; realVelocity: { x: number; y: number; z: number } }) => { c.isOnFloor = false; c.realVelocity = { x: 0, y: 0, z: 0 }; });+ world.update(body, FirstPersonController, (c: FirstPersonControllerData) => Object.assign(c, over));+ };+ const vy = (body: number) => (world.get(body, CharacterController3D) as { velocity: { y: number } }).velocity.y;++ it('still jumps just after walking off an edge, and not once the coyote time is gone', () => {+ const { body } = player({ coyoteTime: 0.1 });+ airborne(body, { airTime: 0.05, jumped: false });+ move(world, fakeInput(['Space'], undefined, ['Space']), null, 1 / 60);+ expect(vy(body)).toBe(420);+ airborne(body, { airTime: 0.3, jumped: false, jumpHeld: 0 });+ move(world, fakeInput(['Space'], undefined, ['Space']), null, 1 / 60);+ expect(vy(body)).toBe(0);+ });++ it('keeps a jump pressed just before landing and takes off as it lands', () => {+ const { body } = player({ jumpBuffer: 0.12 });+ airborne(body, { airTime: 1, jumped: true });+ move(world, fakeInput([], undefined, ['Space']), null, 1 / 60);+ expect(vy(body)).toBe(0);+ world.update(body, CharacterController3D, (c: { isOnFloor: boolean }) => { c.isOnFloor = true; });+ move(world, fakeInput(), null, 1 / 60);+ expect(vy(body)).toBe(420);+ });++ it("falls by its own gravity when it has one: twice the world's, from what it really moved at", () => {+ const { body } = player({ gravityScale: 2 });+ airborne(body, { airTime: 0.5, jumped: true });+ world.update(body, CharacterController3D, (c: { realVelocity: { y: number } }) => { c.realVelocity.y = -100; });+ move(world, fakeInput(), null, 0.5, -981);+ expect(vy(body)).toBeCloseTo(-100 - 981 * 2 * 0.5);+ const { body: plain } = player();+ airborne(plain, { airTime: 0.5, jumped: true });+ move(world, fakeInput(), null, 0.5, -981);+ expect(vy(plain)).toBe(0); // scale 1: the solver carries the fall, as it always did+ });+it('draws what is held by a second camera over the world\'s, and keeps the world\'s from drawing it', () => {const systems: Array<{ _fn: () => void }> = [];installViewModels({ world, addSystemToSchedule: (_s: unknown, def: { _fn: () => void }) => { systems.push(def); } } as never);diff --git a/sdk/tests/particle-emit-at-wasm.test.ts b/sdk/tests/particle-emit-at-wasm.test.tsnew file mode 100644index 000000000..a65790199--- /dev/null+++ b/sdk/tests/particle-emit-at-wasm.test.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Particle.emitAt through the real core: a burst where something happened, now, from an emitter that is neither+ * moved nor replayed — Saltline's bullet impacts were a pool of emitters dragged to each hit and restarted.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { Transform, ParticleEmitter } from '../src/ecs/component';+import { Particle, ParticlePlugin } from '../src/particle';+import { ParticleCollisionEvent, type ParticleCollisionEventPayload } from '../src/particle/collision';+import { EventReader, type EventReaderInstance } from '../src/ecs/event';+import { defineSystem, Schedule } from '../src/ecs/system';+import { Physics3DPlugin, Physics3DRuntime } from '../src/physics3d/Physics3DPlugin';+import { RigidBody3D, BoxCollider3D } from '../src/physics3d/Physics3DComponents';+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++let engine: ESEngineModule;+const apps: App[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });++describe.skipIf(!HAS_WASM)('Particle.emitAt through the core', () => {+ beforeAll(async () => { engine = await loadWasmModule(); });++ const quiet = { rate: 0, burstCount: 0, playOnStart: false, looping: false, lifetimeMin: 5, lifetimeMax: 5, speedMin: 0, speedMax: 0, gravity: { x: 0, y: 0, z: 0 } };++ it('spawns what it is asked for at once, from an emitter that never plays, and no more than its pool', async () => {+ const app = App.new(); apps.push(app);+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });+ app.addPlugin(new ParticlePlugin());+ const e = app.world.spawn();+ app.world.insert(e, Transform, {});+ app.world.insert(e, ParticleEmitter, { ...quiet, maxParticles: 10 });+ await app.stepFrames(2, 1 / 60);+ const particle = app.getResource(Particle);+ expect(particle.getAliveCount(e)).toBe(0);+ expect(particle.emitAt(e, 6, { x: 3, y: 0, z: 0 })).toBe(6);+ await app.stepFrames(1, 1 / 60);+ expect(particle.getAliveCount(e)).toBe(6);+ expect(particle.emitAt(e, 6, { x: -3, y: 0, z: 0 })).toBe(4); // the pool holds 10+ await app.stepFrames(30, 1 / 60);+ expect(particle.getAliveCount(e)).toBe(10); // they live their lifetime+ });++ // Where they start, read off where they hit: the emitter stands at the origin with no speed of its own, so a particle+ // that reaches a wall at x 100 started where emitAt put it and moved as emitAt aimed it.+ it.skipIf(!hasSideModule('physics3d'))('starts them at the point, aimed along the normal and carried by the velocity', async () => {+ const app = App.new(); apps.push(app);+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });+ const module = await loadSideModule<Physics3DWasmModule>('physics3d');+ app.addPlugin(new Physics3DPlugin('', { gravity: { x: 0, y: 0, z: 0 } }, async () => module));+ await app.getResource(Physics3DRuntime).initPromise;+ app.addPlugin(new ParticlePlugin());+ const world = app.world;+ const wall = world.spawn();+ world.insert(wall, Transform, { position: { x: 100, y: 0, z: 0 } });+ world.insert(wall, RigidBody3D, { bodyType: 0 });+ world.insert(wall, BoxCollider3D, { halfExtents: { x: 5, y: 200, z: 200 } });+ const received: ParticleCollisionEventPayload[] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([EventReader(ParticleCollisionEvent)],+ (reader: EventReaderInstance<ParticleCollisionEventPayload>) => { for (const hit of reader) received.push(hit); }, { name: 'ReadHits' }));+ const e = world.spawn();+ world.insert(e, Transform, {});+ // A cone of no width along its own +Y, 3000 units/s: emitAt turns that +Y onto the normal (+X here).+ world.insert(e, ParticleEmitter, { ...quiet, shape: 3, shapeAngle: 0, shapeRadius: 0, speedMin: 3000, speedMax: 3000, maxParticles: 4,+ collisionEnabled: true, collisionMode: 2, collisionFallback: 1, collisionEvents: true, collisionMask: 65535 });+ await app.stepFrames(2, 1 / 60);+ app.getResource(Particle).emitAt(e, 1, { x: 60, y: 7, z: 0 }, { normal: { x: 1, y: 0, z: 0 } });+ await app.stepFrames(3, 1 / 60);+ const hit = received.find((h) => h.emitter === e);+ expect(hit).toBeDefined();+ expect(hit!.body).toBe(wall);+ expect(hit!.x).toBeCloseTo(95, 1); // the wall's near face+ expect(hit!.y).toBeCloseTo(7, 1); // the height it was emitted at+ expect(hit!.velocityX).toBeCloseTo(3000, 0);+ });+});diff --git a/sdk/tests/voxel-terrain-wasm.test.ts b/sdk/tests/voxel-terrain-wasm.test.tsindex e0cd4dd30..cc9362a4f 100644--- a/sdk/tests/voxel-terrain-wasm.test.ts+++ b/sdk/tests/voxel-terrain-wasm.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeAll, describe, expect, it } from 'vitest';import { App } from '../src/app/app';import { MeshRenderer, Parent, RuntimeOnly, Transform, type TransformData } from '../src/ecs/component';import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { setWorldUnitsPerMeter, REFERENCE_UNITS_PER_METER } from '../src/ecs/worldUnits';import { Assets } from '../src/asset/AssetPlugin';import type { Assets as AssetsApi } from '../src/asset/Assets';import type { MeshData } from '../src/asset/meshFormat';@@ -30,6 +31,7 @@ const apps: App[] = [];afterEach(() => {while (apps.length) apps.pop()!.quit?.();setEditorMode(false); setPlayMode(false);+ setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER);});interface Scene {@@ -45,6 +47,8 @@ async function scene(options: { physics?: boolean; solver?: string; fields?: RecsetPlayMode(true);if (options.physics !== false) {const module = await loadSideModule<Physics3DWasmModule>(options.solver ?? 'physics3d');+ // A metre world, as a project with world3d.unitsPerMeter 1 is: its defaults (a character's capsule) are in metres too.+ setWorldUnitsPerMeter(1);app.addPlugin(new Physics3DPlugin('', { fixedTimestep: 1 / 60, pixelsPerUnit: 1 }, async () => module));await app.getResource(Physics3DRuntime).initPromise;}diff --git a/sdk/tests/world-units.test.ts b/sdk/tests/world-units.test.tsnew file mode 100644index 000000000..2fea080e0--- /dev/null+++ b/sdk/tests/world-units.test.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Defaults follow the project's units: a length a default fills in is written at 100 units a metre and scaled by+ * the project's own, so a character is a 1.6 m person in a centimetre project and in a metre one alike.+ */+import { describe, it, expect, afterEach } from 'vitest';+import { setWorldUnitsPerMeter, worldUnitScale, REFERENCE_UNITS_PER_METER } from '../src/ecs/worldUnits';+import { defineComponent } from '../src/ecs/component';+import { CharacterController3D, BoxCollider3D } from '../src/physics3d/Physics3DComponents';+import { FirstPersonController, FirstPersonViewModel } from '../src/gameplay/FirstPersonController';+import { NavVolume } from '../src/ai/nav/NavVolume';+import { getComponent } from '../src/ecs/component';++afterEach(() => setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER));++describe('world-unit defaults', () => {+ it('are the defaults as written at the reference 100 units a metre — the same object', () => {+ expect(worldUnitScale()).toBe(1);+ const raw = FirstPersonController._default;+ expect(raw.moveSpeed).toBe(320);+ expect(FirstPersonController._default).toBe(raw);+ expect(CharacterController3D._default.radius).toBe(30);+ });++ it('in a metre project are metres: a 1.6 m character, a 3.2 m/s walk, a near plane of a centimetre', () => {+ setWorldUnitsPerMeter(1);+ const cc = CharacterController3D._default;+ expect(cc.radius).toBeCloseTo(0.3);+ expect(cc.halfHeight).toBeCloseTo(0.5);+ expect(FirstPersonController.create().moveSpeed).toBeCloseTo(3.2);+ expect(FirstPersonViewModel.create().nearPlane).toBeCloseTo(0.01);+ expect(BoxCollider3D._default.halfExtents).toEqual({ x: 0.5, y: 0.5, z: 0.5 });+ expect(NavVolume.create().cellSize).toBeCloseTo(0.5);+ });++ it('never touch a value the scene states, nor a field that is not a length', () => {+ setWorldUnitsPerMeter(1);+ const fp = FirstPersonController.create({ moveSpeed: 5 });+ expect(fp.moveSpeed).toBe(5);+ expect(fp.sprintMultiplier).toBe(1.6);+ expect(fp.pitchMax).toBe(85);+ expect(CharacterController3D._default.maxSlope).toBe(0.87);+ });++ it('reach the generated builtins too (particles)', () => {+ setWorldUnitsPerMeter(1);+ const emitter = getComponent('ParticleEmitter')!._default as { speedMin: number; startSizeMin: number; rate: number };+ expect(emitter.speedMin).toBeCloseTo(5);+ expect(emitter.startSizeMin).toBeCloseTo(1);+ expect(emitter.rate).toBe(10);+ });++ it('refuses a world-unit field that names no field', () => {+ expect(() => defineComponent('WorldUnitTypo', { speed: 1 }, { worldUnitFields: ['sped'] })).toThrow(/sped/);+ });+});diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex a25fb4612..c25b4272d 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -952,6 +952,13 @@ void particle_reset(ecs::Registry& registry, u32 entity) {g_particleSystem->reset(Entity::fromRaw(entity));}+u32 particle_emitAt(ecs::Registry& registry, u32 entity, u32 count, f32 px, f32 py, f32 pz,+ f32 nx, f32 ny, f32 nz, f32 vx, f32 vy, f32 vz) {+ if (!g_particleSystem) return 0;+ return g_particleSystem->emitAt(registry, Entity::fromRaw(entity), count, glm::vec3(px, py, pz),+ glm::vec3(nx, ny, nz), glm::vec3(vx, vy, vz));+}+u32 particle_getAliveCount(u32 entity) {if (!g_particleSystem) return 0;return g_particleSystem->aliveCount(Entity::fromRaw(entity));diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex e6a1ce451..544e57fd0 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -209,6 +209,10 @@ void particle_collisionSetBudget(u32 queries, u32 events, bool debug);void particle_play(ecs::Registry& registry, u32 entity);void particle_stop(ecs::Registry& registry, u32 entity);void particle_reset(ecs::Registry& registry, u32 entity);+/// Spawn @p count of an emitter's particles at a world point now (normal: the shape's +Y, zero = the entity's own turn).+/// Returns how many were spawned.+u32 particle_emitAt(ecs::Registry& registry, u32 entity, u32 count, f32 px, f32 py, f32 pz,+ f32 nx, f32 ny, f32 nz, f32 vx, f32 vy, f32 vz);u32 particle_getAliveCount(u32 entity);void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count);void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 23f00ec19..a028409f4 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -749,6 +749,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("particle_play", &esengine::particle_play);emscripten::function("particle_stop", &esengine::particle_stop);emscripten::function("particle_reset", &esengine::particle_reset);+ emscripten::function("particle_emitAt", &esengine::particle_emitAt);emscripten::function("particle_getAliveCount", &esengine::particle_getAliveCount);emscripten::function("particle_set_color_lut", &esengine::particle_set_color_lut);emscripten::function("particle_set_size_lut", &esengine::particle_set_size_lut);diff --git a/src/esengine/ecs/components/RigidBody3D.hpp b/src/esengine/ecs/components/RigidBody3D.hppindex c6a40ee4d..ac1841f1a 100644--- a/src/esengine/ecs/components/RigidBody3D.hpp+++ b/src/esengine/ecs/components/RigidBody3D.hpp@@ -74,8 +74,9 @@ struct RigidBody3D {/** @brief An axis-aligned box, sized in world units around the entity's origin. */ES_COMPONENT()struct BoxCollider3D {+ // World units at the reference 100 a metre, scaled by the project's units per metre (sdk ecs/worldUnits.ts).ES_PROPERTY()- glm::vec3 halfExtents{0.5f, 0.5f, 0.5f};+ glm::vec3 halfExtents{50.0f, 50.0f, 50.0f};/** @brief Where the shape sits from the entity's origin, in world units; zero is centred on it. */ES_PROPERTY(optional)@@ -98,7 +99,7 @@ struct BoxCollider3D {ES_COMPONENT()struct SphereCollider3D {ES_PROPERTY(min=0)- f32 radius{0.5f};+ f32 radius{50.0f};/** @brief Where the shape sits from the entity's origin, in world units; zero is centred on it. */ES_PROPERTY(optional)@@ -127,10 +128,10 @@ struct SphereCollider3D {ES_COMPONENT()struct CapsuleCollider3D {ES_PROPERTY(min=0)- f32 radius{0.3f};+ f32 radius{30.0f};ES_PROPERTY(min=0)- f32 halfHeight{0.5f};+ f32 halfHeight{50.0f};/** @brief Where the shape sits from the entity's origin, in world units; zero is centred on it. */ES_PROPERTY(optional)@@ -218,12 +219,15 @@ struct CharacterController3D {ES_PROPERTY()glm::vec3 velocity{0.0f, 0.0f, 0.0f};+ /** @brief World units, as every length here: these defaults are a 1.6 m person at the reference scale of 100 units+ * a metre, and scale with the project's units per metre (sdk ecs/worldUnits.ts). They read 0.3 / 0.5 before —+ * metres, under a solver that reads centimetres by default, which made a 3 mm character. */ES_PROPERTY(min=0)- f32 radius{0.3f};+ f32 radius{30.0f};/** @brief Half the cylinder; total height is `2*(halfHeight + radius)`. */ES_PROPERTY(min=0)- f32 halfHeight{0.5f};+ f32 halfHeight{50.0f};/** @brief Steepest ground it can stand on. Beyond this it slides. */ES_PROPERTY(min=0, max=1.5708, unit="rad")@@ -231,11 +235,11 @@ struct CharacterController3D {/** @brief Tallest step it climbs instead of stopping at. 0 = climbs nothing. */ES_PROPERTY(min=0, advanced)- f32 stepHeight{0.4f};+ f32 stepHeight{40.0f};/** @brief How far it reaches down to stay on the floor over a crest. 0 = off. */ES_PROPERTY(min=0, advanced)- f32 snapDown{0.5f};+ f32 snapDown{50.0f};/** @brief Mass used when it pushes dynamic bodies. */ES_PROPERTY(min=0, advanced)diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cppindex f0a39cc0b..7f940aedd 100644--- a/src/esengine/particle/ParticleSystem.cpp+++ b/src/esengine/particle/ParticleSystem.cpp@@ -522,6 +522,45 @@ void ParticleSystem::emitInto(const ecs::ParticleEmitter& emitter, EmitterState&}}+u32 ParticleSystem::emitAt(ecs::Registry& registry, Entity entity, u32 count, const glm::vec3& position,+ const glm::vec3& normal, const glm::vec3& velocity) {+ if (count == 0 || !registry.valid(entity) || !registry.has<ecs::ParticleEmitter>(entity)) return 0;+ const auto& emitter = registry.get<ecs::ParticleEmitter>(entity);+ if (emitter.gpuSimulation && gpu_available_) return 0;+ auto it = states_.find(entity);+ if (it == states_.end()) {+ it = states_.emplace(entity, EmitterState(static_cast<u32>(std::clamp(emitter.maxParticles, 0, 1'000'000)))).first;+ }+ EmitterState& state = it->second;+ if (state.gpu) return 0;++ glm::quat rotation(1.0f, 0.0f, 0.0f, 0.0f);+ glm::vec3 scale(1.0f);+ EmitterFrame storage;+ if (registry.has<ecs::Transform>(entity)) {+ const auto& t = registry.get<ecs::Transform>(entity);+ rotation = t.worldRotation;+ scale = t.worldScale;+ storage = {t.worldPosition, t.worldRotation, t.worldScale};+ }+ const f32 n = glm::length(normal);+ if (n > 1e-6f) {+ // The shortest turn from +Y onto the normal; straight down is a half turn about X.+ const glm::vec3 to = normal / n;+ const f32 d = glm::dot(glm::vec3(0.0f, 1.0f, 0.0f), to);+ if (d < -0.9999f) rotation = glm::quat(0.0f, 1.0f, 0.0f, 0.0f);+ else {+ const glm::vec3 axis = glm::cross(glm::vec3(0.0f, 1.0f, 0.0f), to);+ rotation = glm::normalize(glm::quat(1.0f + d, axis.x, axis.y, axis.z));+ }+ }+ const bool local = emitter.simulationSpace == static_cast<i32>(ecs::SimulationSpace::Local);+ const u32 before = state.pool.aliveCount();+ emitInto(emitter, state, EmitterFrame{position, rotation, scale}, /*isWorldSpace=*/true, velocity, count,+ /*allowBirthTrigger=*/true, 0, local ? &storage : nullptr);+ return state.pool.aliveCount() - before;+}+void ParticleSystem::drainSubEmitters(ecs::Registry& registry, Entity parent, Entity child,f32 inheritVelocity, f32 chance) {// Take ownership of the queue up front: emitInto below spawns into the childdiff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hppindex e02c5c3db..5f4027792 100644--- a/src/esengine/particle/ParticleSystem.hpp+++ b/src/esengine/particle/ParticleSystem.hpp@@ -183,6 +183,18 @@ public:void reset(Entity entity);u32 aliveCount(Entity entity) const;++ /**+ * @brief Spawn @p count of @p entity's particles at a world point, now: an impact's sparks, a muzzle's flash, without+ * moving the emitter or replaying it.+ * @details The emitter's own settings make them (shape, speed, size, colour, life). Its shape stands at @p position,+ * turned so its local +Y — a cone's or a hemisphere's axis — points along @p normal when one is given, and+ * as the entity is turned otherwise; @p velocity is added to every particle. A Local-space emitter keeps them+ * in its own frame, as a sub-emitter's burst is kept. CPU-simulated emitters only: a GPU one answers 0.+ * @return How many were spawned (fewer than asked when the pool or the particle budget is full).+ */+ u32 emitAt(ecs::Registry& registry, Entity entity, u32 count, const glm::vec3& position,+ const glm::vec3& normal, const glm::vec3& velocity);u32 totalAliveParticles() const;void setParticleLimit(u32 limit) { particle_limit_ = limit; }diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjsindex b3bdcd262..d59636d8f 100644--- a/tools/check-project-settings.mjs+++ b/tools/check-project-settings.mjs@@ -87,9 +87,6 @@ const DECLARED_GAPS = {physicsConfig: {editor: 'edit mode does not simulate — see physicsEnabled',},- physics3dWorld: {- editor: 'edit mode does not simulate — see physicsEnabled',- },colorSpace: {editor: 'boot-fixed — shaders compile against it, so the settings page asks '+ 'for a reload rather than applying live (EngineHost.resolveColorSpace)',