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 gore with wounds, spatter, pools and the reduced setting (#1143)

Ruben Lütkeabe190b17a59
diff --git a/art/verse/gore/build.py b/art/verse/gore/build.py
new file mode 100644
index 0000000000..aa1ef76e96
--- /dev/null
+++ b/art/verse/gore/build.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""Build the gore assets of the Unreal Verse (WP05).
+
+ python art/verse/gore/build.py # bake masks, then run the editor step
+ python art/verse/gore/build.py --bake # masks and records only (no editor, no lock)
+ python art/verse/gore/build.py --only M_Gore_Droplet # rebuild listed assets only
+
+1. Bakes the procedural masks (``textures.py``) to ``art/verse/.cache/unreal/gore/``
+ (ignored; sources are never committed, art-pipeline 6.4) and writes the
+ import records and MI recipes (``records.py``, art-pipeline 7 and 10.3).
+2. Runs ``unreal_assets.py`` in a headless editor (``-ExecutePythonScript``) under the machine-wide
+ gpu-heavy lock (``scripts/unreal/with_lock.py``), which imports the masks
+ and writes the materials into ``unreal/Verse/Content/Verse/Gore/`` and the
+ test body material into ``Content/Verse/Test/WP05/``.
+
+The run fails when the editor step reports a failure or writes no report.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+REPO = HERE.parents[2]
+sys.path.insert(0, str(REPO))
+sys.path.insert(0, str(HERE))
+
+import records # noqa: E402
+import spec # noqa: E402
+
+from scripts.unreal import _common as common # noqa: E402
+from scripts.unreal import with_lock # noqa: E402
+
+CACHE = records.CACHE
+
+
+def editor_command(script: Path, log: Path) -> list[str]:
+ engine = common.engine_root()
+ return [
+ str(common.editor_cmd(engine)),
+ str(common.project_file(REPO)),
+ # The full editor (headless): texture import needs a Slate application, which the
+ # pythonscript commandlet does not create.
+ f"-ExecutePythonScript={script}",
+ "-unattended",
+ "-nosplash",
+ "-nullrhi",
+ "-nosound",
+ "-NoP4",
+ "-stdout",
+ f"-abslog={log}",
+ ]
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--bake", action="store_true", help="bake the masks and records only")
+ parser.add_argument("--only", nargs="+", default=[],
+ help="rebuild only these assets (untouched assets are never re-saved)")
+ options = parser.parse_args(argv)
+ known = set(spec.TEXTURES) | set(spec.INSTANCES) | set(spec.MATERIALS)
+ unknown = sorted(set(options.only) - known)
+ if unknown:
+ parser.error(f"unknown assets: {', '.join(unknown)}")
+
+ if records.main([]) != 0:
+ return 1
+ if options.bake:
+ return 0
+
+ out_dir = REPO / "unreal" / "Verse" / "Saved" / "Harness" / "proof" / "WP05" / "assets"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ result = out_dir / "unreal_assets.json"
+ result.unlink(missing_ok=True)
+ env = dict(os.environ)
+ env["VERSE_GORE_TEXTURES"] = str(CACHE)
+ env["VERSE_GORE_RESULT"] = str(result)
+ env["VERSE_GORE_QUIT"] = "1"
+ env["VERSE_GORE_HERE"] = str(HERE)
+ env["VERSE_GORE_ONLY"] = ",".join(options.only)
+ code = with_lock.run_locked(
+ editor_command(HERE / "unreal_assets.py", out_dir / "unreal_assets.log"),
+ label="gore assets (wp05)",
+ env=env,
+ )
+ if not result.exists():
+ print(f"[gore] editor exited {code} without a report")
+ return code or 1
+ report = json.loads(result.read_text(encoding="utf-8"))
+ for warning in report.get("warnings", []):
+ print(f"[gore] warning: {warning}")
+ assets = len(report.get("assets", []))
+ print(f"[gore] editor exit {code}, ok={report.get('ok')}, assets={assets}")
+ if not report.get("ok"):
+ print(report.get("traceback", report.get("error", "")))
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/art/verse/gore/records.py b/art/verse/gore/records.py
new file mode 100644
index 0000000000..0807b2f84b
--- /dev/null
+++ b/art/verse/gore/records.py
@@ -0,0 +1,106 @@
+#!/usr/bin/env python3
+"""Import records of the gore assets (WP05, art-pipeline 10.3).
+
+ python art/verse/gore/records.py # bake the masks and write the records
+ python art/verse/gore/records.py --check # fail when a committed record is stale
+
+Writes, owned by WP05 (work-packages 0.2, "Art records"):
+
+ unreal/Verse/Art/Import/Gore/T_Gore_*_M.import.json mask textures (verse.import/1)
+
+Every mask is own work (``license.kind: "own"``) made with numpy, not Blender,
+so ``export.blender`` is ``0.0.0``. The masters, ``MF_Gore_WoundMask`` and the
+test material are built in the editor and are not an imported kind, so they
+need no record. The ``MI_Gore_*`` instances get ``verse.mi/1`` recipes once
+contract change request #1171 (item 3) lets VerseGore's own decal master be a
+parent; until then ``spec.INSTANCES`` is their single description.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+REPO = HERE.parents[2]
+sys.path.insert(0, str(HERE))
+
+import spec # noqa: E402
+
+CACHE = REPO / "art" / "verse" / ".cache" / "unreal" / "gore"
+ART = REPO / "unreal" / "Verse" / "Art"
+
+
+def _sha256(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def texture_record(name: str, png: Path) -> dict:
+ return {
+ "schema": "verse.import/1",
+ "name": name,
+ "asset_path": spec.asset_path(spec.GORE, name),
+ "kind": "texture",
+ "source": {"builder": "art/verse/gore/textures.py", "function": "all_textures", "args": {}},
+ "export": {
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "file": png.relative_to(REPO).as_posix(),
+ "sha256": _sha256(png),
+ "blender": "0.0.0",
+ },
+ "lightmap": "none",
+ "texture": {
+ "group": "World",
+ "max_size": spec.TEXTURES[name],
+ "srgb": False,
+ "compression": "Masks",
+ "flip_green": False,
+ "channels": dict(spec.TEXTURE_CHANNELS),
+ },
+ "license": {"kind": "own"},
+ "owner": spec.OWNER,
+ }
+
+
+def all_records(cache: Path) -> dict[Path, dict]:
+ out: dict[Path, dict] = {}
+ for name in spec.TEXTURES:
+ record = texture_record(name, cache / f"{name}.png")
+ out[ART / "Import" / "Gore" / f"{name}.import.json"] = record
+ return out
+
+
+def render(record: dict) -> str:
+ return json.dumps(record, indent=2, sort_keys=True) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--check", action="store_true", help="compare instead of writing")
+ options = parser.parse_args(argv)
+
+ import textures
+
+ textures.bake(CACHE)
+ stale = []
+ for path, record in all_records(CACHE).items():
+ text = render(record)
+ if options.check:
+ if not path.exists() or path.read_text(encoding="utf-8") != text:
+ stale.append(path.relative_to(REPO).as_posix())
+ continue
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(text.encode("utf-8"))
+ if stale:
+ print("[gore] stale records:\n " + "\n ".join(stale))
+ return 1
+ print("[gore] records " + ("current" if options.check else "written"))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/art/verse/gore/spec.py b/art/verse/gore/spec.py
new file mode 100644
index 0000000000..e2a68e99c3
--- /dev/null
+++ b/art/verse/gore/spec.py
@@ -0,0 +1,60 @@
+"""The gore asset list (WP05): one table read by the editor step and the record writer.
+
+Pure data, no ``unreal`` or ``bpy`` import, so ``unreal_assets.py`` (inside the
+editor) and ``records.py`` (plain Python) describe the same assets.
+"""
+
+from __future__ import annotations
+
+OWNER = "WP05"
+GORE = "/Game/Verse/Gore"
+TEST = "/Game/Verse/Test/WP05"
+
+# Mask textures: name -> (max size, channel meaning). Built by textures.py.
+TEXTURES: dict[str, int] = {
+ "T_Gore_Spatter_0_M": 512,
+ "T_Gore_Spatter_1_M": 512,
+ "T_Gore_Spatter_2_M": 512,
+ "T_Gore_Spatter_3_M": 512,
+ "T_Gore_Drip_M": 512,
+ "T_Gore_Pool_M": 1024,
+}
+TEXTURE_CHANNELS = {
+ "r": "coverage (decal opacity)",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "b": "unused, 0",
+}
+
+# Decal instances of M_Gore_Decal: name -> (mask texture, scalar overrides).
+INSTANCES: dict[str, tuple[str, dict[str, float]]] = {
+ "MI_Gore_Spatter_0": ("T_Gore_Spatter_0_M", {}),
+ "MI_Gore_Spatter_1": ("T_Gore_Spatter_1_M", {}),
+ "MI_Gore_Spatter_2": ("T_Gore_Spatter_2_M", {}),
+ "MI_Gore_Spatter_3": ("T_Gore_Spatter_3_M", {}),
+ "MI_Gore_Drip": ("T_Gore_Drip_M", {"RoughnessThick": 0.1}),
+ "MI_Gore_Pool": ("T_Gore_Pool_M", {"RoughnessThick": 0.05, "RoughnessThin": 0.2}),
+}
+
+# Masters, the material function and the test material:
+# name -> (folder, kind, builder function, use).
+MATERIALS: dict[str, tuple[str, str, str, str]] = {
+ "M_Gore_Decal": (GORE, "material", "build_decal_master",
+ "deferred decal master: Mask texture, decal colour R = opacity, "
+ "G = darkening"),
+ "M_Gore_Droplet": (GORE, "material", "build_droplet",
+ "burst droplets on an instanced static mesh; world position offset animates "
+ "each instance from 7 custom data floats (spawn time, velocity xyz, life, "
+ "drag, gravity)"),
+ "M_Gore_Flash": (GORE, "material", "build_flash",
+ "Reduced level: neutral, unlit, additive impact flash"),
+ "MF_Gore_WoundMask": (GORE, "material_function", "build_wound_function",
+ "wound mask for the character master: Verse_WoundCount and "
+ "Verse_Wound_00..15 (xyz reference-pose component space cm, w radius cm) "
+ "against the pre-skinned position"),
+ "M_Gore_TestBody": (TEST, "material", "build_test_body",
+ "WP13 fake: a body material using the wound mask (test only)"),
+}
+
+
+def asset_path(folder: str, name: str) -> str:
+ return f"{folder}/{name}.{name}"
diff --git a/art/verse/gore/textures.py b/art/verse/gore/textures.py
new file mode 100644
index 0000000000..b0d70b9581
--- /dev/null
+++ b/art/verse/gore/textures.py
@@ -0,0 +1,180 @@
+"""Procedural gore mask textures for the Unreal Verse (WP05, own work).
+
+Every texture is generated from a seed, so the bake is reproducible and the
+PNG sources are never committed (art-pipeline 6.4): ``build.py`` writes them
+to ``art/verse/.cache/gore/`` and the editor step imports them as
+``/Game/Verse/Gore/T_Gore_*_M``.
+
+Channel use (``_M`` masks, sRGB off):
+ R coverage (decal opacity)
+ G thickness (darker, glossier where blood is thick)
+ B unused, 0
+
+Shapes:
+ spatter a directional burst: a dense core, elongated drops and satellite
+ droplets with tails flying toward +U (the decal's roll points it
+ along the bolt), four seeds
+ drip a small round drip with a few satellites (floor below a wound)
+ pool a large irregular pool with a thick centre and a soft rim
+"""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import numpy as np
+
+SIZE = 512
+POOL_SIZE = 1024
+SPATTER_SEEDS = (11, 23, 37, 53)
+
+
+def _grid(size: int) -> tuple[np.ndarray, np.ndarray]:
+ axis = (np.arange(size, dtype=np.float32) + 0.5) / size * 2.0 - 1.0
+ return np.meshgrid(axis, axis, indexing="xy")
+
+
+def _value_noise(size: int, cells: int, rng: np.random.Generator) -> np.ndarray:
+ """Smooth value noise in [0, 1] (bicubic-free: smoothstep-blended lattice)."""
+ lattice = rng.random((cells + 1, cells + 1), dtype=np.float32)
+ coords = np.linspace(0.0, cells, size, endpoint=False, dtype=np.float32)
+ i = np.floor(coords).astype(np.int32)
+ f = coords - i
+ f = f * f * (3.0 - 2.0 * f)
+ x0, x1 = i, np.minimum(i + 1, cells)
+ top = lattice[np.ix_(x0, x0)] * (1 - f)[None, :] + lattice[np.ix_(x0, x1)] * f[None, :]
+ bottom = lattice[np.ix_(x1, x0)] * (1 - f)[None, :] + lattice[np.ix_(x1, x1)] * f[None, :]
+ return top * (1 - f)[:, None] + bottom * f[:, None]
+
+
+def _fbm(size: int, rng: np.random.Generator, octaves: int = 4, base: int = 4) -> np.ndarray:
+ total = np.zeros((size, size), dtype=np.float32)
+ amplitude, weight = 1.0, 0.0
+ for octave in range(octaves):
+ total += amplitude * _value_noise(size, base * 2**octave, rng)
+ weight += amplitude
+ amplitude *= 0.5
+ return total / weight
+
+
+def _blob(
+ x: np.ndarray, y: np.ndarray, cx: float, cy: float, rx: float, ry: float, angle: float
+) -> np.ndarray:
+ """Signed field > 0 inside an ellipse (1 at the centre)."""
+ c, s = math.cos(angle), math.sin(angle)
+ dx, dy = x - cx, y - cy
+ u = (dx * c + dy * s) / rx
+ v = (-dx * s + dy * c) / ry
+ return 1.0 - (u * u + v * v)
+
+
+def _soft(field: np.ndarray, edge: float = 0.08) -> np.ndarray:
+ return np.clip(field / edge, 0.0, 1.0)
+
+
+def spatter(seed: int, size: int = SIZE) -> np.ndarray:
+ rng = np.random.default_rng(seed)
+ x, y = _grid(size)
+ noise = _fbm(size, rng)
+ field = np.full((size, size), -1.0, dtype=np.float32)
+ thick = np.zeros((size, size), dtype=np.float32)
+
+ # Core: a few overlapping lobes left of centre.
+ for _ in range(rng.integers(3, 6)):
+ cx, cy = rng.uniform(-0.45, -0.15), rng.uniform(-0.15, 0.15)
+ r = rng.uniform(0.14, 0.26)
+ lobe = _blob(x, y, cx, cy, r * rng.uniform(1.0, 1.5), r, rng.uniform(-0.4, 0.4))
+ field = np.maximum(field, lobe)
+ thick = np.maximum(thick, np.clip(lobe, 0.0, 1.0))
+
+ # Elongated drops fanning toward +U, with tails.
+ for _ in range(rng.integers(18, 30)):
+ angle = rng.normal(0.0, 0.35)
+ dist = rng.uniform(0.25, 0.9)
+ cx, cy = -0.3 + math.cos(angle) * dist, math.sin(angle) * dist
+ r = rng.uniform(0.012, 0.05) * (1.15 - dist * 0.6)
+ stretch = 1.5 + dist * 3.0
+ drop = _blob(x, y, cx, cy, r * stretch, r, angle)
+ back = r * stretch * 1.4
+ tail = _blob(x, y, cx - math.cos(angle) * back, cy - math.sin(angle) * back,
+ r * stretch * 1.6, r * 0.35, angle)
+ field = np.maximum(field, np.maximum(drop, tail * 0.9))
+ thick = np.maximum(thick, np.clip(drop, 0.0, 1.0) * 0.8)
+
+ # Fine mist.
+ for _ in range(rng.integers(60, 110)):
+ angle = rng.normal(0.0, 0.6)
+ dist = rng.uniform(0.2, 0.98)
+ cx, cy = -0.3 + math.cos(angle) * dist, math.sin(angle) * dist
+ r = rng.uniform(0.003, 0.011)
+ field = np.maximum(field, _blob(x, y, cx, cy, r * 1.3, r, angle))
+
+ field = field + (noise - 0.5) * 0.25
+ coverage = _soft(field, 0.06)
+ thickness = np.clip(thick * 0.8 + (noise - 0.5) * 0.3, 0.0, 1.0) * coverage
+ # Fade out at the square's border so no decal shows a straight edge.
+ border = np.clip((1.0 - np.maximum(np.abs(x), np.abs(y))) / 0.06, 0.0, 1.0)
+ return np.stack([coverage * border, thickness * border, np.zeros_like(coverage)], axis=-1)
+
+
+def drip(seed: int = 71, size: int = SIZE) -> np.ndarray:
+ rng = np.random.default_rng(seed)
+ x, y = _grid(size)
+ noise = _fbm(size, rng)
+ field = _blob(x, y, 0.0, 0.0, 0.42, 0.38, rng.uniform(0, math.pi))
+ for _ in range(9):
+ a, d = rng.uniform(0, 2 * math.pi), rng.uniform(0.5, 0.85)
+ r = rng.uniform(0.03, 0.08)
+ satellite = _blob(x, y, math.cos(a) * d, math.sin(a) * d, r, r, 0.0)
+ field = np.maximum(field, satellite)
+ field = field + (noise - 0.5) * 0.3
+ coverage = _soft(field, 0.05)
+ thickness = np.clip(_blob(x, y, 0.0, 0.0, 0.35, 0.3, 0.0), 0.0, 1.0) * coverage
+ return np.stack([coverage, thickness, np.zeros_like(coverage)], axis=-1)
+
+
+def pool(seed: int = 97, size: int = POOL_SIZE) -> np.ndarray:
+ rng = np.random.default_rng(seed)
+ x, y = _grid(size)
+ noise = _fbm(size, rng, octaves=5, base=3)
+ radius = np.sqrt(x * x + y * y)
+ angle = np.arctan2(y, x)
+ wobble = 0.0
+ for k in range(2, 7):
+ phase = rng.uniform(0, 2 * math.pi)
+ wobble = wobble + rng.uniform(0.02, 0.06) / k * np.sin(k * angle + phase)
+ field = (0.78 + wobble) - radius + (noise - 0.5) * 0.18
+ for _ in range(4): # lobes where the blood ran
+ a = rng.uniform(0, 2 * math.pi)
+ lobe = _blob(x, y, math.cos(a) * 0.55, math.sin(a) * 0.55, 0.28, 0.17, a)
+ field = np.maximum(field, lobe * 0.3)
+ coverage = _soft(field, 0.03)
+ thickness = np.clip(1.0 - radius / 0.8, 0.0, 1.0) ** 0.6 * coverage
+ return np.stack([coverage, thickness, np.zeros_like(coverage)], axis=-1)
+
+
+def all_textures() -> dict[str, np.ndarray]:
+ textures = {
+ f"T_Gore_Spatter_{index}_M": spatter(seed) for index, seed in enumerate(SPATTER_SEEDS)
+ }
+ textures["T_Gore_Drip_M"] = drip()
+ textures["T_Gore_Pool_M"] = pool()
+ return textures
+
+
+def write_png(path: Path, image: np.ndarray) -> None:
+ from PIL import Image
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+ data = (np.clip(image, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
+ Image.fromarray(data, mode="RGB").save(path, optimize=True)
+
+
+def bake(out_dir: Path) -> list[Path]:
+ paths = []
+ for name, image in all_textures().items():
+ path = out_dir / f"{name}.png"
+ write_png(path, image)
+ paths.append(path)
+ return paths
diff --git a/art/verse/gore/unreal_assets.py b/art/verse/gore/unreal_assets.py
new file mode 100644
index 0000000000..07ae18cecd
--- /dev/null
+++ b/art/verse/gore/unreal_assets.py
@@ -0,0 +1,413 @@
+"""Editor step of the gore asset build (WP05): textures, materials, instances.
+
+Runs inside the headless Unreal editor (``-ExecutePythonScript``), started
+by ``art/verse/gore/build.py`` under the machine lock. Inputs come from the
+environment:
+
+ VERSE_GORE_TEXTURES folder with the baked ``T_Gore_*_M.png`` masks
+ VERSE_GORE_RESULT JSON report path
+ VERSE_GORE_QUIT "1": quit the editor when done
+ VERSE_GORE_HERE this folder (for ``spec.py``, the shared asset table)
+ VERSE_GORE_ONLY comma-separated asset names to rebuild; empty = all
+
+Creates or replaces, under ``/Game/Verse/Gore`` (owned by WP05):
+
+ T_Gore_Spatter_0..3_M, T_Gore_Drip_M, T_Gore_Pool_M mask textures
+ M_Gore_Decal deferred decal master (mask, thickness, decal colour)
+ MI_Gore_Spatter_0..3 wall and floor spatter
+ MI_Gore_Drip floor drip below a wound
+ MI_Gore_Pool pool under a body (glossier)
+ M_Gore_Droplet burst droplets (instanced static meshes, animated on the GPU)
+ M_Gore_Flash Reduced level: neutral impact flash (unlit, additive)
+ MF_Gore_WoundMask wound mask function for the character master (WP13)
+
+and under ``/Game/Verse/Test/WP05``:
+
+ M_Gore_TestBody the WP13 fake: a body material with the wound mask
+
+Colours are the dark, desaturated reds art-pipeline 8.1 leaves to VerseGore.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import traceback
+
+import unreal
+
+sys.path.insert(0, os.environ.get("VERSE_GORE_HERE") or os.path.dirname(os.path.abspath(__file__)))
+
+import spec # noqa: E402
+
+GORE = spec.GORE
+TEST = spec.TEST
+TEXTURES = list(spec.TEXTURES)
+ONLY = {name for name in os.environ.get("VERSE_GORE_ONLY", "").split(",") if name}
+# Linear colours: fresh blood is a dark red, thick blood near black-red.
+BLOOD = unreal.LinearColor(0.115, 0.006, 0.004, 1.0)
+BLOOD_THICK = unreal.LinearColor(0.032, 0.0015, 0.001, 1.0)
+WOUND_SLOTS = 16
+
+ASSETS = unreal.AssetToolsHelpers.get_asset_tools()
+MEL = unreal.MaterialEditingLibrary
+LIB = unreal.EditorAssetLibrary
+REPORT: dict = {"ok": True, "assets": [], "warnings": []}
+
+
+def warn(text: str) -> None:
+ REPORT["warnings"].append(text)
+ unreal.log_warning(f"[verse_gore] {text}")
+
+
+def fresh(name: str, folder: str, cls, factory):
+ path = f"{folder}/{name}"
+ if LIB.does_asset_exist(path):
+ LIB.delete_asset(path)
+ asset = ASSETS.create_asset(name, folder, cls, factory)
+ REPORT["assets"].append(path)
+ return asset
+
+
+def set_prop(obj, name: str, value) -> None:
+ try:
+ obj.set_editor_property(name, value)
+ except Exception as error: # property names move between engine versions
+ warn(f"{obj.get_name()}.{name}: {error}")
+
+
+def wanted(name: str) -> bool:
+ return not ONLY or name in ONLY
+
+
+def load_textures() -> dict:
+ textures = {}
+ for name in TEXTURES:
+ texture = unreal.load_asset(f"{GORE}/{name}")
+ if texture is None:
+ raise RuntimeError(f"texture missing (build it first): {name}")
+ textures[name] = texture
+ return textures
+
+
+def import_textures(folder: str) -> dict:
+ tasks = []
+ for name in [name for name in TEXTURES if wanted(name)]:
+ task = unreal.AssetImportTask()
+ task.filename = os.path.join(folder, f"{name}.png")
+ task.destination_path = GORE
+ task.destination_name = name
+ task.automated = True
+ task.replace_existing = True
+ task.save = False
+ tasks.append(task)
+ if tasks:
+ ASSETS.import_asset_tasks(tasks)
+ textures = load_textures()
+ for name in [name for name in TEXTURES if wanted(name)]:
+ texture = textures[name]
+ if texture is None:
+ raise RuntimeError(f"texture import failed: {name}")
+ set_prop(texture, "srgb", False)
+ set_prop(texture, "compression_settings", unreal.TextureCompressionSettings.TC_MASKS)
+ set_prop(texture, "lod_group", unreal.TextureGroup.TEXTUREGROUP_WORLD)
+ # Gore appears the frame it is hit; a streaming mip would show a flat square first.
+ set_prop(texture, "never_stream", True)
+ REPORT["assets"].append(f"{GORE}/{name}")
+ return textures
+
+
+def node(material, cls, x: int, y: int, **props):
+ expression = MEL.create_material_expression(material, cls, x, y)
+ for key, value in props.items():
+ set_prop(expression, key, value)
+ return expression
+
+
+def fnode(function, cls, x: int, y: int, **props):
+ expression = MEL.create_material_expression_in_function(function, cls, x, y)
+ for key, value in props.items():
+ set_prop(expression, key, value)
+ return expression
+
+
+def link(a, a_out: str, b, b_in: str) -> None:
+ if not MEL.connect_material_expressions(a, a_out, b, b_in):
+ warn(f"link {a.get_name()}.{a_out} -> {b.get_name()}.{b_in} failed")
+
+
+def mask(material, make, source, channels: str, x: int, y: int):
+ flags = {c: c in channels for c in "rgba"}
+ expression = make(material, unreal.MaterialExpressionComponentMask, x, y, **flags)
+ link(source, "", expression, "")
+ return expression
+
+
+def build_decal_master(textures: dict):
+ material = fresh("M_Gore_Decal", GORE, unreal.Material, unreal.MaterialFactoryNew())
+ set_prop(material, "material_domain", unreal.MaterialDomain.MD_DEFERRED_DECAL)
+ set_prop(material, "blend_mode", unreal.BlendMode.BLEND_TRANSLUCENT)
+ sample = node(material, unreal.MaterialExpressionTextureSampleParameter2D, -900, 0,
+ parameter_name="Mask", texture=textures["T_Gore_Spatter_0_M"],
+ sampler_type=unreal.MaterialSamplerType.SAMPLERTYPE_MASKS)
+ decal = node(material, unreal.MaterialExpressionDecalColor, -900, 300)
+ # Decal colour (float3): R = opacity, G = darkening (VerseGore sets it per decal).
+ decal_a = mask(material, node, decal, "r", -700, 300)
+ decal_g = mask(material, node, decal, "g", -700, 400)
+ opacity_scale = node(material, unreal.MaterialExpressionScalarParameter, -700, 200,
+ parameter_name="Opacity", default_value=1.0)
+ opacity = node(material, unreal.MaterialExpressionMultiply, -450, 150)
+ link(sample, "R", opacity, "A")
+ link(decal_a, "", opacity, "B")
+ opacity2 = node(material, unreal.MaterialExpressionMultiply, -250, 150)
+ link(opacity, "", opacity2, "A")
+ link(opacity_scale, "", opacity2, "B")
+ MEL.connect_material_property(opacity2, "", unreal.MaterialProperty.MP_OPACITY)
+
+ fresh_color = node(material, unreal.MaterialExpressionVectorParameter, -700, -300,
+ parameter_name="BloodColor", default_value=BLOOD)
+ thick_color = node(material, unreal.MaterialExpressionVectorParameter, -700, -150,
+ parameter_name="BloodThickColor", default_value=BLOOD_THICK)
+ color = node(material, unreal.MaterialExpressionLinearInterpolate, -450, -250)
+ link(fresh_color, "", color, "A")
+ link(thick_color, "", color, "B")
+ link(sample, "G", color, "Alpha")
+ shade = node(material, unreal.MaterialExpressionMultiply, -250, -250)
+ link(color, "", shade, "A")
+ link(decal_g, "", shade, "B")
+ MEL.connect_material_property(shade, "", unreal.MaterialProperty.MP_BASE_COLOR)
+
+ rough_thin = node(material, unreal.MaterialExpressionScalarParameter, -700, 500,
+ parameter_name="RoughnessThin", default_value=0.42)
+ rough_thick = node(material, unreal.MaterialExpressionScalarParameter, -700, 600,
+ parameter_name="RoughnessThick", default_value=0.14)
+ rough = node(material, unreal.MaterialExpressionLinearInterpolate, -450, 520)
+ link(rough_thin, "", rough, "A")
+ link(rough_thick, "", rough, "B")
+ link(sample, "G", rough, "Alpha")
+ MEL.connect_material_property(rough, "", unreal.MaterialProperty.MP_ROUGHNESS)
+ MEL.recompile_material(material)
+ return material
+
+
+def build_instance(name: str, parent, texture, scalars: dict | None = None):
+ instance = fresh(name, GORE, unreal.MaterialInstanceConstant,
+ unreal.MaterialInstanceConstantFactoryNew())
+ MEL.set_material_instance_parent(instance, parent)
+ MEL.set_material_instance_texture_parameter_value(instance, "Mask", texture)
+ for key, value in (scalars or {}).items():
+ MEL.set_material_instance_scalar_parameter_value(instance, key, value)
+ MEL.update_material_instance(instance)
+ return instance
+
+
+# World position offset of one droplet instance (HLSL of a Custom node). The instance sits at the
+# burst origin; custom data carries spawn time, velocity, life, drag and gravity, and the motion is
+# the exact solution of gravity plus linear drag, the same as UVerseGoreSubsystem::DropletOffset.
+# A droplet stretches along its velocity, shrinks over its life and collapses to its pivot after.
+DROPLET_WPO = """
+float age = max(Now - Spawn, 0.0);
+float k = max(Drag, 0.01);
+float e = exp(-k * age);
+float3 terminal = float3(0.0, 0.0, Gravity / k);
+float3 velocity = float3(VX, VY, VZ);
+float3 travel = (velocity + terminal) * ((1.0 - e) / k) - terminal * age;
+float3 current = (velocity + terminal) * e - terminal;
+float speed = length(current);
+float3 dir = speed > 0.001 ? current / speed : float3(0.0, 0.0, 1.0);
+float alive = age < Life ? 1.0 : 0.0;
+float shrink = (1.0 - 0.6 * saturate(age / max(Life, 0.01))) * alive;
+float3 shaped = (Offset + dir * dot(Offset, dir) * (speed / 400.0)) * shrink;
+return travel * alive + shaped - Offset;
+"""
+DROPLET_INPUTS = ["Offset", "Now", "Spawn", "VX", "VY", "VZ", "Life", "Drag", "Gravity"]
+
+
+def build_droplet():
+ material = fresh("M_Gore_Droplet", GORE, unreal.Material, unreal.MaterialFactoryNew())
+ set_prop(material, "used_with_instanced_static_meshes", True)
+ # Droplets fly up to ~4 m from their instance; culling bounds must cover the offset.
+ set_prop(material, "max_world_position_offset_displacement", 450.0)
+ color = node(material, unreal.MaterialExpressionVectorParameter, -500, -100,
+ parameter_name="BloodColor", default_value=BLOOD)
+ MEL.connect_material_property(color, "", unreal.MaterialProperty.MP_BASE_COLOR)
+ rough = node(material, unreal.MaterialExpressionConstant, -500, 100, r=0.12)
+ MEL.connect_material_property(rough, "", unreal.MaterialProperty.MP_ROUGHNESS)
+ spec_node = node(material, unreal.MaterialExpressionConstant, -500, 200, r=0.65)
+ MEL.connect_material_property(spec_node, "", unreal.MaterialProperty.MP_SPECULAR)
+
+ inputs = []
+ for name in DROPLET_INPUTS:
+ item = unreal.CustomInput()
+ item.set_editor_property("input_name", name)
+ inputs.append(item)
+ custom = node(material, unreal.MaterialExpressionCustom, -300, 400,
+ code=DROPLET_WPO.strip(), description="VerseGoreDroplet",
+ output_type=unreal.CustomMaterialOutputType.CMOT_FLOAT3)
+ set_prop(custom, "inputs", inputs)
+ # Vertex offset from the instance pivot in world space (local = instance space for an ISM).
+ local = node(material, unreal.MaterialExpressionLocalPosition, -1100, 300,
+ included_offsets=unreal.PositionIncludedOffsets.EXCLUDE_OFFSETS)
+ to_world = node(material, unreal.MaterialExpressionTransform, -900, 300,
+ transform_source_type=unreal.MaterialVectorCoordTransformSource.TRANSFORMSOURCE_LOCAL,
+ transform_type=unreal.MaterialVectorCoordTransform.TRANSFORM_WORLD)
+ link(local, "", to_world, "")
+ link(to_world, "", custom, "Offset")
+ now = node(material, unreal.MaterialExpressionTime, -900, 400)
+ link(now, "", custom, "Now")
+ for index, name in enumerate(["Spawn", "VX", "VY", "VZ", "Life", "Drag", "Gravity"]):
+ data = node(material, unreal.MaterialExpressionPerInstanceCustomData,
+ -900, 480 + 80 * index, data_index=index)
+ link(data, "", custom, name)
+ MEL.connect_material_property(custom, "", unreal.MaterialProperty.MP_WORLD_POSITION_OFFSET)
+ MEL.recompile_material(material)
+ return material
+
+
+def build_flash():
+ material = fresh("M_Gore_Flash", GORE, unreal.Material, unreal.MaterialFactoryNew())
+ set_prop(material, "used_with_instanced_static_meshes", True)
+ set_prop(material, "blend_mode", unreal.BlendMode.BLEND_ADDITIVE)
+ set_prop(material, "shading_model", unreal.MaterialShadingModel.MSM_UNLIT)
+ # Neutral: warm-white, never red (no blood) and never cyan or violet (art-pipeline 8.3).
+ color = node(material, unreal.MaterialExpressionConstant3Vector, -700, 0,
+ constant=unreal.LinearColor(0.9, 0.86, 0.78, 1.0))
+ fresnel = node(material, unreal.MaterialExpressionFresnel, -700, 200)
+ inverse = node(material, unreal.MaterialExpressionOneMinus, -500, 200)
+ link(fresnel, "", inverse, "")
+ glow = node(material, unreal.MaterialExpressionMultiply, -350, 50)
+ link(color, "", glow, "A")
+ link(inverse, "", glow, "B")
+ strength = node(material, unreal.MaterialExpressionScalarParameter, -350, 250,
+ parameter_name="Strength", default_value=3.0)
+ out = node(material, unreal.MaterialExpressionMultiply, -150, 100)
+ link(glow, "", out, "A")
+ link(strength, "", out, "B")
+ MEL.connect_material_property(out, "", unreal.MaterialProperty.MP_EMISSIVE_COLOR)
+ MEL.recompile_material(material)
+ return material
+
+
+def build_wound_mask(owner, make, x0: int, y0: int):
+ """Wound mask: max over 16 slots of saturate((radius - |p - centre|) / soft).
+
+ ``p`` is the pre-skinned (reference pose) local position, so a wound sits
+ on the same spot of the body whatever the animation does. Returns the node
+ whose single output is the 0..1 mask.
+ """
+ position = make(owner, unreal.MaterialExpressionPreSkinnedPosition, x0, y0)
+ interp = make(owner, unreal.MaterialExpressionVertexInterpolator, x0 + 200, y0)
+ link(position, "", interp, "")
+ count = make(owner, unreal.MaterialExpressionScalarParameter, x0 + 200, y0 - 200,
+ parameter_name="Verse_WoundCount", default_value=0.0)
+ total = None
+ for index in range(WOUND_SLOTS):
+ y = y0 + 150 * (index + 1)
+ slot = make(owner, unreal.MaterialExpressionVectorParameter, x0, y,
+ parameter_name=f"Verse_Wound_{index:02d}",
+ default_value=unreal.LinearColor(0.0, 0.0, 0.0, 0.0))
+ centre = mask(owner, make, slot, "rgb", x0 + 200, y)
+ distance = make(owner, unreal.MaterialExpressionDistance, x0 + 400, y)
+ link(interp, "", distance, "A")
+ link(centre, "", distance, "B")
+ # A vector parameter's default output is RGB; the radius is its "A" output.
+ inside = make(owner, unreal.MaterialExpressionSubtract, x0 + 600, y)
+ link(slot, "A", inside, "A")
+ link(distance, "", inside, "B")
+ soft = make(owner, unreal.MaterialExpressionMultiply, x0 + 600, y + 60, const_b=0.4)
+ link(slot, "A", soft, "A")
+ soft_min = make(owner, unreal.MaterialExpressionMax, x0 + 750, y + 60, const_b=0.05)
+ link(soft, "", soft_min, "A")
+ ratio = make(owner, unreal.MaterialExpressionDivide, x0 + 900, y)
+ link(inside, "", ratio, "A")
+ link(soft_min, "", ratio, "B")
+ clamp = make(owner, unreal.MaterialExpressionSaturate, x0 + 1050, y)
+ link(ratio, "", clamp, "")
+ if total is None:
+ total = clamp
+ else:
+ merged = make(owner, unreal.MaterialExpressionMax, x0 + 1200, y)
+ link(total, "", merged, "A")
+ link(clamp, "", merged, "B")
+ total = merged
+ gate = make(owner, unreal.MaterialExpressionSaturate, x0 + 400, y0 - 200)
+ link(count, "", gate, "")
+ gated = make(owner, unreal.MaterialExpressionMultiply, x0 + 1400, y0)
+ link(total, "", gated, "A")
+ link(gate, "", gated, "B")
+ return gated
+
+
+def build_wound_function():
+ function = fresh("MF_Gore_WoundMask", GORE, unreal.MaterialFunction,
+ unreal.MaterialFunctionFactoryNew())
+ set_prop(function, "description",
+ "Verse wound mask (WP05). 0..1 mask from Verse_WoundCount and Verse_Wound_00..15 "
+ "(xyz: reference-pose component space cm, w: radius cm). Needs a skeletal mesh.")
+ gated = build_wound_mask(function, fnode, -1800, -1400)
+ output = fnode(function, unreal.MaterialExpressionFunctionOutput, 0, 0, output_name="Mask")
+ link(gated, "", output, "")
+ MEL.update_material_function(function)
+ return function
+
+
+def build_test_body():
+ material = fresh("M_Gore_TestBody", TEST, unreal.Material, unreal.MaterialFactoryNew())
+ set_prop(material, "used_with_skeletal_mesh", True)
+ wound = build_wound_mask(material, node, -2200, -1400)
+ skin = node(material, unreal.MaterialExpressionConstant3Vector, -500, -300,
+ constant=unreal.LinearColor(0.21, 0.19, 0.17, 1.0))
+ blood = node(material, unreal.MaterialExpressionConstant3Vector, -500, -150, constant=BLOOD)
+ color = node(material, unreal.MaterialExpressionLinearInterpolate, -250, -250)
+ link(skin, "", color, "A")
+ link(blood, "", color, "B")
+ link(wound, "", color, "Alpha")
+ MEL.connect_material_property(color, "", unreal.MaterialProperty.MP_BASE_COLOR)
+ rough = node(material, unreal.MaterialExpressionLinearInterpolate, -250, 50,
+ const_a=0.75, const_b=0.2)
+ link(wound, "", rough, "Alpha")
+ MEL.connect_material_property(rough, "", unreal.MaterialProperty.MP_ROUGHNESS)
+ MEL.recompile_material(material)
+ return material
+
+
+def main() -> None:
+ folder = os.environ["VERSE_GORE_TEXTURES"]
+ textures = import_textures(folder)
+ if wanted("M_Gore_Decal"):
+ master = build_decal_master(textures)
+ else:
+ master = unreal.load_asset(f"{GORE}/M_Gore_Decal")
+ for name, (texture, scalars) in spec.INSTANCES.items():
+ if wanted(name):
+ build_instance(name, master, textures[texture], scalars)
+ builders = {
+ "M_Gore_Droplet": build_droplet,
+ "M_Gore_Flash": build_flash,
+ "MF_Gore_WoundMask": build_wound_function,
+ "M_Gore_TestBody": build_test_body,
+ }
+ for name, build in builders.items():
+ if wanted(name):
+ build()
+ for path in REPORT["assets"]:
+ if not LIB.save_asset(path, only_if_is_dirty=False):
+ warn(f"save failed: {path}")
+
+
+try:
+ main()
+except Exception as error: # the host must see every failure in the report
+ REPORT["ok"] = False
+ REPORT["error"] = f"{type(error).__name__}: {error}"
+ REPORT["traceback"] = traceback.format_exc()
+finally:
+ result = os.environ.get("VERSE_GORE_RESULT")
+ if result:
+ with open(result, "w", encoding="utf-8") as handle:
+ json.dump(REPORT, handle, indent=2, sort_keys=True)
+ unreal.log(f"[verse_gore] ok={REPORT['ok']} assets={len(REPORT['assets'])} "
+ f"warnings={len(REPORT['warnings'])}")
+ if os.environ.get("VERSE_GORE_QUIT") == "1":
+ unreal.SystemLibrary.quit_editor()
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Drip_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Drip_M.import.json
new file mode 100644
index 0000000000..a7d919bdbe
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Drip_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Drip_M.T_Gore_Drip_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Drip_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "76905de8e67e8b1a66cdbb20c7ed4bac20661b9dc7ffe8535232d2134f234b72"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Drip_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 512,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Pool_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Pool_M.import.json
new file mode 100644
index 0000000000..3f5e8fe3d8
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Pool_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Pool_M.T_Gore_Pool_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Pool_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "b05d00e7289da957fca1e596022ee65a4723770adb0addbdb3e1577d1436c30c"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Pool_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 1024,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_0_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_0_M.import.json
new file mode 100644
index 0000000000..d0d9f28360
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_0_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Spatter_0_M.T_Gore_Spatter_0_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Spatter_0_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "dcd0ab1dc8d257d6a73402d71bda1f9c6966fb28669f35dff2215885eaabc019"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Spatter_0_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 512,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_1_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_1_M.import.json
new file mode 100644
index 0000000000..c1680ac071
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_1_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Spatter_1_M.T_Gore_Spatter_1_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Spatter_1_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "5a03626b5425d1fa4c492315f7eaee76d9866afabf50583c5f75900269a396b1"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Spatter_1_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 512,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_2_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_2_M.import.json
new file mode 100644
index 0000000000..84629bc9ce
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_2_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Spatter_2_M.T_Gore_Spatter_2_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Spatter_2_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "e5e2e5a1f1100a6f5d828500d1f92cff083e172f85f7781f04d00346cf74471d"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Spatter_2_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 512,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_3_M.import.json b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_3_M.import.json
new file mode 100644
index 0000000000..8cfe8ece92
--- /dev/null
+++ b/unreal/Verse/Art/Import/Gore/T_Gore_Spatter_3_M.import.json
@@ -0,0 +1,35 @@
+{
+ "asset_path": "/Game/Verse/Gore/T_Gore_Spatter_3_M.T_Gore_Spatter_3_M",
+ "export": {
+ "blender": "0.0.0",
+ "file": "art/verse/.cache/unreal/gore/T_Gore_Spatter_3_M.png",
+ "format": "png",
+ "settings_id": "png-ue/1",
+ "sha256": "f2dff1c534b6c93fefc4a4040baf42fd18e7087ba3a4eec6a97305c8e62fb145"
+ },
+ "kind": "texture",
+ "license": {
+ "kind": "own"
+ },
+ "lightmap": "none",
+ "name": "T_Gore_Spatter_3_M",
+ "owner": "WP05",
+ "schema": "verse.import/1",
+ "source": {
+ "args": {},
+ "builder": "art/verse/gore/textures.py",
+ "function": "all_textures"
+ },
+ "texture": {
+ "channels": {
+ "b": "unused, 0",
+ "g": "thickness (darker and glossier where blood is thick)",
+ "r": "coverage (decal opacity)"
+ },
+ "compression": "Masks",
+ "flip_green": false,
+ "group": "World",
+ "max_size": 512,
+ "srgb": false
+ }
+}
diff --git a/unreal/Verse/Content/Verse/Gore/MF_Gore_WoundMask.uasset b/unreal/Verse/Content/Verse/Gore/MF_Gore_WoundMask.uasset
new file mode 100644
index 0000000000..96184a6bb4
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MF_Gore_WoundMask.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5faaa6dd0e96b2314dcfe6bfc89a8aca6f5bada93be7acb1c4b7218caa1a1ba4
+size 64171
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Drip.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Drip.uasset
new file mode 100644
index 0000000000..bf84115408
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Drip.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4bcb77234440eca3589ce7f67df6183d86aafc3f480522d5a257392a9f6a78f7
+size 4144
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Pool.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Pool.uasset
new file mode 100644
index 0000000000..a0dc96d0e8
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Pool.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7fc8fa8a34d0251b04b90818034a25678f06039a3673fd0773b19bac15722e4b
+size 4584
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_0.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_0.uasset
new file mode 100644
index 0000000000..b559eb0806
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_0.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:54d449cd51962986ae27d6ac3375d33920212d03ab30620b1b790486bcac3778
+size 3429
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_1.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_1.uasset
new file mode 100644
index 0000000000..5536378c94
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_1.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:58dda54a67009cebf2b3fc80bd33afbcb1fd3af7f5f19a6ff178f787f5772660
+size 3429
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_2.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_2.uasset
new file mode 100644
index 0000000000..5d342157ab
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_2.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a31144e032069842cbf09bf654862dbbc599b2a740b8f08bfe3678765b753bfb
+size 3429
diff --git a/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_3.uasset b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_3.uasset
new file mode 100644
index 0000000000..7276c13d38
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/MI_Gore_Spatter_3.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c3d1298bf580a9811f0ca14bb1a2d99001f74fe45b63f0e26439672b83fea8b6
+size 3429
diff --git a/unreal/Verse/Content/Verse/Gore/M_Gore_Decal.uasset b/unreal/Verse/Content/Verse/Gore/M_Gore_Decal.uasset
new file mode 100644
index 0000000000..1221152259
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/M_Gore_Decal.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:11b7c3e00f640e5fce16f1ed211a602f1a6701a13940d7e155f5a8f4eb9484ec
+size 12392
diff --git a/unreal/Verse/Content/Verse/Gore/M_Gore_Droplet.uasset b/unreal/Verse/Content/Verse/Gore/M_Gore_Droplet.uasset
new file mode 100644
index 0000000000..62e6602a75
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/M_Gore_Droplet.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:66301c1e2eaa1fb22018fe87c10c53a6932d886e1a5d7f00ac122c6c0bf10d32
+size 12871
diff --git a/unreal/Verse/Content/Verse/Gore/M_Gore_Flash.uasset b/unreal/Verse/Content/Verse/Gore/M_Gore_Flash.uasset
new file mode 100644
index 0000000000..a3baf1010b
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/M_Gore_Flash.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3e212f93a67fa1d4676e006885dde98825dee53bec1fe8f91744621f8316e548
+size 7907
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Drip_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Drip_M.uasset
new file mode 100644
index 0000000000..3a65ceddae
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Drip_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:94a8e31e5d2bc06612b40924c17d768efda5ba496dcfef79d696b9faa5214133
+size 22085
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Pool_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Pool_M.uasset
new file mode 100644
index 0000000000..f77b5f32a0
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Pool_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cf6a95e5c36a209ffd1243c61cb3064edb77110174f1f0c7aa51c5863bddd92d
+size 140753
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_0_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_0_M.uasset
new file mode 100644
index 0000000000..e506ad588b
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_0_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:89cd67a63f9273fc5aa7212db00e36b75b67d07fff4fc44d356fb975de89d4f9
+size 29984
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_1_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_1_M.uasset
new file mode 100644
index 0000000000..4005992330
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_1_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6613aa4215c9c272783cbb4b9a672417eabfe8ff0877aebb16fb4064a074e341
+size 28383
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_2_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_2_M.uasset
new file mode 100644
index 0000000000..a027d7ceae
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_2_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6f042e9931ababf99c75655f0799b488236d1788362e3eb4699774f1adf7103f
+size 34405
diff --git a/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_3_M.uasset b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_3_M.uasset
new file mode 100644
index 0000000000..2d037f8f79
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Gore/T_Gore_Spatter_3_M.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7334b9dfb89c5b7b227812e3db7dcc92a031408d187cfd376caf01cfdf512bea
+size 34440
diff --git a/unreal/Verse/Content/Verse/Test/WP05/M_Gore_TestBody.uasset b/unreal/Verse/Content/Verse/Test/WP05/M_Gore_TestBody.uasset
new file mode 100644
index 0000000000..2c379af810
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Test/WP05/M_Gore_TestBody.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:09c10106a4fd8904ed9eb3812c25886d951f1fc6773aa8f3493f4c4e2d1f37dc
+size 72341
diff --git a/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreActor.cpp b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreActor.cpp
new file mode 100644
index 0000000000..105bb3abbf
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreActor.cpp
@@ -0,0 +1,95 @@
+#include "Gore/VerseGoreActor.h"
+
+#include "Components/DecalComponent.h"
+#include "Components/InstancedStaticMeshComponent.h"
+#include "Engine/CollisionProfile.h"
+#include "Engine/StaticMesh.h"
+#include "Gore/VerseGoreSubsystem.h"
+#include "Materials/MaterialInterface.h"
+
+AVerseGoreActor::AVerseGoreActor()
+{
+ PrimaryActorTick.bCanEverTick = false;
+ bReplicates = false;
+ SetReplicatingMovement(false);
+ bNetLoadOnClient = false;
+ SetCanBeDamaged(false);
+ bFindCameraComponentWhenViewTarget = false;
+ SetActorEnableCollision(false);
+
+ USceneComponent* Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
+ Root->SetMobility(EComponentMobility::Movable);
+ RootComponent = Root;
+
+ Droplets = NewInstanced(TEXT("Droplets"));
+ // M_Gore_Droplet animates each instance from these floats (spawn time, velocity, life, drag, gravity).
+ Droplets->NumCustomDataFloats = UVerseGoreSubsystem::DropletCustomFloats;
+ Flashes = NewInstanced(TEXT("Flashes"));
+}
+
+UInstancedStaticMeshComponent* AVerseGoreActor::NewInstanced(FName Name)
+{
+ UInstancedStaticMeshComponent* Component = CreateDefaultSubobject<UInstancedStaticMeshComponent>(Name);
+ Component->SetupAttachment(RootComponent);
+ Component->SetMobility(EComponentMobility::Movable);
+ MakeCosmetic(Component);
+ Component->SetCanEverAffectNavigation(false);
+ Component->bDisableCollision = true;
+ Component->NumCustomDataFloats = 0;
+ return Component;
+}
+
+void AVerseGoreActor::MakeCosmetic(UPrimitiveComponent* Component)
+{
+ if (!Component)
+ {
+ return;
+ }
+ Component->SetCollisionEnabled(ECollisionEnabled::NoCollision);
+ Component->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName);
+ Component->SetCollisionResponseToAllChannels(ECR_Ignore);
+ Component->SetGenerateOverlapEvents(false);
+ Component->SetCanEverAffectNavigation(false);
+ Component->CanCharacterStepUpOn = ECB_No;
+ Component->SetCastShadow(false);
+ Component->bReceivesDecals = false;
+ Component->SetIsReplicated(false);
+}
+
+void AVerseGoreActor::SetLook(UStaticMesh* DropletMesh, UMaterialInterface* DropletMaterial, UMaterialInterface* FlashMaterial)
+{
+ if (DropletMesh)
+ {
+ Droplets->SetStaticMesh(DropletMesh);
+ Flashes->SetStaticMesh(DropletMesh);
+ }
+ if (DropletMaterial)
+ {
+ Droplets->SetMaterial(0, DropletMaterial);
+ }
+ if (FlashMaterial)
+ {
+ Flashes->SetMaterial(0, FlashMaterial);
+ }
+ // Setting a mesh rebuilds body setup; keep both cosmetic afterwards.
+ MakeCosmetic(Droplets);
+ MakeCosmetic(Flashes);
+}
+
+UDecalComponent* AVerseGoreActor::NewDecal(UMaterialInterface* Material, const FVector& Size, const FLinearColor& Color,
+ int32 SortOrder, const FTransform& Transform)
+{
+ UDecalComponent* Decal = NewObject<UDecalComponent>(this, NAME_None, RF_Transient);
+ Decal->SetupAttachment(RootComponent);
+ Decal->SetMobility(EComponentMobility::Movable);
+ Decal->SetDecalMaterial(Material);
+ Decal->DecalSize = Size;
+ Decal->DecalColor = Color;
+ Decal->SortOrder = SortOrder;
+ Decal->SetWorldTransform(Transform);
+ Decal->SetFadeScreenSize(0.002f);
+ Decal->bDestroyOwnerAfterFade = false;
+ Decal->SetIsReplicated(false);
+ Decal->RegisterComponent();
+ return Decal;
+}
diff --git a/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreConsole.cpp b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreConsole.cpp
new file mode 100644
index 0000000000..4ec22a10d2
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreConsole.cpp
@@ -0,0 +1,103 @@
+// Developer console commands of the gore module (WP05.1 synthetic event player, WP05.8 budget).
+// Not part of the Verse.QA.* set of parity.md 19; non-Shipping only.
+
+#include "CoreMinimal.h"
+
+#if !UE_BUILD_SHIPPING
+
+#include "Engine/World.h"
+#include "EngineUtils.h"
+#include "GameFramework/Pawn.h"
+#include "GameFramework/PlayerController.h"
+#include "GameFramework/PlayerState.h"
+#include "Gore/VerseGoreSubsystem.h"
+#include "HAL/IConsoleManager.h"
+#include "VerseLog.h"
+
+namespace VerseGoreConsole
+{
+ /** Places a synthetic victim: the first pawn that is not the viewer, else 3 m in front of the camera. */
+ void PickTargets(UWorld* World, FVerseGoreSyntheticParams& Params)
+ {
+ APawn* Viewer = nullptr;
+ if (APlayerController* Controller = World->GetFirstPlayerController())
+ {
+ Viewer = Controller->GetPawn();
+ FVector EyeLocation;
+ FRotator EyeRotation;
+ Controller->GetPlayerViewPoint(EyeLocation, EyeRotation);
+ Params.ShooterLocation = EyeLocation;
+ Params.VictimLocation = EyeLocation + EyeRotation.Vector() * 300.0 - FVector(0.0, 0.0, 150.0);
+ }
+ for (TActorIterator<APawn> It(World); It; ++It)
+ {
+ if (*It != Viewer)
+ {
+ Params.VictimLocation = It->GetActorLocation() - FVector(0.0, 0.0, It->GetSimpleCollisionHalfHeight());
+ if (const APlayerState* PlayerState = It->GetPlayerState())
+ {
+ Params.VictimId = PlayerState->GetPlayerId();
+ }
+ break;
+ }
+ }
+ }
+
+ FAutoConsoleCommandWithWorldAndArgs PlayCommand(
+ TEXT("Verse.Gore.Play"),
+ TEXT("Verse.Gore.Play <hits|deaths|finisher|storm> [seed] [seconds]: play a synthetic event stream into gore only (never on the hub)"),
+ FConsoleCommandWithWorldAndArgsDelegate::CreateLambda([](const TArray<FString>& Args, UWorld* World)
+ {
+ UVerseGoreSubsystem* Gore = UVerseGoreSubsystem::Get(World);
+ FVerseGoreSyntheticParams Params;
+ if (!Gore || Args.Num() < 1 || !FVerseGoreSyntheticStream::ParseKind(Args[0], Params.Kind))
+ {
+ UE_LOG(LogVerseGore, Warning, TEXT("Verse.Gore.Play <hits|deaths|finisher|storm> [seed] [seconds]"));
+ return;
+ }
+ Params.Seed = Args.Num() > 1 ? uint32(FCString::Atoi(*Args[1])) : 1u;
+ Params.DurationSeconds = Args.Num() > 2 ? FCString::Atod(*Args[2]) : (Params.Kind == EVerseGoreSyntheticKind::Storm ? 60.0 : 10.0);
+ PickTargets(World, Params);
+ Gore->PlaySynthetic(Params);
+ UE_LOG(LogVerseGore, Log, TEXT("Synthetic %s stream started (seed %u, %.1f s)"), *Args[0], Params.Seed, Params.DurationSeconds);
+ }));
+
+ FAutoConsoleCommandWithWorldAndArgs LevelCommand(
+ TEXT("Verse.Gore.Level"),
+ TEXT("Verse.Gore.Level <full|reduced>: switch the gore level live (reduced purges existing gore)"),
+ FConsoleCommandWithWorldAndArgsDelegate::CreateLambda([](const TArray<FString>& Args, UWorld* World)
+ {
+ if (UVerseGoreSubsystem* Gore = UVerseGoreSubsystem::Get(World); Gore && Args.Num() == 1)
+ {
+ Gore->SetGoreLevel(Args[0].Equals(TEXT("reduced"), ESearchCase::IgnoreCase) ? EVerseGoreLevel::Reduced : EVerseGoreLevel::Full);
+ }
+ }));
+
+ FAutoConsoleCommandWithWorldAndArgs StatsCommand(
+ TEXT("Verse.Gore.Stats"),
+ TEXT("Verse.Gore.Stats [file]: log the gore budget JSON, or write it to a file"),
+ FConsoleCommandWithWorldAndArgsDelegate::CreateLambda([](const TArray<FString>& Args, UWorld* World)
+ {
+ if (const UVerseGoreSubsystem* Gore = UVerseGoreSubsystem::Get(World))
+ {
+ if (Args.Num() > 0)
+ {
+ Gore->WriteBudgetJson(Args[0]);
+ }
+ UE_LOG(LogVerseGore, Display, TEXT("%s"), *Gore->BudgetJson());
+ }
+ }));
+
+ FAutoConsoleCommandWithWorldAndArgs PurgeCommand(
+ TEXT("Verse.Gore.Purge"),
+ TEXT("Verse.Gore.Purge: remove all gore"),
+ FConsoleCommandWithWorldAndArgsDelegate::CreateLambda([](const TArray<FString>&, UWorld* World)
+ {
+ if (UVerseGoreSubsystem* Gore = UVerseGoreSubsystem::Get(World))
+ {
+ Gore->Purge();
+ }
+ }));
+}
+
+#endif // !UE_BUILD_SHIPPING
diff --git a/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSubsystem.cpp b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSubsystem.cpp
new file mode 100644
index 0000000000..5b5b09c0cf
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSubsystem.cpp
@@ -0,0 +1,1267 @@
+#include "Gore/VerseGoreSubsystem.h"
+
+#include "AnimationRuntime.h"
+#include "Camera/PlayerCameraManager.h"
+#include "Components/DecalComponent.h"
+#include "Components/InstancedStaticMeshComponent.h"
+#include "Components/SkeletalMeshComponent.h"
+#include "Engine/SkinnedAsset.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/World.h"
+#include "EngineUtils.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/Pawn.h"
+#include "GameFramework/PlayerController.h"
+#include "GameFramework/PlayerState.h"
+#include "Gore/VerseGoreActor.h"
+#include "HAL/PlatformTime.h"
+#include "Materials/MaterialInstanceDynamic.h"
+#include "Materials/MaterialInterface.h"
+#include "Misc/App.h"
+#include "Misc/ConfigCacheIni.h"
+#include "Misc/FileHelper.h"
+#include "Misc/ScopeExit.h"
+#include "Stats/Stats.h"
+#include "VerseLog.h"
+#include "VerseRng.h"
+
+namespace VerseGorePrivate
+{
+ /** Gore's own assets (work-packages.md WP05 owns /Game/Verse/Gore/**), built by art/verse/gore/. */
+ const TCHAR* SpatterMaterialPaths[] = {
+ TEXT("/Game/Verse/Gore/MI_Gore_Spatter_0.MI_Gore_Spatter_0"),
+ TEXT("/Game/Verse/Gore/MI_Gore_Spatter_1.MI_Gore_Spatter_1"),
+ TEXT("/Game/Verse/Gore/MI_Gore_Spatter_2.MI_Gore_Spatter_2"),
+ TEXT("/Game/Verse/Gore/MI_Gore_Spatter_3.MI_Gore_Spatter_3"),
+ };
+ const TCHAR* DripMaterialPath = TEXT("/Game/Verse/Gore/MI_Gore_Drip.MI_Gore_Drip");
+ const TCHAR* PoolMaterialPath = TEXT("/Game/Verse/Gore/MI_Gore_Pool.MI_Gore_Pool");
+ const TCHAR* DropletMaterialPath = TEXT("/Game/Verse/Gore/M_Gore_Droplet.M_Gore_Droplet");
+ const TCHAR* FlashMaterialPath = TEXT("/Game/Verse/Gore/M_Gore_Flash.M_Gore_Flash");
+ /** Engine primitive used as the droplet and flash shape (referenced, never committed). */
+ const TCHAR* DropletMeshPath = TEXT("/Engine/BasicShapes/Sphere.Sphere");
+ /** The settings section UVerseSettings (module Verse) saves to; read as text, no include. */
+ const TCHAR* SettingsSection = TEXT("/Script/Verse.VerseSettings");
+
+ /** Pools for one victim closer together than this are one pool (death after finisher kill). */
+ constexpr double PoolDedupeSeconds = 3.0;
+
+ double CyclesToMs(uint64 Cycles)
+ {
+ return FPlatformTime::ToMilliseconds64(Cycles);
+ }
+
+ template <typename T>
+ T* LoadOptional(const TCHAR* Path)
+ {
+ return Cast<T>(StaticLoadObject(T::StaticClass(), nullptr, Path, nullptr, LOAD_NoWarn | LOAD_Quiet));
+ }
+
+ float SmoothGrowth(float Alpha)
+ {
+ const float A = FMath::Clamp(Alpha, 0.f, 1.f);
+ return 1.f - FMath::Square(1.f - A); // ease out: fast spread, slow stop
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Tuning tables
+
+FName VerseGoreParams::WoundSlot(int32 Index)
+{
+ static TArray<FName> Names = []
+ {
+ TArray<FName> Result;
+ for (int32 I = 0; I < 16; ++I)
+ {
+ Result.Add(FName(*FString::Printf(TEXT("Verse_Wound_%02d"), I)));
+ }
+ return Result;
+ }();
+ return Names.IsValidIndex(Index) ? Names[Index] : NAME_None;
+}
+
+int32 FVerseGoreTuning::BaseDroplets(EVerseHitZone Zone)
+{
+ switch (Zone)
+ {
+ case EVerseHitZone::Head: return 30;
+ case EVerseHitZone::Neck: return 26;
+ case EVerseHitZone::UpperTorso: return 20;
+ case EVerseHitZone::LowerTorso: return 18;
+ case EVerseHitZone::Arm: return 12;
+ case EVerseHitZone::Leg: return 12;
+ default: return 10;
+ }
+}
+
+int32 FVerseGoreTuning::SpatterTraces(EVerseHitZone Zone)
+{
+ switch (Zone)
+ {
+ case EVerseHitZone::Head: return 3;
+ case EVerseHitZone::Neck: return 3;
+ case EVerseHitZone::UpperTorso: return 2;
+ case EVerseHitZone::LowerTorso: return 2;
+ default: return 1;
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Lifetime
+
+UVerseGoreSubsystem* UVerseGoreSubsystem::Get(const UObject* WorldContextObject)
+{
+ if (!WorldContextObject || !GEngine)
+ {
+ return nullptr;
+ }
+ const UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::ReturnNull);
+ return World ? World->GetSubsystem<UVerseGoreSubsystem>() : nullptr;
+}
+
+bool UVerseGoreSubsystem::ProcessCanShowGore()
+{
+ return !IsRunningDedicatedServer() && FApp::CanEverRender();
+}
+
+bool UVerseGoreSubsystem::ShouldCreateSubsystem(UObject* Outer) const
+{
+ if (IsRunningDedicatedServer())
+ {
+ return false; // a dedicated server never shows gore (combat-state.md 8)
+ }
+ const UWorld* World = Cast<UWorld>(Outer);
+ if (!World || !(World->WorldType == EWorldType::Game || World->WorldType == EWorldType::PIE))
+ {
+ return false;
+ }
+ return Super::ShouldCreateSubsystem(Outer);
+}
+
+void UVerseGoreSubsystem::Initialize(FSubsystemCollectionBase& Collection)
+{
+ Collection.InitializeDependency<UVerseEventHub>();
+ Super::Initialize(Collection);
+ ReloadLevelFromSettings();
+ UpdateActive();
+}
+
+void UVerseGoreSubsystem::Deinitialize()
+{
+ // The world is tearing down and takes the gore actor and its components with it; only
+ // drop our references here.
+ UnbindHub();
+ SpatterRing.Reset();
+ Pools.Reset();
+ DropletsSim.Reset();
+ FlashesSim.Reset();
+ WoundSets.Reset();
+ PendingWoundClears.Reset();
+ GoreActor.Reset();
+ SyntheticEvents.Reset();
+ SyntheticCursor = 0;
+ CutToBlack.bActive = false;
+ bActive = false;
+ Super::Deinitialize();
+}
+
+void UVerseGoreSubsystem::OnWorldBeginPlay(UWorld& InWorld)
+{
+ Super::OnWorldBeginPlay(InWorld);
+ UpdateActive();
+}
+
+TStatId UVerseGoreSubsystem::GetStatId() const
+{
+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseGoreSubsystem, STATGROUP_Tickables);
+}
+
+void UVerseGoreSubsystem::SetForceActive(bool bForce)
+{
+ bForceActive = bForce;
+ UpdateActive();
+}
+
+void UVerseGoreSubsystem::UpdateActive()
+{
+ const UWorld* World = GetWorld();
+ const bool bServerOnly = World && World->GetNetMode() == NM_DedicatedServer;
+ const bool bWant = bForceActive || (ProcessCanShowGore() && !bServerOnly);
+ if (bWant == bActive && bWant == bBound)
+ {
+ return;
+ }
+ bActive = bWant;
+ if (bActive)
+ {
+ BindHub();
+ }
+ else
+ {
+ UnbindHub();
+ Purge();
+ }
+}
+
+void UVerseGoreSubsystem::BindHub()
+{
+ if (bBound)
+ {
+ return;
+ }
+ UVerseEventHub* EventHub = UVerseEventHub::Get(this);
+ if (!EventHub)
+ {
+ UE_LOG(LogVerseGore, Warning, TEXT("No event hub in this world; gore listens to nothing"));
+ return;
+ }
+ Hub = EventHub;
+ HitHandle = EventHub->OnHit.AddUObject(this, &UVerseGoreSubsystem::HandleHit);
+ DeathHandle = EventHub->OnDeath.AddUObject(this, &UVerseGoreSubsystem::HandleDeath);
+ FinisherHandle = EventHub->OnFinisher.AddUObject(this, &UVerseGoreSubsystem::HandleFinisher);
+ bBound = true;
+}
+
+void UVerseGoreSubsystem::UnbindHub()
+{
+ if (UVerseEventHub* EventHub = Hub.Get())
+ {
+ EventHub->OnHit.Remove(HitHandle);
+ EventHub->OnDeath.Remove(DeathHandle);
+ EventHub->OnFinisher.Remove(FinisherHandle);
+ }
+ HitHandle.Reset();
+ DeathHandle.Reset();
+ FinisherHandle.Reset();
+ Hub.Reset();
+ bBound = false;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Level
+
+void UVerseGoreSubsystem::ReloadLevelFromSettings()
+{
+ FString Value;
+ EVerseGoreLevel FromSettings = EVerseGoreLevel::Full;
+ if (GConfig && GConfig->GetString(VerseGorePrivate::SettingsSection, TEXT("GoreLevel"), Value, GGameUserSettingsIni))
+ {
+ FromSettings = Value.TrimStartAndEnd().Equals(TEXT("Reduced"), ESearchCase::IgnoreCase) ? EVerseGoreLevel::Reduced : EVerseGoreLevel::Full;
+ }
+ SetGoreLevel(FromSettings);
+}
+
+void UVerseGoreSubsystem::SetGoreLevel(EVerseGoreLevel NewLevel)
+{
+ if (NewLevel == Level)
+ {
+ return;
+ }
+ Level = NewLevel;
+ UE_LOG(LogVerseGore, Log, TEXT("Gore level %s"), Level == EVerseGoreLevel::Full ? TEXT("Full") : TEXT("Reduced"));
+ if (Level == EVerseGoreLevel::Reduced)
+ {
+ Purge(); // live switch purges existing gore (WP05.7)
+ }
+ else if (CutToBlack.bActive)
+ {
+ EndCutToBlack();
+ }
+}
+
+void UVerseGoreSubsystem::Purge()
+{
+ for (UDecalComponent* Decal : SpatterRing)
+ {
+ if (IsValid(Decal))
+ {
+ Decal->DestroyComponent();
+ }
+ }
+ SpatterRing.Reset();
+ SpatterNext = 0;
+ for (FPool& Pool : Pools)
+ {
+ if (UDecalComponent* Decal = Pool.Decal.Get())
+ {
+ Decal->DestroyComponent();
+ }
+ }
+ Pools.Reset();
+ DropletsSim.Reset();
+ DropletNext = 0;
+ FlashesSim.Reset();
+ if (AVerseGoreActor* Actor = GoreActor.Get())
+ {
+ Actor->Droplets->ClearInstances();
+ Actor->Flashes->ClearInstances();
+ }
+ for (FWoundSet& Set : WoundSets)
+ {
+ Set.Wounds.Reset();
+ Set.Next = 0;
+ ApplyWounds(Set);
+ }
+ WoundSets.Reset();
+ if (CutToBlack.bActive)
+ {
+ EndCutToBlack();
+ }
+ ++Budget.Purges;
+ RefreshBudgetLive();
+}
+
+// ---------------------------------------------------------------------------------------------
+// Assets and the gore actor
+
+void UVerseGoreSubsystem::LoadLook()
+{
+ if (bLookLoaded)
+ {
+ return;
+ }
+ bLookLoaded = true;
+ using namespace VerseGorePrivate;
+ for (const TCHAR* Path : SpatterMaterialPaths)
+ {
+ if (UMaterialInterface* Material = LoadOptional<UMaterialInterface>(Path))
+ {
+ SpatterMaterials.Add(Material);
+ }
+ }
+ DripMaterial = LoadOptional<UMaterialInterface>(DripMaterialPath);
+ PoolMaterial = LoadOptional<UMaterialInterface>(PoolMaterialPath);
+ if (SpatterMaterials.Num() == 0 || !PoolMaterial)
+ {
+ UE_LOG(LogVerseGore, Warning, TEXT("Gore materials missing under /Game/Verse/Gore; gore is counted but not drawn"));
+ }
+ if (AVerseGoreActor* Actor = GoreActor.Get())
+ {
+ Actor->SetLook(LoadOptional<UStaticMesh>(DropletMeshPath), LoadOptional<UMaterialInterface>(DropletMaterialPath),
+ LoadOptional<UMaterialInterface>(FlashMaterialPath));
+ }
+}
+
+TArray<FString> UVerseGoreSubsystem::RuntimeAssetPaths()
+{
+ using namespace VerseGorePrivate;
+ TArray<FString> Paths;
+ for (const TCHAR* Path : SpatterMaterialPaths)
+ {
+ Paths.Add(Path);
+ }
+ Paths.Append({DripMaterialPath, PoolMaterialPath, DropletMaterialPath, FlashMaterialPath, DropletMeshPath});
+ return Paths;
+}
+
+AVerseGoreActor* UVerseGoreSubsystem::EnsureGoreActor()
+{
+ if (AVerseGoreActor* Existing = GoreActor.Get())
+ {
+ return Existing;
+ }
+ UWorld* World = GetWorld();
+ if (!World)
+ {
+ return nullptr;
+ }
+ FActorSpawnParameters Params;
+ Params.Name = MakeUniqueObjectName(World->PersistentLevel, AVerseGoreActor::StaticClass(), TEXT("VerseGore"));
+ Params.ObjectFlags |= RF_Transient;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AVerseGoreActor* Actor = World->SpawnActor<AVerseGoreActor>(AVerseGoreActor::StaticClass(), FTransform::Identity, Params);
+ GoreActor = Actor;
+ bLookLoaded = false;
+ LoadLook();
+ return Actor;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Victims
+
+void UVerseGoreSubsystem::SetVictimResolver(FVerseGoreVictimResolver Resolver)
+{
+ VictimResolver = MoveTemp(Resolver);
+}
+
+USkeletalMeshComponent* UVerseGoreSubsystem::ResolveVictim(int32 PlayerId) const
+{
+ return VictimResolver ? VictimResolver(PlayerId) : DefaultResolve(PlayerId);
+}
+
+USkeletalMeshComponent* UVerseGoreSubsystem::DefaultResolve(int32 PlayerId) const
+{
+ UWorld* World = GetWorld();
+ if (!World)
+ {
+ return nullptr;
+ }
+ for (TActorIterator<APawn> It(World); It; ++It)
+ {
+ const APlayerState* PlayerState = It->GetPlayerState();
+ if (PlayerState && PlayerState->GetPlayerId() == PlayerId)
+ {
+ return It->FindComponentByClass<USkeletalMeshComponent>();
+ }
+ }
+ return nullptr;
+}
+
+FVector UVerseGoreSubsystem::BodyPoint(USkeletalMeshComponent* Mesh, FName Bone, const FVector& Fallback) const
+{
+ if (Mesh && !Bone.IsNone() && Mesh->DoesSocketExist(Bone))
+ {
+ return Mesh->GetSocketLocation(Bone);
+ }
+ return Mesh ? Mesh->GetComponentLocation() + FVector(0.0, 0.0, 40.0) : Fallback;
+}
+
+bool UVerseGoreSubsystem::BoneLocalToRefPose(const USkeletalMeshComponent* Mesh, FName Bone, const FVector& BoneLocal, FVector& OutRefPose)
+{
+ const USkinnedAsset* Asset = Mesh ? Mesh->GetSkinnedAsset() : nullptr;
+ if (!Asset)
+ {
+ return false;
+ }
+ const FReferenceSkeleton& RefSkeleton = Asset->GetRefSkeleton();
+ const int32 BoneIndex = RefSkeleton.FindBoneIndex(Bone);
+ if (BoneIndex == INDEX_NONE)
+ {
+ return false;
+ }
+ const FTransform BoneRef = FAnimationRuntime::GetComponentSpaceTransformRefPose(RefSkeleton, BoneIndex);
+ OutRefPose = BoneRef.TransformPosition(BoneLocal);
+ return true;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Events
+
+void UVerseGoreSubsystem::HandleHit(const FVerseHitEvent& Event)
+{
+ if (!bActive)
+ {
+ return;
+ }
+ const uint64 Start = FPlatformTime::Cycles64();
+ ++Budget.HitsHandled;
+
+ const FVector Origin = Event.ImpactWorld;
+ const FVector Direction = FVector(Event.Direction).GetSafeNormal(UE_SMALL_NUMBER, FVector::ForwardVector);
+
+ if (Level == EVerseGoreLevel::Reduced || Event.bBlockedBySpawnProtection || Event.Damage <= 0.f)
+ {
+ SpawnFlash(Origin);
+ }
+ else
+ {
+ EnsureGoreActor();
+ USkeletalMeshComponent* Mesh = ResolveVictim(Event.VictimId);
+ const uint32 Seed = FVerseRng::Hash(uint32(Event.VictimId), uint32(Event.ShotCounter), uint32(Event.InstigatorId));
+ const float Scale = FMath::Clamp(Event.Damage / 30.f, 0.5f, 2.f);
+ SpawnBurst(Origin, Direction, FMath::RoundToInt32(FVerseGoreTuning::BaseDroplets(Event.Zone) * Scale), Seed);
+ const int32 Traces = FVerseGoreTuning::SpatterTraces(Event.Zone) + (Event.bKillingBlow ? 1 : 0);
+ SpawnSpatter(Origin, Direction, Traces, Seed, Mesh ? Mesh->GetOwner() : nullptr);
+ if (Mesh && !Event.Bone.IsNone())
+ {
+ AddWound(Mesh, Event.Bone, Event.ImpactBoneLocal, Event.Damage);
+ }
+ }
+
+ RefreshBudgetLive();
+ AccountEvent(VerseGorePrivate::CyclesToMs(FPlatformTime::Cycles64() - Start), true);
+}
+
+void UVerseGoreSubsystem::HandleDeath(const FVerseDeathEvent& Event)
+{
+ if (!bActive)
+ {
+ return;
+ }
+ const uint64 Start = FPlatformTime::Cycles64();
+ ON_SCOPE_EXIT { AccountEvent(VerseGorePrivate::CyclesToMs(FPlatformTime::Cycles64() - Start), false); };
+ ++Budget.DeathsHandled;
+ if (Level == EVerseGoreLevel::Reduced)
+ {
+ return;
+ }
+ USkeletalMeshComponent* Mesh = ResolveVictim(Event.VictimId);
+ if (!Mesh)
+ {
+ return; // nowhere to put a pool
+ }
+ StartPool(Event.VictimId, BodyPoint(Mesh, TEXT("Hips"), Mesh->GetComponentLocation()), Mesh->GetOwner());
+
+ // The body comes back clean after respawn.
+ const float Delay = FMath::Max(0.f, Event.RespawnAt - Event.ServerTime);
+ if (Delay > 0.f)
+ {
+ TWeakObjectPtr<USkeletalMeshComponent> WeakMesh = Mesh;
+ const double ClearAt = GoreTime + Delay;
+ PendingWoundClears.Add({WeakMesh, ClearAt});
+ }
+ RefreshBudgetLive();
+}
+
+void UVerseGoreSubsystem::HandleFinisher(const FVerseFinisherEvent& Event)
+{
+ if (!bActive)
+ {
+ return;
+ }
+ const uint64 Start = FPlatformTime::Cycles64();
+ ON_SCOPE_EXIT { AccountEvent(VerseGorePrivate::CyclesToMs(FPlatformTime::Cycles64() - Start), false); };
+ ++Budget.FinisherPhasesHandled;
+
+ if (Level == EVerseGoreLevel::Reduced)
+ {
+ switch (Event.Phase)
+ {
+ case EVerseFinisherPhase::Takedown:
+ StartCutToBlack(Event);
+ break;
+ case EVerseFinisherPhase::Recover:
+ case EVerseFinisherPhase::Aborted:
+ EndCutToBlack();
+ break;
+ default:
+ break;
+ }
+ return;
+ }
+
+ USkeletalMeshComponent* Mesh = ResolveVictim(Event.VictimId);
+ const FVector Fallback = Event.WarpTarget.GetLocation() + Event.WarpTarget.GetRotation().GetForwardVector() * 60.0 + FVector(0.0, 0.0, 30.0);
+ const FVector Neck = BodyPoint(Mesh, TEXT("Neck"), Fallback);
+ const FVector Across = Event.WarpTarget.GetRotation().GetRightVector();
+ const uint32 Seed = FVerseRng::Hash(uint32(Event.AttackerId), uint32(Event.VictimId), uint32(Event.Phase) + 0x51u);
+
+ switch (Event.Phase)
+ {
+ case EVerseFinisherPhase::Takedown:
+ EnsureGoreActor();
+ SpawnBurst(Neck, (Across + FVector(0.0, 0.0, 0.4)).GetSafeNormal(), 10, Seed);
+ break;
+ case EVerseFinisherPhase::Kill:
+ EnsureGoreActor();
+ SpawnBurst(Neck, (Across + FVector(0.0, 0.0, 0.2)).GetSafeNormal(), 64, Seed);
+ SpawnSpatter(Neck, (Across + FVector(0.0, 0.0, -0.8)).GetSafeNormal(), 4, Seed, Mesh ? Mesh->GetOwner() : nullptr);
+ if (Mesh)
+ {
+ AddWound(Mesh, TEXT("Neck"), FVector(0.0, 5.0, 0.0), 80.f);
+ StartPool(Event.VictimId, Neck, Mesh->GetOwner());
+ }
+ break;
+ default:
+ break;
+ }
+ RefreshBudgetLive();
+}
+
+// ---------------------------------------------------------------------------------------------
+// Bursts, spatter, flashes
+
+void UVerseGoreSubsystem::SpawnBurst(const FVector& Origin, const FVector& Direction, int32 Count, uint32 Seed)
+{
+ const int32 Capacity = Tuning.MaxDroplets;
+ if (Count <= 0 || Capacity <= 0)
+ {
+ return;
+ }
+ // The droplet material moves each instance from its custom data (spawn time, velocity, life,
+ // drag, gravity), so a droplet costs one slot write here and nothing per frame afterwards.
+ AVerseGoreActor* Actor = GoreActor.Get();
+ UInstancedStaticMeshComponent* Ism = Actor ? Actor->Droplets.Get() : nullptr;
+ const UWorld* World = GetWorld();
+ const float WorldTime = World ? float(World->GetTimeSeconds()) : 0.f;
+ FVerseRng Rng(Seed, 1, EVerseRngSalt::None);
+ const int32 BackSpray = FMath::RoundToInt32(Count * Tuning.DropletBackSprayFraction);
+ float Custom[DropletCustomFloats];
+ for (int32 Index = 0; Index < Count; ++Index)
+ {
+ const bool bBack = Index < BackSpray;
+ const FVector Axis = bBack ? -Direction : Direction;
+ const FVector Dir = Rng.ConeDirection(Axis, bBack ? 40.0 : 22.0);
+ FDroplet Droplet;
+ Droplet.Origin = Origin;
+ Droplet.Velocity = Dir * Tuning.DropletSpeedCm * Rng.Range(bBack ? 0.25 : 0.5, bBack ? 0.6 : 1.15);
+ Droplet.Life = Tuning.DropletLifeSeconds * float(Rng.Range(0.6, 1.2));
+ Droplet.SpawnTime = GoreTime;
+ const float Size = Tuning.DropletSizeCm * float(Rng.Range(0.5, 1.4));
+
+ int32 Slot = INDEX_NONE;
+ if (DropletsSim.Num() < Capacity)
+ {
+ Slot = DropletsSim.Add(Droplet);
+ }
+ else
+ {
+ Slot = DropletNext; // oldest first
+ DropletsSim[Slot] = Droplet;
+ DropletNext = (DropletNext + 1) % Capacity;
+ }
+ DropletsLastExpiry = FMath::Max(DropletsLastExpiry, GoreTime + Droplet.Life);
+ ++Budget.DropletsSpawned;
+ if (!Ism)
+ {
+ continue;
+ }
+ // The primitive sphere is 100 cm across.
+ const FTransform Transform(FQuat::Identity, Origin, FVector(Size / 50.f));
+ if (Slot < Ism->GetInstanceCount())
+ {
+ Ism->UpdateInstanceTransform(Slot, Transform, true, false, true);
+ }
+ else
+ {
+ Ism->AddInstance(Transform, true);
+ }
+ Custom[0] = WorldTime;
+ Custom[1] = float(Droplet.Velocity.X);
+ Custom[2] = float(Droplet.Velocity.Y);
+ Custom[3] = float(Droplet.Velocity.Z);
+ Custom[4] = Droplet.Life;
+ Custom[5] = Tuning.DropletDrag;
+ Custom[6] = Tuning.GravityCm;
+ Ism->SetCustomData(Slot, TArrayView<const float>(Custom, DropletCustomFloats), false);
+ }
+}
+
+FVector UVerseGoreSubsystem::DropletOffset(const FVector& Velocity, float Age, float Drag, float Gravity)
+{
+ // dv/dt = -g z - k v, so p(t) = (V + g/k z) (1 - exp(-k t)) / k - (g/k) t z.
+ const double T = FMath::Max(0.f, Age);
+ const double K = FMath::Max(0.01f, Drag);
+ const FVector Terminal(0.0, 0.0, Gravity / K);
+ return (Velocity + Terminal) * ((1.0 - FMath::Exp(-K * T)) / K) - Terminal * T;
+}
+
+TArray<FVector> UVerseGoreSubsystem::GetDropletPositions() const
+{
+ TArray<FVector> Result;
+ for (const FDroplet& D : DropletsSim)
+ {
+ const float Age = float(GoreTime - D.SpawnTime);
+ if (Age < D.Life)
+ {
+ Result.Add(D.Origin + DropletOffset(D.Velocity, Age, Tuning.DropletDrag, Tuning.GravityCm));
+ }
+ }
+ return Result;
+}
+
+int32 UVerseGoreSubsystem::LiveDroplets() const
+{
+ int32 Live = 0;
+ for (const FDroplet& D : DropletsSim)
+ {
+ Live += GoreTime - D.SpawnTime < D.Life ? 1 : 0;
+ }
+ return Live;
+}
+
+void UVerseGoreSubsystem::SpawnSpatter(const FVector& Origin, const FVector& Direction, int32 Traces, uint32 Seed, const AActor* Ignore)
+{
+ UWorld* World = GetWorld();
+ if (!World)
+ {
+ return;
+ }
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseGoreSpatter), false);
+ if (Ignore)
+ {
+ Params.AddIgnoredActor(Ignore);
+ }
+ if (const AVerseGoreActor* Actor = GoreActor.Get())
+ {
+ Params.AddIgnoredActor(Actor);
+ }
+ const float Range = FMath::Max(1.f, Tuning.SpatterRangeCm);
+ for (int32 Index = 0; Index < Traces; ++Index)
+ {
+ FVerseRng Rng(Seed, 100 + Index, EVerseRngSalt::None);
+ const FVector Dir = (Rng.ConeDirection(Direction, Tuning.SpatterConeDeg) + FVector(0.0, 0.0, -0.12)).GetSafeNormal();
+ const FVector From = Origin + Dir * 4.0;
+ FHitResult Hit;
+ if (World->LineTraceSingleByChannel(Hit, From, Origin + Dir * Range, ECC_Visibility, Params))
+ {
+ const float Alpha = FMath::Clamp(float(Hit.Distance) / Range, 0.f, 1.f);
+ const float Size = FMath::Lerp(Tuning.SpatterSizeNearCm, Tuning.SpatterSizeFarCm, Alpha) * float(Rng.Range(0.8, 1.2));
+ PlaceSpatterDecal(Hit.ImpactPoint, Hit.ImpactNormal, Size, Rng.NextU32());
+ }
+ }
+
+ // One drip onto the floor below the wound.
+ FHitResult Floor;
+ if (World->LineTraceSingleByChannel(Floor, Origin, Origin + FVector(0.0, 0.0, -Tuning.DripTraceCm) + Direction * 25.0, ECC_Visibility, Params))
+ {
+ PlaceSpatterDecal(Floor.ImpactPoint, Floor.ImpactNormal, -Tuning.DripSizeCm, Seed ^ 0xD219u);
+ }
+}
+
+bool UVerseGoreSubsystem::PlaceSpatterDecal(const FVector& Location, const FVector& Normal, float Size, uint32 Seed)
+{
+ AVerseGoreActor* Actor = EnsureGoreActor();
+ if (!Actor || Tuning.MaxSpatterDecals <= 0)
+ {
+ return false;
+ }
+ // A negative size marks a floor drip (its own material).
+ const bool bDrip = Size < 0.f;
+ const float Extent = FMath::Abs(Size);
+ FVerseRng Rng(Seed, 7, EVerseRngSalt::None);
+ UMaterialInterface* Material = bDrip && DripMaterial ? DripMaterial.Get()
+ : (SpatterMaterials.Num() > 0 ? SpatterMaterials[Rng.RangeInt(0, SpatterMaterials.Num() - 1)].Get() : nullptr);
+
+ // Size and orientation travel in one transform (decal size stays 1 on the projected axes), so a
+ // recycled decal costs one transform update; colour and sort order are set once at creation.
+ FRotator Rotation = (-Normal).Rotation();
+ Rotation.Roll = float(Rng.Range(0.0, 360.0));
+ const FTransform Transform(Rotation, Location, FVector(1.0, Extent, Extent));
+ UDecalComponent* Decal = nullptr;
+ if (SpatterRing.Num() < Tuning.MaxSpatterDecals)
+ {
+ // Decal colour: R = opacity, G = darkening (read by M_Gore_Decal).
+ const FLinearColor Color(float(Rng.Range(0.85, 1.0)), float(Rng.Range(0.7, 1.0)), 1.f, 1.f);
+ Decal = Actor->NewDecal(Material, FVector(Tuning.DecalDepthCm, 1.0, 1.0), Color, 1, Transform);
+ SpatterRing.Add(Decal);
+ }
+ else
+ {
+ SpatterNext %= SpatterRing.Num();
+ Decal = SpatterRing[SpatterNext];
+ SpatterNext = (SpatterNext + 1) % SpatterRing.Num();
+ ++Budget.DecalsRecycled;
+ if (!IsValid(Decal))
+ {
+ return false;
+ }
+ if (Decal->GetDecalMaterial() != Material)
+ {
+ Decal->SetDecalMaterial(Material);
+ }
+ Decal->SetWorldTransform(Transform);
+ }
+ ++Budget.DecalsSpawned;
+ return true;
+}
+
+void UVerseGoreSubsystem::SpawnFlash(const FVector& Location)
+{
+ if (Tuning.MaxFlashes <= 0)
+ {
+ return;
+ }
+ EnsureGoreActor();
+ if (FlashesSim.Num() >= Tuning.MaxFlashes)
+ {
+ FlashesSim.RemoveAt(0, 1, EAllowShrinking::No);
+ }
+ FlashesSim.Add({Location, 0.f});
+ ++Budget.FlashesSpawned;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Wounds
+
+void UVerseGoreSubsystem::AddWound(USkeletalMeshComponent* Mesh, FName Bone, const FVector& BoneLocal, float Damage)
+{
+ FVector RefPose;
+ if (!BoneLocalToRefPose(Mesh, Bone, BoneLocal, RefPose) || Tuning.MaxWoundsPerCharacter <= 0)
+ {
+ return;
+ }
+ FWoundSet* Set = WoundSets.FindByPredicate([Mesh](const FWoundSet& S) { return S.Mesh.Get() == Mesh; });
+ if (!Set)
+ {
+ Set = &WoundSets.AddDefaulted_GetRef();
+ Set->Mesh = Mesh;
+ }
+ const float Alpha = FMath::Clamp((Damage - 10.f) / 50.f, 0.f, 1.f);
+ const FVector4f Wound(FVector3f(RefPose), FMath::Lerp(Tuning.WoundRadiusMinCm, Tuning.WoundRadiusMaxCm, Alpha));
+ const int32 Max = FMath::Min(Tuning.MaxWoundsPerCharacter, 16);
+ int32 Written = INDEX_NONE;
+ if (Set->Wounds.Num() < Max)
+ {
+ Written = Set->Wounds.Add(Wound);
+ }
+ else
+ {
+ Written = Set->Next;
+ Set->Wounds[Written] = Wound; // oldest first
+ Set->Next = (Set->Next + 1) % Max;
+ ++Budget.WoundsRecycled;
+ }
+ ApplyWounds(*Set, Set->bMaterialsResolved ? Written : INDEX_NONE);
+}
+
+void UVerseGoreSubsystem::ApplyWounds(FWoundSet& Set, int32 Changed)
+{
+ USkeletalMeshComponent* Mesh = Set.Mesh.Get();
+ if (!Mesh)
+ {
+ return;
+ }
+ if (!Set.bMaterialsResolved)
+ {
+ Set.bMaterialsResolved = true;
+ for (int32 Slot = 0; Slot < Mesh->GetNumMaterials(); ++Slot)
+ {
+ UMaterialInterface* Material = Mesh->GetMaterial(Slot);
+ float Unused = 0.f;
+ if (Material && Material->GetScalarParameterValue(FHashedMaterialParameterInfo(VerseGoreParams::WoundCount), Unused))
+ {
+ Set.Materials.Add(Mesh->CreateDynamicMaterialInstance(Slot, Material));
+ }
+ }
+ }
+ // Slot i holds ring entry i (the mask does not care about order), so a new wound writes one
+ // slot plus the count; a full rewrite only happens when the set is cleared.
+ const int32 Count = Set.Wounds.Num();
+ for (const TWeakObjectPtr<UMaterialInstanceDynamic>& Weak : Set.Materials)
+ {
+ UMaterialInstanceDynamic* Mid = Weak.Get();
+ if (!Mid)
+ {
+ continue;
+ }
+ Mid->SetScalarParameterValue(VerseGoreParams::WoundCount, float(Count));
+ if (!Set.Wounds.IsValidIndex(Changed))
+ {
+ for (int32 Index = 0; Index < 16; ++Index)
+ {
+ const FVector4f W = Set.Wounds.IsValidIndex(Index) ? Set.Wounds[Index] : FVector4f(0.f, 0.f, 0.f, 0.f);
+ Mid->SetVectorParameterValue(VerseGoreParams::WoundSlot(Index), FLinearColor(W.X, W.Y, W.Z, W.W));
+ }
+ }
+ else
+ {
+ const FVector4f& W = Set.Wounds[Changed];
+ Mid->SetVectorParameterValue(VerseGoreParams::WoundSlot(Changed), FLinearColor(W.X, W.Y, W.Z, W.W));
+ }
+ }
+}
+
+TArray<FVector4f> UVerseGoreSubsystem::GetWounds(const USkeletalMeshComponent* Mesh) const
+{
+ TArray<FVector4f> Result;
+ const FWoundSet* Set = WoundSets.FindByPredicate([Mesh](const FWoundSet& S) { return S.Mesh.Get() == Mesh; });
+ if (!Set)
+ {
+ return Result;
+ }
+ const int32 Num = Set->Wounds.Num();
+ const bool bFull = Num >= FMath::Min(Tuning.MaxWoundsPerCharacter, 16);
+ for (int32 Index = 0; Index < Num; ++Index)
+ {
+ Result.Add(Set->Wounds[bFull ? (Set->Next + Index) % Num : Index]);
+ }
+ return Result;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Pools
+
+void UVerseGoreSubsystem::StartPool(int32 VictimId, const FVector& BodyLocation, const AActor* Ignore)
+{
+ UWorld* World = GetWorld();
+ AVerseGoreActor* Actor = EnsureGoreActor();
+ if (!World || !Actor || Tuning.MaxPools <= 0)
+ {
+ return;
+ }
+ for (const FPool& Pool : Pools)
+ {
+ if (Pool.VictimId == VictimId && GoreTime - Pool.StartTime < VerseGorePrivate::PoolDedupeSeconds)
+ {
+ return;
+ }
+ }
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseGorePool), false);
+ if (Ignore)
+ {
+ Params.AddIgnoredActor(Ignore);
+ }
+ Params.AddIgnoredActor(Actor);
+ FHitResult Floor;
+ if (!World->LineTraceSingleByChannel(Floor, BodyLocation + FVector(0.0, 0.0, 20.0), BodyLocation - FVector(0.0, 0.0, Tuning.PoolTraceCm), ECC_Visibility, Params))
+ {
+ return;
+ }
+
+ if (Pools.Num() >= Tuning.MaxPools)
+ {
+ if (UDecalComponent* Oldest = Pools[0].Decal.Get())
+ {
+ Oldest->DestroyComponent();
+ }
+ Pools.RemoveAt(0);
+ ++Budget.PoolsRecycled;
+ }
+ FPool Pool;
+ Pool.VictimId = VictimId;
+ Pool.StartTime = GoreTime;
+ Pool.Radius = Tuning.PoolRadiusCm;
+ FRotator Rotation = (-Floor.ImpactNormal).Rotation();
+ Rotation.Roll = float(FVerseRng(uint64(VictimId), uint64(Budget.DeathsHandled), EVerseRngSalt::None).Range(0.0, 360.0));
+ const FTransform Transform(Rotation, Floor.ImpactPoint, FVector(1.0, Tuning.PoolStartFraction, Tuning.PoolStartFraction));
+ UDecalComponent* Decal = Actor->NewDecal(PoolMaterial, FVector(Tuning.DecalDepthCm, Pool.Radius, Pool.Radius),
+ FLinearColor::White, 0, Transform);
+ Pool.Decal = Decal;
+ Pools.Add(Pool);
+ bPoolsDirty = true;
+}
+
+void UVerseGoreSubsystem::UpdatePools()
+{
+ // Growth is a slow ease-out over seconds; writing it at a fixed low rate looks the same and
+ // keeps decal transform updates off most frames.
+ const double Step = Tuning.PoolUpdateHz > 0.f ? 1.0 / Tuning.PoolUpdateHz : 0.0;
+ if (Pools.Num() == 0 || (!bPoolsDirty && GoreTime - LastPoolUpdate < Step))
+ {
+ return;
+ }
+ LastPoolUpdate = GoreTime;
+ bPoolsDirty = false;
+ for (int32 Index = Pools.Num() - 1; Index >= 0; --Index)
+ {
+ UDecalComponent* Decal = Pools[Index].Decal.Get();
+ if (!Decal)
+ {
+ Pools.RemoveAt(Index);
+ continue;
+ }
+ const float Alpha = Tuning.PoolGrowSeconds > 0.f ? float((GoreTime - Pools[Index].StartTime) / Tuning.PoolGrowSeconds) : 1.f;
+ if (Alpha > 1.05f && Decal->GetComponentScale().Y >= 1.0)
+ {
+ continue;
+ }
+ const float Fraction = FMath::Lerp(Tuning.PoolStartFraction, 1.f, VerseGorePrivate::SmoothGrowth(Alpha));
+ Decal->SetWorldScale3D(FVector(1.0, Fraction, Fraction));
+ }
+}
+
+TArray<UDecalComponent*> UVerseGoreSubsystem::GetSpatterDecals() const
+{
+ TArray<UDecalComponent*> Result;
+ const int32 Num = SpatterRing.Num();
+ const bool bFull = Num >= Tuning.MaxSpatterDecals && Num > 0;
+ for (int32 Index = 0; Index < Num; ++Index)
+ {
+ UDecalComponent* Decal = SpatterRing[bFull ? (SpatterNext + Index) % Num : Index];
+ if (IsValid(Decal))
+ {
+ Result.Add(Decal);
+ }
+ }
+ return Result;
+}
+
+TArray<UDecalComponent*> UVerseGoreSubsystem::GetPoolDecals() const
+{
+ TArray<UDecalComponent*> Result;
+ for (const FPool& Pool : Pools)
+ {
+ if (UDecalComponent* Decal = Pool.Decal.Get())
+ {
+ Result.Add(Decal);
+ }
+ }
+ return Result;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Time
+
+void UVerseGoreSubsystem::Tick(float DeltaTime)
+{
+ Super::Tick(DeltaTime);
+ if (bActive)
+ {
+ AdvanceTime(DeltaTime);
+ }
+}
+
+void UVerseGoreSubsystem::AdvanceTime(float DeltaSeconds)
+{
+ const uint64 Start = FPlatformTime::Cycles64();
+ const float Dt = FMath::Max(0.f, DeltaSeconds);
+ GoreTime += Dt;
+
+ NestedEventMs = 0.0;
+
+ // Synthetic playback feeds Gore's own handlers. Only tests publish it on the hub, where every
+ // other consumer (score, respawn, kill cam, bot) would see it too (combat-state.md 8).
+ if (SyntheticCursor < SyntheticEvents.Num())
+ {
+ UVerseEventHub* EventHub = bSyntheticOnHub ? UVerseEventHub::Get(this) : nullptr;
+ while (SyntheticCursor < SyntheticEvents.Num() && SyntheticEvents[SyntheticCursor].Time <= GoreTime - SyntheticStart + UE_KINDA_SMALL_NUMBER)
+ {
+ const FVerseGoreSyntheticEvent Event = SyntheticEvents[SyntheticCursor++];
+ switch (Event.Type)
+ {
+ case FVerseGoreSyntheticEvent::EType::Hit:
+ EventHub ? EventHub->OnHit.Broadcast(Event.Hit) : HandleHit(Event.Hit);
+ break;
+ case FVerseGoreSyntheticEvent::EType::Death:
+ EventHub ? EventHub->OnDeath.Broadcast(Event.Death) : HandleDeath(Event.Death);
+ break;
+ case FVerseGoreSyntheticEvent::EType::Finisher:
+ EventHub ? EventHub->OnFinisher.Broadcast(Event.Finisher) : HandleFinisher(Event.Finisher);
+ break;
+ }
+ }
+ }
+
+ UpdateDroplets();
+ UpdateFlashes(Dt);
+ UpdatePools();
+
+ for (int32 Index = PendingWoundClears.Num() - 1; Index >= 0; --Index)
+ {
+ if (GoreTime < PendingWoundClears[Index].Value)
+ {
+ continue;
+ }
+ const TWeakObjectPtr<USkeletalMeshComponent> Mesh = PendingWoundClears[Index].Key;
+ PendingWoundClears.RemoveAt(Index);
+ for (int32 SetIndex = WoundSets.Num() - 1; SetIndex >= 0; --SetIndex)
+ {
+ if (WoundSets[SetIndex].Mesh == Mesh)
+ {
+ WoundSets[SetIndex].Wounds.Reset();
+ WoundSets[SetIndex].Next = 0;
+ ApplyWounds(WoundSets[SetIndex]);
+ WoundSets.RemoveAt(SetIndex);
+ }
+ }
+ }
+
+ if (CutToBlack.bActive && GoreTime - CutToBlack.StartTime > Tuning.CutToBlackTimeoutSeconds)
+ {
+ UE_LOG(LogVerseGore, Warning, TEXT("Finisher cut to black ended by timeout (no Recover or Aborted)"));
+ EndCutToBlack();
+ }
+
+ RefreshBudgetLive();
+ // The tick's own time: handlers that ran inside it are already counted as events.
+ const double Ms = FMath::Max(0.0, VerseGorePrivate::CyclesToMs(FPlatformTime::Cycles64() - Start) - NestedEventMs);
+ NestedEventMs = 0.0;
+ ++Budget.Ticks;
+ Budget.TickTotalMs += Ms;
+ Budget.TickMaxMs = FMath::Max(Budget.TickMaxMs, Ms);
+ Budget.TickMeanMs = Budget.TickTotalMs / double(Budget.Ticks);
+ RefreshGameThreadBudget();
+}
+
+void UVerseGoreSubsystem::AccountEvent(double Ms, bool bHit)
+{
+ if (bHit)
+ {
+ Budget.HitTotalMs += Ms;
+ Budget.HitMaxMs = FMath::Max(Budget.HitMaxMs, Ms);
+ Budget.HitMeanMs = Budget.HitTotalMs / FMath::Max(1, Budget.HitsHandled);
+ }
+ else
+ {
+ Budget.OtherEventTotalMs += Ms;
+ }
+ NestedEventMs += Ms;
+ RefreshGameThreadBudget();
+}
+
+void UVerseGoreSubsystem::RefreshGameThreadBudget()
+{
+ Budget.GameThreadTotalMs = Budget.HitTotalMs + Budget.OtherEventTotalMs + Budget.TickTotalMs;
+ Budget.GameThreadPerHitMs = Budget.HitsHandled > 0 ? Budget.GameThreadTotalMs / Budget.HitsHandled : 0.0;
+}
+
+void UVerseGoreSubsystem::UpdateDroplets()
+{
+ // Nothing moves on the CPU: the material animates every droplet and collapses it at the end
+ // of its life. The instances are dropped in one call once the last droplet has died.
+ if (DropletsSim.Num() == 0 || GoreTime < DropletsLastExpiry)
+ {
+ return;
+ }
+ DropletsSim.Reset();
+ DropletNext = 0;
+ if (AVerseGoreActor* Actor = GoreActor.Get())
+ {
+ Actor->Droplets->ClearInstances();
+ }
+}
+
+void UVerseGoreSubsystem::UpdateFlashes(float DeltaSeconds)
+{
+ AVerseGoreActor* Actor = GoreActor.Get();
+ if (!Actor)
+ {
+ FlashesSim.Reset();
+ return;
+ }
+ for (int32 Index = FlashesSim.Num() - 1; Index >= 0; --Index)
+ {
+ FlashesSim[Index].Age += DeltaSeconds;
+ if (FlashesSim[Index].Age >= Tuning.FlashLifeSeconds)
+ {
+ FlashesSim.RemoveAt(Index, 1, EAllowShrinking::No);
+ }
+ }
+ UInstancedStaticMeshComponent* Ism = Actor->Flashes;
+ if (Ism->GetInstanceCount() != FlashesSim.Num())
+ {
+ Ism->ClearInstances();
+ TArray<FTransform> Add;
+ for (const FFlash& Flash : FlashesSim)
+ {
+ const float S = Tuning.FlashSizeCm / 100.f;
+ Add.Emplace(FQuat::Identity, Flash.Position, FVector(S));
+ }
+ if (Add.Num() > 0)
+ {
+ Ism->AddInstances(Add, false, true, false);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Cut to black (Reduced finisher)
+
+void UVerseGoreSubsystem::StartCutToBlack(const FVerseFinisherEvent& Event)
+{
+ if (CutToBlack.bActive)
+ {
+ return;
+ }
+ CutToBlack.bActive = true;
+ CutToBlack.AttackerId = Event.AttackerId;
+ CutToBlack.VictimId = Event.VictimId;
+ CutToBlack.StartFrame = GFrameCounter;
+ CutToBlack.EndFrame = 0;
+ CutToBlack.StartTime = GoreTime;
+ ++CutToBlack.Count;
+ SetCameraFade(true);
+}
+
+void UVerseGoreSubsystem::EndCutToBlack()
+{
+ if (!CutToBlack.bActive)
+ {
+ return;
+ }
+ CutToBlack.bActive = false;
+ CutToBlack.EndFrame = GFrameCounter;
+ SetCameraFade(false);
+}
+
+void UVerseGoreSubsystem::SetCameraFade(bool bBlack)
+{
+ UWorld* World = GetWorld();
+ if (!World)
+ {
+ return;
+ }
+ // Actor iteration, not the world's controller list: it also finds controllers that have not
+ // begun play yet (a viewer joining mid-finisher).
+ for (TActorIterator<APlayerController> It(World); It; ++It)
+ {
+ APlayerController* Controller = *It;
+ // Every controller of a client or standalone world is the viewer's; on a listen server
+ // the remote players' controllers are skipped.
+ if (!Controller || !Controller->PlayerCameraManager
+ || (World->GetNetMode() == NM_ListenServer && !Controller->IsLocalController()))
+ {
+ continue;
+ }
+ if (bBlack)
+ {
+ Controller->PlayerCameraManager->SetManualCameraFade(1.f, FLinearColor::Black, false);
+ }
+ else
+ {
+ Controller->PlayerCameraManager->StopCameraFade();
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Synthetic playback
+
+void UVerseGoreSubsystem::PlaySynthetic(const FVerseGoreSyntheticParams& Params)
+{
+ SyntheticEvents = FVerseGoreSyntheticStream::Build(Params);
+ bSyntheticOnHub = Params.bPublishOnHub;
+ SyntheticCursor = 0;
+ SyntheticStart = GoreTime;
+}
+
+void UVerseGoreSubsystem::StopSynthetic()
+{
+ SyntheticEvents.Reset();
+ SyntheticCursor = 0;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Budget
+
+void UVerseGoreSubsystem::RefreshBudgetLive()
+{
+ Budget.SpatterDecals = SpatterRing.Num();
+ Budget.Pools = Pools.Num();
+ Budget.Droplets = LiveDroplets();
+ Budget.Flashes = FlashesSim.Num();
+ Budget.WoundedCharacters = 0;
+ Budget.MaxWoundsOnOneCharacter = 0;
+ for (const FWoundSet& Set : WoundSets)
+ {
+ if (Set.Wounds.Num() > 0)
+ {
+ ++Budget.WoundedCharacters;
+ Budget.MaxWoundsOnOneCharacter = FMath::Max(Budget.MaxWoundsOnOneCharacter, Set.Wounds.Num());
+ }
+ }
+ Budget.PeakSpatterDecals = FMath::Max(Budget.PeakSpatterDecals, Budget.SpatterDecals);
+ Budget.PeakPools = FMath::Max(Budget.PeakPools, Budget.Pools);
+ Budget.PeakDroplets = FMath::Max(Budget.PeakDroplets, Budget.Droplets);
+ Budget.PeakWoundsOnOneCharacter = FMath::Max(Budget.PeakWoundsOnOneCharacter, Budget.MaxWoundsOnOneCharacter);
+}
+
+void UVerseGoreSubsystem::ResetBudget()
+{
+ Budget = FVerseGoreBudget();
+ NestedEventMs = 0.0;
+ RefreshBudgetLive();
+}
+
+FString UVerseGoreSubsystem::BudgetJson() const
+{
+ const FVerseGoreBudget& B = Budget;
+ return FString::Printf(
+ TEXT("{\n")
+ TEXT(" \"schema\": \"verse.gore.budget/1\",\n")
+ TEXT(" \"level\": \"%s\",\n")
+ TEXT(" \"active\": %s,\n")
+ TEXT(" \"caps\": {\"spatter_decals\": %d, \"pools\": %d, \"wounds_per_character\": %d, \"droplets\": %d},\n")
+ TEXT(" \"live\": {\"spatter_decals\": %d, \"pools\": %d, \"droplets\": %d, \"flashes\": %d, \"wounded_characters\": %d, \"max_wounds_on_one_character\": %d},\n")
+ TEXT(" \"peak\": {\"spatter_decals\": %d, \"pools\": %d, \"droplets\": %d, \"wounds_on_one_character\": %d},\n")
+ TEXT(" \"totals\": {\"hits\": %d, \"deaths\": %d, \"finisher_phases\": %d, \"decals_spawned\": %d, \"decals_recycled\": %d, \"pools_recycled\": %d, \"wounds_recycled\": %d, \"droplets_spawned\": %d, \"flashes_spawned\": %d, \"purges\": %d},\n")
+ TEXT(" \"game_thread_ms\": {\"per_hit\": %.5f, \"total\": %.4f, \"hits_total\": %.4f, \"other_events_total\": %.4f, \"ticks_total\": %.4f, \"hit_mean\": %.5f, \"hit_max\": %.5f, \"tick_mean\": %.5f, \"tick_max\": %.5f, \"ticks\": %lld},\n")
+ TEXT(" \"cut_to_black\": {\"count\": %d, \"active\": %s, \"start_frame\": %llu, \"end_frame\": %llu}\n")
+ TEXT("}\n"),
+ Level == EVerseGoreLevel::Full ? TEXT("full") : TEXT("reduced"), bActive ? TEXT("true") : TEXT("false"),
+ Tuning.MaxSpatterDecals, Tuning.MaxPools, Tuning.MaxWoundsPerCharacter, Tuning.MaxDroplets,
+ B.SpatterDecals, B.Pools, B.Droplets, B.Flashes, B.WoundedCharacters, B.MaxWoundsOnOneCharacter,
+ B.PeakSpatterDecals, B.PeakPools, B.PeakDroplets, B.PeakWoundsOnOneCharacter,
+ B.HitsHandled, B.DeathsHandled, B.FinisherPhasesHandled, B.DecalsSpawned, B.DecalsRecycled, B.PoolsRecycled,
+ B.WoundsRecycled, B.DropletsSpawned, B.FlashesSpawned, B.Purges,
+ B.GameThreadPerHitMs, B.GameThreadTotalMs, B.HitTotalMs, B.OtherEventTotalMs, B.TickTotalMs,
+ B.HitMeanMs, B.HitMaxMs, B.TickMeanMs, B.TickMaxMs, B.Ticks,
+ CutToBlack.Count, CutToBlack.bActive ? TEXT("true") : TEXT("false"), CutToBlack.StartFrame, CutToBlack.EndFrame);
+}
+
+bool UVerseGoreSubsystem::WriteBudgetJson(const FString& Path) const
+{
+ return FFileHelper::SaveStringToFile(BudgetJson(), *Path, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
+}
diff --git a/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSynthetic.cpp b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSynthetic.cpp
new file mode 100644
index 0000000000..8ae68335e6
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Gore/VerseGoreSynthetic.cpp
@@ -0,0 +1,197 @@
+#include "Gore/VerseGoreSynthetic.h"
+
+#include "VerseRng.h"
+
+namespace VerseGoreSyntheticPrivate
+{
+ /** Zone weights of a synthetic hit (torso heavy, as rifle fire at a standing body is). */
+ struct FZoneWeight
+ {
+ EVerseHitZone Zone;
+ double Weight;
+ float Damage;
+ };
+
+ constexpr FZoneWeight ZoneWeights[] = {
+ {EVerseHitZone::Head, 0.12, 60.f},
+ {EVerseHitZone::Neck, 0.06, 40.f},
+ {EVerseHitZone::UpperTorso, 0.34, 30.f},
+ {EVerseHitZone::LowerTorso, 0.20, 27.f},
+ {EVerseHitZone::Arm, 0.14, 22.f},
+ {EVerseHitZone::Leg, 0.14, 22.f},
+ };
+
+ EVerseHitZone PickZone(FVerseRng& Rng, float& OutDamage)
+ {
+ double Roll = Rng.NextUnit();
+ for (const FZoneWeight& Entry : ZoneWeights)
+ {
+ if (Roll < Entry.Weight)
+ {
+ OutDamage = Entry.Damage;
+ return Entry.Zone;
+ }
+ Roll -= Entry.Weight;
+ }
+ OutDamage = ZoneWeights[2].Damage;
+ return EVerseHitZone::UpperTorso;
+ }
+}
+
+FName FVerseGoreSyntheticStream::BoneForZone(EVerseHitZone Zone)
+{
+ switch (Zone)
+ {
+ case EVerseHitZone::Head: return TEXT("Head");
+ case EVerseHitZone::Neck: return TEXT("Neck");
+ case EVerseHitZone::UpperTorso: return TEXT("Spine_03");
+ case EVerseHitZone::LowerTorso: return TEXT("Spine_01");
+ case EVerseHitZone::Arm: return TEXT("UpperArm_R");
+ case EVerseHitZone::Leg: return TEXT("Thigh_L");
+ default: return NAME_None;
+ }
+}
+
+double FVerseGoreSyntheticStream::HeightForZone(EVerseHitZone Zone)
+{
+ switch (Zone)
+ {
+ case EVerseHitZone::Head: return 168.0;
+ case EVerseHitZone::Neck: return 152.0;
+ case EVerseHitZone::UpperTorso: return 132.0;
+ case EVerseHitZone::LowerTorso: return 104.0;
+ case EVerseHitZone::Arm: return 128.0;
+ case EVerseHitZone::Leg: return 62.0;
+ default: return 120.0;
+ }
+}
+
+FVerseHitEvent FVerseGoreSyntheticStream::MakeHit(EVerseHitZone Zone, const FVector& VictimLocation, const FVector& ShooterLocation,
+ int32 InstigatorId, int32 VictimId, float Damage, uint16 ShotCounter, float ServerTime, bool bKillingBlow)
+{
+ FVerseHitEvent Hit;
+ Hit.InstigatorId = InstigatorId;
+ Hit.VictimId = VictimId;
+ Hit.WeaponId = TEXT("synthetic_rifle");
+ Hit.Source = EVerseDamageSource::Bolt;
+ Hit.ShotCounter = ShotCounter;
+ Hit.Zone = Zone;
+ Hit.Bone = BoneForZone(Zone);
+
+ FVerseRng Rng(uint64(VictimId) << 32 | ShotCounter, ShotCounter, EVerseRngSalt::Harness);
+ const double Side = Zone == EVerseHitZone::Arm ? 24.0 : Rng.Range(-9.0, 9.0);
+ const FVector Impact = VictimLocation + FVector(Rng.Range(-6.0, 6.0), Side, HeightForZone(Zone) + Rng.Range(-5.0, 5.0));
+ Hit.ImpactWorld = FVector_NetQuantize10(Impact);
+ Hit.ImpactBoneLocal = FVector_NetQuantize10(FVector(Rng.Range(-6.0, 6.0), Rng.Range(-6.0, 6.0), Rng.Range(-4.0, 8.0)));
+ const FVector Dir = (Impact - ShooterLocation).GetSafeNormal(UE_SMALL_NUMBER, FVector::ForwardVector);
+ Hit.Direction = FVector_NetQuantizeNormal(Dir);
+ Hit.DistanceM = float(FVector::Dist(Impact, ShooterLocation) / 100.0);
+ Hit.Damage = Damage;
+ Hit.bHeadshot = Zone == EVerseHitZone::Head ? 1 : 0;
+ Hit.bKillingBlow = bKillingBlow ? 1 : 0;
+ Hit.ServerTime = ServerTime;
+ return Hit;
+}
+
+bool FVerseGoreSyntheticStream::ParseKind(const FString& Text, EVerseGoreSyntheticKind& OutKind)
+{
+ if (Text.Equals(TEXT("hits"), ESearchCase::IgnoreCase) || Text.Equals(TEXT("hit"), ESearchCase::IgnoreCase))
+ {
+ OutKind = EVerseGoreSyntheticKind::Hits;
+ }
+ else if (Text.Equals(TEXT("deaths"), ESearchCase::IgnoreCase) || Text.Equals(TEXT("death"), ESearchCase::IgnoreCase))
+ {
+ OutKind = EVerseGoreSyntheticKind::Deaths;
+ }
+ else if (Text.Equals(TEXT("finisher"), ESearchCase::IgnoreCase))
+ {
+ OutKind = EVerseGoreSyntheticKind::Finisher;
+ }
+ else if (Text.Equals(TEXT("storm"), ESearchCase::IgnoreCase) || Text.Equals(TEXT("gore_storm"), ESearchCase::IgnoreCase))
+ {
+ OutKind = EVerseGoreSyntheticKind::Storm;
+ }
+ else
+ {
+ return false;
+ }
+ return true;
+}
+
+TArray<FVerseGoreSyntheticEvent> FVerseGoreSyntheticStream::Build(const FVerseGoreSyntheticParams& Params)
+{
+ using namespace VerseGoreSyntheticPrivate;
+ TArray<FVerseGoreSyntheticEvent> Events;
+ FVerseRng Rng(Params.Seed, 0, EVerseRngSalt::Harness);
+
+ if (Params.Kind == EVerseGoreSyntheticKind::Finisher)
+ {
+ const EVerseFinisherPhase Phases[] = {EVerseFinisherPhase::Locked, EVerseFinisherPhase::Takedown,
+ EVerseFinisherPhase::Struggle, EVerseFinisherPhase::Kill, EVerseFinisherPhase::Recover};
+ const double Offsets[] = {0.0, VerseGoreFinisherTimes::Takedown, VerseGoreFinisherTimes::Struggle,
+ VerseGoreFinisherTimes::Kill, VerseGoreFinisherTimes::Recover};
+ const FVector Behind = Params.VictimLocation - FVector(80.0, 0.0, 0.0);
+ for (int32 Index = 0; Index < UE_ARRAY_COUNT(Phases); ++Index)
+ {
+ FVerseGoreSyntheticEvent Event;
+ Event.Time = Offsets[Index];
+ Event.Type = FVerseGoreSyntheticEvent::EType::Finisher;
+ Event.Finisher.AttackerId = Params.InstigatorId;
+ Event.Finisher.VictimId = Params.VictimId;
+ Event.Finisher.Phase = Phases[Index];
+ Event.Finisher.SequenceStartServerTime = 0.f;
+ Event.Finisher.WarpTarget = FTransform(FRotator::ZeroRotator, Behind);
+ Events.Add(Event);
+ if (Phases[Index] == EVerseFinisherPhase::Kill)
+ {
+ FVerseGoreSyntheticEvent Death;
+ Death.Time = Offsets[Index];
+ Death.Type = FVerseGoreSyntheticEvent::EType::Death;
+ Death.Death.VictimId = Params.VictimId;
+ Death.Death.KillerId = Params.InstigatorId;
+ Death.Death.Cause = EVerseDamageSource::Finisher;
+ Death.Death.LastZone = EVerseHitZone::Neck;
+ Death.Death.ServerTime = float(Offsets[Index]);
+ Death.Death.RespawnAt = float(Offsets[Index] + 3.0);
+ Events.Add(Death);
+ }
+ }
+ return Events;
+ }
+
+ const double Rate = Params.Kind == EVerseGoreSyntheticKind::Storm ? 30.0 : FMath::Max(0.1, Params.RatePerSecond);
+ const int32 Count = FMath::Max(1, FMath::FloorToInt32(Params.DurationSeconds * Rate));
+ for (int32 Index = 0; Index < Count; ++Index)
+ {
+ const double Time = Index / Rate;
+ float Damage = 30.f;
+ const EVerseHitZone Zone = PickZone(Rng, Damage);
+ const bool bKill = Params.Kind == EVerseGoreSyntheticKind::Deaths;
+ // Shooter wanders on a 6 m arc so bolt directions vary.
+ const double Angle = Rng.Range(-0.6, 0.6);
+ const FVector Offset = Params.ShooterLocation - Params.VictimLocation;
+ const FVector Shooter = Params.VictimLocation + Offset.RotateAngleAxisRad(Angle, FVector::UpVector);
+
+ FVerseGoreSyntheticEvent Event;
+ Event.Time = Time;
+ Event.Type = FVerseGoreSyntheticEvent::EType::Hit;
+ Event.Hit = MakeHit(Zone, Params.VictimLocation, Shooter, Params.InstigatorId, Params.VictimId,
+ bKill ? 100.f : Damage, uint16(Index + 1), float(Time), bKill);
+ Events.Add(Event);
+
+ if (bKill)
+ {
+ FVerseGoreSyntheticEvent Death;
+ Death.Time = Time;
+ Death.Type = FVerseGoreSyntheticEvent::EType::Death;
+ Death.Death.VictimId = Params.VictimId;
+ Death.Death.KillerId = Params.InstigatorId;
+ Death.Death.Cause = EVerseDamageSource::Bolt;
+ Death.Death.LastZone = Zone;
+ Death.Death.ServerTime = float(Time);
+ Death.Death.RespawnAt = float(Time + 3.0);
+ Events.Add(Death);
+ }
+ }
+ return Events;
+}
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.cpp b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.cpp
new file mode 100644
index 0000000000..b7e2300daf
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.cpp
@@ -0,0 +1,231 @@
+#include "Tests/Gore/Fakes/FakeGoreDuel.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Components/PrimitiveComponent.h"
+#include "EngineUtils.h"
+#include "Gore/VerseGoreSynthetic.h"
+#include "UObject/UnrealType.h"
+#include "VerseCollision.h"
+
+namespace FakeGoreDuelPrivate
+{
+ uint32 HashString(const FString& Text)
+ {
+ return FCrc::StrCrc32(*Text);
+ }
+
+ uint32 HashVector(const FVector& V)
+ {
+ return HashCombine(HashCombine(GetTypeHash(FMath::RoundToInt64(V.X * 100.0)), GetTypeHash(FMath::RoundToInt64(V.Y * 100.0))),
+ GetTypeHash(FMath::RoundToInt64(V.Z * 100.0)));
+ }
+
+ /** Net properties of one actor; object references hash as set or unset (paths name the world). */
+ uint32 HashNetProperties(const AActor* Actor)
+ {
+ uint32 Hash = HashString(Actor->GetClass()->GetName());
+ for (TFieldIterator<FProperty> It(Actor->GetClass()); It; ++It)
+ {
+ const FProperty* Property = *It;
+ if (!Property->HasAnyPropertyFlags(CPF_Net))
+ {
+ continue;
+ }
+ Hash = HashCombine(Hash, HashString(Property->GetName()));
+ if (const FObjectPropertyBase* Object = CastField<FObjectPropertyBase>(Property))
+ {
+ Hash = HashCombine(Hash, Object->GetObjectPropertyValue_InContainer(Actor) ? 1u : 0u);
+ continue;
+ }
+ FString Value;
+ Property->ExportText_InContainer(0, Value, Actor, Actor, nullptr, PPF_None);
+ Hash = HashCombine(Hash, HashString(Value));
+ }
+ return HashCombine(Hash, HashVector(Actor->GetActorLocation()));
+ }
+}
+
+FFakeGoreDuel::FFakeGoreDuel(VerseGoreTest::FWorld& InWorld, uint32 InSeed)
+ : W(InWorld)
+ , Seed(InSeed)
+{
+ for (int32 Index = 0; Index < 2; ++Index)
+ {
+ FDuellist& D = Duellists[Index];
+ D.Id = Index + 1;
+ D.Home = FVector(Index == 0 ? -500.0 : 500.0, 0.0, 0.0);
+ D.Mesh = W.AddBody(D.Id, D.Home);
+ D.Pawn = Cast<APawn>(D.Mesh->GetOwner());
+ D.Pawn->SetReplicates(true);
+ }
+}
+
+bool FFakeGoreDuel::Query(const FVector& From, const FVector& To, ECollisionChannel Channel, const AActor* Ignore, FHitResult& OutHit)
+{
+ using namespace FakeGoreDuelPrivate;
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(FakeGoreDuel), true);
+ if (Ignore)
+ {
+ Params.AddIgnoredActor(Ignore);
+ }
+ OutHit = FHitResult();
+ const bool bHit = W.World->LineTraceSingleByChannel(OutHit, From, To, Channel, Params);
+ ++Queries;
+ uint32 Result = HashCombine(GetTypeHash(int32(Channel)), bHit ? 1u : 0u);
+ if (bHit)
+ {
+ const AActor* Actor = OutHit.GetActor();
+ Result = HashCombine(Result, HashVector(OutHit.ImpactPoint));
+ Result = HashCombine(Result, HashString(Actor ? Actor->GetClass()->GetName() : FString()));
+ }
+ QueryHash = HashCombine(QueryHash, Result);
+ return bHit;
+}
+
+void FFakeGoreDuel::Step(double Dt)
+{
+ Time += Dt;
+ ++Tick;
+ FVerseRng Rng(Seed, uint64(Tick), EVerseRngSalt::Harness);
+
+ for (FDuellist& D : Duellists)
+ {
+ if (D.Health <= 0.f && Time >= D.RespawnAt)
+ {
+ D.Health = 100.f;
+ D.RespawnAt = -1.f;
+ }
+ if (D.Health > 0.f)
+ {
+ const double Phase = Time * (0.6 + 0.1 * D.Id) + D.Id;
+ D.Pawn->SetActorLocation(D.Home + FVector(FMath::Sin(Phase) * 250.0, FMath::Cos(Phase * 0.8) * 300.0, 0.0));
+ }
+ }
+
+ // Probes through the space gore paints: from each eye toward both end walls (spatter lands
+ // there) and down to the floor (pools), on every channel gameplay uses.
+ const ECollisionChannel Channels[] = {VerseCollision::Bolt, VerseCollision::HitBody, VerseCollision::Sight};
+ for (const FDuellist& D : Duellists)
+ {
+ const FVector Eye = D.Pawn->GetActorLocation() + FVector(0.0, 0.0, 160.0);
+ const FVector Targets[] = {Eye + FVector(2000.0, 0.0, -40.0), Eye - FVector(2000.0, 0.0, 40.0), Eye - FVector(0.0, 0.0, 400.0)};
+ for (const ECollisionChannel Channel : Channels)
+ {
+ for (const FVector& Target : Targets)
+ {
+ FHitResult Probe;
+ Query(Eye, Target, Channel, D.Pawn, Probe);
+ }
+ }
+ }
+
+ FDuellist& A = Duellists[Tick % 2];
+ FDuellist& B = Duellists[(Tick + 1) % 2];
+ if (Tick % 3 != 0 || A.Health <= 0.f || B.Health <= 0.f)
+ {
+ return;
+ }
+
+ // Sight and the bolt: anything but the target between the two blocks the shot.
+ const FVector Muzzle = A.Pawn->GetActorLocation() + FVector(0.0, 0.0, 160.0);
+ const FVector Chest = B.Pawn->GetActorLocation() + FVector(0.0, 0.0, 130.0);
+ FHitResult SightHit, BoltHit, BodyHit;
+ const bool bSightBlocked = Query(Muzzle, Chest, VerseCollision::Sight, A.Pawn, SightHit) && SightHit.GetActor() != B.Pawn;
+ const bool bBoltBlocked = Query(Muzzle, Chest, VerseCollision::Bolt, A.Pawn, BoltHit) && BoltHit.GetActor() != B.Pawn;
+ Query(Muzzle, Chest + (Chest - Muzzle).GetSafeNormal() * 50.0, VerseCollision::HitBody, A.Pawn, BodyHit);
+ if (bSightBlocked || bBoltBlocked)
+ {
+ ++BlockedShots;
+ return;
+ }
+
+ // Rarely a finisher, else a shot.
+ if (Rng.Chance(0.01))
+ {
+ const double Offsets[] = {0.0, VerseGoreFinisherTimes::Takedown, VerseGoreFinisherTimes::Struggle,
+ VerseGoreFinisherTimes::Kill, VerseGoreFinisherTimes::Recover};
+ const EVerseFinisherPhase Phases[] = {EVerseFinisherPhase::Locked, EVerseFinisherPhase::Takedown,
+ EVerseFinisherPhase::Struggle, EVerseFinisherPhase::Kill, EVerseFinisherPhase::Recover};
+ for (int32 I = 0; I < 5; ++I)
+ {
+ FVerseFinisherEvent Event;
+ Event.AttackerId = A.Id;
+ Event.VictimId = B.Id;
+ Event.Phase = Phases[I];
+ Event.SequenceStartServerTime = float(Time);
+ Event.WarpTarget = FTransform(B.Pawn->GetActorLocation() - FVector(80.0, 0.0, 0.0));
+ W.Hub->OnFinisher.Broadcast(Event); // phases are cosmetic; the fake applies the kill at once
+ (void)Offsets[I];
+ }
+ B.Health = 0.f;
+ }
+ else if (Rng.Chance(0.45))
+ {
+ float Damage = 0.f;
+ const double Roll = Rng.NextUnit();
+ const EVerseHitZone Zone = Roll < 0.12 ? EVerseHitZone::Head : Roll < 0.5 ? EVerseHitZone::UpperTorso
+ : Roll < 0.7 ? EVerseHitZone::LowerTorso : Roll < 0.85 ? EVerseHitZone::Arm : EVerseHitZone::Leg;
+ Damage = Zone == EVerseHitZone::Head ? 60.f : Zone == EVerseHitZone::UpperTorso ? 30.f : 24.f;
+ const bool bKill = B.Health - Damage <= 0.f;
+ const FVerseHitEvent Hit = FVerseGoreSyntheticStream::MakeHit(Zone, B.Pawn->GetActorLocation(),
+ A.Pawn->GetActorLocation() + FVector(0.0, 0.0, 160.0), A.Id, B.Id, Damage, ++Shot, float(Time), bKill);
+ W.Hub->OnHit.Broadcast(Hit);
+ B.Health -= Damage;
+ }
+ else
+ {
+ return;
+ }
+
+ if (B.Health <= 0.f)
+ {
+ B.Health = 0.f;
+ ++B.Deaths;
+ ++A.Kills;
+ B.RespawnAt = float(Time + 3.0);
+ FVerseDeathEvent Death;
+ Death.VictimId = B.Id;
+ Death.KillerId = A.Id;
+ Death.ServerTime = float(Time);
+ Death.RespawnAt = B.RespawnAt;
+ W.Hub->OnDeath.Broadcast(Death);
+ }
+}
+
+uint32 FFakeGoreDuel::StateHash() const
+{
+ using namespace FakeGoreDuelPrivate;
+ TArray<uint32> ActorHashes;
+ int32 Colliding = 0;
+ for (TActorIterator<AActor> It(W.World); It; ++It)
+ {
+ const AActor* Actor = *It;
+ if (Actor->GetIsReplicated())
+ {
+ ActorHashes.Add(HashNetProperties(Actor));
+ }
+ TInlineComponentArray<UPrimitiveComponent*> Primitives(Actor);
+ for (const UPrimitiveComponent* Primitive : Primitives)
+ {
+ if (Primitive->IsRegistered() && Primitive->IsCollisionEnabled())
+ {
+ ++Colliding;
+ }
+ }
+ }
+ ActorHashes.Sort();
+ uint32 Hash = HashCombine(GetTypeHash(Colliding), HashCombine(QueryHash, HashCombine(GetTypeHash(BlockedShots), GetTypeHash(Queries))));
+ for (const uint32 H : ActorHashes)
+ {
+ Hash = HashCombine(Hash, H);
+ }
+ for (const FDuellist& D : Duellists)
+ {
+ Hash = HashCombine(Hash, HashCombine(GetTypeHash(D.Health), HashCombine(GetTypeHash(D.Kills), GetTypeHash(D.Deaths))));
+ Hash = HashCombine(Hash, HashVector(D.Pawn->GetActorLocation()));
+ }
+ return Hash;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.h b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.h
new file mode 100644
index 0000000000..9faef64e9f
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/Fakes/FakeGoreDuel.h
@@ -0,0 +1,60 @@
+#pragma once
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "CoreMinimal.h"
+#include "Tests/Gore/VerseGoreTestWorld.h"
+#include "VerseRng.h"
+
+/**
+ * Fake of the WP10 bot-vs-bot match for the D6 run before WP10 and WP02 land (work-packages.md
+ * 0.3, WP05 "Depends on"). Two replicated duellist pawns on the G0 test human move, fire and die
+ * from one seed; every hit, death and finisher is published on the hub as Combat would. The
+ * duel state lives in this fake (as Combat's replicated state will), so gore can only change it
+ * by changing the world.
+ */
+struct FFakeGoreDuel
+{
+ struct FDuellist
+ {
+ int32 Id = 0;
+ APawn* Pawn = nullptr;
+ USkeletalMeshComponent* Mesh = nullptr;
+ float Health = 100.f;
+ int32 Kills = 0;
+ int32 Deaths = 0;
+ float RespawnAt = -1.f;
+ FVector Home = FVector::ZeroVector;
+ };
+
+ VerseGoreTest::FWorld& W;
+ uint32 Seed = 1;
+ double Time = 0.0;
+ int64 Tick = 0;
+ uint16 Shot = 0;
+ FDuellist Duellists[2];
+ /** World queries the gameplay asked this run, folded together: every shot's bolt and body
+ * trace, every sight check and the probes toward the walls gore paints (VerseBolt,
+ * VerseHitBody, VerseSight). A gore primitive that blocked any of them would change it. */
+ uint32 QueryHash = 0;
+ int32 BlockedShots = 0;
+ int32 Queries = 0;
+
+ FFakeGoreDuel(VerseGoreTest::FWorld& InWorld, uint32 InSeed);
+
+ /** One 30 Hz tick: move, sense, fire (traced), damage, deaths, respawns, finishers. */
+ void Step(double Dt);
+
+ /**
+ * Hash of everything replicated or gameplay-relevant in the world after the tick: every
+ * replicated actor's net properties and transform, the duel state, and the collision state of
+ * every primitive (gore must add none), and the results of every world query of the tick.
+ */
+ uint32 StateHash() const;
+
+private:
+ /** One line trace on `Channel`; its result (hit or not, where, what) is folded into QueryHash. */
+ bool Query(const FVector& From, const FVector& To, ECollisionChannel Channel, const AActor* Ignore, FHitResult& OutHit);
+};
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreIncludeScanTest.cpp b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreIncludeScanTest.cpp
new file mode 100644
index 0000000000..d9ff4537c1
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreIncludeScanTest.cpp
@@ -0,0 +1,95 @@
+#include "Misc/AutomationTest.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "HAL/FileManager.h"
+#include "Internationalization/Regex.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+
+#define VERSE_GORE_SCAN_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+// A5.2: Source/VerseGore/** includes no header of VerseCombat, VerseBot or VerseDestruction
+// (combat-state.md 8, architecture.md 2). Gore talks to them only through Core's hub.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreIncludeScanTest, "Verse.Gore.IncludeScan", VERSE_GORE_SCAN_FLAGS)
+bool FVerseGoreIncludeScanTest::RunTest(const FString&)
+{
+ const FString SourceRoot = FPaths::ConvertRelativePathToFull(FPaths::GameSourceDir());
+ const FString GoreRoot = FPaths::Combine(SourceRoot, TEXT("VerseGore"));
+ if (!TestTrue(TEXT("VerseGore sources present"), FPaths::DirectoryExists(GoreRoot)))
+ {
+ return false;
+ }
+
+ // Every header the forbidden modules hold, as include paths relative to Public/ and Private/.
+ TSet<FString> Forbidden;
+ TSet<FString> ForbiddenNames;
+ for (const TCHAR* Module : {TEXT("VerseCombat"), TEXT("VerseBot"), TEXT("VerseDestruction")})
+ {
+ const FString ModuleRoot = FPaths::Combine(SourceRoot, Module);
+ TArray<FString> Headers;
+ IFileManager::Get().FindFilesRecursive(Headers, *ModuleRoot, TEXT("*.h"), true, false);
+ for (const FString& Header : Headers)
+ {
+ FString Relative = Header;
+ for (const TCHAR* Sub : {TEXT("/Public/"), TEXT("/Private/"), TEXT("/Classes/")})
+ {
+ const int32 At = Relative.Find(Sub);
+ if (At != INDEX_NONE)
+ {
+ Relative = Relative.Mid(At + FCString::Strlen(Sub));
+ break;
+ }
+ }
+ Forbidden.Add(Relative.ToLower());
+ }
+ ForbiddenNames.Add(FString(Module).ToLower());
+ }
+ TestTrue(TEXT("forbidden modules have headers to scan against"), Forbidden.Num() > 0);
+
+ TArray<FString> Files;
+ IFileManager::Get().FindFilesRecursive(Files, *GoreRoot, TEXT("*.*"), true, false);
+ const FRegexPattern Include(TEXT("^\\s*#\\s*include\\s*[\"<]([^\">]+)[\">]"));
+ int32 Scanned = 0, Includes = 0;
+ for (const FString& File : Files)
+ {
+ if (!File.EndsWith(TEXT(".h")) && !File.EndsWith(TEXT(".cpp")) && !File.EndsWith(TEXT(".inl")))
+ {
+ continue;
+ }
+ TArray<FString> Lines;
+ FFileHelper::LoadFileToStringArray(Lines, *File);
+ ++Scanned;
+ for (const FString& Line : Lines)
+ {
+ FRegexMatcher Matcher(Include, Line);
+ if (!Matcher.FindNext())
+ {
+ continue;
+ }
+ ++Includes;
+ const FString Path = Matcher.GetCaptureGroup(1).ToLower();
+ FString FirstSegment;
+ Path.Split(TEXT("/"), &FirstSegment, nullptr);
+ const bool bByPath = Forbidden.Contains(Path);
+ const bool bByModuleFolder = ForbiddenNames.Contains(FirstSegment);
+ const bool bByModuleHeader = Path.StartsWith(TEXT("versecombat")) || Path.StartsWith(TEXT("versebot")) || Path.StartsWith(TEXT("versedestruction"));
+ if (bByPath || bByModuleFolder || bByModuleHeader)
+ {
+ AddError(FString::Printf(TEXT("%s includes %s"), *FPaths::GetCleanFilename(File), *Path));
+ }
+ }
+ }
+ TestTrue(FString::Printf(TEXT("scanned %d files, %d includes"), Scanned, Includes), Scanned >= 8 && Includes > 20);
+
+ // The build rules agree: no Combat, Bot or Destruction edge.
+ FString BuildRules;
+ FFileHelper::LoadFileToString(BuildRules, *FPaths::Combine(GoreRoot, TEXT("VerseGore.Build.cs")));
+ for (const TCHAR* Module : {TEXT("\"VerseCombat\""), TEXT("\"VerseBot\""), TEXT("\"VerseDestruction\"")})
+ {
+ TestFalse(FString::Printf(TEXT("VerseGore.Build.cs names %s"), Module), BuildRules.Contains(Module));
+ }
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreNoGameplayEffectTest.cpp b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreNoGameplayEffectTest.cpp
new file mode 100644
index 0000000000..169f0cf026
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreNoGameplayEffectTest.cpp
@@ -0,0 +1,104 @@
+#include "Misc/AutomationTest.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "HAL/FileManager.h"
+#include "Misc/FileHelper.h"
+#include "Tests/Gore/Fakes/FakeGoreDuel.h"
+
+using namespace VerseGoreTest;
+
+namespace VerseGoreD6
+{
+ /** 10 minutes at 30 Hz (A5.1). */
+ constexpr int32 Ticks = 10 * 60 * 30;
+
+ enum class EMode : uint8 { Off, Full, Reduced };
+
+ TArray<uint32> Run(EMode Mode, uint32 Seed, FVerseGoreBudget& OutBudget, int32& OutQueries)
+ {
+ FWorld W(Mode != EMode::Off, TEXT("VerseGoreD6World"));
+ TArray<uint32> Hashes;
+ if (!W.IsValid())
+ {
+ return Hashes;
+ }
+ W.AddRoom(900.0);
+ W.AddBox(FVector(-900.0, 0.0, 200.0), FVector(20.0, 2000.0, 400.0));
+ W.Gore->SetGoreLevel(Mode == EMode::Reduced ? EVerseGoreLevel::Reduced : EVerseGoreLevel::Full);
+ W.Gore->SetForceActive(Mode != EMode::Off);
+ FFakeGoreDuel Duel(W, Seed);
+ Hashes.Reserve(Ticks);
+ for (int32 Tick = 0; Tick < Ticks; ++Tick)
+ {
+ Duel.Step(1.0 / 30.0);
+ W.Gore->AdvanceTime(1.f / 30.f);
+ Hashes.Add(Duel.StateHash());
+ }
+ OutBudget = W.Gore->GetBudget();
+ OutQueries = Duel.Queries;
+ return Hashes;
+ }
+}
+
+// A5.1 / D6: gore never changes a replicated gameplay value. Runs the fake duel (until WP10's
+// bot-vs-bot harness lands) three times from one seed: gore off, Full, Reduced.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreNoGameplayEffectTest, "Verse.Gore.NoGameplayEffect", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreNoGameplayEffectTest::RunTest(const FString&)
+{
+ using namespace VerseGoreD6;
+ const uint32 Seed = 0xD6u;
+ FVerseGoreBudget OffBudget, FullBudget, ReducedBudget;
+ int32 OffQueries = 0, FullQueries = 0, ReducedQueries = 0;
+ const TArray<uint32> Off = Run(EMode::Off, Seed, OffBudget, OffQueries);
+ const TArray<uint32> Full = Run(EMode::Full, Seed, FullBudget, FullQueries);
+ const TArray<uint32> Reduced = Run(EMode::Reduced, Seed, ReducedBudget, ReducedQueries);
+ // The fake's gameplay traces VerseBolt, VerseHitBody and VerseSight through the gore every tick.
+ TestTrue(FString::Printf(TEXT("gameplay queried the world (%d traces per run)"), FullQueries), FullQueries > Ticks * 6);
+ if (!TestEqual(TEXT("every run produced every tick"), Full.Num(), Ticks) || Off.Num() != Ticks || Reduced.Num() != Ticks)
+ {
+ return false;
+ }
+
+ int32 FirstFullMismatch = INDEX_NONE, FirstReducedMismatch = INDEX_NONE, FullVsReduced = 0;
+ for (int32 Tick = 0; Tick < Ticks; ++Tick)
+ {
+ if (FirstFullMismatch == INDEX_NONE && Full[Tick] != Off[Tick])
+ {
+ FirstFullMismatch = Tick;
+ }
+ if (FirstReducedMismatch == INDEX_NONE && Reduced[Tick] != Off[Tick])
+ {
+ FirstReducedMismatch = Tick;
+ }
+ FullVsReduced += Full[Tick] != Reduced[Tick] ? 1 : 0;
+ }
+ TestEqual(TEXT("Full: state hash equals gore-off on every tick (first mismatch)"), FirstFullMismatch, int32(INDEX_NONE));
+ TestEqual(TEXT("Reduced: state hash equals gore-off on every tick (first mismatch)"), FirstReducedMismatch, int32(INDEX_NONE));
+ TestEqual(TEXT("Full and Reduced ticks that differ"), FullVsReduced, 0);
+
+ // The run must have exercised gore, or the comparison proves nothing.
+ TestTrue(FString::Printf(TEXT("Full drew gore (%d hits, %d decals, %d deaths)"), FullBudget.HitsHandled, FullBudget.DecalsSpawned, FullBudget.DeathsHandled),
+ FullBudget.HitsHandled > 500 && FullBudget.DecalsSpawned > 100 && FullBudget.DeathsHandled > 10 && FullBudget.FinisherPhasesHandled > 0);
+ TestTrue(TEXT("Reduced drew no blood"), ReducedBudget.HitsHandled == FullBudget.HitsHandled && ReducedBudget.DecalsSpawned == 0 && ReducedBudget.DropletsSpawned == 0);
+ if (!UVerseGoreSubsystem::ProcessCanShowGore())
+ {
+ TestEqual(TEXT("gore off handled nothing"), OffBudget.HitsHandled, 0);
+ }
+
+ const FString Dir = ProofDir(TEXT("5.8"));
+ IFileManager::Get().MakeDirectory(*Dir, true);
+ FString Log = FString::Printf(TEXT("# Verse.Gore.NoGameplayEffect seed=0x%X ticks=%d hz=30 harness=FFakeGoreDuel traces_per_run=%d\n# tick off full reduced\n"), Seed, Ticks, FullQueries);
+ for (int32 Tick = 0; Tick < Ticks; Tick += 1)
+ {
+ Log += FString::Printf(TEXT("%d %08x %08x %08x\n"), Tick, Off[Tick], Full[Tick], Reduced[Tick]);
+ }
+ Log += FString::Printf(TEXT("# full: hits=%d decals=%d deaths=%d finisher_phases=%d; reduced: hits=%d decals=%d flashes=%d; mismatches full=%d reduced=%d\n"),
+ FullBudget.HitsHandled, FullBudget.DecalsSpawned, FullBudget.DeathsHandled, FullBudget.FinisherPhasesHandled,
+ ReducedBudget.HitsHandled, ReducedBudget.DecalsSpawned, ReducedBudget.FlashesSpawned,
+ FirstFullMismatch == INDEX_NONE ? 0 : 1, FirstReducedMismatch == INDEX_NONE ? 0 : 1);
+ FFileHelper::SaveStringToFile(Log, *FPaths::Combine(Dir, TEXT("d6_hash.log")));
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTestWorld.h b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTestWorld.h
new file mode 100644
index 0000000000..c901b64d6a
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTestWorld.h
@@ -0,0 +1,152 @@
+#pragma once
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Components/SkeletalMeshComponent.h"
+#include "Components/StaticMeshComponent.h"
+#include "CoreMinimal.h"
+#include "Engine/Engine.h"
+#include "Engine/SkeletalMesh.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/StaticMeshActor.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/Pawn.h"
+#include "Gore/VerseGoreSubsystem.h"
+#include "Materials/MaterialInterface.h"
+#include "Misc/Paths.h"
+
+#define VERSE_GORE_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+namespace VerseGoreTest
+{
+ /** Placeholder art: the G0 test human and the engine's unit cube (referenced, never committed). */
+ inline const TCHAR* TestHumanPath = TEXT("/Game/Verse/Test/G0/SK_Test_Human.SK_Test_Human");
+ inline const TCHAR* CubePath = TEXT("/Engine/BasicShapes/Cube.Cube");
+ /** The WP13 fake: a body material with the wound mask parameters (built by art/verse/gore). */
+ inline const TCHAR* WoundMaterialPath = TEXT("/Game/Verse/Test/WP05/M_Gore_TestBody.M_Gore_TestBody");
+
+ /** Proof folder of work-packages.md 0.4 for one sub-task. */
+ inline FString ProofDir(const TCHAR* SubTask)
+ {
+ return FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness/proof/WP05"), SubTask);
+ }
+
+ /**
+ * A bare game world with its subsystems and a physics scene, gore forced on (tests run under
+ * -nullrhi). Bodies are pawns with a skeletal mesh; the resolver maps ids to them.
+ */
+ struct FWorld
+ {
+ UWorld* World = nullptr;
+ UVerseGoreSubsystem* Gore = nullptr;
+ UVerseEventHub* Hub = nullptr;
+ TMap<int32, TWeakObjectPtr<USkeletalMeshComponent>> Bodies;
+
+ explicit FWorld(bool bForceGore = true, const TCHAR* Name = TEXT("VerseGoreTestWorld"))
+ {
+ World = UWorld::CreateWorld(EWorldType::Game, false, MakeUniqueObjectName(nullptr, UWorld::StaticClass(), Name));
+ if (World)
+ {
+ // A context, so the world can tick (UWorld::Tick looks its context up).
+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);
+ Context.SetCurrentWorld(World);
+ }
+ Gore = World ? World->GetSubsystem<UVerseGoreSubsystem>() : nullptr;
+ Hub = World ? World->GetSubsystem<UVerseEventHub>() : nullptr;
+ if (Gore)
+ {
+ Gore->SetForceActive(bForceGore);
+ Gore->SetGoreLevel(EVerseGoreLevel::Full);
+ Gore->SetVictimResolver([this](int32 Id) -> USkeletalMeshComponent*
+ {
+ const TWeakObjectPtr<USkeletalMeshComponent>* Found = Bodies.Find(Id);
+ return Found ? Found->Get() : nullptr;
+ });
+ }
+ }
+
+ ~FWorld()
+ {
+ if (Gore)
+ {
+ Gore->SetVictimResolver(nullptr);
+ }
+ if (World)
+ {
+ GEngine->DestroyWorldContext(World);
+ World->DestroyWorld(false);
+ }
+ }
+
+ bool IsValid() const { return World && Gore && Hub; }
+
+ /** A blocking box: centre and size in cm. */
+ AStaticMeshActor* AddBox(const FVector& Centre, const FVector& SizeCm)
+ {
+ UStaticMesh* Cube = LoadObject<UStaticMesh>(nullptr, CubePath);
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AStaticMeshActor* Actor = World->SpawnActor<AStaticMeshActor>(AStaticMeshActor::StaticClass(), FTransform(Centre), Params);
+ UStaticMeshComponent* Component = Actor->GetStaticMeshComponent();
+ Component->SetMobility(EComponentMobility::Movable);
+ Component->SetStaticMesh(Cube);
+ Component->SetWorldScale3D(SizeCm / 100.0);
+ Component->SetCollisionProfileName(TEXT("BlockAll"));
+ Component->RecreatePhysicsState();
+ Settle();
+ return Actor;
+ }
+
+ /** Floor top at z = 0 and a wall whose face looks down -X at x = WallX. */
+ void AddRoom(double WallX = 150.0)
+ {
+ AddBox(FVector(0.0, 0.0, -10.0), FVector(2000.0, 2000.0, 20.0));
+ AddBox(FVector(WallX + 10.0, 0.0, 200.0), FVector(20.0, 2000.0, 400.0));
+ }
+
+ /** A body standing on the floor point `Feet`; its id resolves to its mesh. */
+ USkeletalMeshComponent* AddBody(int32 Id, const FVector& Feet, UMaterialInterface* Override = nullptr)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ APawn* Pawn = World->SpawnActor<APawn>(APawn::StaticClass(), FTransform(Feet), Params);
+ USkeletalMeshComponent* Mesh = NewObject<USkeletalMeshComponent>(Pawn, TEXT("Body"));
+ Mesh->SetMobility(EComponentMobility::Movable);
+ Mesh->SetSkeletalMeshAsset(LoadObject<USkeletalMesh>(nullptr, TestHumanPath));
+ Pawn->SetRootComponent(Mesh);
+ Mesh->RegisterComponent();
+ Mesh->SetWorldLocation(Feet);
+ if (Override)
+ {
+ for (int32 Slot = 0; Slot < FMath::Max(1, Mesh->GetNumMaterials()); ++Slot)
+ {
+ Mesh->SetMaterial(Slot, Override);
+ }
+ }
+ Bodies.Add(Id, Mesh);
+ Settle();
+ return Mesh;
+ }
+
+ /** One world tick so new bodies and boxes are in the physics query structure. */
+ void Settle()
+ {
+ if (World && World->bIsWorldInitialized)
+ {
+ World->Tick(LEVELTICK_All, 1.f / 60.f);
+ }
+ }
+
+ /** Steps gore time in fixed frames. */
+ void Advance(double Seconds, double Step = 1.0 / 60.0)
+ {
+ for (double T = 0.0; T < Seconds - 1e-9; T += Step)
+ {
+ Gore->AdvanceTime(float(FMath::Min(Step, Seconds - T)));
+ }
+ }
+ };
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTests.cpp b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTests.cpp
new file mode 100644
index 0000000000..5f4037eff5
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreTests.cpp
@@ -0,0 +1,651 @@
+#include "Misc/AutomationTest.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#include "Camera/PlayerCameraManager.h"
+#include "Components/DecalComponent.h"
+#include "Components/InstancedStaticMeshComponent.h"
+#include "GameFramework/PlayerController.h"
+#include "Gore/VerseGoreActor.h"
+#include "HAL/FileManager.h"
+#include "Materials/MaterialInstanceDynamic.h"
+#include "Misc/FileHelper.h"
+#include "Tests/Gore/VerseGoreTestWorld.h"
+#include "VerseCollision.h"
+#include "VerseRng.h"
+
+using namespace VerseGoreTest;
+
+namespace VerseGoreTestPrivate
+{
+ FVerseHitEvent Hit(EVerseHitZone Zone, const FVector& Feet, const FVector& Shooter, int32 Victim, uint16 Shot, float Damage = 30.f, bool bKill = false)
+ {
+ return FVerseGoreSyntheticStream::MakeHit(Zone, Feet, Shooter, 1, Victim, Damage, Shot, 0.f, bKill);
+ }
+
+ /** Droplet positions now (the material draws the same motion from the instance data). */
+ TArray<FVector> DropletPositions(const UVerseGoreSubsystem* Gore)
+ {
+ return Gore->GetDropletPositions();
+ }
+
+ UMaterialInstanceDynamic* BodyMid(USkeletalMeshComponent* Mesh)
+ {
+ for (int32 Slot = 0; Slot < Mesh->GetNumMaterials(); ++Slot)
+ {
+ if (UMaterialInstanceDynamic* Mid = Cast<UMaterialInstanceDynamic>(Mesh->GetMaterial(Slot)))
+ {
+ return Mid;
+ }
+ }
+ return nullptr;
+ }
+}
+
+using namespace VerseGoreTestPrivate;
+
+// WP05.1: the listener skips a process without a viewport, and binds when forced.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreListenerTest, "Verse.Gore.Listener.SkipsWithoutViewport", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreListenerTest::RunTest(const FString&)
+{
+ FWorld W(false);
+ if (!TestTrue(TEXT("world, hub and gore subsystem exist"), W.IsValid()))
+ {
+ return false;
+ }
+ const bool bCanRender = UVerseGoreSubsystem::ProcessCanShowGore();
+ TestEqual(TEXT("active only where the process can render"), W.Gore->IsActive(), bCanRender);
+ W.Hub->OnHit.Broadcast(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-500, 0, 150), 2, 1));
+ TestEqual(TEXT("hits handled follow the active flag"), W.Gore->GetBudget().HitsHandled, bCanRender ? 1 : 0);
+ if (!bCanRender)
+ {
+ TestNull(TEXT("no gore actor without a viewport"), W.Gore->GetGoreActor());
+ }
+
+ W.Gore->SetForceActive(true);
+ TestTrue(TEXT("forced on"), W.Gore->IsActive());
+ W.Hub->OnHit.Broadcast(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-500, 0, 150), 2, 2));
+ TestTrue(TEXT("forced gore handles hub hits"), W.Gore->GetBudget().HitsHandled >= 1);
+ TestNotNull(TEXT("gore actor spawned on demand"), W.Gore->GetGoreActor());
+ if (!bCanRender)
+ {
+ W.Gore->SetForceActive(false);
+ TestFalse(TEXT("unforced again"), W.Gore->IsActive());
+ TestEqual(TEXT("going inactive purges droplets"), W.Gore->GetBudget().Droplets, 0);
+ }
+ return true;
+}
+
+// WP05.1: synthetic streams are deterministic and shaped as the contract says.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreSyntheticTest, "Verse.Gore.Synthetic.Streams", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreSyntheticTest::RunTest(const FString&)
+{
+ FVerseGoreSyntheticParams Params;
+ Params.Kind = EVerseGoreSyntheticKind::Hits;
+ Params.Seed = 7;
+ const TArray<FVerseGoreSyntheticEvent> A = FVerseGoreSyntheticStream::Build(Params);
+ const TArray<FVerseGoreSyntheticEvent> B = FVerseGoreSyntheticStream::Build(Params);
+ TestEqual(TEXT("same seed, same length"), A.Num(), B.Num());
+ bool bSame = A.Num() == B.Num();
+ for (int32 I = 0; bSame && I < A.Num(); ++I)
+ {
+ bSame = A[I].Hit.Zone == B[I].Hit.Zone && FVector(A[I].Hit.ImpactWorld).Equals(B[I].Hit.ImpactWorld, 0.0)
+ && FVector(A[I].Hit.Direction).Equals(B[I].Hit.Direction, 0.0) && A[I].Time == B[I].Time;
+ }
+ TestTrue(TEXT("same seed, same events"), bSame);
+ Params.Seed = 8;
+ const TArray<FVerseGoreSyntheticEvent> C = FVerseGoreSyntheticStream::Build(Params);
+ bool bDiffer = false;
+ for (int32 I = 0; I < FMath::Min(A.Num(), C.Num()); ++I)
+ {
+ bDiffer |= A[I].Hit.Zone != C[I].Hit.Zone || !FVector(A[I].Hit.Direction).Equals(C[I].Hit.Direction, 1e-6);
+ }
+ TestTrue(TEXT("another seed, other events"), bDiffer);
+ for (const FVerseGoreSyntheticEvent& Event : A)
+ {
+ if (Event.Hit.Zone == EVerseHitZone::None || Event.Hit.Bone.IsNone() || Event.Hit.Damage <= 0.f)
+ {
+ AddError(TEXT("synthetic hit without zone, bone or damage"));
+ break;
+ }
+ }
+
+ Params.Kind = EVerseGoreSyntheticKind::Storm;
+ Params.DurationSeconds = 60.0;
+ TestEqual(TEXT("gore_storm is 30 hits/s for 60 s"), FVerseGoreSyntheticStream::Build(Params).Num(), 1800);
+
+ Params.Kind = EVerseGoreSyntheticKind::Finisher;
+ const TArray<FVerseGoreSyntheticEvent> F = FVerseGoreSyntheticStream::Build(Params);
+ int32 Phases = 0, Deaths = 0;
+ for (const FVerseGoreSyntheticEvent& Event : F)
+ {
+ if (Event.Type == FVerseGoreSyntheticEvent::EType::Finisher)
+ {
+ ++Phases;
+ if (Event.Finisher.Phase == EVerseFinisherPhase::Takedown)
+ {
+ TestEqual(TEXT("Takedown at 0.25 s"), Event.Time, 0.25);
+ }
+ if (Event.Finisher.Phase == EVerseFinisherPhase::Recover)
+ {
+ TestEqual(TEXT("Recover at 2.1 s"), Event.Time, 2.1);
+ }
+ }
+ Deaths += Event.Type == FVerseGoreSyntheticEvent::EType::Death ? 1 : 0;
+ }
+ TestEqual(TEXT("finisher stream phases"), Phases, 5);
+ TestEqual(TEXT("finisher stream death"), Deaths, 1);
+
+ // By default playback feeds only gore, never the hub's other consumers (combat-state.md 8).
+ FWorld W;
+ int32 HubHits = 0;
+ W.Hub->OnHit.AddLambda([&HubHits](const FVerseHitEvent&) { ++HubHits; });
+ Params.Kind = EVerseGoreSyntheticKind::Hits;
+ Params.DurationSeconds = 2.0;
+ Params.RatePerSecond = 5.0;
+ W.Gore->PlaySynthetic(Params);
+ W.Advance(2.5);
+ TestEqual(TEXT("default playback publishes nothing on the hub"), HubHits, 0);
+ TestEqual(TEXT("default playback reaches gore"), W.Gore->GetBudget().HitsHandled, 10);
+ TestFalse(TEXT("stream finished"), W.Gore->IsPlayingSynthetic());
+
+ // A test may publish on the hub, the path Combat's events take.
+ W.Gore->ResetBudget();
+ Params.bPublishOnHub = true;
+ W.Gore->PlaySynthetic(Params);
+ W.Advance(2.5);
+ TestEqual(TEXT("hub playback reaches the hub"), HubHits, 10);
+ TestEqual(TEXT("and gore"), W.Gore->GetBudget().HitsHandled, 10);
+ return true;
+}
+
+// WP05.2: bursts scale with zone and damage and fly along the bolt.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreBurstTest, "Verse.Gore.Burst.ZoneAndDirection", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreBurstTest::RunTest(const FString&)
+{
+ FWorld W;
+ const FVector Shooter(-800.0, 0.0, 150.0);
+ W.Gore->HandleHit(Hit(EVerseHitZone::Head, FVector::ZeroVector, Shooter, 2, 1, 60.f));
+ const int32 Head = W.Gore->GetBudget().DropletsSpawned;
+ W.Gore->Purge();
+ W.Gore->ResetBudget();
+ W.Gore->HandleHit(Hit(EVerseHitZone::Leg, FVector::ZeroVector, Shooter, 2, 2, 22.f));
+ const int32 Leg = W.Gore->GetBudget().DropletsSpawned;
+ TestTrue(FString::Printf(TEXT("head burst (%d) heavier than leg burst (%d)"), Head, Leg), Head > Leg && Leg > 0);
+ W.Gore->Purge();
+
+ const FVerseHitEvent Torso = Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, Shooter, 2, 3, 30.f);
+ W.Gore->HandleHit(Torso);
+ W.Advance(0.1);
+ const TArray<FVector> Positions = DropletPositions(W.Gore);
+ TestTrue(TEXT("droplets drawn as instances"), Positions.Num() > 0);
+ FVector Centroid = FVector::ZeroVector;
+ for (const FVector& P : Positions)
+ {
+ Centroid += P;
+ }
+ Centroid /= FMath::Max(1, Positions.Num());
+ const double Along = FVector::DotProduct((Centroid - FVector(Torso.ImpactWorld)).GetSafeNormal(), FVector(Torso.Direction));
+ TestTrue(FString::Printf(TEXT("spray follows the bolt (dot %.2f)"), Along), Along > 0.3);
+ W.Advance(1.0);
+ TestEqual(TEXT("droplets die out"), W.Gore->GetBudget().Droplets, 0);
+ return true;
+}
+
+// WP05.3: spatter lands on the wall behind the body and drips onto the floor.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreSpatterTest, "Verse.Gore.Spatter.WallAndFloor", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreSpatterTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ W.Gore->HandleHit(Hit(EVerseHitZone::Head, FVector::ZeroVector, FVector(-800.0, 0.0, 168.0), 2, 1, 60.f));
+ int32 OnWall = 0, OnFloor = 0;
+ for (const UDecalComponent* Decal : W.Gore->GetSpatterDecals())
+ {
+ const FVector L = Decal->GetComponentLocation();
+ if (FMath::IsNearlyEqual(L.X, 150.0, 2.0))
+ {
+ ++OnWall;
+ TestTrue(TEXT("wall decal projects into the wall"), Decal->GetForwardVector().X > 0.9);
+ }
+ else if (FMath::IsNearlyEqual(L.Z, 0.0, 2.0))
+ {
+ ++OnFloor;
+ TestTrue(TEXT("floor decal projects down"), Decal->GetForwardVector().Z < -0.9);
+ }
+ }
+ TestTrue(FString::Printf(TEXT("spatter on the wall (%d)"), OnWall), OnWall >= 1);
+ TestEqual(TEXT("one drip on the floor"), OnFloor, 1);
+
+ // No wall in range: no wall spatter.
+ FWorld Open;
+ Open.AddBox(FVector(0.0, 0.0, -10.0), FVector(2000.0, 2000.0, 20.0));
+ Open.Gore->HandleHit(Hit(EVerseHitZone::Head, FVector::ZeroVector, FVector(-800.0, 0.0, 168.0), 2, 1, 60.f));
+ TestTrue(TEXT("open floor: only floor decals"), Open.Gore->GetSpatterDecals().Num() >= 1);
+ for (const UDecalComponent* Decal : Open.Gore->GetSpatterDecals())
+ {
+ TestTrue(TEXT("every decal is on the floor"), FMath::IsNearlyEqual(Decal->GetComponentLocation().Z, 0.0, 2.0));
+ }
+ return true;
+}
+
+// WP05.3 / A5.4: the decal pool is capped and recycles oldest first.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreRecycleTest, "Verse.Gore.Spatter.Recycle", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreRecycleTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ const int32 Cap = W.Gore->GetTuning().MaxSpatterDecals;
+ TestEqual(TEXT("A5.4 cap"), Cap, 256);
+ UDecalComponent* First = nullptr;
+ uint16 Shot = 1;
+ while (W.Gore->GetBudget().DecalsSpawned < Cap)
+ {
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, Shot++));
+ if (!First && W.Gore->GetSpatterDecals().Num() > 0)
+ {
+ First = W.Gore->GetSpatterDecals()[0];
+ }
+ if (Shot > 2000)
+ {
+ break;
+ }
+ }
+ TestEqual(TEXT("ring filled to the cap"), W.Gore->GetBudget().SpatterDecals, Cap);
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, Shot++));
+ TestEqual(TEXT("never above the cap"), W.Gore->GetBudget().SpatterDecals, Cap);
+ TestTrue(TEXT("recycling counted"), W.Gore->GetBudget().DecalsRecycled > 0);
+ const TArray<UDecalComponent*> Ordered = W.Gore->GetSpatterDecals();
+ TestTrue(TEXT("the oldest decal was the first reused"), Ordered.Contains(First) && Ordered[0] != First);
+ for (int32 I = 0; I < 2000; ++I)
+ {
+ W.Gore->HandleHit(Hit(EVerseHitZone::Head, FVector::ZeroVector, FVector(-800.0, 0.0, 168.0), 2, Shot++, 60.f));
+ }
+ TestEqual(TEXT("peak stays at the cap"), W.Gore->GetBudget().PeakSpatterDecals, Cap);
+ return true;
+}
+
+// WP05.4: bone-space impacts become wound slots on the body material, 16 at most.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreWoundTest, "Verse.Gore.Wounds.MaskSlots", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreWoundTest::RunTest(const FString&)
+{
+ FWorld W;
+ UMaterialInterface* BodyMaterial = LoadObject<UMaterialInterface>(nullptr, WoundMaterialPath);
+ TestNotNull(TEXT("WP13 fake body material with wound parameters"), BodyMaterial);
+ USkeletalMeshComponent* Body = W.AddBody(2, FVector::ZeroVector, BodyMaterial);
+ if (!TestNotNull(TEXT("test human loaded"), Body->GetSkeletalMeshAsset()))
+ {
+ return false;
+ }
+ TArray<FVector> Expected;
+ for (int32 I = 0; I < 20; ++I)
+ {
+ FVerseHitEvent Event = Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, uint16(I + 1));
+ Event.ImpactBoneLocal = FVector_NetQuantize10(FVector(2.0 * I, 1.0, -3.0));
+ W.Gore->HandleHit(Event);
+ FVector RefPose;
+ TestTrue(TEXT("bone exists in the reference skeleton"),
+ UVerseGoreSubsystem::BoneLocalToRefPose(Body, Event.Bone, FVector(Event.ImpactBoneLocal), RefPose));
+ Expected.Add(RefPose);
+ }
+ const TArray<FVector4f> Wounds = W.Gore->GetWounds(Body);
+ TestEqual(TEXT("16 wounds per character at most"), Wounds.Num(), 16);
+ TestEqual(TEXT("four oldest recycled"), W.Gore->GetBudget().WoundsRecycled, 4);
+ for (int32 I = 0; I < Wounds.Num(); ++I)
+ {
+ TestTrue(FString::Printf(TEXT("wound %d is hit %d in reference pose"), I, I + 4),
+ FVector(Wounds[I].X, Wounds[I].Y, Wounds[I].Z).Equals(Expected[I + 4], 0.1));
+ TestTrue(TEXT("radius in range"), Wounds[I].W >= 2.5f && Wounds[I].W <= 6.f);
+ }
+ if (UMaterialInstanceDynamic* Mid = BodyMid(Body))
+ {
+ float Count = 0.f;
+ Mid->GetScalarParameterValue(VerseGoreParams::WoundCount, Count);
+ TestEqual(TEXT("material wound count"), Count, 16.f);
+ FLinearColor Newest;
+ Mid->GetVectorParameterValue(VerseGoreParams::WoundSlot(19 % 16), Newest);
+ TestTrue(TEXT("newest wound replaced the oldest slot"), FVector(Newest.R, Newest.G, Newest.B).Equals(Expected[19], 0.1));
+ FLinearColor Kept;
+ Mid->GetVectorParameterValue(VerseGoreParams::WoundSlot(5), Kept);
+ TestTrue(TEXT("other slots keep their wound"), FVector(Kept.R, Kept.G, Kept.B).Equals(Expected[5], 0.1));
+ }
+ else
+ {
+ AddError(TEXT("no dynamic material with wound parameters on the body"));
+ }
+
+ // Death with a respawn delay clears the body's wounds when it respawns.
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ Death.ServerTime = 10.f;
+ Death.RespawnAt = 13.f;
+ W.Gore->HandleDeath(Death);
+ W.Advance(2.9);
+ TestEqual(TEXT("wounds stay until respawn"), W.Gore->GetWounds(Body).Num(), 16);
+ W.Advance(0.2);
+ TestEqual(TEXT("respawn clears wounds"), W.Gore->GetWounds(Body).Num(), 0);
+ return true;
+}
+
+// WP05.5: pools grow over 4 s under the body and are capped at 16.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGorePoolTest, "Verse.Gore.Pools.Growth", VERSE_GORE_TEST_FLAGS)
+bool FVerseGorePoolTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddBox(FVector(0.0, 0.0, -10.0), FVector(4000.0, 4000.0, 20.0));
+ W.AddBody(2, FVector::ZeroVector);
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ W.Gore->HandleDeath(Death);
+ TArray<UDecalComponent*> Pools = W.Gore->GetPoolDecals();
+ if (!TestEqual(TEXT("one pool"), Pools.Num(), 1))
+ {
+ return false;
+ }
+ UDecalComponent* Pool = Pools[0];
+ TestTrue(TEXT("pool lies on the floor"), FMath::IsNearlyEqual(Pool->GetComponentLocation().Z, 0.0, 2.0));
+ auto Radius = [Pool]() { return Pool->DecalSize.Y * Pool->GetComponentScale().Y; };
+ const double Full = W.Gore->GetTuning().PoolRadiusCm;
+ TestTrue(TEXT("starts small"), Radius() < Full * 0.15);
+ W.Gore->HandleDeath(Death);
+ TestEqual(TEXT("a second death within 3 s is the same pool"), W.Gore->GetPoolDecals().Num(), 1);
+ W.Advance(2.0);
+ const double Mid = Radius();
+ TestTrue(FString::Printf(TEXT("half way at 2 s (%.1f cm)"), Mid), Mid > Full * 0.4 && Mid < Full * 0.95);
+ W.Advance(2.0);
+ TestTrue(FString::Printf(TEXT("full at 4 s (%.1f cm)"), Radius()), FMath::IsNearlyEqual(Radius(), Full, Full * 0.02));
+
+ for (int32 Id = 10; Id < 30; ++Id)
+ {
+ W.AddBody(Id, FVector(-1400.0 + 140.0 * (Id - 10), 400.0, 0.0));
+ Death.VictimId = Id;
+ W.Gore->HandleDeath(Death);
+ }
+ TestEqual(TEXT("16 pools at most"), W.Gore->GetPoolDecals().Num(), 16);
+ TestEqual(TEXT("oldest recycled"), W.Gore->GetBudget().PoolsRecycled, 5);
+ TestFalse(TEXT("the first pool was recycled first"), W.Gore->GetPoolDecals().Contains(Pool));
+ return true;
+}
+
+// WP05.6: the finisher bleeds on Takedown and Kill, with one pool.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreFinisherTest, "Verse.Gore.Finisher.Full", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreFinisherTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddBox(FVector(0.0, 0.0, -10.0), FVector(2000.0, 2000.0, 20.0));
+ USkeletalMeshComponent* Body = W.AddBody(2, FVector::ZeroVector);
+ FVerseGoreSyntheticParams Params;
+ Params.Kind = EVerseGoreSyntheticKind::Finisher;
+ Params.VictimId = 2;
+ W.Gore->PlaySynthetic(Params);
+ W.Advance(0.2);
+ TestEqual(TEXT("nothing before Takedown"), W.Gore->GetBudget().DropletsSpawned, 0);
+ W.Advance(0.1);
+ const int32 AfterTakedown = W.Gore->GetBudget().DropletsSpawned;
+ TestTrue(TEXT("Takedown bleeds"), AfterTakedown > 0);
+ W.Advance(1.55);
+ TestTrue(TEXT("Kill bleeds harder"), W.Gore->GetBudget().DropletsSpawned >= AfterTakedown + 40);
+ TestEqual(TEXT("throat wound"), W.Gore->GetWounds(Body).Num(), 1);
+ W.Advance(1.0);
+ TestEqual(TEXT("kill and death make one pool"), W.Gore->GetPoolDecals().Num(), 1);
+ TestFalse(TEXT("Full never cuts to black"), W.Gore->GetCutToBlack().Count > 0);
+ return true;
+}
+
+// WP05.7 / A5.5: Reduced leaves no blood; the finisher cuts to black from Takedown to Recover.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreReducedTest, "Verse.Gore.Reduced.NoBlood", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreReducedTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ USkeletalMeshComponent* Body = W.AddBody(2, FVector::ZeroVector, LoadObject<UMaterialInterface>(nullptr, WoundMaterialPath));
+ W.Gore->SetGoreLevel(EVerseGoreLevel::Reduced);
+ FVerseGoreSyntheticParams Params;
+ Params.Seed = 5;
+ Params.VictimId = 2;
+ Params.DurationSeconds = 1000.0 / 30.0 + 0.01;
+ Params.RatePerSecond = 30.0;
+ TArray<FVerseGoreSyntheticEvent> Events = FVerseGoreSyntheticStream::Build(Params);
+ Events.SetNum(1000);
+ for (const FVerseGoreSyntheticEvent& Event : Events)
+ {
+ W.Hub->OnHit.Broadcast(Event.Hit);
+ W.Gore->AdvanceTime(1.f / 30.f);
+ }
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ W.Hub->OnDeath.Broadcast(Death);
+ const FVerseGoreBudget& B = W.Gore->GetBudget();
+ TestEqual(TEXT("1,000 hits handled"), B.HitsHandled, 1000);
+ TestEqual(TEXT("0 blood decals"), B.DecalsSpawned, 0);
+ TestEqual(TEXT("0 pools"), W.Gore->GetPoolDecals().Num(), 0);
+ TestEqual(TEXT("0 blood particles"), B.DropletsSpawned, 0);
+ TestEqual(TEXT("0 wounds"), W.Gore->GetWounds(Body).Num(), 0);
+ TestEqual(TEXT("a neutral flash per hit"), B.FlashesSpawned, 1000);
+
+ // Cut to black, with a local viewer.
+ FActorSpawnParameters ViewerParams;
+ ViewerParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ APlayerController* Viewer = W.World->SpawnActor<APlayerController>(APlayerController::StaticClass(), FTransform::Identity, ViewerParams);
+ TestNotNull(TEXT("viewer spawned"), Viewer);
+ if (Viewer && !Viewer->PlayerCameraManager)
+ {
+ Viewer->SpawnPlayerCameraManager();
+ }
+ TestNotNull(TEXT("viewer with a camera manager"), Viewer ? Viewer->PlayerCameraManager.Get() : nullptr);
+ FVerseFinisherEvent Finisher;
+ Finisher.AttackerId = 1;
+ Finisher.VictimId = 2;
+ Finisher.Phase = EVerseFinisherPhase::Locked;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ TestFalse(TEXT("Locked does not cut yet"), W.Gore->GetCutToBlack().bActive);
+ Finisher.Phase = EVerseFinisherPhase::Takedown;
+ const uint64 TakedownFrame = GFrameCounter;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ TestTrue(TEXT("cut to black on Takedown"), W.Gore->GetCutToBlack().bActive);
+ TestTrue(TEXT("cut starts within 1 frame of Takedown"), W.Gore->GetCutToBlack().StartFrame - TakedownFrame <= 1);
+ if (Viewer && Viewer->PlayerCameraManager)
+ {
+ TestEqual(TEXT("viewer faded to black"), Viewer->PlayerCameraManager->FadeAmount, 1.f);
+ }
+ Finisher.Phase = EVerseFinisherPhase::Kill;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ TestEqual(TEXT("Kill draws nothing in Reduced"), W.Gore->GetBudget().DropletsSpawned, 0);
+ TestTrue(TEXT("still black through Kill"), W.Gore->GetCutToBlack().bActive);
+ Finisher.Phase = EVerseFinisherPhase::Recover;
+ const uint64 RecoverFrame = GFrameCounter;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ TestFalse(TEXT("cut ends on Recover"), W.Gore->GetCutToBlack().bActive);
+ TestTrue(TEXT("cut ends within 1 frame of Recover"), W.Gore->GetCutToBlack().EndFrame - RecoverFrame <= 1);
+ if (Viewer && Viewer->PlayerCameraManager)
+ {
+ TestFalse(TEXT("viewer fade released"), Viewer->PlayerCameraManager->bEnableFading);
+ }
+
+ // Aborted ends the cut too; a lost Recover times out.
+ Finisher.Phase = EVerseFinisherPhase::Takedown;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ Finisher.Phase = EVerseFinisherPhase::Aborted;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ TestFalse(TEXT("Aborted ends the cut"), W.Gore->GetCutToBlack().bActive);
+ Finisher.Phase = EVerseFinisherPhase::Takedown;
+ W.Hub->OnFinisher.Broadcast(Finisher);
+ W.Advance(4.5);
+ TestFalse(TEXT("timeout ends a cut without Recover"), W.Gore->GetCutToBlack().bActive);
+ return true;
+}
+
+// WP05.7: switching to Reduced live purges existing gore.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreLiveSwitchTest, "Verse.Gore.Reduced.LiveSwitchPurges", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreLiveSwitchTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ USkeletalMeshComponent* Body = W.AddBody(2, FVector::ZeroVector, LoadObject<UMaterialInterface>(nullptr, WoundMaterialPath));
+ for (uint16 Shot = 1; Shot <= 20; ++Shot)
+ {
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, Shot));
+ }
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ W.Gore->HandleDeath(Death);
+ TestTrue(TEXT("Full drew decals"), W.Gore->GetSpatterDecals().Num() > 0);
+ TestTrue(TEXT("Full drew a pool"), W.Gore->GetPoolDecals().Num() > 0);
+ TestTrue(TEXT("Full drew wounds"), W.Gore->GetWounds(Body).Num() > 0);
+ TestTrue(TEXT("Full drew droplets"), W.Gore->GetBudget().Droplets > 0);
+
+ W.Gore->SetGoreLevel(EVerseGoreLevel::Reduced);
+ TestEqual(TEXT("decals purged"), W.Gore->GetSpatterDecals().Num(), 0);
+ TestEqual(TEXT("pools purged"), W.Gore->GetPoolDecals().Num(), 0);
+ TestEqual(TEXT("wounds purged"), W.Gore->GetWounds(Body).Num(), 0);
+ TestEqual(TEXT("droplets purged"), W.Gore->GetBudget().Droplets, 0);
+ TestEqual(TEXT("no droplet instances left"), W.Gore->GetGoreActor()->Droplets->GetInstanceCount(), 0);
+ if (UMaterialInstanceDynamic* Mid = BodyMid(Body))
+ {
+ float Count = -1.f;
+ Mid->GetScalarParameterValue(VerseGoreParams::WoundCount, Count);
+ TestEqual(TEXT("body material wound count reset"), Count, 0.f);
+ }
+ W.Gore->SetGoreLevel(EVerseGoreLevel::Full);
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, 99));
+ TestTrue(TEXT("Full again draws again"), W.Gore->GetSpatterDecals().Num() > 0);
+ return true;
+}
+
+// A5.3: 1,000 traces on every channel through decals, pools and blood particles hit nothing of gore.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreNoCollisionTest, "Verse.Gore.NoCollision", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreNoCollisionTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ for (int32 Id = 2; Id < 6; ++Id)
+ {
+ W.AddBody(Id, FVector(-60.0 * Id, 80.0 * (Id - 3), 0.0));
+ }
+ uint16 Shot = 1;
+ for (int32 Id = 2; Id < 6; ++Id)
+ {
+ for (int32 I = 0; I < 12; ++I)
+ {
+ const EVerseHitZone Zone = EVerseHitZone(1 + (I % 6));
+ W.Gore->HandleHit(Hit(Zone, FVector(-60.0 * Id, 80.0 * (Id - 3), 0.0), FVector(-900.0, 0.0, 150.0), Id, Shot++, 35.f));
+ }
+ FVerseDeathEvent Death;
+ Death.VictimId = Id;
+ W.Gore->HandleDeath(Death);
+ }
+ W.Advance(0.12);
+
+ TArray<FVector> Points;
+ for (const UDecalComponent* Decal : W.Gore->GetSpatterDecals())
+ {
+ Points.Add(Decal->GetComponentLocation());
+ }
+ for (const UDecalComponent* Decal : W.Gore->GetPoolDecals())
+ {
+ Points.Add(Decal->GetComponentLocation());
+ }
+ Points.Append(DropletPositions(W.Gore));
+ TestTrue(FString::Printf(TEXT("gore to probe (%d points)"), Points.Num()), Points.Num() > 50);
+ AVerseGoreActor* Actor = W.Gore->GetGoreActor();
+ if (!TestNotNull(TEXT("gore actor"), Actor) || Points.Num() == 0)
+ {
+ return false;
+ }
+ TestFalse(TEXT("gore actor never replicates"), Actor->GetIsReplicated());
+ TInlineComponentArray<UPrimitiveComponent*> Primitives(Actor);
+ for (const UPrimitiveComponent* Primitive : Primitives)
+ {
+ TestEqual(FString::Printf(TEXT("%s has no collision"), *Primitive->GetName()), Primitive->GetCollisionEnabled(), ECollisionEnabled::NoCollision);
+ }
+
+ FVerseRng Rng(42);
+ int32 GoreHits = 0, Traces = 0;
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseGoreNoCollisionTest), true);
+ for (int32 I = 0; I < 1000; ++I)
+ {
+ const FVector Point = Points[I % Points.Num()];
+ const FVector Dir = Rng.UnitVector();
+ for (int32 Channel = 0; Channel < int32(ECC_OverlapAll_Deprecated); ++Channel)
+ {
+ FHitResult HitResult;
+ ++Traces;
+ if (W.World->LineTraceSingleByChannel(HitResult, Point - Dir * 60.0, Point + Dir * 60.0, ECollisionChannel(Channel), Params)
+ && HitResult.GetActor() == Actor)
+ {
+ ++GoreHits;
+ }
+ }
+ }
+ TestEqual(FString::Printf(TEXT("%d traces on every channel hit gore"), Traces), GoreHits, 0);
+ TestTrue(TEXT("sight and bolt channels included"), int32(VerseCollision::Sight) < int32(ECC_OverlapAll_Deprecated)
+ && int32(VerseCollision::Bolt) < int32(ECC_OverlapAll_Deprecated));
+ return true;
+}
+
+// Every asset gore loads by path resolves, and gore picks up its look. Runs in the editor and in
+// cooked builds (WP22 smoke), where a gore folder left out of the cook would show up here.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreAssetsTest, "Verse.Gore.Assets.Resolve", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreAssetsTest::RunTest(const FString&)
+{
+ for (const FString& Path : UVerseGoreSubsystem::RuntimeAssetPaths())
+ {
+ TestNotNull(FString::Printf(TEXT("%s resolves"), *Path), StaticLoadObject(UObject::StaticClass(), nullptr, *Path));
+ }
+ FWorld W;
+ W.AddRoom(150.0);
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, 1));
+ TestTrue(TEXT("gore materials loaded (gore is drawn, not only counted)"), W.Gore->HasLook());
+ const AVerseGoreActor* Actor = W.Gore->GetGoreActor();
+ TestTrue(TEXT("droplet instances carry the material's custom data"), Actor && Actor->Droplets->NumCustomDataFloats == UVerseGoreSubsystem::DropletCustomFloats);
+ return true;
+}
+
+// A5.4: gore_storm (30 hits/s for 60 s) stays inside the caps and the game-thread budget.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreBudgetTest, "Verse.Gore.Budget.Storm", VERSE_GORE_TEST_FLAGS)
+bool FVerseGoreBudgetTest::RunTest(const FString&)
+{
+ FWorld W;
+ W.AddRoom(150.0);
+ W.AddBody(2, FVector::ZeroVector, LoadObject<UMaterialInterface>(nullptr, WoundMaterialPath));
+ for (int32 Id = 10; Id < 30; ++Id)
+ {
+ W.AddBody(Id, FVector(-120.0 * (Id - 9), 300.0, 0.0));
+ }
+ // Warm-up hit: the first decal creation and asset loads are not part of the steady budget.
+ W.Gore->HandleHit(Hit(EVerseHitZone::UpperTorso, FVector::ZeroVector, FVector(-800.0, 0.0, 132.0), 2, 60000));
+ W.Gore->ResetBudget();
+
+ FVerseGoreSyntheticParams Params;
+ Params.Kind = EVerseGoreSyntheticKind::Storm;
+ Params.DurationSeconds = 60.0;
+ Params.VictimId = 2;
+ Params.Seed = 11;
+ W.Gore->PlaySynthetic(Params);
+ FVerseDeathEvent Death;
+ for (int32 Frame = 0; Frame < 60 * 61; ++Frame)
+ {
+ W.Gore->AdvanceTime(1.f / 60.f);
+ if (Frame % 150 == 0)
+ {
+ Death.VictimId = 10 + (Frame / 150) % 20; // a death every 2.5 s on another body
+ W.Hub->OnDeath.Broadcast(Death);
+ }
+ }
+ const FVerseGoreBudget& B = W.Gore->GetBudget();
+ TestEqual(TEXT("1,800 storm hits"), B.HitsHandled, 1800);
+ TestTrue(FString::Printf(TEXT("spatter decals peak %d <= 256"), B.PeakSpatterDecals), B.PeakSpatterDecals <= 256 && B.PeakSpatterDecals > 0);
+ TestTrue(FString::Printf(TEXT("pools peak %d <= 16"), B.PeakPools), B.PeakPools <= 16 && B.PeakPools > 0);
+ TestTrue(FString::Printf(TEXT("wounds peak %d <= 16"), B.PeakWoundsOnOneCharacter), B.PeakWoundsOnOneCharacter <= 16 && B.PeakWoundsOnOneCharacter > 0);
+ // All gore game-thread time (hits, deaths, ticks) over the storm, per hit handled.
+ TestTrue(FString::Printf(TEXT("game thread per hit %.4f ms (hits %.1f + events %.1f + ticks %.1f ms over %d hits) <= 0.05 ms"),
+ B.GameThreadPerHitMs, B.HitTotalMs, B.OtherEventTotalMs, B.TickTotalMs, B.HitsHandled), B.GameThreadPerHitMs <= 0.05);
+ TestTrue(TEXT("per-hit figure covers the ticks"), B.Ticks > 0 && B.GameThreadTotalMs >= B.HitTotalMs + B.TickTotalMs - 1e-9);
+
+ const FString Dir = ProofDir(TEXT("5.8"));
+ IFileManager::Get().MakeDirectory(*Dir, true);
+ TestTrue(TEXT("budget JSON written"), W.Gore->WriteBudgetJson(FPaths::Combine(Dir, TEXT("budget_gore_storm_nullrhi.json"))));
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreVisualTest.cpp b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreVisualTest.cpp
new file mode 100644
index 0000000000..bb12a8f15e
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Private/Tests/Gore/VerseGoreVisualTest.cpp
@@ -0,0 +1,525 @@
+#include "Misc/AutomationTest.h"
+
+#if WITH_DEV_AUTOMATION_TESTS && WITH_EDITOR
+
+#include "Camera/CameraActor.h"
+#include "Camera/CameraComponent.h"
+#include "Components/DirectionalLightComponent.h"
+#include "Components/PointLightComponent.h"
+#include "Engine/DirectionalLight.h"
+#include "Engine/GameViewportClient.h"
+#include "Engine/PointLight.h"
+#include "GameFramework/PlayerController.h"
+#include "Gore/VerseGoreActor.h"
+#include "HAL/FileManager.h"
+#include "HAL/IConsoleManager.h"
+#include "Misc/App.h"
+#include "Misc/FileHelper.h"
+#include "ShaderCompiler.h"
+#include "Tests/Gore/VerseGoreTestWorld.h"
+#include "UnrealClient.h"
+
+// Verse.Visual.Gore.Pairs: Full vs Reduced screenshot pairs of a body hit, a wall spatter, a pool
+// and a finisher (WP05 evidence), and the GPU cost of gore_storm at 1440p (A5.4). Runs only in a
+// rendered `-game` process of the editor binary (scripts/unreal/screenshot.py --suite Verse.Visual.Gore);
+// editor-only APIs (material compile errors, shader compile flush) keep it out of game builds.
+
+namespace VerseGoreVisual
+{
+ using namespace VerseGoreTest;
+
+ /** Scene far from the default pawn and the entry map's origin. */
+ const FVector Base(0.0, 20000.0, 0.0);
+
+ struct FState
+ {
+ UWorld* World = nullptr;
+ UVerseGoreSubsystem* Gore = nullptr;
+ UVerseEventHub* Hub = nullptr;
+ ACameraActor* Camera = nullptr;
+ TMap<int32, TWeakObjectPtr<USkeletalMeshComponent>> Bodies;
+ TArray<AActor*> Spawned;
+ FString Dir;
+ int32 Frames = 0;
+ TArray<double> GpuMs;
+ /** Median GPU frame time of each phase, in order; key = gore shown. */
+ TArray<TPair<bool, double>> Phases;
+ int32 PhaseFrame = 0;
+ int32 StormFrames = 0;
+ bool bShown = true;
+ uint16 Shot = 1;
+ int32 Shots = 0;
+ };
+ using FStateRef = TSharedRef<FState>;
+
+ UWorld* GameWorld()
+ {
+ for (const FWorldContext& Context : GEngine->GetWorldContexts())
+ {
+ if ((Context.WorldType == EWorldType::Game || Context.WorldType == EWorldType::PIE) && Context.World())
+ {
+ return Context.World();
+ }
+ }
+ return nullptr;
+ }
+
+ template <typename T>
+ T* Spawn(FState& S, const FTransform& Transform)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ T* Actor = S.World->SpawnActor<T>(T::StaticClass(), Transform, Params);
+ S.Spawned.Add(Actor);
+ return Actor;
+ }
+
+ void Box(FState& S, const FVector& Centre, const FVector& Size)
+ {
+ AStaticMeshActor* Actor = Spawn<AStaticMeshActor>(S, FTransform(Base + Centre));
+ UStaticMeshComponent* Component = Actor->GetStaticMeshComponent();
+ Component->SetMobility(EComponentMobility::Movable);
+ Component->SetStaticMesh(LoadObject<UStaticMesh>(nullptr, CubePath));
+ Component->SetWorldScale3D(Size / 100.0);
+ Component->SetCollisionProfileName(TEXT("BlockAll"));
+ }
+
+ USkeletalMeshComponent* Body(FState& S, int32 Id, const FVector& Feet, float Yaw)
+ {
+ APawn* Pawn = Spawn<APawn>(S, FTransform(FRotator(0.f, Yaw, 0.f), Base + Feet));
+ USkeletalMeshComponent* Mesh = NewObject<USkeletalMeshComponent>(Pawn, TEXT("Body"));
+ Mesh->SetMobility(EComponentMobility::Movable);
+ Mesh->SetSkeletalMeshAsset(LoadObject<USkeletalMesh>(nullptr, TestHumanPath));
+ Pawn->SetRootComponent(Mesh);
+ Mesh->RegisterComponent();
+ Mesh->SetWorldLocationAndRotation(Base + Feet, FRotator(0.f, Yaw, 0.f));
+ if (UMaterialInterface* Material = LoadObject<UMaterialInterface>(nullptr, WoundMaterialPath))
+ {
+ for (int32 Slot = 0; Slot < FMath::Max(1, Mesh->GetNumMaterials()); ++Slot)
+ {
+ Mesh->SetMaterial(Slot, Material);
+ }
+ }
+ S.Bodies.Add(Id, Mesh);
+ return Mesh;
+ }
+
+ void Look(FState& S, const FVector& From, const FVector& At)
+ {
+ S.Camera->SetActorLocationAndRotation(Base + From, (At - From).Rotation());
+ if (APlayerController* Controller = S.World->GetFirstPlayerController())
+ {
+ Controller->SetViewTarget(S.Camera);
+ }
+ }
+
+ void Setup(FState& S)
+ {
+ S.World = GameWorld();
+ S.Gore = UVerseGoreSubsystem::Get(S.World);
+ S.Hub = UVerseEventHub::Get(S.World);
+ if (!S.Gore || !S.Hub)
+ {
+ return;
+ }
+ // Floor, back wall at x = 150, a side wall for the finisher.
+ Box(S, FVector(0.0, 0.0, -10.0), FVector(3000.0, 3000.0, 20.0));
+ Box(S, FVector(160.0, 0.0, 200.0), FVector(20.0, 3000.0, 400.0));
+ ADirectionalLight* Sun = Spawn<ADirectionalLight>(S, FTransform(FRotator(-55.f, 35.f, 0.f), Base));
+ Sun->GetComponent()->SetMobility(EComponentMobility::Movable);
+ Sun->GetComponent()->SetIntensity(5.f);
+ APointLight* Lamp = Spawn<APointLight>(S, FTransform(Base + FVector(-150.0, -120.0, 260.0)));
+ Lamp->PointLightComponent->SetMobility(EComponentMobility::Movable);
+ Lamp->PointLightComponent->SetIntensity(9000.f);
+ Lamp->PointLightComponent->SetAttenuationRadius(1500.f);
+ Lamp->PointLightComponent->SetLightColor(FLinearColor(1.f, 0.82f, 0.6f));
+ S.Camera = Spawn<ACameraActor>(S, FTransform(Base));
+ UCameraComponent* Cam = S.Camera->GetCameraComponent();
+ Cam->SetFieldOfView(60.f);
+ Cam->PostProcessSettings.bOverride_AutoExposureMethod = true;
+ Cam->PostProcessSettings.AutoExposureMethod = AEM_Manual;
+ Cam->PostProcessSettings.bOverride_AutoExposureApplyPhysicalCameraExposure = true;
+ Cam->PostProcessSettings.AutoExposureApplyPhysicalCameraExposure = 0;
+ Cam->PostProcessSettings.bOverride_AutoExposureBias = true;
+ Cam->PostProcessSettings.AutoExposureBias = 0.5f;
+ Cam->PostProcessBlendWeight = 1.f;
+ Body(S, 2, FVector::ZeroVector, 180.f);
+ S.Gore->SetVictimResolver([&Bodies = S.Bodies](int32 Id) -> USkeletalMeshComponent*
+ {
+ const TWeakObjectPtr<USkeletalMeshComponent>* Found = Bodies.Find(Id);
+ return Found ? Found->Get() : nullptr;
+ });
+ S.Gore->SetGoreLevel(EVerseGoreLevel::Full);
+ S.Gore->Purge();
+ S.Dir = ProofDir(TEXT("visual"));
+ IFileManager::Get().MakeDirectory(*S.Dir, true);
+ }
+
+ FVerseHitEvent HitOn(FState& S, EVerseHitZone Zone, float Damage, bool bKill = false)
+ {
+ FVerseHitEvent Hit = FVerseGoreSyntheticStream::MakeHit(Zone, Base, Base + FVector(-900.0, -60.0, 160.0), 1, 2, Damage, S.Shot, 0.f, bKill);
+ ++S.Shot;
+ return Hit;
+ }
+
+ /** Raw GPU frame time of the last frame, ms ("stat unit" keeps it updated; no RHI link needed). */
+ double GpuFrameMs()
+ {
+ const FStatUnitData* Data = GEngine->GameViewport ? GEngine->GameViewport->GetStatUnitData() : nullptr;
+ return Data ? double(Data->RawGPUFrameTime[0]) : 0.0;
+ }
+
+ /** Frames per shown or hidden phase of the GPU measurement, and frames skipped after a switch. */
+ constexpr int32 GpuPhaseFrames = 60;
+ constexpr int32 GpuSettleFrames = 10;
+
+ /** Shows or hides every gore primitive (decals, pools, droplets); the work behind them goes on. */
+ void SetGoreShown(FState& S, bool bShown)
+ {
+ if (AVerseGoreActor* Actor = S.Gore ? S.Gore->GetGoreActor() : nullptr)
+ {
+ Actor->SetActorHiddenInGame(!bShown);
+ if (USceneComponent* Root = Actor->GetRootComponent())
+ {
+ Root->SetVisibility(bShown, true);
+ }
+ }
+ }
+
+ struct FGpuResult
+ {
+ TArray<double> Diffs;
+ double Mean = 0.0;
+ double Half = 0.0;
+ };
+
+ /** Shown phase minus the mean of its hidden neighbours; mean and 95 % half width (Student t). */
+ FGpuResult Evaluate(const TArray<TPair<bool, double>>& Phases)
+ {
+ FGpuResult R;
+ for (int32 I = 1; I + 1 < Phases.Num(); ++I)
+ {
+ if (Phases[I].Key && !Phases[I - 1].Key && !Phases[I + 1].Key)
+ {
+ R.Diffs.Add(Phases[I].Value - 0.5 * (Phases[I - 1].Value + Phases[I + 1].Value));
+ }
+ }
+ const int32 N = R.Diffs.Num();
+ if (N < 2)
+ {
+ R.Half = TNumericLimits<double>::Max();
+ return R;
+ }
+ for (const double D : R.Diffs)
+ {
+ R.Mean += D / N;
+ }
+ double Var = 0.0;
+ for (const double D : R.Diffs)
+ {
+ Var += FMath::Square(D - R.Mean) / (N - 1);
+ }
+ // t(0.975, N-1) ~ 1.96 + 2.5 / (N-1): 2.46 at 5, 2.14 at 14 degrees of freedom.
+ R.Half = (1.96 + 2.5 / (N - 1)) * FMath::Sqrt(Var / N);
+ return R;
+ }
+
+ void Shoot(FState& S, const TCHAR* Name)
+ {
+ const FString Path = FPaths::Combine(S.Dir, FString::Printf(TEXT("%s_%s.png"), Name,
+ S.Gore->GetGoreLevel() == EVerseGoreLevel::Full ? TEXT("full") : TEXT("reduced")));
+ FScreenshotRequest::RequestScreenshot(Path, false, false);
+ ++S.Shots;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreVisualPairs, "Verse.Visual.Gore.Pairs",
+ EAutomationTestFlags::ClientContext | EAutomationTestFlags::EngineFilter)
+bool FVerseGoreVisualPairs::RunTest(const FString&)
+{
+ using namespace VerseGoreVisual;
+ if (!FApp::CanEverRender())
+ {
+ AddInfo(TEXT("no RHI: visual gore pairs need a rendered -game run (screenshot.py)"));
+ return true;
+ }
+ FStateRef S = MakeShared<FState>();
+ Setup(*S);
+ if (!TestNotNull(TEXT("gore in the game world"), S->Gore) || !S->Hub)
+ {
+ return false;
+ }
+ TestTrue(TEXT("gore active in a rendered process"), S->Gore->IsActive());
+
+ auto Wait = [this](int32 Frames)
+ {
+ TSharedRef<int32> Count = MakeShared<int32>(0);
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([Count, Frames]() { return ++(*Count) >= Frames; }));
+ };
+ auto Do = [this](TFunction<void()> Step)
+ {
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([Step]() { Step(); return true; }));
+ };
+
+ // One warm-up hit loads every gore material; shaders and streaming settle before the first shot.
+ Do([S]()
+ {
+ // Enough hits to use every spatter instance; they stay on screen while textures upload.
+ for (int32 I = 0; I < 12; ++I)
+ {
+ S->Gore->HandleHit(HitOn(*S, I % 2 ? EVerseHitZone::Head : EVerseHitZone::UpperTorso, 45.f));
+ }
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ S->Hub->OnDeath.Broadcast(Death);
+ Look(*S, FVector(-260.0, -170.0, 150.0), FVector(0.0, 0.0, 120.0));
+ });
+ Wait(60);
+ Do([S]()
+ {
+ S->Gore->SetGoreLevel(EVerseGoreLevel::Reduced);
+ S->Gore->HandleHit(HitOn(*S, EVerseHitZone::UpperTorso, 45.f));
+ S->Gore->SetGoreLevel(EVerseGoreLevel::Full);
+ });
+ Wait(30);
+ Do([]()
+ {
+ if (GShaderCompilingManager)
+ {
+ GShaderCompilingManager->FinishAllCompilation();
+ }
+ });
+ Wait(90);
+ for (const EVerseGoreLevel Level : {EVerseGoreLevel::Full, EVerseGoreLevel::Reduced})
+ {
+ Do([S, Level]() { S->Gore->Purge(); S->Gore->SetGoreLevel(Level); Look(*S, FVector(-260.0, -170.0, 150.0), FVector(0.0, 0.0, 120.0)); });
+ Wait(10);
+ // Body hit: droplets in the air.
+ Do([S]() { S->Gore->HandleHit(HitOn(*S, EVerseHitZone::UpperTorso, 45.f)); S->Gore->HandleHit(HitOn(*S, EVerseHitZone::Head, 60.f)); });
+ Wait(6);
+ Do([S]() { Shoot(*S, TEXT("body_hit")); });
+ Wait(6);
+ // Wall spatter after the droplets settle.
+ Do([S]()
+ {
+ for (int32 I = 0; I < 6; ++I)
+ {
+ S->Gore->HandleHit(HitOn(*S, I % 2 ? EVerseHitZone::Head : EVerseHitZone::UpperTorso, 55.f));
+ }
+ Look(*S, FVector(-180.0, 60.0, 150.0), FVector(150.0, 0.0, 150.0));
+ });
+ Wait(40);
+ Do([S]() { Shoot(*S, TEXT("wall_spatter")); });
+ Wait(6);
+ // Pool after 4 s of growth.
+ Do([S]()
+ {
+ FVerseDeathEvent Death;
+ Death.VictimId = 2;
+ S->Hub->OnDeath.Broadcast(Death);
+ Look(*S, FVector(-220.0, -120.0, 230.0), FVector(0.0, 0.0, 0.0));
+ });
+ Wait(130);
+ Do([S]() { Shoot(*S, TEXT("pool")); });
+ Wait(6);
+ // Finisher: shot just after Kill (Full) / inside the cut to black (Reduced).
+ Do([S]()
+ {
+ S->Gore->Purge();
+ FVerseGoreSyntheticParams Params;
+ Params.Kind = EVerseGoreSyntheticKind::Finisher;
+ Params.VictimId = 2;
+ Params.VictimLocation = Base;
+ S->Gore->PlaySynthetic(Params);
+ Look(*S, FVector(-150.0, -200.0, 170.0), FVector(0.0, 0.0, 110.0));
+ });
+ Wait(57);
+ Do([S]() { Shoot(*S, TEXT("finisher")); });
+ Wait(30);
+ }
+ Do([this, S]()
+ {
+ TestEqual(TEXT("eight screenshots requested"), S->Shots, 8);
+ TestFalse(TEXT("cut to black released after Recover"), S->Gore->GetCutToBlack().bActive);
+ TestTrue(TEXT("Reduced finisher cut to black once"), S->Gore->GetCutToBlack().Count >= 1);
+ });
+
+ // GPU cost of gore_storm at 1440p (A5.4). The storm plays as the row defines it, 30 hits/s for
+ // 60 s, on a fixed 30 Hz step. Gore is shown and hidden in alternating phases; each shown phase
+ // is compared with the mean of the hidden phases on both sides of it, which cancels slow drift
+ // of the shared GPU. The per-pair differences give a mean and a 95 % confidence bound: the test
+ // passes when the upper bound is within 0.3 ms, and fails when the bound is implausible (gore
+ // cheaper than no gore beyond the noise) or too wide to say anything.
+ Do([S]()
+ {
+ if (IConsoleVariable* VSync = IConsoleManager::Get().FindConsoleVariable(TEXT("r.VSync")))
+ {
+ VSync->Set(0);
+ }
+ GEngine->Exec(S->World, TEXT("r.SetRes 2560x1440w"));
+ GEngine->Exec(S->World, TEXT("stat unit"));
+ S->Gore->Purge();
+ S->Gore->SetGoreLevel(EVerseGoreLevel::Full);
+ Look(*S, FVector(-300.0, -40.0, 160.0), FVector(150.0, 0.0, 100.0));
+ // Start at the caps: 256 spatter decals in view, 16 pools, 16 wounds.
+ for (int32 I = 0; I < 220; ++I)
+ {
+ S->Gore->HandleHit(HitOn(*S, EVerseHitZone(1 + I % 6), 55.f));
+ }
+ for (int32 Id = 10; Id < 26; ++Id)
+ {
+ Body(*S, Id, FVector(-60.0 - 25.0 * (Id - 10), -200.0 + 25.0 * (Id - 10), 0.0), 0.f);
+ FVerseDeathEvent Death;
+ Death.VictimId = Id;
+ S->Gore->HandleDeath(Death);
+ }
+ });
+ Wait(60);
+ Do([S]()
+ {
+ FApp::SetUseFixedTimeStep(true);
+ FApp::SetFixedDeltaTime(1.0 / 30.0);
+ S->Gore->ResetBudget();
+ FVerseGoreSyntheticParams Params;
+ Params.Kind = EVerseGoreSyntheticKind::Storm;
+ Params.DurationSeconds = 60.0;
+ Params.Seed = 11;
+ Params.VictimId = 2;
+ Params.VictimLocation = Base;
+ Params.ShooterLocation = Base + FVector(-900.0, -60.0, 160.0);
+ S->Gore->PlaySynthetic(Params);
+ S->GpuMs.Reset();
+ S->Phases.Reset();
+ S->PhaseFrame = 0;
+ S->bShown = false;
+ S->StormFrames = 0;
+ SetGoreShown(*S, false);
+ });
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([S]()
+ {
+ const bool bDone = !S->Gore->IsPlayingSynthetic();
+ ++S->StormFrames;
+ ++S->PhaseFrame;
+ if (S->PhaseFrame > GpuSettleFrames)
+ {
+ S->GpuMs.Add(GpuFrameMs());
+ }
+ if (S->PhaseFrame >= GpuPhaseFrames || bDone)
+ {
+ if (S->GpuMs.Num() >= 20)
+ {
+ S->GpuMs.Sort();
+ S->Phases.Add({S->bShown, S->GpuMs[S->GpuMs.Num() / 2]});
+ }
+ S->GpuMs.Reset();
+ S->PhaseFrame = 0;
+ S->bShown = !S->bShown;
+ SetGoreShown(*S, S->bShown);
+ }
+ return bDone;
+ }));
+ Do([this, S]()
+ {
+ FApp::SetUseFixedTimeStep(false);
+ SetGoreShown(*S, true);
+ const FGpuResult R = Evaluate(S->Phases);
+ const FVerseGoreBudget& B = S->Gore->GetBudget();
+ const FIntPoint Size = GEngine->GameViewport && GEngine->GameViewport->Viewport ? GEngine->GameViewport->Viewport->GetSizeXY() : FIntPoint::ZeroValue;
+ FString PhaseList;
+ for (const TPair<bool, double>& Phase : S->Phases)
+ {
+ PhaseList += FString::Printf(TEXT("%s[%s, %.4f]"), PhaseList.IsEmpty() ? TEXT("") : TEXT(", "), Phase.Key ? TEXT("true") : TEXT("false"), Phase.Value);
+ }
+ FString DiffList;
+ for (const double D : R.Diffs)
+ {
+ DiffList += FString::Printf(TEXT("%s%.4f"), DiffList.IsEmpty() ? TEXT("") : TEXT(", "), D);
+ }
+ const FString Json = FString::Printf(
+ TEXT("{\n \"schema\": \"verse.gore.gpu/2\",\n \"resolution\": [%d, %d],\n")
+ TEXT(" \"storm\": {\"hits_per_second\": 30, \"seconds\": 60, \"step_hz\": 30, \"frames\": %d, \"hits\": %d},\n")
+ TEXT(" \"method\": \"alternating gore shown/hidden phases of %d frames (first %d skipped), median raw GPU frame time per phase; diff = shown - mean(hidden before, hidden after)\",\n")
+ TEXT(" \"phases\": [%s],\n \"diffs_ms\": [%s],\n")
+ TEXT(" \"gore_gpu_ms\": {\"mean\": %.4f, \"ci95_half\": %.4f, \"upper95\": %.4f, \"lower95\": %.4f, \"n\": %d},\n")
+ TEXT(" \"limit_gpu_ms\": 0.3,\n")
+ TEXT(" \"live\": {\"spatter_decals\": %d, \"pools\": %d, \"droplets_peak\": %d, \"max_wounds_on_one_character\": %d},\n")
+ TEXT(" \"game_thread_per_hit_ms\": %.5f\n}\n"),
+ Size.X, Size.Y, S->StormFrames, B.HitsHandled, GpuPhaseFrames, GpuSettleFrames, *PhaseList, *DiffList,
+ R.Mean, R.Half, R.Mean + R.Half, R.Mean - R.Half, R.Diffs.Num(),
+ B.SpatterDecals, B.Pools, B.PeakDroplets, B.MaxWoundsOnOneCharacter, B.GameThreadPerHitMs);
+ FFileHelper::SaveStringToFile(Json, *FPaths::Combine(ProofDir(TEXT("5.8")), TEXT("gpu_gore_storm_1440p.json")));
+ S->Gore->WriteBudgetJson(FPaths::Combine(ProofDir(TEXT("5.8")), TEXT("budget_gore_storm_rendered.json")));
+ AddInfo(FString::Printf(TEXT("gore_storm GPU %.3f ms +- %.3f (95 %%, n=%d) at %dx%d"), R.Mean, R.Half, R.Diffs.Num(), Size.X, Size.Y));
+ TestTrue(FString::Printf(TEXT("storm played 1,800 hits (%d)"), B.HitsHandled), B.HitsHandled == 1800);
+ TestTrue(FString::Printf(TEXT("enough shown/hidden pairs (%d >= 8)"), R.Diffs.Num()), R.Diffs.Num() >= 8);
+ TestTrue(FString::Printf(TEXT("gore_storm GPU upper 95 %% bound %.3f ms <= 0.3 ms at 1440p"), R.Mean + R.Half), R.Mean + R.Half <= 0.3);
+ TestTrue(FString::Printf(TEXT("measurement plausible: upper bound %.3f ms is not below zero"), R.Mean + R.Half), R.Mean + R.Half >= 0.0);
+ TestTrue(TEXT("measured at 1440p"), Size.Y >= 1440);
+ TestTrue(FString::Printf(TEXT("rendered storm game thread per hit %.4f ms <= 0.05 ms"), B.GameThreadPerHitMs), B.GameThreadPerHitMs <= 0.05);
+ TestTrue(TEXT("GPU frame timing available"), S->Phases.Num() > 0 && S->Phases[0].Value > 0.0);
+ S->Gore->Purge();
+ S->Gore->SetVictimResolver(nullptr);
+ for (AActor* Actor : S->Spawned)
+ {
+ if (IsValid(Actor))
+ {
+ Actor->Destroy();
+ }
+ }
+ });
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS && WITH_EDITOR
+
+#if WITH_DEV_AUTOMATION_TESTS && WITH_EDITOR
+
+#include "MaterialShared.h"
+#include "Materials/Material.h"
+#include "SceneInterface.h"
+
+// Verse.Visual.Gore.Materials: every gore material compiles for the running shader platform
+// (needs an RHI, so it runs with the visual suite).
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGoreVisualMaterials, "Verse.Visual.Gore.Materials",
+ EAutomationTestFlags::ClientContext | EAutomationTestFlags::EngineFilter)
+bool FVerseGoreVisualMaterials::RunTest(const FString&)
+{
+ if (!FApp::CanEverRender())
+ {
+ AddInfo(TEXT("no RHI: gore material compilation needs a rendered run (screenshot.py)"));
+ return true;
+ }
+ UWorld* World = VerseGoreVisual::GameWorld();
+ if (!TestTrue(TEXT("game world with a scene"), World && World->Scene))
+ {
+ return false;
+ }
+ const EShaderPlatform Platform = World->Scene->GetShaderPlatform();
+ const TCHAR* Paths[] = {
+ TEXT("/Game/Verse/Gore/M_Gore_Decal.M_Gore_Decal"),
+ TEXT("/Game/Verse/Gore/M_Gore_Droplet.M_Gore_Droplet"),
+ TEXT("/Game/Verse/Gore/M_Gore_Flash.M_Gore_Flash"),
+ TEXT("/Game/Verse/Test/WP05/M_Gore_TestBody.M_Gore_TestBody"),
+ };
+ for (const TCHAR* Path : Paths)
+ {
+ UMaterial* Material = LoadObject<UMaterial>(nullptr, Path);
+ if (!TestNotNull(FString::Printf(TEXT("%s loads"), Path), Material))
+ {
+ continue;
+ }
+ FMaterialResource* Resource = Material->GetMaterialResource(Platform);
+ if (!TestNotNull(FString::Printf(TEXT("%s has a resource"), Path), Resource))
+ {
+ continue;
+ }
+ Resource->FinishCompilation();
+ for (const FString& Error : Resource->GetCompileErrors())
+ {
+ AddError(FString::Printf(TEXT("%s: %s"), Path, *Error));
+ }
+ }
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS && WITH_EDITOR
diff --git a/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreActor.h b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreActor.h
new file mode 100644
index 0000000000..5d0f6ad755
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreActor.h
@@ -0,0 +1,46 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "GameFramework/Actor.h"
+
+#include "VerseGoreActor.generated.h"
+
+class UDecalComponent;
+class UInstancedStaticMeshComponent;
+class UMaterialInterface;
+class UStaticMesh;
+
+/**
+ * The one local, transient actor that owns every gore component of a world (WP05). It never
+ * replicates, never collides, never affects navigation and is invisible to every trace channel,
+ * so the bot and gameplay can never see it (contracts/combat-state.md 8, bot.md 3.1).
+ */
+UCLASS(Transient, NotPlaceable, NotBlueprintable)
+class VERSEGORE_API AVerseGoreActor : public AActor
+{
+ GENERATED_BODY()
+
+public:
+ AVerseGoreActor();
+
+ /** A new decal component (no collision, not saved), registered on this actor at `Transform`. */
+ UDecalComponent* NewDecal(UMaterialInterface* Material, const FVector& Size, const FLinearColor& Color, int32 SortOrder,
+ const FTransform& Transform);
+
+ /** Droplets of blood bursts. */
+ UPROPERTY(VisibleAnywhere, Category = "Gore")
+ TObjectPtr<UInstancedStaticMeshComponent> Droplets;
+
+ /** Neutral impact flashes of the Reduced level. */
+ UPROPERTY(VisibleAnywhere, Category = "Gore")
+ TObjectPtr<UInstancedStaticMeshComponent> Flashes;
+
+ /** Applies mesh and materials once they are loaded (null keeps the component empty). */
+ void SetLook(UStaticMesh* DropletMesh, UMaterialInterface* DropletMaterial, UMaterialInterface* FlashMaterial);
+
+ /** Makes a primitive cosmetic-only: no collision, no overlaps, no navigation, no shadows. */
+ static void MakeCosmetic(UPrimitiveComponent* Component);
+
+private:
+ UInstancedStaticMeshComponent* NewInstanced(FName Name);
+};
diff --git a/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSubsystem.h b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSubsystem.h
new file mode 100644
index 0000000000..2d6042db08
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSubsystem.h
@@ -0,0 +1,240 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Gore/VerseGoreSynthetic.h"
+#include "Gore/VerseGoreTypes.h"
+#include "Subsystems/WorldSubsystem.h"
+
+#include "VerseGoreSubsystem.generated.h"
+
+class AVerseGoreActor;
+class UDecalComponent;
+class UMaterialInstanceDynamic;
+class UMaterialInterface;
+class USkeletalMeshComponent;
+class UVerseEventHub;
+
+/** Resolves a player state id of a contract event to the body mesh gore draws on. */
+using FVerseGoreVictimResolver = TFunction<USkeletalMeshComponent*(int32 PlayerId)>;
+
+/**
+ * The gore of one world (WP05). Listens on the hub to FVerseHitEvent, FVerseDeathEvent and
+ * FVerseFinisherEvent and turns them into blood bursts, wall and floor spatter, wound masks,
+ * pools and finisher gore, or into the Reduced level's neutral flash and cut to black.
+ *
+ * One way only (combat-state.md 8): it reads events and the visibility channel, and writes only
+ * its own transient, non-replicated, collision-free components. It does no work on a dedicated
+ * server or in a process that cannot render (`-nullrhi`), unless a test forces it on.
+ */
+UCLASS()
+class VERSEGORE_API UVerseGoreSubsystem : public UTickableWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ static UVerseGoreSubsystem* Get(const UObject* WorldContextObject);
+
+ /** True when this process has a viewport to draw gore into (no dedicated server, no -nullrhi). */
+ static bool ProcessCanShowGore();
+
+ // USubsystem / UWorldSubsystem
+ virtual bool ShouldCreateSubsystem(UObject* Outer) const override;
+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;
+ virtual void Deinitialize() override;
+ virtual void OnWorldBeginPlay(UWorld& InWorld) override;
+
+ // FTickableGameObject
+ virtual void Tick(float DeltaTime) override;
+ virtual TStatId GetStatId() const override;
+ virtual bool IsTickableInEditor() const override { return false; }
+
+ /** Listening and drawing (false on a dedicated server, under -nullrhi, or before Initialize). */
+ bool IsActive() const { return bActive; }
+
+ /** Test hook: run even where the process cannot render. Binds or unbinds the hub. */
+ void SetForceActive(bool bForce);
+
+ /** The viewer's level. Switching to Reduced purges every existing piece of gore live. */
+ EVerseGoreLevel GetGoreLevel() const { return Level; }
+ void SetGoreLevel(EVerseGoreLevel NewLevel);
+
+ /** Re-reads the level from the viewer's GameUserSettings (`[/Script/Verse.VerseSettings] GoreLevel`). */
+ void ReloadLevelFromSettings();
+
+ /** Removes all gore: decals, pools, droplets, flashes, wounds; ends a cut to black. */
+ void Purge();
+
+ /** The event handlers bound on the hub (public so tools can feed events without a hub). */
+ void HandleHit(const FVerseHitEvent& Event);
+ void HandleDeath(const FVerseDeathEvent& Event);
+ void HandleFinisher(const FVerseFinisherEvent& Event);
+
+ /** Advances gore time: droplets, flashes, pool growth, synthetic playback, cut-to-black timeout. */
+ void AdvanceTime(float DeltaSeconds);
+
+ /** Replaces the default resolver (game state player array -> pawn -> skeletal mesh). */
+ void SetVictimResolver(FVerseGoreVictimResolver Resolver);
+
+ /** Plays a synthetic stream from now on (WP05.1): into Gore's own handlers, or on the hub when
+ * `Params.bPublishOnHub` is set (tests). */
+ void PlaySynthetic(const FVerseGoreSyntheticParams& Params);
+ void StopSynthetic();
+ bool IsPlayingSynthetic() const { return SyntheticCursor < SyntheticEvents.Num(); }
+
+ const FVerseGoreTuning& GetTuning() const { return Tuning; }
+ FVerseGoreTuning& MutableTuning() { return Tuning; }
+
+ const FVerseGoreBudget& GetBudget() const { return Budget; }
+ void ResetBudget();
+ /** Budget as the JSON the harness reads (WP05.8). */
+ FString BudgetJson() const;
+ /** Writes BudgetJson to a file; false when the write fails. */
+ bool WriteBudgetJson(const FString& Path) const;
+
+ const FVerseGoreCutToBlack& GetCutToBlack() const { return CutToBlack; }
+
+ /** The gore actor, created on first use (nullptr while inactive). */
+ AVerseGoreActor* GetGoreActor() const { return GoreActor.Get(); }
+
+ /** Where the live droplets are now (the same motion the droplet material draws). */
+ TArray<FVector> GetDropletPositions() const;
+
+ /** Per-instance custom data floats of a droplet: world spawn time, velocity xyz, life, drag, gravity. */
+ static constexpr int32 DropletCustomFloats = 7;
+
+ /** Droplet offset from its origin after `Age` seconds (exact solution of gravity plus linear drag). */
+ static FVector DropletOffset(const FVector& Velocity, float Age, float Drag, float Gravity);
+
+ /** Wounds currently on one body (ref-pose component space xyz, radius w). */
+ TArray<FVector4f> GetWounds(const USkeletalMeshComponent* Mesh) const;
+
+ /** Live spatter decals and pools, oldest first (tests and screenshots). */
+ TArray<UDecalComponent*> GetSpatterDecals() const;
+ TArray<UDecalComponent*> GetPoolDecals() const;
+
+ /** Every runtime asset gore loads by path (materials and the droplet mesh). A cooked build must
+ * contain all of them; /Game/Verse/Gore is not referenced by any map, so it is cooked through
+ * DirectoriesToAlwaysCook (contract change request #1171). */
+ static TArray<FString> RuntimeAssetPaths();
+
+ /** True once every gore material resolved (false: gore is counted but not drawn). */
+ bool HasLook() const { return bLookLoaded && SpatterMaterials.Num() > 0 && PoolMaterial != nullptr; }
+
+ /** Bone-space impact -> reference-pose component space (what the wound mask compares against). */
+ static bool BoneLocalToRefPose(const USkeletalMeshComponent* Mesh, FName Bone, const FVector& BoneLocal, FVector& OutRefPose);
+
+private:
+ /** One droplet. The GPU animates it from its instance's custom data; the game thread only
+ * writes the slot once at spawn and clears the instances when the last droplet died. */
+ struct FDroplet
+ {
+ FVector Origin = FVector::ZeroVector;
+ FVector Velocity = FVector::ZeroVector;
+ double SpawnTime = 0.0; // gore time
+ float Life = 0.f;
+ };
+
+ struct FFlash
+ {
+ FVector Position = FVector::ZeroVector;
+ float Age = 0.f;
+ };
+
+ struct FPool
+ {
+ TWeakObjectPtr<UDecalComponent> Decal;
+ int32 VictimId = 0;
+ double StartTime = 0.0;
+ float Radius = 0.f;
+ };
+
+ struct FWoundSet
+ {
+ TWeakObjectPtr<USkeletalMeshComponent> Mesh;
+ TArray<FVector4f> Wounds; // ring, oldest first after Normalize
+ int32 Next = 0; // ring write index once full
+ TArray<TWeakObjectPtr<UMaterialInstanceDynamic>> Materials;
+ bool bMaterialsResolved = false;
+ };
+
+ void BindHub();
+ void UnbindHub();
+ void UpdateActive();
+ AVerseGoreActor* EnsureGoreActor();
+ void LoadLook();
+
+ USkeletalMeshComponent* ResolveVictim(int32 PlayerId) const;
+ USkeletalMeshComponent* DefaultResolve(int32 PlayerId) const;
+
+ void SpawnBurst(const FVector& Origin, const FVector& Direction, int32 Count, uint32 Seed);
+ void SpawnSpatter(const FVector& Origin, const FVector& Direction, int32 Traces, uint32 Seed, const AActor* Ignore);
+ void SpawnFlash(const FVector& Location);
+ bool PlaceSpatterDecal(const FVector& Location, const FVector& Normal, float Size, uint32 Seed);
+ void AddWound(USkeletalMeshComponent* Mesh, FName Bone, const FVector& BoneLocal, float Damage);
+ /** Writes the wound slots to the body materials: only `Changed`, or all when INDEX_NONE. Slot i = ring entry i. */
+ void ApplyWounds(FWoundSet& Set, int32 Changed = INDEX_NONE);
+ void StartPool(int32 VictimId, const FVector& BodyLocation, const AActor* Ignore);
+ void UpdatePools();
+ void UpdateDroplets();
+ int32 LiveDroplets() const;
+ /** Adds a handler's time to the budget (and to the nested time of a running tick). */
+ void AccountEvent(double Ms, bool bHit);
+ void RefreshGameThreadBudget();
+ void UpdateFlashes(float DeltaSeconds);
+ void StartCutToBlack(const FVerseFinisherEvent& Event);
+ void EndCutToBlack();
+ void SetCameraFade(bool bBlack);
+ void RefreshBudgetLive();
+
+ FVector BodyPoint(USkeletalMeshComponent* Mesh, FName Bone, const FVector& Fallback) const;
+
+ FVerseGoreTuning Tuning;
+ FVerseGoreBudget Budget;
+ FVerseGoreCutToBlack CutToBlack;
+ EVerseGoreLevel Level = EVerseGoreLevel::Full;
+ bool bActive = false;
+ bool bForceActive = false;
+ bool bBound = false;
+ bool bLookLoaded = false;
+ double GoreTime = 0.0;
+
+ TWeakObjectPtr<UVerseEventHub> Hub;
+ FDelegateHandle HitHandle;
+ FDelegateHandle DeathHandle;
+ FDelegateHandle FinisherHandle;
+
+ TWeakObjectPtr<AVerseGoreActor> GoreActor;
+
+ /** Spatter decal ring: components are reused oldest first once the cap is reached. */
+ UPROPERTY(Transient)
+ TArray<TObjectPtr<UDecalComponent>> SpatterRing;
+ int32 SpatterNext = 0;
+ int32 SpatterLive = 0;
+
+ TArray<FPool> Pools; // oldest first
+ TArray<FDroplet> DropletsSim; // ring of instance slots; slot i = ISM instance i
+ int32 DropletNext = 0;
+ double DropletsLastExpiry = 0.0;
+ double NestedEventMs = 0.0;
+ double LastPoolUpdate = -1.0;
+ bool bPoolsDirty = false;
+ TArray<FFlash> FlashesSim;
+ TArray<FWoundSet> WoundSets;
+ /** Bodies whose wounds clear at a gore time (respawn). */
+ TArray<TPair<TWeakObjectPtr<USkeletalMeshComponent>, double>> PendingWoundClears;
+
+ UPROPERTY(Transient)
+ TArray<TObjectPtr<UMaterialInterface>> SpatterMaterials;
+ UPROPERTY(Transient)
+ TObjectPtr<UMaterialInterface> DripMaterial;
+ UPROPERTY(Transient)
+ TObjectPtr<UMaterialInterface> PoolMaterial;
+
+ FVerseGoreVictimResolver VictimResolver;
+
+ TArray<FVerseGoreSyntheticEvent> SyntheticEvents;
+ int32 SyntheticCursor = 0;
+ double SyntheticStart = 0.0;
+ bool bSyntheticOnHub = false;
+};
diff --git a/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSynthetic.h b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSynthetic.h
new file mode 100644
index 0000000000..15c0eccc34
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreSynthetic.h
@@ -0,0 +1,77 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+// Synthetic event player (WP05.1): seeded streams of the contract events Gore listens to, so
+// Gore, its tests and its screenshots run before Combat exists (work-packages.md 0.3). The
+// streams feed Gore's handlers directly; tests may publish them on UVerseEventHub instead.
+
+enum class EVerseGoreSyntheticKind : uint8
+{
+ /** Body hits on every zone at a steady rate. */
+ Hits,
+ /** Deaths (each with its killing hit). */
+ Deaths,
+ /** One finisher: Locked, Takedown, Struggle, Kill, Recover plus the death. */
+ Finisher,
+ /** `gore_storm` of A5.4: 30 hits per second. */
+ Storm
+};
+
+struct FVerseGoreSyntheticEvent
+{
+ enum class EType : uint8 { Hit, Death, Finisher };
+
+ /** Seconds after the stream started. */
+ double Time = 0.0;
+ EType Type = EType::Hit;
+ FVerseHitEvent Hit;
+ FVerseDeathEvent Death;
+ FVerseFinisherEvent Finisher;
+};
+
+struct VERSEGORE_API FVerseGoreSyntheticParams
+{
+ EVerseGoreSyntheticKind Kind = EVerseGoreSyntheticKind::Hits;
+ uint32 Seed = 1;
+ double DurationSeconds = 10.0;
+ /** Events per second (Hits, Deaths); Storm forces 30. */
+ double RatePerSecond = 4.0;
+ int32 InstigatorId = 1;
+ int32 VictimId = 2;
+ /** Where the victim stands (floor point, cm) and where the shooter fires from. */
+ FVector VictimLocation = FVector::ZeroVector;
+ FVector ShooterLocation = FVector(-1000.0, 0.0, 150.0);
+ /** Publish the events on the world's UVerseEventHub (automation tests only). Off by default:
+ * playback then feeds only Gore's own handlers, so a dev command can never reach score,
+ * respawn, kill cam or the bot (combat-state.md 8, one way). */
+ bool bPublishOnHub = false;
+};
+
+/** Finisher phase offsets from `SequenceStartServerTime`, s (combat-state.md 7.4). */
+namespace VerseGoreFinisherTimes
+{
+ inline constexpr double Takedown = 0.25;
+ inline constexpr double Struggle = 0.9;
+ inline constexpr double Kill = 1.8;
+ inline constexpr double Recover = 2.1;
+ inline constexpr double End = 2.5;
+}
+
+struct VERSEGORE_API FVerseGoreSyntheticStream
+{
+ /** Builds a deterministic stream: the same params give the same events, bit for bit. */
+ static TArray<FVerseGoreSyntheticEvent> Build(const FVerseGoreSyntheticParams& Params);
+
+ /** One body hit as Combat would raise it (bone, zone, bone-local impact, bolt direction). */
+ static FVerseHitEvent MakeHit(EVerseHitZone Zone, const FVector& VictimLocation, const FVector& ShooterLocation,
+ int32 InstigatorId, int32 VictimId, float Damage, uint16 ShotCounter, float ServerTime, bool bKillingBlow);
+
+ /** Bone of `SKEL_Verse_Human` (art-pipeline 12.1) a zone's hit lands on, and its height in cm. */
+ static FName BoneForZone(EVerseHitZone Zone);
+ static double HeightForZone(EVerseHitZone Zone);
+
+ /** Parses "hits", "deaths", "finisher", "storm". */
+ static bool ParseKind(const FString& Text, EVerseGoreSyntheticKind& OutKind);
+};
diff --git a/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreTypes.h b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreTypes.h
new file mode 100644
index 0000000000..63df499b15
--- /dev/null
+++ b/unreal/Verse/Source/VerseGore/Public/Gore/VerseGoreTypes.h
@@ -0,0 +1,142 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+#include "VerseGoreTypes.generated.h"
+
+// Client-cosmetic gore (contracts/combat-state.md 8). Everything here is local to one viewer:
+// nothing replicates, nothing collides, nothing feeds back into gameplay (rule D6).
+
+/** Material parameter names a character material reads to draw wound masks (WP05.4). */
+namespace VerseGoreParams
+{
+ /** Scalar: number of live wounds (0..16). */
+ inline const FName WoundCount(TEXT("Verse_WoundCount"));
+ /** Vector per wound, `Verse_Wound_00` .. `Verse_Wound_15`: xyz = reference-pose component-space
+ * position in cm (compare against the material's pre-skinned position), w = radius in cm. */
+ VERSEGORE_API FName WoundSlot(int32 Index);
+ /** Scalar 0..1 a body material may use to wet the whole mask (pool-time darkening). */
+ inline const FName WoundWetness(TEXT("Verse_WoundWetness"));
+}
+
+/** Frozen caps of acceptance row A5.4 and the start values of the effects (tuning, not frozen). */
+struct VERSEGORE_API FVerseGoreTuning
+{
+ /** A5.4 caps. */
+ int32 MaxSpatterDecals = 256;
+ int32 MaxPools = 16;
+ int32 MaxWoundsPerCharacter = 16;
+ /** Droplet instance slots across all bursts (a ring: the oldest slot is reused first). */
+ int32 MaxDroplets = 768;
+ int32 MaxFlashes = 32;
+
+ /** Spatter: how far blood flies past the body along the bolt, cm. */
+ float SpatterRangeCm = 380.f;
+ /** Spatter cone half-angle around the bolt direction, degrees. */
+ float SpatterConeDeg = 14.f;
+ /** Floor drip trace length below the impact, cm. */
+ float DripTraceCm = 260.f;
+ /** Spatter decal size at contact and at full range, cm (half extents of the projected square). */
+ float SpatterSizeNearCm = 34.f;
+ float SpatterSizeFarCm = 14.f;
+ float DripSizeCm = 16.f;
+ /** Decal projection depth, cm. */
+ float DecalDepthCm = 12.f;
+
+ /** Pools: radius at full growth, cm, and growth time, s (WP05.5). */
+ float PoolRadiusCm = 85.f;
+ float PoolStartFraction = 0.08f;
+ float PoolGrowSeconds = 4.f;
+ float PoolTraceCm = 320.f;
+
+ /** Wounds: radius range, cm, mapped from damage 10..60. */
+ float WoundRadiusMinCm = 2.5f;
+ float WoundRadiusMaxCm = 6.f;
+
+ /** Bursts: droplet life and speeds, cm/s. */
+ float DropletLifeSeconds = 0.7f;
+ float DropletSpeedCm = 520.f;
+ float DropletBackSprayFraction = 0.3f;
+ float DropletSizeCm = 1.6f;
+ float GravityCm = 980.f;
+ /** Linear air drag of droplets, 1/s (the droplet material integrates the same motion). */
+ float DropletDrag = 1.6f;
+ /** Pool growth is written at this rate, Hz (not every frame). */
+ float PoolUpdateHz = 20.f;
+
+ /** Reduced: neutral impact flash life, s, and size, cm. */
+ float FlashLifeSeconds = 0.08f;
+ float FlashSizeCm = 14.f;
+
+ /** Finisher cut to black is ended by Recover or Aborted; this is the safety end, s. */
+ float CutToBlackTimeoutSeconds = 4.f;
+
+ /** Droplets per burst by zone at 30 damage; scaled by damage / 30 within [0.5, 2]. */
+ static int32 BaseDroplets(EVerseHitZone Zone);
+ /** Spatter traces per hit by zone (killing blows add one). */
+ static int32 SpatterTraces(EVerseHitZone Zone);
+};
+
+/** Budget counters reported to the harness (WP05.8, A5.4). */
+USTRUCT(BlueprintType)
+struct VERSEGORE_API FVerseGoreBudget
+{
+ GENERATED_BODY()
+
+ /** Live now. */
+ UPROPERTY(BlueprintReadOnly) int32 SpatterDecals = 0;
+ UPROPERTY(BlueprintReadOnly) int32 Pools = 0;
+ UPROPERTY(BlueprintReadOnly) int32 Droplets = 0;
+ UPROPERTY(BlueprintReadOnly) int32 Flashes = 0;
+ UPROPERTY(BlueprintReadOnly) int32 WoundedCharacters = 0;
+ UPROPERTY(BlueprintReadOnly) int32 MaxWoundsOnOneCharacter = 0;
+
+ /** Peaks since the last reset. */
+ UPROPERTY(BlueprintReadOnly) int32 PeakSpatterDecals = 0;
+ UPROPERTY(BlueprintReadOnly) int32 PeakPools = 0;
+ UPROPERTY(BlueprintReadOnly) int32 PeakDroplets = 0;
+ UPROPERTY(BlueprintReadOnly) int32 PeakWoundsOnOneCharacter = 0;
+
+ /** Totals since the last reset. */
+ UPROPERTY(BlueprintReadOnly) int32 HitsHandled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 DeathsHandled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 FinisherPhasesHandled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 DecalsSpawned = 0;
+ UPROPERTY(BlueprintReadOnly) int32 DecalsRecycled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 PoolsRecycled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 WoundsRecycled = 0;
+ UPROPERTY(BlueprintReadOnly) int32 DropletsSpawned = 0;
+ UPROPERTY(BlueprintReadOnly) int32 FlashesSpawned = 0;
+ UPROPERTY(BlueprintReadOnly) int32 Purges = 0;
+
+ /** Game-thread cost of handling one hit, ms (mean and worst). */
+ UPROPERTY(BlueprintReadOnly) double HitMeanMs = 0.0;
+ UPROPERTY(BlueprintReadOnly) double HitMaxMs = 0.0;
+ /** Game-thread cost of one gore tick, ms (mean and worst). */
+ UPROPERTY(BlueprintReadOnly) double TickMeanMs = 0.0;
+ UPROPERTY(BlueprintReadOnly) double TickMaxMs = 0.0;
+
+ /** All gore game-thread time over the run (hits, deaths, finisher phases and ticks), ms, and
+ * that total divided by the hits handled: the A5.4 "game thread per hit" figure. */
+ UPROPERTY(BlueprintReadOnly) double GameThreadTotalMs = 0.0;
+ UPROPERTY(BlueprintReadOnly) double GameThreadPerHitMs = 0.0;
+
+ /** Accumulators behind the means. Tick time excludes handlers that ran inside the tick. */
+ double HitTotalMs = 0.0;
+ double OtherEventTotalMs = 0.0;
+ double TickTotalMs = 0.0;
+ int64 Ticks = 0;
+};
+
+/** One finisher cut to black as the Reduced level plays it (A5.5). */
+struct FVerseGoreCutToBlack
+{
+ bool bActive = false;
+ int32 AttackerId = 0;
+ int32 VictimId = 0;
+ uint64 StartFrame = 0;
+ uint64 EndFrame = 0;
+ double StartTime = 0.0;
+ int32 Count = 0;
+};