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: add SwingTwist and SixDOF 3D joints
yhh385dcb03ed87
diff --git a/.github/workflows/editor-acceptance.yml b/.github/workflows/editor-acceptance.ymlindex b9b0b824b..e8f9913bb 100644--- a/.github/workflows/editor-acceptance.yml+++ b/.github/workflows/editor-acceptance.yml@@ -50,8 +50,8 @@ jobs:env:CHECK_NAMES: ${{ inputs.checks }}OUT: ${{ github.workspace }}/output/editor-acceptance- ELECTRON_DISABLE_SANDBOX: '1'ESTELLA_MCP_EDITOR_VISIBLE: '1'+ ELECTRON_DISABLE_SANDBOX: '1'run: |read -r -a names <<< "$CHECK_NAMES"xvfb-run -a --server-args="-screen 0 1920x1080x24" node scripts/editor-checks/run.mjs "${names[@]}"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb1751978..17c7fc8f7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **3D swing/twist and six-axis joints.** SwingTwistJoint3D adds an elliptical swing cone and twist limits; SixDOFJoint3D locks, limits or frees each translation/rotation axis. Both support live velocity motors. The existing Details controls expose degree-based authoring, and selected viewport gizmos show limits. The 3D Physics example includes a shoulder and carriage with reversible motors. Headless solver checks do not replace target-device acceptance.+## [0.92.0] - 2026-10-18### Addeddiff --git a/desktop b/desktopindex 6a0f7412a..5256fa7c0 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 6a0f7412a60ee7780df88d8319b92a1e9a489cd0+Subproject commit 5256fa7c0f50781306d801b7d369b9ae3e578bb0diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex 7f7c6a727..7752c20bf 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -412,3 +412,47 @@ straight through and shows up in `sensorEnters` instead of `contactEnters`.Nothing stops an entity carrying both sets, but nothing merges them either: the twoworlds do not see each other, and a 2D collider will never stop a 3D body. Pick oneper scene.++### Swing/twist and six-axis joints++`SwingTwistJoint3D` locks translation and limits rotation with an elliptical swing+cone and a separate twist interval. `axis` is local constraint X (twist),+`normalAxis` is its local Y reference. Directions are normalized and orthogonalized;+zero or parallel directions are rejected.++`SixDOFJoint3D` independently controls each axis using `JointMotion3D.Locked` (0),+`Limited` (1), or `Free` (2) in `translationMotion` and `rotationMotion`. Locked axes+stay at the creation pose; limited axes use the corresponding lower/upper vector;+free axes ignore those bounds. Limited lower bounds must be strictly below upper+bounds. Angular limits lie within −π to π; Y/Z rotation uses Jolt's pyramid limits.++```typescript+cmds.spawn().insert(SixDOFJoint3D, {+ connectedEntity: base,+ translationMotion: { x: JointMotion3D.Limited, y: JointMotion3D.Locked, z: JointMotion3D.Locked },+ translationLower: { x: -100, y: 0, z: 0 },+ translationUpper: { x: 100, y: 0, z: 0 },+});+```++The Inspector shows angles in degrees; files and scripts store radians. Translation+limits and linear velocity use world units and world units/s. Angular velocity is+rad/s; force and torque are N and N·m, independent of `pixelsPerUnit`.++Motors default off. `enableMotor`, `linearVelocity` (SixDOF only),+`angularVelocity`, `maxMotorForce` and `maxMotorTorque` can change while running+without rebuilding the joint. Targets describe **connected body B relative to the+owning body A**, in constraint axes. If B is static, A moves in the opposite direction.+Each motor axis shares the specified force/torque cap. This is velocity control,+not a pose servo or active ragdoll.++Changing a frame, collision setting or limit rebuilds these joints using the+current pose as zero. Disabling/removing a component releases it before its bodies+are removed. `joint3DSettingsError(settings)` reports invalid settings; invalid+joints remain uncreated instead of entering the solver with malformed limits.++The existing **3D Physics** example includes a shoulder/arm and a limited carriage.+Press **J** to reverse their motors; **F1** toggles collider debug drawing. Select+either joint in the editor to inspect its limits. Viewport limits are read-only;+edit their numbers in Details. These components are experimental. Headless Jolt+checks cover limits and motors; target-device acceptance is recorded separately.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.mdxindex bed8f5db7..ec132554b 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@@ -371,3 +371,30 @@ for (const { sensorEntity, visitorEntity } of events.sensorEnters) {没有东西阻止一个实体同时带两套组件,但也没有东西会把它们合并:两个世界互相看不见,一个 2D 碰撞体永远拦不住一个 3D 刚体。**一个场景选一套。**++### SwingTwist 与六自由度关节++`SwingTwistJoint3D` 锁定平移,用椭圆摆动锥和独立扭转区间限制旋转。+`axis` 是局部约束 X(扭转轴),`normalAxis` 是局部 Y 参考方向。+方向会归一化并正交化;零向量或平行方向无效。++`SixDOFJoint3D` 的 `translationMotion` / `rotationMotion` 每轴分别选择+`JointMotion3D.Locked`(0)、`Limited`(1)或 `Free`(2)。锁定轴保持创建姿态;+限制轴读取对应 Lower / Upper 向量,下限必须小于上限;自由轴忽略数值边界。+角度限位必须在 −π 到 π 内,Y/Z 旋转使用 Jolt 的金字塔限位。++Inspector 以度显示角度,文件和脚本仍存弧度。平移限位、线速度分别使用世界单位、+世界单位/秒;角速度为 rad/s,力和扭矩为 N、N·m,不随 `pixelsPerUnit` 缩放。++马达默认关闭。运行时修改 `enableMotor`、`linearVelocity`(仅 SixDOF)、+`angularVelocity`、`maxMotorForce`、`maxMotorTorque` 不会重建关节。+目标速度表示约束坐标系中**连接体 B 相对于声明体 A** 的速度;B 静止时,A 朝相反方向运动。+每个马达轴共享填写的力或扭矩上限。这是速度控制,不是姿态伺服或主动布娃娃。++修改参考坐标系、碰撞设置或限位会重建关节,当前姿态成为新的零点。+禁用、移除组件会在刚体移除前释放约束。+`joint3DSettingsError(settings)` 返回无效设置的原因;无效关节不会进入物理解算。++现有 **3D Physics** 示例包含肩/上臂和受限滑块。按 **J** 反转马达,**F1** 切换碰撞体调试绘制。+在编辑器选中关节即可检查限位;视口提供只读显示,通过细节面板改数值。+两种组件仍为实验性接口。无窗口 Jolt 检查覆盖限位和马达,目标设备验收另行记录。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 36927d000..a4e2235f2 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 130,- "experimental": 2228,+ "experimental": 2234,"deprecated": 3},- "total": 2473,+ "total": 2479,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 7cbdf56a9..94667f4f2 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -134,6 +134,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {MeleeAttack: { category: 'physics', summary: 'A swing whose timing is the animation’s and whose reach is the physics world’s: a `hit` beat asks what is around an animated anchor, and gameplay decides who may be hurt.', doc: 'gameplay/physics-3d', anchor: 'melee-combat', anchorZh: '近战' },Hunter: { category: 'physics', summary: 'A character that hunts what it perceives: it asks navigation for a route, the character controller for the movement, and the animator for a swing — the concrete twin of ThirdPersonController.', doc: 'gameplay/ai/overview', anchor: 'a-melee-enemy-without-writing-one', anchorZh: '不用写代码的近战敌人' },Health: { category: 'physics', summary: 'What something has left, and what makes it damageable at all — written only by the system that answers the Damage bus.', doc: 'gameplay/physics-3d', anchor: 'melee-combat', anchorZh: '近战' },+ SwingTwistJoint3D: { category: 'physics', summary: 'A ball joint with independent twist limits, an elliptical swing cone and optional angular velocity motors.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },+ SixDOFJoint3D: { category: 'physics', summary: 'Locks, limits or frees each translation and rotation axis independently, with optional velocity motors.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },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: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 9f262dbdd..31d879959 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3828,6 +3828,146 @@}]},+ {+ "name": "SixDOFJoint3D",+ "source": "ts",+ "fields": [+ {+ "key": "connectedEntity",+ "type": "Entity",+ "default": "-1"+ },+ {+ "key": "anchor",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Attachment in this entity’s local frame, in world units."+ },+ {+ "key": "axis",+ "type": "Vec3",+ "default": "(1, 0, 0)",+ "doc": "Local X/twist direction. Must be nonzero."+ },+ {+ "key": "normalAxis",+ "type": "Vec3",+ "default": "(0, 1, 0)",+ "doc": "Local Y reference. Must not be parallel to the X/twist axis."+ },+ {+ "key": "enableMotor",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "angularVelocity",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Body B relative to A, in constraint axes (rad/s)."+ },+ {+ "key": "maxMotorTorque",+ "type": "number",+ "default": "10",+ "doc": "Maximum torque per motor axis (N m).",+ "range": "≥ 0"+ },+ {+ "key": "collideConnected",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ },+ {+ "key": "translationMotion",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Each axis: 0 locked, 1 limited, 2 free."+ },+ {+ "key": "rotationMotion",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Each axis: 0 locked, 1 limited, 2 free."+ },+ {+ "key": "translationLower",+ "type": "Vec3",+ "default": "(-100, -100, -100)"+ },+ {+ "key": "translationUpper",+ "type": "Vec3",+ "default": "(100, 100, 100)"+ },+ {+ "key": "rotationLower",+ "type": "Vec3",+ "default": "(-0.5236, -0.5236, -0.5236)"+ },+ {+ "key": "rotationUpper",+ "type": "Vec3",+ "default": "(0.5236, 0.5236, 0.5236)"+ },+ {+ "key": "linearVelocity",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Body B relative to A, in constraint axes (world units/s)."+ },+ {+ "key": "maxMotorForce",+ "type": "number",+ "default": "100",+ "doc": "Maximum force per translation axis (N).",+ "range": "≥ 0"+ }+ ],+ "animatable": [+ "connectedEntity",+ "anchor.x",+ "anchor.y",+ "anchor.z",+ "axis.x",+ "axis.y",+ "axis.z",+ "normalAxis.x",+ "normalAxis.y",+ "normalAxis.z",+ "angularVelocity.x",+ "angularVelocity.y",+ "angularVelocity.z",+ "maxMotorTorque",+ "translationMotion.x",+ "translationMotion.y",+ "translationMotion.z",+ "rotationMotion.x",+ "rotationMotion.y",+ "rotationMotion.z",+ "translationLower.x",+ "translationLower.y",+ "translationLower.z",+ "translationUpper.x",+ "translationUpper.y",+ "translationUpper.z",+ "rotationLower.x",+ "rotationLower.y",+ "rotationLower.z",+ "rotationUpper.x",+ "rotationUpper.y",+ "rotationUpper.z",+ "linearVelocity.x",+ "linearVelocity.y",+ "linearVelocity.z",+ "maxMotorForce"+ ]+ },{"name": "SliderJoint2D","source": "ts",@@ -4430,6 +4570,107 @@"cellSize"]},+ {+ "name": "SwingTwistJoint3D",+ "source": "ts",+ "fields": [+ {+ "key": "connectedEntity",+ "type": "Entity",+ "default": "-1"+ },+ {+ "key": "anchor",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Attachment in this entity’s local frame, in world units."+ },+ {+ "key": "axis",+ "type": "Vec3",+ "default": "(0, 1, 0)",+ "doc": "Local X/twist direction. Must be nonzero."+ },+ {+ "key": "normalAxis",+ "type": "Vec3",+ "default": "(1, 0, 0)",+ "doc": "Local Y reference. Must not be parallel to the X/twist axis."+ },+ {+ "key": "enableMotor",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "angularVelocity",+ "type": "Vec3",+ "default": "(0, 0, 0)",+ "doc": "Body B relative to A, in constraint axes (rad/s)."+ },+ {+ "key": "maxMotorTorque",+ "type": "number",+ "default": "10",+ "doc": "Maximum torque per motor axis (N m).",+ "range": "≥ 0"+ },+ {+ "key": "collideConnected",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ },+ {+ "key": "normalHalfConeAngle",+ "type": "number",+ "default": "0.7854",+ "range": "0–3.1416"+ },+ {+ "key": "planeHalfConeAngle",+ "type": "number",+ "default": "0.7854",+ "range": "0–3.1416"+ },+ {+ "key": "twistMinAngle",+ "type": "number",+ "default": "-0.5236",+ "range": "-3.1416–3.1416"+ },+ {+ "key": "twistMaxAngle",+ "type": "number",+ "default": "0.5236",+ "range": "-3.1416–3.1416"+ }+ ],+ "animatable": [+ "connectedEntity",+ "anchor.x",+ "anchor.y",+ "anchor.z",+ "axis.x",+ "axis.y",+ "axis.z",+ "normalAxis.x",+ "normalAxis.y",+ "normalAxis.z",+ "angularVelocity.x",+ "angularVelocity.y",+ "angularVelocity.z",+ "maxMotorTorque",+ "normalHalfConeAngle",+ "planeHalfConeAngle",+ "twistMinAngle",+ "twistMaxAngle"+ ]+ },{"name": "Text","source": "ts",diff --git a/examples/physics-3d/README.md b/examples/physics-3d/README.mdnew file mode 100644index 000000000..13e192157--- /dev/null+++ b/examples/physics-3d/README.md@@ -0,0 +1,21 @@+# 3D Physics++A playable Jolt workshop with a character, crates, a hinged door, ropes, welded+bodies, a lift, and authored SwingTwist / SixDOF joints. Shapes use the runtime+physics debug overlay; no additional character or model assets are required.++- WASD / arrows: walk; Space: jump; F1: toggle shape drawing.+- J: reverse the shoulder and carriage motors without rebuilding their joints.+- Select UpperArm or SixDOFCarriage in the editor to edit their limits and motors.+ The viewport displays read-only limits; Inspector angles are degrees while+ serialized angles remain radians.++The shoulder's elliptical cone limits are 0.5 / 0.7 radians with twist ±0.35.+The carriage translates ±100 world units along X and rotates ±0.3 radians around+Y; other axes are locked. Both motors start enabled for demonstration. A newly+added joint component defaults to motors off.++`node tools/check-physics3d.mjs` exercises actual Jolt bounds and motor reversal.+SDK tests cover unit conversion, rebuilding and lifecycle; editor checks run in+CI. Headless software results do not constitute native or physical-device+acceptance. Export through the existing project build command.diff --git a/examples/physics-3d/assets/scenes/main.esscene b/examples/physics-3d/assets/scenes/main.essceneindex 39d0f609c..1489b9aa8 100644--- a/examples/physics-3d/assets/scenes/main.esscene+++ b/examples/physics-3d/assets/scenes/main.esscene@@ -1697,6 +1697,236 @@}}]+ },+ {+ "id": 70,+ "name": "Shoulder",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -260,+ "y": 300,+ "z": 150+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 0,+ "gravityScale": 0,+ "linearDamping": 0.1,+ "angularDamping": 0.1+ }+ },+ {+ "type": "BoxCollider3D",+ "data": {+ "halfExtents": {+ "x": 20,+ "y": 20,+ "z": 20+ }+ }+ }+ ]+ },+ {+ "id": 71,+ "name": "UpperArm",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -260,+ "y": 240,+ "z": 150+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 2,+ "gravityScale": 0,+ "linearDamping": 0.1,+ "angularDamping": 0.1+ }+ },+ {+ "type": "CapsuleCollider3D",+ "data": {+ "radius": 16,+ "halfHeight": 40+ }+ },+ {+ "type": "SwingTwistJoint3D",+ "data": {+ "connectedEntity": 70,+ "anchor": {+ "x": 0,+ "y": 60,+ "z": 0+ },+ "axis": {+ "x": 0,+ "y": -1,+ "z": 0+ },+ "normalAxis": {+ "x": 1,+ "y": 0,+ "z": 0+ },+ "normalHalfConeAngle": 0.5,+ "planeHalfConeAngle": 0.7,+ "twistMinAngle": -0.35,+ "twistMaxAngle": 0.35,+ "enableMotor": true,+ "angularVelocity": {+ "x": 0,+ "y": 0,+ "z": 0.8+ },+ "maxMotorTorque": 100+ }+ }+ ]+ },+ {+ "id": 72,+ "name": "SliderBase",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 300,+ "y": 180,+ "z": 150+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 0,+ "gravityScale": 0,+ "linearDamping": 0.1,+ "angularDamping": 0.1+ }+ },+ {+ "type": "BoxCollider3D",+ "data": {+ "halfExtents": {+ "x": 20,+ "y": 20,+ "z": 20+ }+ }+ }+ ]+ },+ {+ "id": 73,+ "name": "SixDOFCarriage",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 300,+ "y": 180,+ "z": 150+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 2,+ "gravityScale": 0,+ "linearDamping": 0.1,+ "angularDamping": 0.1+ }+ },+ {+ "type": "BoxCollider3D",+ "data": {+ "halfExtents": {+ "x": 28,+ "y": 18,+ "z": 24+ }+ }+ },+ {+ "type": "SixDOFJoint3D",+ "data": {+ "connectedEntity": 72,+ "translationMotion": {+ "x": 1,+ "y": 0,+ "z": 0+ },+ "translationLower": {+ "x": -100,+ "y": 0,+ "z": 0+ },+ "translationUpper": {+ "x": 100,+ "y": 0,+ "z": 0+ },+ "rotationMotion": {+ "x": 0,+ "y": 1,+ "z": 0+ },+ "rotationLower": {+ "x": 0,+ "y": -0.3,+ "z": 0+ },+ "rotationUpper": {+ "x": 0,+ "y": 0.3,+ "z": 0+ },+ "enableMotor": true,+ "linearVelocity": {+ "x": 120,+ "y": 0,+ "z": 0+ },+ "angularVelocity": {+ "x": 0,+ "y": 0.4,+ "z": 0+ },+ "maxMotorForce": 500,+ "maxMotorTorque": 100+ }+ }+ ]}]}diff --git a/examples/physics-3d/src/main.ts b/examples/physics-3d/src/main.tsindex 59b0463a1..f20686e95 100644--- a/examples/physics-3d/src/main.ts+++ b/examples/physics-3d/src/main.ts@@ -1,6 +1,6 @@import { addSystemToSchedule, Schedule } from 'esengine';-import { controlSystem, debugToggleSystem, showShapesSystem } from './systems/control';+import { controlSystem, debugToggleSystem, showShapesSystem, reverseJointMotorsSystem } from './systems/control';import { cameraFollowSystem } from './systems/camera';// The 3D world itself needs no wiring: a scene carrying 3D components gets it.@@ -8,3 +8,5 @@ addSystemToSchedule(Schedule.Startup, showShapesSystem);addSystemToSchedule(Schedule.Update, controlSystem);addSystemToSchedule(Schedule.Update, debugToggleSystem);addSystemToSchedule(Schedule.Update, cameraFollowSystem);++addSystemToSchedule(Schedule.Update, reverseJointMotorsSystem);diff --git a/examples/physics-3d/src/systems/control.ts b/examples/physics-3d/src/systems/control.tsindex 69551eb4f..d4cdd78cc 100644--- a/examples/physics-3d/src/systems/control.ts+++ b/examples/physics-3d/src/systems/control.ts@@ -1,6 +1,6 @@import {defineSystem, Query, Mut, Res, ResMut, Input,- CharacterController3D, Physics3DDebugDraw,+ CharacterController3D, Physics3DDebugDraw, SwingTwistJoint3D, SixDOFJoint3D,} from 'esengine';const WALK_SPEED = 320;@@ -49,3 +49,17 @@ export const debugToggleSystem = defineSystem(},{ name: 'DebugToggleSystem' },);++/** Reverse the example's live motors without rebuilding their reference frames. */+export const reverseJointMotorsSystem = defineSystem(+ [Query(Mut(SwingTwistJoint3D)), Query(Mut(SixDOFJoint3D)), Res(Input)],+ (swings, sixes, input) => {+ if (!input.isKeyPressed('KeyJ')) return;+ for (const [, joint] of swings) joint.angularVelocity.z = -joint.angularVelocity.z;+ for (const [, joint] of sixes) {+ joint.linearVelocity.x = -joint.linearVelocity.x;+ joint.angularVelocity.y = -joint.angularVelocity.y;+ }+ },+ { name: 'ReverseJointMotors' },+);diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex a0e66601e..49fe024a7 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -49,7 +49,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>physics3d: ['RigidBody3D', 'BoxCollider3D', 'SphereCollider3D', 'CapsuleCollider3D','MeshCollider3D', 'ConvexCollider3D', 'CharacterController3D',- 'HingeJoint3D', 'DistanceJoint3D', 'SliderJoint3D', 'FixedJoint3D', 'PointJoint3D',+ 'HingeJoint3D', 'DistanceJoint3D', 'SliderJoint3D', 'FixedJoint3D', 'PointJoint3D', 'SwingTwistJoint3D', 'SixDOFJoint3D',],spine: ['SpineAnimation'],dragonbones: ['DragonBonesAnimation'],diff --git a/pipeline/tests/export-side-modules.test.ts b/pipeline/tests/export-side-modules.test.tsindex d88a87d0d..12bdc66ce 100644--- a/pipeline/tests/export-side-modules.test.ts+++ b/pipeline/tests/export-side-modules.test.ts@@ -175,8 +175,8 @@ describe('web package side modules', () => {// Joints and mesh colliders are 3D physics components like the bodies are;// the scan answers for every type the runtime's own gate counts.- it('carries the 3D solver for a joint, not only for a body', async () => {- const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'HingeJoint3D', data: {} }) });+ it.each(['HingeJoint3D', 'SwingTwistJoint3D', 'SixDOFJoint3D'])('carries the 3D solver for %s, not only for a body', async (type) => {+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type, data: {} }) });try {await run(f);expect(shipped(f.out)).toEqual(['physics3d']);diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 58f710da6..2e50102c5 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: 115 public · 118 beta · 1604 experimental · 3 deprecated+Symbols: 115 public · 118 beta · 1610 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4617,9 +4617,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## JointResolver — type @experimental```(root: Entity, path: string) => Entity | null@@ -7959,6 +7965,32 @@ Local = 1World = 0```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SkeletalFieldMeta — interface @public```atlasField: string@@ -8694,6 +8726,28 @@ phase: SubsystemPhasephaseAgeMs: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## SwipeDirection — type @experimental```'left' | 'right' | 'up' | 'down'@@ -12163,6 +12217,11 @@ InputRouter(): boolean```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## layerFrontness — function @experimental```(order: LayerOrder, worldY: number, worldZ: number): numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b27500b27..c57ec0f8b 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: 115 public · 123 beta · 1623 experimental · 3 deprecated+Symbols: 115 public · 123 beta · 1629 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -4625,9 +4625,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## JointResolver — type @experimental```(root: Entity, path: string) => Entity | null@@ -8172,6 +8178,32 @@ Local = 1World = 0```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SkeletalFieldMeta — interface @public```atlasField: string@@ -8907,6 +8939,28 @@ phase: SubsystemPhasephaseAgeMs: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## SwipeDirection — type @experimental```'left' | 'right' | 'up' | 'down'@@ -12426,6 +12480,11 @@ InputRouter(): boolean```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## layerFrontness — function @experimental```(order: LayerOrder, worldY: number, worldZ: number): numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 3c189da9c..9ffb9fdbf 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: 115 public · 120 beta · 1603 experimental · 3 deprecated+Symbols: 115 public · 120 beta · 1609 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4612,9 +4612,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## JointResolver — type @experimental```(root: Entity, path: string) => Entity | null@@ -7954,6 +7960,32 @@ Local = 1World = 0```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SkeletalFieldMeta — interface @public```atlasField: string@@ -8689,6 +8721,28 @@ phase: SubsystemPhasephaseAgeMs: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## SwipeDirection — type @experimental```'left' | 'right' | 'up' | 'down'@@ -12158,6 +12212,11 @@ InputRouter(): boolean```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## layerFrontness — function @experimental```(order: LayerOrder, worldY: number, worldZ: number): numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex bc1f8adad..682021373 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: 115 public · 118 beta · 1625 experimental · 3 deprecated+Symbols: 115 public · 118 beta · 1631 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4612,9 +4612,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## JointResolver — type @experimental```(root: Entity, path: string) => Entity | null@@ -8247,6 +8253,32 @@ Local = 1World = 0```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SkeletalFieldMeta — interface @public```atlasField: string@@ -8982,6 +9014,28 @@ phase: SubsystemPhasephaseAgeMs: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## SwipeDirection — type @experimental```'left' | 'right' | 'up' | 'down'@@ -12472,6 +12526,11 @@ InputRouter(): boolean```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## layerFrontness — function @experimental```(order: LayerOrder, worldY: number, worldZ: number): numberdiff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.mdindex 7e0bd358d..943574bd5 100644--- a/sdk/etc/physics3d.api.md+++ b/sdk/etc/physics3d.api.md@@ -1,7 +1,7 @@# API surface — esengine/physics3d<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 58 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 64 experimental · 0 deprecated## BoxCollider3D — const @experimental```@@ -181,9 +181,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## MeshCollider3D — const @experimental```BuiltinComponentDef<MeshCollider3DData>@@ -300,8 +306,10 @@ _physics3d_addFixedJoint: (entity: number, bodyA: number, bodyB: number, collide_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_addMeshBody: (entity: number, vertexPtr: number, vertexCount: number, indexPtr: number, indexCount: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, layer: number, friction: number, restitution: number) => number_physics3d_addPointJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, collideConnected: number) => number+_physics3d_addSixDOFJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, nx: number, ny: number, nz: number, translationMotion: number, rotationMotion: number, lx: number, ly: number, lz: number, hx: number, hy: number, hz: number, rx: number, ry: number, rz: number, sx: number, sy: number, sz: 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_addSphere: (entity: number, radius: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number) => number+_physics3d_addSwingTwistJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, nx: number, ny: number, nz: number, normalHalf: number, planeHalf: number, twistMin: number, twistMax: number, collideConnected: number) => number_physics3d_contactEnters: () => number_physics3d_contactEntersBytes: () => number_physics3d_contactExits: () => number@@ -324,6 +332,7 @@ _physics3d_sensorEnters: () => number_physics3d_sensorEntersBytes: () => number_physics3d_sensorExits: () => number_physics3d_sensorExitsBytes: () => number+_physics3d_setAdvancedJointMotor: (entity: number, enable: number, vx: number, vy: number, vz: number, wx: number, wy: number, wz: number, maxForce: number, maxTorque: number) => void_physics3d_setCharacterPosition: (characterId: number, px: number, py: number, pz: number) => void_physics3d_setJointMotor: (entity: number, enable: number, speed: number) => void_physics3d_setLayerMask: (layer: number, mask: number) => void@@ -372,6 +381,32 @@ sensorEntity: numbervisitorEntity: number```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SliderJoint3D — const @experimental```ComponentDef<SliderJoint3DData>@@ -407,6 +442,28 @@ radius: numberrestitution: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## assertPhysics3DContract — function @experimental```(module: unknown): void@@ -427,6 +484,11 @@ restitution: number(app: App, contacts?: readonly Contact3D[]): void```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## loadPhysics3DModule — function @experimental```(url: string, factory?: Physics3DModuleFactory): Promise<Physics3DWasmModule>diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 84c7097d0..e74c26962 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: 115 public · 118 beta · 1616 experimental · 3 deprecated+Symbols: 115 public · 118 beta · 1622 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -4619,9 +4619,15 @@ axis: Vec3 | nullconnectedAnchor: Vec3 | nullconnectedEntity: numberenabled: boolean+limits: SwingTwistJoint3DData | SixDOFJoint3DData | undefinedtype: string```+## JointMotion3D — const @experimental+```+{ readonly Locked: 0; readonly Limited: 1; readonly Free: 2; }+```+## JointResolver — type @experimental```(root: Entity, path: string) => Entity | null@@ -7961,6 +7967,32 @@ Local = 1World = 0```+## SixDOFJoint3D — const @experimental+```+ComponentDef<SixDOFJoint3DData>+```++## SixDOFJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+linearVelocity: Vec3+maxMotorForce: number+maxMotorTorque: number+normalAxis: Vec3+rotationLower: Vec3+rotationMotion: Vec3+rotationUpper: Vec3+translationLower: Vec3+translationMotion: Vec3+translationUpper: Vec3+```+## SkeletalFieldMeta — interface @public```atlasField: string@@ -8696,6 +8728,28 @@ phase: SubsystemPhasephaseAgeMs: number```+## SwingTwistJoint3D — const @experimental+```+ComponentDef<SwingTwistJoint3DData>+```++## SwingTwistJoint3DData — interface @experimental+```+anchor: Vec3+angularVelocity: Vec3+axis: Vec3+collideConnected: boolean+connectedEntity: number+enableMotor: boolean+enabled: boolean+maxMotorTorque: number+normalAxis: Vec3+normalHalfConeAngle: number+planeHalfConeAngle: number+twistMaxAngle: number+twistMinAngle: number+```+## SwipeDirection — type @experimental```'left' | 'right' | 'up' | 'down'@@ -12199,6 +12253,11 @@ InputRouter(): boolean```+## joint3DSettingsError — function @experimental+```+(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null+```+## layerFrontness — function @experimental```(order: LayerOrder, worldY: number, worldZ: number): numberdiff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex 393a061f4..ca4298073 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -231,11 +231,13 @@ export {SliderJoint3D,DistanceJoint3D,FixedJoint3D,+ SwingTwistJoint3D, SixDOFJoint3D, JointMotion3D, joint3DSettingsError,type PointJoint3DData,type HingeJoint3DData,type SliderJoint3DData,type DistanceJoint3DData,type FixedJoint3DData,+ type SwingTwistJoint3DData, type SixDOFJoint3DData,readJoint3D,type Joint3DShape,} from './physics3d/Physics3DJoints';diff --git a/sdk/src/physics3d/AdvancedJoint3D.ts b/sdk/src/physics3d/AdvancedJoint3D.tsnew file mode 100644index 000000000..691de0a03--- /dev/null+++ b/sdk/src/physics3d/AdvancedJoint3D.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** @file Swing/twist and per-axis constraints, authored in a body's local frame. */+import { defineComponent, type FieldMeta } from '../ecs/component';+import type { Vec3 } from '../types';++/** Axis motion for SixDOF joints. @experimental */+export const JointMotion3D = { Locked: 0, Limited: 1, Free: 2 } as const;++interface JointFrame3D {+ connectedEntity: number;+ anchor: Vec3;+ axis: Vec3;+ normalAxis: Vec3;+ enableMotor: boolean;+ /** Body B's target angular velocity relative to A, in constraint axes, rad/s. */+ angularVelocity: Vec3;+ maxMotorTorque: number;+ collideConnected: boolean;+ enabled: boolean;+}++/** Shoulder/hip rotation about a twist axis with an elliptical swing cone. @experimental */+export interface SwingTwistJoint3DData extends JointFrame3D {+ normalHalfConeAngle: number;+ planeHalfConeAngle: number;+ twistMinAngle: number;+ twistMaxAngle: number;+}++/** Translation is in world units; angles are radians. Zero is the creation pose. @experimental */+export interface SixDOFJoint3DData extends JointFrame3D {+ /** X/Y/Z: JointMotion3D.Locked, Limited or Free. */+ translationMotion: Vec3;+ rotationMotion: Vec3;+ translationLower: Vec3;+ translationUpper: Vec3;+ rotationLower: Vec3;+ rotationUpper: Vec3;+ /** Body B's target velocity relative to A, in constraint axes, world units/s. */+ linearVelocity: Vec3;+ maxMotorForce: number;+}++const frame = {+ connectedEntity: -1, anchor: { x: 0, y: 0, z: 0 },+ axis: { x: 1, y: 0, z: 0 }, normalAxis: { x: 0, y: 1, z: 0 },+ enableMotor: false, angularVelocity: { x: 0, y: 0, z: 0 },+ maxMotorTorque: 10, collideConnected: false, enabled: true,+};+const fields: Record<string, FieldMeta> = {+ anchor: { tooltip: 'Attachment in this entity’s local frame, in world units.' },+ axis: { category: 'Reference Frame', tooltip: 'Local X/twist direction. Must be nonzero.' },+ normalAxis: { category: 'Reference Frame', tooltip: 'Local Y reference. Must not be parallel to the X/twist axis.' },+ enableMotor: { category: 'Motor' },+ angularVelocity: { category: 'Motor', tooltip: 'Body B relative to A, in constraint axes (rad/s).' },+ maxMotorTorque: { category: 'Motor', min: 0, tooltip: 'Maximum torque per motor axis (N m).' },+ collideConnected: { category: 'Collision' },+};++/** A limited ball joint with separate twist limits. Angles are radians. @experimental */+export const SwingTwistJoint3D = defineComponent<SwingTwistJoint3DData>('SwingTwistJoint3D', {+ ...frame, axis: { x: 0, y: 1, z: 0 }, normalAxis: { x: 1, y: 0, z: 0 }, normalHalfConeAngle: Math.PI / 4, planeHalfConeAngle: Math.PI / 4,+ twistMinAngle: -Math.PI / 6, twistMaxAngle: Math.PI / 6,+}, { entityFields: ['connectedEntity'], fields: {+ ...fields,+ normalHalfConeAngle: { category: 'Swing Limits', min: 0, max: Math.PI },+ planeHalfConeAngle: { category: 'Swing Limits', min: 0, max: Math.PI },+ twistMinAngle: { category: 'Twist Limits', min: -Math.PI, max: Math.PI },+ twistMaxAngle: { category: 'Twist Limits', min: -Math.PI, max: Math.PI },+} });++/** Six axes independently locked, limited or free; optional velocity motors. @experimental */+export const SixDOFJoint3D = defineComponent<SixDOFJoint3DData>('SixDOFJoint3D', {+ ...frame,+ translationMotion: { x: 0, y: 0, z: 0 }, rotationMotion: { x: 0, y: 0, z: 0 },+ translationLower: { x: -100, y: -100, z: -100 }, translationUpper: { x: 100, y: 100, z: 100 },+ rotationLower: { x: -Math.PI / 6, y: -Math.PI / 6, z: -Math.PI / 6 },+ rotationUpper: { x: Math.PI / 6, y: Math.PI / 6, z: Math.PI / 6 },+ linearVelocity: { x: 0, y: 0, z: 0 }, maxMotorForce: 100,+}, { entityFields: ['connectedEntity'], fields: {+ ...fields,+ translationMotion: { category: 'Translation Limits', tooltip: 'Each axis: 0 locked, 1 limited, 2 free.' },+ translationLower: { category: 'Translation Limits' }, translationUpper: { category: 'Translation Limits' },+ rotationMotion: { category: 'Rotation Limits', tooltip: 'Each axis: 0 locked, 1 limited, 2 free.' },+ rotationLower: { category: 'Rotation Limits' }, rotationUpper: { category: 'Rotation Limits' },+ linearVelocity: { category: 'Motor', tooltip: 'Body B relative to A, in constraint axes (world units/s).' },+ maxMotorForce: { category: 'Motor', min: 0, tooltip: 'Maximum force per translation axis (N).' },+} });++const axes = ['x', 'y', 'z'] as const;+const finiteVec = (v: Vec3) => v && axes.every((a) => Number.isFinite(v[a]));++/** Returns an explanation for invalid settings, or null when they are valid. @experimental */+export function joint3DSettingsError(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | null {+ if (![d.anchor, d.axis, d.normalAxis, d.angularVelocity].every(finiteVec)) return 'Joint vectors must be finite.';+ const x = d.axis, y = d.normalAxis;+ const cross = Math.hypot(x.y * y.z - x.z * y.y, x.z * y.x - x.x * y.z, x.x * y.y - x.y * y.x);+ const nx = Math.hypot(x.x, x.y, x.z), ny = Math.hypot(y.x, y.y, y.z);+ const scale = nx * ny;+ if (nx < 1e-6 || ny < 1e-6 || !Number.isFinite(scale) || cross / scale < 1e-5) return 'Reference directions must be nonzero and not parallel.';+ if (!Number.isFinite(d.maxMotorTorque) || d.maxMotorTorque < 0) return 'Motor torque must be finite and nonnegative.';+ if ('translationMotion' in d) {+ if (![d.translationMotion, d.rotationMotion, d.translationLower, d.translationUpper,+ d.rotationLower, d.rotationUpper, d.linearVelocity].every(finiteVec)) return 'Axis settings must be finite.';+ if (!Number.isFinite(d.maxMotorForce) || d.maxMotorForce < 0) return 'Motor force must be finite and nonnegative.';+ for (const a of axes) {+ for (const rotation of [false, true]) {+ const mode = (rotation ? d.rotationMotion : d.translationMotion)[a];+ if (![0, 1, 2].includes(mode)) return 'Axis motion must be Locked, Limited or Free.';+ if (mode !== 1) continue;+ const lo = (rotation ? d.rotationLower : d.translationLower)[a];+ const hi = (rotation ? d.rotationUpper : d.translationUpper)[a];+ if (lo >= hi) return 'A limited axis needs a lower bound below its upper bound.';+ if (rotation && (lo < -Math.PI || hi > Math.PI)) return 'Rotation limits must lie within −π to π.';+ }+ }+ } else {+ if (![d.normalHalfConeAngle, d.planeHalfConeAngle].every((v) => Number.isFinite(v) && v >= 0 && v <= Math.PI)) {+ return 'Swing half angles must lie within 0 to π.';+ }+ if (!Number.isFinite(d.twistMinAngle) || !Number.isFinite(d.twistMaxAngle)+ || d.twistMinAngle < -Math.PI || d.twistMaxAngle > Math.PI || d.twistMinAngle > d.twistMaxAngle) {+ return 'Twist limits must be ordered within −π to π.';+ }+ }+ return null;+}++/** Constraint frame/settings changes rebuild; changing motors does not reset the reference pose. */+export function advancedJointSettings(d: SwingTwistJoint3DData | SixDOFJoint3DData): string {+ const { enableMotor: _enable, angularVelocity: _angular, maxMotorTorque: _torque, ...rest } = d;+ if ('linearVelocity' in rest) {+ const { linearVelocity: _linear, maxMotorForce: _force, ...settings } = rest;+ return JSON.stringify(settings);+ }+ return JSON.stringify(rest);+}++export function jointMotionBits(motion: Vec3): number {+ return motion.x | (motion.y << 2) | (motion.z << 4);+}diff --git a/sdk/src/physics3d/Physics3DJoints.ts b/sdk/src/physics3d/Physics3DJoints.tsindex dc61bf2ac..e2edaa70c 100644--- a/sdk/src/physics3d/Physics3DJoints.ts+++ b/sdk/src/physics3d/Physics3DJoints.ts@@ -20,6 +20,10 @@ import type { World } from '../ecs/world';import type { Entity, Vec3 } from '../types';import type { Physics3DWasmModule } from './Physics3DModule';import { rotateVec3ByQuat } from './ColliderShape3D';+import { SwingTwistJoint3D, SixDOFJoint3D, joint3DSettingsError, advancedJointSettings, jointMotionBits,+ type SwingTwistJoint3DData, type SixDOFJoint3DData } from './AdvancedJoint3D';+export { SwingTwistJoint3D, SixDOFJoint3D, JointMotion3D, joint3DSettingsError,+ type SwingTwistJoint3DData, type SixDOFJoint3DData } from './AdvancedJoint3D';export interface PointJoint3DData {connectedEntity: number;@@ -174,7 +178,7 @@ export const FixedJoint3D = defineComponent<FixedJoint3DData>('FixedJoint3D', {/** The joint components, in the order the system offers an entity's to the world. */export const JOINT3D_TYPES = [- PointJoint3D, HingeJoint3D, SliderJoint3D, DistanceJoint3D, FixedJoint3D,+ PointJoint3D, HingeJoint3D, SliderJoint3D, DistanceJoint3D, FixedJoint3D, SwingTwistJoint3D, SixDOFJoint3D,] as const;/** What the world holds for one joint: the two bodies it was built between, which@@ -188,6 +192,8 @@ export interface Joint3DRecord {* gameplay actually changed it. */motorOn: boolean;motorSpeed: number;+ settings?: string;+ motorSettings?: string;}export type Joint3DMap = Map<Entity, Joint3DRecord>;@@ -195,7 +201,7 @@ 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+/** An entity's joint: the FIRST of the joint components 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 {@@ -220,6 +226,7 @@ export interface Joint3DShape {/** The axis a hinge turns about or a slider travels along. */axis: Vec3 | null;enabled: boolean;+ limits?: SwingTwistJoint3DData | SixDOFJoint3DData;}/**@@ -237,6 +244,7 @@ export function readJoint3D(world: World, entity: number): Joint3DShape | null {connectedAnchor: (d.connectedAnchor as Vec3 | undefined) ?? null,axis: (d.axis as Vec3 | undefined) ?? null,enabled: d.enabled !== false,+ limits: def === SwingTwistJoint3D || def === SixDOFJoint3D ? d as unknown as SwingTwistJoint3DData | SixDOFJoint3DData : undefined,};}return null;@@ -268,6 +276,24 @@ function build(app: App, module: Physics3DWasmModule, entity: Entity,const collide = (raw as AnyJoint).collideConnected ? 1 : 0;const e = entity as number;+ if (def === SwingTwistJoint3D || def === SixDOFJoint3D) {+ const d = raw as SwingTwistJoint3DData | SixDOFJoint3DData;+ if (joint3DSettingsError(d)) return false;+ const a = anchorInMetres(app, entity, d.anchor, ppu);+ const x = axisInWorld(app, entity, d.axis), y = axisInWorld(app, entity, d.normalAxis);+ if ('translationMotion' in d) {+ const lo = d.translationLower, hi = d.translationUpper;+ const rl = d.rotationLower, rh = d.rotationUpper;+ return module._physics3d_addSixDOFJoint(e, bodyA, bodyB, a.x, a.y, a.z,+ x.x, x.y, x.z, y.x, y.y, y.z,+ jointMotionBits(d.translationMotion), jointMotionBits(d.rotationMotion),+ lo.x / ppu, lo.y / ppu, lo.z / ppu, hi.x / ppu, hi.y / ppu, hi.z / ppu,+ rl.x, rl.y, rl.z, rh.x, rh.y, rh.z, collide) !== 0;+ }+ return module._physics3d_addSwingTwistJoint(e, bodyA, bodyB, a.x, a.y, a.z,+ x.x, x.y, x.z, y.x, y.y, y.z, d.normalHalfConeAngle, d.planeHalfConeAngle,+ d.twistMinAngle, d.twistMaxAngle, collide) !== 0;+ }if (def === PointJoint3D) {const d = raw as PointJoint3DData;const a = anchorInMetres(app, entity, d.anchor, ppu);@@ -319,7 +345,10 @@ export function syncJoints3D(app: App, module: Physics3DWasmModule,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+ const advanced = joint && (joint.def === SwingTwistJoint3D || joint.def === SixDOFJoint3D)+ ? joint.data as SwingTwistJoint3DData | SixDOFJoint3DData : null;+ const stillRight = (!advanced || (!joint3DSettingsError(advanced) && advancedJointSettings(advanced) === held.settings))+ && joint !== null&& joint.data.enabled !== false&& joint.def._name === held.type&& !doomed.has(entity) && !doomed.has(connected)@@ -345,6 +374,8 @@ export function syncJoints3D(app: App, module: Physics3DWasmModule,joints.set(entity, {bodyA, bodyB, type: joint.def._name,motorOn: motor.on, motorSpeed: motor.speed,+ settings: joint.def === SwingTwistJoint3D || joint.def === SixDOFJoint3D+ ? advancedJointSettings(joint.data as SwingTwistJoint3DData | SixDOFJoint3DData) : undefined,});}}@@ -375,7 +406,21 @@ function motorOf(app: App, entity: Entity, def: Joint3DDef, ppu: number,function driveJoints3D(app: App, module: Physics3DWasmModule, joints: Joint3DMap,ppu: number): void {for (const [entity, held] of joints) {- if (held.type === HingeJoint3D._name) {+ if (held.type === SwingTwistJoint3D._name || held.type === SixDOFJoint3D._name) {+ const def = held.type === SwingTwistJoint3D._name ? SwingTwistJoint3D : SixDOFJoint3D;+ const d = app.world.get(entity, def) as SwingTwistJoint3DData | SixDOFJoint3DData;+ if (joint3DSettingsError(d)) continue;+ const a = d.angularVelocity;+ const v = 'linearVelocity' in d ? d.linearVelocity : { x: 0, y: 0, z: 0 };+ const force = 'maxMotorForce' in d ? d.maxMotorForce : 0;+ const args = [d.enableMotor ? 1 : 0, v.x / ppu, v.y / ppu, v.z / ppu,+ a.x, a.y, a.z, force, d.maxMotorTorque] as const;+ const signature = args.join(',');+ if (signature !== held.motorSettings) {+ module._physics3d_setAdvancedJointMotor(entity as number, ...args);+ held.motorSettings = signature;+ }+ } else 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) {diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex ae68a45f9..f6d234ea5 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -81,6 +81,19 @@ export interface Physics3DWasmModule {_physics3d_overlapBox(px: number, py: number, pz: number,hx: number, hy: number, hz: number, layerMask: number): number;+ _physics3d_addSwingTwistJoint(entity: number, bodyA: number, bodyB: number,+ px: number, py: number, pz: number, ax: number, ay: number, az: number,+ nx: number, ny: number, nz: number, normalHalf: number, planeHalf: number,+ twistMin: number, twistMax: number, collideConnected: number): number;+ _physics3d_addSixDOFJoint(entity: number, bodyA: number, bodyB: number,+ px: number, py: number, pz: number, ax: number, ay: number, az: number,+ nx: number, ny: number, nz: number, translationMotion: number, rotationMotion: number,+ lx: number, ly: number, lz: number, hx: number, hy: number, hz: number,+ rx: number, ry: number, rz: number, sx: number, sy: number, sz: number,+ collideConnected: number): number;+ _physics3d_setAdvancedJointMotor(entity: number, enable: number,+ vx: number, vy: number, vz: number, wx: number, wy: number, wz: number,+ maxForce: number, maxTorque: number): void;_physics3d_addPointJoint(entity: number, bodyA: number, bodyB: number,px: number, py: number, pz: number,collideConnected: number): number;@@ -143,6 +156,7 @@ const REQUIRED_EXPORTS = ['_physics3d_contactEnters', '_physics3d_contactEntersBytes','_physics3d_sensorEnters', '_physics3d_sensorEntersBytes','_physics3d_addHingeJoint', '_physics3d_removeJoint',+ '_physics3d_addSwingTwistJoint', '_physics3d_addSixDOFJoint', '_physics3d_setAdvancedJointMotor',] as const;/** Throws naming what is missing, rather than letting the first frame do it. */diff --git a/sdk/src/physics3d/index.ts b/sdk/src/physics3d/index.tsindex 9a97d52c1..30c5f69be 100644--- a/sdk/src/physics3d/index.ts+++ b/sdk/src/physics3d/index.ts@@ -76,12 +76,14 @@ export {SliderJoint3D,DistanceJoint3D,FixedJoint3D,+ SwingTwistJoint3D, SixDOFJoint3D, JointMotion3D, joint3DSettingsError,readJoint3D,type PointJoint3DData,type HingeJoint3DData,type SliderJoint3DData,type DistanceJoint3DData,type FixedJoint3DData,+ type SwingTwistJoint3DData, type SixDOFJoint3DData,type Joint3DShape,} from './Physics3DJoints';diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex a477d1f28..779bd9ebc 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -232,7 +232,7 @@ const PHYSICS_COMPONENT_TYPES = new Set([const PHYSICS3D_COMPONENT_TYPES = new Set(['RigidBody3D', 'BoxCollider3D', 'SphereCollider3D', 'CapsuleCollider3D','MeshCollider3D', 'ConvexCollider3D', 'CharacterController3D',- 'PointJoint3D', 'HingeJoint3D', 'SliderJoint3D', 'DistanceJoint3D', 'FixedJoint3D',+ 'PointJoint3D', 'HingeJoint3D', 'SliderJoint3D', 'DistanceJoint3D', 'FixedJoint3D', 'SwingTwistJoint3D', 'SixDOFJoint3D',]);/** True if any entity carries a 3D physics component. */diff --git a/sdk/tests/advanced-joint3d.test.ts b/sdk/tests/advanced-joint3d.test.tsnew file mode 100644index 000000000..7e9b44efb--- /dev/null+++ b/sdk/tests/advanced-joint3d.test.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { SwingTwistJoint3D, SixDOFJoint3D, joint3DSettingsError } from '../src/physics3d/AdvancedJoint3D';+import { assertPhysics3DContract } from '../src/physics3d/Physics3DModule';++describe('advanced joint validation', () => {+ it('accepts all defaults and independent free/limited axes', () => {+ expect(joint3DSettingsError(structuredClone(SwingTwistJoint3D._default))).toBeNull();+ const d = structuredClone(SixDOFJoint3D._default);+ d.rotationMotion = { x: 2, y: 1, z: 0 };+ expect(joint3DSettingsError(d)).toBeNull();+ d.rotationLower.y = 1;+ d.rotationUpper.y = -.2;+ expect(joint3DSettingsError(d)).toMatch(/lower bound/);+ });+ it('rejects nonfinite motors, invalid modes, and parallel frames', () => {+ const d = structuredClone(SixDOFJoint3D._default);+ d.maxMotorForce = Infinity;+ expect(joint3DSettingsError(d)).toMatch(/Motor force/);+ d.maxMotorForce = 0;+ d.translationMotion.x = 3;+ expect(joint3DSettingsError(d)).toMatch(/Axis motion/);+ d.translationMotion.x = 0;+ d.normalAxis = { ...d.axis };+ expect(joint3DSettingsError(d)).toMatch(/parallel/);+ });+ it('rejects a stale physics module at load, before the first simulation frame', () => {+ expect(() => assertPhysics3DContract({})).toThrow('_physics3d_addSwingTwistJoint');+ expect(() => assertPhysics3DContract({})).toThrow('_physics3d_addSixDOFJoint');+ });+});diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.tsindex 824e58771..cab3f0c1f 100644--- a/sdk/tests/physics3d-ecs.test.ts+++ b/sdk/tests/physics3d-ecs.test.ts@@ -21,8 +21,8 @@ import {} from '../src/asset/meshCollision';import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';import {- PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D,- type Joint3DMap, type HingeJoint3DData, type SliderJoint3DData,+ PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D, SwingTwistJoint3D, SixDOFJoint3D,+ type Joint3DMap, type HingeJoint3DData, type SliderJoint3DData, type SixDOFJoint3DData, type SwingTwistJoint3DData,} from '../src/physics3d/Physics3DJoints';import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';import type { App } from '../src/app/app';@@ -93,6 +93,9 @@ function fakeModule(): Physics3DWasmModule & {_physics3d_addSliderJoint: record('addSliderJoint'),_physics3d_addDistanceJoint: record('addDistanceJoint'),_physics3d_addFixedJoint: record('addFixedJoint'),+ _physics3d_addSwingTwistJoint: record('addSwingTwistJoint'),+ _physics3d_addSixDOFJoint: record('addSixDOFJoint'),+ _physics3d_setAdvancedJointMotor: record('setAdvancedJointMotor'),_physics3d_removeJoint: record('removeJoint'),_physics3d_setJointMotor: record('setJointMotor'),_physics3d_jointValue: (entity: number) => { calls.push({ name: 'jointValue', args: [entity] }); return 0.25; },@@ -435,6 +438,44 @@ describe('the 3D world and the ECS', () => {return [a, b] as const;};+ it('scales six-axis limits and velocity without scaling angles or force', () => {+ const [a, b] = pair();+ world.insert(a, SixDOFJoint3D, { connectedEntity: b,+ translationMotion: { x: 1, y: 0, z: 2 },+ translationLower: { x: -200, y: 0, z: 0 }, translationUpper: { x: 300, y: 0, z: 0 },+ rotationMotion: { x: 1, y: 0, z: 0 },+ rotationLower: { x: -0.4, y: 0, z: 0 }, rotationUpper: { x: 0.6, y: 0, z: 0 },+ enableMotor: true, linearVelocity: { x: 150, y: 0, z: 0 },+ angularVelocity: { x: 2, y: 0, z: 0 }, maxMotorForce: 40, maxMotorTorque: 20 });+ stepJoints();+ const args = called('addSixDOFJoint')[0]!.args;+ expect(args.slice(12, 14)).toEqual([33, 1]);+ expect(args.slice(14, 20)).toEqual([-2, 0, 0, 3, 0, 0]);+ expect(args.slice(20, 26)).toEqual([-0.4, 0, 0, 0.6, 0, 0]);+ expect(called('setAdvancedJointMotor')[0]!.args).toEqual([a, 1, 1.5, 0, 0, 2, 0, 0, 40, 20]);+ stepJoints();+ expect(called('setAdvancedJointMotor')).toHaveLength(1);+ world.update(a, SixDOFJoint3D, (d) => { (d as SixDOFJoint3DData).linearVelocity = { x: -200, y: 0, z: 0 }; });+ stepJoints();+ expect(called('addSixDOFJoint')).toHaveLength(1);+ expect(called('setAdvancedJointMotor')[1]!.args[2]).toBe(-2);+ });++ it('rebuilds changed swing limits and removes an invalid frame before stepping', () => {+ const [a, b] = pair();+ world.insert(a, SwingTwistJoint3D, { connectedEntity: b });+ stepJoints();+ world.update(a, SwingTwistJoint3D, (d) => { (d as SwingTwistJoint3DData).normalHalfConeAngle = 0.2; });+ stepJoints();+ expect(called('addSwingTwistJoint')).toHaveLength(2);+ expect(called('removeJoint')).toHaveLength(1);+ world.update(a, SwingTwistJoint3D, (d) => { (d as SwingTwistJoint3DData).normalAxis = { x: 0, y: 1, z: 0 }; });+ stepJoints();+ expect(joints.size).toBe(0);+ expect(called('removeJoint')).toHaveLength(2);+ expect(called('addSwingTwistJoint')).toHaveLength(2);+ });+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 } });diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex 63aa99830..698b28475 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -647,6 +647,59 @@ step(1);check('a removed body leaves the readback', bodyPos(CAP) === null);check('and its state can no longer be read', bodyState(capId) === null);+// Swing/twist and SixDOF must enforce numeric limits while motors push against them.+const advancedBody = (entity, x, motion) => m._physics3d_addBox(entity, 0.2, 0.2, 0.2,+ x, 50, 0, ...IDENTITY, motion, 0, 0, 0, 0, 0, 0, 0.5, 0, 0);+const swingA = advancedBody(150, 800, STATIC), swingB = advancedBody(151, 800, DYNAMIC);+check('a swing twist joint is created', m._physics3d_addSwingTwistJoint(152, swingA, swingB,+ 800, 50, 0, 1, 0, 0, 0, 1, 0, 0, 0, -0.3, 0.3, 0) === 1);+check('an entity cannot silently replace a live constraint', m._physics3d_addSwingTwistJoint(152, swingA, swingB,+ 800, 50, 0, 1, 0, 0, 0, 1, 0, 0, 0, -.1, .1, 0) === 0);+m._physics3d_setAdvancedJointMotor(152, 1, 0, 0, 0, 1, 0, 0, 0, 100);+step(120);+const angleX = (body) => {+ m._physics3d_getBodyState(body);+ const o = m._physics3d_queryResult() >> 2;+ return 2 * Math.atan2(m.HEAPF32[o + 3], m.HEAPF32[o + 6]);+};+const twist = angleX(swingB);+check('twist motor reaches the upper limit without passing it', twist > 0.2 && twist < 0.34, `angle=${twist}`);+m._physics3d_setAdvancedJointMotor(152, 1, 0, 0, 0, -1, 0, 0, 0, 100);+step(120);+const reverseTwist = angleX(swingB);+check('twist motor reverses without rebuilding the joint', reverseTwist < -0.2 && reverseTwist > -0.34, `angle=${reverseTwist}`);+const coneA = advancedBody(158, 1000, STATIC), coneB = advancedBody(159, 1000, DYNAMIC);+check('an unequal swing cone is created', m._physics3d_addSwingTwistJoint(160, coneA, coneB,+ 1000, 50, 0, 1, 0, 0, 0, 1, 0, .3, .6, 0, 0, 0) === 1);+const angleAxis = (body, axis) => {+ m._physics3d_getBodyState(body);+ const o = m._physics3d_queryResult() >> 2;+ return 2 * Math.atan2(m.HEAPF32[o + 3 + axis], m.HEAPF32[o + 6]);+};+m._physics3d_setAdvancedJointMotor(160, 1, 0, 0, 0, 0, 0, 1, 0, 1000);+step(120);+check('normal half cone matches the displayed Z swing bound', near(angleAxis(coneB, 2), .3, .04), `angle=${angleAxis(coneB, 2)}`);+m._physics3d_setAdvancedJointMotor(160, 1, 0, 0, 0, 0, 1, -1, 0, 1000);+step(120);+check('swing remains inside both unequal cone bounds', Math.abs(angleAxis(coneB, 1)) <= .65 && Math.abs(angleAxis(coneB, 2)) <= .35,+ `y=${angleAxis(coneB, 1)} z=${angleAxis(coneB, 2)}`);+const sixA = advancedBody(153, 900, STATIC), sixB = advancedBody(154, 900, DYNAMIC);+const sixArgs = [155, sixA, sixB, 900, 50, 0, 1, 0, 0, 0, 1, 0,+ 33, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];+check('a six axis joint is created', m._physics3d_addSixDOFJoint(...sixArgs) === 1);+m._physics3d_setAdvancedJointMotor(155, 1, 3, 0, 2, 0, 0, 0, 1000, 100);+step(120);+const sixPos = bodyState(sixB);+check('limited X stops at one metre while locked Y stays put', near(sixPos.x, 901, 0.04) && near(sixPos.y, 50, 0.02), JSON.stringify(sixPos));+check('free Z continues through the numeric limits', sixPos.z > 3, JSON.stringify(sixPos));+m._physics3d_setAdvancedJointMotor(155, 1, -3, 0, 0, 0, 0, 0, 100, 100);+step(120);+check('six axis motor reverses to its lower limit', near(bodyState(sixB).x, 899, 0.04), JSON.stringify(bodyState(sixB)));+check('parallel reference axes are rejected', m._physics3d_addSwingTwistJoint(156, swingA, swingB,+ 800, 50, 0, 1, 0, 0, 2, 0, 0, 0.4, 0.4, -0.3, 0.3, 0) === 0);+const invalidSix = [...sixArgs]; invalidSix[0] = 157; invalidSix[14] = 2;+check('reversed limited bounds are rejected', m._physics3d_addSixDOFJoint(...invalidSix) === 0);+m._physics3d_shutdown();check('the world reports itself gone', m._physics3d_isReady() === 0);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hppindex ac87188f2..bcbd4ee80 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp@@ -83,6 +83,17 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz);// Joints+uint32_t physics3d_addSwingTwistJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,+ float px, float py, float pz, float ax, float ay, float az,+ float nx, float ny, float nz, float normalHalf, float planeHalf,+ float twistMin, float twistMax, int collideConnected);+uint32_t physics3d_addSixDOFJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,+ float px, float py, float pz, float ax, float ay, float az, float nx, float ny, float nz,+ int translationMotion, int rotationMotion,+ float lx, float ly, float lz, float hx, float hy, float hz,+ float rx, float ry, float rz, float sx, float sy, float sz, int collideConnected);+void physics3d_setAdvancedJointMotor(uint32_t entity, int enable,+ float vx, float vy, float vz, float wx, float wy, float wz, float maxForce, float maxTorque);uint32_t physics3d_addPointJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,float px, float py, float pz, int collideConnected);uint32_t physics3d_addHingeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,diff --git a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cppindex d5806404b..18a5a9799 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp@@ -5,9 +5,9 @@* @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+ * other. Basic rules include a point they share, an axis* they turn about, an axis they slide along, a distance they keep, and no- * freedom at all.+ * freedom at all. Swing/twist and six-axis constraints add per-axis limits.** 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@@ -29,6 +29,8 @@#include <Jolt/Physics/Constraints/HingeConstraint.h>#include <Jolt/Physics/Constraints/PointConstraint.h>#include <Jolt/Physics/Constraints/SliderConstraint.h>+#include <Jolt/Physics/Constraints/SwingTwistConstraint.h>+#include <Jolt/Physics/Constraints/SixDOFConstraint.h>#include <algorithm>#include <cmath>@@ -158,10 +160,118 @@ void applyMotor(MotorSettings& motor, float maxForceOrTorque) {motor.SetTorqueLimit(maxForceOrTorque);}+bool finiteVector(Vec3Arg v) {+ return std::isfinite(v.GetX()) && std::isfinite(v.GetY()) && std::isfinite(v.GetZ());+}++bool referenceFrame(Vec3Arg x, Vec3Arg y, Vec3& outX, Vec3& outY) {+ if (!finiteVector(x) || !finiteVector(y) || !std::isfinite(x.LengthSq())+ || !std::isfinite(y.LengthSq()) || x.LengthSq() < 1.0e-12f || y.LengthSq() < 1.0e-12f) return false;+ outX = x.Normalized();+ const Vec3 normal = y - outX * outX.Dot(y);+ if (normal.LengthSq() < 1.0e-10f * y.LengthSq()) return false;+ outY = normal.Normalized();+ return true;+}+} // namespaceextern "C" {+/// Both frames coincide at creation, so limits are relative to the authored pose.+EMSCRIPTEN_KEEPALIVE+uint32_t physics3d_addSwingTwistJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,+ float px, float py, float pz, float ax, float ay, float az,+ float nx, float ny, float nz, float normalHalf, float planeHalf,+ float twistMin, float twistMax, int collideConnected) {+ if (bodyA == bodyB || !bothLive(bodyA, bodyB) || g().constraints.count(entity) != 0) return 0;+ Vec3 x, y;+ if (!referenceFrame(Vec3(ax, ay, az), Vec3(nx, ny, nz), x, y)+ || !finiteVector(Vec3(px, py, pz))+ || !std::isfinite(normalHalf) || !std::isfinite(planeHalf)+ || !std::isfinite(twistMin) || !std::isfinite(twistMax)+ || normalHalf < 0 || normalHalf > JPH_PI || planeHalf < 0 || planeHalf > JPH_PI+ || twistMin < -JPH_PI || twistMax > JPH_PI || twistMin > twistMax) return 0;+ SwingTwistConstraintSettings settings;+ settings.mSpace = EConstraintSpace::WorldSpace;+ settings.mPosition1 = settings.mPosition2 = RVec3(px, py, pz);+ settings.mTwistAxis1 = settings.mTwistAxis2 = x;+ settings.mPlaneAxis1 = settings.mPlaneAxis2 = x.Cross(y);+ settings.mNormalHalfConeAngle = normalHalf;+ settings.mPlaneHalfConeAngle = planeHalf;+ settings.mTwistMinAngle = twistMin;+ settings.mTwistMaxAngle = twistMax;+ return adopt(entity,+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB)),+ bodyA, bodyB, collideConnected);+}++/// Axis motion is packed as two bits per axis: 0 locked, 1 limited, 2 free.+EMSCRIPTEN_KEEPALIVE+uint32_t physics3d_addSixDOFJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,+ float px, float py, float pz, float ax, float ay, float az, float nx, float ny, float nz,+ int translationMotion, int rotationMotion,+ float lx, float ly, float lz, float hx, float hy, float hz,+ float rx, float ry, float rz, float sx, float sy, float sz, int collideConnected) {+ if (bodyA == bodyB || !bothLive(bodyA, bodyB) || g().constraints.count(entity) != 0) return 0;+ Vec3 x, y;+ if (!referenceFrame(Vec3(ax, ay, az), Vec3(nx, ny, nz), x, y)+ || !finiteVector(Vec3(px, py, pz))+ || translationMotion < 0 || translationMotion > 63 || rotationMotion < 0 || rotationMotion > 63) return 0;+ SixDOFConstraintSettings settings;+ settings.mSpace = EConstraintSpace::WorldSpace;+ settings.mSwingType = ESwingType::Pyramid;+ settings.mPosition1 = settings.mPosition2 = RVec3(px, py, pz);+ settings.mAxisX1 = settings.mAxisX2 = x;+ settings.mAxisY1 = settings.mAxisY2 = y;+ const float lower[] = {lx, ly, lz, rx, ry, rz};+ const float upper[] = {hx, hy, hz, sx, sy, sz};+ for (int i = 0; i < 6; ++i) {+ const auto axis = static_cast<SixDOFConstraintSettings::EAxis>(i);+ const int mode = ((i < 3 ? translationMotion : rotationMotion) >> (2 * (i % 3))) & 3;+ if (!std::isfinite(lower[i]) || !std::isfinite(upper[i]) || mode == 3) return 0;+ if (mode == 0) settings.MakeFixedAxis(axis);+ else if (mode == 2) settings.MakeFreeAxis(axis);+ else {+ if (lower[i] >= upper[i] || (i >= 3 && (lower[i] < -JPH_PI || upper[i] > JPH_PI))) return 0;+ settings.SetLimitedAxis(axis, lower[i], upper[i]);+ }+ }+ return adopt(entity,+ g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB)),+ bodyA, bodyB, collideConnected);+}++/// Live velocity/force changes do not rebuild the joint or reset its zero pose.+EMSCRIPTEN_KEEPALIVE+void physics3d_setAdvancedJointMotor(uint32_t entity, int enable,+ float vx, float vy, float vz, float wx, float wy, float wz, float maxForce, float maxTorque) {+ const auto it = g().constraints.find(entity);+ if (it == g().constraints.end() || !finiteVector(Vec3(vx, vy, vz)) || !finiteVector(Vec3(wx, wy, wz))+ || !std::isfinite(maxForce) || maxForce < 0 || !std::isfinite(maxTorque) || maxTorque < 0) return;+ TwoBodyConstraint* constraint = it->second;+ const EMotorState state = enable != 0 ? EMotorState::Velocity : EMotorState::Off;+ if (constraint->GetSubType() == EConstraintSubType::SwingTwist) {+ auto* joint = static_cast<SwingTwistConstraint*>(constraint);+ applyMotor(joint->GetSwingMotorSettings(), maxTorque);+ applyMotor(joint->GetTwistMotorSettings(), maxTorque);+ joint->SetSwingMotorState(state);+ joint->SetTwistMotorState(state);+ joint->SetTargetAngularVelocityCS(Vec3(wx, wy, wz));+ } else if (constraint->GetSubType() == EConstraintSubType::SixDOF) {+ auto* joint = static_cast<SixDOFConstraint*>(constraint);+ for (int i = 0; i < 6; ++i) {+ const auto axis = static_cast<SixDOFConstraintSettings::EAxis>(i);+ applyMotor(joint->GetMotorSettings(axis), i < 3 ? maxForce : maxTorque);+ if (!joint->IsFixedAxis(axis)) joint->SetMotorState(axis, state);+ }+ joint->SetTargetVelocityCS(Vec3(vx, vy, vz));+ joint->SetTargetAngularVelocityCS(Vec3(wx, wy, wz));+ } else return;+ g().system->GetBodyInterface().ActivateBody(constraint->GetBody1()->GetID());+ g().system->GetBodyInterface().ActivateBody(constraint->GetBody2()->GetID());+}+/// A shared point, free to turn on all three axes — a chain link, a ragdoll limb.EMSCRIPTEN_KEEPALIVEuint32_t physics3d_addPointJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB,