Skip to content

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

feat(physics3d): a thing breaks when it is hit hard enough - every 3D contact carries the speed at which the two came together, read before the solver from Jolt and PhysX alike, and a Breakable with a breakSpeed breaks on a hit at least that fast, from where it was hit

yhh8aceae038aa3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d8418bb92..03a53d1c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ published separately; it ships inside the editor.
### Added
- **Things that break.** A model can end with a `fracture` step, `{ op: "fracture", pieces: 12, at, focus }`, which cuts it beforehand into pieces that fit together with no gap, each a closed solid whose cut faces are tagged apart from its skin, smaller round `at` where it will be struck. It is still drawn whole; the editor also writes a mesh for each piece and a prefab of them, each with a dynamic body and a convex hull, and the reply hands over a `Breakable` to put beside the MeshRenderer. Raising `Breakable.broken` hides the whole (its renderer, body and colliders are switched off, not removed), puts the pieces where it stood and throws them out from `origin` at `burst` world units a second; `lifetime` takes them away later, and lowering the flag makes it whole again. Its pieces are loaded while it stands whole, so they appear on the frame it breaks. In the editor a clay pot written by `model_write` and placed on a floor broke into the 12 pieces asked for, then the 5 asked for after an edit, each of which moved, spread apart and came to rest on the floor, and was whole again when the flag was lowered. Nothing breaks it of itself yet: a script, a graph or a collision handler raises the flag. `Physics3D.setLinearVelocity(entity, velocity)` is what throws the pieces and is there for anything else that sends a body off. `Prefabs.prepare(path)` loads a prefab and everything its entities use and holds it, so a later `instantiate` does not wait on files.
+- **A thing breaks when it is hit hard enough.** `Breakable.breakSpeed` breaks it on a contact at least that fast, in world units a second at which the two came together, and the pieces leave from where it was hit. It needs a collider of its own, which the editor's reply to a fractured model now hands over as `hull` (a `ConvexCollider3D` of its shape); with a dynamic body as well it can be knocked over and break where it lands. The speed comes from the 3D world: every `Physics3DEvents.contactEnters` entry carries `speed`, how fast the first body was closing on the second along the normal, read before the solver answered, from both the Jolt and PhysX worlds. A sphere dropped 1.5 m onto a pad reported 5.56 m/s from Jolt and 5.40 from PhysX against the 5.42 the fall gives. In the editor a stone dropped six metres onto a pot broke it from its rim and took its collider away, and a pebble set down on another left it whole. Native builds carry the new speed buffer but were only compiled on Windows, not run.
## [0.104.1] - 2026-11-13
diff --git a/desktop b/desktop
index 36b1c213e..89dd6d603 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 36b1c213e5d8414a038912c3fb3da6702a24e30d
+Subproject commit 89dd6d6038025e4aef514053788e5cf20e15c989
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 6d95bc595..3429aa765 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -555,7 +555,7 @@ for (const { sensorEntity, visitorEntity } of events.sensorEnters) {
| Channel | What it carries |
|---|---|
-| `contactEnters` | Both entities, the contact normal and the point, in the same units as `Transform`. |
+| `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. |
| `contactExits` | Only the pair — see below. |
| `sensorEnters` / `sensorExits` | The **sensor first**, then the visitor. |
@@ -654,11 +654,22 @@ world.update(pot, Breakable, (b) => { b.origin = hitPointInItsOwnSpace; b.broken
| `burst` | number | `300` | How fast the pieces leave, in world units a second, out from `origin`. 0 lets them fall where they are. |
| `origin` | vec3 | `0,0,0` | Where it is struck, from its own origin. |
| `lifetime` | number | `0` | Seconds the pieces last before they are taken away. 0 keeps them. |
+| `breakSpeed` | number | `0` | A hit at least this fast breaks it, in world units a second. 0 breaks it only when `broken` is raised. |
The whole is hidden, not removed: its renderer, body and colliders are switched
off and come back when `broken` is lowered. Without a 3D world the pieces
appear in place and stay there.
+To have it break when something hits it, give it a `breakSpeed` and a collider
+of its own (the editor's reply to a fractured model hands over a
+`ConvexCollider3D` of its shape as `hull`). A contact at least that fast, by
+the speed at which the two came together, breaks it, and the pieces leave from
+where it was hit; the hardest hit wins when there are several in a step. With
+the collider alone it stands still; with a dynamic `RigidBody3D` as well it can
+be knocked over, and breaks where it lands if it lands hard enough. In a scene
+of 100 units to the metre, a fall of one metre arrives at about 440 and a thrown
+stone at 1000 or more.
+
`Physics3D.setLinearVelocity(entity, velocity)` is what throws them, and is
there for anything else that needs to send a body off: a blast, a kick. It
answers false for an entity that has no body yet, which is true for the frame an
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
index b1e61186f..d2f396723 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
@@ -488,7 +488,7 @@ for (const { sensorEntity, visitorEntity } of events.sensorEnters) {
| 通道 | 带着什么 |
|---|---|
-| `contactEnters` | 两个实体、接触法线和接触点,接触点与 `Transform` 同单位。 |
+| `contactEnters` | 两个实体、接触法线和接触点,接触点与 `Transform` 同单位;以及 `speed`:接触时第一个物体沿法线靠近第二个物体的速度,同单位每秒,在求解器处理之前读取。从一米高落下的球约以 4.4 m/s 着地。 |
| `contactExits` | 只有这一对——原因见下。 |
| `sensorEnters` / `sensorExits` | **传感器在前**,然后是访客。 |
@@ -563,10 +563,17 @@ world.update(pot, Breakable, (b) => { b.origin = hitPointInItsOwnSpace; b.broken
| `burst` | number | `300` | 碎块从 `origin` 向外飞出的速度,世界单位每秒。0 表示原地落下。 |
| `origin` | vec3 | `0,0,0` | 受击的位置,相对它自己的原点。 |
| `lifetime` | number | `0` | 碎块保留的秒数,之后被移除。0 表示一直保留。 |
+| `breakSpeed` | number | `0` | 撞击速度达到它就碎,世界单位每秒。0 表示只在 `broken` 置真时碎。 |
整体只是隐藏,不是删除:它的渲染器、刚体和碰撞体被关掉,`broken` 置假时恢复。
没有 3D 物理世界时,碎块会原地出现并留在那里。
+要让它被撞碎,给它设 `breakSpeed`,并给它一个自己的碰撞体(编辑器对碎裂模型的回复里会以
+`hull` 给出一个同形状的 `ConvexCollider3D`)。两者相撞的接近速度达到这个值就会碎,碎块从
+被击中的位置飞出;同一步里有多次撞击时取最重的一次。只有碰撞体时它是静止的;再加一个动态
+`RigidBody3D`,它就能被撞倒,落地够重时在落地处碎掉。在 100 单位一米的场景里,一米高落下约
+为 440,扔出的石头在 1000 以上。
+
把碎块抛出去用的是 `Physics3D.setLinearVelocity(entity, velocity)`,其他需要把刚体
送出去的场合(爆炸、踢击)也可以用它。实体还没有刚体时它返回 false,实体刚生成的
那一帧就是这样。
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 8d26620d7..4bfc04f28 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -647,6 +647,13 @@
"doc": "Seconds the pieces last before they are taken away. 0 keeps them.",
"range": "≥ 0, step 0.5"
},
+ {
+ "key": "breakSpeed",
+ "type": "number",
+ "default": "0",
+ "doc": "A hit at least this fast breaks it, in world units a second; it needs a collider to be hit. 0 breaks it only when Broken is raised.",
+ "range": "≥ 0, step 10"
+ },
{
"key": "enabled",
"type": "boolean",
@@ -658,7 +665,8 @@
"origin.x",
"origin.y",
"origin.z",
- "lifetime"
+ "lifetime",
+ "breakSpeed"
]
},
{
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c35242661..31058b842 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1940,6 +1940,7 @@ ComponentDef<BreakableData>
## BreakableData — interface @experimental
```
+breakSpeed: number
broken: boolean
burst: number
enabled: boolean
@@ -1951,6 +1952,7 @@ pieces: string
## BreakablePlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): BreakablePlugin
static prototype: BreakablePlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a440cc68a..c76f1bdc4 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1940,6 +1940,7 @@ ComponentDef<BreakableData>
## BreakableData — interface @experimental
```
+breakSpeed: number
broken: boolean
burst: number
enabled: boolean
@@ -1951,6 +1952,7 @@ pieces: string
## BreakablePlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): BreakablePlugin
static prototype: BreakablePlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 076719f56..21bf965b3 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1935,6 +1935,7 @@ ComponentDef<BreakableData>
## BreakableData — interface @experimental
```
+breakSpeed: number
broken: boolean
burst: number
enabled: boolean
@@ -1946,6 +1947,7 @@ pieces: string
## BreakablePlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): BreakablePlugin
static prototype: BreakablePlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3e4467afd..e77e4d91c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1935,6 +1935,7 @@ ComponentDef<BreakableData>
## BreakableData — interface @experimental
```
+breakSpeed: number
broken: boolean
burst: number
enabled: boolean
@@ -1946,6 +1947,7 @@ pieces: string
## BreakablePlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): BreakablePlugin
static prototype: BreakablePlugin
diff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.md
index 7aef37de0..305c9abfb 100644
--- a/sdk/etc/physics3d.api.md
+++ b/sdk/etc/physics3d.api.md
@@ -140,6 +140,7 @@ normalZ: number
pointX: number
pointY: number
pointZ: number
+speed: number | undefined
```
## ConvexCollider3D — const @experimental
@@ -359,6 +360,8 @@ _physics3d_addSliderJoint: (entity: number, bodyA: number, bodyB: number, px: nu
_physics3d_addSphere: (entity: number, radius: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number, cx: number, cy: number, cz: number) => number
_physics3d_addSwingTwistJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, nx: number, ny: number, nz: number, normalHalf: number, planeHalf: number, twistMin: number, twistMax: number, collideConnected: number) => number
_physics3d_addTorque: ((bodyId: number, tx: number, ty: number, tz: number) => void) | undefined
+_physics3d_contactEnterSpeeds: (() => number) | undefined
+_physics3d_contactEnterSpeedsBytes: (() => number) | undefined
_physics3d_contactEnters: () => number
_physics3d_contactEntersBytes: () => number
_physics3d_contactExits: () => number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e94253900..ec4772280 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1935,6 +1935,7 @@ ComponentDef<BreakableData>
## BreakableData — interface @experimental
```
+breakSpeed: number
broken: boolean
burst: number
enabled: boolean
@@ -1946,6 +1947,7 @@ pieces: string
## BreakablePlugin — class @experimental
```
build: (app: App) => void
+cleanup: (app?: App) => void
name: string
static new (): BreakablePlugin
static prototype: BreakablePlugin
diff --git a/sdk/src/breakable/breakable.ts b/sdk/src/breakable/breakable.ts
index 5eb207536..674590de2 100644
--- a/sdk/src/breakable/breakable.ts
+++ b/sdk/src/breakable/breakable.ts
@@ -35,6 +35,12 @@ export interface BreakableData {
origin: Vec3;
/** Seconds the pieces last before they are taken away. 0 keeps them. */
lifetime: number;
+ /**
+ * A hit at least this fast breaks it, in world units a second at which the two came together where they met:
+ * something thrown at it, or it falling on something. 0 breaks it only when `broken` is raised. It needs a
+ * collider of its own to be hit at all.
+ */
+ breakSpeed: number;
enabled: boolean;
}
@@ -44,6 +50,7 @@ export const Breakable = defineComponent<BreakableData>('Breakable', {
burst: 300,
origin: { x: 0, y: 0, z: 0 },
lifetime: 0,
+ breakSpeed: 0,
enabled: true,
}, {
assetFields: [{ field: 'pieces', type: 'prefab' }],
@@ -53,6 +60,7 @@ export const Breakable = defineComponent<BreakableData>('Breakable', {
burst: { min: 0, step: 10, tooltip: 'How fast the pieces leave, in world units a second, out from Origin. 0 lets them fall where they are.' },
origin: { tooltip: 'Where it is struck, from its own origin: the pieces fly away from here.' },
lifetime: { min: 0, step: 0.5, tooltip: 'Seconds the pieces last before they are taken away. 0 keeps them.' },
+ breakSpeed: { min: 0, step: 10, tooltip: 'A hit at least this fast breaks it, in world units a second; it needs a collider to be hit. 0 breaks it only when Broken is raised.' },
},
});
@@ -65,6 +73,17 @@ export function setBodyPusher(push: BodyPusher | null): void {
pusher = push;
}
+type ContactSink = (a: Entity, b: Entity, speed: number, point: Vec3) => void;
+const sinks = new Set<ContactSink>();
+
+/**
+ * Two bodies met, closing at `speed` world units a second at `point`: what a 3D world says after each of its steps,
+ * so that a thing struck hard enough breaks without the world knowing anything breaks.
+ */
+export function reportContact(a: Entity, b: Entity, speed: number, point: Vec3): void {
+ for (const sink of sinks) sink(a, b, speed, point);
+}
+
interface Broken {
/** Still waiting for its prefab: nothing is shown as broken until the pieces are there to show. */
loading: boolean;
@@ -87,6 +106,16 @@ export function burstVelocity(piece: Vec3, origin: Vec3, speed: number): Vec3 {
export class BreakablePlugin implements Plugin {
name = 'breakable';
+ /** Each app this was built into hears hits through its own sink, taken away when that app ends. */
+ private readonly sinks_ = new Map<App, ContactSink>();
+
+ cleanup(app?: App): void {
+ for (const [owner, sink] of [...this.sinks_]) {
+ if (app && owner !== app) continue;
+ sinks.delete(sink);
+ this.sinks_.delete(owner);
+ }
+ }
build(app: App): void {
const state = new Map<Entity, Broken>();
@@ -125,6 +154,17 @@ export class BreakablePlugin implements Plugin {
if (w.dropped) held.release(); else w.release = () => held.release();
}, () => { /* breaking says why it cannot, when it is asked to */ });
};
+ // Hits are noted as the world steps and acted on in the update after: the step is no place to spawn pieces.
+ const hits: { entity: Entity; speed: number; point: Vec3 }[] = [];
+ const sink: ContactSink = (a, b, speed, point) => {
+ for (const entity of [a, b]) {
+ if (!world.valid(entity) || !world.has(entity, Breakable)) continue;
+ const data = world.get(entity, Breakable) as BreakableData;
+ if (data.enabled && !data.broken && data.breakSpeed > 0 && speed >= data.breakSpeed) hits.push({ entity, speed, point });
+ }
+ };
+ sinks.add(sink);
+ this.sinks_.set(app, sink);
const offDespawn = world.onDespawn((entity: Entity) => {
cool(entity);
const b = state.get(entity);
@@ -176,6 +216,22 @@ export class BreakablePlugin implements Plugin {
return;
}
const prefabs = app.hasResource(Prefabs) ? app.getResource(Prefabs) : null;
+ // Struck hard enough: it breaks from where it was hit, the hardest hit if there were several.
+ if (hits.length) {
+ const hardest = new Map<Entity, { speed: number; point: Vec3 }>();
+ for (const h of hits) if ((hardest.get(h.entity)?.speed ?? -1) < h.speed) hardest.set(h.entity, h);
+ hits.length = 0;
+ for (const [entity, h] of hardest) {
+ if (!world.valid(entity) || !world.has(entity, Breakable)) continue;
+ const t = world.get(entity, Transform) as TransformData & { worldPosition?: Vec3; worldRotation?: { x: number; y: number; z: number; w: number }; worldScale?: Vec3 };
+ const [position, rotation, scale] = [t.worldPosition ?? t.position, t.worldRotation ?? t.rotation, t.worldScale ?? t.scale];
+ const local = q.rotate(q.conjugate(rotation), { x: h.point.x - position.x, y: h.point.y - position.y, z: h.point.z - position.z });
+ world.update(entity, Breakable, (d: BreakableData) => {
+ d.origin = { x: local.x / (scale.x || 1), y: local.y / (scale.y || 1), z: local.z / (scale.z || 1) };
+ d.broken = true;
+ });
+ }
+ }
const live = new Set<Entity>();
for (const entity of world.getEntitiesWithComponents([Breakable])) {
const data = world.get(entity, Breakable) as BreakableData;
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index be355ae19..b02c19d40 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -141,6 +141,9 @@ export interface Physics3DWasmModule {
_physics3d_contactEnters(): number;
_physics3d_contactEntersBytes(): number;
+ /** Optional for older binaries: one closing speed for each contact begun. */
+ _physics3d_contactEnterSpeeds?(): number;
+ _physics3d_contactEnterSpeedsBytes?(): number;
_physics3d_contactExits(): number;
_physics3d_contactExitsBytes(): number;
_physics3d_sensorEnters(): number;
@@ -212,6 +215,11 @@ export interface Contact3DEvent {
pointX: number;
pointY: number;
pointZ: number;
+ /**
+ * How fast A was closing on B where they met, along the normal, in world units a second, read before the solver
+ * answered: a ball dropped on a floor from a metre lands at about 4.4 m/s. Undefined from a binary too old to say.
+ */
+ speed?: number;
}
/** A sensor was entered or left. The SENSOR is always named first. */
@@ -266,6 +274,11 @@ export function drainPhysics3DEvents(module: Physics3DWasmModule,
normalX: f32[o + 2]!, normalY: f32[o + 3]!, normalZ: f32[o + 4]!,
pointX: f32[o + 5]! * pixelsPerUnit, pointY: f32[o + 6]! * pixelsPerUnit, pointZ: f32[o + 7]! * pixelsPerUnit,
}));
+ if (module._physics3d_contactEnterSpeeds && module._physics3d_contactEnterSpeedsBytes) {
+ const speeds = read(module._physics3d_contactEnterSpeeds(), module._physics3d_contactEnterSpeedsBytes(), 1, (o) => f32[o]!);
+ // One for each contact, in its order; a count that does not match is a binary that writes something else.
+ if (speeds.length === events.contactEnters.length) events.contactEnters.forEach((c, i) => { c.speed = speeds[i]! * pixelsPerUnit; });
+ }
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.ts
index 8dd9d87b6..66810870f 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -4,7 +4,7 @@
* @file Physics3DPlugin.ts
* @brief Loads the 3D physics module and drives one world from the ECS.
*/
-import { setBodyPusher } from '../breakable/breakable';
+import { reportContact, setBodyPusher } from '../breakable/breakable';
import { AnimatorController } from '../animation/Animator';
import { installPlanetGravity } from './planetGravity';
import { installRagdolls } from './ragdoll';
@@ -90,6 +90,8 @@ export class Physics3DPlugin implements Plugin {
stepPhysics3D(app, module, runtime.bodies, this.config_,
runtime.characters, events, runtime.joints, runtime.pieces,
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.speed !== undefined) reportContact(c.entityA, c.entityB, c.speed, { x: c.pointX, y: c.pointY, z: c.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/tests/breakable.test.ts b/sdk/tests/breakable.test.ts
index 537352680..6a355e2ef 100644
--- a/sdk/tests/breakable.test.ts
+++ b/sdk/tests/breakable.test.ts
@@ -27,7 +27,7 @@ vi.mock('../src/ecs/component', async (importOriginal) => {
const { App } = await import('../src/app/app');
const { Transform, getComponent } = await import('../src/ecs/component');
-const { Breakable, BreakablePlugin, burstVelocity, setBodyPusher } = await import('../src/breakable/breakable');
+const { Breakable, BreakablePlugin, burstVelocity, reportContact, setBodyPusher } = await import('../src/breakable/breakable');
const { Prefabs } = await import('../src/prefab/prefabServer');
const MeshRenderer = getComponent('MeshRenderer')!;
const Body = getComponent('RigidBody3D')!;
@@ -180,6 +180,49 @@ describe('a thing that breaks', () => {
expect(app.world.valid(made[1]!.root)).toBe(true);
});
+ it('breaks when struck at least as fast as its breakSpeed, from where it was struck', async () => {
+ const { app, whole, prefabs, tick } = setup();
+ app.world.update(whole, Breakable, (d) => { d.breakSpeed = 400; });
+ const other = app.world.spawn('Ball');
+ // Too soft: a ball rolled into it.
+ reportContact(other, whole, 120, { x: 110, y: 50, z: 0 });
+ await tick(2);
+ expect(prefabs.instantiate).not.toHaveBeenCalled();
+ // Hard: thrown at it, it named second or first.
+ reportContact(whole, other, 380, { x: 90, y: 50, z: 0 });
+ reportContact(other, whole, 650, { x: 100, y: 70, z: 10 });
+ await tick(2);
+ expect(prefabs.instantiate).toHaveBeenCalledTimes(1);
+ const data = app.world.get(whole, Breakable);
+ expect(data.broken).toBe(true);
+ // The hardest hit, in its own space: it stands at (100, 50, 0).
+ expect(data.origin).toEqual({ x: 0, y: 20, z: 10 });
+ // Broken things are not broken again by what lands on them.
+ reportContact(other, whole, 900, { x: 100, y: 50, z: 0 });
+ await tick(2);
+ expect(prefabs.instantiate).toHaveBeenCalledTimes(1);
+ });
+
+ it('is not broken by a hit when it has no breakSpeed, however hard', async () => {
+ const { app, whole, prefabs, tick } = setup();
+ reportContact(app.world.spawn('Boulder'), whole, 1e6, { x: 100, y: 50, z: 0 });
+ await tick(2);
+ expect(prefabs.instantiate).not.toHaveBeenCalled();
+ });
+
+ it('stops hearing hits when its app ends', async () => {
+ const { app, whole } = setup();
+ const ball = app.world.spawn('Ball');
+ const asked = vi.spyOn(app.world, 'has');
+ reportContact(ball, whole, 500, { x: 100, y: 50, z: 0 });
+ expect(asked).toHaveBeenCalled();
+ app.quit();
+ asked.mockClear();
+ // An app that has ended holds its world no longer through a hit it was told of.
+ reportContact(ball, whole, 500, { x: 100, y: 50, z: 0 });
+ expect(asked).not.toHaveBeenCalled();
+ });
+
it('takes its pieces with it when it is removed', async () => {
const { app, whole, made, breakIt, tick } = setup();
breakIt(true);
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index f2e4c0db3..96112ce4e 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -308,14 +308,23 @@ const dropId = m._physics3d_addSphere(DROP, 0.5, 20, 2, 0, ...IDENTITY,
...FREE(DYNAMIC), 0.5, 0, 0);
m._physics3d_optimize();
let landing = null;
+let landingSpeed = null;
for (let i = 0; i < 180 && !landing; i++) {
step(1);
- landing = contactEnters().find((e) => e[1] === DROP || e[0] === DROP) ?? null;
+ const enters = contactEnters();
+ const at = enters.findIndex((e) => e[1] === DROP || e[0] === DROP);
+ landing = at >= 0 ? enters[at] : null;
+ if (landing) landingSpeed = pairs('_physics3d_contactEnterSpeeds', '_physics3d_contactEnterSpeedsBytes', 1)[at]?.[0] ?? null;
}
check('a contact names both entities', landing != null
&& (landing[0] === PAD || landing[1] === PAD), JSON.stringify(landing));
check('and where they met', landing != null && near(landing[6], 0.0, 0.15),
`contact y=${landing?.[6]?.toFixed(4)} want the pad's top at 0`);
+// How hard: the sphere fell 1.5 m onto the pad, so it arrives at sqrt(2 g h) = 5.42 m/s, give or take the step it
+// was found in (g/60 = 0.16). Closing speed is A on B along A-to-B, so it is the same whichever side the sphere is.
+check('a contact says how fast the two came together', landingSpeed != null && near(Math.abs(landingSpeed), Math.sqrt(2 * 9.81 * 1.5), 0.35) && landingSpeed > 0,
+ `speed=${landingSpeed?.toFixed(3)} want +${Math.sqrt(2 * 9.81 * 1.5).toFixed(3)}`);
+check('one speed for each contact', m._physics3d_contactEnterSpeedsBytes() / 4 === m._physics3d_contactEntersBytes() / 32);
// A buffer holds ONE step's events, so they are collected as the steps run —
// reading after a run of steps catches only the last one's.
const collect = (read, steps) => {
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
index 289932d3c..9bae9ec0a 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
@@ -159,6 +159,11 @@ size_t physics3d_transformsBytes();
// @heapreturn physics3d_contactEntersBytes()
uintptr_t physics3d_contactEnters();
size_t physics3d_contactEntersBytes();
+// How fast the two came together at each contact begun this step, along its normal, in the world's own units a
+// second: one float for each entry of physics3d_contactEnters, in its order.
+// @heapreturn physics3d_contactEnterSpeedsBytes()
+uintptr_t physics3d_contactEnterSpeeds();
+size_t physics3d_contactEnterSpeedsBytes();
// @heapreturn physics3d_contactExitsBytes()
uintptr_t physics3d_contactExits();
size_t physics3d_contactExitsBytes();
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
index fdca62d14..db24c4490 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
@@ -128,6 +128,8 @@ struct Context {
/// (entityA, entityB, nx,ny,nz, px,py,pz); exit only the pair, because at
/// that moment Jolt has both bodies locked and one of them may already be gone.
std::vector<float> contactEnterBuffer;
+ /** One closing speed for each contact in contactEnterBuffer. */
+ std::vector<float> contactEnterSpeedBuffer;
std::vector<float> contactExitBuffer;
std::vector<float> sensorEnterBuffer;
std::vector<float> sensorExitBuffer;
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index 666518b8b..9c432a5ed 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -127,6 +127,10 @@ public:
static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
static_cast<float>(point.GetZ()),
});
+ // Read before the solver has answered the contact: what the two were doing as they met. The normal points from
+ // the first into the second, so the first closing on the second is a positive speed.
+ const Vec3 closing = body1.GetPointVelocity(point) - body2.GetPointVelocity(point);
+ g().contactEnterSpeedBuffer.push_back(closing.Dot(normal));
}
void OnContactRemoved(const SubShapeIDPair& pair) override {
@@ -241,6 +245,7 @@ void physics3d_shutdown() {
g().characters.clear();
g().sensorBodies.clear();
g().contactEnterBuffer.clear();
+ g().contactEnterSpeedBuffer.clear();
g().contactExitBuffer.clear();
g().sensorEnterBuffer.clear();
g().sensorExitBuffer.clear();
@@ -289,6 +294,7 @@ void physics3d_step(float dt, int collisionSteps) {
// Cleared before the step, not after: the listener fires DURING Update, and a
// buffer emptied afterwards would publish nothing.
g().contactEnterBuffer.clear();
+ g().contactEnterSpeedBuffer.clear();
g().contactExitBuffer.clear();
g().sensorEnterBuffer.clear();
g().sensorExitBuffer.clear();
@@ -902,6 +908,16 @@ size_t physics3d_transformsBytes() {
return g().transformBuffer.size() * sizeof(float);
}
+EMSCRIPTEN_KEEPALIVE
+uintptr_t physics3d_contactEnterSpeeds() {
+ return reinterpret_cast<uintptr_t>(g().contactEnterSpeedBuffer.data());
+}
+
+EMSCRIPTEN_KEEPALIVE
+size_t physics3d_contactEnterSpeedsBytes() {
+ return g().contactEnterSpeedBuffer.size() * sizeof(float);
+}
+
EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactEnters() {
return reinterpret_cast<uintptr_t>(g().contactEnterBuffer.data());
diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
index 179b513ab..41fce39ae 100644
--- a/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXModuleEntry.cpp
@@ -96,11 +96,25 @@ PxFilterFlags filterShader(PxFilterObjectAttributes a0, PxFilterData d0,
flags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT;
if (((d0.word1 | d1.word1) & px3::KIND_CHARACTER) == 0) {
flags |= PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_LOST
- | PxPairFlag::eNOTIFY_CONTACT_POINTS;
+ | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::ePRE_SOLVER_VELOCITY;
}
return PxFilterFlag::eDEFAULT;
}
+/** An actor's velocity at a world point before the solver, from the pair's own record of it; still things are 0. */
+PxVec3 pointVelocity(const PxContactPairHeader& header, int side, const PxContactPairVelocity& v, const PxVec3& at) {
+ const PxContactPairHeaderFlag::Enum removed = side == 0 ? PxContactPairHeaderFlag::eREMOVED_ACTOR_0 : PxContactPairHeaderFlag::eREMOVED_ACTOR_1;
+ PxVec3 velocity = v.linearVelocity[side];
+ const PxActor* actor = header.actors[side];
+ if (!(header.flags & removed) && actor) {
+ if (const PxRigidBody* body = actor->is<PxRigidBody>()) {
+ const PxVec3 centre = (body->getGlobalPose() * body->getCMassLocalPose()).p;
+ velocity += v.angularVelocity[side].cross(at - centre);
+ }
+ }
+ return velocity;
+}
+
/** Records what touched what, in the layouts the Jolt module writes. */
class ContactRecorder final : public PxSimulationEventCallback {
public:
@@ -111,6 +125,13 @@ public:
const uint32_t b = (header.flags & PxContactPairHeaderFlag::eREMOVED_ACTOR_1)
? 0u : px3::entityOf(header.actors[1]);
if (a == 0 && b == 0) return;
+ // This callback comes after the solver: the velocities the two had as they met are in the extra data, one set
+ // for each pair, asked for with ePRE_SOLVER_VELOCITY.
+ const PxContactPairVelocity* before[16] = {};
+ PxContactPairExtraDataIterator extra(header.extraDataStream, header.extraDataStreamSize);
+ while (extra.nextItemSet()) {
+ if (extra.preSolverVelocity && extra.contactPairIndex < 16) before[extra.contactPairIndex] = extra.preSolverVelocity;
+ }
for (PxU32 i = 0; i < count; ++i) {
const PxContactPair& pair = pairs[i];
if (pair.events & PxPairFlag::eNOTIFY_TOUCH_FOUND) {
@@ -126,6 +147,13 @@ public:
static_cast<float>(a), static_cast<float>(b),
normal.x, normal.y, normal.z, position.x, position.y, position.z,
});
+ // How fast A closed on B at the point, along the normal from A to B; 0 where PhysX gave no velocities.
+ float closing = 0.0f;
+ if (i < 16 && before[i]) {
+ const PxVec3 at[2] = { pointVelocity(header, 0, *before[i], position), pointVelocity(header, 1, *before[i], position) };
+ closing = (at[0] - at[1]).dot(normal);
+ }
+ g().contactEnterSpeedBuffer.push_back(closing);
}
if (pair.events & PxPairFlag::eNOTIFY_TOUCH_LOST) {
g().contactExitBuffer.push_back(static_cast<float>(a));
@@ -348,6 +376,7 @@ void physics3d_shutdown() {
g().transformBuffer.clear();
g().queryBuffer.clear();
g().contactEnterBuffer.clear();
+ g().contactEnterSpeedBuffer.clear();
g().contactExitBuffer.clear();
g().sensorEnterBuffer.clear();
g().sensorExitBuffer.clear();
@@ -374,6 +403,7 @@ EMSCRIPTEN_KEEPALIVE
void physics3d_step(float dt, int collisionSteps) {
if (!g().isValid() || dt <= 0.0f) return;
g().contactEnterBuffer.clear();
+ g().contactEnterSpeedBuffer.clear();
g().contactExitBuffer.clear();
g().sensorEnterBuffer.clear();
g().sensorExitBuffer.clear();
@@ -654,6 +684,10 @@ uintptr_t physics3d_transforms() { return reinterpret_cast<uintptr_t>(g().transf
EMSCRIPTEN_KEEPALIVE
size_t physics3d_transformsBytes() { return g().transformBuffer.size() * sizeof(float); }
EMSCRIPTEN_KEEPALIVE
+uintptr_t physics3d_contactEnterSpeeds() { return reinterpret_cast<uintptr_t>(g().contactEnterSpeedBuffer.data()); }
+EMSCRIPTEN_KEEPALIVE
+size_t physics3d_contactEnterSpeedsBytes() { return g().contactEnterSpeedBuffer.size() * sizeof(float); }
+EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactEnters() { return reinterpret_cast<uintptr_t>(g().contactEnterBuffer.data()); }
EMSCRIPTEN_KEEPALIVE
size_t physics3d_contactEntersBytes() { return g().contactEnterBuffer.size() * sizeof(float); }
diff --git a/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp b/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp
index 3993c50c0..7d5bd90db 100644
--- a/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp
+++ b/src/esengine/bindings/modules/physics3d_physx/PhysXWorld.hpp
@@ -108,6 +108,8 @@ struct World {
std::vector<float> transformBuffer;
std::vector<float> queryBuffer;
std::vector<float> contactEnterBuffer;
+ /** One closing speed for each contact in contactEnterBuffer. */
+ std::vector<float> contactEnterSpeedBuffer;
std::vector<float> contactExitBuffer;
std::vector<float> sensorEnterBuffer;
std::vector<float> sensorExitBuffer;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8505381c1..d8bf4db0c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4732,4 +4732,8 @@ export const NOTED = {
{"note": "Things that break."},
"feat(editor): a model with a fracture step writes its pieces and their prefab, and the reply hands over the Breakable that breaks it":
{"note": "Things that break."},
+ "feat(physics3d): a thing breaks when it is hit hard enough - every 3D contact carries the speed at which the two came together, read before the solver from Jolt and PhysX alike, and a Breakable with a breakSpeed breaks on a hit at least that fast, from where it was hit":
+ {"note": "A thing breaks when it is hit hard enough."},
+ "feat(editor): a fractured model's reply hands over a hull of its shape, and the breakable check drops a stone on one pot and a pebble on another":
+ {"note": "A thing breaks when it is hit hard enough."},
};