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): things that break - a model's fracture step cuts it beforehand into pieces that fit with no gap, the editor writes them as a prefab of bodies and hulls, and a Breakable swaps the whole for them when its flag is raised, throws them out from where it was struck and mends when the flag is lowered; its pieces are loaded while it stands, so they appear on the frame it breaks

yhhc8ce0c995494
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fff881c1..d8418bb92 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ published separately; it ships inside the editor.
## [Unreleased]
+### 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.
+
## [0.104.1] - 2026-11-13
### Added
diff --git a/desktop b/desktop
index e0d70fd8a..36b1c213e 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit e0d70fd8a7066bdffe3babf3d157d68ea271ffc9
+Subproject commit 36b1c213e5d8414a038912c3fb3da6702a24e30d
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index d592461c9..6d95bc595 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -633,3 +633,33 @@ Use finite positive placement scales. A rotated box or capsule under non-uniform
scale needs baked collision geometry; the component rejects that unsupported
case instead of creating a mismatched shape. Mesh and convex colliders also apply
the model's composed scale to their source vertices.
+
+## Things that break
+
+Nothing is cut when it breaks. A model is cut beforehand into pieces that fit
+together with no gap (a model's `fracture` step writes them as a prefab, each
+piece a mesh with a body and a convex hull), and a `Breakable` swaps the whole
+for the pieces when its flag is raised.
+
+```typescript
+world.insert(pot, Breakable, { pieces: 'assets/models/pot_pieces.esprefab', burst: 300 });
+// when it is hit:
+world.update(pot, Breakable, (b) => { b.origin = hitPointInItsOwnSpace; b.broken = true; });
+```
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `pieces` | prefab | `''` | The prefab of its pieces. |
+| `broken` | boolean | `false` | Raise to break it; lower to make it whole again. |
+| `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. |
+
+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.
+
+`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
+entity is spawned in.
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 83bb25593..b1e61186f 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
@@ -543,3 +543,30 @@ Inspector 以度显示角度,文件和脚本仍存弧度。平移限位、线
放置缩放必须为有限正数。非均匀缩放下带旋转的盒体或胶囊需要预先烘焙碰撞几何;
组件会明确拒绝该情况。网格和凸包碰撞体也会将模型的合成缩放应用到源顶点。
+
+## 会碎的东西
+
+东西碎的那一刻并没有发生切割。模型是事先切成互相贴合、没有缝隙的碎块的(模型的
+`fracture` 步骤会把它们写成一个预制体,每块是一个带刚体和凸包的网格),`Breakable`
+在标志置真时把整体换成这些碎块。
+
+```typescript
+world.insert(pot, Breakable, { pieces: 'assets/models/pot_pieces.esprefab', burst: 300 });
+// 被击中时:
+world.update(pot, Breakable, (b) => { b.origin = hitPointInItsOwnSpace; b.broken = true; });
+```
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `pieces` | prefab | `''` | 碎块的预制体。 |
+| `broken` | boolean | `false` | 置真即碎;置假恢复完整。 |
+| `burst` | number | `300` | 碎块从 `origin` 向外飞出的速度,世界单位每秒。0 表示原地落下。 |
+| `origin` | vec3 | `0,0,0` | 受击的位置,相对它自己的原点。 |
+| `lifetime` | number | `0` | 碎块保留的秒数,之后被移除。0 表示一直保留。 |
+
+整体只是隐藏,不是删除:它的渲染器、刚体和碰撞体被关掉,`broken` 置假时恢复。
+没有 3D 物理世界时,碎块会原地出现并留在那里。
+
+把碎块抛出去用的是 `Physics3D.setLinearVelocity(entity, velocity)`,其他需要把刚体
+送出去的场合(爆炸、踢击)也可以用它。实体还没有刚体时它返回 false,实体刚生成的
+那一帧就是这样。
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index f35e3cf78..65c106643 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -171,6 +171,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
CapsuleCollider3D: { category: 'physics', summary: 'An upright capsule — what a 3D character is. Total height is 2*(halfHeight + radius).', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: '形状' },
MeshCollider3D: { category: 'physics', summary: 'Collides against an imported mesh\u2019s own triangles — terrain, stairs, a room. Always static, and one-sided.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
ConvexCollider3D: { category: 'physics', summary: 'Collides against the convex hull of an imported mesh — the shape a solver can push, unlike a mesh collider.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
+ Breakable: { category: 'physics', summary: 'A thing that breaks: drawn whole until `broken` is raised, then its pieces, cut beforehand, are put where it stood and thrown out from where it was struck.', doc: 'gameplay/physics-3d', anchor: 'things-that-break', anchorZh: '会碎的东西' },
CharacterController3D: { category: 'physics', summary: 'A kinematic 3D mover: swept against the world, climbs steps, stays glued to slopes, and reports the ground it is on.', doc: 'gameplay/physics-3d', anchor: 'characters', anchorZh: '角色' },
ThirdPersonController: { category: 'physics', summary: 'Turns input into a movement request for a CharacterController3D, and reports what the character actually did to its Animator.', doc: 'gameplay/physics-3d', anchor: 'third-person', anchorZh: '第三人称' },
ThirdPersonCamera: { category: 'physics', summary: 'An eye that orbits a target under pointer control and pulls in when something solid stands between.', doc: 'gameplay/physics-3d', anchor: 'third-person', anchorZh: '第三人称' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 768d64831..8d26620d7 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -611,6 +611,56 @@
}
]
},
+ {
+ "name": "Breakable",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "pieces",
+ "type": "Asset<prefab>",
+ "default": "none",
+ "doc": "The prefab of its pieces: a model with a fracture step writes one beside its mesh."
+ },
+ {
+ "key": "broken",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Raise to break it, lower to make it whole again."
+ },
+ {
+ "key": "burst",
+ "type": "number",
+ "default": "300",
+ "doc": "How fast the pieces leave, in world units a second, out from Origin. 0 lets them fall where they are.",
+ "range": "≥ 0, step 10"
+ },
+ {
+ "key": "origin",
+ "type": "Vec3",
+ "default": "(0, 0, 0)",
+ "doc": "Where it is struck, from its own origin: the pieces fly away from here."
+ },
+ {
+ "key": "lifetime",
+ "type": "number",
+ "default": "0",
+ "doc": "Seconds the pieces last before they are taken away. 0 keeps them.",
+ "range": "≥ 0, step 0.5"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ],
+ "animatable": [
+ "burst",
+ "origin.x",
+ "origin.y",
+ "origin.z",
+ "lifetime"
+ ]
+ },
{
"name": "Camera",
"source": "cpp",
diff --git a/pipeline/src/modeling/booleans.ts b/pipeline/src/modeling/booleans.ts
index 54dc67aba..c2fe74ae7 100644
--- a/pipeline/src/modeling/booleans.ts
+++ b/pipeline/src/modeling/booleans.ts
@@ -11,13 +11,13 @@ import { MeshoptSimplifier } from 'meshoptimizer';
import { triangulateFace } from './triangulate';
import { collectEdges, compact, selectFaces, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
-interface ManifoldMeshData {
+export interface ManifoldMeshData {
numProp: number;
vertProperties: Float32Array;
triVerts: Uint32Array;
faceID?: Uint32Array;
}
-interface ManifoldSolid {
+export interface ManifoldSolid {
add(other: ManifoldSolid): ManifoldSolid;
subtract(other: ManifoldSolid): ManifoldSolid;
intersect(other: ManifoldSolid): ManifoldSolid;
@@ -25,7 +25,7 @@ interface ManifoldSolid {
isEmpty(): boolean;
delete(): void;
}
-interface ManifoldEngine {
+export interface ManifoldEngine {
setup(): void;
Mesh: new (data: ManifoldMeshData) => ManifoldMeshData;
Manifold: new (mesh: ManifoldMeshData) => ManifoldSolid;
@@ -34,7 +34,7 @@ interface ManifoldEngine {
let engine: ManifoldEngine | null = null;
/** Whether any step of a parsed source needs {@link prepareModeling} first. */
-export const needsPreparing = (steps: readonly { op: string; steps?: unknown }[]): boolean => steps.some((s) => s.op === 'boolean' || s.op === 'decimate'
+export const needsPreparing = (steps: readonly { op: string; steps?: unknown }[]): boolean => steps.some((s) => s.op === 'boolean' || s.op === 'decimate' || s.op === 'fracture'
// What a repeat holds runs too.
|| (Array.isArray(s.steps) && needsPreparing(s.steps as { op: string }[])));
@@ -53,8 +53,14 @@ export async function prepareModeling(wasmUrl?: string): Promise<void> {
engine = loaded;
}
+/** The engine a cut runs on, for the steps that cut. Throws where a caller built a source without preparing it. */
+export function loadedEngine(): ManifoldEngine {
+ if (!engine) throw new Error('booleans are not loaded: call prepareModeling() before building this source');
+ return engine;
+}
+
/** Why these faces are not a solid a boolean could cut, or null. */
-function notSolid(mesh: PolyMesh, faces: readonly number[]): string | null {
+export function notSolid(mesh: PolyMesh, faces: readonly number[]): string | null {
const only: PolyMesh = { positions: mesh.positions, faces: faces.map((f) => mesh.faces[f]!) };
let open = 0, crowded = 0;
for (const edge of collectEdges(only).values()) {
@@ -66,7 +72,7 @@ function notSolid(mesh: PolyMesh, faces: readonly number[]): string | null {
return null;
}
-function toSolid(e: ManifoldEngine, mesh: PolyMesh, faces: readonly number[], triangulate: (face: Face) => [number, number, number][]): ManifoldSolid {
+export function toSolid(e: ManifoldEngine, mesh: PolyMesh, faces: readonly number[], triangulate: (face: Face) => [number, number, number][]): ManifoldSolid {
const remap = new Map<number, number>();
const props: number[] = [];
const tris: number[] = [];
diff --git a/pipeline/src/modeling/fracture.ts b/pipeline/src/modeling/fracture.ts
new file mode 100644
index 000000000..19bd345f3
--- /dev/null
+++ b/pipeline/src/modeling/fracture.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fracture.ts — the `fracture` step: a solid cut into the pieces it breaks into.
+ *
+ * A thing that breaks in a game is not broken when it is hit. It was cut beforehand into pieces that fit
+ * together with no gap, drawn as one until the blow, and let go as many after it. This is the cutting.
+ *
+ * The pieces are the cells of points scattered through the solid: each piece is what lies nearer its own
+ * point than any other, so the cuts are flat, every piece is convex where the solid is, and the pieces fill
+ * the solid exactly. Points crowded toward a place make small pieces there and large ones far off, which is
+ * how a pane breaks round a stone. Each cut is made by Manifold, as a boolean is, so a piece is a closed
+ * solid with no slivers; its new faces, the inside of the thing, are tagged apart from its skin.
+ */
+import { PREFAB_FORMAT_VERSION } from 'esengine';
+import { loadedEngine, notSolid, toSolid, type ManifoldEngine, type ManifoldSolid } from './booleans';
+import { triangulateFace } from './triangulate';
+import { boundsOf, compact, cross, dot, normalize, selectFaces, sub, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
+
+export interface FractureParams {
+ /** The closed solid to break. Default every face. */
+ faces?: FaceSelector;
+ /** How many pieces to aim for, 2..64. A point that falls where its cell misses the solid makes none, so there may be fewer. */
+ pieces: number;
+ seed?: number;
+ /** Where it is struck: the pieces are smaller round here. */
+ at?: Vec3;
+ /** How much smaller, 0..1. Default 0.6 where `at` is given. */
+ focus?: number;
+ /** The tag of the faces a cut makes: the inside of the thing. Default "inside". */
+ tag?: string;
+ /** Their colour. Default the colour of the face nearest, a little darker. */
+ color?: readonly number[];
+}
+
+/**
+ * Faces a cut made carry this in place of the face they came from. Above any face index a model has, and below two
+ * to the thirty-first: Manifold keeps an id as a signed number, and one past that comes back as something else.
+ */
+const INSIDE = 1_000_000_000;
+
+function randomOf(seed: number): () => number {
+ let s = (seed * 2654435761 + 0x9e3779b9) >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let t = s;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Everything on the near side of the plane through @p point that faces along @p normal: a box with that plane as one side, larger than the solid. */
+function halfSpace(e: ManifoldEngine, point: Vec3, normal: Vec3, reach: number): ManifoldSolid {
+ const n = normalize(normal);
+ const u = normalize(cross(n, Math.abs(n[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0]));
+ const v = cross(n, u);
+ const props: number[] = [];
+ for (let i = 0; i < 8; i++) {
+ const [x, y, z] = [i & 1 ? 0 : -2 * reach, i & 2 ? 2 * reach : -2 * reach, i & 4 ? 2 * reach : -2 * reach];
+ props.push(point[0] + n[0] * x + u[0] * y + v[0] * z, point[1] + n[1] * x + u[1] * y + v[1] * z, point[2] + n[2] * x + u[2] * y + v[2] * z);
+ }
+ // Each side as two triangles, counter-clockwise from outside.
+ const quads = [[0, 4, 6, 2], [1, 3, 7, 5], [0, 1, 5, 4], [2, 6, 7, 3], [0, 2, 3, 1], [4, 5, 7, 6]];
+ const tris = quads.flatMap(([a, b, c, d]) => [a!, b!, c!, a!, c!, d!]);
+ return new e.Manifold(new e.Mesh({ numProp: 3, vertProperties: new Float32Array(props), triVerts: new Uint32Array(tris), faceID: new Uint32Array(12).fill(INSIDE) }));
+}
+
+/** The solid as its pieces, in its place: together they are the solid it was, and each face says which piece it is of. */
+export function fractureOp(mesh: PolyMesh, p: FractureParams): PolyMesh {
+ const e = loadedEngine();
+ if (!(Number.isInteger(p.pieces) && p.pieces >= 2 && p.pieces <= 64)) throw new Error('pieces must be a whole number, 2..64');
+ if (p.focus !== undefined && !(p.focus >= 0 && p.focus <= 1)) throw new Error('focus must be 0..1');
+ if (mesh.faces.some((f) => f.piece !== undefined)) throw new Error('this model is already in pieces: fracture once');
+ const all = p.faces === undefined ? mesh.faces.map((_, i) => i) : selectFaces(mesh, p.faces);
+ if (all.length === 0) throw new Error(`\`faces\` ${JSON.stringify(p.faces)} matched no face`);
+ const bad = notSolid(mesh, all);
+ if (bad) throw new Error(`what is to be broken is not a closed solid: ${bad}`);
+
+ const used = new Set<number>();
+ for (const f of all) for (const v of mesh.faces[f]!.v) used.add(v);
+ const { min, max } = boundsOf(mesh, used);
+ const size = sub(max, min);
+ const reach = Math.hypot(size[0], size[1], size[2]) * 2 + 1e-6;
+ const random = randomOf(p.seed ?? 1);
+ const focus = p.at ? p.focus ?? 0.6 : 0;
+ const triangulate = (face: Face): [number, number, number][] => triangulateFace(mesh, face);
+
+ // Its points are drawn on its skin, by area, and set a hair inside it. A point drawn anywhere in its bounds falls
+ // in air as often as not - inside a pot, round a ring - and the cell of a point in air may hold none of it, so a pot
+ // asked for eight came out in two. One on the skin always has some of the thing nearest to it.
+ const skin: { a: Vec3; b: Vec3; c: Vec3; inward: Vec3 }[] = [];
+ const areas: number[] = [];
+ let area = 0;
+ for (const f of all) {
+ for (const [i, j, k] of triangulate(mesh.faces[f]!)) {
+ const [a, b, c] = [mesh.positions[i]!, mesh.positions[j]!, mesh.positions[k]!];
+ const n = cross(sub(b, a), sub(c, a));
+ const twice = Math.hypot(n[0], n[1], n[2]);
+ if (twice < 1e-12) continue;
+ skin.push({ a, b, c, inward: [-n[0] / twice, -n[1] / twice, -n[2] / twice] });
+ area += twice / 2;
+ areas.push(area);
+ }
+ }
+ const hair = Math.hypot(size[0], size[1], size[2]) * 1e-3;
+ const onSkin = (): Vec3 => {
+ const want = random() * area;
+ let lo = 0, hi = areas.length - 1;
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (areas[mid]! < want) lo = mid + 1; else hi = mid; }
+ const t = skin[lo]!;
+ let [u, v] = [random(), random()];
+ if (u + v > 1) [u, v] = [1 - u, 1 - v];
+ return [0, 1, 2].map((i) => t.a[i]! + (t.b[i]! - t.a[i]!) * u + (t.c[i]! - t.a[i]!) * v + t.inward[i]! * hair) as unknown as Vec3;
+ };
+ // Toward where it is struck: of a few points drawn, the nearest the blow is kept, more of them the more focus.
+ const tries = p.at && focus > 0 ? 1 + Math.round(8 * focus) : 1;
+ const draw = (): Vec3 => {
+ let best = onSkin();
+ if (!p.at) return best;
+ const far = (q: Vec3): number => Math.hypot(q[0] - p.at![0], q[1] - p.at![1], q[2] - p.at![2]);
+ for (let i = 1; i < tries; i++) { const q = onSkin(); if (far(q) < far(best)) best = q; }
+ return best;
+ };
+ const seeds: Vec3[] = Array.from({ length: p.pieces }, draw);
+ const whole = toSolid(e, mesh, all, triangulate);
+ const allSet = new Set(all);
+ let positions: Vec3[] = [];
+ let made: Face[] = [];
+ let count = 0;
+ // A cell that is a sliver is a piece nobody sees and a body that jitters. Its point is taken out and the others
+ // worked out again, which gives its share to its neighbours and leaves the solid as exactly filled as before.
+ let live = seeds;
+ try {
+ for (let round = 0; round < 4; round++) {
+ const seeds = live;
+ positions = [...mesh.positions];
+ made = [];
+ count = 0;
+ const volumes: number[] = [];
+ const kept: number[] = [];
+ for (let k = 0; k < seeds.length; k++) {
+ // What of the solid is nearer this point than each of the others: one flat cut for every other point.
+ let cell: ManifoldSolid = whole;
+ for (let j = 0; j < seeds.length && !cell.isEmpty(); j++) {
+ if (j === k) continue;
+ const [a, b] = [seeds[k]!, seeds[j]!];
+ const between = sub(b, a);
+ if (dot(between, between) < 1e-18) continue;
+ const cutter = halfSpace(e, [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2], between, reach);
+ const next = cell.intersect(cutter);
+ cutter.delete();
+ if (cell !== whole) cell.delete();
+ cell = next;
+ }
+ if (!cell.isEmpty()) {
+ const out = cell.getMesh();
+ const base = positions.length;
+ for (let i = 0; i < out.vertProperties.length; i += out.numProp) positions.push([out.vertProperties[i]!, out.vertProperties[i + 1]!, out.vertProperties[i + 2]!]);
+ // The colour a cut face takes where none is given: the skin's, darker, as the inside of most things is.
+ const skin = mesh.faces[all[0]!]!.color;
+ const inner: readonly [number, number, number, number] = p.color
+ ? [p.color[0]!, p.color[1]!, p.color[2]!, p.color[3] ?? 1]
+ : skin ? [skin[0] * 0.6, skin[1] * 0.6, skin[2] * 0.6, skin[3]] : [0.6, 0.6, 0.6, 1];
+ for (let t = 0; t * 3 < out.triVerts.length; t++) {
+ const id = out.faceID![t]!;
+ const v = [out.triVerts[t * 3]! + base, out.triVerts[t * 3 + 1]! + base, out.triVerts[t * 3 + 2]! + base];
+ if (id >= INSIDE) made.push({ v, tag: p.tag ?? 'inside', color: inner, piece: count });
+ else {
+ const source = mesh.faces[id];
+ if (!source) throw new Error(`the cut lost track of a face (${id})`);
+ made.push({ ...source, v, piece: count });
+ }
+ }
+ let volume = 0;
+ for (let t = 0; t * 3 < out.triVerts.length; t++) {
+ const [a, b, c] = [positions[out.triVerts[t * 3]! + base]!, positions[out.triVerts[t * 3 + 1]! + base]!, positions[out.triVerts[t * 3 + 2]! + base]!];
+ volume += dot(a, cross(b, c)) / 6;
+ }
+ volumes.push(Math.abs(volume));
+ kept.push(k);
+ count++;
+ }
+ if (cell !== whole) cell.delete();
+ }
+ const total = volumes.reduce((a, b) => a + b, 0);
+ const slivers = new Set(kept.filter((_, i) => volumes[i]! < (total / Math.max(1, count)) * 0.04));
+ if (slivers.size === 0 || count - slivers.size < 2) break;
+ live = seeds.filter((_, k) => kept.includes(k) && !slivers.has(k));
+ // Drawn again in their place while there are rounds to spare, so the count asked for is the count made; the
+ // last round only takes them out.
+ if (round < 2) while (live.length < p.pieces) live.push(draw());
+ }
+ } finally {
+ whole.delete();
+ }
+ if (count < 2) throw new Error(`the solid came out as ${count} piece${count === 1 ? '' : 's'}: its points fell too close together; try another seed, or less focus`);
+ const kept = mesh.faces.filter((_, i) => !allSet.has(i));
+ const result = compact({ positions, faces: [...kept, ...made] });
+ // What is drawn until it breaks: the solid as it came in.
+ result.whole = { positions: mesh.positions, faces: mesh.faces };
+ // Said only where it is not what was asked: a note is read as something to look at.
+ if (count < p.pieces) result.notes = [`${count} pieces of the ${p.pieces} asked: the rest of the points fell where their share of the solid was nothing`];
+ return result;
+}
+
+/**
+ * The pieces of a fractured model as a prefab: one entity for each, where it lies in the model, drawing its own mesh
+ * and with a body and a hull of that mesh, so that put down in a scene they are the model again and let go they fall
+ * apart. A `Breakable` names it and spawns it where the whole stood.
+ */
+export function piecesPrefabOf(name: string, pieces: readonly { mesh: string; center: Vec3 }[], extra: { material?: string | null; texture?: string | null; normalMap?: string | null } = {}): Record<string, unknown> {
+ const idOf = (i: number): string => `p${i + 1}`;
+ return {
+ version: PREFAB_FORMAT_VERSION, name: `${name} Pieces`, rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: `${name} Pieces`, parent: null, children: pieces.map((_, i) => idOf(i)), visible: true, components: [{ type: 'Transform', data: {} }] },
+ ...pieces.map((piece, i) => ({
+ prefabEntityId: idOf(i), name: `Piece ${i + 1}`, parent: 'root', children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: piece.center[0], y: piece.center[1], z: piece.center[2] } } },
+ // Both sides drawn: the inside of a broken thing is seen.
+ { type: 'MeshRenderer', data: { mesh: piece.mesh, ...(extra.normalMap ? { normalMap: extra.normalMap } : {}), ...(extra.texture ? { texture: extra.texture } : {}), ...(extra.material ? { material: extra.material } : {}), lit: true, opaque: true, cullBackfaces: true, enabled: true } },
+ { type: 'RigidBody3D', data: { bodyType: 2, enabled: true } },
+ { type: 'ConvexCollider3D', data: { mesh: piece.mesh, friction: 0.6, restitution: 0.05, enabled: true } },
+ ],
+ })),
+ ],
+ };
+}
diff --git a/pipeline/src/modeling/index.ts b/pipeline/src/modeling/index.ts
index 19e0e137e..6aa92d6c4 100644
--- a/pipeline/src/modeling/index.ts
+++ b/pipeline/src/modeling/index.ts
@@ -10,6 +10,7 @@ export {
} from './modelSource';
export { organic, ORGANIC_DEFAULT_RESOLUTION, ORGANIC_MAX_RESOLUTION, type OrganicParams, type OrganicPart } from './organic';
export { needsPreparing, prepareModeling } from './booleans';
+export { piecesPrefabOf, type FractureParams } from './fracture';
export { bakeModel, HAIR_CUTOFF, modelMaterialDoc, type BakedModel, type ModelReport } from './modelBake';
export { bakeNormalMap, type NormalBakeReport, type NormalMap } from './normalBake';
export type { FaceSelector } from './polyMesh';
diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.ts
index 17af0078b..c397ce7e6 100644
--- a/pipeline/src/modeling/modelBake.ts
+++ b/pipeline/src/modeling/modelBake.ts
@@ -18,7 +18,7 @@ import type { NormalBakeReport } from './normalBake';
import { buildPolyMesh, expandModelSource, validateModelSource, type ModelSource, type StepReport } from './modelSource';
import {
boundsOf, collectEdges, cross, dot, faceArea, faceNormal, length, normalize, sub,
- type PolyMesh, type Vec3,
+ type PolyMesh, type Vec3, compact,
} from './polyMesh';
const DEFAULT_SMOOTH_ANGLE = 30;
@@ -51,6 +51,8 @@ export interface ModelReport {
joints?: Record<string, number>;
/** What a normal map carries, once one has been baked. */
normalBake?: NormalBakeReport;
+ /** For a fractured model: how many pieces it is in. */
+ pieces?: number;
/** The findings above that are worth stopping for, as sentences. */
warnings: string[];
}
@@ -65,6 +67,13 @@ export interface BakedModel {
hair?: { maps: HairMaps; chainRoots?: number[] };
/** Present where a source has shapes: three offsets per surface vertex, for each. */
shapes?: { names: string[]; deltas: Float32Array[] };
+ /**
+ * Present on a fractured model: each piece as a mesh of its own, about its own middle, with where that middle is
+ * in the model. Put back at their centres they are the model; let go, they are what it breaks into.
+ */
+ shards?: { center: Vec3; size: Vec3; volume: number; data: MeshData }[];
+ /** Present on a fractured model: the pieces in their places as one mesh, each face saying which piece it is of. `poly` is the model before the cut, which is what is drawn; this is what it is cut into, to be looked at. */
+ cut?: { poly: PolyMesh; triangles: { v: [number, number, number]; face: number }[] };
/** One triangle per entry: its three positions' indices, and the face it came from. */
triangles: { v: [number, number, number]; face: number }[];
/** Present where a source has a normalBake: what bakeNormalMap carries, onto a mesh already unwrapped and given tangents for it. */
@@ -332,7 +341,13 @@ export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, ma
export function bakeModel(raw: unknown): BakedModel {
// The plain steps: the report counts them, and a step's own fields are read back by its index among them.
const source = expandModelSource(validateModelSource(raw));
- const { mesh, steps, high, notes } = buildPolyMesh(source);
+ const built = buildPolyMesh(source);
+ const { steps, high, notes } = built;
+ // A fractured model is two things: its pieces, which the report and the views are of, and the model before the cut,
+ // which is what is drawn until it breaks.
+ const pieces = built.mesh.faces.some((f) => f.piece !== undefined) ? built.mesh : null;
+ if (pieces && !pieces.whole) throw new Error('fracture has to be the last step: what comes after it would change the pieces and not the model they are cut from');
+ const mesh = pieces?.whole ?? built.mesh;
if (mesh.faces.length === 0) throw new Error('the steps leave no faces; a model starts with a box, cylinder, cone, sphere, plane or prism');
const triangles = mesh.faces.map((f) => triangulateFace(mesh, f));
@@ -434,11 +449,30 @@ export function bakeModel(raw: unknown): BakedModel {
}
const roundVec = (v: readonly number[]): Vec3 => v.map((x) => Math.round(x * 1e5) / 1e5) as unknown as Vec3;
+
+ // The pieces of a fractured model, each a mesh about its own middle.
+ const cut = pieces ?? mesh;
+ const pieceIds = [...new Set(cut.faces.map((f) => f.piece).filter((k): k is number => k !== undefined))].sort((a, b) => a - b);
+ if (pieceIds.length && (rig || shapes)) throw new Error('a model that is rigged or has shapes moves as one skin and cannot also be in pieces: fracture a model of its own');
+ if (pieceIds.length && cut.faces.some((f) => f.piece === undefined)) warnings.push('some faces are of no piece: they are drawn with the whole and go with none of the pieces when it breaks. Fracture every face, or keep what does not break in a model of its own');
+ const shards = pieceIds.map((k) => {
+ const part = compact({ positions: cut.positions, faces: cut.faces.filter((f) => f.piece === k) });
+ const box = boundsOf(part);
+ const center: Vec3 = [(box.min[0] + box.max[0]) / 2, (box.min[1] + box.max[1]) / 2, (box.min[2] + box.max[2]) / 2];
+ const about: PolyMesh = { positions: part.positions.map((q: Vec3) => sub(q, center)), faces: part.faces };
+ const tris = about.faces.map((f) => triangulateFace(about, f));
+ return {
+ center: roundVec(center), size: roundVec(sub(box.max, box.min)),
+ volume: Math.round(Math.abs(signedVolume(about, about.faces.map((_, i) => i), tris)) * 1e6) / 1e6,
+ data: toMeshData(about, tris, source),
+ };
+ });
return {
poly: mesh,
data: unwrapped,
...(rig ? { rig } : {}),
...(shapes ? { shapes } : {}),
+ ...(shards.length ? { shards, cut: { poly: cut, triangles: cut.faces.flatMap((f, face) => triangulateFace(cut, f).map((v) => ({ v, face }))) } } : {}),
...(cards ? { hair: { maps: hairMaps((source.steps.find((s) => s.op === 'hair')?.seed as number | undefined) ?? 1), ...(swing ? { chainRoots: swing.chainRoots } : {}) } } : {}),
...(bake && high ? { detail: { high, size, ...(bake.distance !== undefined ? { distance: bake.distance } : {}), smoothAngle: source.smoothAngle ?? DEFAULT_SMOOTH_ANGLE, ...(lowColors ? { lowColors } : {}), ...(bake.occlusion ? { occlusion: typeof bake.occlusion === 'object' ? bake.occlusion : {} } : {}), ...(bake.surface ? { surface: { roughness: source.material?.roughness ?? 1, metallic: source.material?.metallic ?? 0 } } : {}) } } : {}),
triangles: triangles.flatMap((tris, face) => tris.map((v) => ({ v, face }))),
@@ -452,7 +486,7 @@ export function bakeModel(raw: unknown): BakedModel {
size: roundVec(sub(max, min)),
center: roundVec([(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]),
},
- tags, openEdges, nonManifoldEdges, flippedEdges, degenerateFaces, insideOutShells, steps, ...(jointReport ? { joints: jointReport } : {}), warnings,
+ tags, openEdges, nonManifoldEdges, flippedEdges, degenerateFaces, insideOutShells, steps, ...(jointReport ? { joints: jointReport } : {}), ...(shards.length ? { pieces: shards.length } : {}), warnings,
},
};
}
diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.ts
index 343b02685..b52eff6c5 100644
--- a/pipeline/src/modeling/modelSource.ts
+++ b/pipeline/src/modeling/modelSource.ts
@@ -15,6 +15,7 @@
import * as ops from './modelOps';
import { organic } from './organic';
import { booleanOp } from './booleans';
+import { fractureOp } from './fracture';
import { uvStep } from './modelUv';
import { lathe, loft } from './surfaces';
import { subdivide } from './subdivide';
@@ -163,6 +164,7 @@ export const MODEL_OPS: Record<string, OpSpec> = {
bevel: { params: { edges: 'edges', width: 'number', round: 'integer', tag: 'string' }, required: ['edges', 'width'], run: ops.bevel as OpSpec['run'], says: 'chamfers edges, mitring where they meet; `round` 1..3 rounds them off' },
slice: { params: { faces: 'faces', axis: 'axis', at: 'number|numbers' }, required: ['axis', 'at'], run: ops.slice as OpSpec['run'], says: 'cuts faces across planes, making the seams a window sits between' },
boolean: { params: { operation: 'operation', with: 'faces', from: 'faces', keep: 'boolean', tag: 'string', color: 'color' }, required: ['operation', 'with'], run: booleanOp as unknown as OpSpec['run'], says: 'cuts or joins closed solids: subtract `with` from `from` makes a real hole' },
+ fracture: { params: { faces: 'faces', pieces: 'integer', seed: 'integer', at: 'vec3', focus: 'number', tag: 'string', color: 'color' }, required: ['pieces'], run: fractureOp as unknown as OpSpec['run'], says: 'cuts a closed solid into `pieces` (2..64) that fit together with no gap, smaller round `at` by `focus`; the cut faces are tagged `tag` (default "inside"). It is still drawn whole; each piece is also written as a mesh of its own, for a game to let go when the thing breaks' },
subdivide: { params: { faces: 'faces', levels: 'integer', crease: 'number' }, required: [], run: subdivide as unknown as OpSpec['run'], says: 'rounds whole shells into smooth surfaces, keeping edges sharper than `crease` degrees' },
displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', count: 'integer', axis: 'axis', mirror: 'axis', detail: 'number', along: 'vec3', long: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: ((mesh: PolyMesh, params: never) => displace(mesh, params)) as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave, scratches, pleats or folds' },
hair: { params: { faces: 'faces', count: 'integer', length: 'number', guides: 'guides', gather: 'number', width: 'number', segments: 'integer', droop: 'number', comb: 'vec3', spread: 'number', uneven: 'number', wave: 'number', taper: 'number', seed: 'integer', color: 'color', tipColor: 'color', tag: 'string' }, required: ['faces'], run: hair as unknown as OpSpec['run'], says: 'grows cards of hair from these faces, falling around what is there, or along `guides` for a ponytail or a fringe; run it again for another layer, and only the cards are kept' },
@@ -610,13 +612,17 @@ export function buildPolyMesh(written: ModelSource): ModelBuild {
}
if (mesh.notes) {
for (const note of mesh.notes) notes.push(`${stepLabel(step, index)}: ${note}`);
- mesh = { positions: mesh.positions, faces: mesh.faces };
+ // What a fracture leaves beside its pieces stays with them: it is not a note.
+ mesh = { positions: mesh.positions, faces: mesh.faces, ...(mesh.whole ? { whole: mesh.whole } : {}) };
}
steps.push({ index, ...(id ? { id } : {}), op, faces: mesh.faces.length, ...(op === 'decimate' ? { trianglesBefore: before, trianglesAfter: triangleCount(mesh) } : {}) });
if (index === highAfter) high = compact(mesh);
if (id && wanted.has(id)) kept.set(id, mesh);
});
- return { mesh: hasCards(mesh) ? cardsOnly(mesh) : compact(mesh), steps, notes, ...(high ? { high } : {}) };
+ const done = hasCards(mesh) ? cardsOnly(mesh) : compact(mesh);
+ // Only the last step's: a step after a fracture makes a mesh that has none, and the bake refuses it.
+ if (mesh.whole) done.whole = compact(mesh.whole);
+ return { mesh: done, steps, notes, ...(high ? { high } : {}) };
}
// ---- Edits: changing a source without restating it ------------------------------
diff --git a/pipeline/src/modeling/polyMesh.ts b/pipeline/src/modeling/polyMesh.ts
index 360dd56e5..bdb9d973f 100644
--- a/pipeline/src/modeling/polyMesh.ts
+++ b/pipeline/src/modeling/polyMesh.ts
@@ -24,6 +24,8 @@ export interface Face {
metallic?: number;
/** The hair card this is part of, with `cornerUvs` where its texture lands. */
card?: number;
+ /** Which of the pieces of a fractured solid this is a face of. */
+ piece?: number;
/** A texture's place at each corner, in the order of `v`, in place of any projection. */
cornerUvs?: readonly (readonly [number, number])[];
/** Part of a continuous skin: shaded smooth with its neighbours whatever the angle, and its edges are not features. */
@@ -52,6 +54,11 @@ export interface PolyMesh {
faces: Face[];
/** What the step that just ran wants said in the report. Taken off before the next one runs. */
notes?: string[];
+ /**
+ * Left by `fracture`: the model as it was before it was cut. It is what is drawn until the thing breaks, since
+ * pieces drawn side by side shade apart along every crack. Any step after the cut makes a new mesh without it.
+ */
+ whole?: PolyMesh;
}
export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
diff --git a/pipeline/tests/modeling-fracture.test.ts b/pipeline/tests/modeling-fracture.test.ts
new file mode 100644
index 000000000..09c93eea0
--- /dev/null
+++ b/pipeline/tests/modeling-fracture.test.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * A solid cut into the pieces it breaks into, held to what can be counted: the pieces fill the solid exactly, each is
+ * closed, they are the same pieces from the same seed, and they are smaller where the blow lands.
+ */
+import { beforeAll, describe, expect, it } from 'vitest';
+import { bakeModel, needsPreparing, prepareModeling, validateModelSource, type BakedModel, type ModelStep } from '../src/modeling';
+import { collectEdges } from '../src/modeling/polyMesh';
+
+beforeAll(() => prepareModeling());
+
+const model = (...steps: ModelStep[]): BakedModel => bakeModel({ version: 1, steps });
+const block: ModelStep = { op: 'box', size: [2, 2, 2], tag: 'stone', color: [0.8, 0.7, 0.6] };
+const sum = (values: number[]): number => values.reduce((a, b) => a + b, 0);
+
+describe('fracture', () => {
+ it('cuts a solid into pieces that fill it exactly, each one closed', () => {
+ const m = model(block, { op: 'fracture', pieces: 12, seed: 3 });
+ const shards = m.shards!;
+ expect(shards.length).toBeGreaterThanOrEqual(8);
+ expect(shards.length).toBeLessThanOrEqual(12);
+ expect(m.report.pieces).toBe(shards.length);
+ // Together they are the eight cubic units the block was, and no piece is nothing.
+ expect(sum(shards.map((s) => s.volume))).toBeCloseTo(8, 3);
+ for (const s of shards) expect(s.volume).toBeGreaterThan(1e-4);
+ // What is drawn until it breaks is the block as it was: one shell, twelve triangles, the size it was.
+ expect(m.report.shells).toBe(1);
+ expect(m.report.triangles).toBe(12);
+ expect(m.report.openEdges).toBe(0);
+ expect(m.report.insideOutShells).toBe(0);
+ expect(m.report.bounds.size).toEqual([2, 2, 2]);
+ for (let k = 0; k < shards.length; k++) {
+ const faces = m.cut!.poly.faces.filter((f) => f.piece === k);
+ const edges = [...collectEdges({ positions: m.cut!.poly.positions, faces }).values()];
+ expect(edges.every((e) => e.faces.length === 2), `piece ${k} is closed`).toBe(true);
+ }
+ // All twelve came out, so there is nothing to say; fewer would be said.
+ expect(m.report.warnings.filter((w) => !/pieces of the 12 asked/.test(w))).toEqual([]);
+ });
+
+ it('keeps the skin as it was and tags what a cut laid bare', () => {
+ const m = model(block, { op: 'fracture', pieces: 8, seed: 2 });
+ const [skin, inside] = [m.cut!.poly.faces.filter((f) => f.tag === 'stone'), m.cut!.poly.faces.filter((f) => f.tag === 'inside')];
+ expect(skin.length + inside.length).toBe(m.cut!.poly.faces.length);
+ expect(inside.length).toBeGreaterThan(0);
+ // The skin keeps its colour; the inside is the same stone, darker.
+ expect(skin.every((f) => f.color![0] === 0.8)).toBe(true);
+ expect(inside.every((f) => Math.abs(f.color![0] - 0.48) < 1e-9)).toBe(true);
+ // Every face of the skin lies on the block's own surface; no face of the inside lies wholly on it.
+ const onSurface = (f: { v: number[] }): boolean => [0, 1, 2].some((axis) => [-1, 1].some((side) => f.v.every((v) => Math.abs(m.cut!.poly.positions[v]![axis]! - side) < 1e-5)));
+ expect(skin.every(onSurface)).toBe(true);
+ expect(inside.some(onSurface)).toBe(false);
+ // Named and coloured where the source says.
+ const named = model(block, { op: 'fracture', pieces: 4, seed: 2, tag: 'core', color: [1, 0, 0] });
+ expect(named.cut!.poly.faces.filter((f) => f.tag === 'core').length).toBeGreaterThan(0);
+ expect(named.cut!.poly.faces.find((f) => f.tag === 'core')!.color).toEqual([1, 0, 0, 1]);
+ });
+
+ it('writes each piece about its own middle, and says where that middle is', () => {
+ const m = model(block, { op: 'fracture', pieces: 6, seed: 5 });
+ for (const s of m.shards!) {
+ // Inside the block, and no larger than it.
+ for (const axis of [0, 1, 2]) {
+ expect(Math.abs(s.center[axis]!)).toBeLessThanOrEqual(1);
+ expect(s.size[axis]!).toBeLessThanOrEqual(2 + 1e-6);
+ }
+ expect(s.data.vertexCount).toBeGreaterThan(3);
+ expect(s.data.indices.length % 3).toBe(0);
+ expect(s.data.indices.length).toBeGreaterThan(0);
+ }
+ // The middles are not all one place.
+ expect(new Set(m.shards!.map((s) => s.center.join())).size).toBe(m.shards!.length);
+ });
+
+ it('is the same pieces from the same seed, and other pieces from another', () => {
+ const centres = (seed: number): string => model(block, { op: 'fracture', pieces: 8, seed }).shards!.map((s) => s.center.join()).join('|');
+ expect(centres(4)).toBe(centres(4));
+ expect(centres(4)).not.toBe(centres(5));
+ });
+
+ it('breaks small where it is struck and large far from it', () => {
+ const struck = model(block, { op: 'fracture', pieces: 24, seed: 7, at: [1, 1, 1], focus: 1 }).shards!;
+ const far = (s: { center: readonly number[] }): number => Math.hypot(s.center[0]! - 1, s.center[1]! - 1, s.center[2]! - 1);
+ const near = struck.filter((s) => far(s) < 1.2).map((s) => s.volume);
+ const rest = struck.filter((s) => far(s) >= 1.2).map((s) => s.volume);
+ expect(near.length).toBeGreaterThan(3);
+ expect(rest.length).toBeGreaterThan(0);
+ expect(sum(near) / near.length).toBeLessThan((sum(rest) / rest.length) * 0.5);
+ expect(sum(struck.map((s) => s.volume))).toBeCloseTo(8, 3);
+ });
+
+ it('fills a solid that is not a box: one with a hole through it', () => {
+ const m = model(
+ { op: 'box', size: [4, 3, 0.5], tag: 'wall' }, { op: 'box', size: [1, 1, 2], tag: 'cutter' },
+ { op: 'boolean', operation: 'subtract', with: 'cutter', from: 'wall' },
+ { op: 'fracture', pieces: 10, seed: 1 },
+ );
+ expect(sum(m.shards!.map((s) => s.volume))).toBeCloseTo(6 - 0.5, 3);
+ expect(m.report.openEdges).toBe(0);
+ });
+
+ it('breaks a hollow thing into as many pieces as asked, struck or not', () => {
+ // A thin-walled pot: most of its bounds are air, inside it and round it, where a point owns none of it.
+ const pot = { op: 'lathe', sides: 16, profile: [[0, 0], [0.5, 0], [0.8, 1], [0.5, 1.9], [0.42, 1.9], [0.7, 1], [0.42, 0.1], [0, 0.1]] } as ModelStep;
+ for (const [pieces, focus] of [[5, 0], [5, 0.5], [12, 0.8]] as const) {
+ const m = model(pot, { op: 'fracture', pieces, seed: 4, at: [0.8, 1, 0], focus });
+ expect(m.shards).toHaveLength(pieces);
+ expect(m.report.warnings.join()).not.toMatch(/pieces of the/);
+ expect(m.report.openEdges).toBe(0);
+ }
+ });
+
+ it('breaks one part of a model and leaves the rest whole, and says so', () => {
+ const m = model(block, { op: 'box', size: [4, 0.2, 4], at: [0, -1.1, 0], tag: 'plinth' }, { op: 'fracture', faces: 'stone', pieces: 6, seed: 2 });
+ expect(m.cut!.poly.faces.filter((f) => f.tag === 'plinth').every((f) => f.piece === undefined)).toBe(true);
+ expect(sum(m.shards!.map((s) => s.volume))).toBeCloseTo(8, 3);
+ expect(m.report.warnings.join()).toMatch(/some faces are of no piece/);
+ });
+
+ it('leaves no sliver: a piece too small to see is given to its neighbours, and the solid is still filled', () => {
+ // Crowded hard into one corner, some points would own almost nothing.
+ const m = model(block, { op: 'fracture', pieces: 40, seed: 11, at: [1, 1, 1], focus: 1 });
+ const volumes = m.shards!.map((s) => s.volume);
+ const mean = sum(volumes) / volumes.length;
+ expect(Math.min(...volumes)).toBeGreaterThan(mean * 0.03);
+ expect(sum(volumes)).toBeCloseTo(8, 3);
+ });
+
+ it('has to be the last step, since what follows would change the pieces and not the model', () => {
+ expect(() => model(block, { op: 'fracture', pieces: 4 }, { op: 'box', size: 1, at: [5, 0, 0] })).toThrow(/fracture has to be the last step/);
+ });
+
+ it('refuses what cannot be broken, and says why', () => {
+ expect(() => model({ op: 'plane', size: [2, 2] }, { op: 'fracture', pieces: 4 })).toThrow(/what is to be broken is not a closed solid: they have 4 open edges/);
+ expect(() => model(block, { op: 'fracture', pieces: 1 })).toThrow(/pieces must be a whole number, 2\.\.64/);
+ expect(() => model(block, { op: 'fracture', pieces: 4 }, { op: 'fracture', pieces: 4 })).toThrow(/already in pieces: fracture once/);
+ expect(() => model(block, { op: 'fracture', pieces: 4, faces: 'nothing' })).toThrow(/matched no face/);
+ expect(() => validateModelSource({ version: 1, steps: [block, { op: 'fracture' }] })).toThrow(/pieces/);
+ expect(needsPreparing([{ op: 'fracture' }])).toBe(true);
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index eb9e2c370..c35242661 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 166 beta · 2181 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2188 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1851,6 +1851,11 @@ softness: number
(x: number, z: number) => number | null
```
+## BodyPusher — type @experimental
+```
+(entity: Entity, velocity: Vec3) => boolean
+```
+
## BodyType — enum @experimental
```
Dynamic = 2
@@ -1928,6 +1933,29 @@ isSensor: boolean
restitution: number
```
+## Breakable — const @experimental
+```
+ComponentDef<BreakableData>
+```
+
+## BreakableData — interface @experimental
+```
+broken: boolean
+burst: number
+enabled: boolean
+lifetime: number
+origin: Vec3
+pieces: string
+```
+
+## BreakablePlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): BreakablePlugin
+static prototype: BreakablePlugin
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -8366,6 +8394,7 @@ rootId: string
## PrefabServer — class @beta
```
instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+prepare: (pathOrAddress: string) => Promise<{ release(): void; }>
static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -14855,6 +14884,11 @@ MotionDriver<AnimatorBlend2DMotion>
(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
+## breakablePlugin — const @experimental
+```
+BreakablePlugin
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -14945,6 +14979,11 @@ MotionDriver<AnimatorBlend2DMotion>
(id: string): BuiltinShaderTemplate | undefined
```
+## burstVelocity — function @experimental
+```
+(piece: Vec3, origin: Vec3, speed: number): Vec3
+```
+
## calculateAttenuation — function @experimental
```
(distance: number, config?: SpatialAudioConfig): number
@@ -17885,6 +17924,11 @@ ServicesPlugin
(app: App, sample: BlobShadowGround | null): void
```
+## setBodyPusher — function @experimental
+```
+(push: BodyPusher | null): void
+```
+
## setButtonState — function @experimental
```
(world: World, entity: Entity, state: string): void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 323c346cf..a440cc68a 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 171 beta · 2201 experimental · 3 deprecated
+Symbols: 115 public · 171 beta · 2208 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1851,6 +1851,11 @@ softness: number
(x: number, z: number) => number | null
```
+## BodyPusher — type @experimental
+```
+(entity: Entity, velocity: Vec3) => boolean
+```
+
## BodyType — enum @experimental
```
Dynamic = 2
@@ -1928,6 +1933,29 @@ isSensor: boolean
restitution: number
```
+## Breakable — const @experimental
+```
+ComponentDef<BreakableData>
+```
+
+## BreakableData — interface @experimental
+```
+broken: boolean
+burst: number
+enabled: boolean
+lifetime: number
+origin: Vec3
+pieces: string
+```
+
+## BreakablePlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): BreakablePlugin
+static prototype: BreakablePlugin
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -8580,6 +8608,7 @@ rootId: string
## PrefabServer — class @beta
```
instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+prepare: (pathOrAddress: string) => Promise<{ release(): void; }>
static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -15099,6 +15128,11 @@ MotionDriver<AnimatorBlend2DMotion>
(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
+## breakablePlugin — const @experimental
+```
+BreakablePlugin
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -15189,6 +15223,11 @@ MotionDriver<AnimatorBlend2DMotion>
(id: string): BuiltinShaderTemplate | undefined
```
+## burstVelocity — function @experimental
+```
+(piece: Vec3, origin: Vec3, speed: number): Vec3
+```
+
## calculateAttenuation — function @experimental
```
(distance: number, config?: SpatialAudioConfig): number
@@ -18164,6 +18203,11 @@ ServicesPlugin
(app: App, sample: BlobShadowGround | null): void
```
+## setBodyPusher — function @experimental
+```
+(push: BodyPusher | null): void
+```
+
## setButtonState — function @experimental
```
(world: World, entity: Entity, state: string): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 13da622b3..076719f56 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 168 beta · 2180 experimental · 3 deprecated
+Symbols: 115 public · 168 beta · 2187 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1846,6 +1846,11 @@ softness: number
(x: number, z: number) => number | null
```
+## BodyPusher — type @experimental
+```
+(entity: Entity, velocity: Vec3) => boolean
+```
+
## BodyType — enum @experimental
```
Dynamic = 2
@@ -1923,6 +1928,29 @@ isSensor: boolean
restitution: number
```
+## Breakable — const @experimental
+```
+ComponentDef<BreakableData>
+```
+
+## BreakableData — interface @experimental
+```
+broken: boolean
+burst: number
+enabled: boolean
+lifetime: number
+origin: Vec3
+pieces: string
+```
+
+## BreakablePlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): BreakablePlugin
+static prototype: BreakablePlugin
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -8361,6 +8389,7 @@ rootId: string
## PrefabServer — class @beta
```
instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+prepare: (pathOrAddress: string) => Promise<{ release(): void; }>
static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -14850,6 +14879,11 @@ MotionDriver<AnimatorBlend2DMotion>
(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
+## breakablePlugin — const @experimental
+```
+BreakablePlugin
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -14940,6 +14974,11 @@ MotionDriver<AnimatorBlend2DMotion>
(id: string): BuiltinShaderTemplate | undefined
```
+## burstVelocity — function @experimental
+```
+(piece: Vec3, origin: Vec3, speed: number): Vec3
+```
+
## calculateAttenuation — function @experimental
```
(distance: number, config?: SpatialAudioConfig): number
@@ -17890,6 +17929,11 @@ ServicesPlugin
(app: App, sample: BlobShadowGround | null): void
```
+## setBodyPusher — function @experimental
+```
+(push: BodyPusher | null): void
+```
+
## setButtonState — function @experimental
```
(world: World, entity: Entity, state: string): void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 269ba888a..3e4467afd 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 166 beta · 2202 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2209 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1846,6 +1846,11 @@ softness: number
(x: number, z: number) => number | null
```
+## BodyPusher — type @experimental
+```
+(entity: Entity, velocity: Vec3) => boolean
+```
+
## BodyType — enum @experimental
```
Dynamic = 2
@@ -1923,6 +1928,29 @@ isSensor: boolean
restitution: number
```
+## Breakable — const @experimental
+```
+ComponentDef<BreakableData>
+```
+
+## BreakableData — interface @experimental
+```
+broken: boolean
+burst: number
+enabled: boolean
+lifetime: number
+origin: Vec3
+pieces: string
+```
+
+## BreakablePlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): BreakablePlugin
+static prototype: BreakablePlugin
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -8658,6 +8686,7 @@ rootId: string
## PrefabServer — class @beta
```
instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+prepare: (pathOrAddress: string) => Promise<{ release(): void; }>
static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -15153,6 +15182,11 @@ MotionDriver<AnimatorBlend2DMotion>
(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
+## breakablePlugin — const @experimental
+```
+BreakablePlugin
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -15243,6 +15277,11 @@ MotionDriver<AnimatorBlend2DMotion>
(id: string): BuiltinShaderTemplate | undefined
```
+## burstVelocity — function @experimental
+```
+(piece: Vec3, origin: Vec3, speed: number): Vec3
+```
+
## calculateAttenuation — function @experimental
```
(distance: number, config?: SpatialAudioConfig): number
@@ -18198,6 +18237,11 @@ ServicesPlugin
(app: App, sample: BlobShadowGround | null): void
```
+## setBodyPusher — function @experimental
+```
+(push: BodyPusher | null): void
+```
+
## setButtonState — function @experimental
```
(world: World, entity: Entity, state: string): void
diff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.md
index c73ed9192..7aef37de0 100644
--- a/sdk/etc/physics3d.api.md
+++ b/sdk/etc/physics3d.api.md
@@ -315,12 +315,14 @@ static prototype: Physics3DPlugin
## Physics3DQueries — class @experimental
```
+hasBody: (entity: Entity) => boolean
overlapBox: (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
+setLinearVelocity: (entity: Entity, velocity: { x: number; y: number; z: number; }) => boolean
sphereCast: (origin: { x: number; y: number; z: number; }, radius: number, direction: { x: number; y: number; z: number; }, layerMask?: number) => Cast3DHit | null
teleportCharacter: (entity: Entity, position: { x: number; y: number; z: number; }) => boolean
-static new (module_: Physics3DWasmModule, ppu_: number, characters_?: ReadonlyMap<Entity, number>): Physics3DQueries
+static new (module_: Physics3DWasmModule, ppu_: number, characters_?: ReadonlyMap<Entity, number>, bodies_?: ReadonlyMap<Entity, number>): Physics3DQueries
static prototype: Physics3DQueries
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index d3dc660e6..e94253900 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 166 beta · 2193 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2200 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1846,6 +1846,11 @@ softness: number
(x: number, z: number) => number | null
```
+## BodyPusher — type @experimental
+```
+(entity: Entity, velocity: Vec3) => boolean
+```
+
## BodyType — enum @experimental
```
Dynamic = 2
@@ -1923,6 +1928,29 @@ isSensor: boolean
restitution: number
```
+## Breakable — const @experimental
+```
+ComponentDef<BreakableData>
+```
+
+## BreakableData — interface @experimental
+```
+broken: boolean
+burst: number
+enabled: boolean
+lifetime: number
+origin: Vec3
+pieces: string
+```
+
+## BreakablePlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): BreakablePlugin
+static prototype: BreakablePlugin
+```
+
## BuildProfile — interface @experimental
```
remoteRoot: string | undefined
@@ -8368,6 +8396,7 @@ rootId: string
## PrefabServer — class @beta
```
instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+prepare: (pathOrAddress: string) => Promise<{ release(): void; }>
static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -14884,6 +14913,11 @@ MotionDriver<AnimatorBlend2DMotion>
(x0: number, z0: number, size: number, y0: number, y1: number, ex: number, ey: number, ez: number): number
```
+## breakablePlugin — const @experimental
+```
+BreakablePlugin
+```
+
## bucketOverridesByEntity — function @experimental
```
(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>
@@ -14974,6 +15008,11 @@ MotionDriver<AnimatorBlend2DMotion>
(id: string): BuiltinShaderTemplate | undefined
```
+## burstVelocity — function @experimental
+```
+(piece: Vec3, origin: Vec3, speed: number): Vec3
+```
+
## calculateAttenuation — function @experimental
```
(distance: number, config?: SpatialAudioConfig): number
@@ -17924,6 +17963,11 @@ ServicesPlugin
(app: App, sample: BlobShadowGround | null): void
```
+## setBodyPusher — function @experimental
+```
+(push: BodyPusher | null): void
+```
+
## setButtonState — function @experimental
```
(world: World, entity: Entity, state: string): void
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index 843a14caf..c3694bc62 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -27,6 +27,7 @@ import { ScreenOverlay, defaultScreenOverlay } from '../ui/core/screen-overlay';
import { inputPlugin, Input, setInputExecutionHeld } from '../input/input';
import { assetPlugin } from '../asset';
import { prefabsPlugin } from '../prefab/prefabServer';
+import { breakablePlugin } from '../breakable/breakable';
import { setWasmErrorHandler } from '../wasm/wasmError';
import { corePlugin, DEFAULT_UI_CAMERA_INFO } from './corePlugin';
import {
@@ -2258,6 +2259,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
app.addPlugin(cameraPlugin(options?.getViewportSize));
app.addPlugin(assetPlugin);
app.addPlugin(prefabsPlugin);
+ app.addPlugin(breakablePlugin);
app.addPlugin(inputPlugin);
app.addPlugin(sceneManagerPlugin);
if (options?.plugins) {
diff --git a/sdk/src/breakable/breakable.ts b/sdk/src/breakable/breakable.ts
new file mode 100644
index 000000000..5eb207536
--- /dev/null
+++ b/sdk/src/breakable/breakable.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file breakable.ts
+ * @brief A thing that breaks: drawn whole until it is struck, and its pieces let go after.
+ *
+ * Nothing is cut when it breaks. The pieces were cut beforehand (a model's `fracture` step writes them as a prefab,
+ * each a mesh about its own middle with a body and a hull), and they fit together into the thing with no gap. Raising
+ * `broken` hides the whole, puts the pieces where it stood and throws each one out from where it was struck; lowering
+ * it takes the pieces away and shows the whole again, which is the flag contract `AudioSource.playing` keeps: a script,
+ * a graph node and the inspector all write the same switch.
+ *
+ * It needs no physics to swap one for the other. The 3D world, where a game has one, says how a body is pushed
+ * ({@link setBodyPusher}); a game without one has pieces that appear in place and stay there, and this file pulls
+ * no solver into its bundle.
+ */
+import type { App, Plugin } from '../app/app';
+import type { Entity, Vec3 } from '../types';
+import { defineComponent, getComponent, Transform, type TransformData } from '../ecs/component';
+import { defineSystem, Schedule } from '../ecs/system';
+import { Res, Time, type TimeData } from '../ecs/resource';
+import { isEditor, isPlayMode } from '../ecs/env';
+import { Prefabs, type PrefabServer } from '../prefab/prefabServer';
+import { q } from '../math/quat';
+import { log } from '../util/logger';
+
+export interface BreakableData {
+ /** The prefab of its pieces, as a model's `fracture` step writes it. */
+ pieces: string;
+ /** Raise it and the thing breaks; lower it and it is whole again. */
+ broken: boolean;
+ /** How fast the pieces leave, in world units a second, straight out from `origin`. 0 lets them fall where they are. */
+ burst: number;
+ /** Where it is struck, from its own origin: the pieces fly away from here. */
+ origin: Vec3;
+ /** Seconds the pieces last before they are taken away. 0 keeps them. */
+ lifetime: number;
+ enabled: boolean;
+}
+
+export const Breakable = defineComponent<BreakableData>('Breakable', {
+ pieces: '',
+ broken: false,
+ burst: 300,
+ origin: { x: 0, y: 0, z: 0 },
+ lifetime: 0,
+ enabled: true,
+}, {
+ assetFields: [{ field: 'pieces', type: 'prefab' }],
+ fields: {
+ pieces: { tooltip: 'The prefab of its pieces: a model with a fracture step writes one beside its mesh.' },
+ broken: { tooltip: 'Raise to break it, lower to make it whole again.' },
+ 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.' },
+ },
+});
+
+/** Sets a body's velocity, in world units a second; false while the entity has no body yet. */
+export type BodyPusher = (entity: Entity, velocity: Vec3) => boolean;
+let pusher: BodyPusher | null = null;
+
+/** The 3D world says how a body is pushed, when it has loaded; null when it has gone. */
+export function setBodyPusher(push: BodyPusher | null): void {
+ pusher = push;
+}
+
+interface Broken {
+ /** Still waiting for its prefab: nothing is shown as broken until the pieces are there to show. */
+ loading: boolean;
+ root: Entity | null;
+ age: number;
+ /** Pieces still to be thrown: a body is made by the world's next step, not by the spawn. */
+ throws: { entity: Entity; velocity: Vec3; tries: number }[];
+}
+
+/** Which way each piece goes: out from where the thing was struck, and a little up, so a pot does not only fall open. */
+export function burstVelocity(piece: Vec3, origin: Vec3, speed: number): Vec3 {
+ let [x, y, z] = [piece.x - origin.x, piece.y - origin.y, piece.z - origin.z];
+ const far = Math.hypot(x, y, z);
+ // A piece that lies where it was struck has no way out of its own: up.
+ if (far < 1e-6) [x, y, z] = [0, 1, 0];
+ else [x, y, z] = [x / far, y / far + 0.35, z / far];
+ const long = Math.hypot(x, y, z);
+ return { x: (x / long) * speed, y: (y / long) * speed, z: (z / long) * speed };
+}
+
+export class BreakablePlugin implements Plugin {
+ name = 'breakable';
+
+ build(app: App): void {
+ const state = new Map<Entity, Broken>();
+ const world = app.world;
+ const show = (entity: Entity, visible: boolean): void => {
+ // The whole is hidden, not removed: it is what comes back, with everything a scene hung on it.
+ for (const name of ['MeshRenderer', 'RigidBody3D', 'BoxCollider3D', 'SphereCollider3D', 'CapsuleCollider3D', 'ConvexCollider3D', 'MeshCollider3D']) {
+ const def = getComponent(name);
+ if (def && world.has(entity, def)) world.update(entity, def, (d: { enabled?: boolean }) => { d.enabled = visible; });
+ }
+ };
+ const mend = (entity: Entity): void => {
+ const b = state.get(entity);
+ state.delete(entity);
+ if (b?.root !== null && b?.root !== undefined && world.valid(b.root)) world.despawn(b.root);
+ if (world.valid(entity)) show(entity, true);
+ };
+ // Its pieces are made ready while it stands whole: a prefab's meshes are files of their own, and loaded only
+ // when it breaks they would arrive frames after the blow, with the whole already gone and nothing in its place.
+ const warm = new Map<Entity, { pieces: string; release: (() => void) | null; dropped: boolean }>();
+ const cool = (entity: Entity): void => {
+ const w = warm.get(entity);
+ if (!w) return;
+ warm.delete(entity);
+ w.dropped = true;
+ w.release?.();
+ };
+ const keepWarm = (entity: Entity, pieces: string, prefabs: PrefabServer): void => {
+ const had = warm.get(entity);
+ if (had?.pieces === pieces) return;
+ cool(entity);
+ if (!pieces || typeof prefabs.prepare !== 'function') return;
+ const w = { pieces, release: null as (() => void) | null, dropped: false };
+ warm.set(entity, w);
+ prefabs.prepare(pieces).then((held) => {
+ if (w.dropped) held.release(); else w.release = () => held.release();
+ }, () => { /* breaking says why it cannot, when it is asked to */ });
+ };
+ const offDespawn = world.onDespawn((entity: Entity) => {
+ cool(entity);
+ const b = state.get(entity);
+ if (!b) return;
+ state.delete(entity);
+ if (b.root !== null && world.valid(b.root)) world.despawn(b.root);
+ });
+ void offDespawn;
+
+ const shatter = (entity: Entity, data: BreakableData, prefabs: PrefabServer): void => {
+ const b: Broken = { loading: true, root: null, age: 0, throws: [] };
+ state.set(entity, b);
+ prefabs.instantiate(data.pieces).then((made) => {
+ // Mended, removed or switched off while the pieces were loading: they are not wanted.
+ if (state.get(entity) !== b || !world.valid(entity)) { if (world.valid(made.root)) world.despawn(made.root); return; }
+ 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];
+ // Where the whole stood, turned and sized as it was: the pieces are its children and come with it.
+ world.update(made.root, Transform, (d: TransformData) => { d.position = { ...position }; d.rotation = { ...rotation }; d.scale = { ...scale }; });
+ show(entity, false);
+ b.loading = false;
+ b.root = made.root;
+ if (data.burst > 0) {
+ const from = q.rotate(rotation, { x: data.origin.x * scale.x, y: data.origin.y * scale.y, z: data.origin.z * scale.z });
+ const origin = { x: position.x + from.x, y: position.y + from.y, z: position.z + from.z };
+ const body = getComponent('RigidBody3D');
+ for (const piece of made.entities.values()) {
+ if (piece === made.root || !body || !world.has(piece, body)) continue;
+ const local = (world.get(piece, Transform) as TransformData).position;
+ const turned = q.rotate(rotation, { x: local.x * scale.x, y: local.y * scale.y, z: local.z * scale.z });
+ b.throws.push({ entity: piece, velocity: burstVelocity({ x: position.x + turned.x, y: position.y + turned.y, z: position.z + turned.z }, origin, data.burst), tries: 0 });
+ }
+ }
+ }).catch((err) => {
+ // Whether the prefab could not be read or its pieces could not be placed, the thing is left as it was.
+ log.warn('breakable', `cannot break into "${data.pieces}"; the thing stays whole`, err);
+ if (b.root !== null && world.valid(b.root)) world.despawn(b.root);
+ if (world.valid(entity)) show(entity, true);
+ if (state.get(entity) === b) state.delete(entity);
+ if (world.valid(entity)) world.update(entity, Breakable, (d: BreakableData) => { d.broken = false; });
+ });
+ };
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time)], (time: TimeData) => {
+ if (isEditor() && !isPlayMode()) {
+ // Out of play nothing is broken: what a scene saves is the whole.
+ for (const entity of [...state.keys()]) mend(entity);
+ for (const entity of [...warm.keys()]) cool(entity);
+ return;
+ }
+ const prefabs = app.hasResource(Prefabs) ? app.getResource(Prefabs) : null;
+ const live = new Set<Entity>();
+ for (const entity of world.getEntitiesWithComponents([Breakable])) {
+ const data = world.get(entity, Breakable) as BreakableData;
+ live.add(entity);
+ if (prefabs && data.enabled) keepWarm(entity, data.pieces, prefabs); else cool(entity);
+ const b = state.get(entity);
+ if (!data.enabled || !data.broken) { if (b) mend(entity); continue; }
+ if (!b) { if (data.pieces && prefabs) shatter(entity, data, prefabs); continue; }
+ if (b.loading) continue;
+ // The world makes a piece's body on its next step; until then there is nothing to throw.
+ if (b.throws.length) {
+ b.throws = b.throws.filter((t) => {
+ if (!world.valid(t.entity)) return false;
+ if (pusher?.(t.entity, t.velocity)) return false;
+ return ++t.tries < 30;
+ });
+ }
+ b.age += time.delta;
+ if (data.lifetime > 0 && b.age >= data.lifetime && b.root !== null) {
+ if (world.valid(b.root)) world.despawn(b.root);
+ b.root = null;
+ b.throws = [];
+ }
+ }
+ for (const entity of [...state.keys()]) if (!live.has(entity)) mend(entity);
+ for (const entity of [...warm.keys()]) if (!live.has(entity)) cool(entity);
+ }, { name: 'BreakableSystem' }));
+ }
+}
+
+export const breakablePlugin = new BreakablePlugin();
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 0ac50f24b..5ff82cdbb 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -433,6 +433,7 @@ export {
} from './prefab/index';
export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin, type SpawnOverride } from './prefab/prefabServer';
+export { Breakable, BreakablePlugin, breakablePlugin, burstVelocity, setBodyPusher, type BreakableData, type BodyPusher } from './breakable/breakable';
// =============================================================================
// Runtime Loader
diff --git a/sdk/src/ecs/bridge/nativeRuntime.ts b/sdk/src/ecs/bridge/nativeRuntime.ts
index 2569f9182..4f97781f9 100644
--- a/sdk/src/ecs/bridge/nativeRuntime.ts
+++ b/sdk/src/ecs/bridge/nativeRuntime.ts
@@ -15,6 +15,7 @@ import { App, setAppSurfaceSize } from '../../app/app';
import { World } from '../world';
import { inputPlugin } from '../../input/input';
import { prefabsPlugin } from '../../prefab/prefabServer';
+import { breakablePlugin } from '../../breakable/breakable';
import { sceneManagerPlugin } from '../../scene/scenePlugin';
import { headlessBasePlugins } from '../../runtime/webAppFactory';
import { presentationBasePlugins, inBuildOrder } from '../../app/pluginSets';
@@ -150,6 +151,7 @@ export function createNativeApp(
installNativeUI(app, scope);
app.addPlugin(inputPlugin);
app.addPlugin(prefabsPlugin);
+ app.addPlugin(breakablePlugin);
app.addPlugin(sceneManagerPlugin);
app.addPlugins(headlessBasePlugins());
// The presentation stack — the same list the web factory installs. These used to
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index 14563b72b..8dd9d87b6 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -4,6 +4,7 @@
* @file Physics3DPlugin.ts
* @brief Loads the 3D physics module and drives one world from the ECS.
*/
+import { setBodyPusher } from '../breakable/breakable';
import { AnimatorController } from '../animation/Animator';
import { installPlanetGravity } from './planetGravity';
import { installRagdolls } from './ragdoll';
@@ -74,7 +75,9 @@ export class Physics3DPlugin implements Plugin {
runtime.module = module;
// The character map, not a copy of it: characters are created lazily
// by the step, so a snapshot taken here would never hold one.
- const queries = new Physics3DQueries(module, this.config_.pixelsPerUnit, runtime.characters);
+ const queries = new Physics3DQueries(module, this.config_.pixelsPerUnit, runtime.characters, runtime.bodies);
+ // Whatever throws things about without knowing there is a solver asks through this.
+ setBodyPusher((entity, velocity) => queries.setLinearVelocity(entity, velocity));
app.insertResource(Physics3D, queries);
// What a foot-plant constraint stands on. Beside the queries, because the animation core must not know physics exists.
if (app.hasResource(AnimatorController)) {
diff --git a/sdk/src/physics3d/Physics3DQueries.ts b/sdk/src/physics3d/Physics3DQueries.ts
index 456b3e928..64bd1074b 100644
--- a/sdk/src/physics3d/Physics3DQueries.ts
+++ b/sdk/src/physics3d/Physics3DQueries.ts
@@ -41,7 +41,26 @@ export interface Overlap3DHit {
export class Physics3DQueries {
constructor(private readonly module_: Physics3DWasmModule,
private readonly ppu_: number,
- private readonly characters_: ReadonlyMap<Entity, number> = new Map()) {}
+ private readonly characters_: ReadonlyMap<Entity, number> = new Map(),
+ private readonly bodies_: ReadonlyMap<Entity, number> = new Map()) {}
+
+ /**
+ * Send a body off at a velocity, in world units a second: a blast, a kick, a piece of something that broke. What
+ * the solver does with it after that is the solver's. Answers false for an entity the world has no body for,
+ * which is also true for one frame after a body's entity is spawned: the world makes the body on its next step.
+ */
+ setLinearVelocity(entity: Entity, velocity: { x: number; y: number; z: number }): boolean {
+ const id = this.bodies_.get(entity);
+ if (id === undefined) return false;
+ const p = this.ppu_;
+ this.module_._physics3d_setLinearVelocity(id, velocity.x / p, velocity.y / p, velocity.z / p);
+ return true;
+ }
+
+ /** Whether the world has a body for this entity yet. */
+ hasBody(entity: Entity): boolean {
+ return this.bodies_.has(entity);
+ }
/**
* Put a character somewhere, rather than moving it there. Its position is an
diff --git a/sdk/src/prefab/prefabServer.ts b/sdk/src/prefab/prefabServer.ts
index ea54d545d..953f67493 100644
--- a/sdk/src/prefab/prefabServer.ts
+++ b/sdk/src/prefab/prefabServer.ts
@@ -76,6 +76,19 @@ export class PrefabServer {
} finally { lease.release(); }
}
+ /**
+ * Load a prefab and everything its entities use - meshes, materials,
+ * textures - and hold them, so that an instantiate later finds them loaded
+ * and its entities appear on the frame they are asked for rather than when
+ * their files arrive. Release what it answers when they are no longer
+ * wanted.
+ */
+ async prepare(pathOrAddress: string): Promise<{ release(): void }> {
+ const prepared = await this.getAssets_().preparePrefab(pathOrAddress);
+ let held = true;
+ return { release: () => { if (held) { held = false; prepared.release(); } } };
+ }
+
/**
* The load is asynchronous, so the scene that asked may already be gone by
* the time the entities exist — adopting into whatever is active now is the
diff --git a/sdk/src/runtime/webAppFactory.ts b/sdk/src/runtime/webAppFactory.ts
index 6abc566ae..5658a6976 100644
--- a/sdk/src/runtime/webAppFactory.ts
+++ b/sdk/src/runtime/webAppFactory.ts
@@ -5,6 +5,7 @@ import type { CppRegistry, ESEngineModule } from '../wasm';
import { log } from '../util/logger';
import { assetPlugin } from '../asset';
import { prefabsPlugin } from '../prefab/prefabServer';
+import { breakablePlugin } from '../breakable/breakable';
import { sceneManagerPlugin } from '../scene/scenePlugin';
import { seedEngineComponents } from '../ecs/component';
import { uiPlugins } from '../app/uiPlugins';
@@ -81,6 +82,7 @@ export function createHeadlessApp(module: ESEngineModule, options?: HeadlessAppO
// material, post-process) that only exist after initRenderer().
app.addPlugin(assetPlugin);
app.addPlugin(prefabsPlugin);
+ app.addPlugin(breakablePlugin);
app.addPlugin(sceneManagerPlugin);
// A server steps what the client steps: the optional subsystems an entry
// installed run here too.
diff --git a/sdk/tests/breakable.test.ts b/sdk/tests/breakable.test.ts
new file mode 100644
index 000000000..537352680
--- /dev/null
+++ b/sdk/tests/breakable.test.ts
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file breakable.test.ts
+ * @brief A thing that breaks: whole until its flag is raised, its pieces after, and whole again when it is lowered.
+ *
+ * Held here: that raising `broken` puts the pieces where the whole stood and hides the whole rather than
+ * removing it, that each piece is thrown out from where the thing was struck once the world has a body for
+ * it, that the pieces go after their lifetime, and that lowering the flag undoes all of it.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import type { Entity } from '../src/types';
+import type { TransformData } from '../src/ecs/component';
+import type { PrefabServer } from '../src/prefab/prefabServer';
+
+// The engine's own Transform, MeshRenderer and RigidBody3D live in the C++ registry, which a unit test has none of.
+// Stood in for here by components of the same shape, handed out under the names the breakable asks for them by.
+vi.mock('../src/ecs/component', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../src/ecs/component')>();
+ const Transform = real.defineComponent('BreakableTestTransform', { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } });
+ const stand: Record<string, unknown> = {
+ MeshRenderer: real.defineComponent('BreakableTestRenderer', { enabled: true }),
+ RigidBody3D: real.defineComponent('BreakableTestBody', { bodyType: 2, enabled: true }),
+ };
+ return { ...real, Transform, getComponent: (name: string) => stand[name] ?? real.getComponent(name) };
+});
+
+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 { Prefabs } = await import('../src/prefab/prefabServer');
+const MeshRenderer = getComponent('MeshRenderer')!;
+const Body = getComponent('RigidBody3D')!;
+
+interface Made { root: Entity; pieces: Entity[] }
+
+function setup(pieceAt: [number, number, number][] = [[10, 0, 0], [-10, 0, 0], [0, 10, 0]]) {
+ const app = App.new();
+ app.addPlugin(new BreakablePlugin());
+ const made: Made[] = [];
+ let fail = false;
+ const released: string[] = [];
+ const prefabs = {
+ prepare: vi.fn(async (path: string) => ({ release: () => { released.push(path); } })),
+ instantiate: vi.fn(async () => {
+ if (fail) throw new Error('no such prefab');
+ const root = app.world.spawn('Pieces');
+ app.world.insert(root, Transform, {});
+ const pieces = pieceAt.map(([x, y, z], i) => {
+ const e = app.world.spawn(`Piece ${i + 1}`);
+ app.world.insert(e, Transform, { position: { x, y, z } });
+ app.world.insert(e, Body, {});
+ app.world.setParent?.(e, root);
+ return e;
+ });
+ made.push({ root, pieces });
+ return { root, entities: new Map<number, Entity>([[0, root], ...pieces.map((e, i): [number, Entity] => [i + 1, e])]) };
+ }),
+ } as unknown as PrefabServer;
+ app.insertResource(Prefabs, prefabs);
+ const whole = app.world.spawn('Pot');
+ app.world.insert(whole, Transform, { position: { x: 100, y: 50, z: 0 } });
+ app.world.insert(whole, MeshRenderer, {});
+ app.world.insert(whole, Body, {});
+ app.world.insert(whole, Breakable, { pieces: 'pot_pieces.esprefab', burst: 200 });
+ const breakIt = (on: boolean): void => app.world.update(whole, Breakable, (d) => { d.broken = on; });
+ const tick = async (n = 1): Promise<void> => { for (let i = 0; i < n; i++) await app.tick(0.1); };
+ return { app, whole, made, prefabs, released, breakIt, tick, failNext: () => { fail = true; } };
+}
+
+let pushed: [Entity, { x: number; y: number; z: number }][] = [];
+let bodies = new Set<Entity>();
+beforeEach(() => {
+ pushed = [];
+ bodies = new Set();
+ setBodyPusher((entity, velocity) => { if (!bodies.has(entity)) return false; pushed.push([entity, velocity]); return true; });
+});
+
+describe('a thing that breaks', () => {
+ it('is whole until its flag is raised', async () => {
+ const { app, whole, prefabs, tick } = setup();
+ await tick(3);
+ expect(prefabs.instantiate).not.toHaveBeenCalled();
+ expect(app.world.get(whole, MeshRenderer).enabled).toBe(true);
+ });
+
+ it('has its pieces made ready while it stands whole, and lets them go when it is removed', async () => {
+ const { app, whole, prefabs, released, tick } = setup();
+ await tick(3);
+ expect(prefabs.prepare).toHaveBeenCalledTimes(1);
+ expect(prefabs.prepare).toHaveBeenCalledWith('pot_pieces.esprefab');
+ expect(released).toEqual([]);
+ // Other pieces asked for: the first are let go and the new ones made ready.
+ app.world.update(whole, Breakable, (d) => { d.pieces = 'pot_shards.esprefab'; });
+ await tick(2);
+ expect(released).toEqual(['pot_pieces.esprefab']);
+ expect(prefabs.prepare).toHaveBeenLastCalledWith('pot_shards.esprefab');
+ app.world.despawn(whole);
+ await tick(1);
+ expect(released).toEqual(['pot_pieces.esprefab', 'pot_shards.esprefab']);
+ });
+
+ it('puts its pieces where it stood and hides the whole, which is not removed', async () => {
+ const { app, whole, made, prefabs, breakIt, tick } = setup();
+ breakIt(true);
+ await tick(2);
+ expect(prefabs.instantiate).toHaveBeenCalledTimes(1);
+ expect(prefabs.instantiate).toHaveBeenCalledWith('pot_pieces.esprefab');
+ expect((app.world.get(made[0]!.root, Transform) as TransformData).position).toMatchObject({ x: 100, y: 50, z: 0 });
+ expect(app.world.valid(whole)).toBe(true);
+ expect(app.world.get(whole, MeshRenderer).enabled).toBe(false);
+ expect(app.world.get(whole, Body).enabled).toBe(false);
+ // Once: a thing that is broken is not broken again every frame.
+ await tick(5);
+ expect(prefabs.instantiate).toHaveBeenCalledTimes(1);
+ });
+
+ it('throws each piece out from where it was struck, once the world has a body for it', async () => {
+ const { made, breakIt, tick } = setup();
+ breakIt(true);
+ await tick(2);
+ // No bodies yet: the world makes them on its next step, and nothing is thrown until then.
+ expect(pushed).toEqual([]);
+ for (const e of made[0]!.pieces) bodies.add(e);
+ await tick(1);
+ expect(pushed.map(([e]) => e)).toEqual(made[0]!.pieces);
+ const [right, left, up] = pushed.map(([, v]) => v);
+ // Out along where each lies from the middle, at the speed asked, and a little up.
+ expect(right!.x).toBeGreaterThan(150);
+ expect(left!.x).toBeLessThan(-150);
+ expect(up!.y).toBeGreaterThan(190);
+ for (const v of [right!, left!, up!]) expect(Math.hypot(v.x, v.y, v.z)).toBeCloseTo(200, 6);
+ expect(right!.y).toBeGreaterThan(0);
+ // Thrown once.
+ await tick(3);
+ expect(pushed).toHaveLength(3);
+ });
+
+ it('flies from where it is struck, not from its middle', () => {
+ // Struck on its right side, the piece on the left goes left and the piece at the blow goes up.
+ expect(burstVelocity({ x: -10, y: 0, z: 0 }, { x: 10, y: 0, z: 0 }, 100).x).toBeLessThan(-90);
+ const at = burstVelocity({ x: 10, y: 0, z: 0 }, { x: 10, y: 0, z: 0 }, 100);
+ expect([at.x, at.y, at.z]).toEqual([0, 100, 0]);
+ });
+
+ it('lets its pieces fall where they are when it has no burst', async () => {
+ const { app, whole, made, breakIt, tick } = setup();
+ app.world.update(whole, Breakable, (d) => { d.burst = 0; });
+ breakIt(true);
+ await tick(2);
+ for (const e of made[0]!.pieces) bodies.add(e);
+ await tick(2);
+ expect(pushed).toEqual([]);
+ });
+
+ it('takes the pieces away after their lifetime, and stays broken', async () => {
+ const { app, whole, made, breakIt, tick } = setup();
+ app.world.update(whole, Breakable, (d) => { d.lifetime = 0.5; });
+ breakIt(true);
+ await tick(3);
+ expect(app.world.valid(made[0]!.root)).toBe(true);
+ await tick(5);
+ expect(app.world.valid(made[0]!.root)).toBe(false);
+ expect(app.world.get(whole, MeshRenderer).enabled).toBe(false);
+ expect(app.world.get(whole, Breakable).broken).toBe(true);
+ });
+
+ it('is whole again when the flag is lowered, and breaks afresh when it is raised', async () => {
+ const { app, whole, made, prefabs, breakIt, tick } = setup();
+ breakIt(true);
+ await tick(2);
+ breakIt(false);
+ await tick(1);
+ expect(app.world.valid(made[0]!.root)).toBe(false);
+ expect(app.world.get(whole, MeshRenderer).enabled).toBe(true);
+ expect(app.world.get(whole, Body).enabled).toBe(true);
+ breakIt(true);
+ await tick(2);
+ expect(prefabs.instantiate).toHaveBeenCalledTimes(2);
+ expect(app.world.valid(made[1]!.root)).toBe(true);
+ });
+
+ it('takes its pieces with it when it is removed', async () => {
+ const { app, whole, made, breakIt, tick } = setup();
+ breakIt(true);
+ await tick(2);
+ app.world.despawn(whole);
+ await tick(1);
+ expect(app.world.valid(made[0]!.root)).toBe(false);
+ });
+
+ it('stays whole, and says so, when its pieces cannot be loaded', async () => {
+ const { app, whole, breakIt, tick, failNext } = setup();
+ failNext();
+ breakIt(true);
+ await tick(3);
+ expect(app.world.get(whole, MeshRenderer).enabled).toBe(true);
+ expect(app.world.get(whole, Breakable).broken).toBe(false);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 0a6f19b53..8505381c1 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4728,4 +4728,8 @@ export const NOTED = {
{"note": "A detail the pages cannot hold no longer cracks the ground."},
"fix(foliage): a far plant grows across the ground, not taller - a mesh plant kept in a far version was grown the same every way to cover the ground of those left out, so a flower that stood for ten stood ten times as high and a far meadow was a field of poles; it now grows across the ground only, and Foliage.farGrowUp gives its height a share of the growth back":
{"note": "A far plant grows across the ground, not taller."},
+ "feat(physics3d): things that break - a model's fracture step cuts it beforehand into pieces that fit with no gap, the editor writes them as a prefab of bodies and hulls, and a Breakable swaps the whole for them when its flag is raised, throws them out from where it was struck and mends when the flag is lowered; its pieces are loaded while it stands, so they appear on the frame it breaks":
+ {"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."},
};