Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(verse): add destruction and repair drones (#1156)

Ruben Lütked5267e7f8d74
diff --git a/art/verse/kit/destructible/README.md b/art/verse/kit/destructible/README.md
new file mode 100644
index 0000000000..db43c447e9
--- /dev/null
+++ b/art/verse/kit/destructible/README.md
@@ -0,0 +1,51 @@
+# Destructible kit (WP06)
+
+Builders of the six breakable piece classes of `docs/verse/unreal/contracts/destruction.md`
+3.2: wall panel (1.2 / 2.4 / 4.8 m), cladding wall, container wall, glass pane, catwalk segment
+and ceiling panel. Owner: WP06. Zone owners place them; they never edit them.
+
+| File | What it does | Needs Blender |
+|---|---|---|
+| `geometry.py` | Solids: boxes, slabs with real openings, corrugated sheet, bar grating; convex clipping; seeded Voronoi fracture | no |
+| `catalogue.py` | The pieces, their reference thickness, Holed and Breached variants (up to 4 each), proxy boxes, opening centroids, fracture chunks | no |
+| `validate.py` | The builder validator: closed, manifold, thickness by inward ray sampling within 10 % | no |
+| `pieces.py` | Registers `SM_<Piece>`, `SM_<Piece>_<State>_<n>`, `SM_<Piece>_Proxy_<State>[_<n>]`, `SM_<Piece>_Frac` and `SM_<Piece>_Frac_<State>[_<n>]` as kit pieces | yes |
+| `tests/test_destructible_kit.py` | pytest of all of the above | no |
+
+Run the tests: `python -m pytest art/verse/kit/destructible/tests -q`.
+
+## Geometry rule
+
+Every piece and every variant is one or more solid, closed, manifold shells with the thickness
+of its penetration material (sheet metal 0.3 cm, container wall 0.4 cm, cladding 4.0 cm, glass
+2.4 cm, bar grating 3.0 cm, ceiling tile 2.5 cm). Openings are cut as real geometry: the slab
+face is split on the grid of the opening edges and the opening gets inner walls, so a Holed or
+Breached wall is still one closed shell. A double-plane or one-sided wall fails `validate.py`
+here and `UVerseDestructibleValidator` in the editor.
+
+Collision proxies of wall-like pieces are flat slabs of exactly the reference thickness (for the
+container wall at the middle of the corrugation), at most 16 boxes per state, so the traced
+thickness of a bolt through a proxy is the table's reference thickness.
+
+## Fracture spike (WP06.1): verdict
+
+Route chosen: **Voronoi fracture as code in pure Python, exported as `SM_<Piece>_Frac`**, one
+object per chunk; `verse_pipeline.geometry_collections` turns that set into `GC_<Piece>`.
+
+| Question | Finding |
+|---|---|
+| Determinism | Same seed (`kit.seed_for("verse.destructible", name)`), same chunks, byte for byte (pytest) |
+| Closed chunks | Every chunk part is a closed convex shell (pytest); chunks conserve the piece volume within 1e-6 |
+| Budget | Chunks under 5 cm are left to Niagara, at most 40 rigid chunks per piece (destruction.md 10) |
+| Non-convex pieces | The container wall fractures strip by strip (each corrugation run is convex), the grating bar by bar |
+| Ceiling panel | One chunk: the whole tile falls |
+| Glass | No geometry collection: Niagara shards only |
+| Per-state bursts | `catalogue.debris_sets` picks, per Holed / Breached variant, only the chunks whose centre lies in that opening (nearest the opening first) and, for Destroyed, the largest chunks, each set at most the material's body count (`DEBRIS_BODIES`, tuning.json). Exported as `SM_<Piece>_Frac_<State>[_<n>]` for `GC_<Piece>_<State>[_<n>]`; the runtime spawns the set that fits the grant and charges the budget with its real chunk count, so a standing Holed wall never gets a full chunk set inside it |
+| Fallback | The editor fracture tool with the same seed, if the GC import below cannot build from chunks |
+
+Not proven yet, and owned outside this folder: the export host
+`scripts/verse/export_unreal.py` exports only `kit.architecture` and `kit.props` (its
+`KIT_GROUPS`), so `kit.destructible` pieces cannot be exported until it gains a
+`Destructible` group and content folder `/Game/Verse/Destruction/`; and
+`unreal/Verse/Content/Python/verse_pipeline/geometry_collections.py` is still the reserved
+stub. Both are integration-owner paths; the PR of this package lists them as open.
diff --git a/art/verse/kit/destructible/__init__.py b/art/verse/kit/destructible/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/art/verse/kit/destructible/catalogue.py b/art/verse/kit/destructible/catalogue.py
new file mode 100644
index 0000000000..437e9a9f91
--- /dev/null
+++ b/art/verse/kit/destructible/catalogue.py
@@ -0,0 +1,397 @@
+"""The six destructible piece classes and every state they ship (WP06.2, WP06.3).
+
+Pure Python: each `PieceSpec` builds, per state and variant, the render
+shells, the collision proxy boxes (`SM_<Piece>_Proxy_<State>[_<n>]`, exported
+as `UECOL_Box` primitives) and the opening centroid the server uses to pick a
+variant (contracts/destruction.md 3.1). `fracture_chunks` gives the seeded
+Voronoi chunks of `SM_<Piece>_Frac`; `debris_sets` picks, per state, the chunks
+that really fly (`SM_<Piece>_Frac_<State>_<n>`, the per-state geometry
+collections the client spawns, destruction.md 10). Dimensions in metres,
+Blender piece space.
+
+Thickness is the material's reference thickness (destruction.md 2 and 9,
+decision C4): sheet metal 0.3 cm, corrugated container wall 0.4 cm, cladding
+4.0 cm, laminated glass 2.4 cm, bar grating 3.0 cm, ceiling tile 2.5 cm. The
+collision proxies of wall-like pieces are flat slabs of exactly that
+thickness, so a bolt's traced thickness through a proxy is the reference.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from . import geometry as g
+
+#: Material wire ids of DA_PenetrationTable (destruction.md 2).
+MATERIALS = {
+ "sheet_metal": 0.003,
+ "container_wall": 0.004,
+ "glass": 0.024,
+ "cladding_panel": 0.040,
+ "catwalk_grating": 0.030,
+ "ceiling_panel": 0.025,
+}
+
+#: Most rigid bodies a fracture may spawn (destruction.md 10).
+MAX_BODIES = 40
+#: Fragments under this size are Niagara particles, not rigid bodies.
+MIN_RIGID_M = 0.05
+#: Rigid bodies per state, by material (unreal/Verse/Data/destruction/tuning.json
+#: start_values.debris_bodies through the material's debris type; Breached and
+#: Destroyed share the full value). Glass is Niagara only.
+DEBRIS_BODIES = {
+ "sheet_metal": {"Holed": 12, "Breached": 32, "Destroyed": 32},
+ "container_wall": {"Holed": 14, "Breached": 36, "Destroyed": 36},
+ "cladding_panel": {"Holed": 16, "Breached": 40, "Destroyed": 40},
+ "catwalk_grating": {"Destroyed": 6},
+ "ceiling_panel": {"Destroyed": 1},
+}
+#: A chunk belongs to an opening when its centre lies within this margin of it.
+OPENING_MARGIN_M = 0.10
+
+Opening = tuple[float, float, float, float] # x_min, z_min, x_max, z_max
+
+
+@dataclass
+class StateLook:
+ """One state variant of a piece."""
+
+ state: str
+ variant: int
+ shells: list[g.Mesh]
+ proxy_boxes: list[tuple[g.Vec3, g.Vec3]]
+ centroid: g.Vec3
+
+ @property
+ def proxy_name_suffix(self) -> str:
+ return self.state if self.state == "Intact" else f"{self.state}_{self.variant}"
+
+
+@dataclass
+class DebrisSet:
+ """The chunks one state's debris burst spawns (`GC_<Piece>_<State>_<n>`)."""
+
+ state: str
+ variant: int
+ chunks: list[g.Chunk]
+
+ @property
+ def name_suffix(self) -> str:
+ return self.state if self.state == "Destroyed" else f"{self.state}_{self.variant}"
+
+
+@dataclass
+class PieceSpec:
+ name: str
+ piece_class: str
+ material: str
+ width: float
+ height: float
+ depth: float = 0.0
+ sill: float = 0.0
+ holed: list[list[Opening]] = field(default_factory=list)
+ breached: list[list[Opening]] = field(default_factory=list)
+ fracture_cells: int = 24
+ #: Breached variant that is a low breach (mantle nav link through it).
+ mantle_variant: int | None = None
+
+ @property
+ def thickness(self) -> float:
+ return MATERIALS[self.material]
+
+ @property
+ def thickness_axis(self) -> g.Vec3:
+ return (
+ (0.0, 0.0, 1.0)
+ if self.piece_class in ("CatwalkSegment", "CeilingPanel")
+ else (0.0, 1.0, 0.0)
+ )
+
+ @property
+ def wall_like(self) -> bool:
+ return self.piece_class in ("WallPanel", "CladdingWall", "ContainerWall")
+
+ # ----------------------------------------------------------------------
+ # Shapes
+
+ def _slab_y(self) -> tuple[float, float]:
+ """Y range of the gameplay slab (container: the middle of the corrugation)."""
+ if self.piece_class == "ContainerWall":
+ mid = self.depth / 2
+ return mid - self.thickness / 2, mid + self.thickness / 2
+ return 0.0, self.thickness
+
+ def render_shells(self, openings: list[Opening]) -> list[g.Mesh]:
+ cls = self.piece_class
+ if cls in ("WallPanel", "CladdingWall"):
+ return [g.slab_with_openings(self.width, self.height, 0.0, self.thickness, openings)]
+ if cls == "ContainerWall":
+ strips = g.corrugated(self.width, self.height, self.thickness, self.depth, ribs=8)
+ if not openings:
+ return [g.corrugated_solid(self.width, self.height, self.thickness, self.depth, 8)]
+ return [m for strip in strips for m in _cut_openings(strip, openings)]
+ if cls == "GlassPane":
+ lo = (-self.width / 2, 0.0, self.sill)
+ hi = (self.width / 2, self.thickness, self.sill + self.height)
+ return [g.box(lo, hi)]
+ if cls == "CatwalkSegment":
+ return g.grating(self.width, self.depth, self.thickness, 0.005, 0.03, 0.006)
+ if cls == "CeilingPanel":
+ return [
+ g.box(
+ (-self.width / 2, -self.depth / 2, 0.0),
+ (self.width / 2, self.depth / 2, self.thickness),
+ )
+ ]
+ raise ValueError(cls)
+
+ def proxy_boxes(self, openings: list[Opening]) -> list[tuple[g.Vec3, g.Vec3]]:
+ """Collision boxes of a state: the slab minus the openings, merged row by row (<= 16)."""
+ if not self.wall_like:
+ return [_bounds(self.render_shells([]))]
+ y0, y1 = self._slab_y()
+ xs = sorted(
+ {-self.width / 2, self.width / 2, *(o[0] for o in openings), *(o[2] for o in openings)}
+ )
+ zs = sorted({0.0, self.height, *(o[1] for o in openings), *(o[3] for o in openings)})
+ boxes = []
+ for k in range(len(zs) - 1):
+ cz = (zs[k] + zs[k + 1]) / 2
+ run_start = None
+ for i in range(len(xs) - 1):
+ cx = (xs[i] + xs[i + 1]) / 2
+ solid = not any(o[0] < cx < o[2] and o[1] < cz < o[3] for o in openings)
+ if solid and run_start is None:
+ run_start = xs[i]
+ if not solid and run_start is not None:
+ boxes.append(((run_start, y0, zs[k]), (xs[i], y1, zs[k + 1])))
+ run_start = None
+ if run_start is not None:
+ boxes.append(((run_start, y0, zs[k]), (xs[-1], y1, zs[k + 1])))
+ return boxes
+
+ def looks(self) -> list[StateLook]:
+ out = [
+ StateLook(
+ "Intact",
+ 0,
+ self.render_shells([]),
+ self.proxy_boxes([]),
+ (0.0, 0.0, self.height / 2),
+ )
+ ]
+ for state, variants in (("Holed", self.holed), ("Breached", self.breached)):
+ for k, openings in enumerate(variants):
+ out.append(
+ StateLook(
+ state,
+ k,
+ self.render_shells(openings),
+ self.proxy_boxes(openings),
+ _centroid(openings),
+ )
+ )
+ return out
+
+ def fracture_chunks(self, seed: int) -> list[g.Chunk]:
+ """Seeded Voronoi chunks of the Intact solid; only chunks of at least 5 cm, at most 40."""
+ if self.piece_class == "GlassPane":
+ return [] # glass breaks into Niagara shards only (destruction.md 2)
+ if self.piece_class == "CeilingPanel":
+ shell = self.render_shells([])[0]
+ return [
+ g.Chunk(0, (0.0, 0.0, 0.0), [g.Convex.from_mesh(shell)])
+ ] # the whole tile falls
+ if self.piece_class == "ContainerWall":
+ parts = g.corrugated(self.width, self.height, self.thickness, self.depth, ribs=8)
+ else:
+ # Walls fracture as their intact slab; catwalks as their bars and frames.
+ parts = self.render_shells([])
+ lo, hi = _bounds(parts)
+ points = g.voronoi_points(lo, hi, self.fracture_cells, seed)
+ chunks = [c for c in g.fracture(parts, points) if c.size() >= MIN_RIGID_M]
+ return chunks[:MAX_BODIES]
+
+
+def _chunk_centre(chunk: g.Chunk) -> g.Vec3:
+ lo, hi = chunk.to_mesh().bounds()
+ return tuple((lo[i] + hi[i]) / 2 for i in range(3))
+
+
+def _in_openings(point: g.Vec3, openings: list[Opening], margin: float) -> bool:
+ x, z = point[0], point[2]
+ return any(
+ x0 - margin <= x <= x1 + margin and z0 - margin <= z <= z1 + margin
+ for x0, z0, x1, z1 in openings
+ )
+
+
+def debris_sets(spec: PieceSpec, seed: int) -> list[DebrisSet]:
+ """Per-state debris bursts, each at most the material's body count for that state.
+
+ Holed and Breached: the chunks of the Intact fracture whose centre lies in the
+ variant's openings (nearest the opening centroid first), so the wall that still
+ stands never gets a full chunk set inside it. Destroyed: the largest chunks of the
+ whole piece. Glass has none (Niagara shards only).
+ """
+ budget = DEBRIS_BODIES.get(spec.material, {})
+ chunks = spec.fracture_chunks(seed)
+ if not budget or not chunks:
+ return []
+ out: list[DebrisSet] = []
+ for look in spec.looks():
+ if look.state not in budget:
+ continue
+ openings = (spec.holed if look.state == "Holed" else spec.breached)[look.variant]
+ inside = [c for c in chunks if _in_openings(_chunk_centre(c), openings, OPENING_MARGIN_M)]
+ if not inside:
+ # A small opening between cell centres still throws its nearest chunk.
+ inside = chunks
+
+ def near(c: g.Chunk, centroid: g.Vec3 = look.centroid) -> float:
+ p = _chunk_centre(c)
+ return (p[0] - centroid[0]) ** 2 + (p[2] - centroid[2]) ** 2
+
+ picked = sorted(inside, key=near)[: budget[look.state] if inside is not chunks else 1]
+ out.append(DebrisSet(look.state, look.variant, picked))
+ if "Destroyed" in budget:
+ largest = sorted(chunks, key=lambda c: -c.volume())[: budget["Destroyed"]]
+ out.append(DebrisSet("Destroyed", 0, largest))
+ return out
+
+
+def _cut_openings(strip: g.Mesh, openings: list[Opening]) -> list[g.Mesh]:
+ """Removes the opening rectangles (x, z) from one convex strip; returns convex closed parts."""
+ parts = [g.Convex.from_mesh(strip)]
+ for x0, z0, x1, z1 in openings:
+ next_parts: list[g.Convex] = []
+ for part in parts:
+ # Outside the rectangle = left of x0, right of x1, or between them below z0 / above z1.
+ for keep in (
+ [((1.0, 0.0, 0.0), x0)],
+ [((-1.0, 0.0, 0.0), -x1)],
+ [((-1.0, 0.0, 0.0), -x0), ((1.0, 0.0, 0.0), x1), ((0.0, 0.0, 1.0), z0)],
+ [((-1.0, 0.0, 0.0), -x0), ((1.0, 0.0, 0.0), x1), ((0.0, 0.0, -1.0), -z1)],
+ ):
+ piece: g.Convex | None = part
+ for normal, offset in keep:
+ if piece is None:
+ break
+ piece = piece.clip(normal, offset)
+ if piece is not None:
+ next_parts.append(piece)
+ parts = next_parts
+ return [p.to_mesh() for p in parts]
+
+
+def _bounds(parts: list[g.Mesh]) -> tuple[g.Vec3, g.Vec3]:
+ return g.merge(parts).bounds()
+
+
+def _centroid(openings: list[Opening]) -> g.Vec3:
+ area = sum((o[2] - o[0]) * (o[3] - o[1]) for o in openings)
+ cx = sum((o[0] + o[2]) / 2 * (o[2] - o[0]) * (o[3] - o[1]) for o in openings) / area
+ cz = sum((o[1] + o[3]) / 2 * (o[2] - o[0]) * (o[3] - o[1]) for o in openings) / area
+ return (cx, 0.0, cz)
+
+
+def _holes(width: float) -> list[list[Opening]]:
+ """Four irregular see-and-shoot-through openings (unions of rectangles), never walkable."""
+ q = width / 4
+ out = []
+ for cx, cz in ((-q, 1.45), (q, 1.45), (-q, 0.85), (q, 0.85)):
+ out.append(
+ [
+ (cx - 0.20, cz - 0.12, cx + 0.16, cz + 0.10),
+ (cx - 0.08, cz + 0.10, cx + 0.10, cz + 0.22),
+ (cx + 0.16, cz - 0.04, cx + 0.24, cz + 0.06),
+ ]
+ )
+ return out
+
+
+def _breaches(width: float) -> list[list[Opening]]:
+ """Standing breach (at least 0.9 x 2.0 m, from the floor) and a low breach to mantle through."""
+ half = min(0.5, width / 2 - 0.12)
+ return [
+ [(-half, 0.0, half, 2.05)],
+ [(-half, 0.30, half, 1.10)],
+ ]
+
+
+def catalogue() -> list[PieceSpec]:
+ """Every destructible kit piece WP06 ships."""
+ pieces = []
+ for width in (1.2, 2.4, 4.8):
+ cm = round(width * 100)
+ pieces.append(
+ PieceSpec(
+ f"SM_WallPanel_{cm}",
+ "WallPanel",
+ "sheet_metal",
+ width,
+ 2.7,
+ holed=_holes(width),
+ breached=_breaches(width),
+ fracture_cells=24 if width < 4 else 36,
+ mantle_variant=1,
+ )
+ )
+ pieces.append(
+ PieceSpec(
+ "SM_CladdingWall_240",
+ "CladdingWall",
+ "cladding_panel",
+ 2.4,
+ 2.7,
+ holed=_holes(2.4),
+ breached=_breaches(2.4),
+ fracture_cells=30,
+ mantle_variant=1,
+ )
+ )
+ pieces.append(
+ PieceSpec(
+ "SM_ContainerWall_240",
+ "ContainerWall",
+ "container_wall",
+ 2.4,
+ 2.59,
+ depth=0.04,
+ holed=_holes(2.4),
+ breached=_breaches(2.4),
+ fracture_cells=36,
+ mantle_variant=1,
+ )
+ )
+ pieces.append(PieceSpec("SM_GlassPane_120", "GlassPane", "glass", 1.2, 1.5, sill=0.9))
+ pieces.append(
+ PieceSpec(
+ "SM_CatwalkSegment_240",
+ "CatwalkSegment",
+ "catwalk_grating",
+ 2.4,
+ 0.0,
+ depth=1.2,
+ fracture_cells=6,
+ )
+ )
+ pieces.append(
+ PieceSpec(
+ "SM_CeilingPanel_120",
+ "CeilingPanel",
+ "ceiling_panel",
+ 1.2,
+ 0.0,
+ depth=1.2,
+ fracture_cells=1,
+ )
+ )
+ return pieces
+
+
+def by_name(name: str) -> PieceSpec:
+ for spec in catalogue():
+ if spec.name == name:
+ return spec
+ raise KeyError(name)
diff --git a/art/verse/kit/destructible/geometry.py b/art/verse/kit/destructible/geometry.py
new file mode 100644
index 0000000000..7ec10d9130
--- /dev/null
+++ b/art/verse/kit/destructible/geometry.py
@@ -0,0 +1,489 @@
+"""Solid geometry of the destructible pieces, pure Python (no bpy).
+
+Everything here is in Blender piece space (metres, Z up, X centred, floor at
+Z = 0; wall-like pieces have their room face on Y = 0 and their body toward
++Y; kit/README.md "Conventions"). The Blender builders in ``pieces.py`` turn
+these meshes into objects; pytest and the builder validator check them
+without Blender.
+
+Rules (contracts/destruction.md 9, art-pipeline 13):
+
+- Every piece is a solid, closed, manifold volume with the real thickness of
+ its penetration material. Never double planes, never one-sided shells.
+- Openings (Holed, Breached) are cut as real geometry: the face is split on a
+ grid by the opening edges, the cells inside the opening are dropped and the
+ opening gets its own inner walls, so the result stays one manifold shell.
+- Fracture is Voronoi as code: seeded cell centres, each cell is the piece's
+ convex parts clipped by the bisector half-spaces. Same seed, same chunks.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+
+Vec3 = tuple[float, float, float]
+
+EPS = 1e-9
+
+
+@dataclass
+class Mesh:
+ """Polygon mesh: shared vertices, faces as vertex index loops (outward, counter-clockwise)."""
+
+ verts: list[Vec3] = field(default_factory=list)
+ faces: list[tuple[int, ...]] = field(default_factory=list)
+
+ def add(self, verts: Sequence[Vec3], faces: Iterable[Sequence[int]]) -> None:
+ base = len(self.verts)
+ self.verts.extend(tuple(float(c) for c in v) for v in verts)
+ self.faces.extend(tuple(base + i for i in f) for f in faces)
+
+ def extend(self, other: Mesh) -> None:
+ self.add(other.verts, other.faces)
+
+ def triangles(self) -> list[tuple[int, int, int]]:
+ out = []
+ for face in self.faces:
+ for i in range(1, len(face) - 1):
+ out.append((face[0], face[i], face[i + 1]))
+ return out
+
+ def bounds(self) -> tuple[Vec3, Vec3]:
+ xs, ys, zs = zip(*self.verts, strict=True)
+ return (min(xs), min(ys), min(zs)), (max(xs), max(ys), max(zs))
+
+
+# --------------------------------------------------------------------------
+# Vector helpers
+
+
+def sub(a: Sequence[float], b: Sequence[float]) -> Vec3:
+ return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
+
+
+def add(a: Sequence[float], b: Sequence[float]) -> Vec3:
+ return (a[0] + b[0], a[1] + b[1], a[2] + b[2])
+
+
+def scale(a: Sequence[float], s: float) -> Vec3:
+ return (a[0] * s, a[1] * s, a[2] * s)
+
+
+def dot(a: Sequence[float], b: Sequence[float]) -> float:
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+
+
+def cross(a: Sequence[float], b: Sequence[float]) -> Vec3:
+ return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
+
+
+def length(a: Sequence[float]) -> float:
+ return math.sqrt(dot(a, a))
+
+
+# --------------------------------------------------------------------------
+# Primitive solids
+
+
+def box(lo: Vec3, hi: Vec3) -> Mesh:
+ """Closed box, outward winding."""
+ (x0, y0, z0), (x1, y1, z1) = lo, hi
+ verts = [
+ (x0, y0, z0),
+ (x1, y0, z0),
+ (x1, y1, z0),
+ (x0, y1, z0),
+ (x0, y0, z1),
+ (x1, y0, z1),
+ (x1, y1, z1),
+ (x0, y1, z1),
+ ]
+ faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (2, 3, 7, 6), (1, 2, 6, 5), (3, 0, 4, 7)]
+ mesh = Mesh()
+ mesh.add(verts, faces)
+ return mesh
+
+
+def slab_with_openings(
+ width: float,
+ height: float,
+ y0: float,
+ y1: float,
+ openings: Sequence[tuple[float, float, float, float]],
+ *,
+ z0: float = 0.0,
+) -> Mesh:
+ """A wall slab X in [-w/2, w/2], Z in [z0, z0 + h], Y in [y0, y1] with rectangular openings.
+
+ ``openings`` are (x_min, z_min, x_max, z_max) in piece space; they may touch
+ each other (an irregular hole is a union of rectangles) but must stay inside
+ the slab. The face is split on the grid of all opening edges, cells inside
+ any opening are dropped, and every boundary edge gets a side quad, so the
+ result is one closed manifold shell with real inner walls.
+ """
+ xs = sorted({-width / 2, width / 2, *(o[0] for o in openings), *(o[2] for o in openings)})
+ zs = sorted({z0, z0 + height, *(o[1] for o in openings), *(o[3] for o in openings)})
+ for x_min, z_min, x_max, z_max in openings:
+ if not (-width / 2 <= x_min < x_max <= width / 2 and z0 <= z_min < z_max <= z0 + height):
+ raise ValueError(f"opening {(x_min, z_min, x_max, z_max)} leaves the slab")
+
+ def solid(i: int, k: int) -> bool:
+ if i < 0 or k < 0 or i >= len(xs) - 1 or k >= len(zs) - 1:
+ return False
+ cx, cz = (xs[i] + xs[i + 1]) / 2, (zs[k] + zs[k + 1]) / 2
+ return not any(o[0] < cx < o[2] and o[1] < cz < o[3] for o in openings)
+
+ index: dict[tuple[int, int, int], int] = {}
+ mesh = Mesh()
+
+ def vert(i: int, k: int, side: int) -> int:
+ key = (i, k, side)
+ if key not in index:
+ index[key] = len(mesh.verts)
+ mesh.verts.append((xs[i], y0 if side == 0 else y1, zs[k]))
+ return index[key]
+
+ for i in range(len(xs) - 1):
+ for k in range(len(zs) - 1):
+ if not solid(i, k):
+ continue
+ # Front (-Y): ccw seen from -Y is (x0,z0) (x1,z0) (x1,z1) (x0,z1).
+ mesh.faces.append(
+ (vert(i, k, 0), vert(i + 1, k, 0), vert(i + 1, k + 1, 0), vert(i, k + 1, 0))
+ )
+ mesh.faces.append(
+ (vert(i, k, 1), vert(i, k + 1, 1), vert(i + 1, k + 1, 1), vert(i + 1, k, 1))
+ )
+ # Boundary walls toward empty neighbours.
+ if not solid(i, k - 1): # bottom, normal -Z
+ mesh.faces.append(
+ (vert(i, k, 0), vert(i, k, 1), vert(i + 1, k, 1), vert(i + 1, k, 0))
+ )
+ if not solid(i, k + 1): # top, normal +Z
+ mesh.faces.append(
+ (
+ vert(i, k + 1, 0),
+ vert(i + 1, k + 1, 0),
+ vert(i + 1, k + 1, 1),
+ vert(i, k + 1, 1),
+ )
+ )
+ if not solid(i - 1, k): # left, normal -X
+ mesh.faces.append(
+ (vert(i, k, 0), vert(i, k + 1, 0), vert(i, k + 1, 1), vert(i, k, 1))
+ )
+ if not solid(i + 1, k): # right, normal +X
+ mesh.faces.append(
+ (
+ vert(i + 1, k, 0),
+ vert(i + 1, k, 1),
+ vert(i + 1, k + 1, 1),
+ vert(i + 1, k + 1, 0),
+ )
+ )
+ return mesh
+
+
+def corrugated(width: float, height: float, sheet: float, depth: float, ribs: int) -> list[Mesh]:
+ """A corrugated container wall as convex strips (each a closed prism, sheet thick).
+
+ Trapezoid ribs: flat, rise, crest, fall. Each straight run of the profile is
+ one convex parallelogram prism; neighbouring strips share their end faces'
+ planes only along an edge line, never a face (they meet at a corner).
+ """
+ pitch = width / ribs
+ pts: list[tuple[float, float]] = []
+ for rib in range(ribs):
+ x = -width / 2 + rib * pitch
+ pts += [
+ (x, 0.0),
+ (x + pitch * 0.25, 0.0),
+ (x + pitch * 0.375, depth),
+ (x + pitch * 0.875, depth),
+ ]
+ pts.append((width / 2, 0.0))
+ strips = []
+ for (xa, ya), (xb, yb) in zip(pts, pts[1:], strict=False):
+ if abs(xb - xa) < EPS and abs(yb - ya) < EPS:
+ continue
+ # Parallelogram in XY: the run plus the run offset by the sheet along +Y, extruded in Z.
+ quad = [(xa, ya), (xb, yb), (xb, yb + sheet), (xa, ya + sheet)]
+ strips.append(_extrude_xy(quad, 0.0, height))
+ return strips
+
+
+def corrugated_solid(width: float, height: float, sheet: float, depth: float, ribs: int) -> Mesh:
+ """The same wall as one closed shell (render mesh and proxy)."""
+ pitch = width / ribs
+ outer: list[tuple[float, float]] = []
+ for rib in range(ribs):
+ x = -width / 2 + rib * pitch
+ outer += [
+ (x, 0.0),
+ (x + pitch * 0.25, 0.0),
+ (x + pitch * 0.375, depth),
+ (x + pitch * 0.875, depth),
+ ]
+ outer.append((width / 2, 0.0))
+ inner = [(x, y + sheet) for x, y in outer]
+ m = len(outer)
+ verts = [(x, y, 0.0) for x, y in outer] + [(x, y, 0.0) for x, y in inner]
+ verts += [(x, y, height) for x, y in outer] + [(x, y, height) for x, y in inner]
+ top = 2 * m
+ faces: list[tuple[int, ...]] = []
+ for i in range(m - 1):
+ o0, o1, i0, i1 = i, i + 1, m + i, m + i + 1
+ faces.append((o0, i0, i1, o1)) # bottom strip, normal -Z
+ faces.append((top + o0, top + o1, top + i1, top + i0)) # top strip, normal +Z
+ faces.append((o0, o1, top + o1, top + o0)) # outer face
+ faces.append((i1, i0, top + i0, top + i1)) # inner face
+ faces.append((m + 0, 0, top + 0, top + m)) # left end
+ faces.append((m - 1, 2 * m - 1, top + 2 * m - 1, top + m - 1)) # right end
+ mesh = Mesh()
+ mesh.add(verts, faces)
+ return mesh
+
+
+def _extrude_xy(poly_xy: Sequence[tuple[float, float]], z0: float, z1: float) -> Mesh:
+ n = len(poly_xy)
+ area = sum(
+ x0 * y1 - x1 * y0
+ for (x0, y0), (x1, y1) in zip(poly_xy, [*poly_xy[1:], poly_xy[0]], strict=True)
+ )
+ loop = list(range(n)) if area > 0 else list(reversed(range(n))) # ccw seen from +Z
+ verts = [(x, y, z0) for x, y in poly_xy] + [(x, y, z1) for x, y in poly_xy]
+ faces = [tuple(reversed(loop)), tuple(n + i for i in loop)]
+ for k in range(n):
+ a, b = loop[k], loop[(k + 1) % n]
+ faces.append((a, b, n + b, n + a))
+ mesh = Mesh()
+ mesh.add(verts, faces)
+ return mesh
+
+
+def grating(
+ length_x: float, width_y: float, height: float, bar: float, spacing: float, frame: float
+) -> list[Mesh]:
+ """Bar grating as separate closed bars between two closed side frames (no shared faces)."""
+ parts = [
+ box((-length_x / 2, -width_y / 2, 0.0), (length_x / 2, -width_y / 2 + frame, height)),
+ box((-length_x / 2, width_y / 2 - frame, 0.0), (length_x / 2, width_y / 2, height)),
+ ]
+ inner = width_y - 2 * frame
+ count = max(1, int((inner - bar) // spacing))
+ gap = (inner - count * bar) / (count + 1)
+ y = -width_y / 2 + frame + gap
+ for _ in range(count):
+ parts.append(box((-length_x / 2 + frame, y, 0.0), (length_x / 2 - frame, y + bar, height)))
+ y += bar + gap
+ # End frames close the grating without touching the bars.
+ parts.append(
+ box(
+ (-length_x / 2, -width_y / 2 + frame + gap / 2, 0.0),
+ (-length_x / 2 + frame * 0.9, width_y / 2 - frame - gap / 2, height),
+ )
+ )
+ parts.append(
+ box(
+ (length_x / 2 - frame * 0.9, -width_y / 2 + frame + gap / 2, 0.0),
+ (length_x / 2, width_y / 2 - frame - gap / 2, height),
+ )
+ )
+ return parts
+
+
+def merge(parts: Iterable[Mesh]) -> Mesh:
+ out = Mesh()
+ for part in parts:
+ out.extend(part)
+ return out
+
+
+# --------------------------------------------------------------------------
+# Convex clipping and Voronoi fracture
+
+
+@dataclass
+class Convex:
+ """Convex polyhedron as outward face polygons (each a list of points)."""
+
+ faces: list[list[Vec3]]
+
+ @staticmethod
+ def from_mesh(mesh: Mesh) -> Convex:
+ return Convex([[mesh.verts[i] for i in face] for face in mesh.faces])
+
+ def clip(self, normal: Vec3, offset: float) -> Convex | None:
+ """Keep the part with dot(n, p) <= offset; caps the cut with a new face."""
+ out_faces: list[list[Vec3]] = []
+ cut_points: list[Vec3] = []
+ for face in self.faces:
+ kept: list[Vec3] = []
+ for a, b in zip(face, [*face[1:], face[0]], strict=True):
+ da, db = dot(normal, a) - offset, dot(normal, b) - offset
+ if da <= 1e-12:
+ kept.append(a)
+ if (da < -1e-12 < db) or (db < -1e-12 < da):
+ t = da / (da - db)
+ p = add(a, scale(sub(b, a), t))
+ kept.append(p)
+ cut_points.append(p)
+ elif abs(da) <= 1e-12:
+ cut_points.append(a)
+ kept = _dedupe_loop(kept)
+ if len(kept) >= 3:
+ out_faces.append(kept)
+ if not out_faces:
+ return None
+ # A face already lying in the cut plane is the cap; never add it twice.
+ on_plane = any(
+ all(abs(dot(normal, p) - offset) <= 1e-9 for p in face) for face in out_faces
+ )
+ cap = _order_on_plane(_dedupe_points(cut_points), normal)
+ if len(cap) >= 3 and not on_plane:
+ out_faces.append(cap)
+ result = Convex(out_faces)
+ return result if result.volume() > 1e-12 else None
+
+ def volume(self) -> float:
+ origin = self.faces[0][0]
+ vol = 0.0
+ for face in self.faces:
+ for i in range(1, len(face) - 1):
+ vol += (
+ dot(sub(face[0], origin), cross(sub(face[i], origin), sub(face[i + 1], origin)))
+ / 6.0
+ )
+ return abs(vol)
+
+ def centroid(self) -> Vec3:
+ pts = [p for face in self.faces for p in face]
+ return scale(
+ (sum(p[0] for p in pts), sum(p[1] for p in pts), sum(p[2] for p in pts)), 1.0 / len(pts)
+ )
+
+ def to_mesh(self) -> Mesh:
+ mesh = Mesh()
+ index: dict[tuple, int] = {}
+ for face in self.faces:
+ loop = []
+ for p in face:
+ key = tuple(round(c, 7) for c in p)
+ if key not in index:
+ index[key] = len(mesh.verts)
+ mesh.verts.append(tuple(p))
+ loop.append(index[key])
+ loop = [v for k, v in enumerate(loop) if v != loop[k - 1]]
+ loop = _drop_collinear(loop, mesh.verts)
+ if len(loop) >= 3:
+ mesh.faces.append(tuple(loop))
+ return mesh
+
+
+def _drop_collinear(loop: list[int], verts: list[Vec3]) -> list[int]:
+ """In a convex polyhedron every true vertex is a corner of each face it is on; points in
+ the middle of an edge are clipping leftovers and would make T-junctions."""
+ changed = True
+ while changed and len(loop) > 3:
+ changed = False
+ for k in range(len(loop)):
+ a, b, c = verts[loop[k - 1]], verts[loop[k]], verts[loop[(k + 1) % len(loop)]]
+ if length(cross(sub(b, a), sub(c, b))) < 1e-10 * max(1e-9, length(sub(c, a))):
+ del loop[k]
+ changed = True
+ break
+ return loop
+
+
+def _dedupe_loop(points: list[Vec3]) -> list[Vec3]:
+ out: list[Vec3] = []
+ for p in points:
+ if not out or length(sub(p, out[-1])) > 1e-9:
+ out.append(p)
+ if len(out) > 1 and length(sub(out[0], out[-1])) <= 1e-9:
+ out.pop()
+ return out
+
+
+def _dedupe_points(points: list[Vec3]) -> list[Vec3]:
+ out: list[Vec3] = []
+ for p in points:
+ if all(length(sub(p, q)) > 1e-9 for q in out):
+ out.append(p)
+ return out
+
+
+def _order_on_plane(points: list[Vec3], normal: Vec3) -> list[Vec3]:
+ """Order a convex polygon counter-clockwise around ``normal`` (the outward cap normal)."""
+ if len(points) < 3:
+ return points
+ c = scale(tuple(map(sum, zip(*points, strict=True))), 1.0 / len(points))
+ ref = sub(points[0], c)
+ if length(ref) < EPS:
+ ref = sub(points[1], c)
+ u = scale(ref, 1.0 / length(ref))
+ v = cross(normal, u)
+ return sorted(points, key=lambda p: math.atan2(dot(sub(p, c), v), dot(sub(p, c), u)))
+
+
+@dataclass
+class Chunk:
+ """One fracture chunk: the convex parts of one Voronoi cell."""
+
+ cell: int
+ seed_point: Vec3
+ parts: list[Convex]
+
+ def volume(self) -> float:
+ return sum(p.volume() for p in self.parts)
+
+ def to_mesh(self) -> Mesh:
+ return merge(p.to_mesh() for p in self.parts)
+
+ def size(self) -> float:
+ """Longest bounding-box edge, metres."""
+ lo, hi = self.to_mesh().bounds()
+ return max(hi[i] - lo[i] for i in range(3))
+
+
+def voronoi_points(
+ lo: Vec3, hi: Vec3, count: int, seed: int, *, focus: Vec3 | None = None, spread: float = 0.0
+) -> list[Vec3]:
+ """Seeded cell centres in a box; with ``focus`` half of them cluster around the impact."""
+ rng = random.Random(seed) # noqa: S311 - deterministic art seed, not security
+ points = []
+ for k in range(count):
+ if focus is not None and k % 2 == 0:
+ p = tuple(
+ min(max(focus[i] + rng.uniform(-spread, spread), lo[i]), hi[i]) for i in range(3)
+ )
+ else:
+ p = tuple(rng.uniform(lo[i], hi[i]) for i in range(3))
+ points.append(p)
+ return points
+
+
+def fracture(parts: Sequence[Mesh], points: Sequence[Vec3]) -> list[Chunk]:
+ """Voronoi fracture of convex solid parts by seeded cell centres."""
+ convex_parts = [Convex.from_mesh(p) for p in parts]
+ chunks = []
+ for ci, c in enumerate(points):
+ cell_parts = []
+ for part in convex_parts:
+ piece: Convex | None = part
+ for oi, o in enumerate(points):
+ if oi == ci or piece is None:
+ continue
+ n = sub(o, c)
+ if length(n) < EPS:
+ continue
+ mid = scale(add(o, c), 0.5)
+ piece = piece.clip(n, dot(n, mid))
+ if piece is not None:
+ cell_parts.append(piece)
+ if cell_parts:
+ chunks.append(Chunk(ci, tuple(c), cell_parts))
+ return chunks
diff --git a/art/verse/kit/destructible/pieces.py b/art/verse/kit/destructible/pieces.py
new file mode 100644
index 0000000000..07c2dca7fd
--- /dev/null
+++ b/art/verse/kit/destructible/pieces.py
@@ -0,0 +1,125 @@
+"""Blender builders of the destructible kit (WP06.2, WP06.3, art-pipeline 13).
+
+Registers, for every piece of `catalogue.catalogue()`:
+
+- `SM_<Piece>`: the Intact render mesh (solid, reference thickness).
+- `SM_<Piece>_<State>_<n>`: render mesh of each Holed / Breached variant.
+- `SM_<Piece>_Proxy_Intact`, `SM_<Piece>_Proxy_<State>_<n>`: collision-only
+ proxies, one `UECOL_Box_<nn>` primitive per proxy box (renamed to `UBX_` at
+ export, art-pipeline 3.1); never rendered.
+- `SM_<Piece>_Frac`: the seeded Voronoi chunks, one object per chunk, the
+ input of `verse_pipeline.geometry_collections` (`GC_<Piece>`). Not for glass.
+- `SM_<Piece>_Frac_<State>[_<n>]`: the chunks one state's burst spawns
+ (`GC_<Piece>_<State>[_<n>]`, at most the class's body count), from
+ `catalogue.debris_sets`. The piece's `DebrisSets` list points at them.
+
+The geometry lives in `geometry.py` and `catalogue.py` (pure Python, tested by
+`tests/test_destructible_kit.py`); this module only turns it into objects.
+Every builder runs the builder validator first and fails on any error.
+"""
+
+from __future__ import annotations
+
+from lib import kit
+
+from . import catalogue as cat
+from . import geometry as g
+from . import validate
+
+#: Blender material per penetration material (lib/materials.py).
+MATERIAL = {
+ "sheet_metal": "M_Struct_Gunmetal",
+ "container_wall": "M_Crate_Paint",
+ "cladding_panel": "M_Wall_Charcoal",
+ "glass": "M_Glass_Clear",
+ "catwalk_grating": "M_Floor_Grating",
+ "ceiling_panel": "M_Ceiling_Panel",
+}
+PROXY_MATERIAL = "M_Recess_Dark"
+
+
+def fracture_seed(spec: cat.PieceSpec) -> int:
+ return kit.seed_for("verse.destructible", spec.name)
+
+
+def _object(name: str, mesh: g.Mesh, material: str, **props):
+ return kit.mesh_object(name, mesh.verts, mesh.faces, material, bevel_width=0.0, **props)
+
+
+def _check(spec: cat.PieceSpec, look: cat.StateLook) -> None:
+ ref = spec.thickness if look.state == "Intact" else 0.0
+ report = validate.check_solid(look.shells, spec.thickness_axis, ref)
+ if not report.ok:
+ raise ValueError(f"{spec.name} {look.state} {look.variant}: {'; '.join(report.errors)}")
+
+
+def _render(spec: cat.PieceSpec, look: cat.StateLook, name: str) -> None:
+ _check(spec, look)
+ nav = "walk" if spec.piece_class == "CatwalkSegment" else "block"
+ if spec.piece_class == "CeilingPanel":
+ nav = "none"
+ _object(f"{name}_body", g.merge(look.shells), MATERIAL[spec.material], nav=nav)
+
+
+def _proxy(spec: cat.PieceSpec, look: cat.StateLook, name: str) -> None:
+ for k, (lo, hi) in enumerate(look.proxy_boxes):
+ _object(f"UECOL_Box_{k:02d}", g.box(lo, hi), PROXY_MATERIAL, nav="none")
+ # The proxy mesh itself is the union of its boxes (hidden in game, Verse_ProxyOnly).
+ _object(
+ f"{name}_body",
+ g.merge(g.box(lo, hi) for lo, hi in look.proxy_boxes),
+ PROXY_MATERIAL,
+ nav="none",
+ )
+
+
+def _frac(spec: cat.PieceSpec, name: str) -> None:
+ chunks = spec.fracture_chunks(fracture_seed(spec))
+ for chunk in chunks:
+ _object(
+ f"{name}_Chunk_{chunk.cell:02d}", chunk.to_mesh(), MATERIAL[spec.material], nav="none"
+ )
+
+
+def _debris(spec: cat.PieceSpec, debris: cat.DebrisSet, name: str) -> None:
+ for chunk in debris.chunks:
+ _object(
+ f"{name}_Chunk_{chunk.cell:02d}", chunk.to_mesh(), MATERIAL[spec.material], nav="none"
+ )
+
+
+def _register(spec: cat.PieceSpec) -> None:
+ dims = (spec.width, spec.depth or spec.thickness, spec.height or spec.thickness)
+ for look in spec.looks():
+ render_name = (
+ spec.name if look.state == "Intact" else f"{spec.name}_{look.state}_{look.variant}"
+ )
+ proxy_name = f"{spec.name}_Proxy_{look.proxy_name_suffix}"
+ kit.register_variant(
+ render_name, lambda s=spec, lk=look, n=render_name: _render(s, lk, n), dims=dims
+ )
+ kit.register_variant(
+ proxy_name,
+ lambda s=spec, lk=look, n=proxy_name: _proxy(s, lk, n),
+ dims=dims,
+ nav="none",
+ )
+ if spec.piece_class != "GlassPane":
+ frac_name = f"{spec.name}_Frac"
+ kit.register_variant(
+ frac_name, lambda s=spec, n=frac_name: _frac(s, n), dims=dims, nav="none"
+ )
+ for debris in cat.debris_sets(spec, fracture_seed(spec)):
+ set_name = f"{frac_name}_{debris.name_suffix}"
+ kit.register_variant(
+ set_name,
+ lambda s=spec, d=debris, n=set_name: _debris(s, d, n),
+ dims=dims,
+ nav="none",
+ )
+
+
+def load_all() -> None:
+ """Registers every destructible piece (the export entry calls this per module)."""
+ for spec in cat.catalogue():
+ _register(spec)
diff --git a/art/verse/kit/destructible/tests/test_destructible_kit.py b/art/verse/kit/destructible/tests/test_destructible_kit.py
new file mode 100644
index 0000000000..2ee07e3444
--- /dev/null
+++ b/art/verse/kit/destructible/tests/test_destructible_kit.py
@@ -0,0 +1,181 @@
+"""WP06 destructible kit: geometry rule, variants, proxies and fracture (pure Python).
+
+Run: python -m pytest art/verse/kit/destructible/tests -q
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+ART = Path(__file__).resolve().parents[3] # art/verse
+sys.path.insert(0, str(ART))
+
+from kit.destructible import catalogue as cat # noqa: E402
+from kit.destructible import geometry as g # noqa: E402
+from kit.destructible import validate as v # noqa: E402
+
+PIECES = cat.catalogue()
+IDS = [p.name for p in PIECES]
+
+
+def test_six_classes_and_names():
+ assert {p.piece_class for p in PIECES} == {
+ "WallPanel",
+ "CladdingWall",
+ "ContainerWall",
+ "GlassPane",
+ "CatwalkSegment",
+ "CeilingPanel",
+ }
+ assert {"SM_WallPanel_120", "SM_WallPanel_240", "SM_WallPanel_480"} <= set(IDS)
+ for p in PIECES:
+ assert p.name.startswith("SM_") and len(p.name) <= 64
+
+
[email protected]("spec", PIECES, ids=IDS)
+def test_every_state_is_a_closed_solid_of_reference_thickness(spec):
+ for look in spec.looks():
+ ref = spec.thickness if look.state == "Intact" else 0.0
+ report = v.check_solid(look.shells, spec.thickness_axis, ref)
+ assert report.ok, (look.state, look.variant, report.errors)
+ if ref:
+ assert abs(report.thickness_m - spec.thickness) <= spec.thickness * 0.10
+
+
+ "spec", [p for p in PIECES if p.wall_like], ids=[p.name for p in PIECES if p.wall_like]
+)
+def test_walls_ship_holed_and_breached_variants(spec):
+ looks = spec.looks()
+ holed = [lk for lk in looks if lk.state == "Holed"]
+ breached = [lk for lk in looks if lk.state == "Breached"]
+ assert 1 <= len(holed) <= 4 and 1 <= len(breached) <= 4
+ # Holes are to see and shoot through, never to walk through.
+ for openings in spec.holed:
+ for x0, z0, x1, z1 in openings:
+ assert x1 - x0 < 0.9 or z1 - z0 < 1.2
+ standing = spec.breached[0][0]
+ assert (
+ standing[2] - standing[0] >= 0.9 and standing[3] - standing[1] >= 2.0 and standing[1] == 0.0
+ )
+ low = spec.breached[spec.mantle_variant][0]
+ assert low[1] > 0.0 and low[3] <= 1.2, "the low breach is a mantle opening"
+ # Variant centroids differ, so the server can pick the nearest one.
+ cents = {lk.centroid for lk in holed}
+ assert len(cents) == len(holed)
+
+
[email protected]("spec", PIECES, ids=IDS)
+def test_proxies_are_simple_and_match_the_material(spec):
+ for look in spec.looks():
+ assert 1 <= len(look.proxy_boxes) <= 16, "art-pipeline 5: at most 16 primitives"
+ for lo, hi in look.proxy_boxes:
+ assert all(hi[i] > lo[i] for i in range(3))
+ if spec.wall_like:
+ # The traced thickness through a wall proxy is the reference thickness.
+ assert hi[1] - lo[1] == pytest.approx(spec.thickness, rel=1e-6)
+
+
+ "spec", [p for p in PIECES if p.wall_like], ids=[p.name for p in PIECES if p.wall_like]
+)
+def test_proxy_openings_match_the_render_openings(spec):
+ # A ray straight through the opening centre hits no proxy box; one through solid wall does.
+ for look in spec.looks():
+ cx, _, cz = look.centroid
+
+ def blocked(x, z, boxes=look.proxy_boxes):
+ return any(lo[0] <= x <= hi[0] and lo[2] <= z <= hi[2] for lo, hi in boxes)
+
+ if look.state == "Intact":
+ assert blocked(0.0, spec.height / 2)
+ else:
+ assert not blocked(cx, cz), (look.state, look.variant)
+
+
+ "spec",
+ [p for p in PIECES if p.piece_class != "GlassPane"],
+ ids=[p.name for p in PIECES if p.piece_class != "GlassPane"],
+)
+def test_fracture_is_seeded_closed_and_within_budget(spec):
+ seed = 0x0600 + len(spec.name)
+ a = spec.fracture_chunks(seed)
+ b = spec.fracture_chunks(seed)
+ assert a, "a geometry collection needs at least one chunk"
+ assert len(a) <= cat.MAX_BODIES
+ assert [c.to_mesh().verts for c in a] == [c.to_mesh().verts for c in b], (
+ "same seed, same chunks"
+ )
+ for chunk in a:
+ assert chunk.size() >= cat.MIN_RIGID_M
+ for part in chunk.parts:
+ assert v.check_closed(part.to_mesh()).ok
+ if spec.fracture_cells > 1:
+ assert [c.seed_point for c in spec.fracture_chunks(seed + 1)] != [c.seed_point for c in a]
+
+
+ "spec",
+ [p for p in PIECES if p.piece_class != "GlassPane"],
+ ids=[p.name for p in PIECES if p.piece_class != "GlassPane"],
+)
+def test_debris_sets_fit_the_body_budget_and_their_openings(spec):
+ seed = 0x0600 + len(spec.name)
+ sets = cat.debris_sets(spec, seed)
+ budget = cat.DEBRIS_BODIES[spec.material]
+ assert {s.state for s in sets} == set(budget), "one set per state that throws rigid debris"
+ full = spec.fracture_chunks(seed)
+ for debris in sets:
+ assert 1 <= len(debris.chunks) <= budget[debris.state] <= cat.MAX_BODIES
+ cells = {c.cell for c in full}
+ assert {c.cell for c in debris.chunks} <= cells, "a set is a subset of the fracture"
+ if debris.state in ("Holed", "Breached"):
+ openings = (spec.holed if debris.state == "Holed" else spec.breached)[debris.variant]
+ inside = [
+ c
+ for c in debris.chunks
+ if cat._in_openings(cat._chunk_centre(c), openings, cat.OPENING_MARGIN_M)
+ ]
+ assert inside or len(debris.chunks) == 1, "only opening chunks fly from a standing wall"
+ assert len(debris.chunks) < len(full) or len(full) <= budget[debris.state]
+ holed = [s for s in sets if s.state == "Holed"]
+ assert len(holed) == (len(spec.holed) if "Holed" in budget else 0)
+
+
+def test_glass_has_no_rigid_debris():
+ glass = [p for p in PIECES if p.piece_class == "GlassPane"]
+ assert glass
+ for spec in glass:
+ assert cat.debris_sets(spec, 1) == []
+
+
+def test_fracture_conserves_volume():
+ spec = cat.by_name("SM_WallPanel_240")
+ whole = g.Convex.from_mesh(spec.render_shells([])[0]).volume()
+ points = g.voronoi_points((-1.2, 0.0, 0.0), (1.2, 0.003, 2.7), 24, 7)
+ chunks = g.fracture(spec.render_shells([]), points)
+ assert sum(c.volume() for c in chunks) == pytest.approx(whole, rel=1e-6)
+
+
+def test_validator_rejects_double_planes_and_open_shells():
+ double = g.Mesh()
+ double.add([(-1, 0, 0), (1, 0, 0), (1, 0, 2), (-1, 0, 2)], [(0, 1, 2, 3)])
+ double.add([(-1, 0.003, 0), (-1, 0.003, 2), (1, 0.003, 2), (1, 0.003, 0)], [(0, 1, 2, 3)])
+ report = v.check_solid([double], (0, 1, 0), 0.003)
+ assert not report.ok and "watertight" in report.errors[0]
+ thick = g.box((-1, 0, 0), (1, 0.1, 2))
+ assert not v.check_solid([thick], (0, 1, 0), 0.003).ok, "10 cm is not sheet metal"
+ open_box = g.box((-1, 0, 0), (1, 0.003, 2))
+ open_box.faces.pop()
+ assert not v.check_closed(open_box).ok
+
+
+def test_slab_with_openings_is_one_manifold_shell():
+ slab = g.slab_with_openings(2.4, 2.7, 0.0, 0.04, [(-0.5, 0.0, 0.5, 2.05), (0.7, 1.0, 1.0, 1.3)])
+ assert v.check_closed(slab).ok
+ with pytest.raises(ValueError):
+ g.slab_with_openings(2.4, 2.7, 0.0, 0.04, [(-2.0, 0.0, 0.5, 1.0)])
diff --git a/art/verse/kit/destructible/validate.py b/art/verse/kit/destructible/validate.py
new file mode 100644
index 0000000000..313b1ecbe6
--- /dev/null
+++ b/art/verse/kit/destructible/validate.py
@@ -0,0 +1,150 @@
+"""Builder-side validator of destructible pieces (contracts/destruction.md 9).
+
+The same checks as the editor validator `UVerseDestructibleValidator`
+(`unreal/Verse/Source/VerseDestruction/Private/Validation/`): every shell is
+closed and manifold after welding coincident positions, no zero-area faces,
+and the median inward ray distance from faces facing along the piece's
+thickness axis matches the material's reference thickness within 10 %.
+Pure Python; the cook step and pytest run it before any export.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+
+from .geometry import Mesh, Vec3, cross, dot, length, scale, sub
+
+TOLERANCE = 0.10
+
+
+@dataclass
+class Report:
+ errors: list[str] = field(default_factory=list)
+ thickness_m: float = 0.0
+
+ @property
+ def ok(self) -> bool:
+ return not self.errors
+
+
+def _weld(mesh: Mesh) -> list[int]:
+ grid: dict[tuple[int, int, int], int] = {}
+ out = []
+ for v in mesh.verts:
+ key = (round(v[0] * 1e5), round(v[1] * 1e5), round(v[2] * 1e5)) # 0.01 mm
+ out.append(grid.setdefault(key, len(grid)))
+ return out
+
+
+def check_closed(mesh: Mesh) -> Report:
+ report = Report()
+ if not mesh.faces:
+ report.errors.append("no faces")
+ return report
+ weld = _weld(mesh)
+ directed: Counter[tuple[int, int]] = Counter()
+ degenerate = 0
+ for a, b, c in mesh.triangles():
+ va, vb, vc = weld[a], weld[b], weld[c]
+ area = length(cross(sub(mesh.verts[b], mesh.verts[a]), sub(mesh.verts[c], mesh.verts[a])))
+ if len({va, vb, vc}) < 3 or area < 1e-12:
+ degenerate += 1
+ continue
+ for e in ((va, vb), (vb, vc), (vc, va)):
+ directed[e] += 1
+ if degenerate:
+ report.errors.append(f"{degenerate} zero-area faces")
+ open_edges = sum(1 for (a, b) in directed if (b, a) not in directed)
+ bad = sum(1 for (a, b), n in directed.items() if n > 1 or directed.get((b, a), n) != n)
+ if open_edges:
+ report.errors.append(
+ f"not watertight: {open_edges} open edges (one-sided shell or double plane)"
+ )
+ if bad:
+ report.errors.append(f"not manifold: {bad} edges shared inconsistently")
+ return report
+
+
+def _ray_triangle(origin: Vec3, d: Vec3, a: Vec3, b: Vec3, c: Vec3) -> float | None:
+ e1, e2 = sub(b, a), sub(c, a)
+ p = cross(d, e2)
+ det = dot(e1, p)
+ if abs(det) < 1e-15:
+ return None
+ inv = 1.0 / det
+ s = sub(origin, a)
+ u = dot(s, p) * inv
+ if u < -1e-9 or u > 1 + 1e-9:
+ return None
+ q = cross(s, e1)
+ v = dot(d, q) * inv
+ if v < -1e-9 or u + v > 1 + 1e-9:
+ return None
+ t = dot(e2, q) * inv
+ return t if t > 1e-6 else None
+
+
+def measure_thickness(mesh: Mesh, axis: Vec3) -> float:
+ """Area-weighted median inward ray distance from faces facing along +-axis, metres."""
+ tris = [(mesh.verts[a], mesh.verts[b], mesh.verts[c]) for a, b, c in mesh.triangles()]
+ samples: list[tuple[float, float]] = []
+ for ti, (a, b, c) in enumerate(tris):
+ n = cross(sub(b, a), sub(c, a))
+ area = length(n) / 2
+ if area < 1e-12:
+ continue
+ n = scale(n, 1.0 / (2 * area))
+ if abs(dot(n, axis)) < 0.95:
+ continue
+ centroid = scale((a[0] + b[0] + c[0], a[1] + b[1] + c[1], a[2] + b[2] + c[2]), 1 / 3)
+ best = None
+ for sign in (-1.0, 1.0):
+ d = scale(n, sign)
+ origin = (
+ centroid[0] + d[0] * 1e-5,
+ centroid[1] + d[1] * 1e-5,
+ centroid[2] + d[2] * 1e-5,
+ )
+ for tj, (p, q, r) in enumerate(tris):
+ if tj == ti:
+ continue
+ t = _ray_triangle(origin, d, p, q, r)
+ if t is not None and (best is None or t < best):
+ best = t
+ if best is not None:
+ best += 1e-5
+ break
+ if best is not None:
+ samples.append((best, area))
+ if not samples:
+ return 0.0
+ samples.sort()
+ total = sum(w for _, w in samples)
+ acc = 0.0
+ for d, w in samples:
+ acc += w
+ if acc >= total / 2:
+ return d
+ return samples[-1][0]
+
+
+def check_solid(shells: Sequence[Mesh], axis: Vec3, ref_thickness_m: float) -> Report:
+ """Every shell closed; the whole piece's thickness within 10 % of the reference (0 = skip)."""
+ report = Report()
+ for k, shell in enumerate(shells):
+ for err in check_closed(shell).errors:
+ report.errors.append(f"shell {k}: {err}")
+ if ref_thickness_m > 0:
+ from .geometry import merge
+
+ report.thickness_m = measure_thickness(merge(shells), axis)
+ if report.thickness_m <= 0:
+ report.errors.append("thickness not measurable (no inward hit)")
+ elif abs(report.thickness_m - ref_thickness_m) > ref_thickness_m * TOLERANCE:
+ report.errors.append(
+ f"thickness {report.thickness_m * 100:.3f} cm, the material wants "
+ f"{ref_thickness_m * 100:.3f} cm +-10 %"
+ )
+ return report
diff --git a/unreal/Verse/Data/destruction/tuning.json b/unreal/Verse/Data/destruction/tuning.json
new file mode 100644
index 0000000000..6cc5b0658c
--- /dev/null
+++ b/unreal/Verse/Data/destruction/tuning.json
@@ -0,0 +1,38 @@
+{
+ "schema": "verse.destruction.tuning/1",
+ "owner": "WP06",
+ "status": "propose-only: the contract values of DA_DestructionTuning (destruction.md 3.2, 7, 10) plus WP06 start values; retuned only through the contract change rule and the balance harness",
+ "classes": {
+ "WallPanel": {"material": "sheet_metal", "max_hp": 200, "holed_at_or_below_hp": 100, "breached_by_charge": true, "repair_s": 8},
+ "CladdingWall": {"material": "cladding_panel", "max_hp": 250, "holed_at_or_below_hp": 125, "breached_by_charge": true, "repair_s": 8},
+ "ContainerWall": {"material": "container_wall", "max_hp": 300, "holed_at_or_below_hp": 150, "breached_by_charge": true, "repair_s": 8},
+ "GlassPane": {"material": "glass", "max_hp": 20, "destroyed_at_zero_hp": true, "destroyed_by_charge": true, "destroyed_by_melee_when_damaged": true, "repair_s": 4},
+ "CatwalkSegment": {"material": "catwalk_grating", "max_hp": 0, "destroyed_by_charge": true, "repair_s": 10},
+ "CeilingPanel": {"material": "ceiling_panel", "max_hp": 60, "destroyed_at_zero_hp": true, "destroyed_by_charge": true, "repair_s": 5}
+ },
+ "breach_side_radius_cm": 150,
+ "holes": {"per_piece": 24, "per_arena": 512, "glowing_max": 128, "glow_tau_s": 1.2, "glow_end_s": 4.0},
+ "repair": {"delay_s": 60, "max_active_drones": 3, "drone_hp": 30, "encroach_margin_cm": 10, "encroach_recheck_s": 0.5},
+ "nav": {"dirty_margin_cm": 50, "max_tiles_in_flight": 4, "tile_cm": 320},
+ "budget": {
+ "debris_bodies_high": 400, "debris_bodies_low": 150, "bodies_per_fracture": 40, "min_rigid_fragment_cm": 5,
+ "debris_sleep_s": 3, "debris_despawn_high_s": 10, "debris_despawn_low_s": 6, "debris_fade_s": 0.3,
+ "geometry_collection_actors": 32, "fracture_events_per_s": 64
+ },
+ "start_values": {
+ "drone_speed_cm_s": 600,
+ "drone_noise_interval_ms": 1000,
+ "impulse_ns": {"bolt": 20, "melee": 40, "breach": 1500},
+ "strain_radius_cm": {"bolt": 20, "melee": 30},
+ "debris_bodies": {
+ "MetalShards": {"Holed": 12, "Breached": 32},
+ "CorrugatedChunks": {"Holed": 14, "Breached": 36},
+ "PanelChunks": {"Holed": 16, "Breached": 40},
+ "GratingTwisted": {"Destroyed": 6},
+ "CeilingTile": {"Destroyed": 1},
+ "GlassShards": {},
+ "DustChips": {},
+ "SparksOnly": {}
+ }
+ }
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisBudget.cpp b/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisBudget.cpp
new file mode 100644
index 0000000000..43df190962
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisBudget.cpp
@@ -0,0 +1,189 @@
+#include "Debris/VerseDebrisBudget.h"
+
+FVerseDebrisBudget::FConfig FVerseDebrisBudget::FConfig::High()
+{
+ return FConfig();
+}
+
+FVerseDebrisBudget::FConfig FVerseDebrisBudget::FConfig::Low()
+{
+ FConfig Config;
+ Config.MaxBodies = 150;
+ Config.DespawnS = 6.f;
+ return Config;
+}
+
+FVerseDebrisBudget::FVerseDebrisBudget(const FConfig& InConfig)
+ : Config(InConfig)
+{
+}
+
+int32 FVerseDebrisBudget::DesiredBodies(EVerseDebrisType Type, EVersePieceState ToState)
+{
+ // WP06 start values (unreal/Verse/Data/destruction/tuning.json "debris_bodies"). Damaged is
+ // scorch and sparks only; Niagara-only types never ask for rigid bodies.
+ if (ToState == EVersePieceState::Damaged || ToState == EVersePieceState::Repairing || ToState == EVersePieceState::Intact)
+ {
+ return 0;
+ }
+ switch (Type)
+ {
+ case EVerseDebrisType::MetalShards:
+ return ToState == EVersePieceState::Holed ? 12 : 32;
+ case EVerseDebrisType::CorrugatedChunks:
+ return ToState == EVersePieceState::Holed ? 14 : 36;
+ case EVerseDebrisType::PanelChunks:
+ return ToState == EVersePieceState::Holed ? 16 : 40;
+ case EVerseDebrisType::GratingTwisted:
+ return 6;
+ case EVerseDebrisType::CeilingTile:
+ return 1;
+ case EVerseDebrisType::GlassShards:
+ case EVerseDebrisType::DustChips:
+ case EVerseDebrisType::SparksOnly:
+ return 0;
+ }
+ return 0;
+}
+
+bool FVerseDebrisBudget::HasNiagara(EVerseDebrisType Type)
+{
+ return Type != EVerseDebrisType::GratingTwisted;
+}
+
+int32 FVerseDebrisBudget::ActiveBodies() const
+{
+ int32 Sum = 0;
+ for (const FBurst& Burst : Bursts)
+ {
+ if (!Burst.bFading)
+ {
+ Sum += Burst.Bodies;
+ }
+ }
+ return Sum;
+}
+
+int32 FVerseDebrisBudget::AliveActors() const
+{
+ int32 Count = 0;
+ for (const FBurst& Burst : Bursts)
+ {
+ Count += Burst.Bodies > 0 ? 1 : 0;
+ }
+ return Count;
+}
+
+void FVerseDebrisBudget::EvictOldest(double NowS, TArray<int32>& OutEvicted)
+{
+ for (FBurst& Burst : Bursts) // Bursts are kept in spawn order: the first live one is the oldest.
+ {
+ if (!Burst.bFading && Burst.Bodies > 0)
+ {
+ Burst.bFading = true;
+ Burst.FadeStartS = NowS;
+ OutEvicted.Add(Burst.Id);
+ return;
+ }
+ }
+}
+
+FVerseDebrisBudget::FGrant FVerseDebrisBudget::Request(const FRequest& Request, double NowS)
+{
+ FGrant Grant;
+ Grant.bNiagara = HasNiagara(Request.Type) && Request.ToState != EVersePieceState::Intact;
+ const int32 Desired = DesiredBodies(Request.Type, Request.ToState);
+ const int32 Bodies = FMath::Clamp(Desired, 0, FMath::Min(Config.MaxBodiesPerFracture, Config.MaxBodies));
+ if (Bodies <= 0)
+ {
+ return Grant;
+ }
+ // Oldest bursts fade until the new one fits the body cap (fading bodies no longer count).
+ while (ActiveBodies() + Bodies > Config.MaxBodies)
+ {
+ const int32 Before = Grant.Evicted.Num();
+ EvictOldest(NowS, Grant.Evicted);
+ if (Grant.Evicted.Num() == Before)
+ {
+ break;
+ }
+ }
+ // A fading actor still holds a pool slot: when the pool is full, the oldest actor goes at once.
+ while (AliveActors() + 1 > Config.MaxGeometryCollectionActors)
+ {
+ const int32 Oldest = Bursts.IndexOfByPredicate([](const FBurst& Burst) { return Burst.Bodies > 0; });
+ if (Oldest == INDEX_NONE)
+ {
+ break;
+ }
+ Grant.Removed.Add(Bursts[Oldest].Id);
+ Bursts.RemoveAt(Oldest);
+ }
+ FBurst Burst;
+ Burst.Id = NextId++;
+ Burst.PieceIndex = Request.PieceIndex;
+ Burst.Bodies = Bodies;
+ Burst.SpawnS = NowS;
+ Bursts.Add(Burst);
+ Grant.BurstId = Burst.Id;
+ Grant.Bodies = Bodies;
+ PeakBodies = FMath::Max(PeakBodies, ActiveBodies());
+ PeakActors = FMath::Max(PeakActors, AliveActors());
+ PeakPerFracture = FMath::Max(PeakPerFracture, Bodies);
+ return Grant;
+}
+
+void FVerseDebrisBudget::Commit(int32 BurstId, int32 RealBodies)
+{
+ const int32 Index = Bursts.IndexOfByPredicate([BurstId](const FBurst& Burst) { return Burst.Id == BurstId; });
+ if (Index == INDEX_NONE)
+ {
+ return;
+ }
+ FBurst& Burst = Bursts[Index];
+ ensureMsgf(RealBodies <= Burst.Bodies, TEXT("debris burst %d simulates %d bodies, granted %d"), BurstId, RealBodies, Burst.Bodies);
+ Burst.Bodies = FMath::Clamp(RealBodies, 0, Burst.Bodies);
+ if (Burst.Bodies == 0)
+ {
+ Bursts.RemoveAt(Index);
+ return;
+ }
+ PeakRealBodies = FMath::Max(PeakRealBodies, ActiveBodies());
+ PeakRealActors = FMath::Max(PeakRealActors, AliveActors());
+ PeakRealPerFracture = FMath::Max(PeakRealPerFracture, Burst.Bodies);
+}
+
+TArray<int32> FVerseDebrisBudget::Tick(double NowS)
+{
+ TArray<int32> Removed;
+ for (int32 Index = Bursts.Num() - 1; Index >= 0; --Index)
+ {
+ FBurst& Burst = Bursts[Index];
+ if (!Burst.bAsleep && NowS - Burst.SpawnS >= Config.SleepS)
+ {
+ Burst.bAsleep = true;
+ }
+ if (!Burst.bFading && NowS - Burst.SpawnS >= Config.DespawnS)
+ {
+ Burst.bFading = true;
+ Burst.FadeStartS = NowS;
+ }
+ if (Burst.bFading && NowS - Burst.FadeStartS >= Config.FadeS)
+ {
+ Removed.Add(Burst.Id);
+ Bursts.RemoveAt(Index);
+ }
+ }
+ return Removed;
+}
+
+TArray<int32> FVerseDebrisBudget::PurgeAll()
+{
+ TArray<int32> Removed;
+ for (const FBurst& Burst : Bursts)
+ {
+ Removed.Add(Burst.Id);
+ }
+ Bursts.Reset();
+ return Removed;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisSubsystem.cpp b/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisSubsystem.cpp
new file mode 100644
index 0000000000..f03f3b74fb
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Debris/VerseDebrisSubsystem.cpp
@@ -0,0 +1,309 @@
+#include "Debris/VerseDebrisSubsystem.h"
+
+#include "Destruction/VersePenetrationTable.h"
+#include "Engine/AssetManager.h"
+#include "Engine/StreamableManager.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GeometryCollection/GeometryCollection.h"
+#include "GeometryCollection/GeometryCollectionActor.h"
+#include "GeometryCollection/GeometryCollectionComponent.h"
+#include "GeometryCollection/GeometryCollectionObject.h"
+#include "Misc/App.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "VerseCollision.h"
+#include "VerseLog.h"
+#include "VerseRng.h"
+
+bool UVerseDebrisSubsystem::ShouldSpawnDebris(const UWorld& World)
+{
+ return World.GetNetMode() != NM_DedicatedServer && FApp::CanEverRender() && !IsRunningDedicatedServer();
+}
+
+bool UVerseDebrisSubsystem::ShouldCreateSubsystem(UObject* Outer) const
+{
+ const UWorld* World = Cast<UWorld>(Outer);
+ return World && World->IsGameWorld() && Super::ShouldCreateSubsystem(Outer);
+}
+
+int32 UVerseDebrisSubsystem::PickSet(TConstArrayView<int32> SetBodies, int32 Grant)
+{
+ int32 Best = INDEX_NONE;
+ for (int32 Index = 0; Index < SetBodies.Num(); ++Index)
+ {
+ const int32 Bodies = SetBodies[Index];
+ if (Bodies > 0 && Bodies <= Grant && (Best == INDEX_NONE || Bodies > SetBodies[Best]))
+ {
+ Best = Index;
+ }
+ }
+ return Best;
+}
+
+int32 UVerseDebrisSubsystem::CountBodies(const UGeometryCollection& Collection)
+{
+ return Collection.NumElements(FGeometryCollection::GeometryGroup);
+}
+
+void UVerseDebrisSubsystem::OnWorldBeginPlay(UWorld& InWorld)
+{
+ Super::OnWorldBeginPlay(InWorld);
+ bEnabled = ShouldSpawnDebris(InWorld);
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(&InWorld))
+ {
+ FractureHandle = Hub->OnFracture.AddUObject(this, &UVerseDebrisSubsystem::HandleFracture);
+ }
+}
+
+void UVerseDebrisSubsystem::Deinitialize()
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(GetWorld()))
+ {
+ Hub->OnFracture.Remove(FractureHandle);
+ }
+ for (const int32 Id : Budget.PurgeAll())
+ {
+ ReleaseBurst(Id);
+ }
+ for (AGeometryCollectionActor* Actor : Pool)
+ {
+ if (IsValid(Actor))
+ {
+ Actor->Destroy();
+ }
+ }
+ Pool.Reset();
+ PoolSize = 0;
+ for (const TSharedPtr<FStreamableHandle>& Handle : Preloads)
+ {
+ if (Handle.IsValid())
+ {
+ Handle->CancelHandle();
+ }
+ }
+ Preloads.Reset();
+ Super::Deinitialize();
+}
+
+void UVerseDebrisSubsystem::SetLowPreset(bool bLow)
+{
+ Budget = FVerseDebrisBudget(bLow ? FVerseDebrisBudget::FConfig::Low() : FVerseDebrisBudget::FConfig::High());
+}
+
+TStatId UVerseDebrisSubsystem::GetStatId() const
+{
+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseDebrisSubsystem, STATGROUP_Tickables);
+}
+
+void UVerseDebrisSubsystem::PreloadPiece(const AVerseDestructible& Piece)
+{
+ const UWorld* World = GetWorld();
+ if (!World || !ShouldSpawnDebris(*World) || Piece.DebrisSets.Num() == 0)
+ {
+ return; // servers and headless runs never load debris
+ }
+ TArray<FSoftObjectPath> Paths;
+ for (const FVersePieceDebrisSet& Set : Piece.DebrisSets)
+ {
+ if (!Set.Collection.IsNull() && !Set.Collection.IsValid())
+ {
+ Paths.AddUnique(Set.Collection.ToSoftObjectPath());
+ }
+ }
+ if (Paths.Num() > 0)
+ {
+ Preloads.Add(UAssetManager::GetStreamableManager().RequestAsyncLoad(MoveTemp(Paths)));
+ }
+}
+
+void UVerseDebrisSubsystem::HandleFracture(const FVerseFractureEvent& Event)
+{
+ if (!bEnabled)
+ {
+ return; // DR3: no debris on a dedicated server or without a renderer
+ }
+ const UWorld* World = GetWorld();
+ const double NowS = World ? World->GetTimeSeconds() : 0.0;
+ if (Event.Cause == EVerseFractureCause::Reset)
+ {
+ for (const int32 Id : Budget.PurgeAll())
+ {
+ ReleaseBurst(Id);
+ }
+ return;
+ }
+ if (Event.Cause == EVerseFractureCause::Repair || Event.ToState == EVersePieceState::Repairing || Event.ToState == EVersePieceState::Intact)
+ {
+ return;
+ }
+ const AVerseDestructionManager* Manager = AVerseDestructionManager::Get(this);
+ if (!Manager || !Manager->GetSim().IsValidPiece(Event.PieceIndex))
+ {
+ return;
+ }
+ const FVersePieceDef& Def = Manager->GetSim().GetDef(Event.PieceIndex);
+ const FVersePenetrationRow* Row = GetDefault<UVersePenetrationTable>()->FindRow(uint8(Def.Material));
+ FVerseDebrisBudget::FRequest Request;
+ Request.PieceIndex = Event.PieceIndex;
+ Request.Type = Row ? Row->DebrisType : EVerseDebrisType::SparksOnly;
+ Request.ToState = Event.ToState;
+ const FVerseDebrisBudget::FGrant Grant = Budget.Request(Request, NowS);
+ for (const int32 Id : Grant.Removed)
+ {
+ ReleaseBurst(Id);
+ }
+ for (const int32 Id : Grant.Evicted)
+ {
+ if (const TWeakObjectPtr<AGeometryCollectionActor>* Actor = BurstActors.Find(Id))
+ {
+ if (UGeometryCollectionComponent* Component = Actor->IsValid() ? (*Actor)->GetGeometryCollectionComponent() : nullptr)
+ {
+ Component->PutAllRigidBodiesToSleep(); // fading: no longer simulated
+ }
+ }
+ }
+ if (Grant.BurstId != 0)
+ {
+ const int32 Real = SpawnBurst(Grant.BurstId, Event, Grant.Bodies);
+ // The budget now counts the bodies the component really simulates (0 frees the reservation).
+ Budget.Commit(Grant.BurstId, Real);
+ SpawnedBursts += Real > 0 ? 1 : 0;
+ }
+ // Niagara shards, dust and sparks belong to the look of the class (NS_*, not authored yet).
+}
+
+AGeometryCollectionActor* UVerseDebrisSubsystem::AcquireActor()
+{
+ while (Pool.Num() > 0)
+ {
+ AGeometryCollectionActor* Actor = Pool.Pop(EAllowShrinking::No);
+ if (IsValid(Actor))
+ {
+ return Actor;
+ }
+ --PoolSize;
+ }
+ UWorld* World = GetWorld();
+ if (!World || PoolSize >= Budget.GetConfig().MaxGeometryCollectionActors)
+ {
+ return nullptr;
+ }
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ Params.ObjectFlags |= RF_Transient;
+ AGeometryCollectionActor* Actor = World->SpawnActor<AGeometryCollectionActor>(AGeometryCollectionActor::StaticClass(), FTransform::Identity, Params);
+ if (Actor)
+ {
+ ++PoolSize;
+ }
+ return Actor;
+}
+
+int32 UVerseDebrisSubsystem::SpawnBurst(int32 BurstId, const FVerseFractureEvent& Event, int32 Grant)
+{
+ const AVerseDestructionManager* Manager = AVerseDestructionManager::Get(this);
+ AVerseDestructible* Piece = Manager ? Manager->GetPieceActor(Event.PieceIndex) : nullptr;
+ if (!Piece)
+ {
+ return 0;
+ }
+ // The authored set for this state with the most chunks that fit the grant. Only loaded sets
+ // count: a set still streaming in is skipped rather than loaded on the game thread.
+ const TArray<const FVersePieceDebrisSet*> Sets = Piece->FindDebrisSets(Event.ToState, Event.Variant);
+ TArray<int32> Bodies;
+ TArray<UGeometryCollection*> Loaded;
+ for (const FVersePieceDebrisSet* Set : Sets)
+ {
+ UGeometryCollection* Collection = Set->Collection.Get();
+ Loaded.Add(Collection);
+ Bodies.Add(Collection ? CountBodies(*Collection) : 0);
+ }
+ const int32 Pick = PickSet(Bodies, Grant);
+ if (Pick == INDEX_NONE)
+ {
+ return 0;
+ }
+ AGeometryCollectionActor* Actor = AcquireActor();
+ UGeometryCollectionComponent* Component = Actor ? Actor->GetGeometryCollectionComponent() : nullptr;
+ if (!Component)
+ {
+ if (Actor)
+ {
+ Pool.Add(Actor);
+ }
+ return 0;
+ }
+ Actor->SetActorTransform(Piece->GetActorTransform());
+ Component->UnregisterComponent();
+ Component->SetRestCollection(Loaded[Pick]);
+ Component->SetCollisionProfileName(VerseCollision::Profile::Debris);
+ Component->SetCanEverAffectNavigation(false);
+ Component->SetIsReplicated(false); // GC replication off (architecture 4)
+ Component->SetSimulatePhysics(true);
+ Component->RegisterComponent();
+ Actor->SetActorHiddenInGame(false);
+ Actor->SetActorEnableCollision(true);
+ const int32 Real = Component->GetRestCollection() ? CountBodies(*Component->GetRestCollection()) : 0;
+ if (Real <= 0 || Real > Grant)
+ {
+ UE_LOG(LogVerseDestruction, Error, TEXT("debris set of piece %u has %d bodies, the grant is %d; not spawned"), Event.PieceIndex, Real, Grant);
+ BurstActors.Add(BurstId, Actor);
+ ReleaseBurst(BurstId);
+ return 0;
+ }
+ // Same location, impulse and seed on every client; the crack pattern may still differ (architecture 4).
+ FVerseRng Rng(Event.Seed);
+ const FVector Local = FVector(Event.Location[0], Event.Location[1], Event.Location[2]) / 10.0;
+ const FVector Origin = Piece->GetActorTransform().TransformPosition(Local) + Rng.UnitVector() * 2.0;
+ const FVector Impulse = FVector(Event.Impulse[0], Event.Impulse[1], Event.Impulse[2]) * 0.1; // N s
+ Component->AddRadialImpulse(Origin, FMath::Max<float>(Event.Radius, 10.f), float(Impulse.Size()) / float(Real), RIF_Linear, true);
+ BurstActors.Add(BurstId, Actor);
+ return Real;
+}
+
+void UVerseDebrisSubsystem::ReleaseBurst(int32 BurstId)
+{
+ TWeakObjectPtr<AGeometryCollectionActor> Actor;
+ if (!BurstActors.RemoveAndCopyValue(BurstId, Actor) || !Actor.IsValid())
+ {
+ return;
+ }
+ // Back to the pool: hidden, no collision, not simulating.
+ if (UGeometryCollectionComponent* Component = Actor->GetGeometryCollectionComponent())
+ {
+ Component->SetSimulatePhysics(false);
+ }
+ Actor->SetActorHiddenInGame(true);
+ Actor->SetActorEnableCollision(false);
+ Pool.Add(Actor.Get());
+}
+
+void UVerseDebrisSubsystem::Tick(float DeltaTime)
+{
+ Super::Tick(DeltaTime);
+ const UWorld* World = GetWorld();
+ if (!World || BurstActors.Num() == 0)
+ {
+ Budget.Tick(World ? World->GetTimeSeconds() : 0.0);
+ return;
+ }
+ for (const FVerseDebrisBudget::FBurst& Burst : Budget.GetBursts())
+ {
+ if (Burst.bAsleep)
+ {
+ if (const TWeakObjectPtr<AGeometryCollectionActor>* Actor = BurstActors.Find(Burst.Id))
+ {
+ UGeometryCollectionComponent* Component = Actor->IsValid() ? (*Actor)->GetGeometryCollectionComponent() : nullptr;
+ if (Component && Component->IsAnyRigidBodyAwake())
+ {
+ Component->PutAllRigidBodiesToSleep(); // sleeps after 3 s
+ }
+ }
+ }
+ }
+ for (const int32 Id : Budget.Tick(World->GetTimeSeconds()))
+ {
+ ReleaseBurst(Id);
+ }
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Nav/VerseNavDirtyQueue.cpp b/unreal/Verse/Source/VerseDestruction/Private/Nav/VerseNavDirtyQueue.cpp
new file mode 100644
index 0000000000..ec1b67a70e
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Nav/VerseNavDirtyQueue.cpp
@@ -0,0 +1,74 @@
+#include "Nav/VerseNavDirtyQueue.h"
+
+FBox FVerseNavDirtyQueue::FTile::GetBox() const
+{
+ const FVector Min(Key.X * TileSizeCm, Key.Y * TileSizeCm, MinZ);
+ const FVector Max((Key.X + 1) * TileSizeCm, (Key.Y + 1) * TileSizeCm, MaxZ);
+ return FBox(Min, Max);
+}
+
+FVerseNavDirtyQueue::FVerseNavDirtyQueue(int32 InMaxInFlight, float InMarginCm)
+ : MaxInFlight(FMath::Max(1, InMaxInFlight))
+ , MarginCm(FMath::Max(0.f, InMarginCm))
+{
+}
+
+FIntPoint FVerseNavDirtyQueue::TileOf(const FVector& Point)
+{
+ return FIntPoint(FMath::FloorToInt32(Point.X / TileSizeCm), FMath::FloorToInt32(Point.Y / TileSizeCm));
+}
+
+void FVerseNavDirtyQueue::MarkDirty(const FBox& Box, int32 PieceIndex)
+{
+ if (!Box.IsValid)
+ {
+ return;
+ }
+ const FBox Grown = Box.ExpandBy(MarginCm);
+ const FIntPoint Lo = TileOf(Grown.Min);
+ const FIntPoint Hi = TileOf(Grown.Max);
+ for (int32 X = Lo.X; X <= Hi.X; ++X)
+ {
+ for (int32 Y = Lo.Y; Y <= Hi.Y; ++Y)
+ {
+ const FIntPoint Key(X, Y);
+ FTile* Existing = Queue.FindByPredicate([&Key](const FTile& Tile) { return Tile.Key == Key; });
+ if (Existing)
+ {
+ Existing->MinZ = FMath::Min(Existing->MinZ, float(Grown.Min.Z));
+ Existing->MaxZ = FMath::Max(Existing->MaxZ, float(Grown.Max.Z));
+ continue;
+ }
+ FTile Tile;
+ Tile.Key = Key;
+ Tile.PieceIndex = PieceIndex;
+ Tile.MinZ = float(Grown.Min.Z);
+ Tile.MaxZ = float(Grown.Max.Z);
+ Queue.Add(Tile);
+ }
+ }
+}
+
+TArray<FVerseNavDirtyQueue::FTile> FVerseNavDirtyQueue::Release(int32 CompletedSinceLastRelease)
+{
+ InFlight = FMath::Max(0, InFlight - FMath::Max(0, CompletedSinceLastRelease));
+ const int32 Count = FMath::Min(Queue.Num(), MaxInFlight - InFlight);
+ TArray<FTile> Out;
+ if (Count <= 0)
+ {
+ return Out;
+ }
+ Out.Append(Queue.GetData(), Count);
+ Queue.RemoveAt(0, Count, EAllowShrinking::No);
+ InFlight += Count;
+ PeakInFlight = FMath::Max(PeakInFlight, InFlight);
+ return Out;
+}
+
+TArray<FVerseNavDirtyQueue::FTile> FVerseNavDirtyQueue::ReleaseAll()
+{
+ TArray<FTile> Out = MoveTemp(Queue);
+ Queue.Reset();
+ InFlight = 0;
+ return Out;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructible.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructible.cpp
new file mode 100644
index 0000000000..6a0474ee3e
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructible.cpp
@@ -0,0 +1,227 @@
+#include "Pieces/VerseDestructible.h"
+
+#include "Components/StaticMeshComponent.h"
+#include "Engine/StaticMesh.h"
+#include "StaticMeshResources.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "UObject/ObjectSaveContext.h"
+#include "VerseCollision.h"
+
+AVerseDestructible::AVerseDestructible()
+{
+ PrimaryActorTick.bCanEverTick = false;
+ // The manager replicates the state; pieces themselves never replicate (One File Per Actor statics).
+ bReplicates = false;
+
+ RenderMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RenderMesh"));
+ RenderMesh->SetCollisionProfileName(VerseCollision::Profile::NoCollision);
+ RenderMesh->SetCanEverAffectNavigation(false);
+ RenderMesh->SetMobility(EComponentMobility::Movable);
+ SetRootComponent(RenderMesh);
+
+ ProxyMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ProxyMesh"));
+ ProxyMesh->SetupAttachment(RenderMesh);
+ ProxyMesh->SetCollisionProfileName(VerseCollision::Profile::Destructible);
+ ProxyMesh->SetHiddenInGame(true);
+ ProxyMesh->SetCastShadow(false);
+ ProxyMesh->SetMobility(EComponentMobility::Movable);
+ ProxyMesh->SetCanEverAffectNavigation(true);
+}
+
+void AVerseDestructible::CaptureGuid()
+{
+#if WITH_EDITOR
+ if (!PieceGuid.IsValid() && GetActorGuid().IsValid())
+ {
+ PieceGuid = GetActorGuid();
+ }
+#endif
+}
+
+void AVerseDestructible::PostLoad()
+{
+ Super::PostLoad();
+ CaptureGuid();
+ IntactRender = RenderMesh ? RenderMesh->GetStaticMesh() : nullptr;
+}
+
+void AVerseDestructible::CaptureProxyVertices()
+{
+#if WITH_EDITOR
+ if (!IntactProxy || !IntactProxy->GetRenderData() || IntactProxy->GetRenderData()->LODResources.Num() == 0)
+ {
+ return;
+ }
+ // The proxy is never Nanite (art-pipeline 6.2), so LOD 0 render data is its source geometry.
+ const FPositionVertexBuffer& Positions = IntactProxy->GetRenderData()->LODResources[0].VertexBuffers.PositionVertexBuffer;
+ ProxyVertices.Reset();
+ for (uint32 Vertex = 0; Vertex < Positions.GetNumVertices(); ++Vertex)
+ {
+ ProxyVertices.AddUnique(FVector(Positions.VertexPosition(Vertex)));
+ }
+#endif
+}
+
+#if WITH_EDITOR
+void AVerseDestructible::PreSave(FObjectPreSaveContext SaveContext)
+{
+ CaptureGuid();
+ CaptureProxyVertices();
+ Super::PreSave(SaveContext);
+}
+#endif
+
+void AVerseDestructible::BeginPlay()
+{
+ Super::BeginPlay();
+ if (AVerseDestructionManager* Manager = AVerseDestructionManager::Get(this))
+ {
+ Manager->RegisterPiece(*this);
+ }
+}
+
+void AVerseDestructible::EndPlay(const EEndPlayReason::Type EndPlayReason)
+{
+ if (AVerseDestructionManager* Manager = AVerseDestructionManager::Get(this))
+ {
+ Manager->UnregisterPiece(*this);
+ }
+ Super::EndPlay(EndPlayReason);
+}
+
+void AVerseDestructible::OnConstruction(const FTransform& Transform)
+{
+ Super::OnConstruction(Transform);
+ CaptureGuid();
+ CaptureProxyVertices();
+ if (ProxyMesh)
+ {
+ ProxyMesh->SetCollisionProfileName(PieceClass == EVersePieceClass::GlassPane ? VerseCollision::Profile::Glass
+ : VerseCollision::Profile::Destructible);
+ if (IntactProxy && ProxyMesh->GetStaticMesh() == nullptr)
+ {
+ ProxyMesh->SetStaticMesh(IntactProxy);
+ }
+ }
+}
+
+FVersePieceDef AVerseDestructible::MakeDef() const
+{
+ FVersePieceDef Def;
+ Def.Guid = PieceGuid;
+ Def.Class = PieceClass;
+ Def.Material = Material;
+ Def.Transform = GetActorTransform();
+ Def.IntactBounds = IntactProxy ? IntactProxy->GetBoundingBox() : FallbackIntactBounds;
+ for (int32 Index = 0; Index < HoledVariants.Num() && Index < 4; ++Index)
+ {
+ const FVersePieceVariant& Variant = HoledVariants[Index];
+ Def.HoledBounds.Add(Variant.Proxy ? Variant.Proxy->GetBoundingBox() : Def.IntactBounds);
+ Def.HoledCentroids.Add(Variant.OpeningCentroid);
+ }
+ for (int32 Index = 0; Index < BreachedVariants.Num() && Index < 4; ++Index)
+ {
+ const FVersePieceVariant& Variant = BreachedVariants[Index];
+ Def.BreachedBounds.Add(Variant.Proxy ? Variant.Proxy->GetBoundingBox() : Def.IntactBounds);
+ Def.BreachedCentroids.Add(Variant.OpeningCentroid);
+ }
+ Def.RemainsBounds = Remains.Proxy ? Remains.Proxy->GetBoundingBox() : FBox(ForceInit);
+ Def.MantleLinks = MantleLinks;
+ Def.DropLinks = DropLinks;
+ // Authored data, identical in editor, cooked client and dedicated server (no render-data read here).
+ Def.ProxyVertices = ProxyVertices;
+ if (Def.ProxyVertices.Num() == 0 && Def.IntactBounds.IsValid)
+ {
+ const FBox& B = Def.IntactBounds;
+ for (int32 Corner = 0; Corner < 8; ++Corner)
+ {
+ Def.ProxyVertices.Add(FVector((Corner & 1) ? B.Max.X : B.Min.X, (Corner & 2) ? B.Max.Y : B.Min.Y, (Corner & 4) ? B.Max.Z : B.Min.Z));
+ }
+ }
+ return Def;
+}
+
+TArray<const FVersePieceDebrisSet*> AVerseDestructible::FindDebrisSets(EVersePieceState State, uint8 Variant) const
+{
+ TArray<const FVersePieceDebrisSet*> Out;
+ for (const FVersePieceDebrisSet& Set : DebrisSets)
+ {
+ if (Set.State == State && (State == EVersePieceState::Destroyed || Set.Variant == Variant))
+ {
+ Out.Add(&Set);
+ }
+ }
+ return Out;
+}
+
+const FVersePieceVariant* AVerseDestructible::FindVariant(EVersePieceState State, uint8 Variant) const
+{
+ const TArray<FVersePieceVariant>* List = nullptr;
+ if (State == EVersePieceState::Holed)
+ {
+ List = &HoledVariants;
+ }
+ else if (State == EVersePieceState::Breached)
+ {
+ List = &BreachedVariants;
+ }
+ else if (State == EVersePieceState::Destroyed)
+ {
+ return &Remains;
+ }
+ if (!List || List->Num() == 0)
+ {
+ return nullptr;
+ }
+ return List->IsValidIndex(Variant) ? &(*List)[Variant] : &(*List)[0];
+}
+
+UStaticMesh* AVerseDestructible::GetPresentedProxy() const
+{
+ return ProxyMesh ? ProxyMesh->GetStaticMesh() : nullptr;
+}
+
+void AVerseDestructible::ApplyPresentation(EVersePieceState State, uint8 Variant, EVersePieceState RepairFrom)
+{
+ // While Repairing the gameplay proxy stays the pre-repair proxy until completion (destruction.md 7).
+ const EVersePieceState ProxyState = State == EVersePieceState::Repairing ? RepairFrom : State;
+ if (IntactRender == nullptr && RenderMesh)
+ {
+ IntactRender = RenderMesh->GetStaticMesh();
+ }
+ UStaticMesh* Proxy = IntactProxy;
+ UStaticMesh* Render = IntactRender;
+ bool bRenderVisible = true;
+ if (ProxyState == EVersePieceState::Holed || ProxyState == EVersePieceState::Breached || ProxyState == EVersePieceState::Destroyed)
+ {
+ const FVersePieceVariant* Look = FindVariant(ProxyState, Variant);
+ Proxy = Look ? Look->Proxy.Get() : (ProxyState == EVersePieceState::Destroyed ? nullptr : IntactProxy.Get());
+ if (Look && Look->Render)
+ {
+ Render = Look->Render;
+ }
+ else if (ProxyState == EVersePieceState::Destroyed)
+ {
+ bRenderVisible = false;
+ }
+ }
+ if (ProxyMesh)
+ {
+ if (ProxyMesh->GetStaticMesh() != Proxy)
+ {
+ // SetStaticMesh re-registers the component with the navigation system (old and new bounds dirty).
+ ProxyMesh->SetStaticMesh(Proxy);
+ }
+ ProxyMesh->SetCollisionEnabled(Proxy ? ECollisionEnabled::QueryAndPhysics : ECollisionEnabled::NoCollision);
+ }
+ if (RenderMesh)
+ {
+ if (Render && RenderMesh->GetStaticMesh() != Render)
+ {
+ RenderMesh->SetStaticMesh(Render);
+ }
+ RenderMesh->SetVisibility(bRenderVisible);
+ }
+ PresentedState = State;
+ PresentedVariant = Variant;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionManager.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionManager.cpp
new file mode 100644
index 0000000000..22771c3464
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionManager.cpp
@@ -0,0 +1,630 @@
+#include "Pieces/VerseDestructionManager.h"
+
+#include "AI/NavigationSystemBase.h"
+#include "Components/StaticMeshComponent.h"
+#include "Destruction/VerseDestructionTuning.h"
+#include "Engine/World.h"
+#include "EngineUtils.h"
+#include "Events/VerseEventHub.h"
+#include "Net/UnrealNetwork.h"
+#include "Net/Core/PushModel/PushModel.h"
+#include "NavigationSystem.h"
+#include "UObject/CoreNet.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VersePieceManifest.h"
+#include "Debris/VerseDebrisSubsystem.h"
+#include "Repair/VerseRepairDrone.h"
+#include "VerseLog.h"
+
+AVerseDestructionManager::AVerseDestructionManager()
+{
+ PrimaryActorTick.bCanEverTick = true;
+ PrimaryActorTick.TickGroup = TG_PrePhysics;
+ bReplicates = true;
+ bAlwaysRelevant = true;
+ SetNetUpdateFrequency(30.f);
+ DroneClass = AVerseRepairDrone::StaticClass();
+ Pieces.Owner = this;
+ DamageSink.Owner = this;
+}
+
+AVerseDestructionManager* AVerseDestructionManager::Get(const UObject* WorldContextObject)
+{
+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;
+ if (!World)
+ {
+ return nullptr;
+ }
+ for (TActorIterator<AVerseDestructionManager> It(World); It; ++It)
+ {
+ return *It;
+ }
+ return nullptr;
+}
+
+void AVerseDestructionManager::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ // Push model (destruction.md 3.3): the properties are only compared after a write marked them.
+ FDoRepLifetimeParams Params;
+ Params.bIsPushBased = true;
+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseDestructionManager, Pieces, Params);
+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseDestructionManager, Epoch, Params);
+}
+
+uint32 AVerseDestructionManager::GetServerTimeMs() const
+{
+ const UWorld* World = GetWorld();
+ return World ? uint32(FMath::Max(0.0, World->GetTimeSeconds()) * 1000.0) : 0u;
+}
+
+void AVerseDestructionManager::BeginPlay()
+{
+ Super::BeginPlay();
+ Pieces.Owner = this;
+ DamageSink.Owner = this;
+ RegisterPieces();
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ ArenaSwitchHandle = Hub->OnArenaSwitch.AddUObject(this, &AVerseDestructionManager::HandleArenaSwitch);
+ }
+ if (HasAuthority())
+ {
+ SpawnDrones();
+ }
+}
+
+void AVerseDestructionManager::EndPlay(const EEndPlayReason::Type EndPlayReason)
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnArenaSwitch.Remove(ArenaSwitchHandle);
+ }
+ for (AVerseRepairDrone* Drone : DroneActors)
+ {
+ if (IsValid(Drone))
+ {
+ Drone->Destroy();
+ }
+ }
+ DroneActors.Reset();
+ Super::EndPlay(EndPlayReason);
+}
+
+bool AVerseDestructionManager::IsMissingClientManifest() const
+{
+ const bool bNetworkedClient = !HasAuthority() && GetNetMode() != NM_Standalone;
+ return bNetworkedClient && (!Manifest || Manifest->PieceGuids.Num() == 0);
+}
+
+void AVerseDestructionManager::RegisterPieces()
+{
+ UWorld* World = GetWorld();
+ if (!World)
+ {
+ return;
+ }
+ if (IsMissingClientManifest())
+ {
+ // Sorting only the GUIDs this client has loaded would shift PieceIndex against the server.
+ UE_LOG(LogVerseDestruction, Error, TEXT("%s: a networked client needs DA_PieceManifest; destruction stays off here"), *GetName());
+ return;
+ }
+ TMap<FGuid, AVerseDestructible*> ByGuid;
+ for (TActorIterator<AVerseDestructible> It(World); It; ++It)
+ {
+ AVerseDestructible* Piece = *It;
+ if (!Piece->GetPieceGuid().IsValid())
+ {
+ UE_LOG(LogVerseDestruction, Error, TEXT("%s has no piece GUID; it stays out of the manifest"), *Piece->GetName());
+ continue;
+ }
+ ByGuid.Add(Piece->GetPieceGuid(), Piece);
+ }
+ TArray<FGuid> Order;
+ if (Manifest && Manifest->PieceGuids.Num() > 0)
+ {
+ Order = Manifest->PieceGuids;
+ }
+ else
+ {
+ ByGuid.GenerateKeyArray(Order);
+ UVersePieceManifest::SortGuids(Order);
+ }
+ PieceActors.Reset();
+ SlotOfGuid.Reset();
+ TArray<FVersePieceDef> Defs;
+ for (const FGuid& Guid : Order)
+ {
+ AVerseDestructible* const* Found = ByGuid.Find(Guid);
+ AVerseDestructible* Piece = Found ? *Found : nullptr;
+ SlotOfGuid.Add(Guid, PieceActors.Num());
+ if (Piece)
+ {
+ Piece->SetPieceIndex(PieceActors.Num());
+ Defs.Add(Piece->MakeDef());
+ }
+ else
+ {
+ // Not loaded (yet): an inert slot keeps the index stable until the piece streams in.
+ FVersePieceDef Missing;
+ Missing.Guid = Guid;
+ Missing.Material = EVersePenetrationMaterial::Concrete;
+ Defs.Add(Missing);
+ }
+ PieceActors.Add(Piece);
+ }
+ const UVerseDestructionTuning* Asset = Tuning ? Tuning.Get() : GetDefault<UVerseDestructionTuning>();
+ Sim.Init(MoveTemp(Defs), FVerseDestructionSimTuning::FromAsset(*Asset), DroneDocks, uint64(FractureSeed));
+ if (HasAuthority())
+ {
+ Pieces.Items = Sim.GetItems();
+ Pieces.MarkArrayDirty();
+ MARK_PROPERTY_DIRTY_FROM_NAME(AVerseDestructionManager, Pieces, this);
+ }
+ else
+ {
+ // Items that replicated before the pieces were registered.
+ for (const FVersePieceItem& Item : Pieces.Items)
+ {
+ OnItemReplicated(Item, true);
+ }
+ }
+ UVerseDebrisSubsystem* Debris = World->GetSubsystem<UVerseDebrisSubsystem>();
+ for (AVerseDestructible* Piece : PieceActors)
+ {
+ if (Piece && Debris)
+ {
+ Debris->PreloadPiece(*Piece);
+ }
+ }
+ bRegistered = true;
+}
+
+void AVerseDestructionManager::RegisterPiece(AVerseDestructible& Piece)
+{
+ if (!bRegistered)
+ {
+ return; // RegisterPieces at BeginPlay picks it up
+ }
+ const int32* Slot = SlotOfGuid.Find(Piece.GetPieceGuid());
+ if (!Slot)
+ {
+ UE_LOG(LogVerseDestruction, Error, TEXT("%s (%s) is not in the manifest; it stays inert"), *Piece.GetName(), *Piece.GetPieceGuid().ToString());
+ return;
+ }
+ if (PieceActors[*Slot] == &Piece)
+ {
+ return;
+ }
+ PieceActors[*Slot] = &Piece;
+ Piece.SetPieceIndex(*Slot);
+ Sim.SetDef(uint16(*Slot), Piece.MakeDef());
+ if (const FVersePieceItem* Item = FindItem(uint16(*Slot)))
+ {
+ Piece.ApplyPresentation(Item->State, Item->Variant, Item->RepairFrom);
+ }
+ if (UVerseDebrisSubsystem* Debris = GetWorld() ? GetWorld()->GetSubsystem<UVerseDebrisSubsystem>() : nullptr)
+ {
+ Debris->PreloadPiece(Piece);
+ }
+}
+
+void AVerseDestructionManager::UnregisterPiece(AVerseDestructible& Piece)
+{
+ const int32 Index = Piece.GetPieceIndex();
+ if (PieceActors.IsValidIndex(Index) && PieceActors[Index] == &Piece)
+ {
+ PieceActors[Index] = nullptr;
+ }
+}
+
+void AVerseDestructionManager::SpawnDrones()
+{
+ UWorld* World = GetWorld();
+ if (!World || !DroneClass)
+ {
+ return;
+ }
+ for (int32 Index = 0; Index < DroneDocks.Num(); ++Index)
+ {
+ FActorSpawnParameters Params;
+ Params.Owner = this;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AVerseRepairDrone* Drone = World->SpawnActor<AVerseRepairDrone>(DroneClass, DroneDocks[Index], FRotator::ZeroRotator, Params);
+ if (Drone)
+ {
+ Drone->DroneIndex = Index;
+ DroneActors.Add(Drone);
+ }
+ }
+}
+
+AVerseDestructible* AVerseDestructionManager::GetPieceActor(uint16 PieceIndex) const
+{
+ return PieceActors.IsValidIndex(PieceIndex) ? PieceActors[PieceIndex].Get() : nullptr;
+}
+
+const FVersePieceItem* AVerseDestructionManager::FindItem(uint16 PieceIndex) const
+{
+ if (Pieces.Items.IsValidIndex(PieceIndex) && Pieces.Items[PieceIndex].PieceIndex == PieceIndex)
+ {
+ return &Pieces.Items[PieceIndex]; // the server writes items in manifest order
+ }
+ return Pieces.Items.FindByPredicate([PieceIndex](const FVersePieceItem& Item) { return Item.PieceIndex == PieceIndex; });
+}
+
+void AVerseDestructionManager::ApplyPieceDamage(const FVersePieceDamage& Damage)
+{
+ if (!HasAuthority())
+ {
+ ensureMsgf(false, TEXT("ApplyPieceDamage on a client (DR1)"));
+ return;
+ }
+ Sim.ApplyDamage(Damage, GetServerTimeMs());
+ ApplyDirtyItems();
+}
+
+void AVerseDestructionManager::ApplyHoleCap(uint16 PieceIndex, const FVector& LocalCentroidCm)
+{
+ if (!HasAuthority())
+ {
+ return;
+ }
+ Sim.ApplyHoleCap(PieceIndex, LocalCentroidCm, GetServerTimeMs());
+ ApplyDirtyItems();
+}
+
+void AVerseDestructionManager::ApplyDroneDamage(int32 DroneIndex, float Amount)
+{
+ if (!HasAuthority())
+ {
+ return;
+ }
+ Sim.ApplyDroneDamage(DroneIndex, Amount, GetServerTimeMs());
+ ApplyDirtyItems();
+}
+
+void AVerseDestructionManager::FullReset()
+{
+ if (!HasAuthority())
+ {
+ return;
+ }
+ Sim.FullReset(GetServerTimeMs());
+ ApplyDirtyItems();
+}
+
+void AVerseDestructionManager::HandleArenaSwitch(const FVerseArenaSwitchEvent& Event)
+{
+ // Arena on and arena off both reset, so the normal deck is always intact (destruction.md 11).
+ if (bResetOnArenaSwitch && HasAuthority())
+ {
+ FullReset();
+ }
+}
+
+bool AVerseDestructionManager::IsEncroached(const FBox& WorldBox) const
+{
+ const UWorld* World = GetWorld();
+ if (!World || !WorldBox.IsValid)
+ {
+ return false;
+ }
+ FCollisionObjectQueryParams Objects;
+ Objects.AddObjectTypesToQuery(ECC_Pawn);
+ return World->OverlapAnyTestByObjectType(WorldBox.GetCenter(), FQuat::Identity, Objects, FCollisionShape::MakeBox(WorldBox.GetExtent()));
+}
+
+void AVerseDestructionManager::Tick(float DeltaSeconds)
+{
+ Super::Tick(DeltaSeconds);
+ if (HasAuthority() && bRegistered)
+ {
+ const uint32 NowMs = GetServerTimeMs();
+ Sim.Tick(NowMs, [this](const FBox& Box) { return IsEncroached(Box); });
+ ApplyDirtyItems();
+ PublishTick();
+ }
+}
+
+void AVerseDestructionManager::ApplyDirtyItems()
+{
+ const TArray<uint16> DirtyItems = Sim.DrainDirtyItems();
+ if (DirtyItems.Num() > 0)
+ {
+ MARK_PROPERTY_DIRTY_FROM_NAME(AVerseDestructionManager, Pieces, this);
+ }
+ for (const uint16 Index : DirtyItems)
+ {
+ if (!Pieces.Items.IsValidIndex(Index))
+ {
+ continue;
+ }
+ FVersePieceItem& Item = Pieces.Items[Index];
+ const FVersePieceItem& Truth = Sim.GetItem(Index);
+ // Copy the gameplay fields; keep the fast-array bookkeeping of the replicated item.
+ Item.State = Truth.State;
+ Item.HealthQ = Truth.HealthQ;
+ Item.Variant = Truth.Variant;
+ Item.RepairFrom = Truth.RepairFrom;
+ Item.LastSeed = Truth.LastSeed;
+ FMemory::Memcpy(Item.LastImpulse, Truth.LastImpulse, sizeof(Item.LastImpulse));
+ FMemory::Memcpy(Item.LastLocation, Truth.LastLocation, sizeof(Item.LastLocation));
+ Item.StateTimeMs = Truth.StateTimeMs;
+ Item.Epoch = Truth.Epoch;
+ Pieces.MarkItemDirty(Item);
+ if (AVerseDestructible* Piece = GetPieceActor(Index))
+ {
+ Piece->ApplyPresentation(Item.State, Item.Variant, Item.RepairFrom);
+ }
+ }
+ if (Epoch != Sim.GetEpoch())
+ {
+ Epoch = Sim.GetEpoch();
+ MARK_PROPERTY_DIRTY_FROM_NAME(AVerseDestructionManager, Epoch, this);
+ }
+}
+
+void AVerseDestructionManager::PublishTick()
+{
+ // Every input of this tick is in the sim by now, so several hits on one piece in one frame
+ // (pellets, a breach plus bolts) leave one event (destruction.md 4).
+ for (const FVersePendingFracture& Pending : Sim.DrainEvents())
+ {
+ if (Pending.bPublishLocal)
+ {
+ PublishLocal(Pending.Event);
+ }
+ if (Pending.bMulticast && GetNetMode() != NM_Standalone)
+ {
+ MulticastFracture(Pending.Event);
+ }
+ }
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ for (const FVerseNoiseEvent& Noise : Sim.DrainNoise())
+ {
+ Hub->OnNoise.Broadcast(Noise);
+ }
+ }
+ else
+ {
+ Sim.DrainNoise();
+ }
+ ReleaseNavTiles();
+ SyncDrones();
+}
+
+int32 AVerseDestructionManager::CompletedNavTiles() const
+{
+ const FVerseNavDirtyQueue& Nav = Sim.GetNav();
+ if (Nav.NumInFlight() == 0)
+ {
+ return 0;
+ }
+ const UNavigationSystemV1* NavSys = FNavigationSystem::GetCurrent<UNavigationSystemV1>(GetWorld());
+ if (!NavSys || !NavSys->GetDefaultNavDataInstance())
+ {
+ return Nav.NumInFlight(); // no navmesh in this world: nothing rebuilds, nothing to wait for
+ }
+ // Real feedback: the released tiles are rebuilt once the navigation system has taken every
+ // dirty area and has no tile job queued or running.
+ if (NavSys->HasDirtyAreasQueued() || NavSys->GetNumRemainingBuildTasks() > 0 || NavSys->GetNumRunningBuildTasks() > 0)
+ {
+ return 0;
+ }
+ return Nav.NumInFlight();
+}
+
+void AVerseDestructionManager::ReleaseNavTiles()
+{
+ // Once per server tick: slots free only when the navmesh confirms the rebuild, so at most
+ // NavMaxTilesInFlight tiles are ever handed over and not yet rebuilt (destruction.md 6.1).
+ FVerseNavDirtyQueue& Nav = Sim.GetNav();
+ for (const FVerseNavDirtyQueue::FTile& Tile : Nav.Release(CompletedNavTiles()))
+ {
+ AVerseDestructible* Piece = Tile.PieceIndex != INDEX_NONE ? GetPieceActor(uint16(Tile.PieceIndex)) : nullptr;
+ UStaticMeshComponent* Proxy = Piece ? Piece->GetProxyComponent() : nullptr;
+ if (Proxy && Proxy->IsRegistered())
+ {
+ // The proxy's own octree bounds stay its bounds; the tile (old and new proxy +50 cm) is the dirty area.
+ const FBox Dirty = Tile.GetBox();
+ FNavigationSystem::OnObjectBoundsChanged(*Proxy, Proxy->Bounds.GetBox(), MakeArrayView(&Dirty, 1));
+ }
+ }
+}
+
+void AVerseDestructionManager::SyncDrones()
+{
+ const TArray<FVerseDroneState>& Drones = Sim.GetDrones();
+ for (AVerseRepairDrone* Drone : DroneActors)
+ {
+ if (IsValid(Drone) && Drones.IsValidIndex(Drone->DroneIndex))
+ {
+ const FVerseDroneState& State = Drones[Drone->DroneIndex];
+ Drone->SyncFromSim(State.Location, uint8(State.Task), State.Generation, State.Hp);
+ }
+ }
+}
+
+void AVerseDestructionManager::PublishLocal(const FVerseFractureEvent& Event)
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnFracture.Broadcast(Event);
+ }
+}
+
+void AVerseDestructionManager::MulticastFracture_Implementation(const FVerseFractureEvent& Event)
+{
+ if (HasAuthority())
+ {
+ return; // the server published it when it happened
+ }
+ if (Event.Epoch < Epoch)
+ {
+ return; // events with an old epoch are dropped (destruction.md 4)
+ }
+ PublishLocal(Event);
+}
+
+void AVerseDestructionManager::OnRep_Epoch()
+{
+}
+
+void AVerseDestructionManager::OnItemReplicated(const FVersePieceItem& Item, bool bInitial)
+{
+ // Late joiners and dropped events: the item is the truth; it never spawns debris.
+ if (AVerseDestructible* Piece = GetPieceActor(Item.PieceIndex))
+ {
+ Piece->ApplyPresentation(Item.State, Item.Variant, Item.RepairFrom);
+ }
+}
+
+void AVerseDestructionManager::ReceiveItemsForTest(TConstArrayView<FVersePieceItem> InItems, bool bInitial)
+{
+ for (const FVersePieceItem& Incoming : InItems)
+ {
+ FVersePieceItem* Existing = Pieces.Items.FindByPredicate([&Incoming](const FVersePieceItem& Item) { return Item.PieceIndex == Incoming.PieceIndex; });
+ if (!Existing)
+ {
+ Existing = &Pieces.Items.Add_GetRef(Incoming);
+ }
+ else
+ {
+ *Existing = Incoming;
+ }
+ if (bInitial)
+ {
+ Existing->PostReplicatedAdd(Pieces);
+ }
+ else
+ {
+ Existing->PostReplicatedChange(Pieces);
+ }
+ }
+}
+
+EVersePieceState AVerseDestructionManager::GetPieceState(uint16 PieceIndex) const
+{
+ const FVersePieceItem* Item = FindItem(PieceIndex);
+ return Item ? Item->State : EVersePieceState::Intact;
+}
+
+EVersePenetrationMaterial AVerseDestructionManager::GetPieceMaterial(uint16 PieceIndex) const
+{
+ return Sim.IsValidPiece(PieceIndex) ? Sim.GetDef(PieceIndex).Material : EVersePenetrationMaterial::Concrete;
+}
+
+FBox AVerseDestructionManager::GetPieceBounds(uint16 PieceIndex) const
+{
+ const FVersePieceItem* Item = FindItem(PieceIndex);
+ if (!Item || !Sim.IsValidPiece(PieceIndex))
+ {
+ return FBox(ForceInit);
+ }
+ return Sim.GetDef(PieceIndex).GetWorldBounds(Item->GetProxyState(), Item->Variant);
+}
+
+TArray<uint16> AVerseDestructionManager::GetPiecesInBox(const FBox& WorldBox) const
+{
+ return Sim.GetPiecesInBox(WorldBox);
+}
+
+bool FVersePieceItem::HasFractureRecord() const
+{
+ return LastSeed != 0 || LastImpulse[0] != 0 || LastImpulse[1] != 0 || LastImpulse[2] != 0 || LastLocation[0] != 0
+ || LastLocation[1] != 0 || LastLocation[2] != 0;
+}
+
+namespace
+{
+ template <typename T>
+ void SerializeBitsOf(FArchive& Ar, T& Value, int32 Bits)
+ {
+ uint64 Raw = Ar.IsSaving() ? uint64(Value) & ((uint64(1) << Bits) - 1) : 0;
+ Ar.SerializeBits(&Raw, Bits);
+ if (Ar.IsLoading())
+ {
+ Value = T(Raw);
+ }
+ }
+
+ void SerializeInt16(FArchive& Ar, int16& Value)
+ {
+ uint16 Raw = uint16(Value);
+ SerializeBitsOf(Ar, Raw, 16);
+ Value = int16(Raw);
+ }
+}
+
+bool FVersePieceItem::NetSerialize(FArchive& Ar, UPackageMap* Map, bool& bOutSuccess)
+{
+ bOutSuccess = PieceIndex < (1u << MaxPieceIndexBits);
+ SerializeBitsOf(Ar, PieceIndex, MaxPieceIndexBits);
+ uint8 StateBits = uint8(State);
+ SerializeBitsOf(Ar, StateBits, 3);
+ State = EVersePieceState(StateBits);
+ SerializeBitsOf(Ar, HealthQ, 8);
+ SerializeBitsOf(Ar, Variant, 2);
+ if (State == EVersePieceState::Repairing)
+ {
+ uint8 From = uint8(RepairFrom);
+ SerializeBitsOf(Ar, From, 3);
+ RepairFrom = EVersePieceState(From);
+ }
+ else if (Ar.IsLoading())
+ {
+ RepairFrom = EVersePieceState::Intact;
+ }
+ uint8 bRecord = Ar.IsSaving() && HasFractureRecord() ? 1 : 0;
+ SerializeBitsOf(Ar, bRecord, 1);
+ if (bRecord)
+ {
+ SerializeBitsOf(Ar, LastSeed, 32);
+ for (int32 Axis = 0; Axis < 3; ++Axis)
+ {
+ SerializeInt16(Ar, LastImpulse[Axis]);
+ }
+ for (int32 Axis = 0; Axis < 3; ++Axis)
+ {
+ SerializeInt16(Ar, LastLocation[Axis]);
+ }
+ }
+ else if (Ar.IsLoading())
+ {
+ LastSeed = 0;
+ FMemory::Memzero(LastImpulse, sizeof(LastImpulse));
+ FMemory::Memzero(LastLocation, sizeof(LastLocation));
+ }
+ SerializeBitsOf(Ar, StateTimeMs, 32);
+ SerializeBitsOf(Ar, Epoch, 16);
+ bOutSuccess = bOutSuccess && !Ar.IsError();
+ return true;
+}
+
+int32 FVersePieceItem::MeasureWireBytes(const FVersePieceItem& Item)
+{
+ FNetBitWriter Writer(nullptr, 1024);
+ FVersePieceItem Copy = Item;
+ bool bOk = false;
+ Copy.NetSerialize(Writer, nullptr, bOk);
+ return int32((Writer.GetNumBits() + 7) / 8);
+}
+
+void FVersePieceItem::PostReplicatedAdd(const FVersePieceItemArray& InArraySerializer)
+{
+ if (InArraySerializer.Owner)
+ {
+ InArraySerializer.Owner->OnItemReplicated(*this, true);
+ }
+}
+
+void FVersePieceItem::PostReplicatedChange(const FVersePieceItemArray& InArraySerializer)
+{
+ if (InArraySerializer.Owner)
+ {
+ InArraySerializer.Owner->OnItemReplicated(*this, false);
+ }
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionSim.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionSim.cpp
new file mode 100644
index 0000000000..cec4d71281
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VerseDestructionSim.cpp
@@ -0,0 +1,824 @@
+#include "Pieces/VerseDestructionSim.h"
+
+#include "Pieces/VersePieceRules.h"
+#include "VerseGameplayTags.h"
+#include "VerseLog.h"
+#include "VerseRng.h"
+
+using namespace Verse::Destruction;
+
+namespace
+{
+ int16 QuantizeI16(double Value)
+ {
+ return int16(FMath::Clamp(FMath::RoundToInt64(Value), int64(-32768), int64(32767)));
+ }
+
+ uint8 InstigatorSlot(int32 InstigatorId)
+ {
+ return (InstigatorId < 0 || InstigatorId >= int32(WorldInstigator)) ? WorldInstigator : uint8(InstigatorId);
+ }
+
+ uint32 SecondsToMs(float Seconds)
+ {
+ return uint32(FMath::Max(0.f, Seconds) * 1000.f + 0.5f);
+ }
+}
+
+void FVerseDestructionSim::Init(TArray<FVersePieceDef> InDefs, const FVerseDestructionSimTuning& InTuning,
+ TConstArrayView<FVector> DroneDocks, uint64 InSeed)
+{
+ check(InDefs.Num() <= 2000); // destruction.md 8: at most 2,000 pieces per deck
+ Defs = MoveTemp(InDefs);
+ Tuning = InTuning;
+ Seed = InSeed;
+ SeedCounter = 0;
+ Epoch = 0;
+ Nav = FVerseNavDirtyQueue(Tuning.NavMaxTilesInFlight, Tuning.NavDirtyMarginCm);
+ Items.SetNum(Defs.Num());
+ Server.SetNum(Defs.Num());
+ for (int32 Index = 0; Index < Defs.Num(); ++Index)
+ {
+ FVersePieceItem& Item = Items[Index];
+ Item = FVersePieceItem();
+ Item.PieceIndex = uint16(Index);
+ Item.HealthQ = 255;
+ Server[Index] = FServerPiece();
+ Server[Index].Hp = Tuning.ClassRow(Defs[Index].Class).MaxHp;
+ }
+ Drones.Reset();
+ for (int32 Index = 0; Index < DroneDocks.Num(); ++Index)
+ {
+ FVerseDroneState& Drone = Drones.AddDefaulted_GetRef();
+ Drone.Index = Index;
+ Drone.Dock = DroneDocks[Index];
+ Drone.Location = DroneDocks[Index];
+ Drone.Hp = Tuning.DroneMaxHp;
+ }
+ Events.Reset();
+ EventOfPiece.Reset();
+ Deferred.Reset();
+ EventTickMs = 0;
+ LastTickMs = 0;
+ MulticastTimesMs.Reset();
+ Noise.Reset();
+ Dirty.Reset();
+ Counters = FVerseDestructionCounters();
+}
+
+uint32 FVerseDestructionSim::NextSeed()
+{
+ return FVerseRng(Seed, SeedCounter++, EVerseRngSalt::Fracture).NextU32();
+}
+
+void FVerseDestructionSim::SetDef(uint16 PieceIndex, FVersePieceDef Def)
+{
+ if (!IsValidPiece(PieceIndex))
+ {
+ return;
+ }
+ const bool bWasInert = VerseMaterialNeverBreaks(Defs[PieceIndex].Material) && Items[PieceIndex].State == EVersePieceState::Intact;
+ Defs[PieceIndex] = MoveTemp(Def);
+ if (bWasInert)
+ {
+ // A piece that streamed in late takes its slot with full HP (destruction.md 8).
+ Server[PieceIndex].Hp = Tuning.ClassRow(Defs[PieceIndex].Class).MaxHp;
+ }
+}
+
+bool FVerseDestructionSim::CanBreak(uint16 PieceIndex) const
+{
+ return !VerseMaterialNeverBreaks(Defs[PieceIndex].Material);
+}
+
+void FVerseDestructionSim::ApplyDamage(const FVersePieceDamage& Damage, uint32 NowMs)
+{
+ if (!IsValidPiece(Damage.PieceIndex))
+ {
+ UE_LOG(LogVerseDestruction, Warning, TEXT("ApplyPieceDamage: unknown piece %u"), Damage.PieceIndex);
+ return;
+ }
+ if (Damage.Cause == EVerseFractureCause::Repair || Damage.Cause == EVerseFractureCause::Reset)
+ {
+ return; // not damage causes
+ }
+ if (Damage.Cause != EVerseFractureCause::Breach)
+ {
+ ApplyOne(Damage.PieceIndex, Damage, Rules::EHitRole::Direct, NowMs);
+ return;
+ }
+ ApplyOne(Damage.PieceIndex, Damage, Rules::EHitRole::BreachTarget, NowMs);
+ const float Radius = Damage.BreachRadiusCm > 0.f ? Damage.BreachRadiusCm : Tuning.BreachSideRadiusCm;
+ for (int32 Index = 0; Index < Defs.Num(); ++Index)
+ {
+ if (Index != Damage.PieceIndex && Defs[Index].IsWithinRadius(Damage.Location, Radius))
+ {
+ ApplyOne(uint16(Index), Damage, Rules::EHitRole::BreachSide, NowMs);
+ }
+ }
+}
+
+void FVerseDestructionSim::ApplyOne(uint16 PieceIndex, const FVersePieceDamage& Damage, Rules::EHitRole Role, uint32 NowMs)
+{
+ if (!CanBreak(PieceIndex))
+ {
+ return; // DR4
+ }
+ const FVersePieceDef& Def = Defs[PieceIndex];
+ const FVersePieceClassTuning& Row = Tuning.ClassRow(Def.Class);
+ FServerPiece& Piece = Server[PieceIndex];
+ const uint8 Instigator = InstigatorSlot(Damage.InstigatorId);
+
+ // Any damage while Repairing cancels the repair (destruction.md 7); the damage then applies
+ // to the state it was repairing from. Damage while a drone is on its way recalls it.
+ if (Items[PieceIndex].State == EVersePieceState::Repairing)
+ {
+ CancelRepair(PieceIndex, Damage.Cause, Instigator, NowMs);
+ }
+ else if (Piece.AssignedDrone != INDEX_NONE)
+ {
+ Recall(Drones[Piece.AssignedDrone], NowMs);
+ Piece.AssignedDrone = INDEX_NONE;
+ }
+
+ const EVersePieceState Before = Items[PieceIndex].State;
+ const float HpBefore = Piece.Hp;
+ const Rules::FOutcome Out = Rules::Apply(Row, Before, Piece.Hp, Damage.Cause, Role, Damage.Amount);
+ Piece.Hp = Out.Hp;
+
+ const FVector Local = Def.Transform.InverseTransformPosition(Damage.Location);
+ if (Damage.Cause == EVerseFractureCause::Bolt)
+ {
+ Piece.HitSumLocal += Local;
+ Piece.HitCount += 1;
+ }
+
+ const bool bStateChanged = Out.State != Before;
+ const bool bHpChanged = !FMath::IsNearlyEqual(HpBefore, Piece.Hp);
+ // Any further damage restarts the 60 s (destruction.md 7), also on a piece already at 0 HP
+ // that keeps taking hole-making bolts, so nothing is repaired while it is still under fire
+ // and a recalled drone is not sent straight back.
+ Piece.LastDamageMs = NowMs;
+ if (bStateChanged || bHpChanged)
+ {
+ Piece.bDamagedSinceRepair = true;
+ }
+ if (bStateChanged)
+ {
+ uint8 Variant = Items[PieceIndex].Variant;
+ if (Out.State == EVersePieceState::Holed && Before != EVersePieceState::Holed)
+ {
+ const FVector Centroid = (Damage.Cause == EVerseFractureCause::Bolt && Piece.HitCount > 0)
+ ? Piece.HitSumLocal / double(Piece.HitCount)
+ : Local;
+ Variant = FVersePieceDef::NearestVariant(Def.HoledCentroids, Centroid);
+ }
+ else if (Out.State == EVersePieceState::Breached)
+ {
+ Variant = FVersePieceDef::NearestVariant(Def.BreachedCentroids, Local);
+ }
+ else if (Out.State == EVersePieceState::Destroyed || Out.State == EVersePieceState::Damaged)
+ {
+ Variant = 0;
+ }
+ float ImpulseNs = Tuning.Start.BoltImpulseNs;
+ uint8 Radius = Tuning.Start.BoltStrainRadiusCm;
+ if (Damage.Cause == EVerseFractureCause::Melee)
+ {
+ ImpulseNs = Tuning.Start.MeleeImpulseNs;
+ Radius = Tuning.Start.MeleeStrainRadiusCm;
+ }
+ else if (Damage.Cause == EVerseFractureCause::Breach)
+ {
+ const float BreachRadius = Damage.BreachRadiusCm > 0.f ? Damage.BreachRadiusCm : Tuning.BreachSideRadiusCm;
+ ImpulseNs = Tuning.Start.BreachImpulseNs;
+ Radius = uint8(FMath::Clamp(FMath::RoundToInt(BreachRadius), 0, 255));
+ }
+ const FVector Direction = Damage.Cause == EVerseFractureCause::Breach && Role == Rules::EHitRole::BreachSide
+ ? (Def.GetWorldBounds(Before, Items[PieceIndex].Variant).GetCenter() - Damage.Location).GetSafeNormal()
+ : Damage.Direction.GetSafeNormal();
+ SetState(PieceIndex, Out.State, Variant, Damage.Cause, Damage.Location, Direction, ImpulseNs, Radius, Instigator, NowMs);
+ if (Out.State != EVersePieceState::Damaged && Out.State != EVersePieceState::Intact)
+ {
+ Piece.HitSumLocal = FVector::ZeroVector;
+ Piece.HitCount = 0;
+ }
+ }
+ else if (bHpChanged)
+ {
+ WriteHealth(PieceIndex);
+ }
+}
+
+void FVerseDestructionSim::ApplyHoleCap(uint16 PieceIndex, const FVector& LocalCentroidCm, uint32 NowMs)
+{
+ if (!IsValidPiece(PieceIndex) || !CanBreak(PieceIndex))
+ {
+ return;
+ }
+ const FVersePieceDef& Def = Defs[PieceIndex];
+ const FVersePieceClassTuning& Row = Tuning.ClassRow(Def.Class);
+ if (Row.HoledAtOrBelowHp < 0.f)
+ {
+ return; // only wall pieces turn Holed from holes
+ }
+ if (Items[PieceIndex].State == EVersePieceState::Repairing)
+ {
+ CancelRepair(PieceIndex, EVerseFractureCause::Bolt, WorldInstigator, NowMs);
+ }
+ const EVersePieceState Before = Items[PieceIndex].State;
+ if (!Rules::IsForward(Before, EVersePieceState::Holed) || Before == EVersePieceState::Holed)
+ {
+ return;
+ }
+ FServerPiece& Piece = Server[PieceIndex];
+ Piece.Hp = FMath::Min(Piece.Hp, Row.HoledAtOrBelowHp);
+ Piece.LastDamageMs = NowMs;
+ const uint8 Variant = FVersePieceDef::NearestVariant(Def.HoledCentroids, LocalCentroidCm);
+ SetState(PieceIndex, EVersePieceState::Holed, Variant, EVerseFractureCause::Bolt, Def.Transform.TransformPosition(LocalCentroidCm),
+ FVector::ZeroVector, Tuning.Start.BoltImpulseNs, Tuning.Start.BoltStrainRadiusCm, WorldInstigator, NowMs);
+}
+
+void FVerseDestructionSim::SetState(uint16 PieceIndex, EVersePieceState NewState, uint8 Variant, EVerseFractureCause Cause,
+ const FVector& WorldLocation, const FVector& Direction, float ImpulseNs, uint8 RadiusCm, uint8 Instigator, uint32 NowMs)
+{
+ FVersePieceItem& Item = Items[PieceIndex];
+ const FVersePieceDef& Def = Defs[PieceIndex];
+ FServerPiece& Piece = Server[PieceIndex];
+ const EVersePieceState From = Item.State;
+ const EVersePieceState OldProxy = Item.GetProxyState();
+ const uint8 OldVariant = Item.Variant;
+
+ Item.State = NewState;
+ Item.Variant = Variant;
+ Item.RepairFrom = NewState == EVersePieceState::Repairing ? From : EVersePieceState::Intact;
+ Item.HealthQ = QuantizeHealth(Piece.Hp, Tuning.ClassRow(Def.Class).MaxHp);
+ if (Tuning.ClassRow(Def.Class).MaxHp <= 0.f)
+ {
+ Item.HealthQ = NewState == EVersePieceState::Destroyed ? 0 : 255;
+ }
+ Item.LastSeed = NextSeed();
+ const FVector Impulse = Direction * (ImpulseNs / ImpulseUnitNs);
+ const FVector LocalMm = Def.Transform.InverseTransformPosition(WorldLocation) * 10.0;
+ for (int32 Axis = 0; Axis < 3; ++Axis)
+ {
+ Item.LastImpulse[Axis] = QuantizeI16(Impulse[Axis]);
+ Item.LastLocation[Axis] = QuantizeI16(LocalMm[Axis]);
+ }
+ Item.StateTimeMs = NowMs;
+ Item.Epoch = Epoch;
+ if (From == EVersePieceState::Intact && NewState != EVersePieceState::Intact)
+ {
+ Piece.BrokenSinceMs = NowMs;
+ }
+ MarkDirty(PieceIndex);
+ if (Item.GetProxyState() != OldProxy || Item.Variant != OldVariant)
+ {
+ MarkNav(PieceIndex, OldProxy, OldVariant);
+ }
+ Counters.StateChanges += 1;
+
+ FVerseFractureEvent Event;
+ Event.PieceIndex = PieceIndex;
+ Event.FromState = From;
+ Event.ToState = NewState;
+ Event.Cause = Cause;
+ Event.Variant = Variant;
+ Event.Seed = Item.LastSeed;
+ for (int32 Axis = 0; Axis < 3; ++Axis)
+ {
+ Event.Impulse[Axis] = Item.LastImpulse[Axis];
+ Event.Location[Axis] = Item.LastLocation[Axis];
+ }
+ Event.Radius = RadiusCm;
+ Event.Instigator = Instigator;
+ Event.ServerTimeMs = NowMs;
+ Event.Epoch = Epoch;
+ PushEvent(Event, NowMs);
+
+ if (Cause != EVerseFractureCause::Repair && Cause != EVerseFractureCause::Reset && From != EVersePieceState::Repairing
+ && NewState != EVersePieceState::Repairing)
+ {
+ const EVerseFractureNoise Kind = Rules::NoiseKind(Def.Class, Cause, NewState);
+ PushNoise(VerseTags::Noise_Fracture, WorldLocation, FractureLoudness(Kind), NowMs);
+ }
+}
+
+void FVerseDestructionSim::WriteHealth(uint16 PieceIndex)
+{
+ FVersePieceItem& Item = Items[PieceIndex];
+ const float MaxHp = Tuning.ClassRow(Defs[PieceIndex].Class).MaxHp;
+ const uint8 Q = QuantizeHealth(Server[PieceIndex].Hp, MaxHp);
+ if (MaxHp > 0.f && Q != Item.HealthQ)
+ {
+ // Only an HP change of at least one quantum costs bandwidth (destruction.md 3.3).
+ Item.HealthQ = Q;
+ Item.Epoch = Epoch;
+ MarkDirty(PieceIndex);
+ }
+}
+
+void FVerseDestructionSim::CancelRepair(uint16 PieceIndex, EVerseFractureCause Cause, uint8 Instigator, uint32 NowMs)
+{
+ FServerPiece& Piece = Server[PieceIndex];
+ const EVersePieceState Back = Items[PieceIndex].RepairFrom;
+ if (Piece.AssignedDrone != INDEX_NONE)
+ {
+ Recall(Drones[Piece.AssignedDrone], NowMs);
+ Piece.AssignedDrone = INDEX_NONE;
+ }
+ Piece.LastDamageMs = NowMs; // the 60 s restarts
+ Counters.RepairsInterrupted += 1;
+ SetState(PieceIndex, Back, Items[PieceIndex].Variant, Cause, Defs[PieceIndex].Transform.GetLocation(), FVector::ZeroVector, 0.f, 0,
+ Instigator, NowMs);
+}
+
+void FVerseDestructionSim::Recall(FVerseDroneState& Drone, uint32 NowMs)
+{
+ UpdateDroneLocation(Drone, NowMs);
+ Drone.TargetPiece = INDEX_NONE;
+ StartFlight(Drone, Drone.Dock, NowMs);
+ Drone.Task = EVerseDroneTask::Returning;
+}
+
+bool FVerseDestructionSim::ApplyDroneDamage(int32 DroneIndex, float Amount, uint32 NowMs)
+{
+ if (!Drones.IsValidIndex(DroneIndex) || Amount <= 0.f)
+ {
+ return false;
+ }
+ FVerseDroneState& Drone = Drones[DroneIndex];
+ if (Drone.Task == EVerseDroneTask::Down)
+ {
+ return false;
+ }
+ Drone.Hp -= Amount;
+ if (Drone.Hp > 0.f)
+ {
+ return false;
+ }
+ UpdateDroneLocation(Drone, NowMs);
+ const int32 Target = Drone.TargetPiece;
+ Drone.TargetPiece = INDEX_NONE;
+ Drone.Task = EVerseDroneTask::Down;
+ Drone.Generation += 1;
+ if (Target != INDEX_NONE)
+ {
+ Server[Target].AssignedDrone = INDEX_NONE;
+ if (Items[Target].State == EVersePieceState::Repairing)
+ {
+ CancelRepair(uint16(Target), EVerseFractureCause::Bolt, WorldInstigator, NowMs);
+ }
+ else
+ {
+ Server[Target].LastDamageMs = NowMs;
+ }
+ }
+ return true;
+}
+
+void FVerseDestructionSim::StartFlight(FVerseDroneState& Drone, const FVector& To, uint32 NowMs)
+{
+ Drone.FlightFrom = Drone.Location;
+ Drone.FlightTo = To;
+ Drone.FlightStartMs = NowMs;
+ const double Speed = FMath::Max(1.f, Tuning.Start.DroneSpeedCmS);
+ Drone.FlightEndMs = NowMs + uint32(FMath::CeilToInt64(FVector::Dist(Drone.FlightFrom, To) / Speed * 1000.0));
+}
+
+void FVerseDestructionSim::UpdateDroneLocation(FVerseDroneState& Drone, uint32 NowMs) const
+{
+ if (Drone.Task != EVerseDroneTask::Outbound && Drone.Task != EVerseDroneTask::Returning)
+ {
+ return;
+ }
+ const uint32 Span = Drone.FlightEndMs - Drone.FlightStartMs;
+ const double Alpha = Span == 0 ? 1.0 : FMath::Clamp(double(NowMs - Drone.FlightStartMs) / double(Span), 0.0, 1.0);
+ Drone.Location = FMath::Lerp(Drone.FlightFrom, Drone.FlightTo, Alpha);
+}
+
+int32 FVerseDestructionSim::NumActiveDrones() const
+{
+ int32 Count = 0;
+ for (const FVerseDroneState& Drone : Drones)
+ {
+ Count += Drone.IsActive() ? 1 : 0;
+ }
+ return Count;
+}
+
+void FVerseDestructionSim::Tick(uint32 NowMs, FEncroachFn IsEncroached)
+{
+ LastTickMs = NowMs;
+ const uint32 RecheckMs = SecondsToMs(Tuning.RepairEncroachRecheckS);
+ for (FVerseDroneState& Drone : Drones)
+ {
+ UpdateDroneLocation(Drone, NowMs);
+ switch (Drone.Task)
+ {
+ case EVerseDroneTask::Down:
+ // The dock replaces a downed drone; it flies again when a timer fires.
+ Drone.Task = EVerseDroneTask::Docked;
+ Drone.Location = Drone.Dock;
+ Drone.Hp = Tuning.DroneMaxHp;
+ break;
+ case EVerseDroneTask::Outbound:
+ if (NowMs >= Drone.FlightEndMs && Drone.TargetPiece != INDEX_NONE)
+ {
+ const uint16 PieceIndex = uint16(Drone.TargetPiece);
+ FVersePieceItem& Item = Items[PieceIndex];
+ const EVersePieceState From = Item.State;
+ Drone.Task = EVerseDroneTask::Repairing;
+ Drone.RepairEndMs = NowMs + SecondsToMs(Tuning.ClassRow(Defs[PieceIndex].Class).RepairTimeS);
+ Drone.NextEncroachCheckMs = Drone.RepairEndMs;
+ const uint8 Variant = Item.Variant;
+ ensure(From != EVersePieceState::Intact && From != EVersePieceState::Repairing);
+ SetState(PieceIndex, EVersePieceState::Repairing, Variant, EVerseFractureCause::Repair, Drone.Location, FVector::ZeroVector, 0.f, 0,
+ WorldInstigator, NowMs);
+ }
+ break;
+ case EVerseDroneTask::Repairing:
+ if (Drone.TargetPiece != INDEX_NONE && NowMs >= Drone.RepairEndMs && NowMs >= Drone.NextEncroachCheckMs)
+ {
+ const uint16 PieceIndex = uint16(Drone.TargetPiece);
+ const FBox IntactWorld = Defs[PieceIndex].GetWorldBounds(EVersePieceState::Intact, 0).ExpandBy(Tuning.RepairEncroachMarginCm);
+ if (IsEncroached(IntactWorld))
+ {
+ Drone.NextEncroachCheckMs = NowMs + RecheckMs;
+ break;
+ }
+ FServerPiece& Piece = Server[PieceIndex];
+ Piece.Hp = Tuning.ClassRow(Defs[PieceIndex].Class).MaxHp;
+ Piece.AssignedDrone = INDEX_NONE;
+ Piece.bDamagedSinceRepair = false;
+ Piece.HitSumLocal = FVector::ZeroVector;
+ Piece.HitCount = 0;
+ SetState(PieceIndex, EVersePieceState::Intact, 0, EVerseFractureCause::Repair, Drone.Location, FVector::ZeroVector, 0.f, 0,
+ WorldInstigator, NowMs);
+ Items[PieceIndex].HealthQ = 255;
+ Counters.Repairs += 1;
+ Drone.TargetPiece = INDEX_NONE;
+ StartFlight(Drone, Drone.Dock, NowMs);
+ Drone.Task = EVerseDroneTask::Returning;
+ }
+ break;
+ case EVerseDroneTask::Returning:
+ if (NowMs >= Drone.FlightEndMs)
+ {
+ Drone.Task = EVerseDroneTask::Docked;
+ Drone.Location = Drone.Dock;
+ }
+ break;
+ case EVerseDroneTask::Docked:
+ break;
+ }
+ if (Drone.Task != EVerseDroneTask::Docked && NowMs >= Drone.NextNoiseMs)
+ {
+ // Flight and welding are audible to the bot (destruction.md 7 "Noise").
+ PushNoise(VerseTags::Noise_Drone, Drone.Location, DroneLoudness, NowMs);
+ Drone.NextNoiseMs = NowMs + Tuning.Start.DroneNoiseIntervalMs;
+ }
+ }
+ Dispatch(NowMs);
+ Counters.PeakActiveDrones = FMath::Max(Counters.PeakActiveDrones, NumActiveDrones());
+}
+
+void FVerseDestructionSim::Dispatch(uint32 NowMs)
+{
+ const uint32 DelayMs = SecondsToMs(Tuning.RepairDelayS);
+ TArray<uint16> Queue;
+ for (int32 Index = 0; Index < Items.Num(); ++Index)
+ {
+ const EVersePieceState State = Items[Index].State;
+ const FServerPiece& Piece = Server[Index];
+ const bool bBroken = State != EVersePieceState::Intact && State != EVersePieceState::Repairing;
+ const bool bHpOnly = State == EVersePieceState::Intact && Piece.bDamagedSinceRepair;
+ if ((bBroken || bHpOnly) && Piece.AssignedDrone == INDEX_NONE && NowMs - Piece.LastDamageMs >= DelayMs)
+ {
+ Queue.Add(uint16(Index));
+ }
+ }
+ if (Queue.Num() == 0)
+ {
+ return;
+ }
+ // Catwalks, then walls, then glass, then ceiling panels; longest-broken first within a class.
+ Queue.Sort([this](uint16 A, uint16 B)
+ {
+ const int32 PA = VerseRepairClassPriority(Defs[A].Class);
+ const int32 PB = VerseRepairClassPriority(Defs[B].Class);
+ if (PA != PB)
+ {
+ return PA < PB;
+ }
+ if (Server[A].BrokenSinceMs != Server[B].BrokenSinceMs)
+ {
+ return Server[A].BrokenSinceMs < Server[B].BrokenSinceMs;
+ }
+ return A < B;
+ });
+ for (const uint16 PieceIndex : Queue)
+ {
+ if (NumActiveDrones() >= Tuning.MaxActiveDrones)
+ {
+ return;
+ }
+ const FVector Target = Defs[PieceIndex].GetWorldBounds(EVersePieceState::Intact, 0).GetCenter();
+ int32 Best = INDEX_NONE;
+ double BestDistSq = TNumericLimits<double>::Max();
+ for (FVerseDroneState& Drone : Drones)
+ {
+ if (!Drone.IsFree())
+ {
+ continue;
+ }
+ const double DistSq = FVector::DistSquared(Drone.Location, Target);
+ if (DistSq < BestDistSq)
+ {
+ BestDistSq = DistSq;
+ Best = Drone.Index;
+ }
+ }
+ if (Best == INDEX_NONE)
+ {
+ return;
+ }
+ FVerseDroneState& Drone = Drones[Best];
+ Drone.TargetPiece = PieceIndex;
+ StartFlight(Drone, Target, NowMs);
+ Drone.Task = EVerseDroneTask::Outbound;
+ Server[PieceIndex].AssignedDrone = Best;
+ }
+}
+
+void FVerseDestructionSim::FullReset(uint32 NowMs)
+{
+ Epoch = uint16(Epoch + 1);
+ int32 Written = 0;
+ for (int32 Index = 0; Index < Items.Num(); ++Index)
+ {
+ FVersePieceItem& Item = Items[Index];
+ FServerPiece& Piece = Server[Index];
+ const float MaxHp = Tuning.ClassRow(Defs[Index].Class).MaxHp;
+ const bool bChanged = Item.State != EVersePieceState::Intact || Item.HealthQ != 255 || Item.Variant != 0;
+ const EVersePieceState OldProxy = Item.GetProxyState();
+ const uint8 OldVariant = Item.Variant;
+ Piece = FServerPiece();
+ Piece.Hp = MaxHp;
+ if (!bChanged)
+ {
+ continue; // untouched items cost nothing in the reset burst
+ }
+ Item.State = EVersePieceState::Intact;
+ Item.HealthQ = 255;
+ Item.Variant = 0;
+ Item.RepairFrom = EVersePieceState::Intact;
+ // An Intact piece carries no fracture record, so the reset item packs small.
+ Item.LastSeed = 0;
+ FMemory::Memzero(Item.LastImpulse, sizeof(Item.LastImpulse));
+ FMemory::Memzero(Item.LastLocation, sizeof(Item.LastLocation));
+ Item.StateTimeMs = NowMs;
+ Item.Epoch = Epoch;
+ MarkDirty(uint16(Index));
+ MarkNav(uint16(Index), OldProxy, OldVariant);
+ ++Written;
+ }
+ for (FVerseDroneState& Drone : Drones)
+ {
+ if (Drone.Task == EVerseDroneTask::Outbound || Drone.Task == EVerseDroneTask::Repairing)
+ {
+ Recall(Drone, NowMs);
+ }
+ }
+ // Every changed piece marked its tiles dirty above; the queue rebuilds them (destruction.md 11).
+ // The burst is what the fast array sends: its header, then element id and packed item per write.
+ LastResetBurstBytes = Written > 0 ? FVersePieceItem::FastArrayHeaderBytes : 0;
+ for (const uint16 Index : Dirty)
+ {
+ LastResetBurstBytes += FVersePieceItem::FastArrayItemIdBytes + FVersePieceItem::MeasureWireBytes(Items[Index]);
+ }
+ Deferred.Reset();
+
+ FVerseFractureEvent Event;
+ Event.PieceIndex = AllPieces;
+ Event.FromState = EVersePieceState::Intact;
+ Event.ToState = EVersePieceState::Intact;
+ Event.Cause = EVerseFractureCause::Reset;
+ Event.Instigator = WorldInstigator;
+ Event.ServerTimeMs = NowMs;
+ Event.Epoch = Epoch;
+ // A reset clears whatever this tick held: no stale piece event may follow it.
+ Events.Reset();
+ EventOfPiece.Reset();
+ PushEvent(Event, NowMs);
+}
+
+void FVerseDestructionSim::PushEvent(const FVerseFractureEvent& Event, uint32 NowMs)
+{
+ if (EventTickMs != NowMs)
+ {
+ EventTickMs = NowMs;
+ EventOfPiece.Reset();
+ }
+ if (Tuning.Start.bCoalescePerTick && Event.PieceIndex != AllPieces)
+ {
+ if (const int32* Existing = EventOfPiece.Find(Event.PieceIndex))
+ {
+ // One event per piece per tick: keep the first FromState, take everything else from the latest.
+ FVersePendingFracture& Pending = Events[*Existing];
+ const EVersePieceState From = Pending.Event.FromState;
+ Pending.Event = Event;
+ Pending.Event.FromState = From;
+ Counters.EventsCoalesced += 1;
+ return;
+ }
+ }
+ FVersePendingFracture& Pending = Events.AddDefaulted_GetRef();
+ Pending.Event = Event;
+ // Multicast rate cap: at most N per sliding second; the fast array stays the truth.
+ while (MulticastTimesMs.Num() > 0 && NowMs - MulticastTimesMs[0] >= 1000)
+ {
+ MulticastTimesMs.RemoveAt(0, 1, EAllowShrinking::No);
+ }
+ Pending.bMulticast = Event.PieceIndex == AllPieces || MulticastTimesMs.Num() < Tuning.MaxFractureEventsPerSecond;
+ if (Pending.bMulticast)
+ {
+ Deferred.Remove(Event.PieceIndex); // a newer event of the piece supersedes a waiting one
+ MulticastTimesMs.Add(NowMs);
+ Counters.PeakEventsPerSecond = FMath::Max(Counters.PeakEventsPerSecond, MulticastTimesMs.Num());
+ }
+ else
+ {
+ // Over the cap: published locally now, multicast later once the window has room,
+ // coalesced per piece (destruction.md 4). The fast array stays the truth meanwhile.
+ Counters.EventsOverRate += 1;
+ if (FVerseFractureEvent* Waiting = Deferred.Find(Event.PieceIndex))
+ {
+ const EVersePieceState From = Waiting->FromState;
+ *Waiting = Event;
+ Waiting->FromState = From;
+ }
+ else
+ {
+ Deferred.Add(Event.PieceIndex, Event);
+ }
+ }
+ if (Event.PieceIndex != AllPieces)
+ {
+ EventOfPiece.Add(Event.PieceIndex, Events.Num() - 1);
+ }
+}
+
+void FVerseDestructionSim::PushNoise(const FGameplayTag& Tag, const FVector& Location, float Loudness, uint32 NowMs)
+{
+ FVerseNoiseEvent& Event = Noise.AddDefaulted_GetRef();
+ Event.Noise = Tag;
+ Event.SourceId = -1;
+ Event.Location = Location;
+ Event.Loudness = Loudness;
+ Event.ServerTime = float(NowMs) / 1000.f;
+}
+
+void FVerseDestructionSim::MarkDirty(uint16 PieceIndex)
+{
+ Dirty.Add(PieceIndex);
+}
+
+void FVerseDestructionSim::MarkNav(uint16 PieceIndex, EVersePieceState OldState, uint8 OldVariant)
+{
+ const FVersePieceDef& Def = Defs[PieceIndex];
+ const FVersePieceItem& Item = Items[PieceIndex];
+ const FBox Old = Def.GetWorldBounds(OldState, OldVariant);
+ const FBox New = Def.GetWorldBounds(Item.GetProxyState(), Item.Variant);
+ Nav.MarkDirty(Old, PieceIndex);
+ Nav.MarkDirty(New, PieceIndex);
+ if (!Old.IsValid && !New.IsValid)
+ {
+ Nav.MarkDirty(Def.GetWorldBounds(EVersePieceState::Intact, 0), PieceIndex);
+ }
+}
+
+TArray<FVersePendingFracture> FVerseDestructionSim::DrainEvents()
+{
+ // Deferred over-rate events go out as soon as the sliding second has room; one older than
+ // a second is dropped (the item has long arrived), and so is one of an old epoch.
+ if (Deferred.Num() > 0)
+ {
+ const uint32 NowMs = FMath::Max(EventTickMs, LastTickMs);
+ while (MulticastTimesMs.Num() > 0 && NowMs - MulticastTimesMs[0] >= 1000)
+ {
+ MulticastTimesMs.RemoveAt(0, 1, EAllowShrinking::No);
+ }
+ for (auto It = Deferred.CreateIterator(); It; ++It)
+ {
+ const FVerseFractureEvent& Waiting = It.Value();
+ if (Waiting.Epoch != Epoch || NowMs - Waiting.ServerTimeMs >= 1000)
+ {
+ Counters.EventsDeferredDropped += 1;
+ It.RemoveCurrent();
+ continue;
+ }
+ if (MulticastTimesMs.Num() >= Tuning.MaxFractureEventsPerSecond)
+ {
+ break;
+ }
+ FVersePendingFracture& Late = Events.AddDefaulted_GetRef();
+ Late.Event = Waiting;
+ Late.bMulticast = true;
+ Late.bPublishLocal = false; // published on the server when it happened
+ MulticastTimesMs.Add(NowMs);
+ Counters.PeakEventsPerSecond = FMath::Max(Counters.PeakEventsPerSecond, MulticastTimesMs.Num());
+ Counters.EventsDeferredSent += 1;
+ It.RemoveCurrent();
+ }
+ }
+ for (const FVersePendingFracture& Pending : Events)
+ {
+ Counters.EventsPublished += Pending.bPublishLocal ? 1 : 0;
+ Counters.EventsMulticast += Pending.bMulticast ? 1 : 0;
+ }
+ EventOfPiece.Reset();
+ return MoveTemp(Events);
+}
+
+TArray<FVerseNoiseEvent> FVerseDestructionSim::DrainNoise()
+{
+ return MoveTemp(Noise);
+}
+
+TArray<uint16> FVerseDestructionSim::DrainDirtyItems()
+{
+ TArray<uint16> Out = Dirty.Array();
+ Out.Sort();
+ Counters.ItemWrites += Out.Num();
+ Dirty.Reset();
+ return Out;
+}
+
+FBox FVerseDestructionSim::GetPieceBounds(uint16 PieceIndex) const
+{
+ if (!IsValidPiece(PieceIndex))
+ {
+ return FBox(ForceInit);
+ }
+ const FVersePieceItem& Item = Items[PieceIndex];
+ return Defs[PieceIndex].GetWorldBounds(Item.GetProxyState(), Item.Variant);
+}
+
+TArray<uint16> FVerseDestructionSim::GetPiecesInBox(const FBox& WorldBox) const
+{
+ TArray<uint16> Out;
+ for (int32 Index = 0; Index < Defs.Num(); ++Index)
+ {
+ // Pieces are found by their Intact footprint, so a destroyed piece is still listed.
+ if (Defs[Index].GetWorldBounds(EVersePieceState::Intact, 0).Intersect(WorldBox))
+ {
+ Out.Add(uint16(Index));
+ }
+ }
+ return Out;
+}
+
+TArray<FVersePieceNavLink> FVerseDestructionSim::GetLiveNavLinks(uint16 PieceIndex, EVersePieceNavLinkKind& OutKind) const
+{
+ TArray<FVersePieceNavLink> Out;
+ if (!IsValidPiece(PieceIndex))
+ {
+ return Out;
+ }
+ const FVersePieceDef& Def = Defs[PieceIndex];
+ const EVersePieceState State = Items[PieceIndex].GetProxyState();
+ const TArray<FVersePieceNavLink>* Source = nullptr;
+ if (State == EVersePieceState::Breached)
+ {
+ OutKind = EVersePieceNavLinkKind::Mantle;
+ Source = &Def.MantleLinks;
+ }
+ else if (State == EVersePieceState::Destroyed)
+ {
+ OutKind = EVersePieceNavLinkKind::Drop;
+ Source = &Def.DropLinks;
+ }
+ if (Source)
+ {
+ for (const FVersePieceNavLink& Link : *Source)
+ {
+ FVersePieceNavLink World;
+ World.Start = Def.Transform.TransformPosition(Link.Start);
+ World.End = Def.Transform.TransformPosition(Link.End);
+ Out.Add(World);
+ }
+ }
+ return Out;
+}
+
+uint32 FVerseDestructionSim::ProxyHash(TConstArrayView<FVersePieceItem> InItems)
+{
+ uint32 Hash = 0x9E3779B9u;
+ for (const FVersePieceItem& Item : InItems)
+ {
+ const uint8 Bytes[4] = {uint8(Item.PieceIndex & 0xFF), uint8(Item.PieceIndex >> 8), uint8(Item.GetProxyState()), Item.Variant};
+ Hash = FCrc::MemCrc32(Bytes, sizeof(Bytes), Hash);
+ }
+ return Hash;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceManifest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceManifest.cpp
new file mode 100644
index 0000000000..d5113adb1f
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceManifest.cpp
@@ -0,0 +1,90 @@
+#include "Pieces/VersePieceManifest.h"
+
+#include "Algo/BinarySearch.h"
+#include "EngineUtils.h"
+#include "Pieces/VerseDestructible.h"
+
+void UVersePieceManifest::SortGuids(TArray<FGuid>& Guids)
+{
+ Guids.Sort([](const FGuid& A, const FGuid& B) { return A < B; });
+}
+
+uint32 UVersePieceManifest::ComputeHash(TConstArrayView<FGuid> Guids)
+{
+ uint32 Crc = 0;
+ for (const FGuid& Guid : Guids)
+ {
+ const uint32 Words[4] = {Guid.A, Guid.B, Guid.C, Guid.D};
+ Crc = FCrc::MemCrc32(Words, sizeof(Words), Crc);
+ }
+ return Crc ^ uint32(Guids.Num());
+}
+
+bool UVersePieceManifest::Build(TArray<FGuid> Guids, FString* OutError)
+{
+ for (const FGuid& Guid : Guids)
+ {
+ if (!Guid.IsValid())
+ {
+ if (OutError)
+ {
+ *OutError = TEXT("a destructible has no valid GUID");
+ }
+ return false;
+ }
+ }
+ SortGuids(Guids);
+ const int32 Before = Guids.Num();
+ for (int32 Index = Guids.Num() - 1; Index > 0; --Index)
+ {
+ if (Guids[Index] == Guids[Index - 1])
+ {
+ Guids.RemoveAt(Index);
+ }
+ }
+ if (Guids.Num() != Before && OutError)
+ {
+ *OutError = FString::Printf(TEXT("%d duplicate GUIDs dropped"), Before - Guids.Num());
+ }
+ if (Guids.Num() > MaxPieces)
+ {
+ if (OutError)
+ {
+ *OutError = FString::Printf(TEXT("%d pieces, the limit is %d per deck"), Guids.Num(), MaxPieces);
+ }
+ return false;
+ }
+ PieceGuids = MoveTemp(Guids);
+ Hash = ComputeHash(PieceGuids);
+ return true;
+}
+
+int32 UVersePieceManifest::IndexOf(const FGuid& Guid) const
+{
+ const int32 Index = Algo::LowerBound(PieceGuids, Guid, [](const FGuid& A, const FGuid& B) { return A < B; });
+ return (PieceGuids.IsValidIndex(Index) && PieceGuids[Index] == Guid) ? Index : INDEX_NONE;
+}
+
+bool UVersePieceManifest::IsConsistent() const
+{
+ for (int32 Index = 1; Index < PieceGuids.Num(); ++Index)
+ {
+ if (!(PieceGuids[Index - 1] < PieceGuids[Index]))
+ {
+ return false;
+ }
+ }
+ return PieceGuids.Num() <= MaxPieces && Hash == ComputeHash(PieceGuids);
+}
+
+#if WITH_EDITOR
+TArray<FGuid> UVersePieceManifest::CollectFromWorld(const UWorld& World)
+{
+ TArray<FGuid> Out;
+ for (TActorIterator<AVerseDestructible> It(&World); It; ++It)
+ {
+ Out.Add(It->GetPieceGuid());
+ }
+ return Out;
+}
+#endif
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceRules.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceRules.cpp
new file mode 100644
index 0000000000..eebda5bbe1
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceRules.cpp
@@ -0,0 +1,134 @@
+#include "Pieces/VersePieceRules.h"
+
+namespace Verse::Destruction::Rules
+{
+ namespace
+ {
+ EVersePieceState Max(EVersePieceState A, EVersePieceState B)
+ {
+ return uint8(A) >= uint8(B) ? A : B;
+ }
+ }
+
+ bool IsForward(EVersePieceState From, EVersePieceState To)
+ {
+ if (From == EVersePieceState::Repairing || To == EVersePieceState::Repairing)
+ {
+ return false;
+ }
+ return uint8(To) >= uint8(From);
+ }
+
+ FOutcome Apply(const FVersePieceClassTuning& Row, EVersePieceState State, float Hp, EVerseFractureCause Cause,
+ EHitRole Role, float Amount)
+ {
+ FOutcome Out{State, Hp};
+ if (State == EVersePieceState::Destroyed || State == EVersePieceState::Repairing)
+ {
+ return Out;
+ }
+ if (Row.Material == EVersePenetrationMaterial::Concrete || Row.Material == EVersePenetrationMaterial::ArmorSteel)
+ {
+ return Out; // DR4
+ }
+ const bool bWall = Row.bBreachedByCharge;
+
+ switch (Cause)
+ {
+ case EVerseFractureCause::Bolt:
+ {
+ if (Row.MaxHp <= 0.f)
+ {
+ return Out; // catwalk: bolts pass or scorch, never change state
+ }
+ Out.Hp = FMath::Max(0.f, Hp - FMath::Max(0.f, Amount));
+ EVersePieceState Next = State;
+ if (Next == EVersePieceState::Intact && Row.bDamagedOnFirstHit)
+ {
+ Next = EVersePieceState::Damaged;
+ }
+ if (Row.HoledAtOrBelowHp >= 0.f && Out.Hp <= Row.HoledAtOrBelowHp)
+ {
+ Next = Max(Next, EVersePieceState::Holed); // bullets never take a wall past Holed
+ }
+ if (Row.bDestroyedAtZeroHp && Out.Hp <= 0.f)
+ {
+ Next = EVersePieceState::Destroyed;
+ }
+ Out.State = Max(State, Next);
+ return Out;
+ }
+ case EVerseFractureCause::Melee:
+ {
+ if (!Row.bDestroyedByMeleeWhenDamaged)
+ {
+ return Out; // melee changes only glass
+ }
+ if (State == EVersePieceState::Damaged)
+ {
+ Out.State = EVersePieceState::Destroyed;
+ Out.Hp = 0.f;
+ return Out;
+ }
+ if (State != EVersePieceState::Intact)
+ {
+ return Out; // glass has no Holed or Breached state; never move back
+ }
+ Out.Hp = FMath::Max(0.f, Hp - FMath::Max(0.f, Amount));
+ Out.State = (Row.bDestroyedAtZeroHp && Out.Hp <= 0.f) ? EVersePieceState::Destroyed : EVersePieceState::Damaged;
+ return Out;
+ }
+ case EVerseFractureCause::Breach:
+ {
+ if (Role == EHitRole::BreachSide)
+ {
+ if (bWall)
+ {
+ Out.State = Max(State, EVersePieceState::Holed);
+ Out.Hp = Row.HoledAtOrBelowHp >= 0.f ? FMath::Min(Hp, Row.HoledAtOrBelowHp) : Hp;
+ }
+ else if (Row.bDestroyedAtZeroHp)
+ {
+ Out.State = EVersePieceState::Destroyed; // glass, ceiling
+ Out.Hp = 0.f;
+ }
+ return Out; // catwalks only break as the target
+ }
+ if (Row.bBreachedByCharge)
+ {
+ Out.State = Max(State, EVersePieceState::Breached);
+ Out.Hp = Row.HoledAtOrBelowHp >= 0.f ? FMath::Min(Hp, Row.HoledAtOrBelowHp) : Hp;
+ }
+ else if (Row.bDestroyedByCharge)
+ {
+ Out.State = EVersePieceState::Destroyed;
+ Out.Hp = 0.f;
+ }
+ return Out;
+ }
+ case EVerseFractureCause::Repair:
+ case EVerseFractureCause::Reset:
+ return Out; // never damage causes
+ }
+ return Out;
+ }
+
+ EVerseFractureNoise NoiseKind(EVersePieceClass Class, EVerseFractureCause Cause, EVersePieceState To)
+ {
+ if (Cause == EVerseFractureCause::Breach)
+ {
+ return EVerseFractureNoise::Breach;
+ }
+ switch (Class)
+ {
+ case EVersePieceClass::GlassPane:
+ return EVerseFractureNoise::Glass;
+ case EVersePieceClass::CeilingPanel:
+ return To == EVersePieceState::Destroyed ? EVerseFractureNoise::Tile : EVerseFractureNoise::BoltHole;
+ case EVersePieceClass::CatwalkSegment:
+ return EVerseFractureNoise::Breach;
+ default:
+ return To == EVersePieceState::Damaged ? EVerseFractureNoise::BoltHole : EVerseFractureNoise::WallBreak;
+ }
+ }
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceTypes.cpp b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceTypes.cpp
new file mode 100644
index 0000000000..6fb863e68a
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Pieces/VersePieceTypes.cpp
@@ -0,0 +1,155 @@
+#include "Pieces/VersePieceTypes.h"
+
+FBox FVersePieceDef::GetLocalBounds(EVersePieceState State, uint8 Variant) const
+{
+ switch (State)
+ {
+ case EVersePieceState::Intact:
+ case EVersePieceState::Damaged:
+ return IntactBounds;
+ case EVersePieceState::Holed:
+ return HoledBounds.IsValidIndex(Variant) ? HoledBounds[Variant] : (HoledBounds.Num() > 0 ? HoledBounds[0] : IntactBounds);
+ case EVersePieceState::Breached:
+ return BreachedBounds.IsValidIndex(Variant) ? BreachedBounds[Variant] : (BreachedBounds.Num() > 0 ? BreachedBounds[0] : IntactBounds);
+ case EVersePieceState::Destroyed:
+ return RemainsBounds;
+ case EVersePieceState::Repairing:
+ // The caller resolves Repairing to RepairFrom; on its own it has the Intact footprint.
+ return IntactBounds;
+ }
+ return IntactBounds;
+}
+
+FBox FVersePieceDef::GetWorldBounds(EVersePieceState State, uint8 Variant) const
+{
+ const FBox Local = GetLocalBounds(State, Variant);
+ return Local.IsValid ? Local.TransformBy(Transform) : FBox(ForceInit);
+}
+
+uint8 FVersePieceDef::NearestVariant(TConstArrayView<FVector> Centroids, const FVector& LocalPoint)
+{
+ uint8 Best = 0;
+ double BestDistSq = TNumericLimits<double>::Max();
+ for (int32 Index = 0; Index < Centroids.Num() && Index < 4; ++Index)
+ {
+ const double DistSq = FVector::DistSquared(Centroids[Index], LocalPoint);
+ if (DistSq < BestDistSq)
+ {
+ BestDistSq = DistSq;
+ Best = uint8(Index);
+ }
+ }
+ return Best;
+}
+
+bool FVersePieceDef::IsWithinRadius(const FVector& WorldPoint, float RadiusCm) const
+{
+ const FVector Local = Transform.InverseTransformPosition(WorldPoint);
+ const double RadiusSq = double(RadiusCm) * RadiusCm;
+ if (ProxyVertices.Num() > 0)
+ {
+ for (const FVector& Vertex : ProxyVertices)
+ {
+ if (FVector::DistSquared(Vertex, Local) <= RadiusSq)
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+ // No vertex list: the eight corners of the Intact proxy box are its vertices.
+ if (!IntactBounds.IsValid)
+ {
+ return false;
+ }
+ for (int32 Corner = 0; Corner < 8; ++Corner)
+ {
+ const FVector Vertex((Corner & 1) ? IntactBounds.Max.X : IntactBounds.Min.X,
+ (Corner & 2) ? IntactBounds.Max.Y : IntactBounds.Min.Y,
+ (Corner & 4) ? IntactBounds.Max.Z : IntactBounds.Min.Z);
+ if (FVector::DistSquared(Vertex, Local) <= RadiusSq)
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+int32 VerseRepairClassPriority(EVersePieceClass Class)
+{
+ switch (Class)
+ {
+ case EVersePieceClass::CatwalkSegment:
+ return 0;
+ case EVersePieceClass::WallPanel:
+ case EVersePieceClass::CladdingWall:
+ case EVersePieceClass::ContainerWall:
+ return 1;
+ case EVersePieceClass::GlassPane:
+ return 2;
+ case EVersePieceClass::CeilingPanel:
+ return 3;
+ }
+ return 4;
+}
+
+EVersePenetrationMaterial VerseMaterialOfClass(EVersePieceClass Class)
+{
+ switch (Class)
+ {
+ case EVersePieceClass::WallPanel:
+ return EVersePenetrationMaterial::SheetMetal;
+ case EVersePieceClass::CladdingWall:
+ return EVersePenetrationMaterial::CladdingPanel;
+ case EVersePieceClass::ContainerWall:
+ return EVersePenetrationMaterial::ContainerWall;
+ case EVersePieceClass::GlassPane:
+ return EVersePenetrationMaterial::Glass;
+ case EVersePieceClass::CatwalkSegment:
+ return EVersePenetrationMaterial::CatwalkGrating;
+ case EVersePieceClass::CeilingPanel:
+ return EVersePenetrationMaterial::CeilingPanel;
+ }
+ return EVersePenetrationMaterial::Concrete;
+}
+
+bool VerseMaterialNeverBreaks(EVersePenetrationMaterial Material)
+{
+ return Material == EVersePenetrationMaterial::Concrete || Material == EVersePenetrationMaterial::ArmorSteel;
+}
+
+FVerseDestructionSimTuning FVerseDestructionSimTuning::Contract()
+{
+ return FromAsset(*GetDefault<UVerseDestructionTuning>());
+}
+
+FVerseDestructionSimTuning FVerseDestructionSimTuning::FromAsset(const UVerseDestructionTuning& Asset)
+{
+ FVerseDestructionSimTuning Out;
+ Out.Classes = Asset.Classes;
+ for (const TPair<EVersePieceClass, FVersePieceClassTuning>& Row : UVerseDestructionTuning::MakeContractClasses())
+ {
+ // A class missing from a hand-edited asset falls back to the contract row.
+ if (!Out.Classes.Contains(Row.Key))
+ {
+ Out.Classes.Add(Row.Key, Row.Value);
+ }
+ }
+ Out.BreachSideRadiusCm = Asset.BreachSideRadiusCm;
+ Out.RepairDelayS = Asset.RepairDelayS;
+ Out.MaxActiveDrones = Asset.MaxActiveDrones;
+ Out.DroneMaxHp = Asset.DroneMaxHp;
+ Out.RepairEncroachMarginCm = Asset.RepairEncroachMarginCm;
+ Out.RepairEncroachRecheckS = Asset.RepairEncroachRecheckS;
+ Out.NavDirtyMarginCm = Asset.NavDirtyMarginCm;
+ Out.NavMaxTilesInFlight = Asset.NavMaxTilesInFlight;
+ Out.MaxFractureEventsPerSecond = Asset.MaxFractureEventsPerSecond;
+ return Out;
+}
+
+const FVersePieceClassTuning& FVerseDestructionSimTuning::ClassRow(EVersePieceClass Class) const
+{
+ static const FVersePieceClassTuning Empty;
+ const FVersePieceClassTuning* Row = Classes.Find(Class);
+ return Row ? *Row : Empty;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Repair/VerseRepairDrone.cpp b/unreal/Verse/Source/VerseDestruction/Private/Repair/VerseRepairDrone.cpp
new file mode 100644
index 0000000000..b00b90136f
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Repair/VerseRepairDrone.cpp
@@ -0,0 +1,78 @@
+#include "Repair/VerseRepairDrone.h"
+
+#include "Components/BoxComponent.h"
+#include "Components/StaticMeshComponent.h"
+#include "Net/UnrealNetwork.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "VerseCollision.h"
+
+AVerseRepairDrone::AVerseRepairDrone()
+{
+ PrimaryActorTick.bCanEverTick = false;
+ bReplicates = true;
+ SetReplicatingMovement(true);
+ bAlwaysRelevant = true;
+
+ HitBox = CreateDefaultSubobject<UBoxComponent>(TEXT("HitBox"));
+ HitBox->SetBoxExtent(FVector(30.f, 30.f, 15.f));
+ // Its own hit box on the bolt channel: stops bolts, never blocks or harms pawns (destruction.md 7).
+ HitBox->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
+ HitBox->SetCollisionObjectType(ECC_WorldDynamic);
+ HitBox->SetCollisionResponseToAllChannels(ECR_Ignore);
+ HitBox->SetCollisionResponseToChannel(VerseCollision::Bolt, ECR_Block);
+ HitBox->SetCanEverAffectNavigation(false);
+ SetRootComponent(HitBox);
+
+ Body = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Body"));
+ Body->SetupAttachment(HitBox);
+ Body->SetCollisionProfileName(VerseCollision::Profile::NoCollision);
+ Body->SetCanEverAffectNavigation(false);
+}
+
+void AVerseRepairDrone::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ DOREPLIFETIME(AVerseRepairDrone, DroneIndex);
+ DOREPLIFETIME(AVerseRepairDrone, Task);
+ DOREPLIFETIME(AVerseRepairDrone, Generation);
+ DOREPLIFETIME(AVerseRepairDrone, Hp);
+}
+
+float AVerseRepairDrone::TakeDamage(float DamageAmount, const FDamageEvent& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
+{
+ if (!HasAuthority() || DamageAmount <= 0.f)
+ {
+ return 0.f;
+ }
+ if (AVerseDestructionManager* Manager = AVerseDestructionManager::Get(this))
+ {
+ Manager->ApplyDroneDamage(DroneIndex, DamageAmount);
+ }
+ return DamageAmount; // no score, no XP (destruction.md 7)
+}
+
+void AVerseRepairDrone::SyncFromSim(const FVector& Location, uint8 InTask, uint32 InGeneration, float InHp)
+{
+ SetActorLocation(Location);
+ Hp = InHp;
+ if (Generation != InGeneration)
+ {
+ Generation = InGeneration;
+ OnRep_Generation();
+ }
+ if (Task != InTask)
+ {
+ Task = InTask;
+ OnRep_Task();
+ }
+}
+
+void AVerseRepairDrone::OnRep_Task()
+{
+ OnTaskChanged(Task);
+}
+
+void AVerseRepairDrone::OnRep_Generation()
+{
+ OnShotDown();
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionDeterminismTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionDeterminismTest.cpp
new file mode 100644
index 0000000000..76f92fdb1e
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionDeterminismTest.cpp
@@ -0,0 +1,248 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "Pieces/VersePieceManifest.h"
+
+namespace VerseDestructionTest
+{
+ /** Defined in VerseDestructionStormTest.cpp: runs destruction_storm and returns its hashes. */
+ uint32 StormFinalHash(int32 DurationS, uint64 Seed, TArray<uint32>& OutPerSecond);
+}
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ /**
+ * Stand-in for WP03's hole store (WP03 owns holes): a bolt into a wall piece that is still
+ * Intact or Damaged leaves a hole record; a fracture event to Holed or beyond, a repair and
+ * a reset clear the piece's records (destruction.md 5). Replicated like the items.
+ */
+ struct FStubHoles
+ {
+ TMap<uint16, TArray<uint32>> ByPiece;
+
+ uint32 Hash(uint16 PieceIndex) const
+ {
+ uint32 H = 0x9E3779B9u ^ PieceIndex;
+ if (const TArray<uint32>* Holes = ByPiece.Find(PieceIndex))
+ {
+ for (const uint32 Hole : *Holes)
+ {
+ H = HashCombineFast(H, Hole);
+ }
+ }
+ return H;
+ }
+ };
+
+ /** One client: its own world, the piece actors and a client manager fed through the fast-array path. */
+ struct FClient
+ {
+ TUniquePtr<FTestWorld> World;
+ AVerseDestructionManager* Manager = nullptr;
+ FStubHoles Holes;
+
+ FClient(const TCHAR* Name, const TArray<FVersePieceDef>& Defs, UVersePieceManifest* Manifest, TConstArrayView<FVersePieceItem> Initial)
+ {
+ World = MakeUnique<FTestWorld>(Name);
+ for (const FVersePieceDef& Def : Defs)
+ {
+ World->SpawnPiece(Def);
+ }
+ Manager = World->SpawnManager(true, 0, Manifest);
+ Manager->ReceiveItemsForTest(Initial, true); // the join: the whole fast array once
+ }
+
+ void Deliver(uint16 Index, const FVersePieceItem& Item, const FStubHoles& ServerHoles)
+ {
+ Manager->ReceiveItemsForTest(MakeArrayView(&Item, 1), false);
+ if (const TArray<uint32>* Server = ServerHoles.ByPiece.Find(Index))
+ {
+ Holes.ByPiece.Add(Index, *Server);
+ }
+ else
+ {
+ Holes.ByPiece.Remove(Index);
+ }
+ }
+
+ /** What the client shows and answers for a piece: query state, item variant, actor look, holes. */
+ uint32 PieceHash(uint16 Index) const
+ {
+ const FVersePieceItem* Item = Manager->FindItem(Index);
+ const AVerseDestructible* Actor = Manager->GetPieceActor(Index);
+ uint32 H = uint32(Manager->GetPieceState(Index));
+ H = HashCombineFast(H, Item ? uint32(Item->Variant) : 0xFFu);
+ H = HashCombineFast(H, Actor ? uint32(Actor->GetPresentedState()) : 0xFFu);
+ H = HashCombineFast(H, Actor ? uint32(Actor->GetPresentedVariant()) : 0xFFu);
+ return HashCombineFast(H, Holes.Hash(Index));
+ }
+ };
+
+ uint32 ServerPieceHash(const FVerseDestructionSim& Sim, const FStubHoles& Holes, uint16 Index)
+ {
+ const FVersePieceItem& Item = Sim.GetItem(Index);
+ uint32 H = uint32(Item.State);
+ H = HashCombineFast(H, uint32(Item.Variant));
+ H = HashCombineFast(H, uint32(Item.State)); // the server's actor shows the item's state
+ H = HashCombineFast(H, uint32(Item.Variant));
+ return HashCombineFast(H, Holes.Hash(Index));
+ }
+
+ bool IsWall(EVersePieceClass Class)
+ {
+ return Class == EVersePieceClass::WallPanel || Class == EVersePieceClass::CladdingWall || Class == EVersePieceClass::ContainerWall;
+ }
+}
+
+// A6.7 (local part): a 10-minute destruction storm; two client managers in their own worlds get
+// the item writes through the fast-array callback path, client 1 one tick late, client 2 losing
+// 25 % of the sends (a lost item goes again with its latest value, fast array semantics); the
+// unreliable events are not delivered at all. Every second each client's query state, item
+// variant, actor look and hole set is compared with the server for every piece that has not
+// changed for one second; nothing is flushed before comparing. The multi-process run on the WP10
+// netcode runner is still open.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionDeterminism, "Verse.Destruction.Determinism", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionDeterminism::RunTest(const FString&)
+{
+ const TArray<FVersePieceDef> Defs = MakeArena();
+ FVerseDestructionSim Sim;
+ Sim.Init(Defs, FVerseDestructionSimTuning::Contract(), Docks(4), 0xD7);
+ UVersePieceManifest* Manifest = NewObject<UVersePieceManifest>();
+ for (const FVersePieceDef& Def : Defs)
+ {
+ Manifest->PieceGuids.Add(Def.Guid); // the server's index order
+ }
+ FClient Late(TEXT("VerseDeterminismLate"), Defs, Manifest, Sim.GetItems());
+ FClient Lossy(TEXT("VerseDeterminismLossy"), Defs, Manifest, Sim.GetItems());
+ if (!TestEqual(TEXT("client manager has every piece"), Late.Manager->NumPieces(), Defs.Num()))
+ {
+ return false;
+ }
+ FStubHoles ServerHoles;
+ TArray<uint32> LastChangeMs;
+ LastChangeMs.Init(0, Defs.Num());
+ TArray<uint16> LateQueue;
+ TSet<uint16> LossyPending;
+ FVerseRng Net(0xD7, 1, EVerseRngSalt::Harness);
+ FVerseRng Rng(0xD7, 2, EVerseRngSalt::Harness);
+ int32 Seconds = 0;
+ int64 Compared = 0;
+ int32 Mismatches = 0;
+ int32 HoleRecords = 0;
+ int32 Wave = 0;
+ uint32 NextSecond = 1000;
+ const uint32 EndMs = 600 * 1000;
+ auto Shoot = [&](const FVersePieceDamage& D, uint32 Now)
+ {
+ const EVersePieceState Before = Sim.GetItem(D.PieceIndex).State;
+ Sim.ApplyDamage(D, Now);
+ if (D.Cause == EVerseFractureCause::Bolt && IsWall(Sim.GetDef(D.PieceIndex).Class)
+ && (Before == EVersePieceState::Intact || Before == EVersePieceState::Damaged)
+ && (Sim.GetItem(D.PieceIndex).State == EVersePieceState::Intact || Sim.GetItem(D.PieceIndex).State == EVersePieceState::Damaged))
+ {
+ ServerHoles.ByPiece.FindOrAdd(D.PieceIndex).Add(GetTypeHash(D.Location));
+ LastChangeMs[D.PieceIndex] = Now;
+ LateQueue.AddUnique(D.PieceIndex);
+ ++HoleRecords;
+ }
+ };
+ for (uint32 Now = 0; Now < EndMs; Now += TickMs)
+ {
+ if (Now >= uint32(Wave) * 2000)
+ {
+ const int32 Row = Wave % 30;
+ for (int32 Charge = 0; Charge < 2; ++Charge)
+ {
+ const uint16 Target = uint16(Row * 10 + Rng.RangeInt(0, 7));
+ FVersePieceDamage D = Breach(Sim.GetDef(Target), FVector(Rng.Range(-80, 80), -5, Rng.Range(30, 150)));
+ D.PieceIndex = Target;
+ Shoot(D, Now);
+ }
+ ++Wave;
+ }
+ if (Now - uint32(Wave - 1) * 2000 < 1000)
+ {
+ const uint16 Target = uint16(((Wave - 1) % 30) * 10 + Rng.RangeInt(0, 9));
+ FVersePieceDamage D = Bolt(Sim.GetDef(Target), 4.f, FVector(Rng.Range(-50, 50), -1, Rng.Range(100, 200)));
+ D.PieceIndex = Target;
+ Shoot(D, Now);
+ }
+ Sim.Tick(Now, NeverEncroached);
+ // WP03 clears a piece's holes when it goes Holed or beyond, is repaired or reset.
+ for (const FVersePendingFracture& Pending : Sim.DrainEvents())
+ {
+ const FVerseFractureEvent& E = Pending.Event;
+ if (Pending.bPublishLocal && E.ToState != EVersePieceState::Damaged && E.PieceIndex != Verse::Destruction::AllPieces && ServerHoles.ByPiece.Remove(E.PieceIndex) > 0)
+ {
+ LastChangeMs[E.PieceIndex] = Now;
+ LateQueue.AddUnique(E.PieceIndex);
+ }
+ }
+ Sim.DrainNoise();
+ // Client 1 gets last tick's writes now; this tick's go out next tick.
+ for (const uint16 Index : LateQueue)
+ {
+ Late.Deliver(Index, Sim.GetItem(Index), ServerHoles);
+ }
+ TArray<uint16> Written = Sim.DrainDirtyItems();
+ for (const uint16 Index : Written)
+ {
+ LastChangeMs[Index] = Now;
+ }
+ for (const uint16 Index : LateQueue)
+ {
+ Written.AddUnique(Index);
+ }
+ LateQueue = Written;
+ // Client 2: every pending piece goes with its latest value; 25 % of sends are lost and retried.
+ for (const uint16 Index : Written)
+ {
+ LossyPending.Add(Index);
+ }
+ for (auto It = LossyPending.CreateIterator(); It; ++It)
+ {
+ if (!Net.Chance(0.25))
+ {
+ Lossy.Deliver(*It, Sim.GetItem(*It), ServerHoles);
+ It.RemoveCurrent();
+ }
+ }
+ if (Now >= NextSecond)
+ {
+ NextSecond += 1000;
+ ++Seconds;
+ for (int32 Index = 0; Index < Defs.Num(); ++Index)
+ {
+ if (Now - LastChangeMs[Index] < 1000)
+ {
+ continue; // still settling: compared again next second
+ }
+ const uint32 Truth = ServerPieceHash(Sim, ServerHoles, uint16(Index));
+ Mismatches += Late.PieceHash(uint16(Index)) != Truth ? 1 : 0;
+ Mismatches += Lossy.PieceHash(uint16(Index)) != Truth ? 1 : 0;
+ Compared += 2;
+ }
+ }
+ }
+ AddInfo(FString::Printf(TEXT("%d seconds, %lld piece comparisons, %d hole records, %d repairs"), Seconds, Compared, HoleRecords, Sim.GetCounters().Repairs));
+ TestTrue(TEXT("ten minutes simulated"), Seconds >= 599);
+ TestTrue(TEXT("most pieces compared every second"), Compared > int64(Seconds) * Defs.Num());
+ TestTrue(TEXT("the stub hole store saw holes"), HoleRecords > 0);
+ TestEqual(TEXT("every settled piece: server and 2 clients agree (state, variant, look, holes)"), Mismatches, 0);
+ TestTrue(TEXT("pieces were repaired during the storm"), Sim.GetCounters().Repairs > 0);
+ // Same seed, same inputs: the server replays bit-identically.
+ TArray<uint32> A;
+ TArray<uint32> B;
+ const uint32 FinalA = StormFinalHash(30, 0xBEEF, A);
+ const uint32 FinalB = StormFinalHash(30, 0xBEEF, B);
+ TestEqual(TEXT("replay: same per-second hashes"), A, B);
+ TestEqual(TEXT("replay: same final hash"), FinalA, FinalB);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionNetTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionNetTest.cpp
new file mode 100644
index 0000000000..e32088d562
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionNetTest.cpp
@@ -0,0 +1,211 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Debris/VerseDebrisBudget.h"
+#include "Debris/VerseDebrisSubsystem.h"
+#include "Events/VerseEventHub.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "Pieces/VersePieceManifest.h"
+#include "UObject/CoreNet.h"
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ FVersePieceItem RoundTrip(const FVersePieceItem& In, int32& OutBits)
+ {
+ FNetBitWriter Writer(nullptr, 1024);
+ FVersePieceItem Copy = In;
+ bool bOk = false;
+ Copy.NetSerialize(Writer, nullptr, bOk);
+ OutBits = int32(Writer.GetNumBits());
+ FNetBitReader Reader(nullptr, Writer.GetData(), Writer.GetNumBits());
+ FVersePieceItem Out;
+ Out.NetSerialize(Reader, nullptr, bOk);
+ return Out;
+ }
+
+ bool SameItem(const FVersePieceItem& A, const FVersePieceItem& B)
+ {
+ return A.PieceIndex == B.PieceIndex && A.State == B.State && A.HealthQ == B.HealthQ && A.Variant == B.Variant
+ && A.RepairFrom == B.RepairFrom && A.LastSeed == B.LastSeed && FMemory::Memcmp(A.LastImpulse, B.LastImpulse, sizeof(A.LastImpulse)) == 0
+ && FMemory::Memcmp(A.LastLocation, B.LastLocation, sizeof(A.LastLocation)) == 0 && A.StateTimeMs == B.StateTimeMs
+ && A.Epoch == B.Epoch;
+ }
+
+ TArray<FVersePieceDef> ContainerRow(int32 Count)
+ {
+ TArray<FVersePieceDef> Defs;
+ for (int32 Index = 0; Index < Count; ++Index)
+ {
+ Defs.Add(MakePiece(EVersePieceClass::ContainerWall, FVector(Index * 1000.0, 0, 0), 700 + Index));
+ }
+ return Defs;
+ }
+}
+
+// destruction.md 3.3: the packed item round-trips losslessly and its size is measured, not assumed.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionNetItem, "Verse.Destruction.Net.ItemSerialize", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionNetItem::RunTest(const FString&)
+{
+ FVersePieceItem Fractured;
+ Fractured.PieceIndex = 1999;
+ Fractured.State = EVersePieceState::Breached;
+ Fractured.HealthQ = 17;
+ Fractured.Variant = 3;
+ Fractured.LastSeed = 0xDEADBEEF;
+ Fractured.LastImpulse[0] = -15000;
+ Fractured.LastImpulse[2] = 321;
+ Fractured.LastLocation[1] = -1200;
+ Fractured.StateTimeMs = 3600000;
+ Fractured.Epoch = 65535;
+ FVersePieceItem Repairing = Fractured;
+ Repairing.State = EVersePieceState::Repairing;
+ Repairing.RepairFrom = EVersePieceState::Destroyed;
+ FVersePieceItem Reset;
+ Reset.PieceIndex = 5;
+ Reset.StateTimeMs = 99;
+ Reset.Epoch = 2;
+
+ int32 FracturedBits = 0;
+ int32 RepairingBits = 0;
+ int32 ResetBits = 0;
+ TestTrue(TEXT("fractured item round-trips"), SameItem(RoundTrip(Fractured, FracturedBits), Fractured));
+ TestTrue(TEXT("repairing item round-trips"), SameItem(RoundTrip(Repairing, RepairingBits), Repairing));
+ TestTrue(TEXT("reset item round-trips"), SameItem(RoundTrip(Reset, ResetBits), Reset));
+ AddInfo(FString::Printf(TEXT("wire bits: fractured %d, repairing %d, reset %d"), FracturedBits, RepairingBits, ResetBits));
+ TestEqual(TEXT("fractured item: 26 bytes measured"), FVersePieceItem::MeasureWireBytes(Fractured), (FracturedBits + 7) / 8);
+ TestTrue(TEXT("a fractured item is at most 26 bytes"), FVersePieceItem::MeasureWireBytes(Fractured) <= 26);
+ TestTrue(TEXT("a reset item is at most 10 bytes"), FVersePieceItem::MeasureWireBytes(Reset) <= 10);
+ TestEqual(TEXT("RepairFrom costs 3 bits only while Repairing"), RepairingBits - FracturedBits, 3);
+ return true;
+}
+
+// destruction.md 4 and 6.1 through the real manager: several hits on one piece in one frame leave
+// one event, and damage calls never hand nav tiles over by themselves.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionNetManagerTick, "Verse.Destruction.Net.ManagerTick", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionNetManagerTick::RunTest(const FString&)
+{
+ FTestWorld W(TEXT("VerseDestructionManagerTick"));
+ const TArray<FVersePieceDef> Defs = ContainerRow(24);
+ for (const FVersePieceDef& Def : Defs)
+ {
+ W.SpawnPiece(Def);
+ }
+ AVerseDestructionManager* Manager = W.SpawnManager(false);
+ UVerseEventHub* Hub = UVerseEventHub::Get(W.World);
+ if (!TestNotNull(TEXT("event hub"), Hub))
+ {
+ return false;
+ }
+ TArray<FVerseFractureEvent> Events;
+ const FDelegateHandle Handle = Hub->OnFracture.AddLambda([&Events](const FVerseFractureEvent& E) { Events.Add(E); });
+
+ // One frame: a breach on piece 0 plus five bolts into it.
+ FVersePieceDamage B = Breach(Manager->GetSim().GetDef(0));
+ B.PieceIndex = 0;
+ B.BreachRadiusCm = 1.f;
+ Manager->GetPieceDamage().ApplyPieceDamage(B);
+ for (int32 Shot = 0; Shot < 5; ++Shot)
+ {
+ FVersePieceDamage D = Bolt(Manager->GetSim().GetDef(0), 30.f);
+ D.PieceIndex = 0;
+ Manager->GetPieceDamage().ApplyPieceDamage(D);
+ }
+ TestTrue(TEXT("the state is live at once on the server"), Manager->GetPieceState(0) != EVersePieceState::Intact);
+ TestEqual(TEXT("no event before the tick"), Events.Num(), 0);
+ // Same frame: breach every other piece too (many damage calls, many dirty tiles).
+ for (int32 Index = 1; Index < Defs.Num(); ++Index)
+ {
+ FVersePieceDamage D = Breach(Manager->GetSim().GetDef(uint16(Index)));
+ D.PieceIndex = uint16(Index);
+ D.BreachRadiusCm = 1.f;
+ Manager->GetPieceDamage().ApplyPieceDamage(D);
+ }
+ TestEqual(TEXT("damage calls hand no nav tile over"), Manager->GetNavTilesInFlight(), 0);
+ Manager->Tick(0.f);
+ const int32 OnPiece0 = Events.FilterByPredicate([](const FVerseFractureEvent& E) { return E.PieceIndex == 0; }).Num();
+ TestEqual(TEXT("one event for piece 0 this tick (coalesced)"), OnPiece0, 1);
+ TestTrue(TEXT("at most 4 nav tiles after the tick"), Manager->GetNavTilesInFlight() <= 4);
+ TestTrue(TEXT("tiles are still queued"), Manager->GetSim().GetNav().NumQueued() > 0);
+ for (int32 Tick = 0; Tick < 200 && Manager->GetSim().GetNav().NumQueued() > 0; ++Tick)
+ {
+ Manager->Tick(0.f);
+ TestTrue(TEXT("never more than 4 in flight"), Manager->GetNavTilesInFlight() <= 4);
+ }
+ TestEqual(TEXT("the queue drains tick by tick"), Manager->GetSim().GetNav().NumQueued(), 0);
+ TestTrue(TEXT("peak in flight at most 4"), Manager->GetPeakNavTilesInFlight() <= 4);
+ Hub->OnFracture.Remove(Handle);
+ return true;
+}
+
+// destruction.md 8: a piece that streams in after the manager registered takes its manifest slot
+// and shows the replicated state at once; one that streams out leaves it.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionNetStreaming, "Verse.Destruction.Net.StreamingRegister", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionNetStreaming::RunTest(const FString&)
+{
+ FTestWorld W(TEXT("VerseDestructionStreaming"));
+ const TArray<FVersePieceDef> Defs = ContainerRow(6);
+ UVersePieceManifest* Manifest = NewObject<UVersePieceManifest>();
+ for (const FVersePieceDef& Def : Defs)
+ {
+ Manifest->PieceGuids.Add(Def.Guid); // server order
+ }
+ // Only the first four are loaded when the client manager registers.
+ for (int32 Index = 0; Index < 4; ++Index)
+ {
+ W.SpawnPiece(Defs[Index]);
+ }
+ AVerseDestructionManager* Client = W.SpawnManager(true, 0, Manifest);
+ TestFalse(TEXT("manifest present: the client registers"), Client->IsMissingClientManifest());
+ TestEqual(TEXT("every manifest slot exists"), Client->NumPieces(), 6);
+ TestNull(TEXT("slot 5 is not loaded yet"), Client->GetPieceActor(5));
+ FVersePieceItem Item;
+ Item.PieceIndex = 5;
+ Item.State = EVersePieceState::Destroyed;
+ Client->ReceiveItemsForTest(MakeArrayView(&Item, 1), true);
+ TestEqual(TEXT("the client knows the state of an unloaded piece"), Client->GetPieceState(5), EVersePieceState::Destroyed);
+
+ AVerseDestructible* Late = W.SpawnPiece(Defs[5]);
+ Client->RegisterPiece(*Late);
+ TestTrue(TEXT("the late piece takes slot 5"), Client->GetPieceActor(5) == Late && Late->GetPieceIndex() == 5);
+ TestEqual(TEXT("and shows the replicated state at once"), Late->GetPresentedState(), EVersePieceState::Destroyed);
+ Item.State = EVersePieceState::Repairing;
+ Item.RepairFrom = EVersePieceState::Destroyed;
+ Client->ReceiveItemsForTest(MakeArrayView(&Item, 1), false);
+ TestEqual(TEXT("then follows the items"), Late->GetPresentedState(), EVersePieceState::Repairing);
+ Client->UnregisterPiece(*Late);
+ TestNull(TEXT("streamed out: the slot is empty"), Client->GetPieceActor(5));
+ TestEqual(TEXT("the state stays"), Client->GetPieceState(5), EVersePieceState::Repairing);
+ return true;
+}
+
+// destruction.md 10: the burst is the largest authored set that fits the grant, and the budget
+// is charged with the bodies really spawned.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionDebrisSets, "Verse.Destruction.Debris.Sets", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionDebrisSets::RunTest(const FString&)
+{
+ TestEqual(TEXT("largest set within the grant"), UVerseDebrisSubsystem::PickSet(TArray<int32>{6, 12, 40}, 12), 1);
+ TestEqual(TEXT("a full set over the grant is never taken"), UVerseDebrisSubsystem::PickSet(TArray<int32>{40}, 12), INDEX_NONE);
+ TestEqual(TEXT("empty sets never count"), UVerseDebrisSubsystem::PickSet(TArray<int32>{0, 3}, 12), 1);
+ TestEqual(TEXT("no sets, no burst"), UVerseDebrisSubsystem::PickSet(TArray<int32>(), 40), INDEX_NONE);
+
+ FVerseDebrisBudget Budget;
+ FVerseDebrisBudget::FRequest Request;
+ Request.Type = EVerseDebrisType::MetalShards;
+ Request.ToState = EVersePieceState::Holed;
+ const FVerseDebrisBudget::FGrant Grant = Budget.Request(Request, 0.0);
+ TestEqual(TEXT("Holed sheet metal reserves 12"), Grant.Bodies, 12);
+ Budget.Commit(Grant.BurstId, 7);
+ TestEqual(TEXT("the budget counts the 7 real bodies"), Budget.ActiveBodies(), 7);
+ TestEqual(TEXT("real peak"), Budget.GetPeakRealBodies(), 7);
+ const FVerseDebrisBudget::FGrant Second = Budget.Request(Request, 0.1);
+ Budget.Commit(Second.BurstId, 0);
+ TestEqual(TEXT("nothing spawned frees the reservation"), Budget.ActiveBodies(), 7);
+ TestEqual(TEXT("and the actor slot"), Budget.AliveActors(), 1);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionRepairTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionRepairTest.cpp
new file mode 100644
index 0000000000..ec8adbe3f0
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionRepairTest.cpp
@@ -0,0 +1,228 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "VerseGameplayTags.h"
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ /** Ticks until Pred holds or the limit passes; returns the time it held, or 0. */
+ template <typename TPred>
+ uint32 TickUntil(FVerseDestructionSim& Sim, uint32& Now, uint32 LimitMs, TPred Pred, TFunctionRef<bool(const FBox&)> Encroach = NeverEncroached)
+ {
+ for (; Now <= LimitMs; Now += TickMs)
+ {
+ Sim.Tick(Now, Encroach);
+ Sim.DrainEvents();
+ Sim.DrainNoise();
+ Sim.DrainDirtyItems();
+ if (Pred())
+ {
+ return Now;
+ }
+ }
+ return 0;
+ }
+
+ FVerseDestructionSim MakeSim(TArray<FVersePieceDef> Defs, int32 NumDocks)
+ {
+ FVerseDestructionSim Sim;
+ Sim.Init(MoveTemp(Defs), FVerseDestructionSimTuning::Contract(), VerseDestructionTest::Docks(NumDocks), 3);
+ return Sim;
+ }
+}
+
+// A6.5: repair starts 60 s after the last damage within one tick; damage during repair returns the
+// piece to RepairFrom; a downed drone cancels; at most 3 drones active; completion waits while a
+// pawn overlaps.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionRepairTiming, "Verse.Destruction.Repair.Timing", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionRepairTiming::RunTest(const FString&)
+{
+ const FVersePieceDef Wall = MakePiece(EVersePieceClass::WallPanel, FVector(0, 0, 0), 0);
+ FVerseDestructionSim Sim = MakeSim({Wall}, 1);
+ uint32 Now = 990;
+ FVersePieceDamage Damage = Bolt(Wall);
+ Sim.ApplyDamage(Damage, Now);
+ const uint32 LastDamage = Now;
+ // A second hit 10 s later restarts the 60 s.
+ Now = Run(Sim, Now, LastDamage + 10000);
+ Sim.ApplyDamage(Damage, Now);
+ const uint32 Restart = Now;
+ const uint32 Dispatched = TickUntil(Sim, Now, Restart + 70000, [&Sim] { return Sim.GetDrones()[0].Task == EVerseDroneTask::Outbound; });
+ TestTrue(TEXT("dispatched"), Dispatched != 0);
+ TestTrue(FString::Printf(TEXT("no dispatch before 60 s after the last damage (%u ms)"), Dispatched - Restart), Dispatched - Restart >= 60000);
+ TestTrue(FString::Printf(TEXT("dispatch within one tick of 60 s (%u ms)"), Dispatched - Restart), Dispatched - Restart < 60000 + TickMs);
+ TestEqual(TEXT("still Damaged while the drone flies"), Sim.GetItem(0).State, EVersePieceState::Damaged);
+
+ const uint32 Arrived = TickUntil(Sim, Now, Now + 20000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Repairing; });
+ TestTrue(TEXT("Repairing starts on arrival"), Arrived != 0);
+ TestEqual(TEXT("RepairFrom is the broken state"), Sim.GetItem(0).RepairFrom, EVersePieceState::Damaged);
+ TestEqual(TEXT("the proxy stays the pre-repair proxy"), Sim.GetItem(0).GetProxyState(), EVersePieceState::Damaged);
+ const uint32 Done = TickUntil(Sim, Now, Now + 20000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Intact; });
+ TestTrue(TEXT("repair completes"), Done != 0);
+ TestTrue(FString::Printf(TEXT("wall panel repair takes 8 s (%u ms)"), Done - Arrived), Done - Arrived >= 8000 && Done - Arrived < 8000 + 2 * TickMs);
+ TestEqual(TEXT("full HP after repair"), Sim.GetHp(0), 200.f);
+ TestEqual(TEXT("HealthQ 255"), int32(Sim.GetItem(0).HealthQ), 255);
+ TestEqual(TEXT("drone flies home"), Sim.GetDrones()[0].Task, EVerseDroneTask::Returning);
+ TestEqual(TEXT("one repair counted"), Sim.GetCounters().Repairs, 1);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionRepairInterrupt, "Verse.Destruction.Repair.Interrupt", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionRepairInterrupt::RunTest(const FString&)
+{
+ const FVersePieceDef Wall = MakePiece(EVersePieceClass::ContainerWall, FVector(0, 0, 0), 0);
+ FVerseDestructionSim Sim = MakeSim({Wall}, 1);
+ uint32 Now = 0;
+ FVersePieceDamage Charge = Breach(Wall);
+ Sim.ApplyDamage(Charge, Now);
+ TestEqual(TEXT("Breached"), Sim.GetItem(0).State, EVersePieceState::Breached);
+ TestTrue(TEXT("repair starts"), TickUntil(Sim, Now, 90000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Repairing; }) != 0);
+ // Damage during the repair: back to RepairFrom, drone leaves, the 60 s restart.
+ Now += TickMs;
+ Sim.ApplyDamage(Bolt(Wall), Now);
+ TestEqual(TEXT("damage during repair returns the piece to RepairFrom"), Sim.GetItem(0).State, EVersePieceState::Breached);
+ TestEqual(TEXT("the drone leaves"), Sim.GetDrones()[0].Task, EVerseDroneTask::Returning);
+ TestEqual(TEXT("the 60 s restart at the interrupting hit"), Sim.GetLastDamageMs(0), Now);
+ TestEqual(TEXT("interruption counted"), Sim.GetCounters().RepairsInterrupted, 1);
+ const uint32 Interrupted = Now;
+ const uint32 Again = TickUntil(Sim, Now, Interrupted + 70000, [&Sim] { return Sim.GetDrones()[0].Task == EVerseDroneTask::Outbound; });
+ TestTrue(TEXT("a new dispatch only 60 s after the interruption"), Again != 0 && Again - Interrupted >= 60000);
+
+ // A downed drone cancels the repair as well.
+ TestTrue(TEXT("repairing again"), TickUntil(Sim, Now, Now + 30000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Repairing; }) != 0);
+ TestFalse(TEXT("29 HP does not down the drone"), Sim.ApplyDroneDamage(0, 29.f, Now));
+ TestEqual(TEXT("still repairing after a graze"), Sim.GetItem(0).State, EVersePieceState::Repairing);
+ TestTrue(TEXT("30 HP downs the drone"), Sim.ApplyDroneDamage(0, 1.f, Now));
+ TestEqual(TEXT("downing the drone returns the piece to RepairFrom"), Sim.GetItem(0).State, EVersePieceState::Breached);
+ TestEqual(TEXT("downed drone"), Sim.GetDrones()[0].Task, EVerseDroneTask::Down);
+ TestEqual(TEXT("generation bumped (client debris)"), Sim.GetDrones()[0].Generation, 1u);
+ Now += TickMs;
+ Sim.Tick(Now, NeverEncroached);
+ TestEqual(TEXT("the dock replaces it"), Sim.GetDrones()[0].Task, EVerseDroneTask::Docked);
+ TestEqual(TEXT("with full HP"), Sim.GetDrones()[0].Hp, 30.f);
+ TestFalse(TEXT("an unknown drone takes no damage"), Sim.ApplyDroneDamage(7, 100.f, Now));
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionRepairQueue, "Verse.Destruction.Repair.Queue", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionRepairQueue::RunTest(const FString&)
+{
+ // Six broken pieces and five docks: at most 3 drones active; catwalks, then walls, then glass,
+ // then ceiling panels; within a class the longest-broken first.
+ TArray<FVersePieceDef> Defs;
+ Defs.Add(MakePiece(EVersePieceClass::CeilingPanel, FVector(0, 0, 500), 0));
+ Defs.Add(MakePiece(EVersePieceClass::GlassPane, FVector(500, 0, 0), 1));
+ Defs.Add(MakePiece(EVersePieceClass::WallPanel, FVector(1000, 0, 0), 2));
+ Defs.Add(MakePiece(EVersePieceClass::CatwalkSegment, FVector(1500, 0, 300), 3));
+ Defs.Add(MakePiece(EVersePieceClass::ContainerWall, FVector(2000, 0, 0), 4));
+ Defs.Add(MakePiece(EVersePieceClass::WallPanel, FVector(2500, 0, 0), 5));
+ FVerseDestructionSim Sim = MakeSim(Defs, 5);
+ uint32 Now = 0;
+ // Break order: wall 5 first (longest broken among the walls), then the others at once.
+ FVersePieceDamage D = Bolt(Defs[5]);
+ D.PieceIndex = 5;
+ Sim.ApplyDamage(D, Now);
+ Now += 1000;
+ for (const int32 Index : {0, 1, 2, 4})
+ {
+ D = Index == 0 ? Bolt(Defs[0], 10.f, FVector(0, 0, 1)) : Bolt(Defs[Index]);
+ D.PieceIndex = uint16(Index);
+ Sim.ApplyDamage(D, Now);
+ }
+ FVersePieceDamage Charge = Breach(Defs[3], FVector(0, 0, 5));
+ Charge.PieceIndex = 3;
+ Sim.ApplyDamage(Charge, Now);
+ TestEqual(TEXT("catwalk Destroyed"), Sim.GetItem(3).State, EVersePieceState::Destroyed);
+
+ TArray<int32> FirstWave;
+ int32 PeakActive = 0;
+ for (; Now < 200000; Now += TickMs)
+ {
+ Sim.Tick(Now, NeverEncroached);
+ Sim.DrainEvents();
+ Sim.DrainNoise();
+ Sim.DrainDirtyItems();
+ PeakActive = FMath::Max(PeakActive, Sim.NumActiveDrones());
+ if (FirstWave.Num() == 0 && Sim.NumActiveDrones() > 0 && Now >= 61000)
+ {
+ for (const FVerseDroneState& Drone : Sim.GetDrones())
+ {
+ if (Drone.IsActive())
+ {
+ FirstWave.Add(Drone.TargetPiece);
+ }
+ }
+ }
+ }
+ TestEqual(TEXT("at most 3 drones active"), PeakActive, 3);
+ FirstWave.Sort();
+ // Wall 5 broke first and is due 1 s earlier: it alone goes at 60 s. At 61 s three are active:
+ // wall 5, then the catwalk and the longest-broken walls (2 and 4 tie; index order).
+ TestEqual(TEXT("first wave: catwalk and walls before glass and ceiling"), FirstWave, TArray<int32>({2, 3, 5}));
+ for (int32 Index = 0; Index < Defs.Num(); ++Index)
+ {
+ TestEqual(FString::Printf(TEXT("piece %d repaired in the end"), Index), Sim.GetItem(uint16(Index)).State, EVersePieceState::Intact);
+ }
+ TestEqual(TEXT("six repairs"), Sim.GetCounters().Repairs, 6);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionRepairEncroach, "Verse.Destruction.Repair.Encroachment", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionRepairEncroach::RunTest(const FString&)
+{
+ const FVersePieceDef Glass = MakePiece(EVersePieceClass::GlassPane, FVector(0, 0, 0), 0);
+ FVerseDestructionSim Sim = MakeSim({Glass}, 1);
+ uint32 Now = 0;
+ FVersePieceDamage Charge = Breach(Glass);
+ Sim.ApplyDamage(Charge, Now);
+ TestTrue(TEXT("repairing"), TickUntil(Sim, Now, 90000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Repairing; }) != 0);
+ const uint32 RepairStart = Now;
+ const uint32 PawnLeaves = RepairStart + 4000 + 2100; // glass repairs in 4 s; a pawn stands in it 2.1 s longer
+ FBox Checked(ForceInit);
+ auto Encroach = [&Now, PawnLeaves, &Checked](const FBox& Box)
+ {
+ Checked = Box;
+ return Now < PawnLeaves;
+ };
+ const uint32 Done = TickUntil(Sim, Now, RepairStart + 20000, [&Sim] { return Sim.GetItem(0).State == EVersePieceState::Intact; }, Encroach);
+ TestTrue(TEXT("completion waits while a pawn overlaps"), Done >= PawnLeaves);
+ TestTrue(TEXT("re-checked every 0.5 s"), Done < PawnLeaves + 500 + TickMs);
+ const FBox Expected = Glass.GetWorldBounds(EVersePieceState::Intact, 0).ExpandBy(10.f);
+ TestTrue(TEXT("the overlap box is the Intact proxy +10 cm"), Checked.Min.Equals(Expected.Min, 0.01) && Checked.Max.Equals(Expected.Max, 0.01));
+ TestEqual(TEXT("glass restored with HP"), Sim.GetHp(0), 20.f);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionRepairNoise, "Verse.Destruction.Repair.Noise", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionRepairNoise::RunTest(const FString&)
+{
+ const FVersePieceDef Wall = MakePiece(EVersePieceClass::WallPanel, FVector(0, 0, 0), 0);
+ FVerseDestructionSim Sim = MakeSim({Wall}, 1);
+ Sim.ApplyDamage(Bolt(Wall), 0);
+ Sim.DrainNoise();
+ int32 DroneNoise = 0;
+ float Loudness = 0.f;
+ for (uint32 Now = 0; Now < 75000; Now += TickMs)
+ {
+ Sim.Tick(Now, NeverEncroached);
+ for (const FVerseNoiseEvent& Noise : Sim.DrainNoise())
+ {
+ if (Noise.Noise == VerseTags::Noise_Drone)
+ {
+ ++DroneNoise;
+ Loudness = Noise.Loudness;
+ TestEqual(TEXT("world source"), Noise.SourceId, -1);
+ }
+ }
+ Sim.DrainEvents();
+ Sim.DrainDirtyItems();
+ }
+ TestTrue(TEXT("flight and welding emit Noise.Drone"), DroneNoise >= 5);
+ TestEqual(TEXT("drone loudness 0.15"), Loudness, 0.15f);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStatesTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStatesTest.cpp
new file mode 100644
index 0000000000..79c057ebcf
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStatesTest.cpp
@@ -0,0 +1,301 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Pieces/VersePieceRules.h"
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ struct FOne
+ {
+ FVerseDestructionSim Sim;
+ FVersePieceDef Def;
+ uint32 Now = 1000;
+
+ explicit FOne(EVersePieceClass Class, EVersePenetrationMaterial Material = EVersePenetrationMaterial(0xFF))
+ {
+ Def = MakePiece(Class, FVector::ZeroVector, 1);
+ if (uint8(Material) != 0xFF)
+ {
+ Def.Material = Material;
+ }
+ Sim.Init({Def}, FVerseDestructionSimTuning::Contract(), {}, 7);
+ }
+ EVersePieceState State() const { return Sim.GetItem(0).State; }
+ void Hit(const FVersePieceDamage& Damage)
+ {
+ FVersePieceDamage D = Damage;
+ D.PieceIndex = 0;
+ Sim.ApplyDamage(D, Now);
+ Now += TickMs;
+ }
+ };
+}
+
+// A6.1: every class follows table 3.2; bullets never take a wall past Holed; floor, concrete and
+// armor steel never change.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesWalls, "Verse.Destruction.States.Walls", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesWalls::RunTest(const FString&)
+{
+ struct FCase
+ {
+ EVersePieceClass Class;
+ float MaxHp;
+ float HoledAt;
+ };
+ for (const FCase& Case : {FCase{EVersePieceClass::WallPanel, 200.f, 100.f}, FCase{EVersePieceClass::CladdingWall, 250.f, 125.f},
+ FCase{EVersePieceClass::ContainerWall, 300.f, 150.f}})
+ {
+ const FString Name = UEnum::GetValueAsString(Case.Class);
+ FOne P(Case.Class);
+ TestEqual(Name + TEXT(" starts Intact"), P.State(), EVersePieceState::Intact);
+ TestEqual(Name + TEXT(" starts at full HealthQ"), int32(P.Sim.GetItem(0).HealthQ), 255);
+ P.Hit(Bolt(P.Def));
+ TestEqual(Name + TEXT(" first hit -> Damaged"), P.State(), EVersePieceState::Damaged);
+ const int32 HitsToHoled = FMath::CeilToInt((Case.MaxHp - Case.HoledAt) / 10.f);
+ for (int32 Hit = 1; Hit < HitsToHoled - 1; ++Hit)
+ {
+ P.Hit(Bolt(P.Def));
+ }
+ TestEqual(Name + TEXT(" above the threshold stays Damaged"), P.State(), EVersePieceState::Damaged);
+ P.Hit(Bolt(P.Def));
+ TestEqual(Name + TEXT(" at or below the threshold -> Holed"), P.State(), EVersePieceState::Holed);
+ TestTrue(Name + TEXT(" HP at or below the threshold"), P.Sim.GetHp(0) <= Case.HoledAt);
+ for (int32 Hit = 0; Hit < 60; ++Hit)
+ {
+ P.Hit(Bolt(P.Def));
+ }
+ TestEqual(Name + TEXT(" bullets never take a wall past Holed"), P.State(), EVersePieceState::Holed);
+ TestEqual(Name + TEXT(" HP floors at 0"), P.Sim.GetHp(0), 0.f);
+ P.Hit(Melee(P.Def));
+ TestEqual(Name + TEXT(" melee changes only glass"), P.State(), EVersePieceState::Holed);
+ P.Hit(Breach(P.Def));
+ TestEqual(Name + TEXT(" breach charge -> Breached"), P.State(), EVersePieceState::Breached);
+ P.Hit(Breach(P.Def));
+ TestEqual(Name + TEXT(" a wall is never Destroyed"), P.State(), EVersePieceState::Breached);
+
+ FOne Fresh(Case.Class);
+ Fresh.Hit(Melee(Fresh.Def));
+ TestEqual(Name + TEXT(" melee leaves an intact wall intact"), Fresh.State(), EVersePieceState::Intact);
+ TestEqual(Name + TEXT(" melee costs a wall no HP"), Fresh.Sim.GetHp(0), Case.MaxHp);
+ Fresh.Hit(Breach(Fresh.Def));
+ TestEqual(Name + TEXT(" breach on an intact wall -> Breached"), Fresh.State(), EVersePieceState::Breached);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesOthers, "Verse.Destruction.States.GlassCatwalkCeiling", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesOthers::RunTest(const FString&)
+{
+ {
+ FOne Glass(EVersePieceClass::GlassPane);
+ Glass.Hit(Bolt(Glass.Def, 10.f, FVector(0, 0, 150)));
+ TestEqual(TEXT("glass first hit -> Damaged (crack web)"), Glass.State(), EVersePieceState::Damaged);
+ Glass.Hit(Bolt(Glass.Def, 10.f, FVector(0, 0, 150)));
+ TestEqual(TEXT("glass HP 0 -> Destroyed"), Glass.State(), EVersePieceState::Destroyed);
+ TestEqual(TEXT("destroyed glass HealthQ 0"), int32(Glass.Sim.GetItem(0).HealthQ), 0);
+ Glass.Hit(Breach(Glass.Def));
+ TestEqual(TEXT("Destroyed is final"), Glass.State(), EVersePieceState::Destroyed);
+ }
+ {
+ FOne Glass(EVersePieceClass::GlassPane);
+ Glass.Hit(Melee(Glass.Def));
+ TestEqual(TEXT("melee on intact glass -> Damaged"), Glass.State(), EVersePieceState::Damaged);
+ Glass.Hit(Melee(Glass.Def));
+ TestEqual(TEXT("melee on damaged glass -> Destroyed"), Glass.State(), EVersePieceState::Destroyed);
+ }
+ {
+ FOne Glass(EVersePieceClass::GlassPane);
+ Glass.Hit(Breach(Glass.Def));
+ TestEqual(TEXT("breach charge on glass -> Destroyed"), Glass.State(), EVersePieceState::Destroyed);
+ }
+ {
+ FOne Catwalk(EVersePieceClass::CatwalkSegment);
+ for (int32 Hit = 0; Hit < 100; ++Hit)
+ {
+ Catwalk.Hit(Bolt(Catwalk.Def, 50.f, FVector(0, 0, 1)));
+ }
+ Catwalk.Hit(Melee(Catwalk.Def));
+ TestEqual(TEXT("bolts and melee never change a catwalk"), Catwalk.State(), EVersePieceState::Intact);
+ Catwalk.Hit(Breach(Catwalk.Def, FVector(0, 0, 5)));
+ TestEqual(TEXT("breach charge on a catwalk -> Destroyed"), Catwalk.State(), EVersePieceState::Destroyed);
+ }
+ {
+ FOne Ceiling(EVersePieceClass::CeilingPanel);
+ Ceiling.Hit(Bolt(Ceiling.Def, 10.f, FVector(0, 0, 1)));
+ TestEqual(TEXT("ceiling first hit -> Damaged"), Ceiling.State(), EVersePieceState::Damaged);
+ for (int32 Hit = 0; Hit < 4; ++Hit)
+ {
+ Ceiling.Hit(Bolt(Ceiling.Def, 10.f, FVector(0, 0, 1)));
+ }
+ TestEqual(TEXT("ceiling at 10 HP still Damaged"), Ceiling.State(), EVersePieceState::Damaged);
+ Ceiling.Hit(Bolt(Ceiling.Def, 10.f, FVector(0, 0, 1)));
+ TestEqual(TEXT("ceiling HP 0 -> Destroyed (whole tile falls)"), Ceiling.State(), EVersePieceState::Destroyed);
+ }
+ {
+ FOne Ceiling(EVersePieceClass::CeilingPanel);
+ Ceiling.Hit(Melee(Ceiling.Def));
+ TestEqual(TEXT("melee never changes a ceiling panel"), Ceiling.State(), EVersePieceState::Intact);
+ Ceiling.Hit(Breach(Ceiling.Def, FVector(0, 0, -5)));
+ TestEqual(TEXT("breach charge on a ceiling panel -> Destroyed"), Ceiling.State(), EVersePieceState::Destroyed);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesNeverBreak, "Verse.Destruction.States.NeverBreaks", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesNeverBreak::RunTest(const FString&)
+{
+ for (const EVersePenetrationMaterial Material : {EVersePenetrationMaterial::Concrete, EVersePenetrationMaterial::ArmorSteel})
+ {
+ FOne P(EVersePieceClass::WallPanel, Material);
+ for (int32 Hit = 0; Hit < 50; ++Hit)
+ {
+ P.Hit(Bolt(P.Def, 50.f));
+ }
+ P.Hit(Melee(P.Def));
+ P.Hit(Breach(P.Def));
+ TestEqual(FString::Printf(TEXT("%s never changes state (DR4)"), *UEnum::GetValueAsString(Material)), P.State(), EVersePieceState::Intact);
+ TestEqual(TEXT("and keeps full HealthQ"), int32(P.Sim.GetItem(0).HealthQ), 255);
+ TestEqual(TEXT("and raises no fracture event"), P.Sim.DrainEvents().Num(), 0);
+ }
+ // Non-damage causes are ignored.
+ FOne Wall(EVersePieceClass::WallPanel);
+ FVersePieceDamage Repair = Bolt(Wall.Def);
+ Repair.Cause = EVerseFractureCause::Repair;
+ Wall.Hit(Repair);
+ Repair.Cause = EVerseFractureCause::Reset;
+ Wall.Hit(Repair);
+ TestEqual(TEXT("Repair and Reset are not damage"), Wall.State(), EVersePieceState::Intact);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesBreachRadius, "Verse.Destruction.States.BreachRadius", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesBreachRadius::RunTest(const FString&)
+{
+ // Target wall at the origin; neighbours with a proxy vertex inside 150 cm of the charge go
+ // Holed (walls) or Destroyed (glass, ceiling); catwalks and far pieces do not change.
+ TArray<FVersePieceDef> Defs;
+ Defs.Add(MakePiece(EVersePieceClass::WallPanel, FVector(0, 0, 0), 0)); // 0 target
+ Defs.Add(MakePiece(EVersePieceClass::ContainerWall, FVector(240, 0, 0), 1)); // 1 near wall (vertex at x=120)
+ Defs.Add(MakePiece(EVersePieceClass::GlassPane, FVector(0, 80, 0), 2)); // 2 near glass
+ Defs.Add(MakePiece(EVersePieceClass::CeilingPanel, FVector(0, 0, 160), 3)); // 3 near ceiling tile (corner within 150)
+ Defs.Add(MakePiece(EVersePieceClass::CatwalkSegment, FVector(0, 60, 100), 4)); // 4 near catwalk
+ Defs.Add(MakePiece(EVersePieceClass::WallPanel, FVector(2000, 0, 0), 5)); // 5 far wall
+ Defs.Add(MakePiece(EVersePieceClass::GlassPane, FVector(0, 1000, 0), 6)); // 6 far glass
+ FVerseDestructionSim Sim;
+ Sim.Init(Defs, FVerseDestructionSimTuning::Contract(), {}, 11);
+ // Pre-damage the near wall to Holed: a side breach must not move it back or past Holed.
+ FVersePieceDamage Charge = Breach(Defs[0], FVector(60, -5, 100));
+ Charge.PieceIndex = 0;
+ Sim.ApplyDamage(Charge, 5000);
+ TestEqual(TEXT("target wall Breached"), Sim.GetItem(0).State, EVersePieceState::Breached);
+ TestEqual(TEXT("near wall Holed"), Sim.GetItem(1).State, EVersePieceState::Holed);
+ TestEqual(TEXT("near glass Destroyed"), Sim.GetItem(2).State, EVersePieceState::Destroyed);
+ TestEqual(TEXT("near ceiling panel Destroyed"), Sim.GetItem(3).State, EVersePieceState::Destroyed);
+ TestEqual(TEXT("near catwalk unchanged (breach target only)"), Sim.GetItem(4).State, EVersePieceState::Intact);
+ TestEqual(TEXT("far wall unchanged"), Sim.GetItem(5).State, EVersePieceState::Intact);
+ TestEqual(TEXT("far glass unchanged"), Sim.GetItem(6).State, EVersePieceState::Intact);
+ // Second charge next to the Breached target and the Holed wall: forward only.
+ Charge.PieceIndex = 1;
+ Charge.Location = Defs[1].Transform.TransformPosition(FVector(-100, -5, 100));
+ Sim.ApplyDamage(Charge, 6000);
+ TestEqual(TEXT("side effect never moves a Breached wall back"), Sim.GetItem(0).State, EVersePieceState::Breached);
+ TestEqual(TEXT("the new target goes Breached"), Sim.GetItem(1).State, EVersePieceState::Breached);
+ // Variant choice: the breach variant nearest the charge point (standing 110 cm vs low 50 cm).
+ TestEqual(TEXT("breach variant nearest the charge"), int32(Sim.GetItem(0).Variant), 0);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesVariants, "Verse.Destruction.States.Variants", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesVariants::RunTest(const FString&)
+{
+ // Holed: the variant whose opening centroid is closest to the damage centroid.
+ FOne Right(EVersePieceClass::WallPanel);
+ for (int32 Hit = 0; Hit < 10; ++Hit)
+ {
+ Right.Hit(Bolt(Right.Def, 10.f, FVector(70, 0, 130 + Hit)));
+ }
+ TestEqual(TEXT("hits on the right -> Holed"), Right.State(), EVersePieceState::Holed);
+ TestEqual(TEXT("right opening variant"), int32(Right.Sim.GetItem(0).Variant), 1);
+ FOne Left(EVersePieceClass::WallPanel);
+ for (int32 Hit = 0; Hit < 10; ++Hit)
+ {
+ Left.Hit(Bolt(Left.Def, 10.f, FVector(-80, 0, 150)));
+ }
+ TestEqual(TEXT("left opening variant"), int32(Left.Sim.GetItem(0).Variant), 0);
+ // Breached: the variant nearest the charge position (low breach for a charge at the floor).
+ FOne Low(EVersePieceClass::ContainerWall);
+ Low.Hit(Breach(Low.Def, FVector(0, -5, 40)));
+ TestEqual(TEXT("low charge -> low breach variant"), int32(Low.Sim.GetItem(0).Variant), 1);
+ // The fracture event carries the state change, the seed and the instigator.
+ const TArray<FVersePendingFracture> Events = Low.Sim.DrainEvents();
+ if (TestEqual(TEXT("one fracture event"), Events.Num(), 1))
+ {
+ const FVerseFractureEvent& Event = Events[0].Event;
+ TestEqual(TEXT("event from Intact"), Event.FromState, EVersePieceState::Intact);
+ TestEqual(TEXT("event to Breached"), Event.ToState, EVersePieceState::Breached);
+ TestEqual(TEXT("event cause Breach"), Event.Cause, EVerseFractureCause::Breach);
+ TestEqual(TEXT("event variant"), int32(Event.Variant), 1);
+ TestEqual(TEXT("event instigator slot"), int32(Event.Instigator), 1);
+ TestEqual(TEXT("event radius 150 cm"), int32(Event.Radius), 150);
+ TestEqual(TEXT("event seed = item seed"), Event.Seed, Low.Sim.GetItem(0).LastSeed);
+ TestEqual(TEXT("event location piece-local mm"), int32(Event.Location[2]), 400);
+ }
+ // Noise: a breach is the loudest fracture (destruction.md 6.2).
+ const TArray<FVerseNoiseEvent> Noise = Low.Sim.DrainNoise();
+ if (TestEqual(TEXT("one fracture noise"), Noise.Num(), 1))
+ {
+ TestEqual(TEXT("breach loudness 1.0"), Noise[0].Loudness, 1.0f);
+ TestEqual(TEXT("world source"), Noise[0].SourceId, -1);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStatesForward, "Verse.Destruction.States.ForwardOnly", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStatesForward::RunTest(const FString&)
+{
+ using namespace Verse::Destruction::Rules;
+ const FVerseDestructionSimTuning Tuning = FVerseDestructionSimTuning::Contract();
+ const EVersePieceState States[] = {EVersePieceState::Intact, EVersePieceState::Damaged, EVersePieceState::Holed, EVersePieceState::Breached,
+ EVersePieceState::Destroyed};
+ const EVerseFractureCause Causes[] = {EVerseFractureCause::Bolt, EVerseFractureCause::Breach, EVerseFractureCause::Melee};
+ const EHitRole Roles[] = {EHitRole::Direct, EHitRole::BreachTarget, EHitRole::BreachSide};
+ int32 Checked = 0;
+ for (const TPair<EVersePieceClass, FVersePieceClassTuning>& Row : Tuning.Classes)
+ {
+ for (const EVersePieceState State : States)
+ {
+ for (const EVerseFractureCause Cause : Causes)
+ {
+ for (const EHitRole Role : Roles)
+ {
+ for (const float Hp : {0.f, 10.f, 1000.f})
+ {
+ const FOutcome Out = Apply(Row.Value, State, Hp, Cause, Role, 25.f);
+ ++Checked;
+ if (!IsForward(State, Out.State))
+ {
+ AddError(FString::Printf(TEXT("%s: %s -> %s is backwards"), *UEnum::GetValueAsString(Row.Key),
+ *UEnum::GetValueAsString(State), *UEnum::GetValueAsString(Out.State)));
+ }
+ if (Out.Hp > Hp + KINDA_SMALL_NUMBER)
+ {
+ AddError(TEXT("damage raised HP"));
+ }
+ if (Cause == EVerseFractureCause::Bolt && Row.Value.bBreachedByCharge && uint8(Out.State) > uint8(EVersePieceState::Holed)
+ && uint8(State) <= uint8(EVersePieceState::Holed))
+ {
+ AddError(TEXT("a bolt took a wall past Holed"));
+ }
+ }
+ }
+ }
+ }
+ }
+ TestTrue(TEXT("checked every class x state x cause x role"), Checked >= 6 * 5 * 3 * 3 * 3);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStormTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStormTest.cpp
new file mode 100644
index 0000000000..d9807de898
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionStormTest.cpp
@@ -0,0 +1,250 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Debris/VerseDebrisBudget.h"
+#include "Debris/VerseDebrisSubsystem.h"
+#include "Destruction/VersePenetrationTable.h"
+#include "HAL/PlatformTime.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ /**
+ * Client debris replica fed only by multicast events. It picks the burst the way the debris
+ * subsystem does: the authored set of the new state (the kit ships one per state at the
+ * class's body count, art/verse/kit/destructible DEBRIS_BODIES) that fits the grant, and
+ * charges the budget with that set's chunk count. Headless runs cannot count Chaos particles;
+ * the rendered lane measures those.
+ */
+ struct FDebrisClient
+ {
+ FVerseDebrisBudget Budget;
+ const FVerseDestructionSim* Sim = nullptr;
+
+ FDebrisClient(const FVerseDebrisBudget::FConfig& Config, const FVerseDestructionSim& InSim)
+ : Budget(Config)
+ , Sim(&InSim)
+ {
+ }
+
+ void OnEvent(const FVerseFractureEvent& Event, double NowS)
+ {
+ if (Event.Cause == EVerseFractureCause::Reset)
+ {
+ Budget.PurgeAll();
+ return;
+ }
+ if (Event.Cause == EVerseFractureCause::Repair || !Sim->IsValidPiece(Event.PieceIndex))
+ {
+ return;
+ }
+ const FVersePenetrationRow* Row = GetDefault<UVersePenetrationTable>()->FindRow(uint8(Sim->GetDef(Event.PieceIndex).Material));
+ FVerseDebrisBudget::FRequest Request;
+ Request.PieceIndex = Event.PieceIndex;
+ Request.Type = Row ? Row->DebrisType : EVerseDebrisType::SparksOnly;
+ Request.ToState = Event.ToState;
+ const FVerseDebrisBudget::FGrant Grant = Budget.Request(Request, NowS);
+ if (Grant.BurstId != 0)
+ {
+ const int32 Authored = FVerseDebrisBudget::DesiredBodies(Request.Type, Request.ToState);
+ const TArray<int32> Sets = {Authored};
+ const int32 Pick = UVerseDebrisSubsystem::PickSet(Sets, Grant.Bodies);
+ Budget.Commit(Grant.BurstId, Pick == INDEX_NONE ? 0 : Sets[Pick]);
+ }
+ }
+ };
+
+ struct FStormResult
+ {
+ int32 DurationS = 0;
+ int32 Fractures = 0;
+ int32 PeakEventsPerSecond = 0;
+ int32 EventsOverRate = 0;
+ int32 PeakBodiesHigh = 0;
+ int32 PeakBodiesLow = 0;
+ int32 PeakPerFracture = 0;
+ int32 PeakActors = 0;
+ int32 PeakNavInFlight = 0;
+ int32 Repairs = 0;
+ int32 PeakDrones = 0;
+ double SimMsPerTickMax = 0.0;
+ int32 ItemBytes = 0;
+ int32 ResetBurstBytes = 0;
+ int32 EventsDeferredSent = 0;
+ int32 ItemWrites = 0;
+ uint32 FinalHash = 0;
+ TArray<uint32> HashPerSecond;
+ };
+
+ /**
+ * destruction_storm (destruction.md 10): two breach charges plus a full magazine (30 bolts)
+ * into a container row every 2 s, rows in turn, with repair drones running.
+ */
+ FStormResult RunStorm(int32 DurationS, uint64 Seed);
+}
+
+namespace VerseDestructionTest
+{
+ uint32 StormFinalHash(int32 DurationS, uint64 Seed, TArray<uint32>& OutPerSecond)
+ {
+ const FStormResult R = RunStorm(DurationS, Seed);
+ OutPerSecond = R.HashPerSecond;
+ return R.FinalHash;
+ }
+}
+
+namespace
+{
+ FStormResult RunStorm(int32 DurationS, uint64 Seed)
+ {
+ FVerseDestructionSim Sim;
+ Sim.Init(MakeArena(), FVerseDestructionSimTuning::Contract(), Docks(4), Seed);
+ FDebrisClient High(FVerseDebrisBudget::FConfig::High(), Sim);
+ FDebrisClient Low(FVerseDebrisBudget::FConfig::Low(), Sim);
+ FStormResult Result;
+ Result.DurationS = DurationS;
+ constexpr int32 PerRow = 8;
+ const int32 Rows = 30;
+ FVerseRng Rng(Seed, 0, EVerseRngSalt::Harness);
+ int32 Wave = 0;
+ uint32 NextSecond = 1000;
+ for (uint32 Now = 0; Now < uint32(DurationS) * 1000; Now += TickMs)
+ {
+ const double Start = FPlatformTime::Seconds();
+ // Every 2 s a new wave on the next row: two charges at once, then the magazine over 1 s.
+ const uint32 WaveStart = uint32(Wave) * 2000;
+ if (Now >= WaveStart)
+ {
+ const int32 Row = Wave % Rows;
+ for (int32 Charge = 0; Charge < 2; ++Charge)
+ {
+ const uint16 Target = uint16(Row * (PerRow + 2) + Rng.RangeInt(0, PerRow - 1));
+ FVersePieceDamage D = Breach(Sim.GetDef(Target), FVector(Rng.Range(-80, 80), -5, Rng.Range(30, 150)));
+ D.PieceIndex = Target;
+ Sim.ApplyDamage(D, Now);
+ }
+ ++Wave;
+ }
+ const uint32 SinceWave = Now - (uint32(Wave - 1) * 2000);
+ if (SinceWave < 1000)
+ {
+ const int32 Row = (Wave - 1) % Rows;
+ // 30 rounds over 1 s at 30 Hz: one bolt per tick into the row.
+ const uint16 Target = uint16(Row * (PerRow + 2) + Rng.RangeInt(0, PerRow - 1));
+ FVersePieceDamage D = Bolt(Sim.GetDef(Target), 10.f, FVector(Rng.Range(-110, 110), -1, Rng.Range(20, 240)));
+ D.PieceIndex = Target;
+ Sim.ApplyDamage(D, Now);
+ }
+ Sim.Tick(Now, NeverEncroached);
+ const double NowS = double(Now) / 1000.0;
+ for (const FVersePendingFracture& Pending : Sim.DrainEvents())
+ {
+ Result.Fractures += Pending.bPublishLocal ? 1 : 0;
+ if (Pending.bMulticast)
+ {
+ High.OnEvent(Pending.Event, NowS);
+ Low.OnEvent(Pending.Event, NowS);
+ }
+ }
+ High.Budget.Tick(NowS);
+ Low.Budget.Tick(NowS);
+ Sim.DrainNoise();
+ for (const uint16 Index : Sim.DrainDirtyItems())
+ {
+ Result.ItemBytes = FMath::Max(Result.ItemBytes, FVersePieceItem::MeasureWireBytes(Sim.GetItem(Index)));
+ }
+ // Model: a released tile rebuilds within one server tick (the manager waits for the navmesh).
+ Sim.GetNav().Release(Sim.GetNav().NumInFlight());
+ Result.PeakNavInFlight = FMath::Max(Result.PeakNavInFlight, Sim.GetNav().GetPeakInFlight());
+ Result.SimMsPerTickMax = FMath::Max(Result.SimMsPerTickMax, (FPlatformTime::Seconds() - Start) * 1000.0);
+ if (Now >= NextSecond)
+ {
+ Result.HashPerSecond.Add(FVerseDestructionSim::ProxyHash(Sim.GetItems()));
+ NextSecond += 1000;
+ }
+ }
+ const FVerseDestructionCounters& C = Sim.GetCounters();
+ Result.PeakEventsPerSecond = C.PeakEventsPerSecond;
+ Result.EventsOverRate = C.EventsOverRate;
+ Result.PeakBodiesHigh = High.Budget.GetPeakRealBodies();
+ Result.PeakBodiesLow = Low.Budget.GetPeakRealBodies();
+ Result.PeakPerFracture = FMath::Max(High.Budget.GetPeakRealBodiesPerFracture(), Low.Budget.GetPeakRealBodiesPerFracture());
+ Result.PeakActors = FMath::Max(High.Budget.GetPeakRealActors(), Low.Budget.GetPeakRealActors());
+ Result.EventsDeferredSent = C.EventsDeferredSent;
+ Result.Repairs = C.Repairs;
+ Result.PeakDrones = C.PeakActiveDrones;
+ Result.ItemWrites = C.ItemWrites;
+ Result.FinalHash = FVerseDestructionSim::ProxyHash(Sim.GetItems());
+ Sim.FullReset(uint32(DurationS) * 1000);
+ Result.ResetBurstBytes = Sim.GetLastResetBurstBytes();
+ return Result;
+ }
+
+ void WriteProof(const FStormResult& R)
+ {
+ // Hand-written JSON: the module links no JSON library.
+ const TPair<const TCHAR*, double> Numbers[] = {
+ {TEXT("duration_s"), double(R.DurationS)},
+ {TEXT("fracture_events"), double(R.Fractures)},
+ {TEXT("peak_multicast_events_per_s"), double(R.PeakEventsPerSecond)},
+ {TEXT("events_over_rate_deferred"), double(R.EventsOverRate)},
+ {TEXT("peak_debris_bodies_high"), double(R.PeakBodiesHigh)},
+ {TEXT("peak_debris_bodies_low"), double(R.PeakBodiesLow)},
+ {TEXT("peak_bodies_per_fracture"), double(R.PeakPerFracture)},
+ {TEXT("peak_geometry_collection_actors"), double(R.PeakActors)},
+ {TEXT("peak_nav_tiles_in_flight_one_tick_rebuild_model"), double(R.PeakNavInFlight)},
+ {TEXT("deferred_multicast_events_sent"), double(R.EventsDeferredSent)},
+ {TEXT("repairs"), double(R.Repairs)},
+ {TEXT("peak_active_drones"), double(R.PeakDrones)},
+ {TEXT("state_item_max_wire_bytes_measured"), double(R.ItemBytes)},
+ {TEXT("reset_burst_bytes_measured"), double(R.ResetBurstBytes)},
+ {TEXT("item_writes"), double(R.ItemWrites)},
+ {TEXT("sim_ms_per_tick_max"), double(R.SimMsPerTickMax)},
+ {TEXT("budget_debris_bodies_high"), double(400)},
+ {TEXT("budget_debris_bodies_low"), double(150)},
+ {TEXT("budget_bodies_per_fracture"), double(40)},
+ {TEXT("budget_geometry_collection_actors"), double(32)},
+ {TEXT("budget_fracture_events_per_s"), double(64)},
+ {TEXT("budget_nav_tiles_in_flight"), double(4)},
+ };
+ FString Text = TEXT("{\n \"scenario\": \"destruction_storm\",\n \"package\": \"WP06\",\n \"sub_task\": \"WP06.11\",\n");
+ Text += TEXT(" \"physics_ms\": \"not measured headless: needs the rendered lane (unreal-perf)\",\n");
+ Text += TEXT(" \"debris_bodies_source\": \"authored set chunk counts committed to the budget; Chaos particle counts need the rendered lane\"");
+ for (const TPair<const TCHAR*, double>& Field : Numbers)
+ {
+ Text += FString::Printf(TEXT(",\n \"%s\": %s"), Field.Key, *FString::SanitizeFloat(Field.Value));
+ }
+ Text += TEXT("\n}\n");
+ const FString Path = FPaths::ProjectSavedDir() / TEXT("Harness/proof/WP06/WP06.11/destruction_storm.json");
+ FFileHelper::SaveStringToFile(Text, *Path);
+ }
+}
+
+// A6.3: 400 debris bodies max (150 Low), 40 per fracture, 32 GC actors, at most 64 fracture
+// events/s, state items about 20 bytes. Physics time needs the rendered lane.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionStorm, "Verse.Destruction.Storm", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionStorm::RunTest(const FString&)
+{
+ const FStormResult R = RunStorm(60, 0x5708);
+ WriteProof(R);
+ AddInfo(FString::Printf(TEXT("storm: %d fractures, peak %d events/s, bodies %d (high) %d (low), %d per fracture, %d actors, %d repairs"),
+ R.Fractures, R.PeakEventsPerSecond, R.PeakBodiesHigh, R.PeakBodiesLow, R.PeakPerFracture, R.PeakActors, R.Repairs));
+ TestTrue(TEXT("the storm breaks things"), R.Fractures > 100);
+ TestTrue(TEXT("at most 400 debris bodies on High"), R.PeakBodiesHigh <= 400);
+ TestTrue(TEXT("at most 150 debris bodies on Low"), R.PeakBodiesLow <= 150);
+ TestTrue(TEXT("the High cap is reached (the storm is a real load)"), R.PeakBodiesHigh > 150);
+ TestTrue(TEXT("at most 40 bodies per fracture"), R.PeakPerFracture <= 40);
+ TestTrue(TEXT("at most 32 geometry collection actors"), R.PeakActors <= 32);
+ TestTrue(TEXT("at most 64 multicast fracture events per second"), R.PeakEventsPerSecond <= 64);
+ TestTrue(TEXT("at most 4 nav tiles in flight"), R.PeakNavInFlight <= 4);
+ TestTrue(TEXT("at most 3 drones active"), R.PeakDrones <= 3);
+ TestTrue(FString::Printf(TEXT("a state item measures at most 26 bytes on the wire (%d)"), R.ItemBytes), R.ItemBytes > 0 && R.ItemBytes <= 26);
+ TestTrue(FString::Printf(TEXT("the reset burst after the storm is under 16 KB (%d bytes)"), R.ResetBurstBytes), R.ResetBurstBytes < 16 * 1024);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionTestUtil.h b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionTestUtil.h
new file mode 100644
index 0000000000..a6c913fdc9
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionTestUtil.h
@@ -0,0 +1,230 @@
+#pragma once
+
+#include "CoreMinimal.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Engine/Engine.h"
+#include "Engine/World.h"
+#include "Misc/AutomationTest.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "Pieces/VerseDestructionSim.h"
+#include "Pieces/VersePieceManifest.h"
+#include "Pieces/VersePieceTypes.h"
+#include "VerseRng.h"
+
+// Shared fixtures of the Verse.Destruction.* tests: one placeholder piece per class with the
+// class's real dimensions and material thickness (the shapes art/verse/kit/destructible builds),
+// a seeded test arena, and helpers that drive the simulation in fixed server ticks.
+
+#define VERSE_DESTRUCTION_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+namespace VerseDestructionTest
+{
+ inline constexpr uint32 TickMs = 33; // 30 Hz server
+
+ /** Piece-local Intact box of a class (centred on X, floor at Z = 0, thickness along +Y or +Z). */
+ inline FBox ClassBox(EVersePieceClass Class)
+ {
+ switch (Class)
+ {
+ case EVersePieceClass::WallPanel:
+ return FBox(FVector(-120, 0, 0), FVector(120, 0.3, 270));
+ case EVersePieceClass::CladdingWall:
+ return FBox(FVector(-120, 0, 0), FVector(120, 4.0, 270));
+ case EVersePieceClass::ContainerWall:
+ return FBox(FVector(-120, 0, 0), FVector(120, 4.0, 259)); // 0.4 cm sheet, 4 cm corrugation depth
+ case EVersePieceClass::GlassPane:
+ return FBox(FVector(-60, 0, 90), FVector(60, 2.4, 240));
+ case EVersePieceClass::CatwalkSegment:
+ return FBox(FVector(-120, -60, 0), FVector(120, 60, 3.0));
+ case EVersePieceClass::CeilingPanel:
+ return FBox(FVector(-60, -60, 0), FVector(60, 60, 2.5));
+ }
+ return FBox(FVector(-50), FVector(50));
+ }
+
+ inline FVersePieceDef MakePiece(EVersePieceClass Class, const FVector& Location, int32 Serial)
+ {
+ FVersePieceDef Def;
+ Def.Guid = FGuid(0x0600u, uint32(Class), uint32(Serial), 0x1u);
+ Def.Class = Class;
+ Def.Material = VerseMaterialOfClass(Class);
+ Def.Transform = FTransform(Location);
+ Def.IntactBounds = ClassBox(Class);
+ const bool bWall = Class == EVersePieceClass::WallPanel || Class == EVersePieceClass::CladdingWall || Class == EVersePieceClass::ContainerWall;
+ if (bWall)
+ {
+ const FBox B = Def.IntactBounds;
+ // Two holed variants (left, right) and two breached variants (standing, low).
+ Def.HoledCentroids = {FVector(-60, 0, 140), FVector(60, 0, 140)};
+ Def.HoledBounds = {B, B};
+ Def.BreachedCentroids = {FVector(0, 0, 110), FVector(0, 0, 50)};
+ Def.BreachedBounds = {FBox(B.Min, FVector(B.Max.X, B.Max.Y, B.Max.Z)), FBox(B.Min, B.Max)};
+ Def.MantleLinks.Add({FVector(0, -60, 0), FVector(0, 60, 0)});
+ }
+ if (Class == EVersePieceClass::CatwalkSegment)
+ {
+ Def.DropLinks.Add({FVector(110, 0, 3), FVector(170, 0, -300)});
+ }
+ return Def;
+ }
+
+ /** A dense test arena: container rows plus walls, glass, catwalks and ceiling tiles (about 600 pieces). */
+ inline TArray<FVersePieceDef> MakeArena(int32 ContainerRows = 30, int32 PerRow = 8)
+ {
+ TArray<FVersePieceDef> Defs;
+ int32 Serial = 0;
+ for (int32 Row = 0; Row < ContainerRows; ++Row)
+ {
+ for (int32 Col = 0; Col < PerRow; ++Col)
+ {
+ Defs.Add(MakePiece(EVersePieceClass::ContainerWall, FVector(Col * 245.0, Row * 600.0, 0), Serial++));
+ }
+ Defs.Add(MakePiece(EVersePieceClass::GlassPane, FVector(-200.0, Row * 600.0 + 60.0, 0), Serial++));
+ Defs.Add(MakePiece(EVersePieceClass::CeilingPanel, FVector(100.0, Row * 600.0 + 60.0, 280.0), Serial++));
+ }
+ for (int32 Index = 0; Index < 210; ++Index)
+ {
+ Defs.Add(MakePiece(Index % 2 ? EVersePieceClass::WallPanel : EVersePieceClass::CladdingWall,
+ FVector(3000.0 + (Index % 10) * 250.0, (Index / 10) * 600.0, 0), Serial++));
+ }
+ for (int32 Index = 0; Index < 90; ++Index)
+ {
+ Defs.Add(MakePiece(Index % 3 ? EVersePieceClass::CatwalkSegment : EVersePieceClass::CeilingPanel,
+ FVector(-1500.0 + (Index % 9) * 250.0, (Index / 9) * 1200.0, 450.0), Serial++));
+ }
+ return Defs;
+ }
+
+ inline TArray<FVector> Docks(int32 Count)
+ {
+ TArray<FVector> Out;
+ for (int32 Index = 0; Index < Count; ++Index)
+ {
+ Out.Add(FVector(-800.0, Index * 400.0, 600.0));
+ }
+ return Out;
+ }
+
+ inline FVersePieceDamage Bolt(const FVersePieceDef& Def, float Amount = 10.f, const FVector& Local = FVector(0, 0, 140))
+ {
+ FVersePieceDamage Damage;
+ Damage.Cause = EVerseFractureCause::Bolt;
+ Damage.Amount = Amount;
+ Damage.Location = Def.Transform.TransformPosition(Local);
+ Damage.Direction = FVector(0, 1, 0);
+ Damage.InstigatorId = 0;
+ return Damage;
+ }
+
+ inline FVersePieceDamage Breach(const FVersePieceDef& Def, const FVector& Local = FVector(0, -5, 110))
+ {
+ FVersePieceDamage Damage;
+ Damage.Cause = EVerseFractureCause::Breach;
+ Damage.Amount = 1000.f;
+ Damage.Location = Def.Transform.TransformPosition(Local);
+ Damage.Direction = FVector(0, 1, 0);
+ Damage.BreachRadiusCm = 150.f;
+ Damage.InstigatorId = 1;
+ return Damage;
+ }
+
+ /** A knife strike; 5 piece damage, so intact glass cracks instead of shattering at once. */
+ inline FVersePieceDamage Melee(const FVersePieceDef& Def, float Amount = 5.f)
+ {
+ FVersePieceDamage Damage = Bolt(Def, Amount);
+ Damage.Cause = EVerseFractureCause::Melee;
+ return Damage;
+ }
+
+ /** A bare game world (subsystems, no game mode); ticks only what the test ticks. */
+ struct FTestWorld
+ {
+ UWorld* World = nullptr;
+
+ explicit FTestWorld(const TCHAR* Name)
+ {
+ World = UWorld::CreateWorld(EWorldType::Game, false, Name);
+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);
+ Context.SetCurrentWorld(World);
+ World->InitializeActorsForPlay(FURL());
+ }
+
+ ~FTestWorld()
+ {
+ GEngine->DestroyWorldContext(World);
+ World->DestroyWorld(false);
+ }
+
+ /** Advances world time; in steps, since the world clamps one frame to its max delta (0.4 s). */
+ void Advance(float Seconds)
+ {
+ while (Seconds > 0.f)
+ {
+ const float Step = FMath::Min(Seconds, 0.25f);
+ World->Tick(LEVELTICK_TimeOnly, Step);
+ Seconds -= Step;
+ }
+ }
+
+ AVerseDestructible* SpawnPiece(const FVersePieceDef& Def)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AVerseDestructible* Piece = World->SpawnActor<AVerseDestructible>(AVerseDestructible::StaticClass(), Def.Transform, Params);
+ Piece->PieceClass = Def.Class;
+ Piece->Material = Def.Material;
+ Piece->FallbackIntactBounds = Def.IntactBounds;
+ Piece->SetPieceGuid(Def.Guid);
+ for (int32 Index = 0; Index < Def.HoledCentroids.Num(); ++Index)
+ {
+ Piece->HoledVariants.AddDefaulted_GetRef().OpeningCentroid = Def.HoledCentroids[Index];
+ }
+ for (int32 Index = 0; Index < Def.BreachedCentroids.Num(); ++Index)
+ {
+ Piece->BreachedVariants.AddDefaulted_GetRef().OpeningCentroid = Def.BreachedCentroids[Index];
+ }
+ return Piece;
+ }
+
+ AVerseDestructionManager* SpawnManager(bool bClient, int32 NumDocks = 0, UVersePieceManifest* Manifest = nullptr)
+ {
+ FActorSpawnParameters Params;
+ Params.bDeferConstruction = true;
+ AVerseDestructionManager* Manager = World->SpawnActor<AVerseDestructionManager>(AVerseDestructionManager::StaticClass(), FTransform::Identity, Params);
+ Manager->DroneDocks = VerseDestructionTest::Docks(NumDocks);
+ Manager->Manifest = Manifest;
+ if (bClient)
+ {
+ Manager->SetRole(ROLE_SimulatedProxy);
+ }
+ Manager->FinishSpawning(FTransform::Identity);
+ Manager->RegisterPieces();
+ return Manager;
+ }
+ };
+
+ inline bool NeverEncroached(const FBox&) { return false; }
+
+ /** Ticks the simulation from FromMs to ToMs (exclusive) and drains its outputs; returns the time reached. */
+ inline uint32 Run(FVerseDestructionSim& Sim, uint32 FromMs, uint32 ToMs, TArray<FVersePendingFracture>* OutEvents = nullptr)
+ {
+ uint32 Now = FromMs;
+ for (; Now < ToMs; Now += TickMs)
+ {
+ Sim.Tick(Now, [](const FBox&) { return false; });
+ TArray<FVersePendingFracture> Events = Sim.DrainEvents();
+ if (OutEvents)
+ {
+ OutEvents->Append(Events);
+ }
+ Sim.DrainNoise();
+ Sim.DrainDirtyItems();
+ }
+ return Now;
+ }
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionUnitsTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionUnitsTest.cpp
new file mode 100644
index 0000000000..54a80cca0f
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionUnitsTest.cpp
@@ -0,0 +1,382 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Debris/VerseDebrisBudget.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VersePieceManifest.h"
+#include "Validation/VerseDestructibleValidator.h"
+
+using namespace VerseDestructionTest;
+
+// 6.9: full reset bumps the epoch, sets every item Intact with full HP, recalls drones, dirties
+// nav and multicasts the reset event; the burst stays under 16 KB.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionReset, "Verse.Destruction.Reset", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionReset::RunTest(const FString&)
+{
+ FVerseDestructionSim Sim;
+ Sim.Init(MakeArena(), FVerseDestructionSimTuning::Contract(), Docks(3), 5);
+ TestTrue(TEXT("arena of about 600 pieces"), Sim.Num() >= 590 && Sim.Num() <= 2000);
+ uint32 Now = 0;
+ // Break every piece, then let three drones start repairing.
+ for (int32 Index = 0; Index < Sim.Num(); ++Index)
+ {
+ FVersePieceDamage D = Breach(Sim.GetDef(uint16(Index)), FVector(0, 0, 1));
+ D.PieceIndex = uint16(Index);
+ D.BreachRadiusCm = 1.f; // only the target
+ Sim.ApplyDamage(D, Now);
+ }
+ Now = Run(Sim, 0, 63000);
+ TestEqual(TEXT("three drones busy"), Sim.NumActiveDrones(), 3);
+ Sim.DrainEvents();
+ Sim.FullReset(Now);
+ TestEqual(TEXT("epoch bumped"), int32(Sim.GetEpoch()), 1);
+ int32 NotIntact = 0;
+ for (const FVersePieceItem& Item : Sim.GetItems())
+ {
+ NotIntact += (Item.State != EVersePieceState::Intact || Item.HealthQ != 255 || Item.Variant != 0) ? 1 : 0;
+ }
+ TestEqual(TEXT("every item Intact at full HP"), NotIntact, 0);
+ TestEqual(TEXT("drones recalled"), Sim.NumActiveDrones(), 0);
+ const TArray<FVersePendingFracture> Events = Sim.DrainEvents();
+ if (TestEqual(TEXT("one reset event"), Events.Num(), 1))
+ {
+ TestEqual(TEXT("PieceIndex 0xFFFF"), int32(Events[0].Event.PieceIndex), 0xFFFF);
+ TestEqual(TEXT("Cause Reset"), Events[0].Event.Cause, EVerseFractureCause::Reset);
+ TestEqual(TEXT("new epoch on the event"), int32(Events[0].Event.Epoch), 1);
+ TestTrue(TEXT("the reset is always multicast"), Events[0].bMulticast);
+ }
+ TestTrue(FString::Printf(TEXT("reset burst under 16 KB (%d bytes)"), Sim.GetLastResetBurstBytes()), Sim.GetLastResetBurstBytes() < 16 * 1024);
+ TestEqual(TEXT("every broken item is written once"), Sim.DrainDirtyItems().Num(), Sim.Num());
+ TestTrue(TEXT("nav tiles queued for the rebuild"), Sim.GetNav().NumQueued() > 0);
+ // A second reset with nothing broken writes nothing.
+ Sim.FullReset(Now + 100);
+ TestEqual(TEXT("an intact arena costs no items"), Sim.DrainDirtyItems().Num(), 0);
+ const int32 RepairsBefore = Sim.GetCounters().Repairs;
+ Run(Sim, Now + 100, Now + 70000);
+ TestEqual(TEXT("nothing to repair after a reset"), Sim.GetCounters().Repairs, RepairsBefore);
+ return true;
+}
+
+// 6.7 / A6.4 (logic part): a change dirties old and new proxy bounds +50 cm, at most 4 tiles in
+// flight, and a breach's tiles are handed to navigation within 100 ms. Mantle links live while
+// Breached, drop links while Destroyed.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionNav, "Verse.Destruction.Nav", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionNav::RunTest(const FString&)
+{
+ {
+ FVerseNavDirtyQueue Queue(4, 50.f);
+ Queue.MarkDirty(FBox(FVector(10, 10, 0), FVector(20, 20, 100)));
+ TestEqual(TEXT("a small box near the tile corner dirties 4 tiles with the margin"), Queue.NumQueued(), 4);
+ Queue.MarkDirty(FBox(FVector(10, 10, 0), FVector(20, 20, 300)));
+ TestEqual(TEXT("the same tiles merge"), Queue.NumQueued(), 4);
+ Queue.MarkDirty(FBox(FVector(700, 700, 0), FVector(750, 750, 10)));
+ TestEqual(TEXT("a far box adds its tile"), Queue.NumQueued(), 5);
+ TArray<FVerseNavDirtyQueue::FTile> First = Queue.Release(0);
+ TestEqual(TEXT("at most 4 in flight"), First.Num(), 4);
+ TestEqual(TEXT("nothing more while 4 are in flight"), Queue.Release(0).Num(), 0);
+ TestEqual(TEXT("a finished tile frees a slot"), Queue.Release(1).Num(), 1);
+ TestEqual(TEXT("merged z range"), First[0].MaxZ, 350.f);
+ }
+ // 100 trials: a breach at a random place is released to navigation within 100 ms.
+ FVerseRng Rng(0x6A4);
+ int32 Within = 0;
+ for (int32 Trial = 0; Trial < 100; ++Trial)
+ {
+ const FVector At(Rng.Range(-5000, 5000), Rng.Range(-3000, 3000), 0);
+ FVersePieceDef Wall = MakePiece(EVersePieceClass::ContainerWall, At, Trial);
+ Wall.Transform.SetRotation(FQuat(FVector::UpVector, Rng.Range(0, PI)));
+ FVerseDestructionSim Sim;
+ Sim.Init({Wall}, FVerseDestructionSimTuning::Contract(), {}, uint64(Trial));
+ FVersePieceDamage Charge = Breach(Wall);
+ Sim.ApplyDamage(Charge, 0);
+ FBox Expected = Wall.GetWorldBounds(EVersePieceState::Intact, 0).ExpandBy(50.f);
+ const int32 Dirty = Sim.GetNav().NumQueued();
+ int32 Released = 0;
+ bool bCovers = true;
+ uint32 Now = 0;
+ for (; Now <= 100 && Sim.GetNav().NumQueued() > 0; Now += TickMs)
+ {
+ for (const FVerseNavDirtyQueue::FTile& Tile : Sim.GetNav().Release(Sim.GetNav().NumInFlight()))
+ {
+ ++Released;
+ bCovers &= Tile.GetBox().Intersect(Expected) && Tile.PieceIndex == 0;
+ }
+ TestTrue(TEXT("never more than 4 tiles in flight"), Sim.GetNav().NumInFlight() <= 4);
+ }
+ if (Sim.GetNav().NumQueued() == 0 && Released == Dirty && bCovers && Dirty > 0)
+ {
+ ++Within;
+ }
+ }
+ TestEqual(TEXT("100 of 100 breaches handed to navigation within 100 ms"), Within, 100);
+
+ // Nav links follow the state.
+ FVersePieceDef Wall = MakePiece(EVersePieceClass::WallPanel, FVector(100, 0, 0), 1);
+ FVersePieceDef Catwalk = MakePiece(EVersePieceClass::CatwalkSegment, FVector(0, 500, 300), 2);
+ FVerseDestructionSim Sim;
+ Sim.Init({Wall, Catwalk}, FVerseDestructionSimTuning::Contract(), {}, 1);
+ EVersePieceNavLinkKind Kind = EVersePieceNavLinkKind::Mantle;
+ TestEqual(TEXT("no links while Intact"), Sim.GetLiveNavLinks(0, Kind).Num(), 0);
+ FVersePieceDamage D = Breach(Wall, FVector(0, -5, 40));
+ D.BreachRadiusCm = 1.f;
+ Sim.ApplyDamage(D, 0);
+ const TArray<FVersePieceNavLink> Mantle = Sim.GetLiveNavLinks(0, Kind);
+ TestEqual(TEXT("a low breach opens its mantle link"), Mantle.Num(), 1);
+ TestEqual(TEXT("mantle kind"), Kind, EVersePieceNavLinkKind::Mantle);
+ TestTrue(TEXT("links in world space"), Mantle.Num() == 1 && Mantle[0].Start.Equals(FVector(100, -60, 0)));
+ D = Breach(Catwalk, FVector(0, 0, 5));
+ D.PieceIndex = 1;
+ D.BreachRadiusCm = 1.f;
+ Sim.ApplyDamage(D, 0);
+ TestEqual(TEXT("a destroyed catwalk adds its drop links"), Sim.GetLiveNavLinks(1, Kind).Num(), 1);
+ TestEqual(TEXT("drop kind"), Kind, EVersePieceNavLinkKind::Drop);
+ TestFalse(TEXT("a destroyed catwalk has no walkable proxy"), Sim.GetPieceBounds(1).IsValid != 0);
+ return true;
+}
+
+// 6.4: DA_PieceManifest index rule (destruction.md 8).
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionManifest, "Verse.Destruction.Manifest", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionManifest::RunTest(const FString&)
+{
+ UVersePieceManifest* Manifest = NewObject<UVersePieceManifest>();
+ TArray<FGuid> Guids;
+ FVerseRng Rng(8);
+ for (int32 Index = 0; Index < 600; ++Index)
+ {
+ Guids.Add(FGuid(Rng.NextU32(), Rng.NextU32(), Rng.NextU32(), Rng.NextU32() | 1u));
+ }
+ TArray<FGuid> Shuffled = Guids;
+ for (int32 Index = Shuffled.Num() - 1; Index > 0; --Index)
+ {
+ Shuffled.Swap(Index, Rng.RangeInt(0, Index));
+ }
+ FString Error;
+ TestTrue(TEXT("builds"), Manifest->Build(Shuffled, &Error));
+ TestTrue(TEXT("consistent"), Manifest->IsConsistent());
+ UVersePieceManifest* Other = NewObject<UVersePieceManifest>();
+ Other->Build(Guids);
+ TestEqual(TEXT("order independent: same list"), Manifest->PieceGuids, Other->PieceGuids);
+ TestEqual(TEXT("order independent: same hash (server welcome check)"), Manifest->Hash, Other->Hash);
+ for (int32 Index = 0; Index < Manifest->PieceGuids.Num(); ++Index)
+ {
+ if (Manifest->IndexOf(Manifest->PieceGuids[Index]) != Index)
+ {
+ AddError(TEXT("IndexOf disagrees with the list"));
+ break;
+ }
+ }
+ TestEqual(TEXT("unknown GUID"), Manifest->IndexOf(FGuid(1, 2, 3, 4)), int32(INDEX_NONE));
+ Other->Build(TArray<FGuid>(Guids.GetData(), 599));
+ TestNotEqual(TEXT("a missing piece changes the hash"), Manifest->Hash, Other->Hash);
+ TArray<FGuid> TooMany;
+ for (int32 Index = 0; Index < 2001; ++Index)
+ {
+ TooMany.Add(FGuid(1, 2, 3, uint32(Index + 1)));
+ }
+ TestFalse(TEXT("more than 2,000 pieces per deck fail"), Other->Build(TooMany, &Error));
+ TestFalse(TEXT("an invalid GUID fails"), Other->Build({FGuid()}, &Error));
+ Manifest->Hash ^= 1u;
+ TestFalse(TEXT("a wrong hash is inconsistent"), Manifest->IsConsistent());
+ return true;
+}
+
+namespace
+{
+ FVerseMeshSoup Corrugated(float Sheet, float Depth, float Width, float Height, int32 Ribs)
+ {
+ // Trapezoid ribs as a closed solid: the sheet's two faces follow the same zigzag profile,
+ // offset by the sheet thickness, extruded along Z.
+ TArray<FVector2D> Outer;
+ const float Pitch = Width / Ribs;
+ for (int32 Rib = 0; Rib < Ribs; ++Rib)
+ {
+ const float X = -Width * 0.5f + Rib * Pitch;
+ Outer.Add({X, 0});
+ Outer.Add({X + Pitch * 0.25f, 0});
+ Outer.Add({X + Pitch * 0.375f, Depth});
+ Outer.Add({X + Pitch * 0.875f, Depth});
+ }
+ Outer.Add({Width * 0.5f, 0});
+ FVerseMeshSoup Mesh;
+ // Build the profile polygon: outer line then the inner line offset by Sheet along +Y (flat parts exact).
+ TArray<FVector2D> Poly = Outer;
+ for (int32 Index = Outer.Num() - 1; Index >= 0; --Index)
+ {
+ Poly.Add(Outer[Index] + FVector2D(0, Sheet));
+ }
+ // Extrude: side quads around the polygon, caps triangulated as quads between the two lines.
+ const int32 N = Poly.Num();
+ for (int32 Index = 0; Index < N; ++Index)
+ {
+ const FVector2D& A = Poly[Index];
+ const FVector2D& B = Poly[(Index + 1) % N];
+ Mesh.AddQuad(FVector(A.X, A.Y, 0), FVector(B.X, B.Y, 0), FVector(B.X, B.Y, Height), FVector(A.X, A.Y, Height));
+ }
+ const int32 M = Outer.Num();
+ for (int32 Index = 0; Index + 1 < M; ++Index)
+ {
+ const FVector2D O0 = Outer[Index];
+ const FVector2D O1 = Outer[Index + 1];
+ const FVector2D I0 = O0 + FVector2D(0, Sheet);
+ const FVector2D I1 = O1 + FVector2D(0, Sheet);
+ Mesh.AddQuad(FVector(O0.X, O0.Y, 0), FVector(I0.X, I0.Y, 0), FVector(I1.X, I1.Y, 0), FVector(O1.X, O1.Y, 0));
+ Mesh.AddQuad(FVector(O0.X, O0.Y, Height), FVector(O1.X, O1.Y, Height), FVector(I1.X, I1.Y, Height), FVector(I0.X, I0.Y, Height));
+ }
+ return Mesh;
+ }
+
+ FVerseMeshSoup Grating(float Length, float Width, float Height, float Bar, float Spacing)
+ {
+ FVerseMeshSoup Mesh;
+ for (float Y = -Width * 0.5f; Y + Bar <= Width * 0.5f + 0.01f; Y += Spacing)
+ {
+ Mesh.AddBox(FVector(-Length * 0.5f, Y, 0), FVector(Length * 0.5f, Y + Bar, Height));
+ }
+ return Mesh;
+ }
+}
+
+// A6.6: the validator fails a double-plane wall and a missing proxy and passes the shipped shapes.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionValidator, "Verse.Destruction.Validator", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionValidator::RunTest(const FString&)
+{
+ using V = UVerseDestructibleValidator;
+ struct FShape
+ {
+ EVersePieceClass Class;
+ FVerseMeshSoup Mesh;
+ };
+ TArray<FShape> Shapes;
+ {
+ FVerseMeshSoup M;
+ M.AddBox(FVector(-120, 0, 0), FVector(120, 0.3, 270));
+ Shapes.Add({EVersePieceClass::WallPanel, M});
+ }
+ {
+ FVerseMeshSoup M;
+ M.AddBox(FVector(-120, 0, 0), FVector(120, 4.0, 270));
+ Shapes.Add({EVersePieceClass::CladdingWall, M});
+ }
+ Shapes.Add({EVersePieceClass::ContainerWall, Corrugated(0.4f, 4.f, 240.f, 259.f, 8)});
+ {
+ FVerseMeshSoup M;
+ M.AddBox(FVector(-60, 0, 90), FVector(60, 2.4, 240));
+ Shapes.Add({EVersePieceClass::GlassPane, M});
+ }
+ Shapes.Add({EVersePieceClass::CatwalkSegment, Grating(240.f, 120.f, 3.f, 0.5f, 3.f)});
+ {
+ FVerseMeshSoup M;
+ M.AddBox(FVector(-60, -60, 0), FVector(60, 60, 2.5));
+ Shapes.Add({EVersePieceClass::CeilingPanel, M});
+ }
+ for (const FShape& Shape : Shapes)
+ {
+ const FVerseValidationReport Report = V::CheckSolid(Shape.Mesh, V::ThicknessAxis(Shape.Class), V::RefThicknessCm(Shape.Class));
+ TestTrue(FString::Printf(TEXT("%s passes (%.3f cm): %s"), *UEnum::GetValueAsString(Shape.Class), Report.MeasuredThicknessCm,
+ *FString::Join(Report.Errors, TEXT("; "))),
+ Report.IsOk());
+ }
+ {
+ // Two coincident-free planes 0.3 cm apart: the old thin double-plane wall.
+ FVerseMeshSoup Double;
+ Double.AddQuad(FVector(-120, 0, 0), FVector(120, 0, 0), FVector(120, 0, 270), FVector(-120, 0, 270));
+ Double.AddQuad(FVector(-120, 0.3, 0), FVector(-120, 0.3, 270), FVector(120, 0.3, 270), FVector(120, 0.3, 0));
+ const FVerseValidationReport Report = V::CheckSolid(Double, FVector::RightVector, 0.3f);
+ TestFalse(TEXT("a double-plane wall fails"), Report.IsOk());
+ TestTrue(TEXT("as not watertight"), Report.Errors.Num() > 0 && Report.Errors[0].Contains(TEXT("watertight")));
+ }
+ {
+ FVerseMeshSoup Box;
+ Box.AddBox(FVector(-120, 0, 0), FVector(120, 10.0, 270));
+ TestFalse(TEXT("a 10 cm sheet-metal wall fails the thickness rule"), V::CheckSolid(Box, FVector::RightVector, 0.3f).IsOk());
+ FVerseMeshSoup Open;
+ Open.AddBox(FVector(-120, 0, 0), FVector(120, 0.3, 270));
+ Open.Indices.SetNum(Open.Indices.Num() - 6); // drop one face
+ TestFalse(TEXT("an open shell fails"), V::CheckClosed(Open).IsOk());
+ FVerseMeshSoup Flipped;
+ Flipped.AddBox(FVector(-120, 0, 0), FVector(120, 0.3, 270));
+ Swap(Flipped.Indices[0], Flipped.Indices[1]); // one triangle wound the wrong way
+ TestFalse(TEXT("an inconsistently wound face fails"), V::CheckClosed(Flipped).IsOk());
+ }
+ // Piece level: a wall actor without proxies or geometry collection fails with clear errors.
+ FTestWorld World(TEXT("VerseDestructionValidator"));
+ AVerseDestructible* Piece = World.World->SpawnActor<AVerseDestructible>();
+ Piece->PieceClass = EVersePieceClass::WallPanel;
+ Piece->Material = EVersePenetrationMaterial::SheetMetal;
+ Piece->SetPieceGuid(FGuid(6, 6, 6, 6));
+ UVersePieceManifest* Manifest = NewObject<UVersePieceManifest>();
+ Manifest->Build({FGuid(1, 1, 1, 1)});
+ const FVerseValidationReport Report = V::ValidatePiece(*Piece, Manifest);
+ const FString All = FString::Join(Report.Errors, TEXT("; "));
+ TestTrue(TEXT("missing Intact proxy reported: ") + All, All.Contains(TEXT("missing proxy: Intact")));
+ TestTrue(TEXT("missing Holed proxy reported"), All.Contains(TEXT("missing proxy: Holed")));
+ TestTrue(TEXT("missing Breached proxy reported"), All.Contains(TEXT("missing proxy: Breached")));
+ TestTrue(TEXT("missing geometry collection reported"), All.Contains(TEXT("geometry collection")));
+ TestTrue(TEXT("not in the manifest reported"), All.Contains(TEXT("manifest")));
+ Piece->Material = EVersePenetrationMaterial::Glass;
+ TestTrue(TEXT("a material that does not match the class fails"),
+ FString::Join(V::ValidatePiece(*Piece, nullptr).Errors, TEXT(";")).Contains(TEXT("does not match")));
+ return true;
+}
+
+// 6.5 (budget part): caps, oldest first, lifetimes, Niagara-only types.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionDebrisBudget, "Verse.Destruction.Debris.Budget", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionDebrisBudget::RunTest(const FString&)
+{
+ FVerseDebrisBudget Budget(FVerseDebrisBudget::FConfig::High());
+ FVerseDebrisBudget::FRequest BreachReq;
+ BreachReq.Type = EVerseDebrisType::PanelChunks;
+ BreachReq.ToState = EVersePieceState::Breached;
+ double Now = 0.0;
+ int32 FirstId = 0;
+ for (int32 Index = 0; Index < 20; ++Index)
+ {
+ BreachReq.PieceIndex = uint16(Index);
+ const FVerseDebrisBudget::FGrant Grant = Budget.Request(BreachReq, Now);
+ FirstId = FirstId ? FirstId : Grant.BurstId;
+ TestTrue(TEXT("at most 40 per fracture"), Grant.Bodies <= 40);
+ TestTrue(TEXT("never above 400 bodies"), Budget.ActiveBodies() <= 400);
+ TestTrue(TEXT("never above 32 actors"), Budget.AliveActors() <= 32);
+ if (Index == 10)
+ {
+ TestTrue(TEXT("the oldest is evicted first"), Grant.Evicted.Num() > 0 && Grant.Evicted[0] == FirstId);
+ }
+ Now += 0.01;
+ }
+ TestEqual(TEXT("the cap is held at 400"), Budget.ActiveBodies(), 400);
+ FVerseDebrisBudget::FRequest GlassReq;
+ GlassReq.Type = EVerseDebrisType::GlassShards;
+ GlassReq.ToState = EVersePieceState::Destroyed;
+ const FVerseDebrisBudget::FGrant GlassGrant = Budget.Request(GlassReq, Now);
+ TestEqual(TEXT("glass: no rigid bodies"), GlassGrant.Bodies, 0);
+ TestTrue(TEXT("glass: Niagara shards"), GlassGrant.bNiagara);
+ FVerseDebrisBudget::FRequest ScorchReq;
+ ScorchReq.Type = EVerseDebrisType::MetalShards;
+ ScorchReq.ToState = EVersePieceState::Damaged;
+ TestEqual(TEXT("Damaged: sparks only"), Budget.Request(ScorchReq, Now).Bodies, 0);
+ FVerseDebrisBudget::FRequest TileReq;
+ TileReq.Type = EVerseDebrisType::CeilingTile;
+ TileReq.ToState = EVersePieceState::Destroyed;
+ TestEqual(TEXT("a ceiling tile falls whole"), FVerseDebrisBudget::DesiredBodies(TileReq.Type, TileReq.ToState), 1);
+ Budget.Tick(Now + 3.0);
+ TestTrue(TEXT("asleep after 3 s"), Budget.GetBursts().Num() > 0 && Budget.GetBursts().Last().bAsleep);
+ Budget.Tick(Now + 10.0);
+ Budget.Tick(Now + 10.31);
+ TestEqual(TEXT("despawned after 10 s plus the 0.3 s fade"), Budget.ActiveBodies(), 0);
+ TestEqual(TEXT("and gone"), Budget.GetBursts().Num(), 0);
+
+ FVerseDebrisBudget LowBudget(FVerseDebrisBudget::FConfig::Low());
+ for (int32 Index = 0; Index < 10; ++Index)
+ {
+ LowBudget.Request(BreachReq, 0.0);
+ }
+ TestTrue(TEXT("Low holds 150"), LowBudget.ActiveBodies() <= 150);
+ LowBudget.Tick(6.0);
+ LowBudget.Tick(6.31);
+ TestEqual(TEXT("Low despawns at 6 s"), LowBudget.GetBursts().Num(), 0);
+ TestEqual(TEXT("purge on reset"), Budget.PurgeAll().Num(), 0);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionWorldTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionWorldTest.cpp
new file mode 100644
index 0000000000..38aa05b35e
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Destruction/VerseDestructionWorldTest.cpp
@@ -0,0 +1,213 @@
+#include "Tests/Destruction/VerseDestructionTestUtil.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Algo/Reverse.h"
+#include "Debris/VerseDebrisSubsystem.h"
+#include "Engine/Engine.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VerseDestructionManager.h"
+#include "Pieces/VersePieceManifest.h"
+#include "Repair/VerseRepairDrone.h"
+#include "VerseGameplayTags.h"
+
+using namespace VerseDestructionTest;
+
+namespace
+{
+ TArray<FVersePieceDef> SmallArena()
+ {
+ TArray<FVersePieceDef> Defs;
+ const EVersePieceClass Classes[] = {EVersePieceClass::WallPanel, EVersePieceClass::CladdingWall, EVersePieceClass::ContainerWall,
+ EVersePieceClass::GlassPane, EVersePieceClass::CatwalkSegment, EVersePieceClass::CeilingPanel};
+ for (int32 Index = 0; Index < 30; ++Index)
+ {
+ const EVersePieceClass Class = Classes[Index % 6];
+ const double Z = Class == EVersePieceClass::CatwalkSegment ? 300.0 : (Class == EVersePieceClass::CeilingPanel ? 600.0 : 0.0);
+ Defs.Add(MakePiece(Class, FVector((Index % 6) * 260.0, (Index / 6) * 400.0, Z), 100 + Index));
+ }
+ return Defs;
+ }
+
+ /** Seeded mix of bolts, melee and breach charges on random pieces. */
+ void RandomChanges(AVerseDestructionManager& Server, int32 MinChanges, uint64 Seed, FTestWorld& World)
+ {
+ FVerseRng Rng(Seed);
+ int32 Guard = 20000;
+ while (Server.GetSim().GetCounters().StateChanges < MinChanges && Guard-- > 0)
+ {
+ const int32 Index = Rng.RangeInt(0, Server.NumPieces() - 1);
+ const FVersePieceDef& Def = Server.GetSim().GetDef(uint16(Index));
+ const FBox Box = Def.IntactBounds;
+ const FVector Local(Rng.Range(Box.Min.X, Box.Max.X), Box.Min.Y - 1.0, Rng.Range(Box.Min.Z, Box.Max.Z));
+ const double Roll = Rng.NextUnit();
+ FVersePieceDamage Damage = Roll < 0.85 ? Bolt(Def, 10.f, Local) : (Roll < 0.95 ? Melee(Def) : Breach(Def, Local));
+ Damage.PieceIndex = uint16(Index);
+ Server.GetPieceDamage().ApplyPieceDamage(Damage);
+ World.Advance(0.05f);
+ if (Rng.Chance(0.02))
+ {
+ // A lull longer than the 60 s repair delay: drones fly out and repair in between.
+ for (int32 Step = 0; Step < 8; ++Step)
+ {
+ World.Advance(12.f);
+ Server.Tick(0.05f);
+ }
+ }
+ }
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionWorld, "Verse.Destruction.World.ManagerAndPieces", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionWorld::RunTest(const FString&)
+{
+ FTestWorld W(TEXT("VerseDestructionWorld"));
+ const TArray<FVersePieceDef> Defs = SmallArena();
+ for (const FVersePieceDef& Def : Defs)
+ {
+ W.SpawnPiece(Def);
+ }
+ AVerseDestructionManager* Manager = W.SpawnManager(false, 2);
+ TestEqual(TEXT("every piece registered"), Manager->NumPieces(), Defs.Num());
+ TestTrue(TEXT("found through the world"), AVerseDestructionManager::Get(W.World) == Manager);
+ // Manifest order is GUID order, and the pieces know their index.
+ TArray<FGuid> Guids;
+ for (const FVersePieceDef& Def : Defs)
+ {
+ Guids.Add(Def.Guid);
+ }
+ UVersePieceManifest::SortGuids(Guids);
+ for (int32 Index = 0; Index < Guids.Num(); ++Index)
+ {
+ const AVerseDestructible* Piece = Manager->GetPieceActor(uint16(Index));
+ TestTrue(FString::Printf(TEXT("index %d in GUID order"), Index), Piece && Piece->GetPieceGuid() == Guids[Index] && Piece->GetPieceIndex() == Index);
+ }
+
+ UVerseEventHub* Hub = UVerseEventHub::Get(W.World);
+ TArray<FVerseFractureEvent> Fractures;
+ TArray<FVerseNoiseEvent> Noises;
+ if (!TestNotNull(TEXT("event hub"), Hub))
+ {
+ return false;
+ }
+ const FDelegateHandle A = Hub->OnFracture.AddLambda([&Fractures](const FVerseFractureEvent& E) { Fractures.Add(E); });
+ const FDelegateHandle B = Hub->OnNoise.AddLambda([&Noises](const FVerseNoiseEvent& E) { Noises.Add(E); });
+
+ // Find the glass pane and break it through the frozen damage interface.
+ int32 GlassIndex = INDEX_NONE;
+ for (int32 Index = 0; Index < Manager->NumPieces(); ++Index)
+ {
+ if (Manager->GetPieceMaterial(uint16(Index)) == EVersePenetrationMaterial::Glass)
+ {
+ GlassIndex = Index;
+ break;
+ }
+ }
+ AVerseDestructible* Glass = Manager->GetPieceActor(uint16(GlassIndex));
+ if (!TestNotNull(TEXT("a glass pane"), Glass))
+ {
+ return false;
+ }
+ FVersePieceDamage Damage = Breach(Manager->GetSim().GetDef(uint16(GlassIndex)));
+ Damage.PieceIndex = uint16(GlassIndex);
+ IVersePieceDamage& Sink = Manager->GetPieceDamage();
+ Sink.ApplyPieceDamage(Damage);
+ Manager->Tick(0.f); // events, noise and nav go out once per server tick
+ TestEqual(TEXT("IVersePieceQuery state"), Manager->GetPieceState(uint16(GlassIndex)), EVersePieceState::Destroyed);
+ TestEqual(TEXT("the piece shows it"), Glass->GetPresentedState(), EVersePieceState::Destroyed);
+ TestFalse(TEXT("destroyed glass has no gameplay bounds"), Manager->GetPieceBounds(uint16(GlassIndex)).IsValid != 0);
+ TestTrue(TEXT("hub got the fracture"), Fractures.ContainsByPredicate([GlassIndex](const FVerseFractureEvent& E)
+ { return E.PieceIndex == GlassIndex && E.ToState == EVersePieceState::Destroyed; }));
+ TestTrue(TEXT("hub got Noise.Fracture"), Noises.ContainsByPredicate([](const FVerseNoiseEvent& E) { return E.Noise == VerseTags::Noise_Fracture; }));
+ TestTrue(TEXT("item replicated state"), Manager->FindItem(uint16(GlassIndex)) && Manager->FindItem(uint16(GlassIndex))->State == EVersePieceState::Destroyed);
+
+ // Queries.
+ const FBox All(FVector(-1e5), FVector(1e5));
+ TestEqual(TEXT("GetPiecesInBox finds every piece"), Manager->GetPiecesInBox(All).Num(), Defs.Num());
+ TestEqual(TEXT("an unknown piece is Intact"), Manager->GetPieceState(9999), EVersePieceState::Intact);
+ TestFalse(TEXT("an unknown piece has no bounds"), Manager->GetPieceBounds(9999).IsValid != 0);
+
+ // Reset on the arena switch, with the reset event on the hub.
+ Manager->FullReset();
+ Manager->Tick(0.f);
+ TestEqual(TEXT("reset brings the glass back"), Manager->GetPieceState(uint16(GlassIndex)), EVersePieceState::Intact);
+ TestEqual(TEXT("epoch bumped"), int32(Manager->GetEpoch()), 1);
+ TestTrue(TEXT("reset event for all pieces"), Fractures.ContainsByPredicate([](const FVerseFractureEvent& E)
+ { return E.PieceIndex == Verse::Destruction::AllPieces && E.Cause == EVerseFractureCause::Reset; }));
+
+ // No debris without a renderer (DR3); the subsystem exists but stays off.
+ if (UVerseDebrisSubsystem* Debris = W.World->GetSubsystem<UVerseDebrisSubsystem>())
+ {
+ TestEqual(TEXT("no debris spawned headless"), Debris->GetSpawnedBursts(), 0);
+ }
+ Hub->OnFracture.Remove(A);
+ Hub->OnNoise.Remove(B);
+ return true;
+}
+
+// A6.2: a client joining after 200 changes builds the same proxy set as the server, 0 mismatches,
+// without spawning debris.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDestructionLateJoin, "Verse.Destruction.LateJoin", VERSE_DESTRUCTION_TEST_FLAGS)
+bool FVerseDestructionLateJoin::RunTest(const FString&)
+{
+ const TArray<FVersePieceDef> Defs = SmallArena();
+ FTestWorld ServerWorld(TEXT("VerseDestructionServer"));
+ for (const FVersePieceDef& Def : Defs)
+ {
+ ServerWorld.SpawnPiece(Def);
+ }
+ AVerseDestructionManager* Server = ServerWorld.SpawnManager(false, 3);
+ RandomChanges(*Server, 200, 0xA62, ServerWorld);
+ TestTrue(TEXT("at least 200 state changes"), Server->GetSim().GetCounters().StateChanges >= 200);
+
+ FTestWorld ClientWorld(TEXT("VerseDestructionClient"));
+ for (const FVersePieceDef& Def : Defs)
+ {
+ ClientWorld.SpawnPiece(Def);
+ }
+ AVerseDestructionManager* Client = ClientWorld.SpawnManager(true);
+ TestFalse(TEXT("client has no authority"), Client->HasAuthority());
+ int32 ClientFractures = 0;
+ UVerseEventHub* Hub = UVerseEventHub::Get(ClientWorld.World);
+ const FDelegateHandle Handle = Hub ? Hub->OnFracture.AddLambda([&ClientFractures](const FVerseFractureEvent&) { ++ClientFractures; }) : FDelegateHandle();
+
+ // The late joiner receives the whole fast array (destruction.md 3.3).
+ TArray<FVersePieceItem> Snapshot;
+ for (int32 Index = 0; Index < Server->NumPieces(); ++Index)
+ {
+ Snapshot.Add(*Server->FindItem(uint16(Index)));
+ }
+ // Delivered in reverse order: the client must not depend on arrival order.
+ Algo::Reverse(Snapshot);
+ Client->ReceiveItemsForTest(Snapshot, true);
+
+ int32 Mismatches = 0;
+ int32 Broken = 0;
+ for (int32 Index = 0; Index < Server->NumPieces(); ++Index)
+ {
+ const AVerseDestructible* S = Server->GetPieceActor(uint16(Index));
+ const AVerseDestructible* C = Client->GetPieceActor(uint16(Index));
+ if (!S || !C || S->GetPieceGuid() != C->GetPieceGuid() || S->GetPresentedState() != C->GetPresentedState()
+ || S->GetPresentedVariant() != C->GetPresentedVariant() || Server->GetPieceState(uint16(Index)) != Client->GetPieceState(uint16(Index)))
+ {
+ ++Mismatches;
+ }
+ Broken += Server->GetPieceState(uint16(Index)) != EVersePieceState::Intact ? 1 : 0;
+ }
+ TestEqual(TEXT("0 proxy mismatches between server and late joiner"), Mismatches, 0);
+ TestTrue(TEXT("the join saw broken pieces"), Broken > 0);
+ TestEqual(TEXT("the join raised no fracture event (no debris)"), ClientFractures, 0);
+ if (UVerseDebrisSubsystem* Debris = ClientWorld.World->GetSubsystem<UVerseDebrisSubsystem>())
+ {
+ TestEqual(TEXT("no debris spawned on join"), Debris->GetSpawnedBursts(), 0);
+ }
+ if (Hub)
+ {
+ Hub->OnFracture.Remove(Handle);
+ }
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseDestruction/Private/Validation/VerseDestructibleValidator.cpp b/unreal/Verse/Source/VerseDestruction/Private/Validation/VerseDestructibleValidator.cpp
new file mode 100644
index 0000000000..ae316dd585
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Private/Validation/VerseDestructibleValidator.cpp
@@ -0,0 +1,441 @@
+#include "Validation/VerseDestructibleValidator.h"
+
+#include "Destruction/VersePenetrationTable.h"
+#include "Components/StaticMeshComponent.h"
+#include "Engine/StaticMesh.h"
+#include "Pieces/VerseDestructible.h"
+#include "Pieces/VersePieceManifest.h"
+#include "Pieces/VersePieceTypes.h"
+#include "Debris/VerseDebrisBudget.h"
+#include "Debris/VerseDebrisSubsystem.h"
+#include "GeometryCollection/GeometryCollectionObject.h"
+#include "StaticMeshResources.h"
+#if WITH_EDITORONLY_DATA
+#include "MeshAttributes.h"
+#include "MeshDescription.h"
+#endif
+
+void FVerseMeshSoup::AddQuad(const FVector& A, const FVector& B, const FVector& C, const FVector& D)
+{
+ const int32 Base = Positions.Num();
+ Positions.Append({A, B, C, D});
+ Indices.Append({Base, Base + 1, Base + 2, Base, Base + 2, Base + 3});
+}
+
+void FVerseMeshSoup::AddBox(const FVector& Min, const FVector& Max)
+{
+ const FVector P[8] = {
+ {Min.X, Min.Y, Min.Z}, {Max.X, Min.Y, Min.Z}, {Max.X, Max.Y, Min.Z}, {Min.X, Max.Y, Min.Z},
+ {Min.X, Min.Y, Max.Z}, {Max.X, Min.Y, Max.Z}, {Max.X, Max.Y, Max.Z}, {Min.X, Max.Y, Max.Z},
+ };
+ // Outward, consistent winding.
+ AddQuad(P[0], P[3], P[2], P[1]); // bottom
+ AddQuad(P[4], P[5], P[6], P[7]); // top
+ AddQuad(P[0], P[1], P[5], P[4]); // -Y
+ AddQuad(P[2], P[3], P[7], P[6]); // +Y
+ AddQuad(P[1], P[2], P[6], P[5]); // +X
+ AddQuad(P[3], P[0], P[4], P[7]); // -X
+}
+
+void FVerseValidationReport::Merge(const FVerseValidationReport& Other, const FString& Prefix)
+{
+ for (const FString& Error : Other.Errors)
+ {
+ Errors.Add(Prefix + Error);
+ }
+ if (Other.MeasuredThicknessCm > 0.f && MeasuredThicknessCm <= 0.f)
+ {
+ MeasuredThicknessCm = Other.MeasuredThicknessCm;
+ }
+}
+
+namespace
+{
+ /** Weld positions on a 0.01 mm grid. */
+ TArray<int32> Weld(const FVerseMeshSoup& Mesh, int32& OutUnique)
+ {
+ TMap<FIntVector, int32> Grid;
+ TArray<int32> Map;
+ Map.SetNum(Mesh.Positions.Num());
+ for (int32 Index = 0; Index < Mesh.Positions.Num(); ++Index)
+ {
+ const FVector& P = Mesh.Positions[Index];
+ const FIntVector Key(FMath::RoundToInt32(P.X * 1000.0), FMath::RoundToInt32(P.Y * 1000.0), FMath::RoundToInt32(P.Z * 1000.0));
+ const int32* Found = Grid.Find(Key);
+ Map[Index] = Found ? *Found : Grid.Add(Key, Grid.Num());
+ }
+ OutUnique = Grid.Num();
+ return Map;
+ }
+
+ bool RayTriangle(const FVector& Origin, const FVector& Dir, const FVector& A, const FVector& B, const FVector& C, double& OutT)
+ {
+ const FVector E1 = B - A;
+ const FVector E2 = C - A;
+ const FVector P = FVector::CrossProduct(Dir, E2);
+ const double Det = FVector::DotProduct(E1, P);
+ if (FMath::Abs(Det) < 1e-12)
+ {
+ return false;
+ }
+ const double Inv = 1.0 / Det;
+ const FVector S = Origin - A;
+ const double U = FVector::DotProduct(S, P) * Inv;
+ if (U < -1e-9 || U > 1.0 + 1e-9)
+ {
+ return false;
+ }
+ const FVector Q = FVector::CrossProduct(S, E1);
+ const double V = FVector::DotProduct(Dir, Q) * Inv;
+ if (V < -1e-9 || U + V > 1.0 + 1e-9)
+ {
+ return false;
+ }
+ OutT = FVector::DotProduct(E2, Q) * Inv;
+ return OutT > 1e-4;
+ }
+}
+
+FVerseValidationReport UVerseDestructibleValidator::CheckClosed(const FVerseMeshSoup& Mesh)
+{
+ FVerseValidationReport Report;
+ if (Mesh.NumTriangles() == 0)
+ {
+ Report.Errors.Add(TEXT("no triangles"));
+ return Report;
+ }
+ int32 Unique = 0;
+ const TArray<int32> Map = Weld(Mesh, Unique);
+ TMap<TPair<int32, int32>, int32> Directed;
+ int32 Degenerate = 0;
+ for (int32 Tri = 0; Tri < Mesh.NumTriangles(); ++Tri)
+ {
+ const int32 V[3] = {Map[Mesh.Indices[Tri * 3]], Map[Mesh.Indices[Tri * 3 + 1]], Map[Mesh.Indices[Tri * 3 + 2]]};
+ const FVector& A = Mesh.Positions[Mesh.Indices[Tri * 3]];
+ const FVector& B = Mesh.Positions[Mesh.Indices[Tri * 3 + 1]];
+ const FVector& C = Mesh.Positions[Mesh.Indices[Tri * 3 + 2]];
+ if (V[0] == V[1] || V[1] == V[2] || V[0] == V[2] || FVector::CrossProduct(B - A, C - A).SizeSquared() < 1e-10)
+ {
+ ++Degenerate;
+ continue;
+ }
+ for (int32 Edge = 0; Edge < 3; ++Edge)
+ {
+ Directed.FindOrAdd(TPair<int32, int32>(V[Edge], V[(Edge + 1) % 3])) += 1;
+ }
+ }
+ if (Degenerate > 0)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("%d zero-area faces"), Degenerate));
+ }
+ int32 Open = 0;
+ int32 NonManifold = 0;
+ for (const TPair<TPair<int32, int32>, int32>& Edge : Directed)
+ {
+ if (Edge.Value > 1)
+ {
+ ++NonManifold; // two faces wind the same way over one edge: doubled or flipped faces
+ }
+ const int32* Reverse = Directed.Find(TPair<int32, int32>(Edge.Key.Value, Edge.Key.Key));
+ if (!Reverse)
+ {
+ ++Open;
+ }
+ else if (*Reverse != Edge.Value)
+ {
+ ++NonManifold;
+ }
+ }
+ if (Open > 0)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("not watertight: %d open edges (one-sided shell or double plane)"), Open));
+ }
+ if (NonManifold > 0)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("not manifold: %d edges shared inconsistently"), NonManifold));
+ }
+ return Report;
+}
+
+float UVerseDestructibleValidator::MeasureThickness(const FVerseMeshSoup& Mesh, const FVector& Axis)
+{
+ struct FSample
+ {
+ double Distance;
+ double Weight;
+ };
+ TArray<FSample> Samples;
+ const FVector UnitAxis = Axis.GetSafeNormal();
+ for (int32 Tri = 0; Tri < Mesh.NumTriangles(); ++Tri)
+ {
+ const FVector& A = Mesh.Positions[Mesh.Indices[Tri * 3]];
+ const FVector& B = Mesh.Positions[Mesh.Indices[Tri * 3 + 1]];
+ const FVector& C = Mesh.Positions[Mesh.Indices[Tri * 3 + 2]];
+ const FVector Cross = FVector::CrossProduct(B - A, C - A);
+ const double Area = Cross.Size() * 0.5;
+ if (Area < 1e-8)
+ {
+ continue;
+ }
+ const FVector Normal = Cross / (Area * 2.0);
+ if (FMath::Abs(FVector::DotProduct(Normal, UnitAxis)) < 0.95)
+ {
+ continue;
+ }
+ const FVector Centroid = (A + B + C) / 3.0;
+ double Best = TNumericLimits<double>::Max();
+ // Inward first; a mesh wound inside-out shoots the other way.
+ for (const double Sign : {-1.0, 1.0})
+ {
+ const FVector Dir = Normal * Sign;
+ const FVector Origin = Centroid + Dir * 1e-3;
+ for (int32 Other = 0; Other < Mesh.NumTriangles(); ++Other)
+ {
+ if (Other == Tri)
+ {
+ continue;
+ }
+ double T = 0.0;
+ if (RayTriangle(Origin, Dir, Mesh.Positions[Mesh.Indices[Other * 3]], Mesh.Positions[Mesh.Indices[Other * 3 + 1]],
+ Mesh.Positions[Mesh.Indices[Other * 3 + 2]], T))
+ {
+ Best = FMath::Min(Best, T + 1e-3);
+ }
+ }
+ if (Best < TNumericLimits<double>::Max())
+ {
+ break;
+ }
+ }
+ if (Best < TNumericLimits<double>::Max())
+ {
+ Samples.Add({Best, Area});
+ }
+ }
+ if (Samples.Num() == 0)
+ {
+ return 0.f;
+ }
+ Samples.Sort([](const FSample& L, const FSample& R) { return L.Distance < R.Distance; });
+ double Total = 0.0;
+ for (const FSample& Sample : Samples)
+ {
+ Total += Sample.Weight;
+ }
+ double Acc = 0.0;
+ for (const FSample& Sample : Samples)
+ {
+ Acc += Sample.Weight;
+ if (Acc >= Total * 0.5)
+ {
+ return float(Sample.Distance);
+ }
+ }
+ return float(Samples.Last().Distance);
+}
+
+FVerseValidationReport UVerseDestructibleValidator::CheckSolid(const FVerseMeshSoup& Mesh, const FVector& Axis, float RefThickness)
+{
+ FVerseValidationReport Report = CheckClosed(Mesh);
+ if (RefThickness <= 0.f)
+ {
+ return Report;
+ }
+ Report.MeasuredThicknessCm = MeasureThickness(Mesh, Axis);
+ if (Report.MeasuredThicknessCm <= 0.f)
+ {
+ Report.Errors.Add(TEXT("thickness not measurable (no inward hit)"));
+ }
+ else if (FMath::Abs(Report.MeasuredThicknessCm - RefThickness) > RefThickness * ThicknessTolerance)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("thickness %.3f cm, the material wants %.3f cm +-10 %%"), Report.MeasuredThicknessCm, RefThickness));
+ }
+ return Report;
+}
+
+FVector UVerseDestructibleValidator::ThicknessAxis(EVersePieceClass Class)
+{
+ switch (Class)
+ {
+ case EVersePieceClass::CatwalkSegment:
+ case EVersePieceClass::CeilingPanel:
+ return FVector::UpVector;
+ default:
+ return FVector::RightVector; // wall-like pieces: thickness along piece-local Y (art kit convention)
+ }
+}
+
+float UVerseDestructibleValidator::RefThicknessCm(EVersePieceClass Class)
+{
+ const FVersePenetrationRow* Row = GetDefault<UVersePenetrationTable>()->FindRow(uint8(VerseMaterialOfClass(Class)));
+ return Row ? Row->RefThicknessCm : 0.f;
+}
+
+bool UVerseDestructibleValidator::ReadMesh(const UStaticMesh& Mesh, FVerseMeshSoup& Out)
+{
+ Out = FVerseMeshSoup();
+#if WITH_EDITORONLY_DATA
+ // The source geometry: for a Nanite mesh LOD 0 render data is only the fallback mesh.
+ if (const FMeshDescription* Source = Mesh.GetMeshDescription(0))
+ {
+ const FMeshConstAttributes Attributes(*Source);
+ const TVertexAttributesConstRef<FVector3f> Positions = Attributes.GetVertexPositions();
+ TMap<FVertexID, int32> Slot;
+ for (const FVertexID Vertex : Source->Vertices().GetElementIDs())
+ {
+ Slot.Add(Vertex, Out.Positions.Add(FVector(Positions[Vertex])));
+ }
+ for (const FTriangleID Triangle : Source->Triangles().GetElementIDs())
+ {
+ for (const FVertexID Vertex : Source->GetTriangleVertices(Triangle))
+ {
+ Out.Indices.Add(Slot.FindChecked(Vertex));
+ }
+ }
+ if (Out.NumTriangles() > 0)
+ {
+ return true;
+ }
+ Out = FVerseMeshSoup();
+ }
+#endif
+ const FStaticMeshRenderData* RenderData = Mesh.GetRenderData();
+ if (!RenderData || RenderData->LODResources.Num() == 0)
+ {
+ return false;
+ }
+ const FStaticMeshLODResources& Lod = RenderData->LODResources[0];
+ const FPositionVertexBuffer& Positions = Lod.VertexBuffers.PositionVertexBuffer;
+ if (!Positions.GetAllowCPUAccess() && FPlatformProperties::RequiresCookedData())
+ {
+ return false;
+ }
+ for (uint32 Vertex = 0; Vertex < Positions.GetNumVertices(); ++Vertex)
+ {
+ Out.Positions.Add(FVector(Positions.VertexPosition(Vertex)));
+ }
+ TArray<uint32> Indices;
+ Lod.IndexBuffer.GetCopy(Indices);
+ for (const uint32 I : Indices)
+ {
+ Out.Indices.Add(int32(I));
+ }
+ return Out.NumTriangles() > 0;
+}
+
+FVerseValidationReport UVerseDestructibleValidator::ValidatePiece(const AVerseDestructible& Piece, const UVersePieceManifest* Manifest)
+{
+ FVerseValidationReport Report;
+ const EVersePieceClass Class = Piece.PieceClass;
+ if (Piece.Material != VerseMaterialOfClass(Class))
+ {
+ Report.Errors.Add(FString::Printf(TEXT("material %s does not match class %s"),
+ *UEnum::GetValueAsString(Piece.Material), *UEnum::GetValueAsString(Class)));
+ }
+ if (!Piece.IntactProxy)
+ {
+ Report.Errors.Add(TEXT("missing proxy: Intact"));
+ }
+ const bool bWall = Class == EVersePieceClass::WallPanel || Class == EVersePieceClass::CladdingWall || Class == EVersePieceClass::ContainerWall;
+ if (bWall)
+ {
+ auto CheckVariants = [&Report](const TArray<FVersePieceVariant>& Variants, const TCHAR* State)
+ {
+ if (Variants.Num() == 0)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("missing proxy: %s"), State));
+ }
+ if (Variants.Num() > 4)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("%d %s variants, at most 4"), Variants.Num(), State));
+ }
+ for (int32 Index = 0; Index < Variants.Num(); ++Index)
+ {
+ if (!Variants[Index].Proxy)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("missing proxy: %s variant %d"), State, Index));
+ }
+ }
+ };
+ CheckVariants(Piece.HoledVariants, TEXT("Holed"));
+ CheckVariants(Piece.BreachedVariants, TEXT("Breached"));
+ }
+ // Glass breaks into Niagara shards only (destruction.md 2); every other class ships its
+ // per-state debris sets (GC_<Piece>_<State>_<n>), each within the per-fracture body cap and
+ // declaring the chunk count the asset really has.
+ if (Class != EVersePieceClass::GlassPane && Piece.DebrisSets.Num() == 0)
+ {
+ Report.Errors.Add(TEXT("missing debris geometry collection sets"));
+ }
+ const int32 MaxPerFracture = FVerseDebrisBudget::FConfig::High().MaxBodiesPerFracture;
+ for (int32 Index = 0; Index < Piece.DebrisSets.Num(); ++Index)
+ {
+ const FVersePieceDebrisSet& Set = Piece.DebrisSets[Index];
+ if (Set.Collection.IsNull())
+ {
+ Report.Errors.Add(FString::Printf(TEXT("debris set %d has no geometry collection"), Index));
+ continue;
+ }
+ if (Set.Bodies <= 0 || Set.Bodies > MaxPerFracture)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("debris set %d declares %d bodies, allowed 1 to %d"), Index, Set.Bodies, MaxPerFracture));
+ }
+ if (const UGeometryCollection* Collection = Set.Collection.LoadSynchronous())
+ {
+ const int32 Real = UVerseDebrisSubsystem::CountBodies(*Collection);
+ if (Real != Set.Bodies)
+ {
+ Report.Errors.Add(FString::Printf(TEXT("debris set %d declares %d bodies, the asset has %d"), Index, Set.Bodies, Real));
+ }
+ }
+ else
+ {
+ Report.Errors.Add(FString::Printf(TEXT("debris set %d: %s does not load"), Index, *Set.Collection.ToString()));
+ }
+ }
+ if (!Manifest)
+ {
+ Report.Errors.Add(TEXT("no manifest to check the piece against"));
+ }
+ else if (Manifest->IndexOf(Piece.GetPieceGuid()) == INDEX_NONE)
+ {
+ Report.Errors.Add(TEXT("piece is not in the manifest"));
+ }
+ if (!Piece.GetPieceGuid().IsValid())
+ {
+ Report.Errors.Add(TEXT("no piece GUID"));
+ }
+
+ const FVector Axis = ThicknessAxis(Class);
+ const float Ref = RefThicknessCm(Class);
+ auto CheckMesh = [&Report, &Axis](const UStaticMesh* Mesh, float Thickness, const FString& Label)
+ {
+ if (!Mesh)
+ {
+ return; // a missing mesh is reported by the proxy checks above
+ }
+ FVerseMeshSoup Soup;
+ if (!ReadMesh(*Mesh, Soup))
+ {
+ Report.Errors.Add(Label + TEXT(": geometry not readable (no source mesh, no CPU-accessible render data)"));
+ return;
+ }
+ Report.Merge(CheckSolid(Soup, Axis, Thickness), Label + TEXT(": "));
+ };
+ CheckMesh(Piece.GetRenderComponent() ? Piece.GetRenderComponent()->GetStaticMesh() : nullptr, Ref, TEXT("render"));
+ CheckMesh(Piece.IntactProxy, Ref, TEXT("proxy Intact"));
+ for (int32 Index = 0; Index < Piece.HoledVariants.Num(); ++Index)
+ {
+ // Proxies keep the exact material thickness in every state (DR5, destruction.md 9).
+ CheckMesh(Piece.HoledVariants[Index].Proxy, Ref, FString::Printf(TEXT("proxy Holed %d"), Index));
+ CheckMesh(Piece.HoledVariants[Index].Render, Ref, FString::Printf(TEXT("render Holed %d"), Index));
+ }
+ for (int32 Index = 0; Index < Piece.BreachedVariants.Num(); ++Index)
+ {
+ CheckMesh(Piece.BreachedVariants[Index].Proxy, Ref, FString::Printf(TEXT("proxy Breached %d"), Index));
+ CheckMesh(Piece.BreachedVariants[Index].Render, Ref, FString::Printf(TEXT("render Breached %d"), Index));
+ }
+ CheckMesh(Piece.Remains.Proxy, 0.f, TEXT("proxy Remains"));
+ CheckMesh(Piece.Remains.Render, 0.f, TEXT("render Remains"));
+ return Report;
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisBudget.h b/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisBudget.h
new file mode 100644
index 0000000000..2029eaca85
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisBudget.h
@@ -0,0 +1,109 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTypes.h"
+
+/**
+ * Client debris budget of destruction.md 10: at most 400 rigid bodies on High (150 on Low), at
+ * most 40 per fracture, at most 32 geometry collection actors, sleep at 3 s, despawn at 10 s
+ * (6 s on Low), oldest removed first with a 0.3 s fade. Pure bookkeeping: the debris subsystem
+ * asks it before spawning and drives the actors from its answers, and the storm scenario runs
+ * it without a world.
+ */
+class VERSEDESTRUCTION_API FVerseDebrisBudget
+{
+public:
+ struct FConfig
+ {
+ int32 MaxBodies = 400;
+ int32 MaxBodiesPerFracture = 40;
+ int32 MaxGeometryCollectionActors = 32;
+ float SleepS = 3.f;
+ float DespawnS = 10.f;
+ float FadeS = 0.3f;
+
+ static FConfig High();
+ static FConfig Low();
+ };
+
+ /** One spawned burst (one geometry collection actor, or Niagara only when Bodies is 0). */
+ struct FBurst
+ {
+ int32 Id = 0;
+ uint16 PieceIndex = 0;
+ int32 Bodies = 0;
+ double SpawnS = 0.0;
+ bool bAsleep = false;
+ /** Set when evicted or expired; the actor fades out over FadeS and stops counting. */
+ bool bFading = false;
+ double FadeStartS = 0.0;
+ };
+
+ /** What a fracture's debris consists of, before the budget. */
+ struct FRequest
+ {
+ uint16 PieceIndex = 0;
+ EVerseDebrisType Type = EVerseDebrisType::SparksOnly;
+ EVersePieceState ToState = EVersePieceState::Damaged;
+ };
+
+ struct FGrant
+ {
+ /** 0 = no burst (Niagara only or nothing). */
+ int32 BurstId = 0;
+ int32 Bodies = 0;
+ /** Niagara-only effects (glass shards, dust, sparks) always play. */
+ bool bNiagara = false;
+ /** Bursts the caller must start fading now (oldest first). */
+ TArray<int32> Evicted;
+ /** Bursts whose actors must be destroyed now (the pool of 32 actors was full). */
+ TArray<int32> Removed;
+ };
+
+ explicit FVerseDebrisBudget(const FConfig& InConfig = FConfig::High());
+
+ /** Rigid bodies a fracture wants before the budget (WP06 start values, tuning.json). */
+ static int32 DesiredBodies(EVerseDebrisType Type, EVersePieceState ToState);
+ /** True if the debris type has a Niagara part (shards, dust, sparks). */
+ static bool HasNiagara(EVerseDebrisType Type);
+
+ /** Reserves bodies for a burst (at most the grant); Commit then charges the real count. */
+ FGrant Request(const FRequest& Request, double NowS);
+
+ /**
+ * The burst really simulates RealBodies (<= the grant; the spawned set's chunk count, or 0
+ * when nothing spawned, which frees the reservation). The real peaks count only committed bodies.
+ */
+ void Commit(int32 BurstId, int32 RealBodies);
+
+ /** Advances sleep, despawn and fade; returns bursts whose actors must be destroyed now. */
+ TArray<int32> Tick(double NowS);
+
+ /** Reset: every burst is removed at once (destruction.md 11). */
+ TArray<int32> PurgeAll();
+
+ int32 ActiveBodies() const;
+ int32 AliveActors() const;
+ int32 GetPeakBodies() const { return PeakBodies; }
+ int32 GetPeakActors() const { return PeakActors; }
+ int32 GetPeakBodiesPerFracture() const { return PeakPerFracture; }
+ /** Peaks of the committed (really spawned) bodies, actors and bodies per fracture. */
+ int32 GetPeakRealBodies() const { return PeakRealBodies; }
+ int32 GetPeakRealActors() const { return PeakRealActors; }
+ int32 GetPeakRealBodiesPerFracture() const { return PeakRealPerFracture; }
+ const FConfig& GetConfig() const { return Config; }
+ const TArray<FBurst>& GetBursts() const { return Bursts; }
+
+private:
+ void EvictOldest(double NowS, TArray<int32>& OutEvicted);
+
+ FConfig Config;
+ TArray<FBurst> Bursts;
+ int32 NextId = 1;
+ int32 PeakBodies = 0;
+ int32 PeakActors = 0;
+ int32 PeakPerFracture = 0;
+ int32 PeakRealBodies = 0;
+ int32 PeakRealActors = 0;
+ int32 PeakRealPerFracture = 0;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisSubsystem.h b/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisSubsystem.h
new file mode 100644
index 0000000000..2b3a6ac757
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Debris/VerseDebrisSubsystem.h
@@ -0,0 +1,79 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Debris/VerseDebrisBudget.h"
+#include "Subsystems/WorldSubsystem.h"
+#include "Tickable.h"
+
+#include "VerseDebrisSubsystem.generated.h"
+
+class AGeometryCollectionActor;
+class AVerseDestructible;
+class UGeometryCollection;
+struct FStreamableHandle;
+struct FVerseFractureEvent;
+struct FVersePieceDebrisSet;
+
+/**
+ * Client-side cosmetic debris (destruction.md 4, 10; DR3). Listens to OnFracture on the hub and
+ * spawns one geometry collection burst per fracture inside FVerseDebrisBudget. The burst is the
+ * piece's authored debris set for the new state (GC_<Piece>_<State>_<n>: only the chunks of the
+ * opening, so a Holed wall that still stands gets no full chunk set inside it) with the most
+ * chunks that still fit the grant; the budget is then charged with the rigid bodies the spawned
+ * component really has. Actors come from a pool of at most 32; the sets are loaded
+ * asynchronously when a piece registers, never on the game thread at the first fracture.
+ * A dedicated server and every -nullrhi run spawn nothing; replicated items (late join) never
+ * spawn debris. Debris uses the Verse_Debris profile, so it never blocks pawns, bolts or sight (DR2).
+ */
+UCLASS()
+class VERSEDESTRUCTION_API UVerseDebrisSubsystem : public UTickableWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ /** False on a dedicated server and without a renderer (DR3). */
+ static bool ShouldSpawnDebris(const UWorld& World);
+
+ /**
+ * Index of the set to spawn for a grant: the one with the most bodies that is still at most
+ * Grant, INDEX_NONE when none fits (then only the Niagara part plays).
+ */
+ static int32 PickSet(TConstArrayView<int32> SetBodies, int32 Grant);
+
+ /** Rigid bodies of a geometry collection: its leaf geometry count (every chunk once broken). */
+ static int32 CountBodies(const UGeometryCollection& Collection);
+
+ /** Low preset: 150 bodies, 6 s lifetime. */
+ void SetLowPreset(bool bLow);
+
+ /** Starts the async load of a piece's debris sets (called when the piece registers). */
+ void PreloadPiece(const AVerseDestructible& Piece);
+
+ const FVerseDebrisBudget& GetBudget() const { return Budget; }
+ int32 GetSpawnedBursts() const { return SpawnedBursts; }
+ int32 GetPooledActors() const { return Pool.Num(); }
+
+ virtual void OnWorldBeginPlay(UWorld& InWorld) override;
+ virtual void Deinitialize() override;
+ virtual void Tick(float DeltaTime) override;
+ virtual TStatId GetStatId() const override;
+ virtual bool ShouldCreateSubsystem(UObject* Outer) const override;
+
+private:
+ void HandleFracture(const FVerseFractureEvent& Event);
+ /** Spawns the burst and returns the real rigid body count (0 = nothing spawned). */
+ int32 SpawnBurst(int32 BurstId, const FVerseFractureEvent& Event, int32 Grant);
+ void ReleaseBurst(int32 BurstId);
+ AGeometryCollectionActor* AcquireActor();
+
+ FVerseDebrisBudget Budget;
+ TMap<int32, TWeakObjectPtr<AGeometryCollectionActor>> BurstActors;
+ /** Idle pooled actors (hidden, no collision, not simulating). */
+ UPROPERTY(Transient)
+ TArray<TObjectPtr<AGeometryCollectionActor>> Pool;
+ int32 PoolSize = 0;
+ TArray<TSharedPtr<FStreamableHandle>> Preloads;
+ FDelegateHandle FractureHandle;
+ int32 SpawnedBursts = 0;
+ bool bEnabled = false;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Nav/VerseNavDirtyQueue.h b/unreal/Verse/Source/VerseDestruction/Public/Nav/VerseNavDirtyQueue.h
new file mode 100644
index 0000000000..d4180aff92
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Nav/VerseNavDirtyQueue.h
@@ -0,0 +1,55 @@
+#pragma once
+
+#include "CoreMinimal.h"
+
+/**
+ * Navmesh dirty-tile queue of destruction.md 6.1: every state change marks the piece's old and
+ * new proxy bounds (+50 cm) dirty; the tiles they cover are released at most N at a time, so
+ * at most 4 tiles rebuild at once. Tiles are 32 x 32 cells of 10 cm (320 cm). Pure logic; the
+ * manager hands released tiles to the navigation system.
+ */
+class VERSEDESTRUCTION_API FVerseNavDirtyQueue
+{
+public:
+ static constexpr float TileSizeCm = 320.f;
+
+ struct FTile
+ {
+ FIntPoint Key = FIntPoint::ZeroValue;
+ /** Z range covered by the dirty boxes that touched this tile. */
+ float MinZ = 0.f;
+ float MaxZ = 0.f;
+ /** The piece whose change first dirtied the tile (INDEX_NONE if unknown). */
+ int32 PieceIndex = INDEX_NONE;
+ /** World box of the tile footprint over the Z range. */
+ FBox GetBox() const;
+ };
+
+ explicit FVerseNavDirtyQueue(int32 InMaxInFlight = 4, float InMarginCm = 50.f);
+
+ /** Marks the tiles under Box (grown by the margin) dirty. Tiles already queued merge. */
+ void MarkDirty(const FBox& Box, int32 PieceIndex = INDEX_NONE);
+
+ /**
+ * Called when the navigation system reports rebuilt tiles (or once per nav tick when it
+ * cannot report): frees the in-flight slots and releases up to MaxInFlight queued tiles.
+ */
+ TArray<FTile> Release(int32 CompletedSinceLastRelease);
+
+ /** Releases everything (full reset rebuilds all dirty tiles). */
+ TArray<FTile> ReleaseAll();
+
+ int32 NumQueued() const { return Queue.Num(); }
+ int32 NumInFlight() const { return InFlight; }
+ int32 GetMaxInFlight() const { return MaxInFlight; }
+ int32 GetPeakInFlight() const { return PeakInFlight; }
+
+ static FIntPoint TileOf(const FVector& Point);
+
+private:
+ TArray<FTile> Queue;
+ int32 MaxInFlight = 4;
+ float MarginCm = 50.f;
+ int32 InFlight = 0;
+ int32 PeakInFlight = 0;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructible.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructible.h
new file mode 100644
index 0000000000..d4063bb74d
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructible.h
@@ -0,0 +1,188 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTypes.h"
+#include "GameFramework/Actor.h"
+#include "Pieces/VersePieceTypes.h"
+
+#include "VerseDestructible.generated.h"
+
+class UGeometryCollection;
+class UStaticMesh;
+class UStaticMeshComponent;
+
+/** One authored look of a state variant: collision proxy, render mesh, opening centroid. */
+USTRUCT(BlueprintType)
+struct VERSEDESTRUCTION_API FVersePieceVariant
+{
+ GENERATED_BODY()
+
+ /** SM_<Piece>_Proxy_<State>[_<n>]: gameplay collision, never rendered. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ TObjectPtr<UStaticMesh> Proxy = nullptr;
+
+ /** Render mesh of this variant; empty = keep the Intact render mesh. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ TObjectPtr<UStaticMesh> Render = nullptr;
+
+ /** Piece-local centre of the opening (variant choice, destruction.md 3.1). */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ FVector OpeningCentroid = FVector::ZeroVector;
+};
+
+/**
+ * One authored debris burst of a state (destruction.md 10): GC_<Piece>_<State>_<n>, the chunks
+ * of the Intact fracture that fly out of that opening (Holed, Breached) or of the whole piece
+ * (Destroyed), at most the class's body budget. A piece may ship several sizes per state; the
+ * debris subsystem takes the largest one the budget grants.
+ */
+USTRUCT(BlueprintType)
+struct VERSEDESTRUCTION_API FVersePieceDebrisSet
+{
+ GENERATED_BODY()
+
+ /** Holed, Breached or Destroyed. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ EVersePieceState State = EVersePieceState::Destroyed;
+
+ /** Holed / Breached variant index; ignored for Destroyed. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ uint8 Variant = 0;
+
+ /** Soft, so a server never loads it. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ TSoftObjectPtr<UGeometryCollection> Collection;
+
+ /** Rigid bodies (leaf chunks) of Collection; the validator checks it against the asset. */
+ UPROPERTY(EditAnywhere, Category = "Destructible")
+ int32 Bodies = 0;
+};
+
+/**
+ * One breakable thing (architecture 4): wall panel, cladding wall, container wall, glass pane,
+ * catwalk segment or ceiling panel. Placed by zone owners from WP06 classes and assets. It never
+ * decides its own state: AVerseDestructionManager (server) does and calls ApplyPresentation on
+ * server and clients from the replicated item.
+ */
+UCLASS(Blueprintable)
+class VERSEDESTRUCTION_API AVerseDestructible : public AActor
+{
+ GENERATED_BODY()
+
+public:
+ AVerseDestructible();
+
+ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Destructible")
+ EVersePieceClass PieceClass = EVersePieceClass::WallPanel;
+
+ /** Penetration material; must match the class (validator). */
+ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Destructible")
+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::SheetMetal;
+
+ /** SM_<Piece>_Proxy_Intact (Damaged reuses it). */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Proxies")
+ TObjectPtr<UStaticMesh> IntactProxy = nullptr;
+
+ /** Up to 4 Holed variants. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Proxies")
+ TArray<FVersePieceVariant> HoledVariants;
+
+ /** Up to 4 Breached variants. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Proxies")
+ TArray<FVersePieceVariant> BreachedVariants;
+
+ /** Optional Remains proxy and look on the floor when Destroyed. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Proxies")
+ FVersePieceVariant Remains;
+
+ /** GC_<Piece>, the full fracture (input of the per-state sets); never spawned as a whole. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Debris", meta = (AllowedClasses = "/Script/GeometryCollectionEngine.GeometryCollection"))
+ TSoftObjectPtr<UObject> GeometryCollection;
+
+ /** Per-state debris bursts (GC_<Piece>_<State>_<n>); an empty list means no rigid debris. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Debris")
+ TArray<FVersePieceDebrisSet> DebrisSets;
+
+ /** The debris sets of a state and variant (Destroyed ignores the variant). */
+ TArray<const FVersePieceDebrisSet*> FindDebrisSets(EVersePieceState State, uint8 Variant) const;
+
+ /** Mantle links through a low breach (live while Breached), piece-local. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Nav")
+ TArray<FVersePieceNavLink> MantleLinks;
+
+ /** Drop-down links to the floor below (live while Destroyed; catwalks), piece-local. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Nav")
+ TArray<FVersePieceNavLink> DropLinks;
+
+ /**
+ * Piece-local vertices of the Intact proxy, captured in the editor (construction, save) so
+ * cooked builds and the dedicated server run the 150 cm breach test on the same points as
+ * the editor (destruction.md 3.2). Empty: the proxy box corners.
+ */
+ UPROPERTY(VisibleAnywhere, Category = "Destructible|Proxies")
+ TArray<FVector> ProxyVertices;
+
+ /** Fills ProxyVertices from the Intact proxy's source geometry (editor only; no-op in cooked builds). */
+ void CaptureProxyVertices();
+
+ /** Used only when no Intact proxy mesh is set (tests, graybox): the Intact proxy box, piece-local. */
+ UPROPERTY(EditAnywhere, Category = "Destructible|Proxies")
+ FBox FallbackIntactBounds = FBox(ForceInit);
+
+ UStaticMeshComponent* GetRenderComponent() const { return RenderMesh; }
+ UStaticMeshComponent* GetProxyComponent() const { return ProxyMesh; }
+
+ /** The One File Per Actor GUID, kept at runtime (destruction.md 8). */
+ const FGuid& GetPieceGuid() const { return PieceGuid; }
+ void SetPieceGuid(const FGuid& Guid) { PieceGuid = Guid; }
+
+ /** Index in DA_PieceManifest, set by the manager; INDEX_NONE before registration. */
+ int32 GetPieceIndex() const { return PieceIndex; }
+ void SetPieceIndex(int32 Index) { PieceIndex = Index; }
+
+ /** The static description the simulation runs on. */
+ FVersePieceDef MakeDef() const;
+
+ /** Shows the state's proxy and look. bInstant: late join / reset, no transition effects. */
+ void ApplyPresentation(EVersePieceState State, uint8 Variant, EVersePieceState RepairFrom);
+
+ EVersePieceState GetPresentedState() const { return PresentedState; }
+ uint8 GetPresentedVariant() const { return PresentedVariant; }
+ /** The proxy mesh live now (nullptr when the state has no proxy). */
+ UStaticMesh* GetPresentedProxy() const;
+
+ virtual void PostLoad() override;
+ virtual void OnConstruction(const FTransform& Transform) override;
+#if WITH_EDITOR
+ virtual void PreSave(FObjectPreSaveContext SaveContext) override;
+#endif
+
+protected:
+ /** Registers with the arena's manager (World Partition streaming, destruction.md 8). */
+ virtual void BeginPlay() override;
+ virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
+
+public:
+
+protected:
+ UPROPERTY(VisibleAnywhere, Category = "Destructible")
+ TObjectPtr<UStaticMeshComponent> RenderMesh;
+
+ UPROPERTY(VisibleAnywhere, Category = "Destructible")
+ TObjectPtr<UStaticMeshComponent> ProxyMesh;
+
+ /** Copied from the actor GUID in the editor; actor GUIDs are editor-only. */
+ UPROPERTY(VisibleAnywhere, Category = "Destructible")
+ FGuid PieceGuid;
+
+private:
+ void CaptureGuid();
+ const FVersePieceVariant* FindVariant(EVersePieceState State, uint8 Variant) const;
+
+ UPROPERTY(Transient)
+ TObjectPtr<UStaticMesh> IntactRender = nullptr;
+
+ int32 PieceIndex = INDEX_NONE;
+ EVersePieceState PresentedState = EVersePieceState::Intact;
+ uint8 PresentedVariant = 0;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionManager.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionManager.h
new file mode 100644
index 0000000000..8c620db1c4
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionManager.h
@@ -0,0 +1,170 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionInterfaces.h"
+#include "GameFramework/Actor.h"
+#include "Pieces/VerseDestructionSim.h"
+#include "Pieces/VersePieceItem.h"
+
+#include "VerseDestructionManager.generated.h"
+
+class AVerseDestructible;
+class AVerseRepairDrone;
+class UVerseDestructionTuning;
+class UVersePieceManifest;
+struct FVerseArenaSwitchEvent;
+
+/**
+ * Server fracture authority and replicated piece state of one arena (destruction.md 3.3,
+ * architecture 4). One per arena world; always relevant. The server runs FVerseDestructionSim
+ * and replicates its items in a fast array; clients apply the items to the piece actors
+ * (late joiners build the broken look without debris) and receive an unreliable multicast
+ * per fracture for instant debris. Every state change, repair and reset is published on the
+ * event hub on server and clients.
+ */
+UCLASS()
+class VERSEDESTRUCTION_API AVerseDestructionManager : public AActor, public IVersePieceQuery
+{
+ GENERATED_BODY()
+
+public:
+ AVerseDestructionManager();
+
+ /** The manager of the object's world, or nullptr. */
+ static AVerseDestructionManager* Get(const UObject* WorldContextObject);
+
+ /** Thresholds, HP, times, budgets; the contract defaults when unset. */
+ UPROPERTY(EditAnywhere, Category = "Destruction")
+ TObjectPtr<UVerseDestructionTuning> Tuning;
+
+ /**
+ * DA_PieceManifest of this arena. Required on networked clients (PieceIndex must match the
+ * server); a standalone or server world without it orders the loaded pieces by the same GUID rule.
+ */
+ UPROPERTY(EditAnywhere, Category = "Destruction")
+ TObjectPtr<UVersePieceManifest> Manifest;
+
+ /** One repair drone per dock (destruction.md 7), world cm. */
+ UPROPERTY(EditAnywhere, Category = "Repair")
+ TArray<FVector> DroneDocks;
+
+ UPROPERTY(EditAnywhere, Category = "Repair")
+ TSubclassOf<AVerseRepairDrone> DroneClass;
+
+ /** Server seed of the fracture RNG stream. */
+ UPROPERTY(EditAnywhere, Category = "Destruction")
+ int64 FractureSeed = 0x5EED;
+
+ /** Reset on the hangar's arena switch (destruction.md 11). */
+ UPROPERTY(EditAnywhere, Category = "Destruction")
+ bool bResetOnArenaSwitch = true;
+
+ /**
+ * IVersePieceDamage of this arena. A plain native interface (no UINTERFACE, see Core), so it
+ * is handed out as a reference instead of being a base class of the actor.
+ */
+ IVersePieceDamage& GetPieceDamage() { return DamageSink; }
+
+ /** Server only (DR1); what GetPieceDamage().ApplyPieceDamage calls. */
+ void ApplyPieceDamage(const FVersePieceDamage& Damage);
+
+ // IVersePieceQuery
+ virtual EVersePieceState GetPieceState(uint16 PieceIndex) const override;
+ virtual EVersePenetrationMaterial GetPieceMaterial(uint16 PieceIndex) const override;
+ virtual FBox GetPieceBounds(uint16 PieceIndex) const override;
+ virtual TArray<uint16> GetPiecesInBox(const FBox& WorldBox) const override;
+
+ /** Full reset (destruction.md 11); VerseCombat calls it when the ruleset asks. Server only. */
+ void FullReset();
+
+ /** Hole 25 on a wall piece (destruction.md 5); called by the hole store. Server only. */
+ void ApplyHoleCap(uint16 PieceIndex, const FVector& LocalCentroidCm);
+
+ /** A bolt or melee hit on a repair drone. Server only. */
+ void ApplyDroneDamage(int32 DroneIndex, float Amount);
+
+ /** Registers the world's pieces in manifest order. Called from BeginPlay; tests may call it again. */
+ void RegisterPieces();
+
+ /**
+ * A piece that began play (World Partition streaming) takes its manifest slot and, on a
+ * client, shows the current replicated item at once. Called by AVerseDestructible::BeginPlay.
+ */
+ void RegisterPiece(AVerseDestructible& Piece);
+ /** A piece that streamed out leaves its slot (the replicated state stays). */
+ void UnregisterPiece(AVerseDestructible& Piece);
+
+ /** True when this manager is a client of a networked game and has no manifest (refuses to register). */
+ bool IsMissingClientManifest() const;
+
+ /** Manifest slots (on a client too, before any item replicated). */
+ int32 NumPieces() const { return Sim.Num(); }
+ AVerseDestructible* GetPieceActor(uint16 PieceIndex) const;
+ const FVersePieceItem* FindItem(uint16 PieceIndex) const;
+ uint16 GetEpoch() const { return Epoch; }
+ const FVerseDestructionSim& GetSim() const { return Sim; }
+
+ /** Server time in ms used for every state record. */
+ uint32 GetServerTimeMs() const;
+
+ /** Nav tiles handed to the navigation system and not confirmed rebuilt yet. */
+ int32 GetNavTilesInFlight() const { return Sim.GetNav().NumInFlight(); }
+ int32 GetPeakNavTilesInFlight() const { return Sim.GetNav().GetPeakInFlight(); }
+
+ /** Tests: stands in for the fast array delivering these items to a client. */
+ void ReceiveItemsForTest(TConstArrayView<FVersePieceItem> InItems, bool bInitial);
+
+ /** Client side: a replicated item arrived or changed (fast array callback). */
+ void OnItemReplicated(const FVersePieceItem& Item, bool bInitial);
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ virtual void Tick(float DeltaSeconds) override;
+
+protected:
+ virtual void BeginPlay() override;
+ virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
+
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastFracture(const FVerseFractureEvent& Event);
+
+ UFUNCTION()
+ void OnRep_Epoch();
+
+private:
+ /** After any server input: copies dirty sim items into the fast array and the piece actors. */
+ void ApplyDirtyItems();
+ /** Once per server tick: events (coalesced per piece and tick), noise, nav tiles, drones. */
+ void PublishTick();
+ void PublishLocal(const FVerseFractureEvent& Event);
+ void HandleArenaSwitch(const FVerseArenaSwitchEvent& Event);
+ void SpawnDrones();
+ void SyncDrones();
+ void ReleaseNavTiles();
+ int32 CompletedNavTiles() const;
+ bool IsEncroached(const FBox& WorldBox) const;
+
+ UPROPERTY(Replicated)
+ FVersePieceItemArray Pieces;
+
+ UPROPERTY(ReplicatedUsing = OnRep_Epoch)
+ uint16 Epoch = 0;
+
+ UPROPERTY(Transient)
+ TArray<TObjectPtr<AVerseDestructible>> PieceActors;
+
+ UPROPERTY(Transient)
+ TArray<TObjectPtr<AVerseRepairDrone>> DroneActors;
+
+ struct FDamageSink final : IVersePieceDamage
+ {
+ AVerseDestructionManager* Owner = nullptr;
+ virtual void ApplyPieceDamage(const FVersePieceDamage& Damage) override { Owner->ApplyPieceDamage(Damage); }
+ };
+
+ FDamageSink DamageSink;
+ FVerseDestructionSim Sim;
+ FDelegateHandle ArenaSwitchHandle;
+ /** Manifest GUID -> PieceIndex, built at registration. */
+ TMap<FGuid, int32> SlotOfGuid;
+ bool bRegistered = false;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionSim.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionSim.h
new file mode 100644
index 0000000000..0a3918451c
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VerseDestructionSim.h
@@ -0,0 +1,195 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTypes.h"
+#include "Nav/VerseNavDirtyQueue.h"
+#include "Pieces/VersePieceItem.h"
+#include "Pieces/VersePieceRules.h"
+#include "Pieces/VersePieceTypes.h"
+
+/** A repair drone's task (destruction.md 7). */
+enum class EVerseDroneTask : uint8
+{
+ Docked,
+ Outbound,
+ Repairing,
+ Returning,
+ /** Shot down this tick; the dock replaces it with a fresh drone. */
+ Down
+};
+
+/** Server state of one repair drone. */
+struct VERSEDESTRUCTION_API FVerseDroneState
+{
+ int32 Index = 0;
+ FVector Dock = FVector::ZeroVector;
+ FVector Location = FVector::ZeroVector;
+ FVector FlightFrom = FVector::ZeroVector;
+ FVector FlightTo = FVector::ZeroVector;
+ EVerseDroneTask Task = EVerseDroneTask::Docked;
+ int32 TargetPiece = INDEX_NONE;
+ uint32 FlightStartMs = 0;
+ uint32 FlightEndMs = 0;
+ uint32 RepairEndMs = 0;
+ uint32 NextEncroachCheckMs = 0;
+ uint32 NextNoiseMs = 0;
+ float Hp = 30.f;
+ /** Counts downs, so the actor knows to drop debris and respawn. */
+ uint32 Generation = 0;
+
+ bool IsActive() const { return Task == EVerseDroneTask::Outbound || Task == EVerseDroneTask::Repairing; }
+ bool IsFree() const { return Task == EVerseDroneTask::Docked || Task == EVerseDroneTask::Returning; }
+};
+
+/** One fracture event of a tick, plus whether it fits the multicast rate cap. */
+struct FVersePendingFracture
+{
+ FVerseFractureEvent Event;
+ bool bMulticast = true;
+ /** False for a deferred over-rate event: it was published on the server when it happened. */
+ bool bPublishLocal = true;
+};
+
+/** Counters of the destruction budgets (destruction.md 10), read by the storm scenario. */
+struct VERSEDESTRUCTION_API FVerseDestructionCounters
+{
+ int32 StateChanges = 0;
+ int32 EventsPublished = 0;
+ int32 EventsMulticast = 0;
+ int32 EventsCoalesced = 0;
+ int32 EventsOverRate = 0;
+ /** Over-rate events multicast later, and the ones that aged out (> 1 s) first. */
+ int32 EventsDeferredSent = 0;
+ int32 EventsDeferredDropped = 0;
+ int32 PeakEventsPerSecond = 0;
+ int32 ItemWrites = 0;
+ int32 Repairs = 0;
+ int32 RepairsInterrupted = 0;
+ int32 PeakActiveDrones = 0;
+};
+
+/**
+ * The authoritative destruction simulation of one arena (destruction.md 3 to 8, 11). No UWorld:
+ * AVerseDestructionManager feeds it damage and server time, and drains its outputs (dirty
+ * fast-array items, fracture events, noise, nav tiles) into replication, the event hub and the
+ * navigation system. Deterministic for a given seed, piece list and input sequence.
+ */
+class VERSEDESTRUCTION_API FVerseDestructionSim
+{
+public:
+ /** Answers whether a pawn overlaps a world box (repair encroachment, destruction.md 7). */
+ using FEncroachFn = TFunctionRef<bool(const FBox& WorldBox)>;
+
+ /** Replaces the static description of one slot (a piece that registered after Init). */
+ void SetDef(uint16 PieceIndex, FVersePieceDef Def);
+
+ /** Pieces in manifest order (index = PieceIndex). Docks: one drone each. */
+ void Init(TArray<FVersePieceDef> InDefs, const FVerseDestructionSimTuning& InTuning, TConstArrayView<FVector> DroneDocks, uint64 InSeed);
+
+ // --- Server inputs (DR1: only the server calls these) ---
+
+ /** IVersePieceDamage::ApplyPieceDamage. Breach charges also apply their radius effect. */
+ void ApplyDamage(const FVersePieceDamage& Damage, uint32 NowMs);
+
+ /** Hole cap reached (destruction.md 5, hole 25 on a wall piece): Holed with the variant nearest the hole centroid. */
+ void ApplyHoleCap(uint16 PieceIndex, const FVector& LocalCentroidCm, uint32 NowMs);
+
+ /** A bolt or melee hit on drone `DroneIndex`. Returns true if it was downed. */
+ bool ApplyDroneDamage(int32 DroneIndex, float Amount, uint32 NowMs);
+
+ /** Repair timers, drone flight, repair completion. Call once per server tick. */
+ void Tick(uint32 NowMs, FEncroachFn IsEncroached);
+
+ /** destruction.md 11. */
+ void FullReset(uint32 NowMs);
+
+ // --- Outputs (drained by the owner once per tick) ---
+
+ TArray<FVersePendingFracture> DrainEvents();
+ TArray<FVerseNoiseEvent> DrainNoise();
+ /** Piece indices whose replicated item changed since the last drain. */
+ TArray<uint16> DrainDirtyItems();
+ FVerseNavDirtyQueue& GetNav() { return Nav; }
+ const FVerseNavDirtyQueue& GetNav() const { return Nav; }
+
+ // --- Reads ---
+
+ int32 Num() const { return Defs.Num(); }
+ const FVersePieceDef& GetDef(uint16 PieceIndex) const { return Defs[PieceIndex]; }
+ const FVersePieceItem& GetItem(uint16 PieceIndex) const { return Items[PieceIndex]; }
+ const TArray<FVersePieceItem>& GetItems() const { return Items; }
+ float GetHp(uint16 PieceIndex) const { return Server[PieceIndex].Hp; }
+ uint32 GetLastDamageMs(uint16 PieceIndex) const { return Server[PieceIndex].LastDamageMs; }
+ const TArray<FVerseDroneState>& GetDrones() const { return Drones; }
+ int32 NumActiveDrones() const;
+ uint16 GetEpoch() const { return Epoch; }
+ const FVerseDestructionSimTuning& GetTuning() const { return Tuning; }
+ const FVerseDestructionCounters& GetCounters() const { return Counters; }
+ bool IsValidPiece(int32 PieceIndex) const { return Defs.IsValidIndex(PieceIndex); }
+
+ /** World bounds of the live proxy of a piece. */
+ FBox GetPieceBounds(uint16 PieceIndex) const;
+ TArray<uint16> GetPiecesInBox(const FBox& WorldBox) const;
+
+ /** Nav links live in the piece's current state (mantle while Breached, drop while Destroyed). */
+ TArray<FVersePieceNavLink> GetLiveNavLinks(uint16 PieceIndex, EVersePieceNavLinkKind& OutKind) const;
+
+ /** Hash of every piece's proxy state and variant (determinism gate A6.7). */
+ static uint32 ProxyHash(TConstArrayView<FVersePieceItem> InItems);
+
+ /** Wire bytes of the last reset burst: fast array header plus element id and NetSerialize bytes per written item. */
+ int32 GetLastResetBurstBytes() const { return LastResetBurstBytes; }
+
+private:
+ struct FServerPiece
+ {
+ float Hp = 0.f;
+ uint32 LastDamageMs = 0;
+ uint32 BrokenSinceMs = 0;
+ FVector HitSumLocal = FVector::ZeroVector;
+ int32 HitCount = 0;
+ bool bDamagedSinceRepair = false;
+ int32 AssignedDrone = INDEX_NONE;
+ };
+
+ void ApplyOne(uint16 PieceIndex, const FVersePieceDamage& Damage, Verse::Destruction::Rules::EHitRole Role, uint32 NowMs);
+ void SetState(uint16 PieceIndex, EVersePieceState NewState, uint8 Variant, EVerseFractureCause Cause,
+ const FVector& WorldLocation, const FVector& Direction, float ImpulseNs, uint8 RadiusCm, uint8 Instigator, uint32 NowMs);
+ void WriteHealth(uint16 PieceIndex);
+ void CancelRepair(uint16 PieceIndex, EVerseFractureCause Cause, uint8 Instigator, uint32 NowMs);
+ void Recall(FVerseDroneState& Drone, uint32 NowMs);
+ void Dispatch(uint32 NowMs);
+ void StartFlight(FVerseDroneState& Drone, const FVector& To, uint32 NowMs);
+ void UpdateDroneLocation(FVerseDroneState& Drone, uint32 NowMs) const;
+ void PushEvent(const FVerseFractureEvent& Event, uint32 NowMs);
+ void PushNoise(const FGameplayTag& Tag, const FVector& Location, float Loudness, uint32 NowMs);
+ void MarkDirty(uint16 PieceIndex);
+ void MarkNav(uint16 PieceIndex, EVersePieceState OldState, uint8 OldVariant);
+ uint32 NextSeed();
+ bool CanBreak(uint16 PieceIndex) const;
+
+ TArray<FVersePieceDef> Defs;
+ TArray<FVersePieceItem> Items;
+ TArray<FServerPiece> Server;
+ TArray<FVerseDroneState> Drones;
+ FVerseDestructionSimTuning Tuning;
+ FVerseNavDirtyQueue Nav;
+
+ TArray<FVersePendingFracture> Events;
+ /** Piece -> index into Events for this tick (coalescing). */
+ TMap<uint16, int32> EventOfPiece;
+ /** Over-rate events waiting for room in the multicast window, one per piece (coalesced). */
+ TMap<uint16, FVerseFractureEvent> Deferred;
+ uint32 EventTickMs = 0;
+ uint32 LastTickMs = 0;
+ TArray<uint32> MulticastTimesMs;
+ TArray<FVerseNoiseEvent> Noise;
+ TSet<uint16> Dirty;
+
+ FVerseDestructionCounters Counters;
+ uint64 Seed = 0;
+ uint64 SeedCounter = 0;
+ uint16 Epoch = 0;
+ int32 LastResetBurstBytes = 0;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceItem.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceItem.h
new file mode 100644
index 0000000000..9f8ceae579
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceItem.h
@@ -0,0 +1,118 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTypes.h"
+#include "Net/Serialization/FastArraySerializer.h"
+
+#include "VersePieceItem.generated.h"
+
+class AVerseDestructionManager;
+struct FVersePieceItemArray;
+
+/**
+ * One replicated piece (destruction.md 3.3). Items change only on a state change, an HP change
+ * of at least one quantum, or a hole; the fast array then sends only that item.
+ */
+USTRUCT()
+struct VERSEDESTRUCTION_API FVersePieceItem : public FFastArraySerializerItem
+{
+ GENERATED_BODY()
+
+ /** Index into DA_PieceManifest. */
+ UPROPERTY()
+ uint16 PieceIndex = 0;
+
+ UPROPERTY()
+ EVersePieceState State = EVersePieceState::Intact;
+
+ /** round(255 x hp / maxHp) */
+ UPROPERTY()
+ uint8 HealthQ = 255;
+
+ /** Holed or Breached variant, else 0. */
+ UPROPERTY()
+ uint8 Variant = 0;
+
+ /** Valid while Repairing. */
+ UPROPERTY()
+ EVersePieceState RepairFrom = EVersePieceState::Intact;
+
+ UPROPERTY()
+ uint32 LastSeed = 0;
+
+ /** 1 unit = 0.1 N s. */
+ UPROPERTY()
+ int16 LastImpulse[3] = {0, 0, 0};
+
+ /** Piece-local, 1 mm. */
+ UPROPERTY()
+ int16 LastLocation[3] = {0, 0, 0};
+
+ UPROPERTY()
+ uint32 StateTimeMs = 0;
+
+ UPROPERTY()
+ uint16 Epoch = 0;
+
+ /** The state whose proxy is live: RepairFrom while Repairing (destruction.md 7). */
+ EVersePieceState GetProxyState() const { return State == EVersePieceState::Repairing ? RepairFrom : State; }
+
+ /** True when the item carries a fracture record (seed, impulse or location set). */
+ bool HasFractureRecord() const;
+
+ /**
+ * Packed wire form (destruction.md 3.3): PieceIndex 11 bits (<= 2,000 pieces), State 3,
+ * HealthQ 8, Variant 2 (<= 4 per state), RepairFrom 3 only while Repairing, one bit for the
+ * fracture record (Seed 32, Impulse 3 x 16, Location 3 x 16) when it is set, StateTimeMs 32,
+ * Epoch 16. Lossless for every value the simulation writes. The fast array adds its own
+ * 32-bit element id per item and a 16-byte header per delta (FastArraySerializer.h).
+ */
+ bool NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess);
+
+ /** Bytes this item takes on the wire, measured with a bit writer round trip of NetSerialize. */
+ static int32 MeasureWireBytes(const FVersePieceItem& Item);
+ /** Fast array overhead per delta and per item (header keys and counts, element id). */
+ static constexpr int32 FastArrayHeaderBytes = 16;
+ static constexpr int32 FastArrayItemIdBytes = 4;
+ static constexpr int32 MaxPieceIndexBits = 11;
+
+ void PostReplicatedAdd(const FVersePieceItemArray& InArraySerializer);
+ void PostReplicatedChange(const FVersePieceItemArray& InArraySerializer);
+};
+
+template <>
+struct TStructOpsTypeTraits<FVersePieceItem> : public TStructOpsTypeTraitsBase2<FVersePieceItem>
+{
+ enum
+ {
+ WithNetSerializer = true,
+ };
+};
+
+/** The manager's fast array (destruction.md 3.3). */
+USTRUCT()
+struct VERSEDESTRUCTION_API FVersePieceItemArray : public FFastArraySerializer
+{
+ GENERATED_BODY()
+
+ UPROPERTY()
+ TArray<FVersePieceItem> Items;
+
+ /** Not replicated: the manager that owns this array (client callbacks). */
+ UPROPERTY(NotReplicated)
+ TObjectPtr<AVerseDestructionManager> Owner = nullptr;
+
+ bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
+ {
+ return FFastArraySerializer::FastArrayDeltaSerialize<FVersePieceItem, FVersePieceItemArray>(Items, DeltaParms, *this);
+ }
+};
+
+template <>
+struct TStructOpsTypeTraits<FVersePieceItemArray> : public TStructOpsTypeTraitsBase2<FVersePieceItemArray>
+{
+ enum
+ {
+ WithNetDeltaSerializer = true,
+ };
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceManifest.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceManifest.h
new file mode 100644
index 0000000000..bf32544181
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceManifest.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Engine/DataAsset.h"
+
+#include "VersePieceManifest.generated.h"
+
+class UWorld;
+
+/**
+ * DA_PieceManifest (destruction.md 8): the One File Per Actor GUIDs of every AVerseDestructible
+ * of one arena, sorted by GUID at cook time. PieceIndex = position in this list, the same on
+ * server and clients; the hash is checked in the server welcome.
+ */
+UCLASS(BlueprintType)
+class VERSEDESTRUCTION_API UVersePieceManifest : public UPrimaryDataAsset
+{
+ GENERATED_BODY()
+
+public:
+ static constexpr int32 MaxPieces = 2000;
+
+ /** Sorted ascending (FGuid order). */
+ UPROPERTY(VisibleAnywhere, Category = "Manifest")
+ TArray<FGuid> PieceGuids;
+
+ /** ComputeHash(PieceGuids). */
+ UPROPERTY(VisibleAnywhere, Category = "Manifest")
+ uint32 Hash = 0;
+
+ /** Sorts, de-duplicates and hashes. False if over MaxPieces or a GUID is invalid. */
+ bool Build(TArray<FGuid> Guids, FString* OutError = nullptr);
+
+ /** INDEX_NONE when the GUID is not in the manifest. */
+ int32 IndexOf(const FGuid& Guid) const;
+
+ /** True if PieceGuids is sorted, unique and Hash matches. */
+ bool IsConsistent() const;
+
+ static uint32 ComputeHash(TConstArrayView<FGuid> Guids);
+
+ /** The GUID order rule, shared with the manager when no manifest asset is assigned. */
+ static void SortGuids(TArray<FGuid>& Guids);
+
+#if WITH_EDITOR
+ /** Collects every AVerseDestructible of a world (editor and cook). */
+ static TArray<FGuid> CollectFromWorld(const UWorld& World);
+#endif
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceRules.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceRules.h
new file mode 100644
index 0000000000..c81b79faa3
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceRules.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTuning.h"
+#include "Destruction/VerseDestructionTypes.h"
+
+// The piece state machine of contracts/destruction.md 3.1 and 3.2 as pure functions. The
+// server simulation calls these; nothing else decides a state.
+
+namespace Verse::Destruction::Rules
+{
+ /** How a damage request touches a piece. */
+ enum class EHitRole : uint8
+ {
+ /** A bolt or melee strike on this piece. */
+ Direct,
+ /** The breach charge's target piece. */
+ BreachTarget,
+ /** Another breakable piece with a proxy vertex inside the breach radius. */
+ BreachSide
+ };
+
+ struct FOutcome
+ {
+ EVersePieceState State = EVersePieceState::Intact;
+ float Hp = 0.f;
+ };
+
+ /** Transitions only move towards Destroyed (Repairing and Reset are the only ways back). */
+ VERSEDESTRUCTION_API bool IsForward(EVersePieceState From, EVersePieceState To);
+
+ /**
+ * Applies one damage to a piece that is not Repairing. Returns the new state and hp; the
+ * state never moves backwards. Bullets never take a wall past Holed; melee changes only
+ * glass; catwalks change only by breach charge; concrete and armor steel never change.
+ */
+ VERSEDESTRUCTION_API FOutcome Apply(const FVersePieceClassTuning& Row, EVersePieceState State, float Hp,
+ EVerseFractureCause Cause, EHitRole Role, float Amount);
+
+ /** Which Noise.Fracture loudness a transition produces (destruction.md 6.2). */
+ VERSEDESTRUCTION_API EVerseFractureNoise NoiseKind(EVersePieceClass Class, EVerseFractureCause Cause, EVersePieceState To);
+}
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceTypes.h b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceTypes.h
new file mode 100644
index 0000000000..f9bca910b0
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Pieces/VersePieceTypes.h
@@ -0,0 +1,124 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTuning.h"
+#include "Destruction/VerseDestructionTypes.h"
+
+#include "VersePieceTypes.generated.h"
+
+// Plain data of the destruction runtime (contracts/destruction.md 3, 6.1, 7). Everything here
+// is engine-world free, so the server simulation (FVerseDestructionSim) runs and is tested
+// without a UWorld.
+
+/** One authored nav link of a piece, piece-local cm (destruction.md 6.1). */
+USTRUCT(BlueprintType)
+struct VERSEDESTRUCTION_API FVersePieceNavLink
+{
+ GENERATED_BODY()
+
+ UPROPERTY(EditAnywhere, Category = "Nav")
+ FVector Start = FVector::ZeroVector;
+
+ UPROPERTY(EditAnywhere, Category = "Nav")
+ FVector End = FVector::ZeroVector;
+};
+
+/** Which links of a piece are live in a state (destruction.md 6.1). */
+enum class EVersePieceNavLinkKind : uint8
+{
+ /** Low breach: a mantle link through the opening while Breached. */
+ Mantle,
+ /** Destroyed catwalk: drop-down links to the floor below. */
+ Drop
+};
+
+/**
+ * Static description of one piece, the same on server and clients. Built from an
+ * AVerseDestructible when the manager registers it, or directly by tests.
+ */
+struct VERSEDESTRUCTION_API FVersePieceDef
+{
+ FGuid Guid;
+ EVersePieceClass Class = EVersePieceClass::WallPanel;
+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::SheetMetal;
+
+ /** Piece to world. */
+ FTransform Transform = FTransform::Identity;
+
+ /** Proxy bounds per state, piece-local; Damaged and Repairing reuse others (see GetLocalBounds). */
+ FBox IntactBounds = FBox(ForceInit);
+ TArray<FBox, TInlineAllocator<4>> HoledBounds;
+ TArray<FBox, TInlineAllocator<4>> BreachedBounds;
+ /** Optional authored Remains proxy; invalid = no gameplay collision when Destroyed. */
+ FBox RemainsBounds = FBox(ForceInit);
+
+ /** Intact proxy vertices, piece-local (the breach side-effect radius test of destruction.md 3.2). */
+ TArray<FVector> ProxyVertices;
+
+ /** Opening centroid per Holed / Breached variant, piece-local (destruction.md 3.1). */
+ TArray<FVector, TInlineAllocator<4>> HoledCentroids;
+ TArray<FVector, TInlineAllocator<4>> BreachedCentroids;
+
+ TArray<FVersePieceNavLink> MantleLinks;
+ TArray<FVersePieceNavLink> DropLinks;
+
+ /** Proxy bounds for a state and variant, piece-local; invalid when the state has no proxy. */
+ FBox GetLocalBounds(EVersePieceState State, uint8 Variant) const;
+
+ /** The same in world space (axis-aligned box around the transformed local box). */
+ FBox GetWorldBounds(EVersePieceState State, uint8 Variant) const;
+
+ /** Nearest variant to a piece-local point; 0 when no centroids are authored. */
+ static uint8 NearestVariant(TConstArrayView<FVector> Centroids, const FVector& LocalPoint);
+
+ /** True if any Intact proxy vertex (or, without vertices, the Intact box) lies within Radius of the world point. */
+ bool IsWithinRadius(const FVector& WorldPoint, float RadiusCm) const;
+};
+
+/** Repair priority of a class (destruction.md 7 "Order"): lower first. */
+VERSEDESTRUCTION_API int32 VerseRepairClassPriority(EVersePieceClass Class);
+
+/** The material a class must use (destruction.md 3.2). */
+VERSEDESTRUCTION_API EVersePenetrationMaterial VerseMaterialOfClass(EVersePieceClass Class);
+
+/** Materials that never change state (DR4). */
+VERSEDESTRUCTION_API bool VerseMaterialNeverBreaks(EVersePenetrationMaterial Material);
+
+/**
+ * WP06 start values that are not part of DA_DestructionTuning (drone flight, impulses, debris
+ * body counts). Mirrors unreal/Verse/Data/destruction/tuning.json; tuned through the harness.
+ */
+struct VERSEDESTRUCTION_API FVerseDestructionStartValues
+{
+ float DroneSpeedCmS = 600.f;
+ uint32 DroneNoiseIntervalMs = 1000;
+ float BoltImpulseNs = 20.f;
+ float MeleeImpulseNs = 40.f;
+ float BreachImpulseNs = 1500.f;
+ uint8 BoltStrainRadiusCm = 20;
+ uint8 MeleeStrainRadiusCm = 30;
+ /** Hub events are coalesced per piece per tick always; multicasts beyond the rate cap are dropped (the fast array stays the truth). */
+ bool bCoalescePerTick = true;
+};
+
+/** Everything the simulation needs from DA_DestructionTuning plus the start values. */
+struct VERSEDESTRUCTION_API FVerseDestructionSimTuning
+{
+ TMap<EVersePieceClass, FVersePieceClassTuning> Classes;
+ float BreachSideRadiusCm = 150.f;
+ float RepairDelayS = 60.f;
+ int32 MaxActiveDrones = 3;
+ float DroneMaxHp = 30.f;
+ float RepairEncroachMarginCm = 10.f;
+ float RepairEncroachRecheckS = 0.5f;
+ float NavDirtyMarginCm = 50.f;
+ int32 NavMaxTilesInFlight = 4;
+ int32 MaxFractureEventsPerSecond = 64;
+ FVerseDestructionStartValues Start;
+
+ /** Contract values (a default UVerseDestructionTuning). */
+ static FVerseDestructionSimTuning Contract();
+ static FVerseDestructionSimTuning FromAsset(const UVerseDestructionTuning& Asset);
+
+ const FVersePieceClassTuning& ClassRow(EVersePieceClass Class) const;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Repair/VerseRepairDrone.h b/unreal/Verse/Source/VerseDestruction/Public/Repair/VerseRepairDrone.h
new file mode 100644
index 0000000000..777f8a154f
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Repair/VerseRepairDrone.h
@@ -0,0 +1,68 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "GameFramework/Actor.h"
+
+#include "VerseRepairDrone.generated.h"
+
+class UBoxComponent;
+class UStaticMeshComponent;
+
+/**
+ * A repair drone (destruction.md 7). The server simulation owns its task and position; this
+ * actor only shows it: replicated movement for the cosmetic flight, a bolt-channel hit box with
+ * 30 HP that stops bolts, amber weld effects while repairing. It never blocks or harms pawns.
+ */
+UCLASS(Blueprintable)
+class VERSEDESTRUCTION_API AVerseRepairDrone : public AActor
+{
+ GENERATED_BODY()
+
+public:
+ AVerseRepairDrone();
+
+ /** Index of this drone in the manager's simulation. */
+ UPROPERTY(Replicated, VisibleAnywhere, Category = "Repair")
+ int32 DroneIndex = INDEX_NONE;
+
+ /** EVerseDroneTask as a byte (Docked, Outbound, Repairing, Returning, Down). */
+ UPROPERTY(ReplicatedUsing = OnRep_Task, VisibleAnywhere, Category = "Repair")
+ uint8 Task = 0;
+
+ /** Bumped each time the drone is shot down; clients drop the old body as debris. */
+ UPROPERTY(ReplicatedUsing = OnRep_Generation, VisibleAnywhere, Category = "Repair")
+ uint32 Generation = 0;
+
+ UPROPERTY(Replicated, VisibleAnywhere, Category = "Repair")
+ float Hp = 30.f;
+
+ UBoxComponent* GetHitBox() const { return HitBox; }
+
+ /** Bolts and melee reach the manager's drone damage through the engine damage path. */
+ virtual float TakeDamage(float DamageAmount, const FDamageEvent& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override;
+
+ /** Server: mirror the simulation state. */
+ void SyncFromSim(const FVector& Location, uint8 InTask, uint32 InGeneration, float InHp);
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+
+ /** Client cosmetics hooks (weld sparks, falling body) for the Blueprint look. */
+ UFUNCTION(BlueprintImplementableEvent, Category = "Repair")
+ void OnTaskChanged(uint8 NewTask);
+
+ UFUNCTION(BlueprintImplementableEvent, Category = "Repair")
+ void OnShotDown();
+
+protected:
+ UFUNCTION()
+ void OnRep_Task();
+
+ UFUNCTION()
+ void OnRep_Generation();
+
+ UPROPERTY(VisibleAnywhere, Category = "Repair")
+ TObjectPtr<UBoxComponent> HitBox;
+
+ UPROPERTY(VisibleAnywhere, Category = "Repair")
+ TObjectPtr<UStaticMeshComponent> Body;
+};
diff --git a/unreal/Verse/Source/VerseDestruction/Public/Validation/VerseDestructibleValidator.h b/unreal/Verse/Source/VerseDestruction/Public/Validation/VerseDestructibleValidator.h
new file mode 100644
index 0000000000..5cce543f50
--- /dev/null
+++ b/unreal/Verse/Source/VerseDestruction/Public/Validation/VerseDestructibleValidator.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionTypes.h"
+#include "UObject/Object.h"
+
+#include "VerseDestructibleValidator.generated.h"
+
+class AVerseDestructible;
+class UStaticMesh;
+class UVersePieceManifest;
+
+/** A triangle soup in piece-local centimetres (any source: mesh description, render data, tests). */
+struct VERSEDESTRUCTION_API FVerseMeshSoup
+{
+ TArray<FVector> Positions;
+ /** Three per triangle, counter-clockwise seen from outside (Unreal winding is irrelevant: both orientations are accepted as long as they are consistent). */
+ TArray<int32> Indices;
+
+ void AddBox(const FVector& Min, const FVector& Max);
+ void AddQuad(const FVector& A, const FVector& B, const FVector& C, const FVector& D);
+ int32 NumTriangles() const { return Indices.Num() / 3; }
+};
+
+/** What one check found. */
+struct VERSEDESTRUCTION_API FVerseValidationReport
+{
+ TArray<FString> Errors;
+ /** Median inward thickness along the piece's thickness axis, cm (0 if not measured). */
+ float MeasuredThicknessCm = 0.f;
+
+ bool IsOk() const { return Errors.Num() == 0; }
+ void Merge(const FVerseValidationReport& Other, const FString& Prefix);
+};
+
+/**
+ * UVerseDestructibleValidator (destruction.md 9): breakable pieces are solid, closed volumes whose
+ * thickness matches the material's reference thickness within 10 %; every reachable state has
+ * a proxy, the geometry collection is present, the material matches the class, and the piece is
+ * in the manifest. Pure checks plus a commandlet entry, so both unreal-static/unreal-build and
+ * automation tests run the same code.
+ */
+UCLASS()
+class VERSEDESTRUCTION_API UVerseDestructibleValidator : public UObject
+{
+ GENERATED_BODY()
+
+public:
+ static constexpr float ThicknessTolerance = 0.10f;
+
+ /** Watertight and manifold after welding coincident positions; no zero-area faces. */
+ static FVerseValidationReport CheckClosed(const FVerseMeshSoup& Mesh);
+
+ /** Median inward ray distance from faces facing along +-Axis (unit, piece-local). */
+ static float MeasureThickness(const FVerseMeshSoup& Mesh, const FVector& Axis);
+
+ /** Closed and, when RefThicknessCm > 0, thickness within 10 % of it. */
+ static FVerseValidationReport CheckSolid(const FVerseMeshSoup& Mesh, const FVector& Axis, float RefThicknessCm);
+
+ /** Piece-local axis along which a class measures its thickness. */
+ static FVector ThicknessAxis(EVersePieceClass Class);
+
+ /** Reference thickness of the class's material (DA_PenetrationTable). */
+ static float RefThicknessCm(EVersePieceClass Class);
+
+ /** Proxies of every reachable state, GC, material and manifest, plus the geometry of every mesh it can read. */
+ static FVerseValidationReport ValidatePiece(const AVerseDestructible& Piece, const UVersePieceManifest* Manifest);
+
+ /** Triangles of LOD 0 of a static mesh (render data; cooked meshes need CPU access). False if unreadable. */
+ static bool ReadMesh(const UStaticMesh& Mesh, FVerseMeshSoup& Out);
+};
diff --git a/unreal/Verse/Source/VerseDestruction/VerseDestruction.Build.cs b/unreal/Verse/Source/VerseDestruction/VerseDestruction.Build.cs
index a84722e233..bc3f235ba9 100644
--- a/unreal/Verse/Source/VerseDestruction/VerseDestruction.Build.cs
+++ b/unreal/Verse/Source/VerseDestruction/VerseDestruction.Build.cs
@@ -9,5 +9,11 @@ public class VerseDestruction : ModuleRules
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine" });
PublicDependencyModuleNames.AddRange(new string[] { "VerseCore" });
+ // Engine modules (not Verse edges): FFastArraySerializer and push model of the piece state
+ // (destruction.md 3.3), the debris geometry collections and their real chunk counts (10),
+ // navmesh build feedback for the dirty-tile queue (6.1).
+ PublicDependencyModuleNames.AddRange(new string[] { "NetCore", "Chaos", "GeometryCollectionEngine", "NavigationSystem" });
+ // The validator reads the source geometry of a mesh in the editor (destruction.md 9).
+ PrivateDependencyModuleNames.AddRange(new string[] { "MeshDescription" });
}
}