Skip to content

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

feat(physics): two 3D bodies can be held to each other

esenginef884a89986dc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bbd8c043b..63dd7ef72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,22 @@ published separately; it ships inside the editor.
### Added
+- **Joints for the 3D world.** `PointJoint3D`, `HingeJoint3D`, `SliderJoint3D`,
+ `DistanceJoint3D` and `FixedJoint3D` — a shared point, an axis to turn about,
+ an axis to slide along, a distance to keep, and no freedom at all. A door, a
+ rope bridge, a lift and a ragdoll are all two bodies and a rule, and until now
+ the 3D world could only say "these two touch".
+
+ Anchors and axes are written in the declaring entity's local space and resolved
+ when the joint is made, which also sets the ZERO of every limit: a door placed
+ closed reads `angle` 0. `motorSpeed` can be changed from gameplay at any time,
+ and `angle` / `translation` come back each step.
+
+ `collideConnected` joins the two bodies into one assembly rather than one pair,
+ so everything a chain of joints reaches stops colliding with the rest of that
+ chain — what a door needs against its own frame, and what a ragdoll needs
+ against itself.
+
- **3D colliders are visible while you author them.** The viewport draws a
wireframe of every 3D collider — box, sphere, capsule, character, and the bounds
of a mesh collider — turned the way its entity is. A 3D shape is nothing the
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 332715d40..344a87b7c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -447,6 +447,7 @@ if(ES_BUILD_WEB OR ES_BUILD_WXGAME)
if(ES_ENABLE_JOLT)
set(ES_PHYSICS3D_SOURCES
src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+ src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp
)
if(ES_PHYSICS_ESM)
add_executable(physics3d_module_esm ${ES_PHYSICS3D_SOURCES})
diff --git a/desktop/scripts/editor-checks/physics3d-joint.mjs b/desktop/scripts/editor-checks/physics3d-joint.mjs
new file mode 100644
index 000000000..716579cae
--- /dev/null
+++ b/desktop/scripts/editor-checks/physics3d-joint.mjs
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file physics3d-joint — a joint authored in a scene holds in the running game.
+ *
+ * The module's own checks prove the solver builds constraints and the unit tests
+ * prove the wiring converts units. Neither answers whether a joint SURVIVES the
+ * trip: the joint components are TypeScript ones, so a scene has to carry them
+ * through load, entity-reference remapping and the plugin's per-step sync before
+ * anything holds. Everything else could be right and a door would still fall off.
+ */
+import { makeProject, checker } from '../lib/editorDriver.mjs';
+
+/** A static anchor and a bob hung 150 units to its right by a hinge. */
+const SCENE = JSON.stringify({
+ version: '1.0', name: 'Main',
+ entities: [
+ {
+ id: 0, name: 'Camera', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
+ ],
+ },
+ {
+ id: 1, name: 'Anchor', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 200, z: 0 } } },
+ { type: 'RigidBody3D', data: { bodyType: 0 } },
+ { type: 'BoxCollider3D', data: { halfExtents: { x: 20, y: 20, z: 20 } } },
+ ],
+ },
+ {
+ id: 2, name: 'Bob', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 150, y: 200, z: 0 } } },
+ { type: 'RigidBody3D', data: { bodyType: 2, linearDamping: 0.4, angularDamping: 0.4 } },
+ { type: 'BoxCollider3D', data: { halfExtents: { x: 20, y: 20, z: 20 } } },
+ {
+ type: 'HingeJoint3D',
+ data: {
+ connectedEntity: 1,
+ anchor: { x: -150, y: 0, z: 0 }, // the anchor's position, in Bob's frame
+ axis: { x: 0, y: 0, z: 1 },
+ },
+ },
+ ],
+ },
+ ],
+}, null, 1);
+
+export const name = 'physics3d-joint';
+export const describes = 'a 3D joint authored in a scene holds two bodies together when it runs';
+
+export async function run(ed) {
+ const root = await makeProject({
+ 'project.esproject': JSON.stringify({ name: 'Joint3D', version: '1.0' }, null, 2),
+ 'assets/scenes/main.esscene': SCENE,
+ });
+ const check = checker();
+
+ await ed.open(root, 'assets/scenes/main.esscene');
+ await ed.call('set_play', { state: 'playing' }, 120000);
+
+ let ready = false;
+ for (let i = 0; i < 40 && !ready; i++) {
+ ready = (await ed.json('get_play_state', {}))?.ready === true;
+ if (!ready) await ed.sleep(500);
+ }
+ if (!check(ready, 'the play realm never reported ready')) return check.failures;
+
+ const bob = async () => (await ed.json('play_probe', {
+ code: 'const e = find("HingeJoint3D")[0];'
+ + ' if (!e) return null;'
+ + ' const t = get(e.entity, "Transform");'
+ + ' const j = get(e.entity, "HingeJoint3D");'
+ + ' return { x: t.position.x, y: t.position.y, z: t.position.z, angle: j.angle };',
+ }, 60000));
+
+ const start = await bob();
+ if (!check(start != null, 'the running world has no HingeJoint3D')) return check.failures;
+
+ // Three seconds: far past the swing, and far past the two metres a free body
+ // falls in that time.
+ await ed.sleep(3000);
+ const now = await bob();
+ if (!check(now != null, 'the jointed entity went missing while it ran')) return check.failures;
+
+ const reach = Math.hypot(now.x - 0, now.y - 200, now.z - 0);
+ check(
+ Math.abs(reach - 150) < 20,
+ `the bob is ${reach.toFixed(1)} units from the anchor rather than 150 — the joint is not `
+ + 'holding it (a body in free fall keeps going)',
+ );
+ check(now.y < 150, `the bob never swung down (y=${now.y.toFixed(1)} of 200)`);
+ // The hinge reports where it is, which is the readback half of the same wiring.
+ check(
+ Math.abs(now.angle) > 0.5,
+ `the hinge reports an angle of ${now.angle.toFixed(3)} after swinging a quarter turn`,
+ );
+
+ return check.failures;
+}
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 85445dc9f..13abc8904 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -24,13 +24,16 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
CircleCollider: 'reference/components/physics/#circlecollider',
Disabled: 'reference/components/core/#disabled',
DistanceJoint: 'reference/components/physics/#distancejoint',
+ DistanceJoint3D: 'reference/components/physics/#distancejoint3d',
DragState: 'reference/components/ui/#dragstate',
Draggable: 'reference/components/ui/#draggable',
DragonBonesAnimation: 'reference/components/animation/#dragonbonesanimation',
EventBinding: 'reference/components/gameplay/#eventbinding',
+ FixedJoint3D: 'reference/components/physics/#fixedjoint3d',
FlexContainer: 'reference/components/ui/#flexcontainer',
Focusable: 'reference/components/ui/#focusable',
FollowTarget: 'reference/components/graphics/#followtarget',
+ HingeJoint3D: 'reference/components/physics/#hingejoint3d',
Interactable: 'reference/components/ui/#interactable',
Light2D: 'reference/components/graphics/#light2d',
Marker: 'reference/components/world/#marker',
@@ -48,6 +51,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
Perceiver: 'reference/components/gameplay/#perceiver',
Perception: 'reference/components/gameplay/#perception',
PerceptionTarget: 'reference/components/gameplay/#perceptiontarget',
+ PointJoint3D: 'reference/components/physics/#pointjoint3d',
PolygonCollider: 'reference/components/physics/#polygoncollider',
PostProcessVolume: 'reference/components/graphics/#postprocessvolume',
PrismaticJoint: 'reference/components/physics/#prismaticjoint',
@@ -61,6 +65,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
SegmentCollider: 'reference/components/physics/#segmentcollider',
ShadowCaster2D: 'reference/components/graphics/#shadowcaster2d',
ShapeRenderer: 'reference/components/graphics/#shaperenderer',
+ SliderJoint3D: 'reference/components/physics/#sliderjoint3d',
SphereCollider3D: 'reference/components/physics/#spherecollider3d',
SpineAnimation: 'reference/components/animation/#spineanimation',
Sprite: 'reference/components/graphics/#sprite',
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 2909f23e6..cc5df6102 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -114,6 +114,55 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
leaving every caller to rediscover it.
</Aside>
+## Joints
+
+A door, a rope bridge, a lift, a ragdoll: none of them are one body and a shape.
+They are two bodies and a rule about how they may move relative to each other. A
+joint lives on the entity that declares it and names the other one.
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
+ .insert(RigidBody3D, {})
+ .insert(BoxCollider3D, { halfExtents: { x: 50, y: 100, z: 5 } })
+ .insert(HingeJoint3D, {
+ connectedEntity: frame,
+ anchor: { x: -50, y: 0, z: 0 }, // the door's own edge
+ axis: { x: 0, y: 1, z: 0 }, // upright
+ enableLimit: true, lowerAngle: 0, upperAngle: Math.PI / 2,
+ });
+```
+
+| Component | Rule |
+|---|---|
+| `PointJoint3D` | A shared point, free to turn on all three axes. |
+| `HingeJoint3D` | One axis of rotation, with optional limits and a motor. |
+| `SliderJoint3D` | One axis of travel, with optional limits and a motor. |
+| `DistanceJoint3D` | A distance kept: a rope with `maxLength`, a rod when the lengths meet, a spring with `frequency`. |
+| `FixedJoint3D` | No freedom at all — the two move as one. |
+
+`anchor` and `axis` are written in the declaring entity's own local space, in
+world units, and are resolved against its transform when the joint is made. That
+pose is also the **zero** of every limit: a door placed closed has `angle` 0 and
+opens to `upperAngle`.
+
+Set `motorSpeed` from gameplay at any time — the world is re-driven when it
+changes. In the other direction, `HingeJoint3D.angle` and
+`SliderJoint3D.translation` are written back each step, so a game can ask how far
+the door swung without integrating the swing a second time.
+
+<Aside>
+ `collideConnected` is false by default, and it joins the two bodies into ONE
+ assembly rather than one pair: everything a chain of joints reaches stops
+ colliding with the rest of that chain. That is what a door needs (it must not
+ fight its own frame) and what a ragdoll needs. Turn it on when the two really
+ should meet.
+
+ One joint per entity — the world keys a constraint by the entity that declared
+ it. An entity that needs two joints carries a child for the second, which is
+ also how a scene says which is which.
+</Aside>
+
## Asking the world what is where
The `Physics3D` resource answers spatial questions in world units.
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
index d2e8c5830..3f10fec4a 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
@@ -103,6 +103,50 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
而不是让每个调用者各自重新发现这件事。
</Aside>
+## 关节
+
+门、绳桥、升降台、布娃娃:它们都不是「一个刚体加一个形状」,
+而是**两个刚体**外加一条「它们之间可以怎么动」的规则。
+关节挂在声明它的那个实体上,并指名另一个实体。
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
+ .insert(RigidBody3D, {})
+ .insert(BoxCollider3D, { halfExtents: { x: 50, y: 100, z: 5 } })
+ .insert(HingeJoint3D, {
+ connectedEntity: frame,
+ anchor: { x: -50, y: 0, z: 0 }, // 门自己的那条边
+ axis: { x: 0, y: 1, z: 0 }, // 竖直
+ enableLimit: true, lowerAngle: 0, upperAngle: Math.PI / 2,
+ });
+```
+
+| 组件 | 规则 |
+|---|---|
+| `PointJoint3D` | 共享一个点,三轴自由转动。 |
+| `HingeJoint3D` | 一根转轴,可选限位与马达。 |
+| `SliderJoint3D` | 一条滑轨,可选限位与马达。 |
+| `DistanceJoint3D` | 保持一段距离:只给 `maxLength` 就是绳,两个长度相等就是杆,给了 `frequency` 就是弹簧。 |
+| `FixedJoint3D` | 完全不给自由度——两者作为一个整体运动。 |
+
+`anchor` 与 `axis` 写在**声明关节的那个实体自己的局部空间**里,用世界单位,
+在关节建立的那一刻按它的变换解算成世界量。那个姿态同时也是所有限位的**零点**:
+一扇摆成关闭状态的门,`angle` 就是 0,开到 `upperAngle`。
+
+`motorSpeed` 随时可以由游戏逻辑改写——变了就会重新驱动世界。反方向上,
+`HingeJoint3D.angle` 与 `SliderJoint3D.translation` 每步写回,
+所以游戏可以直接问「门开了多少」,不必自己再积分一遍。
+
+<Aside>
+ `collideConnected` 默认关闭,而且它把两个刚体并进**同一个装配**而不是只对这一对生效:
+ 一串关节所能连通到的所有刚体,彼此之间都不再碰撞。门需要这个(它不能和自己的门框打架),
+ 布娃娃也需要。确实应该互相碰的时候再把它打开。
+
+ **一个实体只有一个关节**——世界按「声明它的实体」给约束建索引。
+ 需要两个关节的实体就挂一个子实体给第二个,这也正好让场景说清楚哪个是哪个。
+</Aside>
+
## 问世界「那里有什么」
`Physics3D` 资源用世界单位回答空间问题。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 5e25592bb..86c75ff1f 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -2,11 +2,11 @@
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
"public": 113,
- "beta": 67,
- "experimental": 1550,
+ "beta": 72,
+ "experimental": 1555,
"deprecated": 3
},
- "total": 1730,
+ "total": 1740,
"subsystems": [
{
"id": "ecs",
@@ -1769,6 +1769,30 @@
"minigame"
]
},
+ {
+ "name": "DistanceJoint3D",
+ "kind": "const",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "FixedJoint3D",
+ "kind": "const",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "GraphNodeType",
"kind": "type",
@@ -1793,6 +1817,18 @@
"minigame"
]
},
+ {
+ "name": "HingeJoint3D",
+ "kind": "const",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "Input",
"kind": "const",
@@ -1971,6 +2007,18 @@
"minigame"
]
},
+ {
+ "name": "PointJoint3D",
+ "kind": "const",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "PrefabOverride",
"kind": "interface",
@@ -2079,6 +2127,18 @@
"minigame"
]
},
+ {
+ "name": "SliderJoint3D",
+ "kind": "const",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "SpawnOverride",
"kind": "type",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 41cad0fe1..680f74041 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -113,6 +113,11 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
CapsuleCollider3D: { category: 'physics', summary: 'An upright capsule — what a 3D character is. Total height is 2*(halfHeight + radius).', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
MeshCollider3D: { category: 'physics', summary: 'Collides against an imported mesh\u2019s own triangles — terrain, stairs, a room. Always static, and one-sided.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
CharacterController3D: { category: 'physics', summary: 'A kinematic 3D mover: swept against the world, climbs steps, stays glued to slopes, and reports the ground it is on.', doc: 'gameplay/physics-3d', anchor: 'characters', anchorZh: 'characters' },
+ PointJoint3D: { category: 'physics', summary: 'Holds two 3D bodies at a shared point, free to turn on all three axes — a chain link, a ragdoll limb.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
+ HingeJoint3D: { category: 'physics', summary: 'One axis of rotation between two 3D bodies — a door or a driven wheel, with optional limits and a motor.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
+ SliderJoint3D: { category: 'physics', summary: 'One axis of travel between two 3D bodies — a lift or a piston, with optional limits and a motor.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
+ DistanceJoint3D: { category: 'physics', summary: 'Keeps two 3D bodies a distance apart: a rope, a rod, or a spring when a frequency is given.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
+ FixedJoint3D: { category: 'physics', summary: 'Locks two 3D bodies together in the pose they were placed in — no freedom at all.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },
CharacterController: { category: 'physics', summary: 'Kinematic character movement that slides along walls, climbs slopes and reports ground contact.', doc: 'gameplay/physics', anchor: 'character-controller', anchorZh: '角色控制器' },
OneWayPlatform: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },
DistanceJoint: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 9891d484a..06194416c 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -991,6 +991,70 @@
"motorSpeed"
]
},
+ {
+ "name": "DistanceJoint3D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "connectedEntity",
+ "type": "Entity",
+ "default": "-1"
+ },
+ {
+ "key": "anchor",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "connectedAnchor",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "minLength",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "maxLength",
+ "type": "number",
+ "default": "100"
+ },
+ {
+ "key": "frequency",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "damping",
+ "type": "number",
+ "default": "0.5"
+ },
+ {
+ "key": "collideConnected",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "connectedEntity",
+ "anchor.x",
+ "anchor.y",
+ "anchor.z",
+ "connectedAnchor.x",
+ "connectedAnchor.y",
+ "connectedAnchor.z",
+ "minLength",
+ "maxLength",
+ "frequency",
+ "damping"
+ ]
+ },
{
"name": "DragState",
"source": "ts",
@@ -1175,6 +1239,30 @@
}
]
},
+ {
+ "name": "FixedJoint3D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "connectedEntity",
+ "type": "Entity",
+ "default": "-1"
+ },
+ {
+ "key": "collideConnected",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "connectedEntity"
+ ]
+ },
{
"name": "FlexContainer",
"source": "cpp",
@@ -1305,6 +1393,86 @@
"damping"
]
},
+ {
+ "name": "HingeJoint3D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "connectedEntity",
+ "type": "Entity",
+ "default": "-1"
+ },
+ {
+ "key": "anchor",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "axis",
+ "type": "Vec3",
+ "default": "(0, 1, 0)"
+ },
+ {
+ "key": "enableLimit",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "lowerAngle",
+ "type": "number",
+ "default": "-1.5708"
+ },
+ {
+ "key": "upperAngle",
+ "type": "number",
+ "default": "1.5708"
+ },
+ {
+ "key": "enableMotor",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "motorSpeed",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "maxMotorTorque",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "collideConnected",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "angle",
+ "type": "number",
+ "default": "0"
+ }
+ ],
+ "animatable": [
+ "connectedEntity",
+ "anchor.x",
+ "anchor.y",
+ "anchor.z",
+ "axis.x",
+ "axis.y",
+ "axis.z",
+ "lowerAngle",
+ "upperAngle",
+ "motorSpeed",
+ "maxMotorTorque",
+ "angle"
+ ]
+ },
{
"name": "Interactable",
"source": "cpp",
@@ -2264,6 +2432,38 @@
"fields": [],
"tag": true
},
+ {
+ "name": "PointJoint3D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "connectedEntity",
+ "type": "Entity",
+ "default": "-1"
+ },
+ {
+ "key": "anchor",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "collideConnected",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "connectedEntity",
+ "anchor.x",
+ "anchor.y",
+ "anchor.z"
+ ]
+ },
{
"name": "PolygonCollider",
"source": "ts",
@@ -2840,6 +3040,86 @@
}
]
},
+ {
+ "name": "SliderJoint3D",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "connectedEntity",
+ "type": "Entity",
+ "default": "-1"
+ },
+ {
+ "key": "anchor",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "axis",
+ "type": "Vec3",
+ "default": "(0, 1, 0)"
+ },
+ {
+ "key": "enableLimit",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "lowerTranslation",
+ "type": "number",
+ "default": "-100"
+ },
+ {
+ "key": "upperTranslation",
+ "type": "number",
+ "default": "100"
+ },
+ {
+ "key": "enableMotor",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "motorSpeed",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "maxMotorForce",
+ "type": "number",
+ "default": "0"
+ },
+ {
+ "key": "collideConnected",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "translation",
+ "type": "number",
+ "default": "0"
+ }
+ ],
+ "animatable": [
+ "connectedEntity",
+ "anchor.x",
+ "anchor.y",
+ "anchor.z",
+ "axis.x",
+ "axis.y",
+ "axis.z",
+ "lowerTranslation",
+ "upperTranslation",
+ "motorSpeed",
+ "maxMotorForce",
+ "translation"
+ ]
+ },
{
"name": "SphereCollider3D",
"source": "cpp",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5abacd0f5..ef5bef6fd 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 60 beta · 1435 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1440 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2486,6 +2486,24 @@ ComponentDef<{}>
ComponentDef<DistanceJointData>
```
+## DistanceJoint3D — const @beta
+```
+ComponentDef<DistanceJoint3DData>
+```
+
+## DistanceJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedAnchor: Vec3
+connectedEntity: number
+damping: number
+enabled: boolean
+frequency: number
+maxLength: number
+minLength: number
+```
+
## DocumentDiagnostic — interface @experimental
```
code: string
@@ -3054,6 +3072,18 @@ type: "filter"
{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }
```
+## FixedJoint3D — const @beta
+```
+ComponentDef<FixedJoint3DData>
+```
+
+## FixedJoint3DData — interface @experimental
+```
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## FlattenContext — interface @experimental
```
allocateId: () => number
@@ -3487,6 +3517,27 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## HingeJoint3D — const @beta
+```
+ComponentDef<HingeJoint3DData>
+```
+
+## HingeJoint3DData — interface @experimental
+```
+anchor: Vec3
+angle: number
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerAngle: number
+maxMotorTorque: number
+motorSpeed: number
+upperAngle: number
+```
+
## HitAreaShape — type @experimental
```
| { type: 'rect'; x: number; y: number; width: number; height: number }
@@ -5380,6 +5431,19 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## PointJoint3D — const @beta
+```
+ComponentDef<PointJoint3DData>
+```
+
+## PointJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## PolygonCollider — const @experimental
```
ComponentDef<PolygonColliderData>
@@ -6801,6 +6865,27 @@ setValue: (value: number) => void
trackEntity: number
```
+## SliderJoint3D — const @beta
+```
+ComponentDef<SliderJoint3DData>
+```
+
+## SliderJoint3DData — interface @experimental
+```
+anchor: Vec3
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerTranslation: number
+maxMotorForce: number
+motorSpeed: number
+translation: number
+upperTranslation: number
+```
+
## SliderOptions — interface @experimental
```
disabled: boolean | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e232d0bc4..8d65bf6e9 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 65 beta · 1454 experimental · 3 deprecated
+Symbols: 113 public · 70 beta · 1459 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2494,6 +2494,24 @@ ComponentDef<{}>
ComponentDef<DistanceJointData>
```
+## DistanceJoint3D — const @beta
+```
+ComponentDef<DistanceJoint3DData>
+```
+
+## DistanceJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedAnchor: Vec3
+connectedEntity: number
+damping: number
+enabled: boolean
+frequency: number
+maxLength: number
+minLength: number
+```
+
## DocumentDiagnostic — interface @experimental
```
code: string
@@ -3062,6 +3080,18 @@ type: "filter"
{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }
```
+## FixedJoint3D — const @beta
+```
+ComponentDef<FixedJoint3DData>
+```
+
+## FixedJoint3DData — interface @experimental
+```
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## FlattenContext — interface @experimental
```
allocateId: () => number
@@ -3495,6 +3525,27 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## HingeJoint3D — const @beta
+```
+ComponentDef<HingeJoint3DData>
+```
+
+## HingeJoint3DData — interface @experimental
+```
+anchor: Vec3
+angle: number
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerAngle: number
+maxMotorTorque: number
+motorSpeed: number
+upperAngle: number
+```
+
## HitAreaShape — type @experimental
```
| { type: 'rect'; x: number; y: number; width: number; height: number }
@@ -5563,6 +5614,19 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## PointJoint3D — const @beta
+```
+ComponentDef<PointJoint3DData>
+```
+
+## PointJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## PolygonCollider — const @experimental
```
ComponentDef<PolygonColliderData>
@@ -6994,6 +7058,27 @@ setValue: (value: number) => void
trackEntity: number
```
+## SliderJoint3D — const @beta
+```
+ComponentDef<SliderJoint3DData>
+```
+
+## SliderJoint3DData — interface @experimental
+```
+anchor: Vec3
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerTranslation: number
+maxMotorForce: number
+motorSpeed: number
+translation: number
+upperTranslation: number
+```
+
## SliderOptions — interface @experimental
```
disabled: boolean | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index cc23d06da..3ffe9c439 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 62 beta · 1434 experimental · 3 deprecated
+Symbols: 113 public · 67 beta · 1439 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2481,6 +2481,24 @@ ComponentDef<{}>
ComponentDef<DistanceJointData>
```
+## DistanceJoint3D — const @beta
+```
+ComponentDef<DistanceJoint3DData>
+```
+
+## DistanceJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedAnchor: Vec3
+connectedEntity: number
+damping: number
+enabled: boolean
+frequency: number
+maxLength: number
+minLength: number
+```
+
## DocumentDiagnostic — interface @experimental
```
code: string
@@ -3049,6 +3067,18 @@ type: "filter"
{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }
```
+## FixedJoint3D — const @beta
+```
+ComponentDef<FixedJoint3DData>
+```
+
+## FixedJoint3DData — interface @experimental
+```
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## FlattenContext — interface @experimental
```
allocateId: () => number
@@ -3482,6 +3512,27 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## HingeJoint3D — const @beta
+```
+ComponentDef<HingeJoint3DData>
+```
+
+## HingeJoint3DData — interface @experimental
+```
+anchor: Vec3
+angle: number
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerAngle: number
+maxMotorTorque: number
+motorSpeed: number
+upperAngle: number
+```
+
## HitAreaShape — type @experimental
```
| { type: 'rect'; x: number; y: number; width: number; height: number }
@@ -5375,6 +5426,19 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## PointJoint3D — const @beta
+```
+ComponentDef<PointJoint3DData>
+```
+
+## PointJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## PolygonCollider — const @experimental
```
ComponentDef<PolygonColliderData>
@@ -6796,6 +6860,27 @@ setValue: (value: number) => void
trackEntity: number
```
+## SliderJoint3D — const @beta
+```
+ComponentDef<SliderJoint3DData>
+```
+
+## SliderJoint3DData — interface @experimental
+```
+anchor: Vec3
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerTranslation: number
+maxMotorForce: number
+motorSpeed: number
+translation: number
+upperTranslation: number
+```
+
## SliderOptions — interface @experimental
```
disabled: boolean | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 4fabc6a57..16f002452 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 60 beta · 1455 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1460 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2481,6 +2481,24 @@ ComponentDef<{}>
ComponentDef<DistanceJointData>
```
+## DistanceJoint3D — const @beta
+```
+ComponentDef<DistanceJoint3DData>
+```
+
+## DistanceJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedAnchor: Vec3
+connectedEntity: number
+damping: number
+enabled: boolean
+frequency: number
+maxLength: number
+minLength: number
+```
+
## DocumentDiagnostic — interface @experimental
```
code: string
@@ -3049,6 +3067,18 @@ type: "filter"
{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }
```
+## FixedJoint3D — const @beta
+```
+ComponentDef<FixedJoint3DData>
+```
+
+## FixedJoint3DData — interface @experimental
+```
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## FlattenContext — interface @experimental
```
allocateId: () => number
@@ -3482,6 +3512,27 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## HingeJoint3D — const @beta
+```
+ComponentDef<HingeJoint3DData>
+```
+
+## HingeJoint3DData — interface @experimental
+```
+anchor: Vec3
+angle: number
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerAngle: number
+maxMotorTorque: number
+motorSpeed: number
+upperAngle: number
+```
+
## HitAreaShape — type @experimental
```
| { type: 'rect'; x: number; y: number; width: number; height: number }
@@ -5620,6 +5671,19 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## PointJoint3D — const @beta
+```
+ComponentDef<PointJoint3DData>
+```
+
+## PointJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## PolygonCollider — const @experimental
```
ComponentDef<PolygonColliderData>
@@ -7041,6 +7105,27 @@ setValue: (value: number) => void
trackEntity: number
```
+## SliderJoint3D — const @beta
+```
+ComponentDef<SliderJoint3DData>
+```
+
+## SliderJoint3DData — interface @experimental
+```
+anchor: Vec3
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerTranslation: number
+maxMotorForce: number
+motorSpeed: number
+translation: number
+upperTranslation: number
+```
+
## SliderOptions — interface @experimental
```
disabled: boolean | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 63b0d9b81..8ab60d979 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 60 beta · 1445 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1450 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2481,6 +2481,24 @@ ComponentDef<{}>
ComponentDef<DistanceJointData>
```
+## DistanceJoint3D — const @beta
+```
+ComponentDef<DistanceJoint3DData>
+```
+
+## DistanceJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedAnchor: Vec3
+connectedEntity: number
+damping: number
+enabled: boolean
+frequency: number
+maxLength: number
+minLength: number
+```
+
## DocumentDiagnostic — interface @experimental
```
code: string
@@ -3049,6 +3067,18 @@ type: "filter"
{ identityMatrix(): number[]; grayscaleMatrix(): number[]; sepiaMatrix(): number[]; brightnessMatrix(value: number): number[]; contrastMatrix(value: number): number[]; saturationMatrix(value: number): number[]; invertMatrix(): number[]; getColorMatrixShader: () => ShaderHandle; colorMatrixUniforms(matrix: number[]): Record<string, number[]>; }
```
+## FixedJoint3D — const @beta
+```
+ComponentDef<FixedJoint3DData>
+```
+
+## FixedJoint3DData — interface @experimental
+```
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## FlattenContext — interface @experimental
```
allocateId: () => number
@@ -3482,6 +3512,27 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## HingeJoint3D — const @beta
+```
+ComponentDef<HingeJoint3DData>
+```
+
+## HingeJoint3DData — interface @experimental
+```
+anchor: Vec3
+angle: number
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerAngle: number
+maxMotorTorque: number
+motorSpeed: number
+upperAngle: number
+```
+
## HitAreaShape — type @experimental
```
| { type: 'rect'; x: number; y: number; width: number; height: number }
@@ -5382,6 +5433,19 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## PointJoint3D — const @beta
+```
+ComponentDef<PointJoint3DData>
+```
+
+## PointJoint3DData — interface @experimental
+```
+anchor: Vec3
+collideConnected: boolean
+connectedEntity: number
+enabled: boolean
+```
+
## PolygonCollider — const @experimental
```
ComponentDef<PolygonColliderData>
@@ -6803,6 +6867,27 @@ setValue: (value: number) => void
trackEntity: number
```
+## SliderJoint3D — const @beta
+```
+ComponentDef<SliderJoint3DData>
+```
+
+## SliderJoint3DData — interface @experimental
+```
+anchor: Vec3
+axis: Vec3
+collideConnected: boolean
+connectedEntity: number
+enableLimit: boolean
+enableMotor: boolean
+enabled: boolean
+lowerTranslation: number
+maxMotorForce: number
+motorSpeed: number
+translation: number
+upperTranslation: number
+```
+
## SliderOptions — interface @experimental
```
disabled: boolean | undefined
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 2791f44e4..f946d1316 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -200,6 +200,19 @@ export {
type CharacterController3DData,
} from './physics3d/Physics3DComponents';
+export {
+ PointJoint3D,
+ HingeJoint3D,
+ SliderJoint3D,
+ DistanceJoint3D,
+ FixedJoint3D,
+ type PointJoint3DData,
+ type HingeJoint3DData,
+ type SliderJoint3DData,
+ type DistanceJoint3DData,
+ type FixedJoint3DData,
+} from './physics3d/Physics3DJoints';
+
export {
readCollider3DShapes,
collider3DWireframe,
diff --git a/sdk/src/physics3d/ColliderShape3D.ts b/sdk/src/physics3d/ColliderShape3D.ts
index c49b8694f..5d2c5bdf1 100644
--- a/sdk/src/physics3d/ColliderShape3D.ts
+++ b/sdk/src/physics3d/ColliderShape3D.ts
@@ -58,7 +58,8 @@ export interface Collider3DInstance {
const ZERO: Vec3 = { x: 0, y: 0, z: 0 };
-function rotateByQuat(q: Quat, v: Vec3): Vec3 {
+/** @internal Shared with the joint wiring, which turns anchors and axes the same way. */
+export function rotateVec3ByQuat(q: Quat, v: Vec3): Vec3 {
// t = 2 * (q.xyz × v); v' = v + q.w * t + q.xyz × t
const tx = 2 * (q.y * v.z - q.z * v.y);
const ty = 2 * (q.z * v.x - q.x * v.z);
@@ -265,7 +266,7 @@ export function collider3DWireframe(shape: Collider3DShape, segments = COLLIDER3
*/
export function placeCollider3DWireframe(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][] {
return lines.map((line) => line.map((p) => {
- const r = rotateByQuat(rotation, p);
+ const r = rotateVec3ByQuat(rotation, p);
return { x: position.x + r.x, y: position.y + r.y, z: position.z + r.z };
}));
}
diff --git a/sdk/src/physics3d/Physics3DJoints.ts b/sdk/src/physics3d/Physics3DJoints.ts
new file mode 100644
index 000000000..eb9168402
--- /dev/null
+++ b/sdk/src/physics3d/Physics3DJoints.ts
@@ -0,0 +1,356 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DJoints.ts
+ * @brief Joints between 3D bodies, as a scene authors them.
+ * @details A joint lives on the entity that declares it and names the other one,
+ * the same shape the 2D joints use — so a scene reads the same whichever
+ * world it is in, and one entity can be jointed to several others by
+ * carrying several joint entities rather than one crowded component.
+ *
+ * Anchors and axes are written in THIS entity's local space, in world
+ * units, and are resolved against its transform when the joint is made:
+ * an author moves the piece and the joint follows, rather than holding a
+ * world coordinate that stops meaning anything once the scene is edited.
+ */
+import { defineComponent, Transform } from '../ecs/component';
+import type { TransformData } from '../ecs/component.generated';
+import type { App } from '../app/app';
+import type { Entity, Vec3 } from '../types';
+import type { Physics3DWasmModule } from './Physics3DModule';
+import { rotateVec3ByQuat } from './ColliderShape3D';
+
+export interface PointJoint3DData {
+ connectedEntity: number;
+ anchor: Vec3;
+ collideConnected: boolean;
+ enabled: boolean;
+}
+
+/**
+ * A shared point the two bodies turn freely about — a chain link, a ragdoll limb.
+ *
+ * @beta
+ */
+export const PointJoint3D = defineComponent<PointJoint3DData>('PointJoint3D', {
+ connectedEntity: -1,
+ anchor: { x: 0, y: 0, z: 0 },
+ collideConnected: false,
+ enabled: true,
+}, { entityFields: ['connectedEntity'] });
+
+export interface HingeJoint3DData {
+ connectedEntity: number;
+ anchor: Vec3;
+ axis: Vec3;
+ enableLimit: boolean;
+ lowerAngle: number;
+ upperAngle: number;
+ enableMotor: boolean;
+ motorSpeed: number;
+ maxMotorTorque: number;
+ collideConnected: boolean;
+ enabled: boolean;
+ /** Where the hinge is now, in radians. Written by the world each step. */
+ angle: number;
+}
+
+/**
+ * One axis of rotation — a door, a lever, a driven wheel. Limits are radians
+ * measured from the pose the joint was made in, so zero is where you placed it.
+ *
+ * @beta
+ */
+export const HingeJoint3D = defineComponent<HingeJoint3DData>('HingeJoint3D', {
+ connectedEntity: -1,
+ anchor: { x: 0, y: 0, z: 0 },
+ axis: { x: 0, y: 1, z: 0 },
+ enableLimit: false,
+ lowerAngle: -Math.PI / 2,
+ upperAngle: Math.PI / 2,
+ enableMotor: false,
+ motorSpeed: 0,
+ maxMotorTorque: 0,
+ collideConnected: false,
+ enabled: true,
+ angle: 0,
+}, { entityFields: ['connectedEntity'] });
+
+export interface SliderJoint3DData {
+ connectedEntity: number;
+ anchor: Vec3;
+ axis: Vec3;
+ enableLimit: boolean;
+ lowerTranslation: number;
+ upperTranslation: number;
+ enableMotor: boolean;
+ motorSpeed: number;
+ maxMotorForce: number;
+ collideConnected: boolean;
+ enabled: boolean;
+ /** How far along the axis it has travelled, in world units. Written by the
+ * world each step. */
+ translation: number;
+}
+
+/**
+ * One axis of travel — a lift, a piston, a sliding door. Limits are world units
+ * along `axis`, again measured from where the joint was made.
+ *
+ * @beta
+ */
+export const SliderJoint3D = defineComponent<SliderJoint3DData>('SliderJoint3D', {
+ connectedEntity: -1,
+ anchor: { x: 0, y: 0, z: 0 },
+ axis: { x: 0, y: 1, z: 0 },
+ enableLimit: false,
+ lowerTranslation: -100,
+ upperTranslation: 100,
+ enableMotor: false,
+ motorSpeed: 0,
+ maxMotorForce: 0,
+ collideConnected: false,
+ enabled: true,
+ translation: 0,
+}, { entityFields: ['connectedEntity'] });
+
+export interface DistanceJoint3DData {
+ connectedEntity: number;
+ anchor: Vec3;
+ connectedAnchor: Vec3;
+ minLength: number;
+ maxLength: number;
+ frequency: number;
+ damping: number;
+ collideConnected: boolean;
+ enabled: boolean;
+}
+
+/**
+ * A distance kept between two points: a rope when only `maxLength` matters, a rod
+ * when the two lengths meet, a spring when `frequency` is above zero.
+ *
+ * @beta
+ */
+export const DistanceJoint3D = defineComponent<DistanceJoint3DData>('DistanceJoint3D', {
+ connectedEntity: -1,
+ anchor: { x: 0, y: 0, z: 0 },
+ connectedAnchor: { x: 0, y: 0, z: 0 },
+ minLength: 0,
+ maxLength: 100,
+ frequency: 0,
+ damping: 0.5,
+ collideConnected: false,
+ enabled: true,
+}, { entityFields: ['connectedEntity'] });
+
+export interface FixedJoint3DData {
+ connectedEntity: number;
+ collideConnected: boolean;
+ enabled: boolean;
+}
+
+/**
+ * No freedom at all: the two move as one. It has no anchor — the pose the pieces
+ * are in when the joint is made is the joint.
+ *
+ * @beta
+ */
+export const FixedJoint3D = defineComponent<FixedJoint3DData>('FixedJoint3D', {
+ connectedEntity: -1,
+ collideConnected: false,
+ enabled: true,
+}, { entityFields: ['connectedEntity'] });
+
+/** The joint components, in the order the system offers an entity's to the world. */
+export const JOINT3D_TYPES = [
+ PointJoint3D, HingeJoint3D, SliderJoint3D, DistanceJoint3D, FixedJoint3D,
+] as const;
+
+/** What the world holds for one joint: the two bodies it was built between, which
+ * are what it takes to take the joint back out again. */
+export interface Joint3DRecord {
+ bodyA: number;
+ bodyB: number;
+ /** Which component built it — a joint whose component changed is rebuilt. */
+ type: string;
+ /** The motor the world was last told about, so a joint is only re-driven when
+ * gameplay actually changed it. */
+ motorOn: boolean;
+ motorSpeed: number;
+}
+
+export type Joint3DMap = Map<Entity, Joint3DRecord>;
+
+type AnyJoint = { connectedEntity: number; collideConnected: boolean; enabled: boolean };
+type Joint3DDef = (typeof JOINT3D_TYPES)[number];
+
+/** An entity's joint: the FIRST of the five it carries, matching what the world
+ * builds — the module keys one constraint per entity, so a second component on
+ * the same entity would be geometry nothing enforces. */
+function jointOn(app: App, entity: Entity): { def: Joint3DDef; data: AnyJoint } | null {
+ for (const def of JOINT3D_TYPES) {
+ if (app.world.has(entity, def)) {
+ return { def, data: app.world.get(entity, def) as unknown as AnyJoint };
+ }
+ }
+ return null;
+}
+
+/** A local (world-unit) point on `entity`, in metres, where the solver wants it. */
+function anchorInMetres(app: App, entity: Entity, local: Vec3, ppu: number): Vec3 {
+ const t = app.world.get(entity, Transform) as TransformData | undefined;
+ const p = t?.worldPosition ?? { x: 0, y: 0, z: 0 };
+ const r = t?.worldRotation ?? { x: 0, y: 0, z: 0, w: 1 };
+ const turned = rotateVec3ByQuat(r, local);
+ return { x: (p.x + turned.x) / ppu, y: (p.y + turned.y) / ppu, z: (p.z + turned.z) / ppu };
+}
+
+/** A local direction on `entity`, in world space. Directions do not scale. */
+function axisInWorld(app: App, entity: Entity, local: Vec3): Vec3 {
+ const t = app.world.get(entity, Transform) as TransformData | undefined;
+ return rotateVec3ByQuat(t?.worldRotation ?? { x: 0, y: 0, z: 0, w: 1 }, local);
+}
+
+/**
+ * Hand one joint to the world. The entity that declares it is body A and the one
+ * it names is body B, so `anchor` and `connectedAnchor` read in that order and a
+ * hinge's angle grows the way the axis points.
+ */
+function build(app: App, module: Physics3DWasmModule, entity: Entity,
+ def: Joint3DDef, bodyA: number, bodyB: number, ppu: number): boolean {
+ const raw = app.world.get(entity, def) as unknown;
+ const collide = (raw as AnyJoint).collideConnected ? 1 : 0;
+ const e = entity as number;
+
+ if (def === PointJoint3D) {
+ const d = raw as PointJoint3DData;
+ const a = anchorInMetres(app, entity, d.anchor, ppu);
+ return module._physics3d_addPointJoint(e, bodyA, bodyB, a.x, a.y, a.z, collide) !== 0;
+ }
+ if (def === HingeJoint3D) {
+ const d = raw as HingeJoint3DData;
+ const a = anchorInMetres(app, entity, d.anchor, ppu);
+ const axis = axisInWorld(app, entity, d.axis);
+ return module._physics3d_addHingeJoint(
+ e, bodyA, bodyB, a.x, a.y, a.z, axis.x, axis.y, axis.z,
+ d.enableLimit ? 1 : 0, d.lowerAngle, d.upperAngle,
+ d.enableMotor ? 1 : 0, d.motorSpeed, d.maxMotorTorque, collide) !== 0;
+ }
+ if (def === SliderJoint3D) {
+ const d = raw as SliderJoint3DData;
+ const a = anchorInMetres(app, entity, d.anchor, ppu);
+ const axis = axisInWorld(app, entity, d.axis);
+ // Travel and speed are lengths; torque and force are not, the same split
+ // the 2D joints make.
+ return module._physics3d_addSliderJoint(
+ e, bodyA, bodyB, a.x, a.y, a.z, axis.x, axis.y, axis.z,
+ d.enableLimit ? 1 : 0, d.lowerTranslation / ppu, d.upperTranslation / ppu,
+ d.enableMotor ? 1 : 0, d.motorSpeed / ppu, d.maxMotorForce, collide) !== 0;
+ }
+ if (def === DistanceJoint3D) {
+ const d = raw as DistanceJoint3DData;
+ const a = anchorInMetres(app, entity, d.anchor, ppu);
+ const b = anchorInMetres(app, d.connectedEntity as Entity, d.connectedAnchor, ppu);
+ return module._physics3d_addDistanceJoint(
+ e, bodyA, bodyB, a.x, a.y, a.z, b.x, b.y, b.z,
+ d.minLength / ppu, d.maxLength / ppu, d.frequency, d.damping, collide) !== 0;
+ }
+ return module._physics3d_addFixedJoint(e, bodyA, bodyB, collide) !== 0;
+}
+
+/**
+ * Bring the world's joints in line with the ECS.
+ *
+ * Called BEFORE bodies are removed, and that order is load-bearing: the module
+ * holds each constraint against two bodies, so a body taken out from under a live
+ * joint leaves the solver holding nothing.
+ *
+ * @param doomed Entities whose bodies are about to go, so their joints go first.
+ */
+export function syncJoints3D(app: App, module: Physics3DWasmModule,
+ bodies: Map<Entity, number>, joints: Joint3DMap,
+ ppu: number, doomed: ReadonlySet<Entity>): void {
+ for (const [entity, held] of joints) {
+ const joint = app.world.valid(entity) ? jointOn(app, entity) : null;
+ const connected = joint ? joint.data.connectedEntity as Entity : (-1 as Entity);
+ const stillRight = joint !== null
+ && joint.data.enabled !== false
+ && joint.def._name === held.type
+ && !doomed.has(entity) && !doomed.has(connected)
+ && bodies.get(entity) === held.bodyA
+ && bodies.get(connected) === held.bodyB;
+ if (stillRight) continue;
+ module._physics3d_removeJoint(entity as number, held.bodyA, held.bodyB);
+ joints.delete(entity);
+ }
+
+ for (const def of JOINT3D_TYPES) {
+ for (const entity of app.world.queryEntities([def])) {
+ if (joints.has(entity)) continue;
+ const joint = jointOn(app, entity);
+ if (!joint || joint.data.enabled === false) continue;
+ const bodyA = bodies.get(entity);
+ const bodyB = bodies.get(joint.data.connectedEntity as Entity);
+ // A joint waits for both ends: a scene that spawns the other half a
+ // frame later gets its joint on that frame rather than never.
+ if (bodyA === undefined || bodyB === undefined || bodyA === bodyB) continue;
+ if (build(app, module, entity, joint.def, bodyA, bodyB, ppu)) {
+ const motor = motorOf(app, entity, joint.def, ppu);
+ joints.set(entity, {
+ bodyA, bodyB, type: joint.def._name,
+ motorOn: motor.on, motorSpeed: motor.speed,
+ });
+ }
+ }
+ }
+
+ driveJoints3D(app, module, joints, ppu);
+}
+
+/** The motor a driven joint is asking for right now, in the module's units. */
+function motorOf(app: App, entity: Entity, def: Joint3DDef, ppu: number,
+): { on: boolean; speed: number } {
+ if (def === HingeJoint3D) {
+ const d = app.world.get(entity, HingeJoint3D) as HingeJoint3DData;
+ return { on: d.enableMotor === true, speed: d.motorSpeed };
+ }
+ if (def === SliderJoint3D) {
+ const d = app.world.get(entity, SliderJoint3D) as SliderJoint3DData;
+ return { on: d.enableMotor === true, speed: d.motorSpeed / ppu };
+ }
+ return { on: false, speed: 0 };
+}
+
+/**
+ * Carry gameplay's motor changes into the world, and the joint's own state back.
+ * A joint is built once, so without this `motorSpeed` would be a field nothing
+ * reads after the first frame — and no game could ask how far the door swung.
+ */
+function driveJoints3D(app: App, module: Physics3DWasmModule, joints: Joint3DMap,
+ ppu: number): void {
+ for (const [entity, held] of joints) {
+ if (held.type === HingeJoint3D._name) {
+ const d = app.world.get(entity, HingeJoint3D) as HingeJoint3DData;
+ const on = d.enableMotor === true;
+ if (on !== held.motorOn || d.motorSpeed !== held.motorSpeed) {
+ module._physics3d_setJointMotor(entity as number, on ? 1 : 0, d.motorSpeed);
+ held.motorOn = on;
+ held.motorSpeed = d.motorSpeed;
+ }
+ d.angle = module._physics3d_jointValue(entity as number);
+ app.world.set(entity, HingeJoint3D, d);
+ } else if (held.type === SliderJoint3D._name) {
+ const d = app.world.get(entity, SliderJoint3D) as SliderJoint3DData;
+ const on = d.enableMotor === true;
+ const speed = d.motorSpeed / ppu;
+ if (on !== held.motorOn || speed !== held.motorSpeed) {
+ module._physics3d_setJointMotor(entity as number, on ? 1 : 0, speed);
+ held.motorOn = on;
+ held.motorSpeed = speed;
+ }
+ d.translation = module._physics3d_jointValue(entity as number) * ppu;
+ app.world.set(entity, SliderJoint3D, d);
+ }
+ }
+}
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index 816357dfe..a05a0415c 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -70,6 +70,33 @@ export interface Physics3DWasmModule {
_physics3d_overlapBox(px: number, py: number, pz: number,
hx: number, hy: number, hz: number, layerMask: number): number;
+ _physics3d_addPointJoint(entity: number, bodyA: number, bodyB: number,
+ px: number, py: number, pz: number,
+ collideConnected: number): number;
+ _physics3d_addHingeJoint(entity: number, bodyA: number, bodyB: number,
+ px: number, py: number, pz: number,
+ ax: number, ay: number, az: number,
+ enableLimit: number, lower: number, upper: number,
+ enableMotor: number, motorSpeed: number, maxTorque: number,
+ collideConnected: number): number;
+ _physics3d_addSliderJoint(entity: number, bodyA: number, bodyB: number,
+ px: number, py: number, pz: number,
+ ax: number, ay: number, az: number,
+ enableLimit: number, lower: number, upper: number,
+ enableMotor: number, motorSpeed: number, maxForce: number,
+ collideConnected: number): number;
+ _physics3d_addDistanceJoint(entity: number, bodyA: number, bodyB: number,
+ ax: number, ay: number, az: number,
+ bx: number, by: number, bz: number,
+ minLength: number, maxLength: number,
+ frequency: number, damping: number,
+ collideConnected: number): number;
+ _physics3d_addFixedJoint(entity: number, bodyA: number, bodyB: number,
+ collideConnected: number): number;
+ _physics3d_removeJoint(entity: number, bodyA: number, bodyB: number): void;
+ _physics3d_setJointMotor(entity: number, enable: number, speed: number): void;
+ _physics3d_jointValue(entity: number): number;
+
_physics3d_contactEnters(): number;
_physics3d_contactEntersBytes(): number;
_physics3d_contactExits(): number;
@@ -103,6 +130,7 @@ const REQUIRED_EXPORTS = [
'_physics3d_sphereCast', '_physics3d_overlapSphere', '_physics3d_overlapBox',
'_physics3d_contactEnters', '_physics3d_contactEntersBytes',
'_physics3d_sensorEnters', '_physics3d_sensorEntersBytes',
+ '_physics3d_addHingeJoint', '_physics3d_removeJoint',
] as const;
/** Throws naming what is missing, rather than letting the first frame do it. */
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index d5955a71e..bce917259 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -16,6 +16,7 @@ import {
stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,
} from './Physics3DSystem';
import { Physics3DQueries } from './Physics3DQueries';
+import type { Joint3DMap } from './Physics3DJoints';
/** Ask the 3D world what is where. Present once the module has loaded. */
export const Physics3D = defineResource<Physics3DQueries | null>(null, 'Physics3D');
@@ -28,10 +29,13 @@ export interface Physics3DRuntime {
bodies: Map<Entity, number>;
/** Entity -> character id. Characters are not bodies and are kept apart. */
characters: Map<Entity, number>;
+ /** Entity -> the joint it declared, with the bodies it was built between. */
+ joints: Joint3DMap;
}
export const Physics3DRuntime = defineResource<Physics3DRuntime>(
- { module: null, initPromise: null, bodies: new Map(), characters: new Map() },
+ { module: null, initPromise: null, bodies: new Map(), characters: new Map(),
+ joints: new Map() },
'Physics3DRuntime',
);
@@ -52,6 +56,7 @@ export class Physics3DPlugin implements Plugin {
build(app: App): void {
const runtime: Physics3DRuntime = {
module: null, initPromise: null, bodies: new Map(), characters: new Map(),
+ joints: new Map(),
};
const events: Physics3DEventsData = {
contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],
@@ -74,7 +79,7 @@ export class Physics3DPlugin implements Plugin {
this.config_.pixelsPerUnit));
app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
stepPhysics3D(app, module, runtime.bodies, this.config_,
- runtime.characters, events);
+ runtime.characters, events, runtime.joints);
}));
app.setFixedTimestep?.(this.config_.fixedTimestep);
app.subsystems?.transition?.('physics3d', 'ready');
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index 77e5f7b7e..b7bcd9359 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -21,6 +21,7 @@ import {
type CapsuleCollider3DData, type CharacterController3DData, type MeshCollider3DData,
} from './Physics3DComponents';
import { getMeshCollision } from '../asset/meshCollision';
+import { syncJoints3D, type Joint3DMap } from './Physics3DJoints';
import type { Entity } from '../types';
import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';
import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';
@@ -196,7 +197,8 @@ function addMeshBody(module: Physics3DWasmModule, entity: Entity,
export function stepPhysics3D(app: App, module: Physics3DWasmModule,
bodies: BodyMap, config: Physics3DConfig,
characters: BodyMap = new Map(),
- events?: Physics3DEventsData): void {
+ events?: Physics3DEventsData,
+ joints: Joint3DMap = new Map()): void {
const ppu = config.pixelsPerUnit;
moveCharacters(app, module, characters, config);
@@ -210,9 +212,16 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,
if (id !== 0) bodies.set(entity, id);
}
}
- for (const [entity, id] of bodies) {
- if (live.has(entity) && app.world.valid(entity)) continue;
- module._physics3d_removeBody(id);
+ const doomed = new Set<Entity>();
+ for (const entity of bodies.keys()) {
+ if (!live.has(entity) || !app.world.valid(entity)) doomed.add(entity);
+ }
+ // Joints first, and told what is about to go: the module holds a constraint
+ // against two bodies, so removing a body under a live joint leaves the solver
+ // holding nothing.
+ syncJoints3D(app, module, bodies, joints, ppu, doomed);
+ for (const entity of doomed) {
+ module._physics3d_removeBody(bodies.get(entity)!);
bodies.delete(entity);
}
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index 3af70ba5c..d61f95a13 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -217,7 +217,8 @@ const PHYSICS_COMPONENT_TYPES = new Set([
/** The same question for the 3D world, which is a different module entirely. */
const PHYSICS3D_COMPONENT_TYPES = new Set([
'RigidBody3D', 'BoxCollider3D', 'SphereCollider3D', 'CapsuleCollider3D',
- 'CharacterController3D',
+ 'MeshCollider3D', 'CharacterController3D',
+ 'PointJoint3D', 'HingeJoint3D', 'SliderJoint3D', 'DistanceJoint3D', 'FixedJoint3D',
]);
/** True if any entity carries a 3D physics component. */
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index e1b6df471..46982e786 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -20,6 +20,10 @@ import {
registerMeshCollision, releaseMeshCollision, extractPositions,
} from '../src/asset/meshCollision';
import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
+import {
+ PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D,
+ type Joint3DMap, type HingeJoint3DData, type SliderJoint3DData,
+} from '../src/physics3d/Physics3DJoints';
import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
import type { App } from '../src/app/app';
import type { Entity } from '../src/types';
@@ -83,6 +87,14 @@ function fakeModule(): Physics3DWasmModule & {
_physics3d_setCharacterPosition: record('setCharacterPosition'),
_physics3d_addMeshBody: record('addMeshBody'),
_physics3d_setLayerMask: record('setLayerMask'),
+ _physics3d_addPointJoint: record('addPointJoint'),
+ _physics3d_addHingeJoint: record('addHingeJoint'),
+ _physics3d_addSliderJoint: record('addSliderJoint'),
+ _physics3d_addDistanceJoint: record('addDistanceJoint'),
+ _physics3d_addFixedJoint: record('addFixedJoint'),
+ _physics3d_removeJoint: record('removeJoint'),
+ _physics3d_setJointMotor: record('setJointMotor'),
+ _physics3d_jointValue: (entity: number) => { calls.push({ name: 'jointValue', args: [entity] }); return 0.25; },
// Distinct allocations, as a real heap gives: one address for everything
// let the index write land on top of the vertex write.
_malloc: (bytes: number) => { const at = scratchTop; scratchTop += bytes; return at; },
@@ -343,6 +355,185 @@ describe('the 3D world and the ECS', () => {
stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
expect(bodies.size).toBe(0);
});
+
+ describe('joints', () => {
+ let joints: Joint3DMap;
+ beforeEach(() => { joints = new Map(); });
+
+ const stepJoints = () =>
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, new Map(),
+ undefined, joints);
+
+ /** A pair of bodies a joint can be hung between. */
+ const pair = (aPos = { x: 0, y: 0, z: 0 }, bPos = { x: 100, y: 0, z: 0 }) => {
+ const a = spawn(aPos);
+ world.insert(a, BoxCollider3D);
+ const b = spawn(bPos);
+ world.insert(b, BoxCollider3D);
+ return [a, b] as const;
+ };
+
+ it('hands the anchor over in metres, from where the entity is', () => {
+ const [a, b] = pair({ x: 200, y: 100, z: 0 });
+ world.insert(a, HingeJoint3D, { connectedEntity: b, anchor: { x: 50, y: 0, z: 0 } });
+
+ stepJoints();
+
+ const [call] = called('addHingeJoint');
+ expect(call).toBeDefined();
+ // (200 + 50, 100, 0) world units at 100 to the metre.
+ expect(call!.args.slice(3, 6)).toEqual([2.5, 1, 0]);
+ });
+
+ it('turns the anchor and the axis with the entity', () => {
+ const [a, b] = pair();
+ // A quarter turn about Z: +x becomes +y, and so does the hinge axis.
+ const half = Math.PI / 4;
+ const t = world.get(a, Transform) as TransformData;
+ t.worldRotation = { x: 0, y: 0, z: Math.sin(half), w: Math.cos(half) };
+ world.insert(a, HingeJoint3D, {
+ connectedEntity: b, anchor: { x: 100, y: 0, z: 0 }, axis: { x: 1, y: 0, z: 0 },
+ });
+
+ stepJoints();
+
+ const [call] = called('addHingeJoint');
+ const [px, py, pz, ax, ay, az] = call!.args.slice(3, 9);
+ expect(px).toBeCloseTo(0, 5);
+ expect(py).toBeCloseTo(1, 5);
+ expect(pz).toBeCloseTo(0, 5);
+ expect(ax).toBeCloseTo(0, 5);
+ expect(ay).toBeCloseTo(1, 5);
+ expect(az).toBeCloseTo(0, 5);
+ });
+
+ it('scales travel but not force', () => {
+ const [a, b] = pair();
+ world.insert(a, SliderJoint3D, {
+ connectedEntity: b, enableLimit: true,
+ lowerTranslation: -200, upperTranslation: 300,
+ enableMotor: true, motorSpeed: 150, maxMotorForce: 400,
+ });
+
+ stepJoints();
+
+ const args = called('addSliderJoint')[0]!.args;
+ expect(args.slice(10, 12)).toEqual([-2, 3]); // world units → metres
+ expect(args[13]).toBe(1.5); // speed is a length too
+ expect(args[14]).toBe(400); // force is not
+ });
+
+ it('waits for the body at the other end', () => {
+ const a = spawn();
+ world.insert(a, BoxCollider3D);
+ const b = world.spawn(); // no Transform, no body yet
+ world.insert(a, PointJoint3D, { connectedEntity: b });
+
+ stepJoints();
+ expect(called('addPointJoint')).toHaveLength(0);
+ expect(joints.size).toBe(0);
+
+ world.insert<TransformData>(b, Transform, {
+ position: { x: 100, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 }, worldPosition: { x: 100, y: 0, z: 0 },
+ worldRotation: { x: 0, y: 0, z: 0, w: 1 }, worldScale: { x: 1, y: 1, z: 1 },
+ });
+ world.insert(b, RigidBody3D);
+ world.insert(b, BoxCollider3D);
+
+ stepJoints();
+ expect(called('addPointJoint')).toHaveLength(1);
+ });
+
+ it('builds one joint per entity, the one the module keys', () => {
+ const [a, b] = pair();
+ world.insert(a, FixedJoint3D, { connectedEntity: b });
+ world.insert(a, PointJoint3D, { connectedEntity: b });
+
+ stepJoints();
+
+ expect(called('addPointJoint')).toHaveLength(1);
+ expect(called('addFixedJoint')).toHaveLength(0);
+ });
+
+ it('makes each joint once, not once per step', () => {
+ const [a, b] = pair();
+ world.insert(a, PointJoint3D, { connectedEntity: b });
+ stepJoints();
+ stepJoints();
+ stepJoints();
+ expect(called('addPointJoint')).toHaveLength(1);
+ });
+
+ it('takes the joint back when its component goes', () => {
+ const [a, b] = pair();
+ world.insert(a, PointJoint3D, { connectedEntity: b });
+ stepJoints();
+ world.remove(a, PointJoint3D);
+ stepJoints();
+
+ expect(called('removeJoint')).toHaveLength(1);
+ expect(joints.size).toBe(0);
+ });
+
+ it('takes the joint out BEFORE the body it hangs on', () => {
+ // The module holds a constraint against two bodies. A body removed
+ // while a joint still names it leaves the solver holding nothing, and
+ // nothing in a later step can notice that.
+ const [a, b] = pair();
+ world.insert(a, PointJoint3D, { connectedEntity: b });
+ stepJoints();
+ module.calls.length = 0;
+ world.remove(b, RigidBody3D);
+ stepJoints();
+
+ const removeJoint = module.calls.findIndex((c) => c.name === 'removeJoint');
+ const removeBody = module.calls.findIndex((c) => c.name === 'removeBody');
+ expect(removeJoint).toBeGreaterThanOrEqual(0);
+ expect(removeBody).toBeGreaterThanOrEqual(0);
+ expect(removeJoint).toBeLessThan(removeBody);
+ });
+
+ it('leaves a disabled joint out of the world', () => {
+ const [a, b] = pair();
+ world.insert(a, PointJoint3D, { connectedEntity: b, enabled: false });
+ stepJoints();
+ expect(called('addPointJoint')).toHaveLength(0);
+ });
+
+ it('carries a new motor speed into a joint that already exists', () => {
+ // A joint is built once. Without this, writing motorSpeed from a script
+ // would set a field nothing reads — the door never opens.
+ const [a, b] = pair();
+ const hinge = world.insert<HingeJoint3DData>(a, HingeJoint3D, {
+ connectedEntity: b, enableMotor: true, motorSpeed: 1, maxMotorTorque: 100,
+ });
+ stepJoints();
+ expect(called('setJointMotor')).toHaveLength(0); // built with it already
+
+ hinge.motorSpeed = 4;
+ stepJoints();
+ const [drive] = called('setJointMotor');
+ expect(drive!.args).toEqual([a as number, 1, 4]);
+
+ // ...and only when it changes: a call every step would fight the solver.
+ stepJoints();
+ expect(called('setJointMotor')).toHaveLength(1);
+ });
+
+ it('writes the joint state back where gameplay can read it', () => {
+ const [a, b] = pair();
+ world.insert(a, HingeJoint3D, { connectedEntity: b });
+ stepJoints();
+ expect((world.get(a, HingeJoint3D) as HingeJoint3DData).angle).toBe(0.25);
+
+ const [c, d] = pair({ x: 500, y: 0, z: 0 }, { x: 600, y: 0, z: 0 });
+ world.insert(c, SliderJoint3D, { connectedEntity: d });
+ stepJoints();
+ // An angle is an angle; travel is a length and comes back in world units.
+ expect((world.get(c, SliderJoint3D) as SliderJoint3DData).translation).toBe(25);
+ });
+ });
});
describe('a scene asks for the world it needs', () => {
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index 396bd9f4d..0bccae560 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -424,7 +424,123 @@ check('and stops at the pillars', swept != null && swept.fraction < 0.5
&& (swept.entity === LEFT || swept.entity === RIGHT),
`entity=${swept?.entity} fraction=${swept?.fraction?.toFixed(4)}`);
-// ── 11) A removed body is gone from both the sweep and the getter ───────────
+// ── 11) Joints: what holds two bodies to each other ─────────────────────────
+// Each asserts a distance the geometry fixes, not "it moved": a joint that was
+// never installed leaves a body in free fall, which is motion too.
+const HELD = (motion, gravity = 1) => [motion, gravity, 0.4, 0.4, 0, 0];
+const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
+
+// A hinge holds an arm at arm's length and lets it swing down to hang.
+const HINGE_ANCHOR = 60, HINGE_ARM = 61, HINGE_JOINT = 62;
+const hingeAnchorId = m._physics3d_addBox(HINGE_ANCHOR, 0.1, 0.1, 0.1, 300, 10, 0,
+ ...IDENTITY, ...HELD(STATIC), 0.5, 0, 0);
+const hingeArmId = m._physics3d_addBox(HINGE_ARM, 1, 0.1, 0.1, 301, 10, 0,
+ ...IDENTITY, ...HELD(DYNAMIC), 0.5, 0, 0);
+check('a hinge is made when both bodies are in the world',
+ m._physics3d_addHingeJoint(HINGE_JOINT, hingeAnchorId, hingeArmId,
+ 300, 10, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0) === 1);
+step(600);
+const arm = bodyState(hingeArmId);
+check('the arm stays one metre from the hinge', arm && near(dist(arm, { x: 300, y: 10, z: 0 }), 1, 0.05),
+ `r=${arm ? dist(arm, { x: 300, y: 10, z: 0 }).toFixed(4) : 'null'}`);
+// Hanging, not merely held: an arm the hinge failed to swing would still be at
+// x=301. The tolerance is where a damped swing goes to sleep, not a rounding.
+check('and hangs below it rather than beside it', arm && near(arm.y, 9, 0.2) && near(arm.x, 300, 0.2),
+ `y=${arm?.y.toFixed(3)} x=${arm?.x.toFixed(3)}`);
+
+// A distance joint is a rope: slack until it is not, then it holds.
+const ROPE_ANCHOR = 63, ROPE_BALL = 64, ROPE_JOINT = 65;
+const ropeAnchorId = m._physics3d_addBox(ROPE_ANCHOR, 0.1, 0.1, 0.1, 320, 20, 0,
+ ...IDENTITY, ...HELD(STATIC), 0.5, 0, 0);
+const ropeBallId = m._physics3d_addSphere(ROPE_BALL, 0.3, 320, 19, 0,
+ ...IDENTITY, ...HELD(DYNAMIC), 0.5, 0, 0);
+m._physics3d_addDistanceJoint(ROPE_JOINT, ropeAnchorId, ropeBallId,
+ 320, 20, 0, 320, 19, 0, 0, 3, 0, 0, 0);
+step(300);
+const ball = bodyState(ropeBallId);
+check('a rope stops the fall at its own length', ball && near(dist(ball, { x: 320, y: 20, z: 0 }), 3, 0.05),
+ `r=${ball ? dist(ball, { x: 320, y: 20, z: 0 }).toFixed(4) : 'null'}`);
+
+// A fixed joint: two bodies, one motion. Both fall, their offset does not change.
+const WELD_A = 66, WELD_B = 67, WELD_JOINT = 68;
+const weldAId = m._physics3d_addBox(WELD_A, 0.5, 0.5, 0.5, 340, 20, 0,
+ ...IDENTITY, ...HELD(DYNAMIC), 0.5, 0, 0);
+const weldBId = m._physics3d_addBox(WELD_B, 0.5, 0.5, 0.5, 342, 20, 0,
+ ...IDENTITY, ...HELD(DYNAMIC), 0.5, 0, 0);
+m._physics3d_addFixedJoint(WELD_JOINT, weldAId, weldBId, 0);
+step(60);
+const weldA = bodyState(weldAId);
+const weldB = bodyState(weldBId);
+check('a fixed joint keeps the offset it was made with',
+ weldA && weldB && near(weldB.x - weldA.x, 2, 0.05) && near(weldB.y - weldA.y, 0, 0.05),
+ `d=(${(weldB?.x - weldA?.x).toFixed(3)}, ${(weldB?.y - weldA?.y).toFixed(3)})`);
+check('and both of them fell', weldA && weldA.y < 19, `y=${weldA?.y.toFixed(3)}`);
+
+// A slider travels on one axis and stops at its limit.
+const RAIL = 69, CAR = 70, RAIL_JOINT = 71;
+const railId = m._physics3d_addBox(RAIL, 0.1, 0.1, 0.1, 360, 20, 0,
+ ...IDENTITY, ...HELD(STATIC), 0.5, 0, 0);
+const carId = m._physics3d_addBox(CAR, 0.5, 0.5, 0.5, 360, 19, 0,
+ ...IDENTITY, ...HELD(DYNAMIC), 0.5, 0, 0);
+m._physics3d_addSliderJoint(RAIL_JOINT, railId, carId, 360, 19, 0, 0, 1, 0,
+ 1, -2, 0, 0, 0, 0, 0);
+step(300);
+const car = bodyState(carId);
+check('a slider stops at its lower limit', car && near(car.y, 17, 0.05), `y=${car?.y.toFixed(3)}`);
+check('and does not leave its axis', car && near(car.x, 360, 0.02) && near(car.z, 0, 0.02),
+ `x=${car?.x.toFixed(3)} z=${car?.z.toFixed(3)}`);
+
+// ★ collideConnected, as two runs of the same setup. Both pairs overlap and are
+// joined by a rope far longer than the gap, so the rope pulls on neither: the
+// ONLY thing that can push them apart is contact between them.
+const KEEP_A = 72, KEEP_B = 73, KEEP_JOINT = 74;
+const PUSH_A = 75, PUSH_B = 76, PUSH_JOINT = 77;
+const keepAId = m._physics3d_addSphere(KEEP_A, 0.5, 380, 30, 0, ...IDENTITY, ...HELD(DYNAMIC, 0), 0.5, 0, 0);
+const keepBId = m._physics3d_addSphere(KEEP_B, 0.5, 380.2, 30, 0, ...IDENTITY, ...HELD(DYNAMIC, 0), 0.5, 0, 0);
+m._physics3d_addDistanceJoint(KEEP_JOINT, keepAId, keepBId,
+ 380, 30, 0, 380.2, 30, 0, 0, 5, 0, 0, 0);
+const pushAId = m._physics3d_addSphere(PUSH_A, 0.5, 390, 30, 0, ...IDENTITY, ...HELD(DYNAMIC, 0), 0.5, 0, 0);
+const pushBId = m._physics3d_addSphere(PUSH_B, 0.5, 390.2, 30, 0, ...IDENTITY, ...HELD(DYNAMIC, 0), 0.5, 0, 0);
+m._physics3d_addDistanceJoint(PUSH_JOINT, pushAId, pushBId,
+ 390, 30, 0, 390.2, 30, 0, 0, 5, 1, 0, 1);
+step(120);
+const keepGap = dist(bodyState(keepAId), bodyState(keepBId));
+const pushGap = dist(bodyState(pushAId), bodyState(pushBId));
+check('joined bodies pass through each other when the joint says so',
+ near(keepGap, 0.2, 0.05), `gap=${keepGap.toFixed(4)}`);
+check('and collide when it does not', pushGap > 0.9, `gap=${pushGap.toFixed(4)}`);
+
+// A motor drives the joint, and the joint says where it got to.
+const MOTOR_ANCHOR = 78, MOTOR_ARM = 79, MOTOR_JOINT = 80;
+const motorAnchorId = m._physics3d_addBox(MOTOR_ANCHOR, 0.1, 0.1, 0.1, 400, 10, 0,
+ ...IDENTITY, ...HELD(STATIC), 0.5, 0, 0);
+const motorArmId = m._physics3d_addBox(MOTOR_ARM, 1, 0.1, 0.1, 401, 10, 0,
+ ...IDENTITY, ...HELD(DYNAMIC, 0), 0.5, 0, 0);
+m._physics3d_addHingeJoint(MOTOR_JOINT, motorAnchorId, motorArmId, 400, 10, 0, 0, 0, 1,
+ 0, 0, 0, 1, 2, 1e7, 0);
+check('a joint with nothing turned yet reads zero', near(m._physics3d_jointValue(MOTOR_JOINT), 0, 0.02),
+ `angle=${m._physics3d_jointValue(MOTOR_JOINT).toFixed(4)}`);
+step(30);
+const driven = m._physics3d_jointValue(MOTOR_JOINT);
+// Half a second at 2 rad/s, less whatever the motor spent getting there.
+check('a motor turns the hinge at the speed it was given', driven > 0.6 && driven < 1.3,
+ `angle=${driven.toFixed(4)}`);
+// Driven the other way rather than switched off: a motor that stopped answering
+// would leave the arm coasting on the momentum it already has, which reads the
+// same as "the new speed was applied" until the sign changes.
+m._physics3d_setJointMotor(MOTOR_JOINT, 1, -2);
+step(45);
+const reversed = m._physics3d_jointValue(MOTOR_JOINT);
+check('and a new speed reaches a joint that already exists', reversed < 0.4,
+ `angle=${reversed.toFixed(4)} was=${driven.toFixed(4)}`);
+
+// Removing the joint gives the body back to gravity.
+m._physics3d_removeJoint(ROPE_JOINT, ropeAnchorId, ropeBallId);
+step(120);
+const freed = bodyState(ropeBallId);
+check('a removed joint lets go', freed && freed.y < 15, `y=${freed?.y.toFixed(3)}`);
+
+// ── 12) A removed body is gone from both the sweep and the getter ───────────
m._physics3d_removeBody(capId);
step(1);
check('a removed body leaves the readback', bodyPos(CAP) === null);
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp
new file mode 100644
index 000000000..d5806404b
--- /dev/null
+++ b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp
@@ -0,0 +1,336 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DConstraints.cpp
+ * @brief Joints: what holds two 3D bodies to each other.
+ * @details A door, a rope, a lift, a ragdoll — none of them are a body and a shape,
+ * they are two bodies and a rule about how they may move relative to each
+ * other. Five rules cover almost all of it: a point they share, an axis
+ * they turn about, an axis they slide along, a distance they keep, and no
+ * freedom at all.
+ *
+ * Anchors and axes arrive in WORLD space, taken at the moment the joint is
+ * made. That is also what sets the zero of every limit: both bodies are
+ * given the same reference axis, so "0" means the pose the scene was
+ * authored in and a door's limits read the way an author wrote them.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "./Physics3DContext.hpp"
+
+#include <Jolt/Physics/Body/BodyLock.h>
+#include <Jolt/Physics/Collision/GroupFilter.h>
+#include <Jolt/Physics/Constraints/DistanceConstraint.h>
+#include <Jolt/Physics/Constraints/FixedConstraint.h>
+#include <Jolt/Physics/Constraints/HingeConstraint.h>
+#include <Jolt/Physics/Constraints/PointConstraint.h>
+#include <Jolt/Physics/Constraints/SliderConstraint.h>
+
+#include <algorithm>
+#include <cmath>
+
+using namespace JPH;
+using esengine::physics3d::Context;
+
+namespace {
+
+Context& g() { return esengine::physics3d::ctx(); }
+
+/// Bodies in one assembly ignore each other. Jolt filters collision per body, so
+/// "this joint's two ends do not collide" can only be said as a group they share.
+class AssemblyGroupFilter final : public GroupFilter {
+public:
+ bool CanCollide(const CollisionGroup& a, const CollisionGroup& b) const override {
+ if (a.GetGroupID() == CollisionGroup::cInvalidGroup
+ || b.GetGroupID() == CollisionGroup::cInvalidGroup) {
+ return true;
+ }
+ return a.GetGroupID() != b.GetGroupID();
+ }
+};
+
+GroupFilter* assemblyFilter() {
+ static Ref<GroupFilter> instance = new AssemblyGroupFilter();
+ return instance;
+}
+
+void writeGroup(uint32_t body, uint32_t group) {
+ BodyLockWrite lock(g().system->GetBodyLockInterface(), BodyID(body));
+ if (!lock.Succeeded()) return;
+ lock.GetBody().SetCollisionGroup(group == 0
+ ? CollisionGroup()
+ : CollisionGroup(assemblyFilter(), group, static_cast<CollisionGroup::SubGroupID>(body)));
+}
+
+/// Put both bodies in one assembly, merging the groups they were already in: a
+/// chain built joint by joint has to end up as ONE group, or its first and third
+/// links would still collide.
+void joinAssembly(uint32_t a, uint32_t b) {
+ Context& c = g();
+ const auto ga = c.jointGroupOf.find(a);
+ const auto gb = c.jointGroupOf.find(b);
+ uint32_t group = 0;
+ if (ga == c.jointGroupOf.end() && gb == c.jointGroupOf.end()) {
+ group = c.nextJointGroup++;
+ } else if (ga == c.jointGroupOf.end()) {
+ group = gb->second;
+ } else if (gb == c.jointGroupOf.end()) {
+ group = ga->second;
+ } else if (ga->second != gb->second) {
+ group = ga->second;
+ const uint32_t old = gb->second;
+ for (const uint32_t member : c.jointGroupMembers[old]) {
+ c.jointGroupOf[member] = group;
+ c.jointGroupMembers[group].push_back(member);
+ writeGroup(member, group);
+ }
+ c.jointGroupMembers.erase(old);
+ } else {
+ group = ga->second;
+ }
+ for (const uint32_t body : {a, b}) {
+ if (c.jointGroupOf[body] != group || c.jointHolds[body] == 0) {
+ c.jointGroupOf[body] = group;
+ std::vector<uint32_t>& members = c.jointGroupMembers[group];
+ if (std::find(members.begin(), members.end(), body) == members.end()) {
+ members.push_back(body);
+ }
+ writeGroup(body, group);
+ }
+ c.jointHolds[body] += 1;
+ }
+}
+
+/// The reverse: a body whose last joint is gone collides with its siblings again.
+void leaveAssembly(uint32_t body) {
+ Context& c = g();
+ const auto hold = c.jointHolds.find(body);
+ if (hold == c.jointHolds.end()) return;
+ if (hold->second > 1) { hold->second -= 1; return; }
+ c.jointHolds.erase(hold);
+ const auto group = c.jointGroupOf.find(body);
+ if (group != c.jointGroupOf.end()) {
+ std::vector<uint32_t>& members = c.jointGroupMembers[group->second];
+ members.erase(std::remove(members.begin(), members.end(), body), members.end());
+ if (members.empty()) c.jointGroupMembers.erase(group->second);
+ c.jointGroupOf.erase(group);
+ }
+ writeGroup(body, 0);
+}
+
+/// Any unit vector at right angles to `v` — the reference the limits measure from.
+/// Both bodies are given the same one, so the pose at creation reads as zero.
+Vec3 perpendicularTo(Vec3Arg v) {
+ const Vec3 axis = v.NormalizedOr(Vec3::sAxisY());
+ const Vec3 other = std::abs(axis.GetY()) < 0.9f ? Vec3::sAxisY() : Vec3::sAxisX();
+ return axis.Cross(other).NormalizedOr(Vec3::sAxisX());
+}
+
+/// Register a built constraint under the entity that authored it, replacing
+/// whatever that entity had before.
+uint32_t adopt(uint32_t entity, TwoBodyConstraint* constraint,
+ uint32_t bodyA, uint32_t bodyB, int collideConnected) {
+ if (constraint == nullptr) return 0;
+ g().system->AddConstraint(constraint);
+ g().constraints[entity] = constraint;
+ if (collideConnected == 0) joinAssembly(bodyA, bodyB);
+ return 1;
+}
+
+/// Both bodies, or nothing: a joint to a body that is not in the world yet has no
+/// meaning, and the SDK retries on a later step once it is.
+bool bothLive(uint32_t bodyA, uint32_t bodyB) {
+ if (!g().isValid()) return false;
+ const BodyLockInterface& lock = g().system->GetBodyLockInterface();
+ BodyLockRead a(lock, BodyID(bodyA));
+ BodyLockRead b(lock, BodyID(bodyB));
+ return a.Succeeded() && b.Succeeded();
+}
+
+void applyMotor(MotorSettings& motor, float maxForceOrTorque) {
+ motor.mSpringSettings.mFrequency = 20.0f;
+ motor.mSpringSettings.mDamping = 1.0f;
+ motor.SetForceLimit(maxForceOrTorque);
+ motor.SetTorqueLimit(maxForceOrTorque);
+}
+
+} // namespace
+
+extern "C" {
+
+/// A shared point, free to turn on all three axes — a chain link, a ragdoll limb.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addPointJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,
+ float px, float py, float pz, int collideConnected) {
+ if (!bothLive(bodyA, bodyB)) return 0;
+ PointConstraintSettings settings;
+ settings.mSpace = EConstraintSpace::WorldSpace;
+ settings.mPoint1 = settings.mPoint2 = RVec3(px, py, pz);
+ return adopt(entity,
+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB)),
+ bodyA, bodyB, collideConnected);
+}
+
+/// One axis of rotation, optionally limited and optionally driven — a door, a
+/// lever, a wheel with a motor.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addHingeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,
+ float px, float py, float pz,
+ float ax, float ay, float az,
+ int enableLimit, float lowerAngle, float upperAngle,
+ int enableMotor, float motorSpeed, float maxTorque,
+ int collideConnected) {
+ if (!bothLive(bodyA, bodyB)) return 0;
+ const Vec3 axis = Vec3(ax, ay, az).NormalizedOr(Vec3::sAxisY());
+ const Vec3 normal = perpendicularTo(axis);
+ HingeConstraintSettings settings;
+ settings.mSpace = EConstraintSpace::WorldSpace;
+ settings.mPoint1 = settings.mPoint2 = RVec3(px, py, pz);
+ settings.mHingeAxis1 = settings.mHingeAxis2 = axis;
+ settings.mNormalAxis1 = settings.mNormalAxis2 = normal;
+ if (enableLimit != 0) {
+ settings.mLimitsMin = lowerAngle;
+ settings.mLimitsMax = upperAngle;
+ }
+ if (enableMotor != 0) applyMotor(settings.mMotorSettings, maxTorque);
+ TwoBodyConstraint* constraint =
+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB));
+ if (constraint != nullptr && enableMotor != 0) {
+ auto* hinge = static_cast<HingeConstraint*>(constraint);
+ hinge->SetMotorState(EMotorState::Velocity);
+ hinge->SetTargetAngularVelocity(motorSpeed);
+ }
+ return adopt(entity, constraint, bodyA, bodyB, collideConnected);
+}
+
+/// One axis of travel — a lift, a piston, a sliding door.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addSliderJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,
+ float px, float py, float pz,
+ float ax, float ay, float az,
+ int enableLimit, float lower, float upper,
+ int enableMotor, float motorSpeed, float maxForce,
+ int collideConnected) {
+ if (!bothLive(bodyA, bodyB)) return 0;
+ const Vec3 axis = Vec3(ax, ay, az).NormalizedOr(Vec3::sAxisY());
+ const Vec3 normal = perpendicularTo(axis);
+ SliderConstraintSettings settings;
+ settings.mSpace = EConstraintSpace::WorldSpace;
+ settings.mPoint1 = settings.mPoint2 = RVec3(px, py, pz);
+ settings.mSliderAxis1 = settings.mSliderAxis2 = axis;
+ settings.mNormalAxis1 = settings.mNormalAxis2 = normal;
+ if (enableLimit != 0) {
+ settings.mLimitsMin = lower;
+ settings.mLimitsMax = upper;
+ }
+ if (enableMotor != 0) applyMotor(settings.mMotorSettings, maxForce);
+ TwoBodyConstraint* constraint =
+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB));
+ if (constraint != nullptr && enableMotor != 0) {
+ auto* slider = static_cast<SliderConstraint*>(constraint);
+ slider->SetMotorState(EMotorState::Velocity);
+ slider->SetTargetVelocity(motorSpeed);
+ }
+ return adopt(entity, constraint, bodyA, bodyB, collideConnected);
+}
+
+/// A distance kept between two points — a rope (max only), a rod (min = max), or
+/// a spring when a frequency is given.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addDistanceJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,
+ float ax, float ay, float az,
+ float bx, float by, float bz,
+ float minLength, float maxLength,
+ float frequency, float damping,
+ int collideConnected) {
+ if (!bothLive(bodyA, bodyB)) return 0;
+ DistanceConstraintSettings settings;
+ settings.mSpace = EConstraintSpace::WorldSpace;
+ settings.mPoint1 = RVec3(ax, ay, az);
+ settings.mPoint2 = RVec3(bx, by, bz);
+ settings.mMinDistance = minLength;
+ settings.mMaxDistance = std::max(maxLength, minLength);
+ if (frequency > 0.0f) {
+ settings.mLimitsSpringSettings.mFrequency = frequency;
+ settings.mLimitsSpringSettings.mDamping = damping;
+ }
+ return adopt(entity,
+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB)),
+ bodyA, bodyB, collideConnected);
+}
+
+/// No freedom at all: the two move as one, until something breaks them apart.
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addFixedJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,
+ int collideConnected) {
+ if (!bothLive(bodyA, bodyB)) return 0;
+ FixedConstraintSettings settings;
+ // The pose the two are in right now IS the joint — an author places the pieces
+ // and the joint holds them there, rather than snapping them somewhere else.
+ settings.mAutoDetectPoint = true;
+ return adopt(entity,
+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB)),
+ bodyA, bodyB, collideConnected);
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics3d_removeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB) {
+ const auto it = g().constraints.find(entity);
+ if (it == g().constraints.end()) return;
+ g().system->RemoveConstraint(it->second);
+ g().constraints.erase(it);
+ leaveAssembly(bodyA);
+ leaveAssembly(bodyB);
+ // A body held still by a joint falls asleep, and losing the joint is not an
+ // event that wakes it: without this it hangs exactly where the joint left it.
+ BodyInterface& bodies = g().system->GetBodyInterface();
+ bodies.ActivateBody(BodyID(bodyA));
+ bodies.ActivateBody(BodyID(bodyB));
+}
+
+/// Drive an existing hinge or slider from gameplay, without rebuilding the joint.
+EMSCRIPTEN_KEEPALIVE
+void physics3d_setJointMotor(uint32_t entity, int enable, float speed) {
+ const auto it = g().constraints.find(entity);
+ if (it == g().constraints.end()) return;
+ Constraint* constraint = it->second;
+ const EMotorState state = enable != 0 ? EMotorState::Velocity : EMotorState::Off;
+ // The module is built without RTTI, so the kind comes from Jolt's own tag.
+ switch (constraint->GetSubType()) {
+ case EConstraintSubType::Hinge: {
+ auto* hinge = static_cast<HingeConstraint*>(constraint);
+ hinge->SetMotorState(state);
+ hinge->SetTargetAngularVelocity(speed);
+ break;
+ }
+ case EConstraintSubType::Slider: {
+ auto* slider = static_cast<SliderConstraint*>(constraint);
+ slider->SetMotorState(state);
+ slider->SetTargetVelocity(speed);
+ break;
+ }
+ default: break;
+ }
+}
+
+/// What the joint is at right now — a hinge's angle, a slider's travel — so a
+/// game can watch a door swing without integrating it a second time.
+EMSCRIPTEN_KEEPALIVE
+float physics3d_jointValue(uint32_t entity) {
+ const auto it = g().constraints.find(entity);
+ if (it == g().constraints.end()) return 0.0f;
+ Constraint* constraint = it->second;
+ switch (constraint->GetSubType()) {
+ case EConstraintSubType::Hinge:
+ return static_cast<HingeConstraint*>(constraint)->GetCurrentAngle();
+ case EConstraintSubType::Slider:
+ return static_cast<SliderConstraint*>(constraint)->GetCurrentPosition();
+ default: return 0.0f;
+ }
+}
+
+} // extern "C"
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
index 5beeedc55..676787d7a 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
@@ -24,6 +24,7 @@
#include <Jolt/Core/JobSystemSingleThreaded.h>
#include <Jolt/Core/TempAllocator.h>
#include <Jolt/Physics/PhysicsSystem.h>
+#include <Jolt/Physics/Constraints/TwoBodyConstraint.h>
#include <cstdint>
#include <memory>
@@ -137,6 +138,19 @@ struct Context {
/// otherwise be indistinguishable from a solid one.
std::unordered_set<uint32_t> sensorBodies;
+ /// Joints, keyed by the entity whose component authored them — one per entity,
+ /// the same ownership the 2D world uses.
+ std::unordered_map<uint32_t, JPH::Ref<JPH::TwoBodyConstraint>> constraints;
+ /// Bodies a joint asked not to collide, in groups: Jolt filters per body, not
+ /// per constraint, so the only way to say it is "these bodies are one
+ /// assembly" — and joining two assemblies has to merge their members.
+ std::unordered_map<uint32_t, uint32_t> jointGroupOf;
+ std::unordered_map<uint32_t, std::vector<uint32_t>> jointGroupMembers;
+ /// How many joints hold each body in its assembly, so a body leaves the group
+ /// when the last joint holding it goes and can collide with its siblings again.
+ std::unordered_map<uint32_t, uint32_t> jointHolds;
+ uint32_t nextJointGroup = 1;
+
/// Characters are not bodies: a CharacterVirtual is swept against the world
/// rather than solved in it, which is what lets it climb stairs and stay
/// glued to a slope without inheriting momentum from whatever it stands on.