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): what a shooter asks of the 3D world - raycastAll names every body on a line with how thick it was, joints give way past a breakForce or breakTorque, a character's meetings are told and strike what can break, and Hitboxes put a box on each bone that follows the animation, from Jolt and PhysX alike
yhh1c0ac2480f9f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 44a4771de..da0ad5ef4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,10 @@ published separately; it ships inside the editor.- **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.+- **A shot through cover.** `Physics3D.raycastAll(origin, direction, layers, maxHits)` names every body on a line, nearest first, each with where the line goes in and comes out and how thick it was there, so a shot can spend its strength on a plaster wall and go on into what is behind it. Along a line through a 0.2 m wall, a 1 m box and a bone-sized sensor, both the Jolt and PhysX worlds named all three with their entry and exit to four places and measured the wall at 0.2000 m; a line that ends inside a body comes out of it at its end.+- **A joint that gives way.** Every 3D joint takes a `breakForce` (N) and `breakTorque` (N m): held with more than either over a step, it is taken out of the world, its `enabled` lowered, and the break told in `Physics3DEvents.jointBreaks`, so a chandelier comes down when its mount is pulled harder than it holds. A 2 kg weight hanging on a rope pulls on it with 19.62 N in both worlds; in the editor a rope rated at 15 N gave way and its weight fell to the floor while one rated at 30 N held.+- **A character that runs into something says so.** `Physics3DEvents.characterHits` tells what a 3D character ran into that it was not already touching, once a meeting, with how fast it closed, the mass they met with and the impulse, as a contact between bodies does; a `Breakable` a character runs into is struck with it, so a dive through a window breaks it and a lean on it does not. A character dropped 2.1 m onto a floor told it once, at 6.38 m/s against the 6.42 the fall gives and with its own 70 kg, and walking into a 30 kg crate at 3 m/s met it with 21 kg, in both worlds.+- **Telling the parts of a character apart.** `Hitboxes` puts a box on each bone of a skinned character, the size its ragdoll would give it, that follows the animation: a kinematic sensor that nothing walks into or is pushed by and that a ray meets, so a shot names the bone it struck and `hitPartOf` says whose. While the ragdoll is limp its own bodies stand in. In the editor a character from the character-rig example given `Hitboxes` had a sensor box on each of its bones, a ray at one of them met that character's bone by name, and three quarters of a second of animation later a ray where the bone had gone still met it.### Fixeddiff --git a/desktop b/desktopindex 8e727c571..0dbf5025b 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 8e727c5718a435c181539e0e40e249a16ce58e2c+Subproject commit 0dbf5025bd623e940122943a85811532344fcc22diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex 17dad6fce..8b7dbee96 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -425,6 +425,35 @@ next.a collider too, and it is `Health` that says an entity can be hurt at all.</Aside>+## Telling the parts of a character apart++A character's capsule is one shape, so a shot that meets it cannot say whether+it met a head or a boot. Give the character a `Hitboxes` and each bone long+enough gets a box along it, the size its ragdoll would give it: a kinematic+body the world moves to wherever the animation has put the bone, and a sensor,+so nothing walks into it or is pushed by it, its own character included. A ray+meets the bone, and `hitPartOf` says whose it is and which.++```typescript+world.insert(soldier, Hitboxes, { layer: HITBOXES });+// a shot:+const hit = physics.raycast(muzzle, aim, WORLD | HITBOXES_MASK);+const part = hit && hitPartOf(world, hit.entity); // { character, bone: 'head' }+const damage = part?.bone.toLowerCase().includes('head') ? 100 : 34;+```++| Property | Default | Description |+|---|---|---|+| `skin` | `0` | The skinned mesh whose bones get boxes; 0 finds the first on the entity or below it. |+| `thickness` | `0.25` | A box's thickness as a fraction of its bone's length. |+| `minBoneLength` | `5` | A bone shorter than this (world units) gets no box; what hangs from it is its parent's. |+| `layer` | `0` | The collision layer the boxes are in, so a shot can ask for them and a sight line leave them out. |++While the character's `Ragdoll` is limp its bones are bodies of their own,+which a ray meets just as well; the boxes give way to them and come back when it+stands up. How much a head is worth against a hand is the game's: the engine+says which part was met.+## JointsA door, a rope bridge, a lift, a ragdoll: none of them are one body and a shape.@@ -462,7 +491,12 @@ 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`: adoor 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+on it pulls it up. Every joint also takes a `breakForce` (N) and `breakTorque` (N m):+held with more than either over a step, it is taken out of the world, its+`enabled` lowered, and the break told in `Physics3DEvents.jointBreaks`. A+chandelier on a `FixedJoint3D` with a `breakForce` comes down when a shot or a+blast pulls harder than its mount holds; raising `enabled` again joins the two+where they are then. A range always holds the pose the joint was made in: one thatdoes not reach 0 (`lowerAngle: 0.2`) is widened to 0, and a hinge's goes nofurther 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 far@@ -505,6 +539,7 @@ const occupants = q.overlapSphere(spawnPoint, 50);| Query | Answers ||---|---|| `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. |+| `raycastAll(origin, direction, layerMask?, maxHits?)` | Every body on the line, nearest first, each with `fraction` and `exitFraction` where the line goes in and out and `thickness`, how much of it the line crosses in world units: a shot through thin cover spends its strength on each in turn. || `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. |@@ -600,6 +635,8 @@ for (const { sensorEntity, visitorEntity } of events.sensorEnters) {|---|---|| `contactEnters` | Both entities, the contact normal and the point, in the same units as `Transform`, and `speed`: how fast the first was closing on the second where they met, along the normal, in those units a second, read before the solver answered (a ball dropped a metre lands at about 4.4 m/s); `mass`, the kilograms they met with, 1 / (1/a + 1/b) with a body that does not move counting as no inverse mass, so a stone landing on a floor meets it with its own; and `impulse`, `speed` times `mass`, how hard. || `contactExits` | Only the pair — see below. |+| `characterHits` | What a character ran into that it was not already touching, once a meeting: `character`, `other`, the point, the normal toward the character, `speed`, `mass` (its own against something that does not move) and `impulse`, as a contact's. A `Breakable` a character runs into is struck with it, so a dive through a window breaks it and a lean on it does not. |+| `jointBreaks` | Joints that gave way this step: `entity`, `force` (N) and `torque` (N m). || `sensorEnters` / `sensorExits` | The **sensor first**, then the visitor. |<Aside>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 fbeaf3ba3..e1bc506ee 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@@ -369,6 +369,31 @@ const hitSparks = defineSystem(玩法的规则,跟着这一刀走——地板也是碰撞体,而一个实体能不能被打,是 `Health` 说了算。</Aside>+## 分辨角色的部位++角色的胶囊是一个整体,射中它时分不出打中的是头还是靴子。给角色加上 `Hitboxes`,每根足够长的+骨骼都会得到一个沿骨骼的盒子,大小与布娃娃给它的一致:它是一个运动学刚体,世界会把它移到动画+把骨骼放到的位置;它也是传感器,任何东西都不会撞上它或被它推开,包括它自己的角色。射线命中的就是+那根骨骼,`hitPartOf` 会告诉你它属于谁、是哪一根。++```typescript+world.insert(soldier, Hitboxes, { layer: HITBOXES });+// 射击时:+const hit = physics.raycast(muzzle, aim, WORLD | HITBOXES_MASK);+const part = hit && hitPartOf(world, hit.entity); // { character, bone: 'head' }+const damage = part?.bone.toLowerCase().includes('head') ? 100 : 34;+```++| 属性 | 默认 | 说明 |+|---|---|---|+| `skin` | `0` | 要挂盒子的蒙皮网格;0 表示在本实体或其下找第一个。 |+| `thickness` | `0.25` | 盒子的粗细,占骨骼长度的比例。 |+| `minBoneLength` | `5` | 短于此长度(世界单位)的骨骼不单独挂盒子,挂在它下面的归父骨骼。 |+| `layer` | `0` | 盒子所在的碰撞层,射击时可以专门查它们,视线检测时可以排除它们。 |++角色的 `Ragdoll` 瘫软时,骨骼会变成各自独立的刚体,射线一样能命中;这时盒子让位,角色站起来后+再装回去。打中头和打中手各值多少伤害由游戏决定,引擎只负责告诉你打中的是哪个部位。+## 关节门、绳桥、升降台、布娃娃:它们都不是「一个刚体加一个形状」,@@ -403,7 +428,9 @@ cmds.spawn()`motorSpeed` 随时可以由游戏逻辑改写——变了就会重新驱动世界。铰链和滑轨的 `enableLimit`、`lowerAngle`/`upperAngle` 或 `lowerTranslation`/`upperTranslation`、`maxMotorTorque`/`maxMotorForce`,以及距离关节的 `minLength`、`maxLength`、`frequency`、`damping` 也一样:收窄门的范围就能把门锁住,-运行中缩短绳子会把挂着的东西拉上来。范围总是包含关节建立时的姿态:不含 0 的范围(如 `lowerAngle: 0.2`)+运行中缩短绳子会把挂着的东西拉上来。每种关节还有 `breakForce`(N)和 `breakTorque`(N·m):某一步承受的力或扭矩超过它,+关节就会从世界中移除,`enabled` 置为 false,并在 `Physics3DEvents.jointBreaks` 里报告。用带 `breakForce` 的+`FixedJoint3D` 挂起的吊灯,被子弹或爆炸拉得超过挂点承受力时就会掉下来;重新打开 `enabled`,两者会在当时的位置重新连上。范围总是包含关节建立时的姿态:不含 0 的范围(如 `lowerAngle: 0.2`)会扩展到 0,铰链的范围在两个求解器里都不超过正反各半圈。反方向上,`HingeJoint3D.angle` 与 `SliderJoint3D.translation` 每步写回,所以游戏可以直接问「门开了多少」,不必自己再积分一遍。@@ -442,6 +469,7 @@ const occupants = q.overlapSphere(spawnPoint, 50);| 查询 | 回答 ||---|---|| `raycast(origin, direction, layerMask?)` | 一条线上最近的刚体,形如 `{ entity, fraction, x, y, z, normalX, normalY, normalZ }`,没有则为 `null`。`direction` 自带射线长度。 |+| `raycastAll(origin, direction, layerMask?, maxHits?)` | 射线上的每个刚体,由近到远,每个带 `fraction` 和 `exitFraction`(射入与射出的位置)以及 `thickness`(射线穿过它的长度,世界单位):穿透薄掩体的子弹依次在每个上消耗威力。 || `sphereCast(origin, radius, direction, layerMask?)` | 一个运动的球最先撞上的刚体,形状同上,没有则为 `null`。 || `boxCast(origin, halfExtents, direction, layerMask?, rotation?)` | 盒子的同样查询,可用 `rotation` 旋转:箱子能不能穿过门。 || `capsuleCast(origin, radius, halfHeight, direction, layerMask?, rotation?)` | 胶囊的同样查询,胶囊沿自身 y 轴竖立,和角色一样;`halfHeight` 是中间直段的一半。 |@@ -528,6 +556,8 @@ for (const { sensorEntity, visitorEntity } of events.sensorEnters) {|---|---|| `contactEnters` | 两个实体、接触法线和接触点,接触点与 `Transform` 同单位;以及 `speed`:接触时第一个物体沿法线靠近第二个物体的速度,同单位每秒,在求解器处理之前读取(从一米高落下的球约以 4.4 m/s 着地);`mass`:两者相撞时的有效质量(千克),1 / (1/a + 1/b),不动的物体视为逆质量为 0,所以石头落在地上时就是石头自己的质量;`impulse`:`speed` 乘 `mass`,即撞击力度。 || `contactExits` | 只有这一对——原因见下。 |+| `characterHits` | 角色撞上的、之前没在接触的东西,每次相遇报一次:`character`、`other`、接触点、指向角色的法线、`speed`、`mass`(对不动的物体就是角色自身质量)和 `impulse`,与刚体接触的含义相同。角色撞上的 `Breakable` 会以这个冲量受击,所以扑窗会撞碎玻璃,靠在玻璃上不会。 |+| `jointBreaks` | 这一步断开的关节:`entity`、`force`(N)和 `torque`(N·m)。 || `sensorEnters` / `sensorExits` | **传感器在前**,然后是访客。 |<Aside>diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 198ee4c2d..b285ae784 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": 178,- "experimental": 3101,+ "experimental": 3105,"deprecated": 3},- "total": 3394,+ "total": 3398,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 65c106643..bd2731cab 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -179,6 +179,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {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: '近战' },Ragdoll: { category: 'physics', summary: 'Turns a skinned character\'s bones into jointed bodies while active, with limits by part of the body and one-way knees and elbows, and blends back to the animation when it is switched off.', doc: 'gameplay/physics-3d', anchor: 'ragdoll', anchorZh: '布娃娃' },+ Hitboxes: { category: 'physics', summary: 'A box on each bone of a skinned character that follows the animation: a kinematic sensor a ray meets and names, so a shot can tell a head from a boot.', doc: 'gameplay/physics-3d', anchor: 'telling-the-parts-of-a-character-apart', anchorZh: '分辨角色的部位' },RagdollJoint: { category: 'physics', summary: 'What the author says of one bone of a ragdoll: no body of its own, or limits (and a one-way bend) of its own.', doc: 'gameplay/physics-3d', anchor: 'ragdoll', anchorZh: '布娃娃' },FirstPersonController: { category: 'physics', summary: 'Looks, walks, jumps and crouches in a CharacterController3D from the keyboard, the pointer and the touch screen, through a camera on a child.', doc: 'gameplay/physics-3d', anchor: 'first-person', anchorZh: '第一人称' },FirstPersonViewModel: { category: 'physics', summary: 'On the player\'s camera: draws what is held with a second camera over the world\'s, with its own field of view and near plane, so it does not go through walls.', doc: 'gameplay/physics-3d', anchor: 'a-view-model', anchorZh: '视图模型' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 51b58c62f..a687560f5 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1711,6 +1711,16 @@"key": "enabled","type": "boolean","default": "true"+ },+ {+ "key": "breakForce",+ "type": "number",+ "default": "0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0"}],"animatable": [@@ -1724,7 +1734,9 @@"minLength","maxLength","frequency",- "damping"+ "damping",+ "breakForce",+ "breakTorque"]},{@@ -2286,10 +2298,22 @@"key": "enabled","type": "boolean","default": "true"+ },+ {+ "key": "breakForce",+ "type": "number",+ "default": "0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0"}],"animatable": [- "connectedEntity"+ "connectedEntity",+ "breakForce",+ "breakTorque"]},{@@ -3463,6 +3487,16 @@"type": "boolean","default": "true"},+ {+ "key": "breakForce",+ "type": "number",+ "default": "0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0"+ },{"key": "angle","type": "number",@@ -3481,9 +3515,54 @@"upperAngle","motorSpeed","maxMotorTorque",+ "breakForce",+ "breakTorque","angle"]},+ {+ "name": "Hitboxes",+ "source": "ts",+ "fields": [+ {+ "key": "skin",+ "type": "Entity",+ "default": "none"+ },+ {+ "key": "thickness",+ "type": "number",+ "default": "0.25",+ "doc": "A box's thickness as a fraction of its bone's length.",+ "range": "0.01–2"+ },+ {+ "key": "minBoneLength",+ "type": "number",+ "default": "5",+ "doc": "A bone shorter than this gets no box of its own, in world units.",+ "range": "≥ 0"+ },+ {+ "key": "layer",+ "type": "number",+ "default": "0",+ "doc": "The collision layer the boxes are in, for a shot to ask for.",+ "range": "0–15, step 1"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "skin",+ "thickness",+ "minBoneLength",+ "layer"+ ]+ },{"name": "Hunter","source": "ts",@@ -6051,13 +6130,25 @@"key": "enabled","type": "boolean","default": "true"+ },+ {+ "key": "breakForce",+ "type": "number",+ "default": "0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0"}],"animatable": ["connectedEntity","anchor.x","anchor.y",- "anchor.z"+ "anchor.z",+ "breakForce",+ "breakTorque"]},{@@ -6997,6 +7088,20 @@"type": "boolean","default": "true"},+ {+ "key": "breakForce",+ "type": "number",+ "default": "0",+ "doc": "Newtons it gives way at; 0 never.",+ "range": "≥ 0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0",+ "doc": "Newton metres of twist it gives way at; 0 never.",+ "range": "≥ 0"+ },{"key": "translationMotion","type": "Vec3",@@ -7058,6 +7163,8 @@"angularVelocity.y","angularVelocity.z","maxMotorTorque",+ "breakForce",+ "breakTorque","translationMotion.x","translationMotion.y","translationMotion.z",@@ -7241,6 +7348,16 @@"type": "boolean","default": "true"},+ {+ "key": "breakForce",+ "type": "number",+ "default": "0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0"+ },{"key": "translation","type": "number",@@ -7259,6 +7376,8 @@"upperTranslation","motorSpeed","maxMotorForce",+ "breakForce",+ "breakTorque","translation"]},@@ -7999,6 +8118,20 @@"type": "boolean","default": "true"},+ {+ "key": "breakForce",+ "type": "number",+ "default": "0",+ "doc": "Newtons it gives way at; 0 never.",+ "range": "≥ 0"+ },+ {+ "key": "breakTorque",+ "type": "number",+ "default": "0",+ "doc": "Newton metres of twist it gives way at; 0 never.",+ "range": "≥ 0"+ },{"key": "normalHalfConeAngle","type": "number",@@ -8039,6 +8172,8 @@"angularVelocity.y","angularVelocity.z","maxMotorTorque",+ "breakForce",+ "breakTorque","normalHalfConeAngle","planeHalfConeAngle","twistMinAngle",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6967e337f..85a7b50c4 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3698,6 +3698,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -4530,6 +4532,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -5362,6 +5366,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -8168,6 +8174,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -10248,6 +10256,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -10372,6 +10382,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -11337,6 +11349,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex e3c512126..d12070210 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3706,6 +3706,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -4538,6 +4540,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -5370,6 +5374,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -8382,6 +8388,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -10477,6 +10485,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -10601,6 +10611,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -11566,6 +11578,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 403f5ca78..61c83a5cc 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3693,6 +3693,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -4525,6 +4527,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -5357,6 +5361,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -8163,6 +8169,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -10243,6 +10251,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -10367,6 +10377,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -11332,6 +11344,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex efa75f2a8..3445b2059 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3693,6 +3693,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -4525,6 +4527,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -5357,6 +5361,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -8460,6 +8466,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -10540,6 +10548,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -10664,6 +10674,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -11629,6 +11641,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: booleandiff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.mdindex 8bf31ad5b..f1319380d 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 · 81 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 85 experimental · 0 deprecated## BONE_LIMITS — const @experimental```@@ -172,6 +172,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -189,6 +191,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -204,6 +208,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -215,6 +221,20 @@ motorSpeed: numberupperAngle: number```+## Hitboxes — const @experimental+```+ComponentDef<HitboxesData>+```++## HitboxesData — interface @experimental+```+enabled: boolean+layer: number+minBoneLength: number+skin: number+thickness: number+```+## Joint3DShape — interface @experimental```anchor: Vec3 | null@@ -296,8 +316,10 @@ ResourceDef<Physics3DEventsData>## Physics3DEventsData — interface @experimental```+characterHits: CharacterHit3DEvent[] | undefinedcontactEnters: Contact3DEvent[]contactExits: { entityA: Entity; entityB: Entity; }[]+jointBreaks: JointBreak3DEvent[] | undefinedsensorEnters: Sensor3DEvent[]sensorExits: Sensor3DEvent[]```@@ -335,6 +357,7 @@ isAwake: (entity: Entity) => booleanoverlapBox: (centre: { x: number; y: number; z: number; }, halfExtents: { x: number; y: number; z: number; }, layerMask?: number) => Overlap3DHit[]overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => Overlap3DHit[]raycast: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, layerMask?: number, options?: { characters?: boolean; }) => Cast3DHit | null+raycastAll: (origin: { x: number; y: number; z: number; }, direction: { x: number; y: number; z: number; }, layerMask?: number, maxHits?: number) => RaycastAll3DHit[]setAngularVelocity: (entity: Entity, velocity: { x: number; y: number; z: number; }) => booleansetAwake: (entity: Entity, awake: boolean) => booleansetGravity: (gravity: { x: number; y: number; z: number; }) => boolean@@ -382,6 +405,8 @@ _physics3d_addSwingTwistJoint: (entity: number, bodyA: number, bodyB: number, px_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_characterHits: (() => number) | undefined+_physics3d_characterHitsBytes: (() => number) | undefined_physics3d_contactEnterMasses: (() => number) | undefined_physics3d_contactEnterMassesBytes: (() => number) | undefined_physics3d_contactEnterSpeeds: (() => number) | undefined@@ -396,6 +421,7 @@ _physics3d_getBodyState: (bodyId: number) => number_physics3d_init: (gx: number, gy: number, gz: number, maxBodies: number) => void_physics3d_isAwake: ((bodyId: number) => number) | undefined_physics3d_isReady: () => number+_physics3d_jointForce: ((entity: number) => number) | undefined_physics3d_jointValue: (entity: number) => number_physics3d_moveCharacter: (characterId: number, vx: number, vy: number, vz: number, dt: number, stepUp: number, stepDown: number) => void_physics3d_optimize: () => void@@ -404,6 +430,7 @@ _physics3d_overlapSphere: (px: number, py: number, pz: number, radius: number, l_physics3d_queryResult: () => number_physics3d_queryResultBytes: () => number_physics3d_raycast: (ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, layerMask: number) => number+_physics3d_raycastAll: ((ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, layerMask: number, maxHits: number) => number) | undefined_physics3d_raycastWith: (ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, layerMask: number, flags: number) => number_physics3d_removeBody: (bodyId: number) => void_physics3d_removeCharacter: (characterId: number) => void@@ -441,6 +468,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -523,6 +552,20 @@ skin: number{ readonly Uniform: 0; readonly Humanoid: 1; }```+## RaycastAll3DHit — interface @experimental+```+entity: number+exitFraction: number+fraction: number+normalX: number+normalY: number+normalZ: number+thickness: number+x: number+y: number+z: number+```+## RigidBody3D — const @experimental```BuiltinComponentDef<RigidBody3DData>@@ -557,6 +600,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -582,6 +627,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -619,6 +666,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -656,6 +705,11 @@ twistMinAngle: number(app: App, contacts?: readonly Contact3D[]): void```+## hitPartOf — function @experimental+```+(world: World, entity: Entity): { character: Entity; bone: string; } | null+```+## joint3DSettingsError — function @experimental```(d: SwingTwistJoint3DData | SixDOFJoint3DData): string | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 1e5e4ef49..27c4d184f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3693,6 +3693,8 @@ ComponentDef<DistanceJoint3DData>## DistanceJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedAnchor: Vec3connectedEntity: number@@ -4525,6 +4527,8 @@ ComponentDef<FixedJoint3DData>## FixedJoint3DData — interface @experimental```+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -5357,6 +5361,8 @@ ComponentDef<HingeJoint3DData>anchor: Vec3angle: numberaxis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -8170,6 +8176,8 @@ ComponentDef<PointJoint3DData>## PointJoint3DData — interface @experimental```anchor: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenabled: boolean@@ -10250,6 +10258,8 @@ ComponentDef<SixDOFJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: boolean@@ -10374,6 +10384,8 @@ ComponentDef<SliderJoint3DData>```anchor: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableLimit: boolean@@ -11339,6 +11351,8 @@ ComponentDef<SwingTwistJoint3DData>anchor: Vec3angularVelocity: Vec3axis: Vec3+breakForce: number+breakTorque: numbercollideConnected: booleanconnectedEntity: numberenableMotor: booleandiff --git a/sdk/src/physics3d/AdvancedJoint3D.ts b/sdk/src/physics3d/AdvancedJoint3D.tsindex 691de0a03..1bb4b566b 100644--- a/sdk/src/physics3d/AdvancedJoint3D.ts+++ b/sdk/src/physics3d/AdvancedJoint3D.ts@@ -18,6 +18,10 @@ interface JointFrame3D {maxMotorTorque: number;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;}/** Shoulder/hip rotation about a twist axis with an elliptical swing cone. @experimental */@@ -46,7 +50,7 @@ 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,+ maxMotorTorque: 10, collideConnected: false, enabled: true, breakForce: 0, breakTorque: 0,};const fields: Record<string, FieldMeta> = {anchor: { tooltip: 'Attachment in this entity’s local frame, in world units.' },@@ -56,6 +60,8 @@ const fields: Record<string, FieldMeta> = {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' },+ breakForce: { category: 'Breaking', min: 0, tooltip: 'Newtons it gives way at; 0 never.' },+ breakTorque: { category: 'Breaking', min: 0, tooltip: 'Newton metres of twist it gives way at; 0 never.' },};/** A limited ball joint with separate twist limits. Angles are radians. @experimental */diff --git a/sdk/src/physics3d/Physics3DJoints.ts b/sdk/src/physics3d/Physics3DJoints.tsindex 7b8501837..e142d8204 100644--- a/sdk/src/physics3d/Physics3DJoints.ts+++ b/sdk/src/physics3d/Physics3DJoints.ts@@ -18,7 +18,7 @@ import type { TransformData } from '../ecs/component.generated';import type { App } from '../app/app';import type { World } from '../ecs/world';import type { Entity, Vec3 } from '../types';-import type { Physics3DWasmModule } from './Physics3DModule';+import type { JointBreak3DEvent, Physics3DWasmModule } from './Physics3DModule';import { rotateVec3ByQuat } from './ColliderShape3D';import { SwingTwistJoint3D, SixDOFJoint3D, joint3DSettingsError, advancedJointSettings, jointMotionBits,type SwingTwistJoint3DData, type SixDOFJoint3DData } from './AdvancedJoint3D';@@ -30,6 +30,10 @@ export interface PointJoint3DData {anchor: Vec3;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;}/**@@ -42,6 +46,8 @@ export const PointJoint3D = defineComponent<PointJoint3DData>('PointJoint3D', {anchor: { x: 0, y: 0, z: 0 },collideConnected: false,enabled: true,+ breakForce: 0,+ breakTorque: 0,}, {entityFields: ['connectedEntity'],fields: { anchor: { tooltip: 'Where the joint attaches, in THIS entity\'s frame (world units).' } },@@ -59,6 +65,10 @@ export interface HingeJoint3DData {maxMotorTorque: number;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;/** Where the hinge is now, in radians. Written by the world each step. */angle: number;}@@ -81,6 +91,8 @@ export const HingeJoint3D = defineComponent<HingeJoint3DData>('HingeJoint3D', {maxMotorTorque: 0,collideConnected: false,enabled: true,+ breakForce: 0,+ breakTorque: 0,angle: 0,}, {entityFields: ['connectedEntity'],@@ -99,6 +111,10 @@ export interface SliderJoint3DData {maxMotorForce: number;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;/** How far along the axis it has travelled, in world units. Written by the* world each step. */translation: number;@@ -122,6 +138,8 @@ export const SliderJoint3D = defineComponent<SliderJoint3DData>('SliderJoint3D',maxMotorForce: 0,collideConnected: false,enabled: true,+ breakForce: 0,+ breakTorque: 0,translation: 0,}, {entityFields: ['connectedEntity'],@@ -138,6 +156,10 @@ export interface DistanceJoint3DData {damping: number;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;}/**@@ -156,12 +178,18 @@ export const DistanceJoint3D = defineComponent<DistanceJoint3DData>('DistanceJoidamping: 0.5,collideConnected: false,enabled: true,+ breakForce: 0,+ breakTorque: 0,}, { entityFields: ['connectedEntity'] });export interface FixedJoint3DData {connectedEntity: number;collideConnected: boolean;enabled: boolean;+ /** The force it gives way at, in newtons: past it the joint is taken out of the world and `enabled` lowered. 0 never. */+ breakForce: number;+ /** The twist it gives way at, in newton metres. 0 never. */+ breakTorque: number;}/**@@ -174,6 +202,8 @@ export const FixedJoint3D = defineComponent<FixedJoint3DData>('FixedJoint3D', {connectedEntity: -1,collideConnected: false,enabled: true,+ breakForce: 0,+ breakTorque: 0,}, { entityFields: ['connectedEntity'] });/** The joint components, in the order the system offers an entity's to the world. */@@ -422,6 +452,30 @@ function reshape(app: App, module: Physics3DWasmModule, entity: Entity, held: Joheld.shape = signature;}+/**+ * Take out of the world every joint that held with more than its breakForce or breakTorque over the step just run, lower its+ * `enabled` so it is not made again, and say so. A joint raised again is made afresh between the bodies where they are then.+ */+export function breakJoints3D(app: App, module: Physics3DWasmModule, joints: Joint3DMap, broken?: JointBreak3DEvent[]): void {+ if (!module._physics3d_jointForce) return;+ for (const [entity, held] of [...joints]) {+ const def = JOINT3D_TYPES.find((d) => d._name === held.type);+ if (!def || !app.world.valid(entity) || !app.world.has(entity, def)) continue;+ const d = app.world.get(entity, def) as unknown as { breakForce?: number; breakTorque?: number; enabled: boolean };+ const maxForce = d.breakForce ?? 0, maxTorque = d.breakTorque ?? 0;+ if (!(maxForce > 0) && !(maxTorque > 0)) continue;+ if (!module._physics3d_jointForce(entity as number)) continue;+ const f32 = module.HEAPF32, o = module._physics3d_queryResult() >> 2;+ const force = f32[o]!, torque = f32[o + 1]!;+ if (!((maxForce > 0 && force > maxForce) || (maxTorque > 0 && torque > maxTorque))) continue;+ module._physics3d_removeJoint(entity as number, held.bodyA, held.bodyB);+ joints.delete(entity);+ d.enabled = false;+ app.world.set(entity, def, d as never);+ broken?.push({ entity, force, torque });+ }+}+/** 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 } {diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex a4814067f..023a8a38d 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -137,6 +137,13 @@ 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: (force N, torque N m) the joint held with over the last step, to the query buffer. */+ _physics3d_jointForce?(entity: number): number;+ /** Optional for older binaries: every body on a line, (entity, entry, exit, point, normal) each, nearest first. */+ _physics3d_raycastAll?(ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, layerMask: number, maxHits: number): number;+ /** Optional for older binaries: what characters ran into this step, ten floats a meeting. */+ _physics3d_characterHits?(): number;+ _physics3d_characterHitsBytes?(): number;/** 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;@@ -255,6 +262,34 @@ export interface Contact3DEvent {impulse?: number;}+/** A character ran into something it was not already touching, as a contact between bodies would say it. */+export interface CharacterHit3DEvent {+ character: Entity;+ other: Entity;+ pointX: number;+ pointY: number;+ pointZ: number;+ /** Toward the character. */+ normalX: number;+ normalY: number;+ normalZ: number;+ /** How fast it closed on what it met, world units a second. */+ speed: number;+ /** The mass they met with, kilograms: the character's own against something that does not move. */+ mass: number;+ /** `speed` times `mass`, as a contact's: what a Breakable it ran into is struck with. */+ impulse: number;+}++/** A joint gave way: which, and what it was holding when it did. */+export interface JointBreak3DEvent {+ entity: Entity;+ /** Newtons. */+ force: number;+ /** Newton metres. */+ torque: number;+}+/** A sensor was entered or left. The SENSOR is always named first. */export interface Sensor3DEvent {sensorEntity: Entity;@@ -268,6 +303,10 @@ export interface Physics3DEventsData {contactExits: Array<{ entityA: Entity; entityB: Entity }>;sensorEnters: Sensor3DEvent[];sensorExits: Sensor3DEvent[];+ /** What characters ran into this step; empty from a binary too old to say. */+ characterHits?: CharacterHit3DEvent[];+ /** Joints that gave way this step. */+ jointBreaks?: JointBreak3DEvent[];}/**@@ -322,6 +361,18 @@ export function drainPhysics3DEvents(module: Physics3DWasmModule,});}}+ if (module._physics3d_characterHits && module._physics3d_characterHitsBytes) {+ events.characterHits = read(module._physics3d_characterHits(), module._physics3d_characterHitsBytes(), 10, (o) => {+ const speed = f32[o + 8]! * pixelsPerUnit, mass = f32[o + 9]!;+ return {+ character: f32[o] as Entity, other: f32[o + 1] as Entity,+ pointX: f32[o + 2]! * pixelsPerUnit, pointY: f32[o + 3]! * pixelsPerUnit, pointZ: f32[o + 4]! * pixelsPerUnit,+ normalX: f32[o + 5]!, normalY: f32[o + 6]!, normalZ: f32[o + 7]!,+ speed, mass, impulse: speed > 0 ? speed * mass : 0,+ };+ });+ }+ events.jointBreaks = [];events.contactExits = read(module._physics3d_contactExits(), module._physics3d_contactExitsBytes(), 2,(o) => ({ entityA: f32[o] as Entity, entityB: f32[o + 1] as Entity }));diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex 5c00edfec..29685c56a 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -7,6 +7,7 @@import { reportContact, setBodyPusher } from '../breakable/breakable';import { AnimatorController } from '../animation/Animator';import { installPlanetGravity } from './planetGravity';+import { installHitboxes } from './hitboxes';import { installRagdolls } from './ragdoll';import { Physics3DRuntime } from './physics3dRuntime';import type { App, Plugin } from '../app/app';@@ -58,6 +59,8 @@ export class Physics3DPlugin implements Plugin {installPlanetGravity(app);// A character with a Ragdoll component can go limp; with none, the systems find nothing.installRagdolls(app);+ // A character a shot can tell the parts of has a box on each bone; with none, the system finds nothing.+ installHitboxes(app);app.subsystems?.transition?.('physics3d', 'initializing');const initPromise = loadPhysics3DModule(this.wasmUrl_, this.factory_).then((module) => {@@ -92,6 +95,8 @@ export class Physics3DPlugin implements Plugin {app.hasResource(CollisionGeometryRes) ? app.getResource(CollisionGeometryRes) : null);// What met what, and how hard: told to whatever breaks, which knows nothing of the solver.for (const c of events.contactEnters) if (c.impulse !== undefined) reportContact(c.entityA, c.entityB, c.impulse, { x: c.pointX, y: c.pointY, z: c.pointZ });+ // A character that runs into a window strikes it as a body would: a dive through it, not a lean on it.+ for (const h of events.characterHits ?? []) reportContact(h.character, h.other, h.impulse, { x: h.pointX, y: h.pointY, z: h.pointZ });}, { name: 'Physics3DStepSystem' }), { profileDomain: 'physics3d' });// Installed with the world, drawn only once a game turns the resource// on — a scene that never asks for it pays a resource and nothing else.diff --git a/sdk/src/physics3d/Physics3DQueries.ts b/sdk/src/physics3d/Physics3DQueries.tsindex 06a05804a..22e7f308e 100644--- a/sdk/src/physics3d/Physics3DQueries.ts+++ b/sdk/src/physics3d/Physics3DQueries.ts@@ -25,6 +25,23 @@ export interface Cast3DHit {}/** One body an overlap test found, and a point where it touches. */+/** One body on a line: where the line goes into it and comes out, as fractions of the line, and how far that is. */+export interface RaycastAll3DHit {+ entity: Entity;+ /** Where the line goes in, 0 at its start and 1 at its end. */+ fraction: number;+ /** Where it comes out; 1 where the line ends inside it. */+ exitFraction: number;+ /** How much of it the line crosses, in world units: what a shot through it has to go through. */+ thickness: number;+ x: number;+ y: number;+ z: number;+ normalX: number;+ normalY: number;+ normalZ: number;+}+export interface Overlap3DHit {entity: Entity;x: number;@@ -266,6 +283,32 @@ export class Physics3DQueries {return hit ? this.readCast_() : null;}+ /**+ * Every body on a line, nearest first, at most `maxHits`: each with where the line goes in and comes out and how much+ * of it the line crosses. A shot that passes through thin cover asks this, and spends its strength on each in turn.+ * Characters are not met, as `raycast` does not meet them; a character with `Hitboxes` is met by its bones.+ */+ raycastAll(origin: { x: number; y: number; z: number }, direction: { x: number; y: number; z: number },+ layerMask = 0, maxHits = 16): RaycastAll3DHit[] {+ if (!this.module_._physics3d_raycastAll) return [];+ const p = this.ppu_;+ const count = this.module_._physics3d_raycastAll(origin.x / p, origin.y / p, origin.z / p,+ direction.x / p, direction.y / p, direction.z / p, layerMask, Math.max(0, Math.floor(maxHits)));+ const f32 = this.module_.HEAPF32, base = this.module_._physics3d_queryResult() >> 2;+ const length = Math.hypot(direction.x, direction.y, direction.z);+ const out: RaycastAll3DHit[] = [];+ for (let i = 0; i < count; i++) {+ const o = base + i * 9;+ out.push({+ entity: f32[o] as Entity, fraction: f32[o + 1]!, exitFraction: f32[o + 2]!,+ thickness: (f32[o + 2]! - f32[o + 1]!) * length,+ x: f32[o + 3]! * p, y: f32[o + 4]! * p, z: f32[o + 5]! * p,+ normalX: f32[o + 6]!, normalY: f32[o + 7]!, normalZ: f32[o + 8]!,+ });+ }+ return out;+ }+/*** 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.diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.tsindex 032de77f3..688c007c0 100644--- a/sdk/src/physics3d/Physics3DSystem.ts+++ b/sdk/src/physics3d/Physics3DSystem.ts@@ -27,7 +27,7 @@ import {import { getMeshCollision } from '../asset/meshCollision';import { isImplicitStatic } from './implicitStatic';import { CompoundCollider3D, encodeCompoundParts } from './CompoundCollider3D';-import { syncJoints3D, type Joint3DMap } from './Physics3DJoints';+import { breakJoints3D, syncJoints3D, type Joint3DMap } from './Physics3DJoints';import type { Entity } from '../types';import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';@@ -482,6 +482,8 @@ export function stepPhysics3D(app: App, module: Physics3DWasmModule,// Drained immediately after the step that produced them: the module's buffers// hold one step's worth and the next step clears them.if (events) drainPhysics3DEvents(module, events, ppu);+ // What gave way under this step: read now, while the step's force is the one the joint is reporting.+ breakJoints3D(app, module, joints, events?.jointBreaks);// Only bodies the solver moved are in the buffer, so this is the frame's// moving population rather than every body in the world.diff --git a/sdk/src/physics3d/hitboxes.ts b/sdk/src/physics3d/hitboxes.tsnew file mode 100644index 000000000..50798ae95--- /dev/null+++ b/sdk/src/physics3d/hitboxes.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file hitboxes.ts+ * @brief A skinned character a shot can tell the parts of: a box on each bone that follows the animation, met by rays and+ * by nothing else.+ *+ * @details A character's capsule is one shape, so a shot that meets it cannot say whether it met a head or a boot. With a+ * `Hitboxes`, each bone long enough gets a box along it, the size the character's ragdoll would give it, on the+ * bone's own entity: a kinematic body the world moves to wherever the animation has put the bone, and a sensor,+ * so nothing walks into it or is pushed by it - its own character included - and a ray still meets it. What a ray+ * meets is then the bone, and `hitPartOf` says whose and which.+ *+ * While the character's `Ragdoll` is limp its bones are bodies of their own, which a ray meets just as well; the+ * boxes give way to them, and come back when it stands up.+ */+import type { App } from '../app/app';+import type { Entity } from '../types';+import type { World } from '../ecs/world';+import { defineSystem, Schedule } from '../ecs/system';+import { playModeOnly } from '../ecs/env';+import { defineComponent, Name, Parent, type ComponentDef, type ParentData } from '../ecs/component';+import { log } from '../util/logger';+import { RigidBody3D, BoxCollider3D } from './Physics3DComponents';+import { Ragdoll, ragdollPlan, type RagdollData } from './ragdoll';++export interface HitboxesData {+ /** The skinned mesh whose bones get boxes; 0 finds the first one on the entity or below it. */+ skin: number;+ /** A box's thickness as a fraction of its bone's length, as a ragdoll's limbs. */+ thickness: number;+ /** A bone shorter than this gets no box (a finger, a toe); what hangs from it is its parent's. World units. */+ minBoneLength: number;+ /** The collision layer the boxes are in, so a shot can ask for them and a sight line can leave them out. */+ layer: number;+ enabled: boolean;+}++/** @experimental */+export const Hitboxes: ComponentDef<HitboxesData> = defineComponent<HitboxesData>('Hitboxes', {+ skin: 0, thickness: 0.25, minBoneLength: 5, layer: 0, enabled: true,+}, {+ entityFields: ['skin'],+ fields: {+ thickness: { min: 0.01, max: 2, tooltip: 'A box\'s thickness as a fraction of its bone\'s length.' },+ minBoneLength: { min: 0, tooltip: 'A bone shorter than this gets no box of its own, in world units.' },+ layer: { min: 0, max: 15, step: 1, tooltip: 'The collision layer the boxes are in, for a shot to ask for.' },+ },+});++/**+ * Which character a ray met and which of its bones, from the entity it met: the bone's own name, and the entity with the+ * `Hitboxes` (or `Ragdoll`) above it. Null for anything that is not a part of one.+ *+ * @experimental+ */+export function hitPartOf(world: World, entity: Entity): { character: Entity; bone: string } | null {+ if (!world.valid(entity)) return null;+ const bone = world.has(entity, Name) ? (world.get(entity, Name) as { value: string }).value : '';+ let at: Entity | undefined = entity;+ for (let guard = 0; at !== undefined && world.valid(at) && guard < 256; guard++) {+ if (at !== entity && (world.has(at, Hitboxes) || world.has(at, Ragdoll))) return { character: at, bone };+ at = world.has(at, Parent) ? (world.get(at, Parent) as ParentData).entity : undefined;+ }+ return null;+}++/** Installs the system that puts boxes on a character's bones and takes them off. Called once by the 3D physics plugin. */+export function installHitboxes(app: App): void {+ const world = app.world;+ /** The bones each character's boxes are on. */+ const boxed = new Map<Entity, Entity[]>();++ const take = (entity: Entity): void => {+ for (const bone of boxed.get(entity) ?? []) {+ if (!world.valid(bone)) continue;+ world.remove(bone, BoxCollider3D);+ world.remove(bone, RigidBody3D);+ }+ boxed.delete(entity);+ };++ const give = (entity: Entity, data: HitboxesData): void => {+ const plan = ragdollPlan(world, entity, { ...(Ragdoll._default as RagdollData), skin: data.skin, thickness: data.thickness, minBoneLength: data.minBoneLength });+ if (!plan) {+ log.warn('physics3d', `Hitboxes on entity ${entity} found no skinned mesh with joints on it or below it`);+ boxed.set(entity, []);+ return;+ }+ const bones: Entity[] = [];+ for (const { limb } of plan.limbs) {+ const bone = limb.entity as Entity;+ // A bone that is already a body (something else made it one) is left to that.+ if (world.has(bone, RigidBody3D)) continue;+ world.insert(bone, RigidBody3D, { bodyType: 1, layer: data.layer, enabled: true });+ world.insert(bone, BoxCollider3D, { halfExtents: limb.halfExtents, center: limb.center, isSensor: true, enabled: true });+ bones.push(bone);+ }+ boxed.set(entity, bones);+ };++ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ const live = new Set<Entity>();+ for (const entity of world.getEntitiesWithComponents([Hitboxes])) {+ live.add(entity);+ const data = world.get(entity, Hitboxes) as HitboxesData;+ const limp = world.has(entity, Ragdoll) && (world.get(entity, Ragdoll) as RagdollData).active;+ if (limp) {+ // The ragdoll has put bodies of its own on these bones, over the boxes: they are its now, and it takes them off.+ boxed.delete(entity);+ continue;+ }+ if (!data.enabled) { if (boxed.has(entity)) take(entity); continue; }+ if (!boxed.has(entity)) give(entity, data);+ }+ for (const entity of [...boxed.keys()]) if (!live.has(entity)) take(entity);+ }, { name: 'HitboxSystem' }), { runIf: playModeOnly });+}diff --git a/sdk/src/physics3d/index.ts b/sdk/src/physics3d/index.tsindex 4302c106b..971443dd9 100644--- a/sdk/src/physics3d/index.ts+++ b/sdk/src/physics3d/index.ts@@ -32,6 +32,7 @@ export {Physics3DQueries,type Cast3DHit,type Overlap3DHit,+ type RaycastAll3DHit,} from './Physics3DQueries';export {@@ -70,6 +71,7 @@ export {type CharacterController3DData,} from './Physics3DComponents';export { CompoundCollider3D, type CompoundCollider3DData, type CompoundColliderPart3D } from './CompoundCollider3D';+export { Hitboxes, hitPartOf, type HitboxesData } from './hitboxes';export {PointJoint3D,diff --git a/sdk/src/physics3d/ragdoll.ts b/sdk/src/physics3d/ragdoll.tsindex cf311f979..8a6633d9c 100644--- a/sdk/src/physics3d/ragdoll.ts+++ b/sdk/src/physics3d/ragdoll.ts@@ -416,7 +416,7 @@ export function ragdollPlan(world: World, entity: Entity, data: RagdollData): Raconst h = limb.hinge;return { limb, joint: { kind: 'sixDOF' as const, data: {connectedEntity: limb.connected, anchor: none, axis: h.axis, normalAxis: h.normalAxis,- enableMotor: false, angularVelocity: none, maxMotorTorque: 10, collideConnected: false, enabled: true,+ enableMotor: false, angularVelocity: none, maxMotorTorque: 10, collideConnected: false, enabled: true, breakForce: 0, breakTorque: 0,translationMotion: none, rotationMotion: { x: JointMotion3D.Limited, y: JointMotion3D.Locked, z: JointMotion3D.Locked },translationLower: none, translationUpper: none,rotationLower: { x: -h.upper, y: 0, z: 0 }, rotationUpper: { x: -h.lower, y: 0, z: 0 },@@ -426,7 +426,7 @@ export function ragdollPlan(world: World, entity: Entity, data: RagdollData): Raconst swing = rad(limb.swingDeg ?? data.swing * limb.swing), twist = rad(limb.twistDeg ?? data.twist * limb.twist);return { limb, joint: { kind: 'swingTwist' as const, data: {connectedEntity: limb.connected, anchor: none, axis: limb.axis, normalAxis: limb.normalAxis,- enableMotor: false, angularVelocity: none, maxMotorTorque: 10, collideConnected: false, enabled: true,+ enableMotor: false, angularVelocity: none, maxMotorTorque: 10, collideConnected: false, enabled: true, breakForce: 0, breakTorque: 0,normalHalfConeAngle: swing, planeHalfConeAngle: swing, twistMinAngle: -twist, twistMaxAngle: twist,} } };}),diff --git a/sdk/tests/physics3d-shooting.test.ts b/sdk/tests/physics3d-shooting.test.tsnew file mode 100644index 000000000..689cfd615--- /dev/null+++ b/sdk/tests/physics3d-shooting.test.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file physics3d-shooting.test.ts+ * @brief What a shooter asks of the 3D world, as the SDK reads it from the module and acts on it.+ *+ * Held here: a line's every crossing comes back in world units with how thick each was; a joint that held with more than+ * its breakForce or breakTorque is taken out, its `enabled` lowered and the break told, and one within them is left; a+ * character's meetings are read as contacts are, with the impulse they strike with; and a part a ray met is named by+ * the character above it. What the solver does is the real-solver smoke's (physics3d-smoke.mjs).+ */+import { describe, it, expect } from 'vitest';+import type { Entity } from '../src/types';+import type { App } from '../src/app/app';+import type { Physics3DWasmModule, Physics3DEventsData } from '../src/physics3d/Physics3DModule';+import { drainPhysics3DEvents } from '../src/physics3d/Physics3DModule';+import { Physics3DQueries } from '../src/physics3d/Physics3DQueries';+import { breakJoints3D, DistanceJoint3D, HingeJoint3D, type Joint3DMap } from '../src/physics3d/Physics3DJoints';++function heapModule(extra: Record<string, unknown>) {+ const heap = new Float32Array(1024);+ const calls: { name: string; args: number[] }[] = [];+ return { heap, calls, module: { HEAPF32: heap, _physics3d_queryResult: () => 0, ...extra } as unknown as Physics3DWasmModule };+}++describe('a line through cover', () => {+ it('comes back nearest first in world units, each with how thick it was', () => {+ const { heap, module } = heapModule({});+ let asked: number[] = [];+ Object.assign(module, { _physics3d_raycastAll: (...args: number[]) => {+ asked = args;+ heap.set([7, 0.495, 0.505, 9.9, 1, 0, -1, 0, 0, 8, 0.575, 0.625, 11.5, 1, 0, -1, 0, 0], 0);+ return 2;+ } });+ const physics = new Physics3DQueries(module, 100, new Map(), new Map());+ const hits = physics.raycastAll({ x: 0, y: 100, z: 0 }, { x: 2000, y: 0, z: 0 }, 2, 4);+ expect(asked).toEqual([0, 1, 0, 20, 0, 0, 2, 4]);+ expect(hits.map((h) => h.entity)).toEqual([7, 8]);+ expect(hits[0]!.thickness).toBeCloseTo(20, 2);+ expect(hits[1]!.thickness).toBeCloseTo(100, 2);+ expect(hits[0]!.x).toBeCloseTo(990, 3);+ expect(hits[0]).toMatchObject({ y: 100, normalX: -1 });+ });++ it('is no crossings in a world built before the call', () => {+ const { module } = heapModule({});+ expect(new Physics3DQueries(module, 100).raycastAll({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 })).toEqual([]);+ });+});++/** A world of joint components held in a map, as much of a World as breaking joints touches. */+function jointWorld(rows: [Entity, typeof DistanceJoint3D | typeof HingeJoint3D, Record<string, unknown>][]) {+ const store = new Map<Entity, Map<unknown, Record<string, unknown>>>();+ for (const [e, def, data] of rows) store.set(e, new Map([[def, { ...(def._default as object), ...data }]]));+ const world = {+ valid: (e: Entity) => store.has(e),+ has: (e: Entity, def: unknown) => store.get(e)?.has(def) ?? false,+ get: (e: Entity, def: unknown) => store.get(e)!.get(def)!,+ set: (e: Entity, def: unknown, data: Record<string, unknown>) => { store.get(e)!.set(def, data); },+ };+ return { app: { world } as unknown as App, world };+}++describe('a joint that gives way', () => {+ it('is taken out of the world past its breakForce, with its enabled lowered and the break told', () => {+ const { app, world } = jointWorld([+ [1 as Entity, DistanceJoint3D, { breakForce: 15 }],+ [2 as Entity, DistanceJoint3D, { breakForce: 30 }],+ [3 as Entity, HingeJoint3D, { breakTorque: 5 }],+ [4 as Entity, DistanceJoint3D, {}],+ ]);+ const forces: Record<number, [number, number]> = { 1: [19.6, 0], 2: [19.6, 0], 3: [0, 8], 4: [1e6, 1e6] };+ const removed: number[] = [];+ const asked: number[] = [];+ const { heap, module } = heapModule({+ _physics3d_jointForce: (e: number) => { asked.push(e); heap.set(forces[e]!, 0); return 1; },+ _physics3d_removeJoint: (e: number) => { removed.push(e); },+ });+ const joints: Joint3DMap = new Map([1, 2, 3, 4].map((e) => [e as Entity, {+ bodyA: 10 + e, bodyB: 20 + e, type: e === 3 ? HingeJoint3D._name : DistanceJoint3D._name, motorOn: false, motorSpeed: 0,+ }]));+ const broken: { entity: Entity; force: number; torque: number }[] = [];+ breakJoints3D(app, module, joints, broken);+ expect(removed).toEqual([1, 3]);+ expect(broken.map((b) => [b.entity, +b.force.toFixed(1), b.torque])).toEqual([[1, 19.6, 0], [3, 0, 8]]);+ expect((world.get(1 as Entity, DistanceJoint3D) as { enabled: boolean }).enabled).toBe(false);+ expect((world.get(2 as Entity, DistanceJoint3D) as { enabled: boolean }).enabled).toBe(true);+ expect([...joints.keys()]).toEqual([2, 4]);+ // One with no threshold is never even asked: a world full of joints pays nothing for the few that can break.+ expect(asked).not.toContain(4);+ });++ it('does nothing in a world that cannot say the force', () => {+ const { app } = jointWorld([[1 as Entity, DistanceJoint3D, { breakForce: 1 }]]);+ const { module } = heapModule({});+ const joints: Joint3DMap = new Map([[1 as Entity, { bodyA: 1, bodyB: 2, type: DistanceJoint3D._name, motorOn: false, motorSpeed: 0 }]]);+ breakJoints3D(app, module, joints);+ expect(joints.size).toBe(1);+ });+});++describe('a character that runs into something', () => {+ it('is read as a contact is: in world units, with the impulse it strikes with', () => {+ const { heap, module } = heapModule({+ _physics3d_contactEnters: () => 0, _physics3d_contactEntersBytes: () => 0,+ _physics3d_contactExits: () => 0, _physics3d_contactExitsBytes: () => 0,+ _physics3d_sensorEnters: () => 0, _physics3d_sensorEntersBytes: () => 0,+ _physics3d_sensorExits: () => 0, _physics3d_sensorExitsBytes: () => 0,+ _physics3d_characterHits: () => 400 * 4, _physics3d_characterHitsBytes: () => 40,+ });+ heap.set([5, 9, 1, 0.5, 0, -1, 0, 0, 3, 70], 400);+ const events = { contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [] } as Physics3DEventsData;+ drainPhysics3DEvents(module, events, 100);+ expect(events.characterHits).toEqual([{ character: 5, other: 9, pointX: 100, pointY: 50, pointZ: 0, normalX: -1, normalY: 0, normalZ: 0, speed: 300, mass: 70, impulse: 21000 }]);+ expect(events.jointBreaks).toEqual([]);+ });+});diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex d37000a6f..e016278ef 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -984,6 +984,63 @@ check('the world\'s gravity can be changed', near(fall, -1, 0.02), `vy=${fall.tocheck('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)}`);}+// ── A shot through cover, a rope that gives way, a character that runs into things ──+{+ const rows = (count, stride) => Array.from({ length: count }, (_, i) => Array.from(m.HEAPF32.subarray((m._physics3d_queryResult() >> 2) + i * stride, (m._physics3d_queryResult() >> 2) + (i + 1) * stride)));+ // Along y 100: a wall 0.2 m thick at x 10, a 1 m box at x 12, and a bone-sized sensor at x 15 that nothing collides with.+ m._physics3d_addBox(9800, 0.1, 1, 1, 10, 100, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ m._physics3d_addBox(9801, 0.5, 0.5, 0.5, 12, 100, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ m._physics3d_addBox(9802, 0.25, 0.25, 0.25, 15, 100, 0, ...IDENTITY, ...FREE(KINEMATIC), 0.5, 0, 1);+ m._physics3d_optimize();+ const crossed = rows(m._physics3d_raycastAll(0, 100, 0, 20, 0, 0, 0, 16), 9);+ const want = [[9800, 9.9 / 20, 10.1 / 20], [9801, 11.5 / 20, 12.5 / 20], [9802, 14.75 / 20, 15.25 / 20]];+ check('a line names every body it crosses, nearest first, with where it goes in and out',+ crossed.length === 3 && crossed.every((h, i) => h[0] === want[i][0] && near(h[1], want[i][1], 2e-4) && near(h[2], want[i][2], 2e-4)),+ JSON.stringify(crossed.map((h) => h.slice(0, 3).map((v) => +v.toFixed(4)))));+ check('so a shot knows the wall it went through was 0.2 m', crossed[0] && near((crossed[0][2] - crossed[0][1]) * 20, 0.2, 0.005), `${crossed[0] && ((crossed[0][2] - crossed[0][1]) * 20).toFixed(4)} m`);+ const ending = rows(m._physics3d_raycastAll(0, 100, 0, 12, 0, 0, 0, 16), 9);+ check('a line that ends inside a body comes out of it at its end', ending.length === 2 && near(ending[1][2], 1, 1e-4), JSON.stringify(ending.map((h) => h.slice(0, 3))));+ check('and the nearest is kept to as many as asked', m._physics3d_raycastAll(0, 100, 0, 20, 0, 0, 0, 1) === 1);+ const sensed = m._physics3d_raycast(14, 100, 0, 2, 0, 0, 0) ? m.HEAPF32[m._physics3d_queryResult() >> 2] : null;+ check('a ray meets a sensor, as a shot must meet a bone', sensed === 9802, `entity=${sensed}`);++ // A 2 kg ball hanging still on a rope: the rope holds it with its weight.+ const hook = m._physics3d_addBox(9810, 0.1, 0.1, 0.1, 9100, 50, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ const weight = m._physics3d_addSphere(9811, 0.2, 9100, 49, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);+ m._physics3d_setMass(weight, 2);+ m._physics3d_addDistanceJoint(9812, hook, weight, 9100, 50, 0, 9100, 49, 0, 0, 1, 0, 0, 0);+ step(240);+ const held = m._physics3d_jointForce(9812) ? rows(1, 2)[0] : null;+ check('a joint says the force it holds with', held && near(held[0], 2 * 9.81, 0.4) && near(held[1], 0, 0.05), `${held?.map((v) => v.toFixed(3))} want 19.62 N, 0`);+ check('and a joint that is not there says nothing', m._physics3d_jointForce(99999) === 0);++ // A character dropped onto a floor, then walked into a 30 kg crate.+ m._physics3d_addBox(9820, 5, 0.5, 5, 9200, -0.5, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);+ const crate = m._physics3d_addBox(9821, 0.4, 0.4, 0.4, 9202, 0.4, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);+ m._physics3d_setMass(crate, 30);+ m._physics3d_optimize();+ const runner = m._physics3d_addCharacter(9822, 0.3, 0.6, 9200, 3, 0, 0.87, 70, 0, 0);+ const met = [];+ const frame = (vx) => {+ m._physics3d_moveCharacter(runner, vx, 0, 0, 1 / 60, 0.3, 0.3);+ step(1);+ const base = m._physics3d_characterHits() >> 2;+ for (let i = 0; i < m._physics3d_characterHitsBytes() / 4; i += 10) met.push(Array.from(m.HEAPF32.subarray(base + i, base + i + 10)));+ };+ for (let i = 0; i < 90; i++) frame(0);+ const landed = met.filter((h) => h[0] === 9822 && h[1] === 9820);+ // From 3 m with its foot 0.9 below its middle: a 2.1 m fall, sqrt(2 g h) = 6.42 m/s, met with its own 70 kg.+ check('a character landing says so once, how fast and with its own mass', landed.length === 1 && near(landed[0][8], Math.sqrt(2 * 9.81 * 2.1), 0.35) && near(landed[0][9], 70, 1e-3),+ JSON.stringify(landed.map((h) => [h[8].toFixed(3), h[9]])));+ check('and its normal points up at it', landed[0] && near(landed[0][6], 1, 0.05));+ for (let i = 0; i < 60; i++) frame(3);+ const shoved = met.filter((h) => h[0] === 9822 && h[1] === 9821);+ // 70 kg against 30: 1 / (1/70 + 1/30) = 21 kg, at the 3 m/s it walked.+ check('a character walking into a crate meets it with both their masses', shoved.length >= 1 && near(shoved[0][9], 21, 0.01) && near(shoved[0][8], 3, 0.3),+ JSON.stringify(shoved.map((h) => [h[8].toFixed(3), h[9].toFixed(3)])));+ m._physics3d_removeCharacter(runner);+}+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 2eb98fd39..5f57d6b1b 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp@@ -36,6 +36,11 @@ int physics3d_isReady();void physics3d_step(float dt, int collisionSteps);void physics3d_optimize();void physics3d_setLayerMask(uint32_t layer, uint32_t mask);+/// Every body on a line, nearest first, at most maxHits of them: writes (entity, entry, exit, px,py,pz, nx,ny,nz) for+/// each into the query buffer, where entry and exit are fractions of the line at which it goes into the body and out of+/// it (1 where the line ends inside it), the point and normal where it goes in. Returns how many. What a shot that+/// passes through thin cover needs: the second body, and how much of the first it crossed to get there.+int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits);/// physics3d_raycast with flags: bit 0 also meets characters (a shot, which must hit an enemy that walks)./// Plain physics3d_raycast stays blind to them: line of sight and a camera's boom ask about the world.int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz,@@ -159,6 +164,9 @@ 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);+// What the joint held its two bodies together with over the last step: writes (force in newtons, torque in newton+// metres) into the query buffer, its limits' share included and its motor's not. 1 for a joint, 0 for none.+int physics3d_jointForce(uint32_t entity);// 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);@@ -205,6 +213,12 @@ size_t physics3d_contactEnterSpeedsBytes();// @heapreturn physics3d_contactEnterMassesBytes()uintptr_t physics3d_contactEnterMasses();size_t physics3d_contactEnterMassesBytes();+// What characters ran into this step, each meeting once until they part: (character entity, other entity, px,py,pz,+// nx,ny,nz with the normal toward the character, closing speed, meeting mass in kilograms) for each, the speed and mass+// as a contact between bodies gives them. Read after the step; the next step's first move starts it again.+// @heapreturn physics3d_characterHitsBytes()+uintptr_t physics3d_characterHits();+size_t physics3d_characterHitsBytes();// @heapreturn physics3d_contactExitsBytes()uintptr_t physics3d_contactExits();size_t physics3d_contactExitsBytes();diff --git a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cppindex a3a264ffa..6f665618e 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DConstraints.cpp@@ -488,6 +488,61 @@ void physics3d_setDistanceJoint(uint32_t entity, float minLength, float maxLengtwakeEnds(it->second.GetPtr());}+EMSCRIPTEN_KEEPALIVE+int physics3d_jointForce(uint32_t entity) {+ g().queryBuffer.clear();+ const auto it = g().constraints.find(entity);+ if (it == g().constraints.end()) return 0;+ Constraint* constraint = it->second.GetPtr();+ // Jolt keeps what each part of a constraint applied over the step as an impulse; over the step's length it is the+ // force the part held with.+ float linear = 0.0f, angular = 0.0f;+ switch (constraint->GetSubType()) {+ case EConstraintSubType::Point:+ linear = static_cast<PointConstraint*>(constraint)->GetTotalLambdaPosition().Length();+ break;+ case EConstraintSubType::Hinge: {+ auto* c = static_cast<HingeConstraint*>(constraint);+ const Vector<2> r = c->GetTotalLambdaRotation();+ linear = c->GetTotalLambdaPosition().Length();+ angular = std::sqrt(r[0] * r[0] + r[1] * r[1]) + std::abs(c->GetTotalLambdaRotationLimits());+ break;+ }+ case EConstraintSubType::Slider: {+ auto* c = static_cast<SliderConstraint*>(constraint);+ const Vector<2> p = c->GetTotalLambdaPosition();+ linear = std::sqrt(p[0] * p[0] + p[1] * p[1]) + std::abs(c->GetTotalLambdaPositionLimits());+ angular = c->GetTotalLambdaRotation().Length();+ break;+ }+ case EConstraintSubType::Distance:+ linear = std::abs(static_cast<DistanceConstraint*>(constraint)->GetTotalLambdaPosition());+ break;+ case EConstraintSubType::Fixed: {+ auto* c = static_cast<FixedConstraint*>(constraint);+ linear = c->GetTotalLambdaPosition().Length();+ angular = c->GetTotalLambdaRotation().Length();+ break;+ }+ case EConstraintSubType::SwingTwist: {+ auto* c = static_cast<SwingTwistConstraint*>(constraint);+ linear = c->GetTotalLambdaPosition().Length();+ angular = Vec3(c->GetTotalLambdaTwist(), c->GetTotalLambdaSwingY(), c->GetTotalLambdaSwingZ()).Length();+ break;+ }+ case EConstraintSubType::SixDOF: {+ auto* c = static_cast<SixDOFConstraint*>(constraint);+ linear = c->GetTotalLambdaPosition().Length();+ angular = c->GetTotalLambdaRotation().Length();+ break;+ }+ default: break;+ }+ const float step = g().solverStep > 0.0f ? g().solverStep : 1.0f / 60.0f;+ g().queryBuffer = {linear / step, angular / step};+ return 1;+}+/// 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/Physics3DContext.hpp b/src/esengine/bindings/modules/physics3d/Physics3DContext.hppindex dda71caf6..2d52f8e37 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp@@ -123,6 +123,9 @@ struct Context {std::vector<float> transformBuffer;/// The last query's hits, in the shape its getter documents.std::vector<float> queryBuffer;+ /** The length of the last solver step - a step's own, over its collision steps - which a constraint's impulse is+ * divided by to give the force it held with. */+ float solverStep = 1.0f / 60.0f;/// Refilled every step by the contact listener. Enter carries the geometry/// (entityA, entityB, nx,ny,nz, px,py,pz); exit only the pair, because at@@ -132,6 +135,9 @@ struct Context {std::vector<float> contactEnterSpeedBuffer;/** One meeting mass, in kilograms, for each contact in contactEnterBuffer. */std::vector<float> contactEnterMassBuffer;+ /** What characters ran into, ten floats a meeting; read after the step, emptied by the next step's first move. */+ std::vector<float> characterHitBuffer;+ bool characterHitsStale = false;std::vector<float> contactExitBuffer;std::vector<float> sensorEnterBuffer;std::vector<float> sensorExitBuffer;@@ -160,6 +166,8 @@ struct Context {std::unordered_map<uint32_t, std::unique_ptr<JPH::CharacterVirtual>> characters;/// A character is not a body, so its layer is not stored in one.std::unordered_map<uint32_t, uint32_t> characterLayers;+ /** The bodies each character touched after its last move, so a meeting is told once, not every move it lasts. */+ std::unordered_map<uint32_t, std::vector<uint32_t>> characterTouching;uint32_t nextCharacterId = 1;/// Characters are swept against the WORLD, and the world does not contain/// them: without this they walk through each other, which is the one pair ofdiff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex 19747c550..c3d84a352 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -36,7 +36,9 @@#include <Jolt/RegisterTypes.h>#include <cstddef>+#include <algorithm>#include <cmath>+#include <vector>using namespace JPH;using esengine::physics3d::Context;@@ -297,6 +299,9 @@ void physics3d_setSolver(int velocityIterations, int positionIterations, int allEMSCRIPTEN_KEEPALIVEvoid physics3d_step(float dt, int collisionSteps) {if (!g().isValid() || dt <= 0.0f) return;+ // No character moved this step: what the last one met has been read, and is not told again.+ if (g().characterHitsStale) g().characterHitBuffer.clear();+ g().solverStep = dt / static_cast<float>(std::max(collisionSteps, 1));// Cleared before the step, not after: the listener fires DURING Update, and a// buffer emptied afterwards would publish nothing.g().contactEnterBuffer.clear();@@ -328,6 +333,7 @@ void physics3d_step(float dt, int collisionSteps) {out.push_back(rotation.GetZ());out.push_back(rotation.GetW());}+ g().characterHitsStale = true;}/// Rebuild the broad-phase tree. Worth calling once after the static geometry of a@@ -695,6 +701,7 @@ void physics3d_removeCharacter(uint32_t characterId) {if (found != g().characters.end()) g().characterVsCharacter.Remove(found->second.get());g().characters.erase(characterId);g().characterLayers.erase(characterId);+ g().characterTouching.erase(characterId);g().entityOf.erase(characterId | CHARACTER_ID_TAG);}@@ -705,6 +712,40 @@ void physics3d_removeCharacter(uint32_t characterId) {* launches off the top of every slope it walks down.* Writes (px,py,pz, groundState, nx,ny,nz, vx,vy,vz) to the query buffer.*/+/// What a character ran into on this move that it was not already touching: told once, with how fast it closed and the+/// mass it met with, as a contact between bodies is.+static void noteCharacterMeetings(uint32_t characterId, const CharacterVirtual& character, Vec3Arg velocity) {+ if (g().characterHitsStale) { g().characterHitBuffer.clear(); g().characterHitsStale = false; }+ std::vector<uint32_t>& touching = g().characterTouching[characterId];+ std::vector<uint32_t> now;+ const auto self = g().entityOf.find(characterId | CHARACTER_ID_TAG);+ const float own = character.GetMass() > 0.0f ? 1.0f / character.GetMass() : 0.0f;+ for (const auto& contact : character.GetActiveContacts()) {+ if (!contact.mHadCollision || contact.mWasDiscarded || contact.mBodyB.IsInvalid()) continue;+ const uint32_t key = contact.mBodyB.GetIndexAndSequenceNumber();+ if (std::find(now.begin(), now.end(), key) != now.end()) continue;+ now.push_back(key);+ if (std::find(touching.begin(), touching.end(), key) != touching.end()) continue;+ float other = 0.0f;+ {+ const BodyLockRead lock(g().system->GetBodyLockInterface(), contact.mBodyB);+ if (lock.Succeeded() && lock.GetBody().IsDynamic()) other = lock.GetBody().GetMotionProperties()->GetInverseMass();+ }+ const float both = own + other;+ const auto owner = g().entityOf.find(key);+ // The normal points toward the character: closing on what it met is moving against it.+ const float closing = -(velocity - contact.mLinearVelocity).Dot(contact.mContactNormal);+ g().characterHitBuffer.insert(g().characterHitBuffer.end(), {+ self == g().entityOf.end() ? 0.0f : static_cast<float>(self->second),+ owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),+ static_cast<float>(contact.mPosition.GetX()), static_cast<float>(contact.mPosition.GetY()), static_cast<float>(contact.mPosition.GetZ()),+ contact.mContactNormal.GetX(), contact.mContactNormal.GetY(), contact.mContactNormal.GetZ(),+ std::max(closing, 0.0f), both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity(),+ });+ }+ touching.swap(now);+}+EMSCRIPTEN_KEEPALIVEvoid physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,float dt, float stepUp, float stepDown) {@@ -739,6 +780,8 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,g().system->GetDefaultLayerFilter(objectLayer),{}, {}, *g().temp);+ noteCharacterMeetings(characterId, character, Vec3(vx, vertical, vz));+const RVec3 position = character.GetPosition();const Vec3 normal = character.GetGroundNormal();// The velocity it REACHED, not the one it was given: a character shoving a@@ -976,6 +1019,48 @@ int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dzreturn 1;}+EMSCRIPTEN_KEEPALIVE+int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits) {+ g().queryBuffer.clear();+ if (!g().isValid() || maxHits == 0) return 0;+ const Vec3 direction(dx, dy, dz);+ if (!(direction.LengthSq() > 0.0f)) return 0;+ const MaskLayerFilter filter(layerMask);+ const RayCastSettings settings;+ // Where the line goes into each body, from its start; and where it comes out, by going in from its end.+ AllHitCollisionCollector<CastRayCollector> forward, backward;+ g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz), direction}, settings, forward, {}, filter);+ g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz) + direction, -direction}, settings, backward, {}, filter);+ struct Crossing { BodyID body; SubShapeID part; float entry; float exit; };+ std::vector<Crossing> crossings;+ for (const RayCastResult& hit : forward.mHits) {+ auto same = std::find_if(crossings.begin(), crossings.end(), [&](const Crossing& c) { return c.body == hit.mBodyID; });+ if (same == crossings.end()) crossings.push_back({hit.mBodyID, hit.mSubShapeID2, hit.mFraction, 1.0f});+ else if (hit.mFraction < same->entry) { same->entry = hit.mFraction; same->part = hit.mSubShapeID2; }+ }+ for (Crossing& c : crossings) {+ float exit = 1.0f;+ for (const RayCastResult& hit : backward.mHits) if (hit.mBodyID == c.body) exit = std::min(exit, 1.0f - hit.mFraction);+ // A body the line ends inside is met by the backward line at once: it comes out nowhere short of the end.+ c.exit = std::max(exit, c.entry);+ }+ std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) { return a.entry < b.entry; });+ if (crossings.size() > maxHits) crossings.resize(maxHits);+ for (const Crossing& c : crossings) {+ const RVec3 point = RVec3(ox, oy, oz) + Vec3(direction * c.entry);+ Vec3 normal = Vec3::sZero();+ const BodyLockRead lock(g().system->GetBodyLockInterface(), c.body);+ if (lock.Succeeded()) normal = lock.GetBody().GetWorldSpaceSurfaceNormal(c.part, point);+ auto owner = g().entityOf.find(c.body.GetIndexAndSequenceNumber());+ g().queryBuffer.insert(g().queryBuffer.end(), {+ owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second), c.entry, c.exit,+ static_cast<float>(point.GetX()), static_cast<float>(point.GetY()), static_cast<float>(point.GetZ()),+ normal.GetX(), normal.GetY(), normal.GetZ(),+ });+ }+ return static_cast<int>(crossings.size());+}+/*** @brief The world's nearest hit, or a character's when one is nearer and `flags` bit 0 asks for them.* @details A CharacterVirtual is not a body, so the narrow phase cannot meet it; each capsule is cast against in its@@ -1030,6 +1115,16 @@ size_t physics3d_transformsBytes() {return g().transformBuffer.size() * sizeof(float);}+EMSCRIPTEN_KEEPALIVE+uintptr_t physics3d_characterHits() {+ return reinterpret_cast<uintptr_t>(g().characterHitBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+size_t physics3d_characterHitsBytes() {+ return g().characterHitBuffer.size() * sizeof(float);+}+EMSCRIPTEN_KEEPALIVEuintptr_t physics3d_contactEnterMasses() {return reinterpret_cast<uintptr_t>(g().contactEnterMassBuffer.data());diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cppindex eeab46d7f..d2f7434c0 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXJoints.cpp@@ -420,6 +420,17 @@ void physics3d_setDistanceJoint(uint32_t entity, float minLength, float maxLengtwakeEnds(found->second.joint);}+EMSCRIPTEN_KEEPALIVE+int physics3d_jointForce(uint32_t entity) {+ g().queryBuffer.clear();+ auto found = g().joints.find(entity);+ if (found == g().joints.end()) return 0;+ PxVec3 linear(0.0f), angular(0.0f);+ found->second.joint->getConstraint()->getForce(linear, angular);+ g().queryBuffer = {linear.magnitude(), angular.magnitude()};+ return 1;+}+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 b11d7722c..0e4b8201c 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp@@ -416,6 +416,8 @@ void physics3d_setSolver(int velocityIterations, int positionIterations, int allEMSCRIPTEN_KEEPALIVEvoid physics3d_step(float dt, int collisionSteps) {if (!g().isValid() || dt <= 0.0f) return;+ // No character moved this step: what the last one met has been read, and is not told again.+ if (g().characterHitsStale) g().characterHitBuffer.clear();g().contactEnterBuffer.clear();g().contactEnterSpeedBuffer.clear();g().contactEnterMassBuffer.clear();@@ -446,6 +448,7 @@ void physics3d_step(float dt, int collisionSteps) {pose.q.x, pose.q.y, pose.q.z, pose.q.w,});}+ g().characterHitsStale = true;}EMSCRIPTEN_KEEPALIVE@@ -781,6 +784,10 @@ uintptr_t physics3d_transforms() { return reinterpret_cast<uintptr_t>(g().transfEMSCRIPTEN_KEEPALIVEsize_t physics3d_transformsBytes() { return g().transformBuffer.size() * sizeof(float); }EMSCRIPTEN_KEEPALIVE+uintptr_t physics3d_characterHits() { return reinterpret_cast<uintptr_t>(g().characterHitBuffer.data()); }+EMSCRIPTEN_KEEPALIVE+size_t physics3d_characterHitsBytes() { return g().characterHitBuffer.size() * sizeof(float); }+EMSCRIPTEN_KEEPALIVEuintptr_t physics3d_contactEnterMasses() { return reinterpret_cast<uintptr_t>(g().contactEnterMassBuffer.data()); }EMSCRIPTEN_KEEPALIVEsize_t physics3d_contactEnterMassesBytes() { return g().contactEnterMassBuffer.size() * sizeof(float); }diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cppindex 3b47738e2..cf56b0687 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXQueries.cpp@@ -17,6 +17,7 @@#include "../physics3d/Physics3DBindings.hpp"#include <algorithm>+#include <limits>#include <cmath>using namespace physx;@@ -97,7 +98,14 @@ public:float bestUp = -2.0f;PxVec3 bestNormal{0.0f};+ /** What this move ran into, the first touch of each: the actor, where, and its normal toward the character. */+ struct Met { const PxRigidActor* actor; PxVec3 at; PxVec3 normal; };+ std::vector<Met> met;+void onShapeHit(const PxControllerShapeHit& hit) override {+ if (hit.actor != nullptr && std::none_of(met.begin(), met.end(), [&](const Met& m) { return m.actor == hit.actor; })) {+ met.push_back({hit.actor, PxVec3(static_cast<float>(hit.worldPos.x), static_cast<float>(hit.worldPos.y), static_cast<float>(hit.worldPos.z)), hit.worldNormal});+ }const float up = hit.worldNormal.y;if (up > bestUp) { bestUp = up; bestNormal = hit.worldNormal; }if (moving == nullptr || !(moving->pushForce > 0.0f) || hit.actor == nullptr) return;@@ -125,6 +133,31 @@ public:HitReport& hitReport() { static HitReport r; return r; }+/// What a character ran into on this move that it was not already touching: told once, with how fast it closed and the+/// mass it met with, as a contact between bodies is - and as the Jolt world tells it.+void noteCharacterMeetings(Character& c, const std::vector<HitReport::Met>& met, const PxVec3& velocity) {+ if (g().characterHitsStale) { g().characterHitBuffer.clear(); g().characterHitsStale = false; }+ std::vector<const PxRigidActor*> now;+ const float own = c.mass > 0.0f ? 1.0f / c.mass : 0.0f;+ for (const HitReport::Met& m : met) {+ now.push_back(m.actor);+ if (std::find(c.touching.begin(), c.touching.end(), m.actor) != c.touching.end()) continue;+ float other = 0.0f;+ PxVec3 moving(0.0f);+ if (const PxRigidDynamic* d = m.actor->is<PxRigidDynamic>()) {+ if (!(d->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) { other = d->getInvMass(); moving = d->getLinearVelocity(); }+ }+ const float both = own + other;+ const float closing = -(velocity - moving).dot(m.normal);+ g().characterHitBuffer.insert(g().characterHitBuffer.end(), {+ static_cast<float>(c.entity), static_cast<float>(px3::entityOf(m.actor)),+ m.at.x, m.at.y, m.at.z, m.normal.x, m.normal.y, m.normal.z,+ std::max(closing, 0.0f), both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity(),+ });+ }+ c.touching.swap(now);+}+/// Only bodies that move, in the character's layers, and never itself.class MovableFilter final : public PxQueryFilterCallback {public:@@ -228,7 +261,6 @@ EMSCRIPTEN_KEEPALIVEuint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,float px, float py, float pz, float maxSlope, float mass,uint32_t layer, float pushForce) {- (void)mass;if (!g().isValid() || g().controllers == nullptr || !(radius > 0.0f)) return 0;PxCapsuleControllerDesc desc;desc.radius = radius;@@ -252,6 +284,7 @@ uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,character->entity = entity;character->layer = layer;character->pushForce = pushForce;+ character->mass = mass > 0.0f ? mass : 70.0f;character->body = std::make_unique<Body>();character->body->entity = entity;character->body->layer = layer;@@ -305,6 +338,7 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,report.dt = dt;report.bestUp = -2.0f;report.bestNormal = PxVec3(0.0f);+ report.met.clear();const PxVec3 startedAt = toVec(controller.getPosition());PxControllerCollisionFlags flags = controller.move(PxVec3(vx, vertical, vz) * dt, 1.0e-4f, dt, filters);@@ -321,6 +355,7 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,// A ceiling ends a jump, as it does for Unity's CharacterController.if ((flags & PxControllerCollisionFlag::eCOLLISION_UP) && vertical > 0.0f) vertical = 0.0f;report.moving = nullptr;+ noteCharacterMeetings(c, report.met, PxVec3(vx, vertical, vz));c.grounded = grounded;c.verticalSpeed = vertical;@@ -408,6 +443,50 @@ static int sweepQuery(const PxGeometry& shape, const PxTransform& pose, float dx}} // namespace+EMSCRIPTEN_KEEPALIVE+int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits) {+ g().queryBuffer.clear();+ if (!g().isValid() || maxHits == 0) return 0;+ PxVec3 dir(dx, dy, dz);+ const float length = dir.normalizeSafe();+ if (!(length > 0.0f)) return 0;+ const PxVec3 origin(ox, oy, oz);+ // Where the line goes into each actor, from its start; and where it comes out, by going in from its end.+ PxRaycastHit forwardHits[64], backwardHits[64];+ PxRaycastBuffer forward(forwardHits, 64), backward(backwardHits, 64);+ LayerFilter filter(layerMask, false, nullptr, true);+ const PxHitFlags wanted = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL;+ g().scene->raycast(origin, dir, length, forward, wanted, queryData(true), &filter);+ g().scene->raycast(origin + dir * length, -dir, length, backward, wanted, queryData(true), &filter);+ struct Crossing { const PxRigidActor* actor; float entry; float exit; PxVec3 normal; };+ std::vector<Crossing> crossings;+ for (PxU32 i = 0; i < forward.getNbTouches(); ++i) {+ const PxRaycastHit& hit = forward.getTouch(i);+ const float f = hit.distance / length;+ auto same = std::find_if(crossings.begin(), crossings.end(), [&](const Crossing& c) { return c.actor == hit.actor; });+ if (same == crossings.end()) crossings.push_back({hit.actor, f, 1.0f, hit.normal});+ else if (f < same->entry) { same->entry = f; same->normal = hit.normal; }+ }+ for (Crossing& c : crossings) {+ float exit = 1.0f;+ for (PxU32 i = 0; i < backward.getNbTouches(); ++i) {+ const PxRaycastHit& hit = backward.getTouch(i);+ if (hit.actor == c.actor) exit = std::min(exit, 1.0f - hit.distance / length);+ }+ c.exit = std::max(exit, c.entry);+ }+ std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) { return a.entry < b.entry; });+ if (crossings.size() > maxHits) crossings.resize(maxHits);+ for (const Crossing& c : crossings) {+ const PxVec3 point = origin + dir * (c.entry * length);+ g().queryBuffer.insert(g().queryBuffer.end(), {+ static_cast<float>(px3::entityOf(c.actor)), c.entry, c.exit, point.x, point.y, point.z,+ c.normal.x, c.normal.y, c.normal.z,+ });+ }+ return static_cast<int>(crossings.size());+}+EMSCRIPTEN_KEEPALIVEint 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) {diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp b/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hppindex 4a1a44002..4f59f8f98 100644--- a/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp@@ -74,6 +74,9 @@ struct Character {bool grounded = false;physx::PxVec3 groundNormal{0.0f, 1.0f, 0.0f};float pushForce = 0.0f;+ float mass = 70.0f;+ /** The actors it touched after its last move, so a meeting is told once, not every move it lasts. */+ std::vector<const physx::PxRigidActor*> touching;std::unique_ptr<Body> body; // the kinematic actor's record, so hits name the entity};@@ -112,6 +115,9 @@ struct World {std::vector<float> contactEnterSpeedBuffer;/** One meeting mass, in kilograms, for each contact in contactEnterBuffer. */std::vector<float> contactEnterMassBuffer;+ /** What characters ran into, ten floats a meeting; read after the step, emptied by the next step's first move. */+ std::vector<float> characterHitBuffer;+ bool characterHitsStale = false;std::vector<float> contactExitBuffer;std::vector<float> sensorEnterBuffer;std::vector<float> sensorExitBuffer;diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex ed8c0ca7c..e86078692 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4746,4 +4746,8 @@ export const NOTED = {{"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."},+ "feat(physics3d): what a shooter asks of the 3D world - raycastAll names every body on a line with how thick it was, joints give way past a breakForce or breakTorque, a character's meetings are told and strike what can break, and Hitboxes put a box on each bone that follows the animation, from Jolt and PhysX alike":+ {"note": "A shot through cover."},+ "feat(editor): the shooting-physics check aims at an animated character's bones, shoots through a wall and hangs two weights on ropes rated either side of their load":+ {"note": "Telling the parts of a character apart."},};