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(physics3d): a turned box and an upright capsule can be swept, a body's mass data read, and a joint's range, motor limit, lengths and spring changed while it runs, from Jolt and PhysX alike; a Jolt motor switched on in play keeps its torque limit
yhhf32fb7ae3415
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a209780d0..44a4771de 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,12 @@ published separately; it ships inside the editor.- **A script can push a 3D body about.** `Physics3D` answered where things were and could set a velocity, and nothing more: there was no force, no impulse, no torque, and a script could not ask how fast a body was going, while the 2D world had all of it. It now has `applyImpulse(entity, impulse, at?)` and `applyForce(entity, force, at?)`, at a world point or the centre of mass, `applyTorque`, `applyAngularImpulse`, `getLinearVelocity`, `setAngularVelocity` and `getAngularVelocity`, `getMass`, `setAwake` and `isAwake`, and `setGravity` and `getGravity`, all in world units, from both the Jolt and PhysX worlds. In each, 4 N s at the centre of a 2 kg sphere gave it 2.000 m/s and no spin; 1 N s half a metre off its centre gave it 2.500 rad/s, which r x J over its inertia says; a force lasted one step; and with gravity set to 2 m/s squared a body fell at 1.000 m/s after half a second.- **A blast.** `Physics3D.explode(centre, radius, impulse, { upward })` strikes every moving body within reach away from the centre, less the further it is and none at the edge, and strikes every `Breakable` it reaches as hard, standing or not, so a grenade breaks the pots round it. In the editor a blast beside a pot broke it and threw the 50 g pebble at its foot away and up.- **A thing that breaks says so.** `Broke` is sent once a `Breakable`'s pieces stand in its place, with where it was struck in the world and how hard, for the sound, the dust and the score; a thing whose pieces could not be loaded did not break and sends nothing.+- **Box and capsule sweeps, and what a 3D body weighs.** `Physics3D.boxCast(origin, halfExtents, direction, layers, rotation)` and `capsuleCast(origin, radius, halfHeight, direction, layers, rotation)` sweep a turned box or an upright capsule as `sphereCast` sweeps a ball, and `getMassData(entity)` answers a body's mass, its centre of mass in the world and how hard it is to turn about each of its own axes. Swept ten metres down onto a slab, a half-metre box landed at 0.400 of the way, turned an eighth of a turn on its edge at 0.379, a capsule standing at 0.375 and lying at 0.425, as the geometry gives, in both the Jolt and PhysX worlds; a 2 x 1 x 0.5 m block answered 1000 kg and moments of 104.17, 354.17 and 416.67 kg m squared, a block's own, in both.+- **A joint changed while it runs.** A 3D hinge's or slider's range and motor limit, and a distance joint's lengths and spring, reach a joint already in the world when gameplay changes them; before, only the motor's speed did, and a door locked from a script by narrowing its range swung on. A door turning at 2 rad/s stopped at 0.30 rad when its range was set to plus or minus 0.3 and went on when it was taken away, and a ball on a three-metre rope rose to one metre when the rope was shortened, in both worlds. A range always holds the pose the joint was made in: one that does not reach 0 is widened to 0, in both worlds alike.++### Fixed++- **A Jolt hinge or slider whose motor is switched on in play keeps its limit.** Made with its motor off, a joint in the Jolt world took the solver's own motor settings when the motor was turned on later, which push without bound, so a door with a `maxMotorTorque` of 10 opened as if it had none, where the PhysX world held it to 10. Both now hold every motor to its limit from the start: switched on with a limit of nothing, a door turns nothing in either.## [0.104.1] - 2026-11-13diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex c87d03724..17dad6fce 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -458,7 +458,13 @@ pose is also the **zero** of every limit: a door placed closed has `angle` 0 andopens to `upperAngle`.Set `motorSpeed` from gameplay at any time — the world is re-driven when it-changes. In the other direction, `HingeJoint3D.angle` and+changes. So are a hinge's or slider's `enableLimit`, `lowerAngle`/`upperAngle`+or `lowerTranslation`/`upperTranslation` and `maxMotorTorque`/`maxMotorForce`,+and a distance joint's `minLength`, `maxLength`, `frequency` and `damping`: a+door locked by narrowing its range stops, a rope shortened while something hangs+on it pulls it up. A range always holds the pose the joint was made in: one that+does not reach 0 (`lowerAngle: 0.2`) is widened to 0, and a hinge's goes no+further than half a turn either way, in both solvers. In the other direction, `HingeJoint3D.angle` and`SliderJoint3D.translation` are written back each step, so a game can ask how farthe door swung without integrating the swing a second time.@@ -500,6 +506,8 @@ const occupants = q.overlapSphere(spawnPoint, 50);|---|---|| `raycast(origin, direction, layerMask?)` | The nearest body on a line, as `{ entity, fraction, x, y, z, normalX, normalY, normalZ }`, or `null`. `direction` carries the ray's length. || `sphereCast(origin, radius, direction, layerMask?)` | The first body a moving sphere would meet, same shape, or `null`. |+| `boxCast(origin, halfExtents, direction, layerMask?, rotation?)` | The same for a box, turned by `rotation` or not at all: whether a crate fits through a door. |+| `capsuleCast(origin, radius, halfHeight, direction, layerMask?, rotation?)` | The same for a capsule standing along its own y, as a character does; `halfHeight` is half its straight part. || `overlapSphere(centre, radius, layerMask?)` / `overlapBox(centre, halfExtents, layerMask?)` | Every body already inside a volume, as `{ entity, x, y, z }[]`. |`Physics3D` holds `null` until the physics module has finished loading, so a system@@ -538,6 +546,7 @@ physics.explode(grenadeAt, 400, 3000, { upward: 0.4 });| `setLinearVelocity(entity, v)` / `getLinearVelocity(entity)` | Its speed, in world units a second. || `setAngularVelocity(entity, w)` / `getAngularVelocity(entity)` | Its spin, in radians a second. || `getMass(entity)` | Kilograms; `null` for a body that does not move. Set with `RigidBody3D.mass`. |+| `getMassData(entity)` | `{ mass, centre, inertia }`: kilograms, its centre of mass in the world, and how hard it is to turn about each of its own axes (kg by world units squared; its moments of inertia where those are its principal axes, as a box's are; `Infinity` about an axis it may not turn on). || `setAwake(entity, awake)` / `isAwake(entity)` | Wake a sleeping body, or put one to sleep until something touches it. || `setGravity(g)` / `getGravity()` | The world's gravity, in metres a second squared as the project's physics settings give it. A sleeping body stays put until woken. || `explode(centre, radius, impulse, { upward?, layers? })` | Strikes every moving body within `radius` away from `centre` with `impulse`, less the further it is and none at the edge; `upward` (0..1) tips the push toward the sky. A `Breakable` it reaches is struck as hard, standing or not. Answers how many bodies it moved. |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 ed415c99d..fbeaf3ba3 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@@ -400,7 +400,11 @@ cmds.spawn()在关节建立的那一刻按它的变换解算成世界量。那个姿态同时也是所有限位的**零点**:一扇摆成关闭状态的门,`angle` 就是 0,开到 `upperAngle`。-`motorSpeed` 随时可以由游戏逻辑改写——变了就会重新驱动世界。反方向上,+`motorSpeed` 随时可以由游戏逻辑改写——变了就会重新驱动世界。铰链和滑轨的 `enableLimit`、+`lowerAngle`/`upperAngle` 或 `lowerTranslation`/`upperTranslation`、`maxMotorTorque`/`maxMotorForce`,+以及距离关节的 `minLength`、`maxLength`、`frequency`、`damping` 也一样:收窄门的范围就能把门锁住,+运行中缩短绳子会把挂着的东西拉上来。范围总是包含关节建立时的姿态:不含 0 的范围(如 `lowerAngle: 0.2`)+会扩展到 0,铰链的范围在两个求解器里都不超过正反各半圈。反方向上,`HingeJoint3D.angle` 与 `SliderJoint3D.translation` 每步写回,所以游戏可以直接问「门开了多少」,不必自己再积分一遍。@@ -439,6 +443,8 @@ const occupants = q.overlapSphere(spawnPoint, 50);|---|---|| `raycast(origin, direction, layerMask?)` | 一条线上最近的刚体,形如 `{ entity, fraction, x, y, z, normalX, normalY, normalZ }`,没有则为 `null`。`direction` 自带射线长度。 || `sphereCast(origin, radius, direction, layerMask?)` | 一个运动的球最先撞上的刚体,形状同上,没有则为 `null`。 |+| `boxCast(origin, halfExtents, direction, layerMask?, rotation?)` | 盒子的同样查询,可用 `rotation` 旋转:箱子能不能穿过门。 |+| `capsuleCast(origin, radius, halfHeight, direction, layerMask?, rotation?)` | 胶囊的同样查询,胶囊沿自身 y 轴竖立,和角色一样;`halfHeight` 是中间直段的一半。 || `overlapSphere(centre, radius, layerMask?)` / `overlapBox(centre, halfExtents, layerMask?)` | 已经在某个体积里的所有刚体,形如 `{ entity, x, y, z }[]`。 |物理模块加载完成之前 `Physics3D` 是 `null`,所以在最初几帧里询问的系统要先判断。@@ -472,6 +478,7 @@ physics.explode(grenadeAt, 400, 3000, { upward: 0.4 });| `setLinearVelocity(entity, v)` / `getLinearVelocity(entity)` | 线速度,世界单位每秒。 || `setAngularVelocity(entity, w)` / `getAngularVelocity(entity)` | 角速度,弧度每秒。 || `getMass(entity)` | 千克;不动的刚体返回 `null`。用 `RigidBody3D.mass` 设定。 |+| `getMassData(entity)` | `{ mass, centre, inertia }`:质量(千克)、世界中的质心、绕自身三个轴转动的难度(千克·世界单位²;当这三个轴就是主轴时即为转动惯量,长方体就是如此;不允许转动的轴为 `Infinity`)。 || `setAwake(entity, awake)` / `isAwake(entity)` | 唤醒休眠的刚体,或让它休眠直到被碰到。 || `setGravity(g)` / `getGravity()` | 世界重力,单位与项目物理设置一致,米每秒²。休眠的刚体在被唤醒前不会动。 || `explode(centre, radius, impulse, { upward?, layers? })` | 把 `radius` 内的每个运动刚体从 `centre` 向外撞开,力度为 `impulse`,越远越小,到边缘为零;`upward`(0..1)让推力偏向上方。被波及的 `Breakable` 以同样力度计算,不论它是否静止。返回推动了多少个刚体。 |diff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.mdindex d1d5ed9cd..8bf31ad5b 100644--- a/sdk/etc/physics3d.api.md+++ b/sdk/etc/physics3d.api.md@@ -322,11 +322,14 @@ applyAngularImpulse: (entity: Entity, impulse: { x: number; y: number; z: numberapplyForce: (entity: Entity, force: { x: number; y: number; z: number; }, at?: { x: number; y: number; z: number; }) => booleanapplyImpulse: (entity: Entity, impulse: { x: number; y: number; z: number; }, at?: { x: number; y: number; z: number; }) => booleanapplyTorque: (entity: Entity, torque: { x: number; y: number; z: number; }) => boolean+boxCast: (origin: { x: number; y: number; z: number; }, halfExtents: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, layerMask?: number, rotation?: { x: number; y: number; z: number; w: number; }) => Cast3DHit | null+capsuleCast: (origin: { x: number; y: number; z: number; }, radius: number, halfHeight: number, direction: { x: number; y: number; z: number; }, layerMask?: number, rotation?: { x: number; y: number; z: number; w: number; }) => Cast3DHit | nullexplode: (centre: { x: number; y: number; z: number; }, radius: number, impulse: number, options?: { upward?: number; layers?: number; }) => numbergetAngularVelocity: (entity: Entity) => { x: number; y: number; z: number; } | nullgetGravity: () => { x: number; y: number; z: number; }getLinearVelocity: (entity: Entity) => { x: number; y: number; z: number; } | nullgetMass: (entity: Entity) => number | null+getMassData: (entity: Entity) => { mass: number; centre: { x: number; y: number; z: number; }; inertia: { x: number; y: number; z: number; }; } | nullhasBody: (entity: Entity) => booleanisAwake: (entity: Entity) => booleanoverlapBox: (centre: { x: number; y: number; z: number; }, halfExtents: { x: number; y: number; z: number; }, layerMask?: number) => Overlap3DHit[]@@ -377,6 +380,8 @@ _physics3d_addSliderJoint: (entity: number, bodyA: number, bodyB: number, px: nu_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, cx: number, cy: number, cz: 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_addTorque: ((bodyId: number, tx: number, ty: number, tz: number) => void) | undefined+_physics3d_boxCast: ((px: number, py: number, pz: number, hx: number, hy: number, hz: number, qx: number, qy: number, qz: number, qw: number, dx: number, dy: number, dz: number, layerMask: number) => number) | undefined+_physics3d_capsuleCast: ((px: number, py: number, pz: number, radius: number, halfHeight: number, qx: number, qy: number, qz: number, qw: number, dx: number, dy: number, dz: number, layerMask: number) => number) | undefined_physics3d_contactEnterMasses: (() => number) | undefined_physics3d_contactEnterMassesBytes: (() => number) | undefined_physics3d_contactEnterSpeeds: (() => number) | undefined@@ -386,6 +391,7 @@ _physics3d_contactEntersBytes: () => number_physics3d_contactExits: () => number_physics3d_contactExitsBytes: () => number_physics3d_getBodyDynamics: ((bodyId: number) => number) | undefined+_physics3d_getBodyMassData: ((bodyId: number) => number) | undefined_physics3d_getBodyState: (bodyId: number) => number_physics3d_init: (gx: number, gy: number, gz: number, maxBodies: number) => void_physics3d_isAwake: ((bodyId: number) => number) | undefined@@ -410,8 +416,11 @@ _physics3d_setAdvancedJointMotor: (entity: number, enable: number, vx: number, v_physics3d_setAngularVelocity: ((bodyId: number, wx: number, wy: number, wz: number) => void) | undefined_physics3d_setAwake: ((bodyId: number, awake: number) => void) | undefined_physics3d_setCharacterPosition: (characterId: number, px: number, py: number, pz: number) => void+_physics3d_setDistanceJoint: ((entity: number, minLength: number, maxLength: number, frequency: number, damping: number) => void) | undefined_physics3d_setGravity: ((gx: number, gy: number, gz: number) => void) | undefined+_physics3d_setJointLimits: ((entity: number, enable: number, lower: number, upper: number) => void) | undefined_physics3d_setJointMotor: (entity: number, enable: number, speed: number) => void+_physics3d_setJointMotorLimit: ((entity: number, limit: number) => void) | undefined_physics3d_setLayerMask: (layer: number, mask: number) => void_physics3d_setLinearVelocity: (bodyId: number, vx: number, vy: number, vz: number) => void_physics3d_setMass: ((bodyId: number, mass: number) => void) | undefineddiff --git a/sdk/src/physics3d/Physics3DJoints.ts b/sdk/src/physics3d/Physics3DJoints.tsindex e2edaa70c..7b8501837 100644--- a/sdk/src/physics3d/Physics3DJoints.ts+++ b/sdk/src/physics3d/Physics3DJoints.ts@@ -194,6 +194,9 @@ export interface Joint3DRecord {motorSpeed: number;settings?: string;motorSettings?: string;+ /** A hinge's or slider's range and motor limit, or a distance joint's lengths and spring, as the world last had+ * them: a change in play reaches the joint without making it again. */+ shape?: string;}export type Joint3DMap = Map<Entity, Joint3DRecord>;@@ -373,7 +376,7 @@ export function syncJoints3D(app: App, module: Physics3DWasmModule,const motor = motorOf(app, entity, joint.def, ppu);joints.set(entity, {bodyA, bodyB, type: joint.def._name,- motorOn: motor.on, motorSpeed: motor.speed,+ motorOn: motor.on, motorSpeed: motor.speed, shape: shapeOf(app, entity, joint.def, ppu)?.join(','),settings: joint.def === SwingTwistJoint3D || joint.def === SixDOFJoint3D? advancedJointSettings(joint.data as SwingTwistJoint3DData | SixDOFJoint3DData) : undefined,});@@ -384,6 +387,41 @@ export function syncJoints3D(app: App, module: Physics3DWasmModule,driveJoints3D(app, module, joints, ppu);}+/**+ * What a joint's range, motor limit or lengths are now, in the module's units: [enable, lower, upper, limit] for a+ * hinge or slider, [min, max, frequency, damping] for a distance joint; null for a joint that has none.+ */+function shapeOf(app: App, entity: Entity, def: Joint3DDef, ppu: number): number[] | null {+ if (def === HingeJoint3D) {+ const d = app.world.get(entity, HingeJoint3D) as HingeJoint3DData;+ return [d.enableLimit ? 1 : 0, d.lowerAngle, d.upperAngle, d.maxMotorTorque];+ }+ if (def === SliderJoint3D) {+ const d = app.world.get(entity, SliderJoint3D) as SliderJoint3DData;+ return [d.enableLimit ? 1 : 0, d.lowerTranslation / ppu, d.upperTranslation / ppu, d.maxMotorForce];+ }+ if (def === DistanceJoint3D) {+ const d = app.world.get(entity, DistanceJoint3D) as DistanceJoint3DData;+ return [d.minLength / ppu, d.maxLength / ppu, d.frequency, d.damping];+ }+ return null;+}++/** Carry a joint's range, motor limit or lengths into the world when gameplay changed them. */+function reshape(app: App, module: Physics3DWasmModule, entity: Entity, held: Joint3DRecord, def: Joint3DDef, ppu: number): void {+ const now = shapeOf(app, entity, def, ppu);+ if (!now) return;+ const signature = now.join(',');+ if (signature === held.shape) return;+ if (def === DistanceJoint3D) {+ module._physics3d_setDistanceJoint?.(entity as number, now[0]!, now[1]!, now[2]!, now[3]!);+ } else {+ module._physics3d_setJointLimits?.(entity as number, now[0]!, now[1]!, now[2]!);+ module._physics3d_setJointMotorLimit?.(entity as number, now[3]!);+ }+ held.shape = signature;+}+/** 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 } {@@ -420,7 +458,10 @@ function driveJoints3D(app: App, module: Physics3DWasmModule, joints: Joint3DMapmodule._physics3d_setAdvancedJointMotor(entity as number, ...args);held.motorSettings = signature;}+ } else if (held.type === DistanceJoint3D._name) {+ reshape(app, module, entity, held, DistanceJoint3D, ppu);} else if (held.type === HingeJoint3D._name) {+ reshape(app, module, entity, held, HingeJoint3D, ppu);const d = app.world.get(entity, HingeJoint3D) as HingeJoint3DData;const on = d.enableMotor === true;if (on !== held.motorOn || d.motorSpeed !== held.motorSpeed) {@@ -431,6 +472,7 @@ function driveJoints3D(app: App, module: Physics3DWasmModule, joints: Joint3DMapd.angle = module._physics3d_jointValue(entity as number);app.world.set(entity, HingeJoint3D, d);} else if (held.type === SliderJoint3D._name) {+ reshape(app, module, entity, held, SliderJoint3D, ppu);const d = app.world.get(entity, SliderJoint3D) as SliderJoint3DData;const on = d.enableMotor === true;const speed = d.motorSpeed / ppu;diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex 9165b7ac0..a4814067f 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -137,6 +137,10 @@ export interface Physics3DWasmModule {collideConnected: number): number;_physics3d_removeJoint(entity: number, bodyA: number, bodyB: number): void;_physics3d_setJointMotor(entity: number, enable: number, speed: number): void;+ /** Optional for older binaries: a live hinge's or slider's range, its motor's limit, a distance joint's shape. */+ _physics3d_setJointLimits?(entity: number, enable: number, lower: number, upper: number): void;+ _physics3d_setJointMotorLimit?(entity: number, limit: number): void;+ _physics3d_setDistanceJoint?(entity: number, minLength: number, maxLength: number, frequency: number, damping: number): void;_physics3d_jointValue(entity: number): number;_physics3d_contactEnters(): number;@@ -156,6 +160,13 @@ export interface Physics3DWasmModule {_physics3d_setGravity?(gx: number, gy: number, gz: number): void;_physics3d_setAwake?(bodyId: number, awake: number): void;_physics3d_isAwake?(bodyId: number): number;+ /** Optional for older binaries: (mass, centre x/y/z in metres, moments about its own axes in kg m^2) to the query buffer. */+ _physics3d_getBodyMassData?(bodyId: number): number;+ /** Optional for older binaries: a turned box or an upright capsule swept, written as a sphere cast is. */+ _physics3d_boxCast?(px: number, py: number, pz: number, hx: number, hy: number, hz: number,+ qx: number, qy: number, qz: number, qw: number, dx: number, dy: number, dz: number, layerMask: number): number;+ _physics3d_capsuleCast?(px: number, py: number, pz: number, radius: number, halfHeight: number,+ qx: number, qy: number, qz: number, qw: number, dx: number, dy: number, dz: number, layerMask: number): number;_physics3d_contactExits(): number;_physics3d_contactExitsBytes(): number;_physics3d_sensorEnters(): number;diff --git a/sdk/src/physics3d/Physics3DQueries.ts b/sdk/src/physics3d/Physics3DQueries.tsindex c9b876d2b..06a05804a 100644--- a/sdk/src/physics3d/Physics3DQueries.ts+++ b/sdk/src/physics3d/Physics3DQueries.ts@@ -266,6 +266,53 @@ export class Physics3DQueries {return hit ? this.readCast_() : null;}+ /**+ * The first body a box would meet, swept from `origin` along `direction` (which carries the distance), turned by+ * `rotation` or not at all: whether a crate fits through a door, what a sliding block would strike.+ */+ boxCast(origin: { x: number; y: number; z: number }, halfExtents: { x: number; y: number; z: number },+ direction: { x: number; y: number; z: number }, layerMask = 0,+ rotation: { x: number; y: number; z: number; w: number } = { x: 0, y: 0, z: 0, w: 1 }): Cast3DHit | null {+ if (!this.module_._physics3d_boxCast) return null;+ const p = this.ppu_;+ const hit = this.module_._physics3d_boxCast(origin.x / p, origin.y / p, origin.z / p,+ halfExtents.x / p, halfExtents.y / p, halfExtents.z / p, rotation.x, rotation.y, rotation.z, rotation.w,+ direction.x / p, direction.y / p, direction.z / p, layerMask);+ return hit ? this.readCast_() : null;+ }++ /**+ * The first body an upright capsule would meet - `halfHeight` is half the straight part between its round ends,+ * along its own y as a character stands - swept from `origin` along `direction`: where a body that walks could+ * go, before it goes.+ */+ capsuleCast(origin: { x: number; y: number; z: number }, radius: number, halfHeight: number,+ direction: { x: number; y: number; z: number }, layerMask = 0,+ rotation: { x: number; y: number; z: number; w: number } = { x: 0, y: 0, z: 0, w: 1 }): Cast3DHit | null {+ if (!this.module_._physics3d_capsuleCast) return null;+ const p = this.ppu_;+ const hit = this.module_._physics3d_capsuleCast(origin.x / p, origin.y / p, origin.z / p, radius / p, halfHeight / p,+ rotation.x, rotation.y, rotation.z, rotation.w, direction.x / p, direction.y / p, direction.z / p, layerMask);+ return hit ? this.readCast_() : null;+ }++ /**+ * What it weighs and how it turns: mass in kilograms, its centre of mass in the world, and how hard it is to turn+ * about each of its own axes, in kilograms by world units squared - its moments of inertia where those are its+ * principal axes, as a box's or a ball's are; Infinity about an axis it may not turn on. null for a body that does+ * not move.+ */+ getMassData(entity: Entity): { mass: number; centre: { x: number; y: number; z: number }; inertia: { x: number; y: number; z: number } } | null {+ const id = this.bodies_.get(entity);+ if (id === undefined || !this.module_._physics3d_getBodyMassData?.(id)) return null;+ const f32 = this.module_.HEAPF32, o = this.module_._physics3d_queryResult() >> 2, p = this.ppu_, p2 = p * p;+ return {+ mass: f32[o]!,+ centre: { x: f32[o + 1]! * p, y: f32[o + 2]! * p, z: f32[o + 3]! * p },+ inertia: { x: f32[o + 4]! * p2, y: f32[o + 5]! * p2, z: f32[o + 6]! * p2 },+ };+ }+/** Every body overlapping a sphere — what a spawn point asks before it spawns. */overlapSphere(centre: { x: number; y: number; z: number }, radius: number,layerMask = 0): Overlap3DHit[] {diff --git a/sdk/tests/physics3d-body-control.test.ts b/sdk/tests/physics3d-body-control.test.tsindex 8e927931d..334baa27e 100644--- a/sdk/tests/physics3d-body-control.test.ts+++ b/sdk/tests/physics3d-body-control.test.ts@@ -48,6 +48,13 @@ function fakeWorld(at: Record<number, [number, number, number]>, overlaps: numbeheap.set([2, 0.1, 0.2, 0.3], 0);return 1;},+ _physics3d_boxCast: (...args: number[]) => { calls.push({ name: 'boxCast', args }); heap.set([30, 0.25, 1, 2, 3, 0, 1, 0], 0); return 1; },+ _physics3d_capsuleCast: (...args: number[]) => { calls.push({ name: 'capsuleCast', args }); return 0; },+ _physics3d_getBodyMassData: (id: number) => {+ if (!moving.has(id)) return 0;+ heap.set([2, 1, 0.5, 0, 0.2, Infinity, 0.3], 0);+ return 1;+ },_physics3d_overlapSphere: () => {// Read out before anything else uses the buffer, as the real one is.// Entities, as the real one names them: body n is entity 10 n here.@@ -98,6 +105,25 @@ describe('pushing a 3D body from a script', () => {expect(physics.getAngularVelocity(30 as Entity)).toBeNull();});+ it('sweeps a turned box and an upright capsule in metres, and reads the hit back in world units', () => {+ const turn = { x: 0, y: 0.3826834, z: 0, w: 0.9238795 };+ const hit = physics.boxCast({ x: 100, y: 500, z: 0 }, { x: 50, y: 25, z: 50 }, { x: 0, y: -1000, z: 0 }, 4, turn);+ expect(last('boxCast')).toEqual([1, 5, 0, 0.5, 0.25, 0.5, turn.x, turn.y, turn.z, turn.w, 0, -10, 0, 4]);+ expect(hit).toMatchObject({ entity: 30, fraction: 0.25, x: 100, y: 200, z: 300, normalY: 1 });+ // Unturned when no turn is given, and none hit is null.+ expect(physics.capsuleCast({ x: 0, y: 0, z: 0 }, 30, 60, { x: 0, y: 0, z: 500 })).toBeNull();+ expect(last('capsuleCast')).toEqual([0, 0, 0, 0.3, 0.6, 0, 0, 0, 1, 0, 0, 5, 0]);+ });++ it('reads mass data back: kilograms, the centre in world units, moments in kg by world units squared', () => {+ const data = physics.getMassData(10 as Entity)!;+ expect(data.mass).toBe(2);+ expect(data.centre).toEqual({ x: 100, y: 50, z: 0 });+ expect(data.inertia.x).toBeCloseTo(2000, 3);+ expect(data.inertia.y).toBe(Infinity);+ expect(physics.getMassData(30 as Entity)).toBeNull();+ });+it('answers false and null for an entity the world has no body for', () => {expect(physics.applyImpulse(99 as Entity, { x: 1, y: 0, z: 0 })).toBe(false);expect(physics.applyForce(99 as Entity, { x: 1, y: 0, z: 0 })).toBe(false);diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.tsindex d89e5648e..cfeac2b33 100644--- a/sdk/tests/physics3d-ecs.test.ts+++ b/sdk/tests/physics3d-ecs.test.ts@@ -21,7 +21,7 @@ import {} from '../src/asset/meshCollision';import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';import {- PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D, SwingTwistJoint3D, SixDOFJoint3D,+ PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D, SwingTwistJoint3D, SixDOFJoint3D, DistanceJoint3D,type Joint3DMap, type HingeJoint3DData, type SliderJoint3DData, type SixDOFJoint3DData, type SwingTwistJoint3DData,} from '../src/physics3d/Physics3DJoints';import { drainPhysics3DEvents, type Physics3DEventsData, type Physics3DWasmModule } from '../src/physics3d/Physics3DModule';@@ -98,6 +98,9 @@ function fakeModule(): Physics3DWasmModule & {_physics3d_setAdvancedJointMotor: record('setAdvancedJointMotor'),_physics3d_removeJoint: record('removeJoint'),_physics3d_setJointMotor: record('setJointMotor'),+ _physics3d_setJointLimits: record('setJointLimits'),+ _physics3d_setJointMotorLimit: record('setJointMotorLimit'),+ _physics3d_setDistanceJoint: record('setDistanceJoint'),_physics3d_setMass: record('setMass'),_physics3d_jointValue: (entity: number) => { calls.push({ name: 'jointValue', args: [entity] }); return 0.25; },// Distinct allocations, as a real heap gives: one address for everything@@ -722,6 +725,44 @@ describe('the 3D world and the ECS', () => {expect(called('setJointMotor')).toHaveLength(1);});+ it('carries a new range and motor limit into a hinge or slider that already exists', () => {+ // Built once; without this, a door locked from a script by narrowing its range would swing on.+ const [a, b] = pair();+ const hinge = world.insert<HingeJoint3DData>(a, HingeJoint3D, { connectedEntity: b, maxMotorTorque: 10 });+ stepJoints();+ expect(called('setJointLimits')).toHaveLength(0);+ hinge.enableLimit = true;+ hinge.lowerAngle = -0.2;+ hinge.upperAngle = 0.4;+ hinge.maxMotorTorque = 50;+ stepJoints();+ expect(called('setJointLimits').map((c) => c.args)).toEqual([[a as number, 1, -0.2, 0.4]]);+ expect(called('setJointMotorLimit').map((c) => c.args)).toEqual([[a as number, 50]]);+ stepJoints();+ expect(called('setJointLimits')).toHaveLength(1);++ // A slider's travel is a length, and reaches the world in metres; its force does not.+ const [c, d] = pair({ x: 500, y: 0, z: 0 }, { x: 600, y: 0, z: 0 });+ const slider = world.insert<SliderJoint3DData>(c, SliderJoint3D, { connectedEntity: d });+ stepJoints();+ slider.enableLimit = true;+ slider.lowerTranslation = -50;+ slider.upperTranslation = 150;+ stepJoints();+ expect(called('setJointLimits').at(-1)!.args).toEqual([c as number, 1, -0.5, 1.5]);+ });++ it('carries a new length and spring into a distance joint that already exists', () => {+ const [a, b] = pair();+ const rope = world.insert<{ maxLength: number; minLength: number; frequency: number; damping: number }>(a, DistanceJoint3D, { connectedEntity: b, maxLength: 300 });+ stepJoints();+ expect(called('setDistanceJoint')).toHaveLength(0);+ rope.maxLength = 100;+ rope.frequency = 2;+ stepJoints();+ expect(called('setDistanceJoint').map((c) => c.args)).toEqual([[a as number, 0, 1, 2, 0.5]]);+ });+it('writes the joint state back where gameplay can read it', () => {const [a, b] = pair();world.insert(a, HingeJoint3D, { connectedEntity: b });diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex 1000c403a..d37000a6f 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -918,6 +918,72 @@ check('the world\'s gravity can be changed', near(fall, -1, 0.02), `vy=${fall.to}++// ── Swept boxes and capsules, and what a body weighs ───────────────────────+{+ // A slab whose top is at y 0.5, far from everything; shapes are swept down onto it from y 5, ten metres.+ m._physics3d_addBox(9600, 1, 0.5, 1, 8000, 0, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ m._physics3d_optimize();+ const castHit = () => { const o = m._physics3d_queryResult() >> 2; return { entity: m.HEAPF32[o], fraction: m.HEAPF32[o + 1], y: m.HEAPF32[o + 3] }; };+ const S = Math.SQRT1_2;+ const box = m._physics3d_boxCast(8000, 5, 0, 0.5, 0.5, 0.5, ...IDENTITY, 0, -10, 0, 0) ? castHit() : null;+ // A box half a metre each way lands with its centre at 1.0: four metres of ten.+ check('a box swept down lands on what is under it', box && box.entity === 9600 && near(box.fraction, 0.4, 0.006), JSON.stringify(box));+ const turned = m._physics3d_boxCast(8000, 5, 0, 0.5, 0.5, 0.5, 0, 0, Math.sin(Math.PI / 8), Math.cos(Math.PI / 8), 0, -10, 0, 0) ? castHit() : null;+ // Turned an eighth of a turn about z it stands on an edge, its centre 0.707 above the slab.+ check('and a turned box lands on its edge', turned && near(turned.fraction, (5 - 0.5 - S) / 10, 0.006), JSON.stringify(turned));+ const upright = m._physics3d_capsuleCast(8000, 5, 0, 0.25, 0.5, ...IDENTITY, 0, -10, 0, 0) ? castHit() : null;+ // Standing, its foot is 0.75 below its centre; lying (a quarter turn about z), 0.25.+ check('an upright capsule swept down lands on its foot', upright && near(upright.fraction, (5 - 0.5 - 0.75) / 10, 0.006), JSON.stringify(upright));+ const lying = m._physics3d_capsuleCast(8000, 5, 0, 0.25, 0.5, 0, 0, S, S, 0, -10, 0, 0) ? castHit() : null;+ check('and a lying one on its side', lying && near(lying.fraction, (5 - 0.5 - 0.25) / 10, 0.006), JSON.stringify(lying));+ check('a cast that meets nothing says so', m._physics3d_boxCast(8000, 5, 0, 0.5, 0.5, 0.5, ...IDENTITY, 0, 10, 0, 0) === 0);++ // A 2 m x 1 m x 0.5 m block at the density of water: 1000 kg, and a block's moments m/12 (b^2 + c^2).+ const block = m._physics3d_addBox(9601, 1, 0.5, 0.25, 8100, 50, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);+ const data = m._physics3d_getBodyMassData(block) ? Array.from(m.HEAPF32.subarray(m._physics3d_queryResult() >> 2, (m._physics3d_queryResult() >> 2) + 7)) : null;+ const want = [1000, 8100, 50, 0, 1000 / 12 * (1 + 0.25), 1000 / 12 * (4 + 0.25), 1000 / 12 * (4 + 1)];+ check('a body says its mass, its centre and its moments of inertia', data && data.every((v, i) => Math.abs(v - want[i]) <= Math.max(0.01 * Math.abs(want[i]), 1e-3)),+ `${data?.map((v) => v.toFixed(2)).join(',')} want ${want.map((v) => v.toFixed(2)).join(',')}`);+ check('and a body that does not move has none to say', m._physics3d_getBodyMassData(m._physics3d_addBox(9602, 1, 1, 1, 8200, 0, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0)) === 0);+}++// ── A joint changed while it runs ───────────────────────────────────────────+{+ // A door on a vertical hinge, weightless, made with its motor off and a motor limit of nothing.+ const post = m._physics3d_addBox(9700, 0.1, 1, 0.1, 8300, 50, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ const door = m._physics3d_addBox(9701, 0.5, 1, 0.05, 8300.6, 50, 0, ...IDENTITY, ...[DYNAMIC, 0, 0, 0, 0, 0, 0], 0.5, 0, 0);+ m._physics3d_addHingeJoint(9702, post, door, 8300, 50, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0);+ m._physics3d_setJointMotor(9702, 1, 2);+ step(30);+ // A motor allowed no torque turns nothing - in both worlds, where Jolt's used to push without bound when it was+ // switched on after the joint was made.+ check('a motor turned on later keeps the limit it was given', near(m._physics3d_jointValue(9702), 0, 0.01), `angle=${m._physics3d_jointValue(9702).toFixed(4)}`);+ m._physics3d_setJointMotorLimit(9702, 1000);+ step(30);+ const swung = m._physics3d_jointValue(9702);+ check('and turns once it is allowed to', Math.abs(swung) > 0.5, `angle=${swung.toFixed(4)} after half a second at 2 rad/s`);+ m._physics3d_setJointLimits(9702, 1, -0.3, 0.3);+ step(60);+ const held = m._physics3d_jointValue(9702);+ check('a range set while it runs stops it at the end', Math.abs(Math.abs(held) - 0.3) < 0.05, `angle=${held.toFixed(4)}`);+ m._physics3d_setJointLimits(9702, 0, 0, 0);+ step(30);+ check('and taken away lets it go on', Math.abs(m._physics3d_jointValue(9702)) > 0.6, `angle=${m._physics3d_jointValue(9702).toFixed(4)}`);++ // A ball on a three-metre rope, which is shortened to one while it hangs.+ const hook = m._physics3d_addBox(9710, 0.1, 0.1, 0.1, 8400, 50, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ const bob = m._physics3d_addSphere(9711, 0.3, 8400, 49, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);+ m._physics3d_addDistanceJoint(9712, hook, bob, 8400, 50, 0, 8400, 49, 0, 0, 3, 0, 0, 0);+ step(120);+ const centre = () => { m._physics3d_getBodyState(bob); const o = m._physics3d_queryResult() >> 2; return Math.hypot(m.HEAPF32[o] - 8400, m.HEAPF32[o + 1] - 50, m.HEAPF32[o + 2]); };+ const long = centre();+ m._physics3d_setDistanceJoint(9712, 0, 1, 0, 0);+ step(120);+ const short = centre();+ check('a rope shortened while it hangs pulls up what hangs on it', near(long, 3, 0.05) && near(short, 1, 0.05), `${long.toFixed(3)} then ${short.toFixed(3)}`);+}+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 ac58cbe3b..2eb98fd39 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp@@ -103,6 +103,11 @@ void physics3d_setGravity(float gx, float gy, float gz);// Wake a body (awake != 0) or put it to sleep; and whether it is awake: 1 awake, 0 asleep or not a moving body.void physics3d_setAwake(uint32_t bodyId, int awake);int physics3d_isAwake(uint32_t bodyId);+// Writes (mass, cx, cy, cz, ix, iy, iz): kilograms, its centre of mass in the world in metres, and how hard it is to+// turn about each of its own axes in kg m^2 - the moment that answers a twist about that axis alone, its moment of+// inertia there where the axis is a principal one, as a box's are; infinite about an axis it may not turn on.+// 0 for a body that does not move.+int physics3d_getBodyMassData(uint32_t bodyId);int physics3d_getBodyState(uint32_t bodyId);// What a force needs to know of a body: its mass and how it is turning.int physics3d_getBodyDynamics(uint32_t bodyId);@@ -154,11 +159,25 @@ uint32_t physics3d_addFixedJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyBint collideConnected);void physics3d_removeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB);void physics3d_setJointMotor(uint32_t entity, int enable, float speed);+// A hinge's angles (radians) or a slider's travel (metres) it may move between, or none (enable 0). A range is+// measured from the pose the joint was made in and always holds it: one that does not reach 0 is widened to 0.+void physics3d_setJointLimits(uint32_t entity, int enable, float lower, float upper);+// The most a hinge's motor may twist (newton metres) or a slider's push (newtons).+void physics3d_setJointMotorLimit(uint32_t entity, float limit);+// A distance joint's shortest and longest (metres), and its spring (frequency 0 is rigid).+void physics3d_setDistanceJoint(uint32_t entity, float minLength, float maxLength, float frequency, float damping);float physics3d_jointValue(uint32_t entity);// Queries. Each answers a hit count and leaves the hits in the query buffer.int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz,uint32_t layerMask);+// A box of half-extents (hx, hy, hz), turned by (qx, qy, qz, qw), swept from (px, py, pz) along (dx, dy, dz): the+// first body it would meet, written as sphereCast writes it.+int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask);+// An upright capsule (its length along its own y, as a character stands), turned by (qx, qy, qz, qw), swept the same way.+int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask);int physics3d_sphereCast(float px, float py, float pz, float radius,float dx, float dy, float dz, uint32_t layerMask);int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cppindex 18a5a9799..a3a264ffa 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp@@ -160,6 +160,12 @@ void applyMotor(MotorSettings& motor, float maxForceOrTorque) {motor.SetTorqueLimit(maxForceOrTorque);}+/// A hinge's limits as Jolt can hold them: within a half turn either way and never excluding the pose it was made in.+static void hingeRange(float lower, float upper, float& outMin, float& outMax) {+ outMin = std::clamp(std::min(lower, 0.0f), -JPH_PI, 0.0f);+ outMax = std::clamp(std::max(upper, 0.0f), 0.0f, JPH_PI);+}+bool finiteVector(Vec3Arg v) {return std::isfinite(v.GetX()) && std::isfinite(v.GetY()) && std::isfinite(v.GetZ());}@@ -302,11 +308,9 @@ uint32_t physics3d_addHingeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyBsettings.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);+ if (enableLimit != 0) hingeRange(lowerAngle, upperAngle, settings.mLimitsMin, settings.mLimitsMax);+ // Always: a motor turned on later is held to the same torque as one that started on.+ applyMotor(settings.mMotorSettings, maxTorque);TwoBodyConstraint* constraint =g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB));if (constraint != nullptr && enableMotor != 0) {@@ -334,10 +338,10 @@ uint32_t physics3d_addSliderJoint(uint32_t entity, uint32_t bodyA, uint32_t bodysettings.mSliderAxis1 = settings.mSliderAxis2 = axis;settings.mNormalAxis1 = settings.mNormalAxis2 = normal;if (enableLimit != 0) {- settings.mLimitsMin = lower;- settings.mLimitsMax = upper;+ settings.mLimitsMin = std::min(lower, 0.0f);+ settings.mLimitsMax = std::max(upper, 0.0f);}- if (enableMotor != 0) applyMotor(settings.mMotorSettings, maxForce);+ applyMotor(settings.mMotorSettings, maxForce);TwoBodyConstraint* constraint =g().system->GetBodyInterface().CreateConstraint(&settings, BodyID(bodyA), BodyID(bodyB));if (constraint != nullptr && enableMotor != 0) {@@ -402,6 +406,15 @@ void physics3d_removeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyB) {bodies.ActivateBody(BodyID(bodyB));}+/// A joint changed under two sleeping bodies does nothing until they wake: they are woken.+static void wakeEnds(Constraint* constraint) {+ if (constraint->GetType() != EConstraintType::TwoBodyConstraint) return;+ auto* two = static_cast<TwoBodyConstraint*>(constraint);+ BodyInterface& bodies = g().system->GetBodyInterface();+ bodies.ActivateBody(two->GetBody1()->GetID());+ bodies.ActivateBody(two->GetBody2()->GetID());+}+/// Drive an existing hinge or slider from gameplay, without rebuilding the joint.EMSCRIPTEN_KEEPALIVEvoid physics3d_setJointMotor(uint32_t entity, int enable, float speed) {@@ -427,6 +440,54 @@ void physics3d_setJointMotor(uint32_t entity, int enable, float speed) {}}+EMSCRIPTEN_KEEPALIVE+void physics3d_setJointLimits(uint32_t entity, int enable, float lower, float upper) {+ const auto it = g().constraints.find(entity);+ if (it == g().constraints.end() || !std::isfinite(lower) || !std::isfinite(upper)) return;+ Constraint* constraint = it->second;+ switch (constraint->GetSubType()) {+ case EConstraintSubType::Hinge: {+ float lo = -JPH_PI, hi = JPH_PI;+ if (enable != 0) hingeRange(lower, upper, lo, hi);+ static_cast<HingeConstraint*>(constraint)->SetLimits(lo, hi);+ break;+ }+ case EConstraintSubType::Slider:+ if (enable != 0) static_cast<SliderConstraint*>(constraint)->SetLimits(std::min(lower, 0.0f), std::max(upper, 0.0f));+ else static_cast<SliderConstraint*>(constraint)->SetLimits(-FLT_MAX, FLT_MAX);+ break;+ default: return;+ }+ wakeEnds(constraint);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setJointMotorLimit(uint32_t entity, float limit) {+ const auto it = g().constraints.find(entity);+ if (it == g().constraints.end() || !std::isfinite(limit) || limit < 0.0f) return;+ Constraint* constraint = it->second;+ switch (constraint->GetSubType()) {+ case EConstraintSubType::Hinge: applyMotor(static_cast<HingeConstraint*>(constraint)->GetMotorSettings(), limit); break;+ case EConstraintSubType::Slider: applyMotor(static_cast<SliderConstraint*>(constraint)->GetMotorSettings(), limit); break;+ default: return;+ }+ wakeEnds(constraint);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setDistanceJoint(uint32_t entity, float minLength, float maxLength, float frequency, float damping) {+ const auto it = g().constraints.find(entity);+ if (it == g().constraints.end() || it->second->GetSubType() != EConstraintSubType::Distance) return;+ if (!std::isfinite(minLength) || !std::isfinite(maxLength) || !std::isfinite(frequency) || !std::isfinite(damping)) return;+ auto* distance = static_cast<DistanceConstraint*>(it->second.GetPtr());+ const float lo = std::max(minLength, 0.0f);+ distance->SetDistance(lo, std::max(maxLength, lo));+ SpringSettings& spring = distance->GetLimitsSpringSettings();+ spring.mFrequency = std::max(frequency, 0.0f);+ spring.mDamping = std::max(damping, 0.0f);+ wakeEnds(it->second.GetPtr());+}+/// 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_KEEPALIVEdiff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex 004dac888..19747c550 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -627,6 +627,26 @@ int physics3d_isAwake(uint32_t bodyId) {return g().system->GetBodyInterface().IsActive(BodyID(bodyId)) ? 1 : 0;}+EMSCRIPTEN_KEEPALIVE+int physics3d_getBodyMassData(uint32_t bodyId) {+ if (!g().isValid() || bodyId == 0) return 0;+ const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));+ if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;+ const Body& body = lock.GetBody();+ const MotionProperties* motion = body.GetMotionProperties();+ const float inverseMass = motion->GetInverseMass();+ if (!(inverseMass > 0.0f)) return 0;+ const RVec3 centre = body.GetCenterOfMassPosition();+ // About the body's own axes, not Jolt's principal ones, which it orders as it likes: a twist about an axis alone+ // turns it by inverse-inertia along that axis, and the moment is its inverse.+ const Mat44 inverse = motion->GetLocalSpaceInverseInertia();+ const auto moment = [](float i) { return i > 0.0f ? 1.0f / i : std::numeric_limits<float>::infinity(); };+ g().queryBuffer = { 1.0f / inverseMass,+ static_cast<float>(centre.GetX()), static_cast<float>(centre.GetY()), static_cast<float>(centre.GetZ()),+ moment(inverse(0, 0)), moment(inverse(1, 1)), moment(inverse(2, 2)) };+ return 1;+}+/// A torque of (tx, ty, tz) newton metres, over the next step.EMSCRIPTEN_KEEPALIVEvoid physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz) {@@ -864,14 +884,48 @@ int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float* the very gaps a moving body would not fit. Writes* (entity, fraction, px,py,pz, nx,ny,nz); returns 0 for a clear path.*/+static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask);+EMSCRIPTEN_KEEPALIVEint physics3d_sphereCast(float px, float py, float pz, float radius,float dx, float dy, float dz, uint32_t layerMask) {g().queryBuffer.clear();if (!g().isValid() || radius <= 0.0f) return 0;const SphereShape shape(radius);- const RShapeCast cast(&shape, Vec3::sReplicate(1.0f),- RMat44::sTranslation(RVec3(px, py, pz)), Vec3(dx, dy, dz));+ return castShapeQuery(shape, RMat44::sTranslation(RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);+}++/// A turn that is not one - zero, or not a number - is no turn.+static Quat turnOf(float qx, float qy, float qz, float qw) {+ const Quat q(qx, qy, qz, qw);+ const float length = q.Length();+ return std::isfinite(length) && length > 1e-6f ? q / length : Quat::sIdentity();+}++EMSCRIPTEN_KEEPALIVE+int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || !(hx > 0.0f) || !(hy > 0.0f) || !(hz > 0.0f)) return 0;+ // Rounded no more than its thinnest side allows: a box a centimetre thick is still a box.+ const BoxShape shape(Vec3(hx, hy, hz), std::min({0.05f, hx, hy, hz}));+ return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);+}++EMSCRIPTEN_KEEPALIVE+int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || !(radius > 0.0f) || !(halfHeight >= 0.0f)) return 0;+ if (halfHeight == 0.0f) return physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, layerMask);+ const CapsuleShape shape(halfHeight, radius);+ return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);+}++/// The first body a shape swept from `start` along `direction` meets, written to the query buffer as+/// (entity, fraction, px,py,pz, nx,ny,nz); 1 for a hit.+static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask) {+ const RShapeCast cast(&shape, Vec3::sReplicate(1.0f), start, direction);ClosestHitCollisionCollector<CastShapeCollector> collector;const ShapeCastSettings settings;const MaskLayerFilter filter(layerMask);diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cppindex cd6b10772..eeab46d7f 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp@@ -103,6 +103,46 @@ uint32_t adopt(uint32_t entity, PxJoint* joint, JointKind kind, int collideConnereturn 1;}+/// The rule the Jolt world keeps, kept here so a scene behaves the same in both: a hinge within a half turn either way+/// and never excluding the pose it was made in; a slider's travel the same without the half turn.+static void hingeRange(float lower, float upper, float& outMin, float& outMax) {+ outMin = std::clamp(std::min(lower, 0.0f), -PxPi, 0.0f);+ outMax = std::clamp(std::max(upper, 0.0f), 0.0f, PxPi);+}++/// A distance joint's lengths and spring; the spring speaks frequency and damping ratio as the Jolt world does.+static void shapeDistance(PxDistanceJoint* joint, float minLength, float maxLength, float frequency, float damping) {+ const float lo = std::max(minLength, 0.0f);+ joint->setMinDistance(lo);+ joint->setMaxDistance(std::max(maxLength, lo));+ PxDistanceJointFlags flags = PxDistanceJointFlag::eMAX_DISTANCE_ENABLED;+ if (lo > 0.0f) flags |= PxDistanceJointFlag::eMIN_DISTANCE_ENABLED;+ if (frequency > 0.0f) {+ // PhysX speaks in a stiffness and a damping, which need the mass the spring moves.+ PxRigidActor* a = nullptr;+ PxRigidActor* b = nullptr;+ joint->getActors(a, b);+ float massA = 0.0f, massB = 0.0f;+ if (a) if (PxRigidDynamic* d = a->is<PxRigidDynamic>()) massA = d->getMass();+ if (b) if (PxRigidDynamic* d = b->is<PxRigidDynamic>()) massB = d->getMass();+ const float mass = massA > 0.0f && massB > 0.0f ? massA * massB / (massA + massB) : std::max(massA, massB);+ const float omega = 2.0f * PxPi * frequency;+ joint->setStiffness(mass * omega * omega);+ joint->setDamping(2.0f * mass * std::max(damping, 0.0f) * omega);+ flags |= PxDistanceJointFlag::eSPRING_ENABLED;+ }+ joint->setDistanceJointFlags(flags);+}++/// A joint changed under two sleeping bodies does nothing until they wake: they are woken.+static void wakeEnds(PxJoint* joint) {+ PxRigidActor* a = nullptr;+ PxRigidActor* b = nullptr;+ joint->getActors(a, b);+ wake(a);+ wake(b);+}+PxD6JointDrive motor(bool on, float limit) {return on ? PxD6JointDrive(0.0f, MOTOR_DAMPING, limit) : PxD6JointDrive();}@@ -249,8 +289,10 @@ uint32_t physics3d_addHingeJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyBPxRigidActor* b = actorOf(bodyB);PxRevoluteJoint* joint = PxRevoluteJointCreate(px3::physics(), a, localFrame(a, frame), b, localFrame(b, frame));if (joint == nullptr) return 0;- if (enableLimit != 0 && lowerAngle < upperAngle) {- joint->setLimit(PxJointAngularLimitPair(lowerAngle, upperAngle));+ if (enableLimit != 0) {+ float lo = 0.0f, hi = 0.0f;+ hingeRange(lowerAngle, upperAngle, lo, hi);+ joint->setLimit(PxJointAngularLimitPair(lo, hi));joint->setRevoluteJointFlag(PxRevoluteJointFlag::eLIMIT_ENABLED, true);}joint->setDriveForceLimit(maxTorque);@@ -272,9 +314,9 @@ uint32_t physics3d_addSliderJoint(uint32_t entity, uint32_t bodyA, uint32_t bodyif (axis.normalizeSafe() <= 0.0f) axis = PxVec3(0.0f, 1.0f, 0.0f);PxD6Joint* joint = d6(bodyA, bodyB, worldFrame(PxVec3(px, py, pz), axis, perpendicularTo(axis)));if (joint == nullptr) return 0;- const bool limited = enableLimit != 0 && lower < upper;+ const bool limited = enableLimit != 0;joint->setMotion(PxD6Axis::eX, limited ? PxD6Motion::eLIMITED : PxD6Motion::eFREE);- if (limited) joint->setLinearLimit(PxD6Axis::eX, PxJointLinearLimitPair(lower, upper, PxSpring(0.0f, 0.0f)));+ if (limited) joint->setLinearLimit(PxD6Axis::eX, PxJointLinearLimitPair(std::min(lower, 0.0f), std::max(upper, 0.0f), PxSpring(0.0f, 0.0f)));if (enableMotor != 0) {joint->setDrive(PxD6Drive::eX, motor(true, maxForce));joint->setDriveVelocity(PxVec3(motorSpeed, 0.0f, 0.0f), PxVec3(0.0f), true);@@ -293,26 +335,7 @@ uint32_t physics3d_addDistanceJoint(uint32_t entity, uint32_t bodyA, uint32_t boPxDistanceJoint* joint = PxDistanceJointCreate(px3::physics(),a, localFrame(a, PxTransform(PxVec3(ax, ay, az))), b, localFrame(b, PxTransform(PxVec3(bx, by, bz))));if (joint == nullptr) return 0;- const float maxDistance = std::max(maxLength, minLength);- joint->setMaxDistance(maxDistance);- joint->setMinDistance(std::max(minLength, 0.0f));- PxDistanceJointFlags flags = PxDistanceJointFlag::eMAX_DISTANCE_ENABLED;- if (minLength > 0.0f) flags |= PxDistanceJointFlag::eMIN_DISTANCE_ENABLED;- if (frequency > 0.0f) {- // Jolt speaks in a frequency and a damping ratio; PhysX in a stiffness- // and a damping, which need the mass the spring moves.- float mass = 0.0f;- float massA = 0.0f, massB = 0.0f;- if (PxRigidDynamic* d = a->is<PxRigidDynamic>()) massA = d->getMass();- if (PxRigidDynamic* d = b->is<PxRigidDynamic>()) massB = d->getMass();- if (massA > 0.0f && massB > 0.0f) mass = massA * massB / (massA + massB);- else mass = std::max(massA, massB);- const float omega = 2.0f * PxPi * frequency;- joint->setStiffness(mass * omega * omega);- joint->setDamping(2.0f * mass * std::max(damping, 0.0f) * omega);- flags |= PxDistanceJointFlag::eSPRING_ENABLED;- }- joint->setDistanceJointFlags(flags);+ shapeDistance(joint, minLength, maxLength, frequency, damping);return adopt(entity, joint, JointKind::Distance, collideConnected);}@@ -351,6 +374,52 @@ void physics3d_setJointMotor(uint32_t entity, int enable, float speed) {}}+EMSCRIPTEN_KEEPALIVE+void physics3d_setJointLimits(uint32_t entity, int enable, float lower, float upper) {+ auto found = g().joints.find(entity);+ if (found == g().joints.end() || !std::isfinite(lower) || !std::isfinite(upper)) return;+ if (found->second.kind == JointKind::Hinge) {+ auto* hinge = static_cast<PxRevoluteJoint*>(found->second.joint);+ float lo = 0.0f, hi = 0.0f;+ hingeRange(lower, upper, lo, hi);+ hinge->setLimit(PxJointAngularLimitPair(lo, hi));+ hinge->setRevoluteJointFlag(PxRevoluteJointFlag::eLIMIT_ENABLED, enable != 0);+ } else if (found->second.kind == JointKind::Slider) {+ auto* slider = static_cast<PxD6Joint*>(found->second.joint);+ slider->setMotion(PxD6Axis::eX, enable != 0 ? PxD6Motion::eLIMITED : PxD6Motion::eFREE);+ if (enable != 0) slider->setLinearLimit(PxD6Axis::eX, PxJointLinearLimitPair(std::min(lower, 0.0f), std::max(upper, 0.0f), PxSpring(0.0f, 0.0f)));+ } else {+ return;+ }+ wakeEnds(found->second.joint);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setJointMotorLimit(uint32_t entity, float limit) {+ auto found = g().joints.find(entity);+ if (found == g().joints.end() || !std::isfinite(limit) || limit < 0.0f) return;+ found->second.maxForce = limit;+ if (found->second.kind == JointKind::Hinge) {+ static_cast<PxRevoluteJoint*>(found->second.joint)->setDriveForceLimit(limit);+ } else if (found->second.kind == JointKind::Slider) {+ auto* slider = static_cast<PxD6Joint*>(found->second.joint);+ // A drive that is on has damping; one that is off has none, and stays off.+ if (slider->getDrive(PxD6Drive::eX).damping > 0.0f) slider->setDrive(PxD6Drive::eX, motor(true, limit));+ } else {+ return;+ }+ wakeEnds(found->second.joint);+}++EMSCRIPTEN_KEEPALIVE+void physics3d_setDistanceJoint(uint32_t entity, float minLength, float maxLength, float frequency, float damping) {+ auto found = g().joints.find(entity);+ if (found == g().joints.end() || found->second.kind != JointKind::Distance) return;+ if (!std::isfinite(minLength) || !std::isfinite(maxLength) || !std::isfinite(frequency) || !std::isfinite(damping)) return;+ shapeDistance(static_cast<PxDistanceJoint*>(found->second.joint), minLength, maxLength, frequency, damping);+ wakeEnds(found->second.joint);+}+EMSCRIPTEN_KEEPALIVEfloat physics3d_jointValue(uint32_t entity) {auto found = g().joints.find(entity);diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cppindex f67afcf89..b11d7722c 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp@@ -687,6 +687,33 @@ int physics3d_getBodyDynamics(uint32_t bodyId) {return 1;}+EMSCRIPTEN_KEEPALIVE+int physics3d_getBodyMassData(uint32_t bodyId) {+ PxRigidDynamic* dynamic = dynamicOf(bodyId);+ if (!g().isValid() || dynamic == nullptr || isKinematic(dynamic)) return 0;+ const float mass = dynamic->getMass();+ if (!(mass > 0.0f)) return 0;+ const PxVec3 centre = (dynamic->getGlobalPose() * dynamic->getCMassLocalPose()).p;+ // About the body's own axes, as the Jolt world answers: the mass frame may be turned from them, so each axis is+ // taken into it, its inverse moments weighed along it, and the moment is the inverse of that.+ const PxVec3 inertia = dynamic->getMassSpaceInertiaTensor();+ const PxQuat frame = dynamic->getCMassLocalPose().q;+ const PxRigidDynamicLockFlags locked = dynamic->getRigidDynamicLockFlags();+ const float inf = std::numeric_limits<float>::infinity();+ const auto moment = [&](const PxVec3& axis, bool isLocked) {+ if (isLocked) return inf;+ const PxVec3 a = frame.rotateInv(axis);+ const auto inv = [](float i) { return i > 0.0f ? 1.0f / i : 0.0f; };+ const float weighed = a.x * a.x * inv(inertia.x) + a.y * a.y * inv(inertia.y) + a.z * a.z * inv(inertia.z);+ return weighed > 0.0f ? 1.0f / weighed : inf;+ };+ g().queryBuffer = {mass, centre.x, centre.y, centre.z,+ moment(PxVec3(1, 0, 0), static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)),+ moment(PxVec3(0, 1, 0), static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)),+ moment(PxVec3(0, 0, 1), static_cast<bool>(locked & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z))};+ return 1;+}+EMSCRIPTEN_KEEPALIVEvoid physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {PxRigidDynamic* dynamic = dynamicOf(bodyId);diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cppindex 0fb32b580..3b47738e2 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp@@ -384,6 +384,51 @@ int physics3d_sphereCast(float px, float py, float pz, float radius,return 1;}+namespace {+/// A turn that is not one - zero, or not a number - is no turn.+static PxQuat turnOf(float qx, float qy, float qz, float qw) {+ const PxQuat q(qx, qy, qz, qw);+ const float length = q.magnitude();+ return std::isfinite(length) && length > 1e-6f ? q * (1.0f / length) : PxQuat(PxIdentity);+}++/// A geometry swept from a pose: the first body it meets, as sphereCast writes it.+static int sweepQuery(const PxGeometry& shape, const PxTransform& pose, float dx, float dy, float dz, uint32_t layerMask) {+ PxVec3 dir(dx, dy, dz);+ const float length = dir.normalizeSafe();+ if (!(length > 0.0f)) return 0;+ PxSweepBuffer hit;+ LayerFilter filter(layerMask, false);+ if (!g().scene->sweep(shape, pose, dir, length, hit, PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, queryData(), &filter)+ || !hit.hasBlock) return 0;+ const PxSweepHit& b = hit.block;+ g().queryBuffer = {static_cast<float>(px3::entityOf(b.actor)), b.distance / length,+ b.position.x, b.position.y, b.position.z, b.normal.x, b.normal.y, b.normal.z};+ return 1;+}+} // namespace++EMSCRIPTEN_KEEPALIVE+int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || !(hx > 0.0f) || !(hy > 0.0f) || !(hz > 0.0f)) return 0;+ return sweepQuery(PxBoxGeometry(hx, hy, hz), PxTransform(PxVec3(px, py, pz), turnOf(qx, qy, qz, qw)), dx, dy, dz, layerMask);+}++EMSCRIPTEN_KEEPALIVE+int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,+ float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || !(radius > 0.0f) || !(halfHeight >= 0.0f)) return 0;+ if (halfHeight == 0.0f) return physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, layerMask);+ // A PhysX capsule lies along its x; turned a quarter about z it stands along y, as the Jolt world's and a+ // character's do.+ const PxQuat upright(PxHalfPi, PxVec3(0.0f, 0.0f, 1.0f));+ return sweepQuery(PxCapsuleGeometry(radius, halfHeight), PxTransform(PxVec3(px, py, pz), turnOf(qx, qy, qz, qw) * upright),+ dx, dy, dz, layerMask);+}+EMSCRIPTEN_KEEPALIVEint physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask) {return physics3d_raycastWith(ox, oy, oz, dx, dy, dz, layerMask, 0);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex b41d54f5c..ed8c0ca7c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4744,4 +4744,6 @@ export const NOTED = {{"note": "A script can push a 3D body about."},"feat(editor): the breakable check sets off a blast beside the last pot, which breaks it and throws the pebble at its foot":{"note": "A blast."},+ "feat(physics3d): a turned box and an upright capsule can be swept, a body's mass data read, and a joint's range, motor limit, lengths and spring changed while it runs, from Jolt and PhysX alike; a Jolt motor switched on in play keeps its torque limit":+ {"note": "A joint changed while it runs."},};