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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): add the penetration table, bolt and sight traces, bolt holes and the WP03 content (#1149)
Ruben Lütke6f28e6887f1e
diff --git a/unreal/Verse/Content/Verse/Destruction/_Holes/DA_PenetrationTable.uasset b/unreal/Verse/Content/Verse/Destruction/_Holes/DA_PenetrationTable.uassetnew file mode 100644index 0000000000..d0fe610890--- /dev/null+++ b/unreal/Verse/Content/Verse/Destruction/_Holes/DA_PenetrationTable.uasset@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:bcc7510318089ceb93fff69e5154926adaf13b4f09e779110bccb29f4ddc3713+size 1280diff --git a/unreal/Verse/Content/Verse/Destruction/_Holes/M_HoleRim_Decal.uasset b/unreal/Verse/Content/Verse/Destruction/_Holes/M_HoleRim_Decal.uassetnew file mode 100644index 0000000000..76a19a405d--- /dev/null+++ b/unreal/Verse/Content/Verse/Destruction/_Holes/M_HoleRim_Decal.uasset@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:3cbf990abcb3b297926990fe8c5cb329d3a635e6f9755c9a8dff525fb5eaf079+size 11230diff --git a/unreal/Verse/Content/Verse/Test/WP03/LV_WP03_Penetration.umap b/unreal/Verse/Content/Verse/Test/WP03/LV_WP03_Penetration.umapnew file mode 100644index 0000000000..a0b3b08ab4--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP03/LV_WP03_Penetration.umap@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:be1d9d6a47b2b067c9f7ac862e4727730ef8ffc90526f002a42ed11a9c69ed34+size 63718diff --git a/unreal/Verse/Content/Verse/Test/WP03/M_WP03_HoleSurface.uasset b/unreal/Verse/Content/Verse/Test/WP03/M_WP03_HoleSurface.uassetnew file mode 100644index 0000000000..df3e43cd3b--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP03/M_WP03_HoleSurface.uasset@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:1cbfcc9a98da262c88244e44a34f64d3ffd85baea51cb57c598032b4e09ea72a+size 6655diff --git a/unreal/Verse/Content/Verse/Test/WP03/Python/wp03_content.py b/unreal/Verse/Content/Verse/Test/WP03/Python/wp03_content.pynew file mode 100644index 0000000000..708467c31c--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP03/Python/wp03_content.py@@ -0,0 +1,338 @@+"""Create and verify the WP03 content (editor Python, ``pythonscript`` commandlet).++Run headless under the machine lock, from the worktree root::++ python scripts/unreal/with_lock.py --label wp03-content -- \+ "C:/Program Files/Epic Games/UE_5.7/Engine/Binaries/Win64/UnrealEditor-Cmd.exe" \+ unreal/Verse/Verse.uproject -run=pythonscript \+ -script=unreal/Verse/Content/Verse/Test/WP03/Python/wp03_content.py \+ -nullrhi -unattended -nosplash -NoSound -abslog=unreal/Verse/Saved/wp03_content.log++What it makes (all own work, no engine sample content):++* ``/Game/Verse/Destruction/_Holes/DA_PenetrationTable``: the rows of+ ``Data/destruction/penetration.json`` through the WP03.2 importer (frozen+ wire order check). Re-run after every retune of the JSON; the game loads+ the asset, so a retune reaches cooked and dedicated-server builds.+* The three WP03.7 world-surface physical materials (``PM_Verse_HallFloor``,+ ``PM_Verse_StructuralWall``, ``PM_Verse_StructuralBeam``) are made only with+ ``VERSE_WP03_PHYSMATS=1``: art-pipeline section 3 has no physical material+ prefix yet (request #1161), so they cannot be committed until it does.+* ``/Game/Verse/Destruction/_Holes/M_HoleRim_Decal``: the rim decal of+ WP03.6 (deferred decal, translucent), scalar ``RimGlow``, vector+ ``RimGlowColor``, a charred base.+* Placeholder geometry is the engine's built-in ``/Engine/BasicShapes/Cube``+ (100 cm, box collision; engine primitives, not a sample content pack). An+ own ``SM_`` mesh would need an art-pipeline import record (art-pipeline 9).+* ``/Game/Verse/Test/WP03/M_WP03_HoleSurface``: a test surface master with+ the ``HoleMask`` texture parameter (masked, two-sided, emissive ``Tint``),+ standing in for the WP14.1 masters in WP03 tests and the fixture map.+* ``/Game/Verse/Test/WP03/LV_WP03_Penetration``: the WP03.8 fixture map.++Idempotent: an asset that already matches is not saved again, so a rerun does+not churn LFS objects. Every result line starts with ``VERSE_WP03``; the last+one is ``VERSE_WP03 OK`` or ``VERSE_WP03 FAIL``.+"""++from __future__ import annotations++import json+import os+import traceback++import unreal++HOLES = "/Game/Verse/Destruction/_Holes"+PHYS = HOLES + "/PhysicalMaterials"+TEST = "/Game/Verse/Test/WP03"+BOX = "/Engine/BasicShapes/Cube"+MAP = TEST + "/LV_WP03_Penetration"+SURFACES = ("HallFloor", "StructuralWall", "StructuralBeam")+FACTORS = (0.5, 1.0, 3.0)+CHARRED = (0.018, 0.014, 0.011)++ASSETS = unreal.AssetToolsHelpers.get_asset_tools()+EAL = unreal.EditorAssetLibrary+MEL = unreal.MaterialEditingLibrary+++def log(text: str) -> None:+ unreal.log("VERSE_WP03 " + text)+++def project_dir() -> str:+ return unreal.Paths.convert_relative_path_to_full(unreal.Paths.project_dir())+++def table_rows() -> list[dict]:+ path = os.path.join(project_dir(), "Data", "destruction", "penetration.json")+ with open(path, encoding="utf-8") as handle:+ return json.load(handle)["materials"]+++def existing(path: str):+ return EAL.load_asset(path) if EAL.does_asset_exist(path) else None+++def save(asset) -> None:+ if not EAL.save_loaded_asset(asset, only_if_is_dirty=False):+ raise RuntimeError(f"could not save {asset.get_path_name()}")+ log(f"saved {asset.get_path_name()}")+++def make_table() -> None:+ path = HOLES + "/DA_PenetrationTable"+ table = existing(path)+ library = unreal.VersePenetrationTableLibrary+ if table is not None and not library.diff_penetration_json(table, ""):+ log("DA_PenetrationTable matches penetration.json")+ return+ if table is None:+ factory = unreal.DataAssetFactory()+ factory.set_editor_property("data_asset_class", unreal.VersePenetrationTable)+ table = ASSETS.create_asset(+ "DA_PenetrationTable", HOLES, unreal.VersePenetrationTable, factory+ )+ # A bool UFUNCTION with an out parameter returns the out value on success and None on failure.+ if library.import_penetration_json(table, "") is None:+ raise RuntimeError(+ "penetration.json rejected; Verse.Destruction.Penetration.Import says why"+ )+ save(table)+++def make_physical_materials() -> None:+ for surface in SURFACES:+ name = f"PM_Verse_{surface}"+ if existing(f"{PHYS}/{name}") is not None:+ continue+ asset = ASSETS.create_asset(+ name, PHYS, unreal.PhysicalMaterial, unreal.PhysicalMaterialFactoryNew()+ )+ save(asset)+++def expression(material, cls, x: int, y: int):+ return MEL.create_material_expression(material, cls, x, y)+++def connect(a, b, b_input: str, a_output: str = "") -> None:+ if not MEL.connect_material_expressions(a, a_output, b, b_input):+ raise RuntimeError(f"cannot connect {a.get_name()} to {b.get_name()}.{b_input}")+++def to_property(node, prop, output: str = "") -> None:+ if not MEL.connect_material_property(node, output, prop):+ raise RuntimeError(f"cannot connect {node.get_name()} to {prop}")+++def make_rim_decal() -> None:+ path = HOLES + "/M_HoleRim_Decal"+ if existing(path) is not None:+ return+ material = ASSETS.create_asset(+ "M_HoleRim_Decal", HOLES, unreal.Material, unreal.MaterialFactoryNew()+ )+ material.set_editor_property("material_domain", unreal.MaterialDomain.MD_DEFERRED_DECAL)+ material.set_editor_property("blend_mode", unreal.BlendMode.BLEND_TRANSLUCENT)++ glow = expression(material, unreal.MaterialExpressionScalarParameter, -900, -200)+ glow.set_editor_property("parameter_name", "RimGlow")+ glow.set_editor_property("default_value", 0.0)+ color = expression(material, unreal.MaterialExpressionVectorParameter, -900, -50)+ color.set_editor_property("parameter_name", "RimGlowColor")+ color.set_editor_property("default_value", unreal.LinearColor(*CHARRED, 1.0))++ # Ring mask over the decal footprint: 1 at the opening, fading out to the footprint edge.+ uv = expression(material, unreal.MaterialExpressionTextureCoordinate, -1200, 200)+ centre = expression(material, unreal.MaterialExpressionConstant2Vector, -1200, 320)+ centre.set_editor_property("r", 0.5)+ centre.set_editor_property("g", 0.5)+ dist = expression(material, unreal.MaterialExpressionDistance, -1000, 250)+ connect(uv, dist, "A")+ connect(centre, dist, "B")+ edge = expression(material, unreal.MaterialExpressionConstant, -1000, 400)+ edge.set_editor_property("r", 0.5)+ inside = expression(material, unreal.MaterialExpressionSubtract, -820, 300)+ connect(edge, inside, "A")+ connect(dist, inside, "B")+ gain = expression(material, unreal.MaterialExpressionConstant, -820, 450)+ gain.set_editor_property("r", 4.0)+ scaled = expression(material, unreal.MaterialExpressionMultiply, -660, 320)+ connect(inside, scaled, "A")+ connect(gain, scaled, "B")+ ring = expression(material, unreal.MaterialExpressionSaturate, -500, 320)+ connect(scaled, ring, "")++ hot = expression(material, unreal.MaterialExpressionMultiply, -600, -120)+ connect(color, hot, "A")+ connect(glow, hot, "B")+ emissive = expression(material, unreal.MaterialExpressionMultiply, -380, -60)+ connect(hot, emissive, "A")+ connect(ring, emissive, "B")+ base = expression(material, unreal.MaterialExpressionConstant3Vector, -380, 120)+ base.set_editor_property("constant", unreal.LinearColor(*CHARRED, 1.0))++ to_property(emissive, unreal.MaterialProperty.MP_EMISSIVE_COLOR)+ to_property(base, unreal.MaterialProperty.MP_BASE_COLOR)+ to_property(ring, unreal.MaterialProperty.MP_OPACITY)+ MEL.recompile_material(material)+ save(material)+++def make_surface() -> None:+ path = TEST + "/M_WP03_HoleSurface"+ if existing(path) is not None:+ return+ material = ASSETS.create_asset(+ "M_WP03_HoleSurface", TEST, unreal.Material, unreal.MaterialFactoryNew()+ )+ material.set_editor_property("blend_mode", unreal.BlendMode.BLEND_MASKED)+ material.set_editor_property("two_sided", True)+ tint = expression(material, unreal.MaterialExpressionVectorParameter, -600, 0)+ tint.set_editor_property("parameter_name", "Tint")+ tint.set_editor_property("default_value", unreal.LinearColor(0.3, 0.3, 0.3, 1.0))+ black = expression(material, unreal.MaterialExpressionConstant3Vector, -600, -150)+ black.set_editor_property("constant", unreal.LinearColor(0.0, 0.0, 0.0, 1.0))+ mask = expression(material, unreal.MaterialExpressionTextureSampleParameter2D, -600, 200)+ mask.set_editor_property("parameter_name", "HoleMask")+ mask.set_editor_property(+ "texture", unreal.load_asset("/Engine/EngineResources/WhiteSquareTexture")+ )+ to_property(black, unreal.MaterialProperty.MP_BASE_COLOR)+ to_property(tint, unreal.MaterialProperty.MP_EMISSIVE_COLOR)+ to_property(mask, unreal.MaterialProperty.MP_OPACITY_MASK, "R")+ MEL.recompile_material(material)+ save(material)+++def spawn_piece(+ box,+ material_id: str,+ wire: int,+ thickness_cm: float,+ location,+ rotation=None,+ label: str = "",+ role: str = "grid",+):+ # The editor actor subsystem places through the level viewport, which a commandlet lacks;+ # the WP03 library spawns straight into the editor world.+ world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()+ transform = unreal.Transform(+ location, rotation or unreal.Rotator(0, 0, 0), unreal.Vector(thickness_cm / 100.0, 1.0, 1.0)+ )+ profile = "Verse_Glass" if material_id == "glass" else "Verse_Destructible"+ tags = [+ f"verse.wp03.material:{material_id}",+ f"verse.wp03.wire:{wire}",+ f"verse.wp03.thickness_cm:{thickness_cm:g}",+ "verse.wp03.role:" + role,+ ]+ surface = unreal.load_asset(TEST + "/M_WP03_HoleSurface")+ actor = unreal.VersePenetrationTableLibrary.spawn_fixture_piece(+ world,+ box,+ surface,+ transform,+ profile,+ tags,+ label or f"WP03_{material_id}_{thickness_cm:g}cm",+ )+ if actor is None:+ raise RuntimeError(f"could not spawn {material_id} {thickness_cm:g} cm")+ return actor+++def make_map() -> None:+ if EAL.does_asset_exist(MAP):+ return+ levels = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)+ if not levels.new_level(MAP, False):+ raise RuntimeError(f"could not create {MAP}")+ box = unreal.load_asset(BOX)+ rows = table_rows()+ # Grid: one row per material (X), one column per thickness factor (Y), 1.5 m apart.+ for row in rows:+ for column, factor in enumerate(FACTORS):+ thickness = row["ref_thickness_cm"] * factor+ location = unreal.Vector(300.0 + 150.0 * row["wire"], 150.0 * column, 100.0)+ spawn_piece(box, row["id"], row["wire"], thickness, location)+ # Hole angle rig (A3.3): a 0.3 cm sheet and a 4 cm panel, each at 30 deg to the ray.+ sheet = next(r for r in rows if r["id"] == "sheet_metal")+ panel = next(r for r in rows if r["id"] == "cladding_panel")+ rig = unreal.Rotator(0.0, 0.0, 30.0)+ spawn_piece(+ box,+ sheet["id"],+ sheet["wire"],+ 0.3,+ unreal.Vector(300.0, 600.0, 100.0),+ rig,+ "WP03_HoleRig_Sheet",+ "hole_rig",+ )+ spawn_piece(+ box,+ panel["id"],+ panel["wire"],+ 4.0,+ unreal.Vector(300.0, 750.0, 100.0),+ rig,+ "WP03_HoleRig_Panel",+ "hole_rig",+ )+ # A container row: three walls one metre apart (rifle through two walls keeps 0.5625).+ wall = next(r for r in rows if r["id"] == "container_wall")+ for index in range(3):+ spawn_piece(+ box,+ wall["id"],+ wall["wire"],+ wall["ref_thickness_cm"],+ unreal.Vector(300.0 + 100.0 * index, 900.0, 100.0),+ None,+ f"WP03_ContainerRow_{index}",+ "container_row",+ )+ if not levels.save_current_level():+ raise RuntimeError(f"could not save {MAP}")+ log(f"saved {MAP}")+++def verify() -> list[str]:+ problems = []+ table = existing(HOLES + "/DA_PenetrationTable")+ if table is None:+ problems.append("DA_PenetrationTable missing")+ elif unreal.VersePenetrationTableLibrary.diff_penetration_json(table, ""):+ problems.append("DA_PenetrationTable differs from penetration.json")+ for path in (+ HOLES + "/M_HoleRim_Decal",+ TEST + "/M_WP03_HoleSurface",+ MAP,+ ):+ if not EAL.does_asset_exist(path):+ problems.append(f"{path} missing")+ return problems+++def main() -> None:+ try:+ make_table()+ if os.environ.get("VERSE_WP03_PHYSMATS") == "1":+ make_physical_materials()+ make_rim_decal()+ make_surface()+ make_map()+ problems = verify()+ for problem in problems:+ log("problem: " + problem)+ log("FAIL" if problems else "OK")+ except Exception: # noqa: BLE001 - every failure must reach the log marker+ for line in traceback.format_exc().splitlines():+ log(line)+ log("FAIL")+++main()diff --git a/unreal/Verse/Content/Verse/Test/WP03/penetration_golden.json b/unreal/Verse/Content/Verse/Test/WP03/penetration_golden.jsonnew file mode 100644index 0000000000..064c6d30d7--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP03/penetration_golden.json@@ -0,0 +1,985 @@+{+ "schema": "verse.penetration-golden/1",+ "owner": "WP03",+ "rule": "cost = row.cost x clamp(thickness / ref, 0.5, 3.0); passes when power >= cost; damage_left is the damage fraction left of a bolt that entered with 1.0; a stopped bolt keeps 0 power and 0 damage",+ "start_damage": 1.0,+ "tolerance": 0.0001,+ "cases": [+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 0.5,+ "thickness_cm": 0.15,+ "power": 50,+ "cost": 7.5,+ "passed": true,+ "power_left": 42.5,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 0.5,+ "thickness_cm": 0.15,+ "power": 100,+ "cost": 7.5,+ "passed": true,+ "power_left": 92.5,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 0.5,+ "thickness_cm": 0.15,+ "power": 150,+ "cost": 7.5,+ "passed": true,+ "power_left": 142.5,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 1.0,+ "thickness_cm": 0.3,+ "power": 50,+ "cost": 15.0,+ "passed": true,+ "power_left": 35.0,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 1.0,+ "thickness_cm": 0.3,+ "power": 100,+ "cost": 15.0,+ "passed": true,+ "power_left": 85.0,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 1.0,+ "thickness_cm": 0.3,+ "power": 150,+ "cost": 15.0,+ "passed": true,+ "power_left": 135.0,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 3.0,+ "thickness_cm": 0.9,+ "power": 50,+ "cost": 45.0,+ "passed": true,+ "power_left": 5.0,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 3.0,+ "thickness_cm": 0.9,+ "power": 100,+ "cost": 45.0,+ "passed": true,+ "power_left": 55.0,+ "damage_left": 0.85+ },+ {+ "material": "sheet_metal",+ "wire": 0,+ "thickness_factor": 3.0,+ "thickness_cm": 0.9,+ "power": 150,+ "cost": 45.0,+ "passed": true,+ "power_left": 105.0,+ "damage_left": 0.85+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 0.5,+ "thickness_cm": 0.2,+ "power": 50,+ "cost": 12.5,+ "passed": true,+ "power_left": 37.5,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 0.5,+ "thickness_cm": 0.2,+ "power": 100,+ "cost": 12.5,+ "passed": true,+ "power_left": 87.5,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 0.5,+ "thickness_cm": 0.2,+ "power": 150,+ "cost": 12.5,+ "passed": true,+ "power_left": 137.5,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 1.0,+ "thickness_cm": 0.4,+ "power": 50,+ "cost": 25.0,+ "passed": true,+ "power_left": 25.0,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 1.0,+ "thickness_cm": 0.4,+ "power": 100,+ "cost": 25.0,+ "passed": true,+ "power_left": 75.0,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 1.0,+ "thickness_cm": 0.4,+ "power": 150,+ "cost": 25.0,+ "passed": true,+ "power_left": 125.0,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 3.0,+ "thickness_cm": 1.2,+ "power": 50,+ "cost": 75.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 3.0,+ "thickness_cm": 1.2,+ "power": 100,+ "cost": 75.0,+ "passed": true,+ "power_left": 25.0,+ "damage_left": 0.75+ },+ {+ "material": "container_wall",+ "wire": 1,+ "thickness_factor": 3.0,+ "thickness_cm": 1.2,+ "power": 150,+ "cost": 75.0,+ "passed": true,+ "power_left": 75.0,+ "damage_left": 0.75+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 0.5,+ "thickness_cm": 1.2,+ "power": 50,+ "cost": 2.5,+ "passed": true,+ "power_left": 47.5,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 0.5,+ "thickness_cm": 1.2,+ "power": 100,+ "cost": 2.5,+ "passed": true,+ "power_left": 97.5,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 0.5,+ "thickness_cm": 1.2,+ "power": 150,+ "cost": 2.5,+ "passed": true,+ "power_left": 147.5,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 1.0,+ "thickness_cm": 2.4,+ "power": 50,+ "cost": 5.0,+ "passed": true,+ "power_left": 45.0,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 1.0,+ "thickness_cm": 2.4,+ "power": 100,+ "cost": 5.0,+ "passed": true,+ "power_left": 95.0,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 1.0,+ "thickness_cm": 2.4,+ "power": 150,+ "cost": 5.0,+ "passed": true,+ "power_left": 145.0,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 3.0,+ "thickness_cm": 7.2,+ "power": 50,+ "cost": 15.0,+ "passed": true,+ "power_left": 35.0,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 3.0,+ "thickness_cm": 7.2,+ "power": 100,+ "cost": 15.0,+ "passed": true,+ "power_left": 85.0,+ "damage_left": 0.95+ },+ {+ "material": "glass",+ "wire": 2,+ "thickness_factor": 3.0,+ "thickness_cm": 7.2,+ "power": 150,+ "cost": 15.0,+ "passed": true,+ "power_left": 135.0,+ "damage_left": 0.95+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 0.5,+ "thickness_cm": 2.0,+ "power": 50,+ "cost": 15.0,+ "passed": true,+ "power_left": 35.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 0.5,+ "thickness_cm": 2.0,+ "power": 100,+ "cost": 15.0,+ "passed": true,+ "power_left": 85.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 0.5,+ "thickness_cm": 2.0,+ "power": 150,+ "cost": 15.0,+ "passed": true,+ "power_left": 135.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 1.0,+ "thickness_cm": 4.0,+ "power": 50,+ "cost": 30.0,+ "passed": true,+ "power_left": 20.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 1.0,+ "thickness_cm": 4.0,+ "power": 100,+ "cost": 30.0,+ "passed": true,+ "power_left": 70.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 1.0,+ "thickness_cm": 4.0,+ "power": 150,+ "cost": 30.0,+ "passed": true,+ "power_left": 120.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 3.0,+ "thickness_cm": 12.0,+ "power": 50,+ "cost": 90.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 3.0,+ "thickness_cm": 12.0,+ "power": 100,+ "cost": 90.0,+ "passed": true,+ "power_left": 10.0,+ "damage_left": 0.7+ },+ {+ "material": "cladding_panel",+ "wire": 3,+ "thickness_factor": 3.0,+ "thickness_cm": 12.0,+ "power": 150,+ "cost": 90.0,+ "passed": true,+ "power_left": 60.0,+ "damage_left": 0.7+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 0.5,+ "thickness_cm": 1.5,+ "power": 50,+ "cost": 5.0,+ "passed": true,+ "power_left": 45.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 0.5,+ "thickness_cm": 1.5,+ "power": 100,+ "cost": 5.0,+ "passed": true,+ "power_left": 95.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 0.5,+ "thickness_cm": 1.5,+ "power": 150,+ "cost": 5.0,+ "passed": true,+ "power_left": 145.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 1.0,+ "thickness_cm": 3.0,+ "power": 50,+ "cost": 10.0,+ "passed": true,+ "power_left": 40.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 1.0,+ "thickness_cm": 3.0,+ "power": 100,+ "cost": 10.0,+ "passed": true,+ "power_left": 90.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 1.0,+ "thickness_cm": 3.0,+ "power": 150,+ "cost": 10.0,+ "passed": true,+ "power_left": 140.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 3.0,+ "thickness_cm": 9.0,+ "power": 50,+ "cost": 30.0,+ "passed": true,+ "power_left": 20.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 3.0,+ "thickness_cm": 9.0,+ "power": 100,+ "cost": 30.0,+ "passed": true,+ "power_left": 70.0,+ "damage_left": 0.9+ },+ {+ "material": "catwalk_grating",+ "wire": 4,+ "thickness_factor": 3.0,+ "thickness_cm": 9.0,+ "power": 150,+ "cost": 30.0,+ "passed": true,+ "power_left": 120.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 50,+ "cost": 4.0,+ "passed": true,+ "power_left": 46.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 100,+ "cost": 4.0,+ "passed": true,+ "power_left": 96.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 150,+ "cost": 4.0,+ "passed": true,+ "power_left": 146.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 50,+ "cost": 8.0,+ "passed": true,+ "power_left": 42.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 100,+ "cost": 8.0,+ "passed": true,+ "power_left": 92.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 150,+ "cost": 8.0,+ "passed": true,+ "power_left": 142.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 50,+ "cost": 24.0,+ "passed": true,+ "power_left": 26.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 100,+ "cost": 24.0,+ "passed": true,+ "power_left": 76.0,+ "damage_left": 0.9+ },+ {+ "material": "ceiling_panel",+ "wire": 5,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 150,+ "cost": 24.0,+ "passed": true,+ "power_left": 126.0,+ "damage_left": 0.9+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 0.5,+ "thickness_cm": 15.0,+ "power": 50,+ "cost": 200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 0.5,+ "thickness_cm": 15.0,+ "power": 100,+ "cost": 200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 0.5,+ "thickness_cm": 15.0,+ "power": 150,+ "cost": 200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 1.0,+ "thickness_cm": 30.0,+ "power": 50,+ "cost": 400.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 1.0,+ "thickness_cm": 30.0,+ "power": 100,+ "cost": 400.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 1.0,+ "thickness_cm": 30.0,+ "power": 150,+ "cost": 400.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 3.0,+ "thickness_cm": 90.0,+ "power": 50,+ "cost": 1200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 3.0,+ "thickness_cm": 90.0,+ "power": 100,+ "cost": 1200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "concrete",+ "wire": 6,+ "thickness_factor": 3.0,+ "thickness_cm": 90.0,+ "power": 150,+ "cost": 1200.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 50,+ "cost": 5000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 100,+ "cost": 5000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 0.5,+ "thickness_cm": 1.25,+ "power": 150,+ "cost": 5000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 50,+ "cost": 10000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 100,+ "cost": 10000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 1.0,+ "thickness_cm": 2.5,+ "power": 150,+ "cost": 10000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 50,+ "cost": 30000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 100,+ "cost": 30000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ },+ {+ "material": "armor_steel",+ "wire": 7,+ "thickness_factor": 3.0,+ "thickness_cm": 7.5,+ "power": 150,+ "cost": 30000.0,+ "passed": false,+ "power_left": 0.0,+ "damage_left": 0.0+ }+ ],+ "chains": [+ {+ "name": "rifle through two container walls",+ "power": 100,+ "damage": 1.0,+ "max_pieces": 3,+ "pieces": [+ {+ "material": "container_wall",+ "thickness_cm": 0.4+ },+ {+ "material": "container_wall",+ "thickness_cm": 0.4+ }+ ],+ "passed": [+ true,+ true+ ],+ "power_left": [+ 75.0,+ 50.0+ ],+ "damage_left": [+ 0.75,+ 0.5625+ ]+ },+ {+ "name": "pistol spends its power exactly on two container walls (power >= cost passes)",+ "power": 50,+ "damage": 1.0,+ "max_pieces": 2,+ "pieces": [+ {+ "material": "container_wall",+ "thickness_cm": 0.4+ },+ {+ "material": "container_wall",+ "thickness_cm": 0.4+ }+ ],+ "passed": [+ true,+ true+ ],+ "power_left": [+ 25.0,+ 0.0+ ],+ "damage_left": [+ 0.75,+ 0.5625+ ]+ },+ {+ "name": "pistol through glass and sheet metal",+ "power": 50,+ "damage": 1.0,+ "max_pieces": 2,+ "pieces": [+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "sheet_metal",+ "thickness_cm": 0.3+ }+ ],+ "passed": [+ true,+ true+ ],+ "power_left": [+ 45.0,+ 30.0+ ],+ "damage_left": [+ 0.95,+ 0.8075+ ]+ },+ {+ "name": "fourth piece stops the rifle",+ "power": 100,+ "damage": 1.0,+ "max_pieces": 3,+ "pieces": [+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "glass",+ "thickness_cm": 2.4+ }+ ],+ "passed": [+ true,+ true,+ true,+ false+ ],+ "power_left": [+ 95.0,+ 90.0,+ 85.0,+ 0.0+ ],+ "damage_left": [+ 0.95,+ 0.9025,+ 0.857375,+ 0.0+ ]+ },+ {+ "name": "pistol limit two stops the third pane",+ "power": 50,+ "damage": 1.0,+ "max_pieces": 2,+ "pieces": [+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "glass",+ "thickness_cm": 2.4+ },+ {+ "material": "glass",+ "thickness_cm": 2.4+ }+ ],+ "passed": [+ true,+ true,+ false+ ],+ "power_left": [+ 45.0,+ 40.0,+ 0.0+ ],+ "damage_left": [+ 0.95,+ 0.9025,+ 0.0+ ]+ },+ {+ "name": "concrete stops everything",+ "power": 150,+ "damage": 1.0,+ "max_pieces": 3,+ "pieces": [+ {+ "material": "concrete",+ "thickness_cm": 15.0+ }+ ],+ "passed": [+ false+ ],+ "power_left": [+ 0.0+ ],+ "damage_left": [+ 0.0+ ]+ }+ ]+}diff --git a/unreal/Verse/Data/destruction/penetration.json b/unreal/Verse/Data/destruction/penetration.jsonnew file mode 100644index 0000000000..d7b0117202--- /dev/null+++ b/unreal/Verse/Data/destruction/penetration.json@@ -0,0 +1,96 @@+{+ "schema": "verse.penetration/1",+ "source": "docs/verse/unreal/contracts/destruction.md section 2 (frozen columns, wire order and cost formula; numbers retune only through its change rule)",+ "power_anchor": 100,+ "max_pieces": 3,+ "materials": [+ {+ "wire": 0,+ "id": "sheet_metal",+ "ref_thickness_cm": 0.3,+ "cost": 15,+ "damage_multiplier": 0.85,+ "breakable_by_bullets": true,+ "breakable_by_breach": true,+ "debris": "MetalShards",+ "note": "rigid shards plus sparks"+ },+ {+ "wire": 1,+ "id": "container_wall",+ "ref_thickness_cm": 0.4,+ "cost": 25,+ "damage_multiplier": 0.75,+ "breakable_by_bullets": true,+ "breakable_by_breach": true,+ "debris": "CorrugatedChunks",+ "note": "corrugated; rigid chunks plus sparks"+ },+ {+ "wire": 2,+ "id": "glass",+ "ref_thickness_cm": 2.4,+ "cost": 5,+ "damage_multiplier": 0.95,+ "breakable_by_bullets": true,+ "breakable_by_breach": true,+ "debris": "GlassShards",+ "note": "laminated; Niagara only, no rigid bodies"+ },+ {+ "wire": 3,+ "id": "cladding_panel",+ "ref_thickness_cm": 4.0,+ "cost": 30,+ "damage_multiplier": 0.7,+ "breakable_by_bullets": true,+ "breakable_by_breach": true,+ "debris": "PanelChunks",+ "note": "composite; rigid chunks plus insulation dust"+ },+ {+ "wire": 4,+ "id": "catwalk_grating",+ "ref_thickness_cm": 3.0,+ "cost": 10,+ "damage_multiplier": 0.9,+ "breakable_by_bullets": false,+ "breakable_by_breach": true,+ "debris": "GratingTwisted",+ "note": "bar grating; rigid, few large pieces"+ },+ {+ "wire": 5,+ "id": "ceiling_panel",+ "ref_thickness_cm": 2.5,+ "cost": 8,+ "damage_multiplier": 0.9,+ "breakable_by_bullets": true,+ "breakable_by_breach": true,+ "debris": "CeilingTile",+ "note": "metal tile; the whole tile falls, plus dust"+ },+ {+ "wire": 6,+ "id": "concrete",+ "ref_thickness_cm": 30.0,+ "cost": 400,+ "damage_multiplier": 0.0,+ "breakable_by_bullets": false,+ "breakable_by_breach": false,+ "debris": "DustChips",+ "note": "Niagara only"+ },+ {+ "wire": 7,+ "id": "armor_steel",+ "ref_thickness_cm": 2.5,+ "cost": 10000,+ "damage_multiplier": 0.0,+ "breakable_by_bullets": false,+ "breakable_by_breach": false,+ "debris": "SparksOnly",+ "note": "impassable"+ }+ ]+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseBoltHoleComponent.cpp b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseBoltHoleComponent.cppnew file mode 100644index 0000000000..a0b252eca8--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseBoltHoleComponent.cpp@@ -0,0 +1,353 @@+#include "Holes/VerseBoltHoleComponent.h"++#include "Destruction/VerseDestructionTuning.h"+#include "GameFramework/Actor.h"+#include "Net/UnrealNetwork.h"+#include "Penetration/VersePenetrationMath.h"++UVerseBoltHoleComponent::UVerseBoltHoleComponent()+{+ PrimaryComponentTick.bCanEverTick = false;+ SetIsReplicatedByDefault(true);+}++void UVerseBoltHoleComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const+{+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);+ DOREPLIFETIME(UVerseBoltHoleComponent, Slots);+ DOREPLIFETIME(UVerseBoltHoleComponent, Epoch);+}++void UVerseBoltHoleComponent::ApplyTuning(const UVerseDestructionTuning& Tuning)+{+ HolesPerPiece = FMath::Max(1, Tuning.HolesPerPiece);+ HolesPerArena = FMath::Max(1, Tuning.HolesPerArena);+}++bool UVerseBoltHoleComponent::HasServerAuthority() const+{+ const AActor* OwnerActor = GetOwner();+ return OwnerActor == nullptr || OwnerActor->HasAuthority();+}++bool UVerseBoltHoleComponent::IsLiveSlot(int32 SlotIndex) const+{+ return Slots.IsValidIndex(SlotIndex) && Slots[SlotIndex].IsUsed() && Slots[SlotIndex].Hole.Epoch == Epoch;+}++EVerseHoleAddResult UVerseBoltHoleComponent::AddHole(uint16 PieceIndex, EVersePenetrationMaterial Material,+ const FVector& AxisPointLocalCm, const FVector& AxisDirectionLocal, uint8 RadiusMm, uint32 ServerTimeMs)+{+ if (!HasServerAuthority())+ {+ return EVerseHoleAddResult::NotAuthority;+ }+ if (!VersePenetration::KeepsBoltHoles(Material) || PieceIndex == VersePenetration::NoPiece)+ {+ return EVerseHoleAddResult::NotHoleMaterial;+ }++ const FVerseBoltHole NewHole = FVerseBoltHole::Make(PieceIndex, AxisPointLocalCm, AxisDirectionLocal, RadiusMm, ServerTimeMs, Epoch);+ TArray<uint16, TInlineAllocator<2>> Touched;+ Touched.Add(PieceIndex);+ if (NumOnPiece(PieceIndex) >= HolesPerPiece)+ {+ if (VersePenetration::IsWallMaterial(Material))+ {+ // Hole 25 on a wall: the piece turns Holed with the variant nearest the hole centroid.+ FVector Centroid = NewHole.GetAxisPointCm();+ const TConstArrayView<FVerseBoltHole> Existing = GetPieceHoles(PieceIndex);+ for (const FVerseBoltHole& Hole : Existing)+ {+ Centroid += Hole.GetAxisPointCm();+ }+ Centroid /= double(Existing.Num() + 1);+ ClearPiece(PieceIndex);+ OnPieceHoleCap.Broadcast(PieceIndex, Centroid);+ return EVerseHoleAddResult::PieceHoled;+ }+ // Glass and ceiling panels: the piece's oldest hole goes.+ RemoveSlot(ByPiece.FindChecked(PieceIndex).SlotIndices[0]);+ }+ while (LiveCount >= HolesPerArena)+ {+ const int32 Before = LiveCount;+ EvictForArenaCap();+ if (LiveCount == Before)+ {+ break;+ }+ }++ const int32 SlotIndex = FreeSlots.IsEmpty() ? Slots.AddDefaulted() : FreeSlots.Pop(EAllowShrinking::No);+ FVerseBoltHoleSlot& Slot = Slots[SlotIndex];+ Slot.Hole = NewHole;+ Slot.Sequence = NextSequence++;+ if (NextSequence == 0)+ {+ NextSequence = 1;+ }+ FPieceHoles& Piece = ByPiece.FindOrAdd(PieceIndex);+ Piece.Holes.Add(NewHole);+ Piece.SlotIndices.Add(SlotIndex);+ Piece.Axes.Emplace(NewHole);+ ++LiveCount;+ Broadcast(Touched, false);+ return EVerseHoleAddResult::Added;+}++void UVerseBoltHoleComponent::RemoveSlot(int32 SlotIndex)+{+ if (!Slots.IsValidIndex(SlotIndex) || !Slots[SlotIndex].IsUsed())+ {+ return;+ }+ const uint16 PieceIndex = Slots[SlotIndex].Hole.PieceIndex;+ if (FPieceHoles* Piece = ByPiece.Find(PieceIndex))+ {+ const int32 At = Piece->SlotIndices.IndexOfByKey(SlotIndex);+ if (At != INDEX_NONE)+ {+ Piece->SlotIndices.RemoveAt(At);+ Piece->Holes.RemoveAt(At);+ Piece->Axes.RemoveAt(At);+ }+ if (Piece->SlotIndices.IsEmpty())+ {+ ByPiece.Remove(PieceIndex);+ }+ }+ Slots[SlotIndex] = FVerseBoltHoleSlot();+ FreeSlots.Add(SlotIndex);+ --LiveCount;+ const uint16 Touched[] = {PieceIndex};+ Broadcast(Touched, false);+}++void UVerseBoltHoleComponent::EvictForArenaCap()+{+ // The piece with the most holes; ties go to the piece whose oldest hole is older.+ int32 BestCount = -1;+ uint32 BestSequence = MAX_uint32;+ int32 BestSlot = INDEX_NONE;+ for (const TPair<uint16, FPieceHoles>& Pair : ByPiece)+ {+ const int32 Count = Pair.Value.SlotIndices.Num();+ if (Count == 0)+ {+ continue;+ }+ const int32 OldestSlot = Pair.Value.SlotIndices[0];+ const uint32 Sequence = Slots[OldestSlot].Sequence;+ if (Count > BestCount || (Count == BestCount && Sequence < BestSequence))+ {+ BestCount = Count;+ BestSequence = Sequence;+ BestSlot = OldestSlot;+ }+ }+ RemoveSlot(BestSlot);+}++void UVerseBoltHoleComponent::ClearPiece(uint16 PieceIndex)+{+ if (!HasServerAuthority())+ {+ return;+ }+ FPieceHoles Removed;+ if (!ByPiece.RemoveAndCopyValue(PieceIndex, Removed))+ {+ return;+ }+ for (const int32 SlotIndex : Removed.SlotIndices)+ {+ Slots[SlotIndex] = FVerseBoltHoleSlot();+ FreeSlots.Add(SlotIndex);+ --LiveCount;+ }+ const uint16 Touched[] = {PieceIndex};+ Broadcast(Touched, false);+}++void UVerseBoltHoleComponent::ResetAll(uint16 NewEpoch)+{+ if (!HasServerAuthority())+ {+ return;+ }+ Slots.Reset();+ FreeSlots.Reset();+ ByPiece.Reset();+ LiveCount = 0;+ Epoch = NewEpoch;+ Broadcast({}, true);+}++void UVerseBoltHoleComponent::Broadcast(TConstArrayView<uint16> Pieces, bool bAll)+{+ OnHolesChanged.Broadcast(Pieces, bAll);+}++void UVerseBoltHoleComponent::OnRep_Slots()+{+ // Find the pieces whose slots changed since the last update; rebuild only those.+ TArray<uint16, TInlineAllocator<8>> Touched;+ const int32 Count = FMath::Max(Slots.Num(), SeenSlots.Num());+ for (int32 Index = 0; Index < Count; ++Index)+ {+ const FVerseBoltHoleSlot* Now = Slots.IsValidIndex(Index) ? &Slots[Index] : nullptr;+ const FVerseBoltHoleSlot* Was = SeenSlots.IsValidIndex(Index) ? &SeenSlots[Index] : nullptr;+ if (Now && Was && *Now == *Was)+ {+ continue;+ }+ if (Now && Now->IsUsed())+ {+ Touched.AddUnique(Now->Hole.PieceIndex);+ }+ if (Was && Was->IsUsed())+ {+ Touched.AddUnique(Was->Hole.PieceIndex);+ }+ }+ SeenSlots = Slots;+ RebuildPieces(Touched);+ Broadcast(Touched, false);+}++void UVerseBoltHoleComponent::OnRep_Epoch()+{+ SeenSlots = Slots;+ RebuildAll();+ Broadcast({}, true);+}++void UVerseBoltHoleComponent::RebuildPieces(TConstArrayView<uint16> Pieces)+{+ if (Pieces.IsEmpty())+ {+ return;+ }+ struct FEntry+ {+ uint32 Sequence;+ int32 Slot;+ };+ TMap<uint16, TArray<FEntry>> Found;+ for (const uint16 Piece : Pieces)+ {+ Found.Add(Piece);+ if (const FPieceHoles* Old = ByPiece.Find(Piece))+ {+ LiveCount -= Old->SlotIndices.Num();+ }+ ByPiece.Remove(Piece);+ }+ for (int32 Index = 0; Index < Slots.Num(); ++Index)+ {+ // A client can briefly hold records of the previous epoch; they never count.+ if (!IsLiveSlot(Index))+ {+ continue;+ }+ if (TArray<FEntry>* Entries = Found.Find(Slots[Index].Hole.PieceIndex))+ {+ Entries->Add({Slots[Index].Sequence, Index});+ }+ }+ for (TPair<uint16, TArray<FEntry>>& Pair : Found)+ {+ if (Pair.Value.IsEmpty())+ {+ continue;+ }+ Pair.Value.Sort([](const FEntry& A, const FEntry& B) { return A.Sequence < B.Sequence; });+ FPieceHoles& Piece = ByPiece.Add(Pair.Key);+ for (const FEntry& Entry : Pair.Value)+ {+ Piece.Holes.Add(Slots[Entry.Slot].Hole);+ Piece.SlotIndices.Add(Entry.Slot);+ Piece.Axes.Emplace(Slots[Entry.Slot].Hole);+ }+ LiveCount += Pair.Value.Num();+ }+}++void UVerseBoltHoleComponent::RebuildAll()+{+ ByPiece.Reset();+ LiveCount = 0;+ TArray<uint16> Pieces;+ for (int32 Index = 0; Index < Slots.Num(); ++Index)+ {+ if (IsLiveSlot(Index))+ {+ Pieces.AddUnique(Slots[Index].Hole.PieceIndex);+ }+ }+ RebuildPieces(Pieces);+}++TConstArrayView<FVerseBoltHole> UVerseBoltHoleComponent::GetPieceHoles(uint16 PieceIndex) const+{+ const FPieceHoles* Found = ByPiece.Find(PieceIndex);+ return Found ? TConstArrayView<FVerseBoltHole>(Found->Holes) : TConstArrayView<FVerseBoltHole>();+}++void UVerseBoltHoleComponent::GetAllHoles(TArray<FVerseBoltHole>& OutHoles) const+{+ TArray<int32> Live;+ Live.Reserve(LiveCount);+ for (int32 Index = 0; Index < Slots.Num(); ++Index)+ {+ if (IsLiveSlot(Index))+ {+ Live.Add(Index);+ }+ }+ Live.Sort([this](int32 A, int32 B) { return Slots[A].Sequence < Slots[B].Sequence; });+ OutHoles.Reset(Live.Num());+ for (const int32 Index : Live)+ {+ OutHoles.Add(Slots[Index].Hole);+ }+}++UVerseBoltHoleComponent::FHoleAxis::FHoleAxis(const FVerseBoltHole& Hole)+ : PointCm(Hole.GetAxisPointCm())+ , Direction(Hole.GetAxisDirection())+{+ const double RadiusCm = double(Hole.RadiusMm) / 10.0;+ RadiusSq = RadiusCm * RadiusCm;+}++bool UVerseBoltHoleComponent::FHoleAxis::Contains(const FVector& PieceLocalCm) const+{+ // Exactly FVerseBoltHole::ContainsPoint, with the axis already decoded.+ const FVector Rel = PieceLocalCm - PointCm;+ return (Rel - Direction * FVector::DotProduct(Rel, Direction)).SizeSquared() <= RadiusSq;+}++bool UVerseBoltHoleComponent::RayPassesPieceHoles(uint16 PieceIndex, const FVector& EntryLocalCm, const FVector& ExitLocalCm) const+{+ const FPieceHoles* Found = ByPiece.Find(PieceIndex);+ if (!Found)+ {+ return false;+ }+ for (const FHoleAxis& Axis : Found->Axes)+ {+ if (Axis.Contains(EntryLocalCm) && Axis.Contains(ExitLocalCm))+ {+ return true;+ }+ }+ return false;+}++int32 UVerseBoltHoleComponent::NumOnPiece(uint16 PieceIndex) const+{+ const FPieceHoles* Found = ByPiece.Find(PieceIndex);+ return Found ? Found->SlotIndices.Num() : 0;+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleGlow.cpp b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleGlow.cppnew file mode 100644index 0000000000..b635314c09--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleGlow.cpp@@ -0,0 +1,109 @@+#include "Holes/VerseHoleGlow.h"++namespace VerseHoleGlow+{+ namespace+ {+ // Incandescent steel: hue drifts from about 38 deg (white-amber) to about 6 deg (dull red).+ const FLinearColor WhiteAmber(1.0f, 0.78f, 0.46f);+ const FLinearColor Amber(1.0f, 0.42f, 0.08f);+ const FLinearColor DullRed(0.62f, 0.07f, 0.02f);+ }++ FLinearColor ColorAt(float AgeS)+ {+ const float Age = FMath::Max(0.f, AgeS);+ if (Age <= 1.f)+ {+ return FMath::Lerp(WhiteAmber, Amber, Age);+ }+ const float T = FMath::Clamp((Age - 1.f) / 1.5f, 0.f, 1.f);+ return FMath::Lerp(Amber, DullRed, T);+ }++ FVerseHoleGlowSample Sample(float AgeS, float TauS, float EndS)+ {+ FVerseHoleGlowSample Out;+ const float Age = FMath::Max(0.f, AgeS);+ if (Age >= EndS || TauS <= 0.f)+ {+ Out.Color = CharredColor();+ return Out;+ }+ const float FadeStart = EndS - EndFadeS;+ const float Fade = Age <= FadeStart ? 1.f : FMath::Clamp((EndS - Age) / EndFadeS, 0.f, 1.f);+ Out.Color = ColorAt(Age);+ Out.Intensity = FMath::Exp(-Age / TauS) * Fade;+ Out.bGlowing = Out.Intensity > 0.f;+ return Out;+ }++ FLinearColor CharredColor()+ {+ return FLinearColor(0.018f, 0.014f, 0.011f);+ }++ float AgeS(uint32 TimeMs, uint32 NowMs, uint32 MaxFutureMs)+ {+ if (TimeMs <= NowMs)+ {+ return (NowMs - TimeMs) / 1000.f;+ }+ // Within the skew window a record from the future is fresh; beyond it the clock that+ // stamped it is not this one, and the hole reads as long cooled.+ return TimeMs - NowMs <= MaxFutureMs ? 0.f : MAX_flt;+ }++ TArray<int32> SelectGlowing(TConstArrayView<uint32> TimesMs, uint32 NowMs, int32 Cap, float EndS, uint32 MaxFutureMs)+ {+ TArray<int32> Young;+ for (int32 Index = 0; Index < TimesMs.Num(); ++Index)+ {+ if (AgeS(TimesMs[Index], NowMs, MaxFutureMs) < EndS)+ {+ Young.Add(Index);+ }+ }+ // Newest first; ties keep the later record.+ Young.Sort([&TimesMs](int32 A, int32 B) { return TimesMs[A] != TimesMs[B] ? TimesMs[A] > TimesMs[B] : A > B; });+ if (Cap >= 0 && Young.Num() > Cap)+ {+ Young.SetNum(Cap);+ }+ return Young;+ }++ bool IsBannedPixel(const FColor& Srgb)+ {+ const float R = Srgb.R / 255.f;+ const float G = Srgb.G / 255.f;+ const float B = Srgb.B / 255.f;+ const float Max = FMath::Max3(R, G, B);+ const float Min = FMath::Min3(R, G, B);+ const float Delta = Max - Min;+ const float Value = Max;+ const float Saturation = Max > 0.f ? Delta / Max : 0.f;+ if (Delta <= 0.f || Saturation <= 0.25f || Value <= 0.08f)+ {+ return false;+ }+ float Hue;+ if (Max == R)+ {+ Hue = 60.f * FMath::Fmod((G - B) / Delta, 6.f);+ }+ else if (Max == G)+ {+ Hue = 60.f * ((B - R) / Delta + 2.f);+ }+ else+ {+ Hue = 60.f * ((R - G) / Delta + 4.f);+ }+ if (Hue < 0.f)+ {+ Hue += 360.f;+ }+ return Hue >= 160.f && Hue <= 330.f;+ }+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleRenderComponent.cpp b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleRenderComponent.cppnew file mode 100644index 0000000000..ee78a11626--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Holes/VerseHoleRenderComponent.cpp@@ -0,0 +1,415 @@+#include "Holes/VerseHoleRenderComponent.h"++#include "Components/DecalComponent.h"+#include "Components/MeshComponent.h"+#include "Engine/Canvas.h"+#include "Engine/TextureRenderTarget2D.h"+#include "Engine/World.h"+#include "GameFramework/Actor.h"+#include "GameFramework/GameStateBase.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Holes/VerseHoleGlow.h"+#include "Kismet/KismetRenderingLibrary.h"+#include "Materials/MaterialInstanceDynamic.h"+#include "Materials/MaterialInterface.h"+#include "Misc/App.h"+#include "Misc/CommandLine.h"+#include "Misc/Parse.h"+#include "VerseLog.h"++namespace+{+ /** -nullrhi runs draw nothing. Read from the command line: VerseDestruction does not link RHI. */+ bool UsesNullRhi()+ {+ static const bool bNullRhi = FParse::Param(FCommandLine::Get(), TEXT("nullrhi"));+ return bNullRhi;+ }++ /** Rim decal footprint per hole radius (the charred rim is wider than the opening). */+ constexpr float RimFootprint = 1.8f;+ const TCHAR* const DefaultRimDecalPath = TEXT("/Game/Verse/Destruction/_Holes/M_HoleRim_Decal.M_HoleRim_Decal");++ /** The two axes of the largest face of a box and the thickness axis. */+ void FaceAxes(const FBox& Box, int32& U, int32& V, int32& Depth)+ {+ const FVector Size = Box.GetSize();+ Depth = Size.X <= Size.Y && Size.X <= Size.Z ? 0 : (Size.Y <= Size.Z ? 1 : 2);+ U = Depth == 0 ? 1 : 0;+ V = Depth == 2 ? 1 : 2;+ }+}++UVerseHoleRenderComponent::UVerseHoleRenderComponent()+{+ PrimaryComponentTick.bCanEverTick = true;+ PrimaryComponentTick.bStartWithTickEnabled = false;+ PrimaryComponentTick.TickInterval = 1.f / 30.f;+ SetIsReplicatedByDefault(false);+ RimDecalMaterial = TSoftObjectPtr<UMaterialInterface>(FSoftObjectPath(DefaultRimDecalPath));+}++bool UVerseHoleRenderComponent::CanRender(const UWorld* World)+{+ return World && World->GetNetMode() != NM_DedicatedServer && FApp::CanEverRender() && !UsesNullRhi();+}++void UVerseHoleRenderComponent::SetHoleSource(UVerseBoltHoleComponent* InHoles)+{+ if (UVerseBoltHoleComponent* Old = HoleSource.Get())+ {+ Old->OnHolesChanged.Remove(HolesChangedHandle);+ }+ HoleSource = InHoles;+ if (InHoles)+ {+ HolesChangedHandle = InHoles->OnHolesChanged.AddUObject(this, &UVerseHoleRenderComponent::HandleHolesChanged);+ }+ MarkAllDirty();+}++void UVerseHoleRenderComponent::RegisterPieceVisual(uint16 PieceIndex, UMeshComponent* Mesh, const FBox& LocalBounds, USceneComponent* Frame)+{+ FPieceVisual& Visual = Pieces.FindOrAdd(PieceIndex);+ Visual.Mesh = Mesh;+ Visual.Frame = Frame ? Frame : (Mesh && Mesh->GetOwner() ? Mesh->GetOwner()->GetRootComponent() : nullptr);+ Visual.LocalBounds = LocalBounds;+ DirtyPieces.Add(PieceIndex);+ DirtyVisuals.Add(PieceIndex);+ bDirty = true;+ SetComponentTickEnabled(true);+}++void UVerseHoleRenderComponent::SetServerTimeSource(TFunction<uint32()> InNow)+{+ NowMs = MoveTemp(InNow);+}++uint32 UVerseHoleRenderComponent::CurrentTimeMs() const+{+ if (NowMs)+ {+ return NowMs();+ }+ const UWorld* World = GetWorld();+ if (!World)+ {+ return 0;+ }+ // Hole records carry server time. A client world clock lags the server clock (a late joiner+ // by the whole match), so the glow ages against the replicated server clock.+ const AGameStateBase* GameState = World->GetGameState();+ const double Seconds = GameState ? GameState->GetServerWorldTimeSeconds() : World->GetTimeSeconds();+ return uint32(FMath::Max(0.0, Seconds) * 1000.0);+}++void UVerseHoleRenderComponent::HandleHolesChanged(TConstArrayView<uint16> InPieces, bool bAll)+{+ if (bAll)+ {+ bAllDirty = true;+ }+ DirtyPieces.Append(InPieces);+ bDirty = true;+ SetComponentTickEnabled(true);+}++void UVerseHoleRenderComponent::MarkAllDirty()+{+ HandleHolesChanged({}, true);+}++void UVerseHoleRenderComponent::EndPlay(const EEndPlayReason::Type Reason)+{+ SetHoleSource(nullptr);+ for (UDecalComponent* Decal : DecalPool)+ {+ if (Decal)+ {+ Decal->DestroyComponent();+ }+ }+ DecalPool.Reset();+ Masks.Reset();+ Super::EndPlay(Reason);+}++FVector2D UVerseHoleRenderComponent::HoleUV(const FBox& LocalBounds, const FVector& LocalPointCm)+{+ int32 U, V, Depth;+ FaceAxes(LocalBounds, U, V, Depth);+ const FVector Size = LocalBounds.GetSize();+ const FVector Rel = LocalPointCm - LocalBounds.Min;+ return FVector2D(Size[U] > 0.0 ? FMath::Clamp(Rel[U] / Size[U], 0.0, 1.0) : 0.5,+ Size[V] > 0.0 ? FMath::Clamp(1.0 - Rel[V] / Size[V], 0.0, 1.0) : 0.5);+}++float UVerseHoleRenderComponent::HoleRadiusPx(const FBox& LocalBounds, float RadiusCm, int32 InMaskSize)+{+ int32 U, V, Depth;+ FaceAxes(LocalBounds, U, V, Depth);+ const FVector Size = LocalBounds.GetSize();+ const double Longest = FMath::Max(Size[U], Size[V]);+ return Longest > 0.0 ? float(RadiusCm / Longest * InMaskSize) : 0.f;+}++UTextureRenderTarget2D* UVerseHoleRenderComponent::GetMask(uint16 PieceIndex) const+{+ const TObjectPtr<UTextureRenderTarget2D>* Found = Masks.Find(PieceIndex);+ return Found ? Found->Get() : nullptr;+}++void UVerseHoleRenderComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)+{+ Super::TickComponent(DeltaTime, TickType, ThisTickFunction);+ Sync();+ if (!bDirty && GlowingCount == 0)+ {+ SetComponentTickEnabled(false);+ }+}++void UVerseHoleRenderComponent::Sync()+{+ if (bDirty)+ {+ RebuildSlots();+ bDirty = false;+ }+ UpdateGlow();+}++UDecalComponent* UVerseHoleRenderComponent::AcquireDecal(int32 Index)+{+ if (DecalPool.IsValidIndex(Index) && DecalPool[Index])+ {+ return DecalPool[Index];+ }+ AActor* Owner = GetOwner();+ if (!Owner)+ {+ return nullptr;+ }+ UDecalComponent* Decal = NewObject<UDecalComponent>(Owner, NAME_None, RF_Transient);+ Decal->SetupAttachment(Owner->GetRootComponent());+ Decal->RegisterComponent();+ if (DecalPool.Num() <= Index)+ {+ DecalPool.SetNum(Index + 1);+ }+ DecalPool[Index] = Decal;+ return Decal;+}++void UVerseHoleRenderComponent::RebuildSlots()+{+ const UVerseBoltHoleComponent* Source = HoleSource.Get();+ const TConstArrayView<FVerseBoltHoleSlot> Slots = Source ? Source->GetSlots() : TConstArrayView<FVerseBoltHoleSlot>();++ const bool bRender = CanRender(GetWorld());+ UMaterialInterface* RimMaterial = bRender ? RimDecalMaterial.LoadSynchronous() : nullptr;+ if (bRender && !RimMaterial && !bWarnedNoMaterial)+ {+ UE_LOG(LogVerseDestruction, Warning, TEXT("hole rim decal material %s missing; holes render as masks only"),+ *RimDecalMaterial.ToString());+ bWarnedNoMaterial = true;+ }++ // The hole component keeps every hole at a stable slot index, so a change touches only the+ // slots whose hole is new or gone; the decal of a slot follows the hole that lives in it.+ if (bAllDirty)+ {+ DirtyPieces.Append(MaskPieces);+ DirtyVisuals.Append(MaskPieces);+ }+ const int32 Count = FMath::Max(Slots.Num(), HoleSlots.Num());+ HoleSlots.SetNum(Count);+ LiveSlots = 0;+ for (int32 Index = 0; Index < Count; ++Index)+ {+ FHoleSlot& Slot = HoleSlots[Index];+ const bool bLive = Slots.IsValidIndex(Index) && Source->IsLiveSlot(Index);+ const uint32 Sequence = bLive ? Slots[Index].Sequence : 0;+ if (bLive)+ {+ ++LiveSlots;+ if (bAllDirty)+ {+ DirtyPieces.Add(Slots[Index].Hole.PieceIndex);+ }+ }+ const bool bChanged = Slot.Sequence != Sequence;+ const bool bVisualChanged = bLive && (bAllDirty || DirtyVisuals.Contains(Slots[Index].Hole.PieceIndex));+ if (!bChanged && !bVisualChanged)+ {+ continue;+ }+ if (bChanged && Slot.Sequence != 0)+ {+ DirtyPieces.Add(Slot.Hole.PieceIndex);+ }+ Slot.Sequence = Sequence;+ Slot.bGlowing = false;+ if (!bLive)+ {+ Slot.Hole = FVerseBoltHole();+ if (UDecalComponent* Decal = Slot.Decal.Get())+ {+ Decal->SetVisibility(false);+ }+ continue;+ }+ Slot.Hole = Slots[Index].Hole;+ DirtyPieces.Add(Slot.Hole.PieceIndex);+ ++SlotUpdates;+ PlaceDecal(Index, RimMaterial);+ }+ // After a reset the slot array is shorter: hide and drop the rest.+ for (int32 Index = Slots.Num(); Index < HoleSlots.Num(); ++Index)+ {+ if (UDecalComponent* Decal = HoleSlots[Index].Decal.Get())+ {+ Decal->SetVisibility(false);+ }+ }+ HoleSlots.SetNum(Slots.Num());++ // A piece gets its mask on its first hole and keeps it (cleared) until the component goes.+ TSet<uint16> ToDraw;+ for (const uint16 PieceIndex : DirtyPieces)+ {+ if (Source && Source->NumOnPiece(PieceIndex) > 0)+ {+ MaskPieces.Add(PieceIndex);+ }+ if (MaskPieces.Contains(PieceIndex))+ {+ ToDraw.Add(PieceIndex);+ }+ }+ DirtyPieces.Reset();+ DirtyVisuals.Reset();+ bAllDirty = false;+ MaskRedraws += ToDraw.Num();+ RedrawMasks(ToDraw);+}++void UVerseHoleRenderComponent::PlaceDecal(int32 Index, UMaterialInterface* RimMaterial)+{+ FHoleSlot& Slot = HoleSlots[Index];+ const FPieceVisual* Visual = Pieces.Find(Slot.Hole.PieceIndex);+ const USceneComponent* Frame = Visual ? Visual->Frame.Get() : nullptr;+ if (!RimMaterial || !Frame)+ {+ return;+ }+ UDecalComponent* Decal = AcquireDecal(Index);+ if (!Decal)+ {+ return;+ }+ const FTransform& PieceToWorld = Frame->GetComponentTransform();+ const FVector AxisWorld = PieceToWorld.TransformVectorNoScale(Slot.Hole.GetAxisDirection());+ const float RadiusCm = Slot.Hole.RadiusMm / 10.f;+ const float HalfDepth = float(Visual->LocalBounds.GetExtent().GetMin()) + 0.5f;+ Decal->SetWorldLocationAndRotation(PieceToWorld.TransformPosition(Slot.Hole.GetAxisPointCm()), FRotationMatrix::MakeFromX(AxisWorld).Rotator());+ Decal->DecalSize = FVector(HalfDepth, RadiusCm * RimFootprint, RadiusCm * RimFootprint);+ UMaterialInstanceDynamic* Mid = Cast<UMaterialInstanceDynamic>(Decal->GetDecalMaterial());+ if (!Mid || Mid->Parent != RimMaterial)+ {+ Mid = UMaterialInstanceDynamic::Create(RimMaterial, this);+ Decal->SetDecalMaterial(Mid);+ }+ Decal->SetVisibility(true);+ Decal->MarkRenderStateDirty();+ Slot.Decal = Decal;+ Slot.Material = Mid;+}++void UVerseHoleRenderComponent::RedrawMasks(const TSet<uint16>& PiecesToDraw)+{+ if (!CanRender(GetWorld()))+ {+ return;+ }+ for (const uint16 PieceIndex : PiecesToDraw)+ {+ const FPieceVisual* Visual = Pieces.Find(PieceIndex);+ if (!Visual)+ {+ continue;+ }+ UTextureRenderTarget2D* Mask = GetMask(PieceIndex);+ if (!Mask)+ {+ Mask = UKismetRenderingLibrary::CreateRenderTarget2D(this, MaskSize, MaskSize, RTF_R8, FLinearColor::White);+ Masks.Add(PieceIndex, Mask);+ if (UMeshComponent* Mesh = Visual->Mesh.Get())+ {+ for (int32 Slot = 0; Slot < Mesh->GetNumMaterials(); ++Slot)+ {+ if (UMaterialInstanceDynamic* Mid = Mesh->CreateDynamicMaterialInstance(Slot))+ {+ Mid->SetTextureParameterValue(MaskParameter, Mask);+ }+ }+ }+ }+ UKismetRenderingLibrary::ClearRenderTarget2D(this, Mask, FLinearColor::White);+ UCanvas* Canvas = nullptr;+ FVector2D Size;+ FDrawToRenderTargetContext Context;+ UKismetRenderingLibrary::BeginDrawCanvasToRenderTarget(this, Mask, Canvas, Size, Context);+ if (Canvas)+ {+ const UVerseBoltHoleComponent* Source = HoleSource.Get();+ const TConstArrayView<FVerseBoltHole> PieceHoles = Source ? Source->GetPieceHoles(PieceIndex) : TConstArrayView<FVerseBoltHole>();+ for (const FVerseBoltHole& Hole : PieceHoles)+ {+ const FVector2D Uv = HoleUV(Visual->LocalBounds, Hole.GetAxisPointCm());+ const float Radius = HoleRadiusPx(Visual->LocalBounds, Hole.RadiusMm / 10.f, MaskSize);+ Canvas->K2_DrawPolygon(nullptr, Uv * Size, FVector2D(Radius, Radius), 24, FLinearColor::Black);+ }+ }+ UKismetRenderingLibrary::EndDrawCanvasToRenderTarget(this, Context);+ }+}++void UVerseHoleRenderComponent::UpdateGlow()+{+ const uint32 Now = CurrentTimeMs();+ TArray<uint32> Times;+ TArray<int32> SlotOf;+ Times.Reserve(LiveSlots);+ SlotOf.Reserve(LiveSlots);+ for (int32 Index = 0; Index < HoleSlots.Num(); ++Index)+ {+ if (HoleSlots[Index].Sequence != 0)+ {+ Times.Add(HoleSlots[Index].Hole.ServerTimeMs);+ SlotOf.Add(Index);+ }+ }+ const TArray<int32> Glowing = VerseHoleGlow::SelectGlowing(Times, Now, GlowingCap, GlowEndS);+ TBitArray<> IsGlowing(false, HoleSlots.Num());+ for (const int32 Index : Glowing)+ {+ IsGlowing[SlotOf[Index]] = true;+ }+ GlowingCount = Glowing.Num();+ for (int32 Index = 0; Index < HoleSlots.Num(); ++Index)+ {+ FHoleSlot& Slot = HoleSlots[Index];+ const bool bWasGlowing = Slot.bGlowing;+ Slot.bGlowing = IsGlowing[Index];+ UMaterialInstanceDynamic* Mid = Slot.Material.Get();+ if (!Mid || Slot.Sequence == 0 || (!Slot.bGlowing && !bWasGlowing))+ {+ continue;+ }+ const float AgeS = VerseHoleGlow::AgeS(Slot.Hole.ServerTimeMs, Now);+ const FVerseHoleGlowSample Sample = Slot.bGlowing ? VerseHoleGlow::Sample(AgeS, GlowTauS, GlowEndS) : FVerseHoleGlowSample();+ Mid->SetScalarParameterValue(GlowParameter, Sample.Intensity * VerseHoleGlow::PeakEmissive);+ Mid->SetVectorParameterValue(GlowColorParameter, Sample.bGlowing ? Sample.Color : VerseHoleGlow::CharredColor());+ }+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationJson.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationJson.cppnew file mode 100644index 0000000000..2531bf430c--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationJson.cpp@@ -0,0 +1,374 @@+#include "Penetration/VersePenetrationJson.h"++#include "Misc/Parse.h"++namespace+{+ class FReader+ {+ public:+ explicit FReader(const FString& InText) : Text(InText) {}++ bool ReadDocument(FVerseJson& Out, FString& OutError)+ {+ SkipSpace();+ if (!ReadValue(Out, 0))+ {+ OutError = FString::Printf(TEXT("%s at offset %d"), *Error, Pos);+ return false;+ }+ SkipSpace();+ if (Pos != Text.Len())+ {+ OutError = FString::Printf(TEXT("trailing text at offset %d"), Pos);+ return false;+ }+ return true;+ }++ private:+ const FString& Text;+ int32 Pos = 0;+ FString Error;++ static constexpr int32 MaxDepth = 64;++ TCHAR Peek() const { return Pos < Text.Len() ? Text[Pos] : TCHAR(0); }++ void SkipSpace()+ {+ while (Pos < Text.Len() && (Text[Pos] == ' ' || Text[Pos] == '\t' || Text[Pos] == '\r' || Text[Pos] == '\n'))+ {+ ++Pos;+ }+ }++ bool Fail(const TCHAR* What)+ {+ Error = What;+ return false;+ }++ bool Literal(const TCHAR* Word)+ {+ const int32 Len = FCString::Strlen(Word);+ if (Text.Len() - Pos >= Len && FCString::Strncmp(*Text + Pos, Word, Len) == 0)+ {+ Pos += Len;+ return true;+ }+ return false;+ }++ bool ReadValue(FVerseJson& Out, int32 Depth)+ {+ if (Depth > MaxDepth)+ {+ return Fail(TEXT("nesting too deep"));+ }+ SkipSpace();+ const TCHAR C = Peek();+ if (C == '{')+ {+ return ReadObject(Out, Depth);+ }+ if (C == '[')+ {+ return ReadArray(Out, Depth);+ }+ if (C == '"')+ {+ Out.Type = FVerseJson::EType::String;+ return ReadString(Out.String);+ }+ if (Literal(TEXT("true")))+ {+ Out.Type = FVerseJson::EType::Bool;+ Out.Bool = true;+ return true;+ }+ if (Literal(TEXT("false")))+ {+ Out.Type = FVerseJson::EType::Bool;+ Out.Bool = false;+ return true;+ }+ if (Literal(TEXT("null")))+ {+ Out.Type = FVerseJson::EType::Null;+ return true;+ }+ if (C == '-' || FChar::IsDigit(C))+ {+ return ReadNumber(Out);+ }+ return Fail(TEXT("unexpected character"));+ }++ bool ReadNumber(FVerseJson& Out)+ {+ const int32 Start = Pos;+ if (Peek() == '-')+ {+ ++Pos;+ }+ if (!FChar::IsDigit(Peek()))+ {+ return Fail(TEXT("bad number"));+ }+ while (FChar::IsDigit(Peek()))+ {+ ++Pos;+ }+ if (Peek() == '.')+ {+ ++Pos;+ if (!FChar::IsDigit(Peek()))+ {+ return Fail(TEXT("bad number"));+ }+ while (FChar::IsDigit(Peek()))+ {+ ++Pos;+ }+ }+ if (Peek() == 'e' || Peek() == 'E')+ {+ ++Pos;+ if (Peek() == '+' || Peek() == '-')+ {+ ++Pos;+ }+ if (!FChar::IsDigit(Peek()))+ {+ return Fail(TEXT("bad number"));+ }+ while (FChar::IsDigit(Peek()))+ {+ ++Pos;+ }+ }+ Out.Type = FVerseJson::EType::Number;+ Out.Number = FCString::Atod(*Text.Mid(Start, Pos - Start));+ return true;+ }++ bool ReadString(FString& Out)+ {+ ++Pos; // opening quote+ Out.Reset();+ while (Pos < Text.Len())+ {+ const TCHAR C = Text[Pos++];+ if (C == '"')+ {+ return true;+ }+ if (C != '\\')+ {+ Out.AppendChar(C);+ continue;+ }+ if (Pos >= Text.Len())+ {+ break;+ }+ const TCHAR E = Text[Pos++];+ switch (E)+ {+ case '"': Out.AppendChar('"'); break;+ case '\\': Out.AppendChar('\\'); break;+ case '/': Out.AppendChar('/'); break;+ case 'b': Out.AppendChar('\b'); break;+ case 'f': Out.AppendChar('\f'); break;+ case 'n': Out.AppendChar('\n'); break;+ case 'r': Out.AppendChar('\r'); break;+ case 't': Out.AppendChar('\t'); break;+ case 'u':+ {+ if (Text.Len() - Pos < 4)+ {+ return Fail(TEXT("bad unicode escape"));+ }+ uint32 Code = 0;+ for (int32 I = 0; I < 4; ++I)+ {+ const TCHAR H = Text[Pos++];+ if (!FChar::IsHexDigit(H))+ {+ return Fail(TEXT("bad unicode escape"));+ }+ Code = Code * 16 + FParse::HexDigit(H);+ }+ Out.AppendChar(TCHAR(Code));+ break;+ }+ default:+ return Fail(TEXT("bad escape"));+ }+ }+ return Fail(TEXT("unterminated string"));+ }++ bool ReadArray(FVerseJson& Out, int32 Depth)+ {+ ++Pos;+ Out.Type = FVerseJson::EType::Array;+ SkipSpace();+ if (Peek() == ']')+ {+ ++Pos;+ return true;+ }+ while (true)+ {+ if (!ReadValue(Out.Array.AddDefaulted_GetRef(), Depth + 1))+ {+ return false;+ }+ SkipSpace();+ if (Peek() == ',')+ {+ ++Pos;+ continue;+ }+ if (Peek() == ']')+ {+ ++Pos;+ return true;+ }+ return Fail(TEXT("expected , or ]"));+ }+ }++ bool ReadObject(FVerseJson& Out, int32 Depth)+ {+ ++Pos;+ Out.Type = FVerseJson::EType::Object;+ SkipSpace();+ if (Peek() == '}')+ {+ ++Pos;+ return true;+ }+ while (true)+ {+ SkipSpace();+ if (Peek() != '"')+ {+ return Fail(TEXT("expected a key"));+ }+ TPair<FString, FVerseJson>& Member = Out.Object.AddDefaulted_GetRef();+ if (!ReadString(Member.Key))+ {+ return false;+ }+ SkipSpace();+ if (Peek() != ':')+ {+ return Fail(TEXT("expected :"));+ }+ ++Pos;+ if (!ReadValue(Member.Value, Depth + 1))+ {+ return false;+ }+ SkipSpace();+ if (Peek() == ',')+ {+ ++Pos;+ continue;+ }+ if (Peek() == '}')+ {+ ++Pos;+ return true;+ }+ return Fail(TEXT("expected , or }"));+ }+ }+ };+}++bool FVerseJson::Parse(const FString& Text, FVerseJson& Out, FString& OutError)+{+ Out = FVerseJson();+ FReader Reader(Text);+ return Reader.ReadDocument(Out, OutError);+}++const FVerseJson* FVerseJson::Find(const TCHAR* Key) const+{+ if (Type != EType::Object)+ {+ return nullptr;+ }+ for (const TPair<FString, FVerseJson>& Member : Object)+ {+ if (Member.Key == Key)+ {+ return &Member.Value;+ }+ }+ return nullptr;+}++bool FVerseJson::TryNumber(const TCHAR* Key, double& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::Number)+ {+ Out = V->Number;+ return true;+ }+ return false;+}++bool FVerseJson::TryString(const TCHAR* Key, FString& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::String)+ {+ Out = V->String;+ return true;+ }+ return false;+}++bool FVerseJson::TryBool(const TCHAR* Key, bool& Out) const+{+ const FVerseJson* V = Find(Key);+ if (V && V->Type == EType::Bool)+ {+ Out = V->Bool;+ return true;+ }+ return false;+}++const TArray<FVerseJson>* FVerseJson::FindArray(const TCHAR* Key) const+{+ const FVerseJson* V = Find(Key);+ return V && V->Type == EType::Array ? &V->Array : nullptr;+}++double FVerseJson::NumberOr(const TCHAR* Key, double Default) const+{+ double Out = Default;+ TryNumber(Key, Out);+ return Out;+}++FString FVerseJson::StringOr(const TCHAR* Key, const FString& Default) const+{+ FString Out = Default;+ TryString(Key, Out);+ return Out;+}++bool FVerseJson::BoolOr(const TCHAR* Key, bool Default) const+{+ bool Out = Default;+ TryBool(Key, Out);+ return Out;+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationMath.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationMath.cppnew file mode 100644index 0000000000..27f47ff256--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationMath.cpp@@ -0,0 +1,59 @@+#include "Penetration/VersePenetrationMath.h"++namespace VersePenetration+{+ int32 EffectiveMaxPieces(int32 WeaponMaxPieces)+ {+ return FMath::Clamp(WeaponMaxPieces, 0, Verse::Destruction::MaxPenetrations);+ }++ FVersePenetrationStep EvaluatePiece(const FVersePenetrationRow& Row, float TracedThicknessCm, float Power, float Damage,+ bool bLimitReached)+ {+ FVersePenetrationStep Step;+ Step.Cost = UVersePenetrationTable::PassCost(Row, TracedThicknessCm);+ Step.bPassed = !bLimitReached && Power >= Step.Cost;+ if (Step.bPassed)+ {+ Step.PowerLeft = Power - Step.Cost;+ Step.DamageLeft = Damage * Row.DamageMultiplier;+ }+ return Step;+ }++ bool KeepsBoltHoles(EVersePenetrationMaterial Material)+ {+ switch (Material)+ {+ case EVersePenetrationMaterial::SheetMetal:+ case EVersePenetrationMaterial::ContainerWall:+ case EVersePenetrationMaterial::Glass:+ case EVersePenetrationMaterial::CladdingPanel:+ case EVersePenetrationMaterial::CeilingPanel:+ return true;+ default:+ return false;+ }+ }++ bool IsWallMaterial(EVersePenetrationMaterial Material)+ {+ return Material == EVersePenetrationMaterial::SheetMetal || Material == EVersePenetrationMaterial::ContainerWall+ || Material == EVersePenetrationMaterial::CladdingPanel;+ }++ TConstArrayView<const TCHAR*> FrozenMaterialIds()+ {+ static const TCHAR* const Ids[] = {+ TEXT("sheet_metal"),+ TEXT("container_wall"),+ TEXT("glass"),+ TEXT("cladding_panel"),+ TEXT("catwalk_grating"),+ TEXT("ceiling_panel"),+ TEXT("concrete"),+ TEXT("armor_steel"),+ };+ return Ids;+ }+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationPhysicalMaterial.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationPhysicalMaterial.cppnew file mode 100644index 0000000000..c3a361d470--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationPhysicalMaterial.cpp@@ -0,0 +1,57 @@+#include "Penetration/VersePenetrationPhysicalMaterial.h"++namespace VersePenetration+{+ EVersePenetrationMaterial WorldSurfaceMaterial(EVerseWorldSurface Surface)+ {+ switch (Surface)+ {+ case EVerseWorldSurface::StructuralBeam:+ return EVersePenetrationMaterial::ArmorSteel;+ case EVerseWorldSurface::HallFloor:+ case EVerseWorldSurface::StructuralWall:+ default:+ return EVersePenetrationMaterial::Concrete;+ }+ }++ FString PhysicalMaterialName(EVerseWorldSurface Surface)+ {+ switch (Surface)+ {+ case EVerseWorldSurface::HallFloor:+ return TEXT("PM_Verse_HallFloor");+ case EVerseWorldSurface::StructuralBeam:+ return TEXT("PM_Verse_StructuralBeam");+ case EVerseWorldSurface::StructuralWall:+ default:+ return TEXT("PM_Verse_StructuralWall");+ }+ }++ bool SurfaceFromPhysicalMaterialName(const FString& Name, EVerseWorldSurface& OutSurface)+ {+ const EVerseWorldSurface Surfaces[] = {EVerseWorldSurface::HallFloor, EVerseWorldSurface::StructuralWall, EVerseWorldSurface::StructuralBeam};+ for (const EVerseWorldSurface Surface : Surfaces)+ {+ const FString Base = PhysicalMaterialName(Surface);+ if (Name.Equals(Base, ESearchCase::IgnoreCase)+ || (Name.StartsWith(Base + TEXT("_"), ESearchCase::IgnoreCase)))+ {+ OutSurface = Surface;+ return true;+ }+ }+ return false;+ }++ EVersePenetrationMaterial ResolveWorldMaterial(const UObject* PhysicalMaterial)+ {+ EVerseWorldSurface Surface = EVerseWorldSurface::StructuralWall;+ if (PhysicalMaterial && SurfaceFromPhysicalMaterialName(PhysicalMaterial->GetName(), Surface))+ {+ return WorldSurfaceMaterial(Surface);+ }+ return EVersePenetrationMaterial::Concrete;+ }+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationSubsystem.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationSubsystem.cppnew file mode 100644index 0000000000..cf212efa3a--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationSubsystem.cpp@@ -0,0 +1,380 @@+#include "Penetration/VersePenetrationSubsystem.h"++#include "Components/PrimitiveComponent.h"+#include "Destruction/VersePenetrationTable.h"+#include "Engine/World.h"+#include "GameFramework/Actor.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Misc/Paths.h"+#include "Penetration/VersePenetrationMath.h"+#include "Penetration/VersePenetrationPhysicalMaterial.h"+#include "Penetration/VersePenetrationTableImport.h"+#include "PhysicalMaterials/PhysicalMaterial.h"+#include "VerseCollision.h"+#include "VerseLog.h"++namespace+{+ /** Probe offset in front of a later shape entry: off the surface, well below any modelled gap. */+ constexpr double ProbeBackoffCm = 0.05;+ /** Entries closer than this to a run's start belong to that run. */+ constexpr double SameEntryCm = 0.01;++ /** A reverse trace from Probe back to RunStart that meets a surface of Component: Probe was in air, OutExit is the run's exit. */+ bool ReverseExit(const UPrimitiveComponent& Component, const FVector& Probe, const FVector& RunStart, FVector& OutExit)+ {+ FHitResult Hit;+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VersePenetrationExit), false);+ if (const_cast<UPrimitiveComponent&>(Component).LineTraceComponent(Hit, Probe, RunStart, Params) && !Hit.bStartPenetrating+ && Hit.Distance > UE_KINDA_SMALL_NUMBER)+ {+ OutExit = Hit.ImpactPoint;+ return true;+ }+ return false;+ }+}++void UVersePenetrationSubsystem::Initialize(FSubsystemCollectionBase& Collection)+{+ Super::Initialize(Collection);+ Table = VersePenetrationImport::LoadRuntimeTable(this);+}++void UVersePenetrationSubsystem::Deinitialize()+{+ Proxies.Reset();+ PieceFrames.Reset();+ PieceQuery = nullptr;+ HoleSource.Reset();+ Super::Deinitialize();+}++void UVersePenetrationSubsystem::SetTable(UVersePenetrationTable* InTable)+{+ if (InTable)+ {+ Table = InTable;+ }+}++void UVersePenetrationSubsystem::SetPieceQuery(const IVersePieceQuery* InPieceQuery)+{+ PieceQuery = InPieceQuery;+}++void UVersePenetrationSubsystem::SetHoleSource(UVerseBoltHoleComponent* InHoles)+{+ HoleSource = InHoles;+}++void UVersePenetrationSubsystem::RegisterPieceProxy(UPrimitiveComponent* Proxy, uint16 PieceIndex, EVersePenetrationMaterial Material,+ USceneComponent* Frame)+{+ if (!Proxy)+ {+ return;+ }+ USceneComponent* PieceFrame = Frame;+ if (!PieceFrame)+ {+ const AActor* Owner = Proxy->GetOwner();+ PieceFrame = Owner && Owner->GetRootComponent() ? Owner->GetRootComponent() : Proxy;+ }+ FVersePieceProxyInfo Info;+ Info.PieceIndex = PieceIndex;+ Info.Material = Material;+ Info.Frame = PieceFrame;+ Proxies.Add(TObjectKey<UPrimitiveComponent>(Proxy), Info);+ PieceFrames.Add(PieceIndex, PieceFrame);+}++void UVersePenetrationSubsystem::UnregisterPieceProxy(UPrimitiveComponent* Proxy)+{+ Proxies.Remove(TObjectKey<UPrimitiveComponent>(Proxy));+}++const FVersePieceProxyInfo* UVersePenetrationSubsystem::FindPieceProxy(const UPrimitiveComponent* Proxy) const+{+ return Proxy ? Proxies.Find(TObjectKey<UPrimitiveComponent>(Proxy)) : nullptr;+}++bool UVersePenetrationSubsystem::GetPieceFrame(uint16 PieceIndex, FTransform& OutPieceToWorld) const+{+ const TWeakObjectPtr<USceneComponent>* Frame = PieceFrames.Find(PieceIndex);+ if (!Frame || !Frame->IsValid())+ {+ return false;+ }+ OutPieceToWorld = (*Frame)->GetComponentTransform();+ return true;+}++EVersePieceState UVersePenetrationSubsystem::PieceState(uint16 PieceIndex) const+{+ return PieceQuery ? PieceQuery->GetPieceState(PieceIndex) : EVersePieceState::Intact;+}++bool UVersePenetrationSubsystem::FindExit(const UPrimitiveComponent& Component, const FVector& Entry, const FVector& Dir, FVector& OutExit)+{+ FVersePenetrationRuns Runs;+ const bool bFound = FindSolidRuns(Component, Entry, Dir, {}, Runs);+ OutExit = Runs.Last().Exit;+ return bFound;+}++bool UVersePenetrationSubsystem::FindSolidRuns(const UPrimitiveComponent& Component, const FVector& Entry, const FVector& Dir,+ TConstArrayView<FVector> LaterEntries, FVersePenetrationRuns& OutRuns)+{+ OutRuns.Reset();+ FVector RunStart = Entry;+ for (const FVector& Next : LaterEntries)+ {+ // The entry of another shape of the same component: if the point just in front of it is+ // in air, the run that started at RunStart ended at the surface a reverse trace meets first.+ if (FVector::DotProduct(Next - RunStart, Dir) <= ProbeBackoffCm + SameEntryCm)+ {+ continue;+ }+ FVector Exit;+ if (ReverseExit(Component, Next - Dir * ProbeBackoffCm, RunStart, Exit))+ {+ OutRuns.Add({RunStart, Exit});+ RunStart = Next;+ }+ }+ const double Reach = 2.0 * Component.Bounds.SphereRadius + 1.0;+ FVector Exit;+ const bool bFound = ReverseExit(Component, RunStart + Dir * Reach, RunStart, Exit);+ OutRuns.Add({RunStart, bFound ? Exit : RunStart});+ return bFound;+}++void UVersePenetrationSubsystem::CollectCrossings(const FVector& Start, const FVector& End, ECollisionChannel Channel, const FName StatName,+ FVersePenetrationCrossings& OutCrossings) const+{+ OutCrossings.Reset();+ const UWorld* World = GetWorld();+ const FVector Direction = (End - Start).GetSafeNormal();+ if (!World || Direction.IsNearlyZero())+ {+ return;+ }+ // One query for the whole segment: every blocking response is read as an overlap, so the+ // multi trace lists each shape the channel would hit (Chaos reports one hit per shape).+ // Whatever ignores the channel (pawn capsules, debris) still ignores it.+ FCollisionQueryParams Params(StatName, false);+ Params.bReturnPhysicalMaterial = true;+ FCollisionResponseParams Responses;+ Responses.CollisionResponse.SetAllChannels(ECR_Overlap);+ TArray<FHitResult> Shapes;+ World->LineTraceMultiByChannel(Shapes, Start, End, Channel, Params, Responses);+ Shapes.StableSort([](const FHitResult& A, const FHitResult& B) { return A.Distance < B.Distance; });++ // One crossing per component, in the order of its first entry. The later shape entries of the+ // same component split it into solid runs.+ TArray<TArray<FVector, TInlineAllocator<4>>, TInlineAllocator<8>> LaterEntries;+ for (const FHitResult& Hit : Shapes)+ {+ const UPrimitiveComponent* Component = Hit.GetComponent();+ if (!Component)+ {+ continue;+ }+ const FVector Entry = Hit.bStartPenetrating ? Start : FVector(Hit.ImpactPoint);+ const int32 Existing =+ OutCrossings.IndexOfByPredicate([Component](const FVersePenetrationCrossing& Crossing) { return Crossing.Component == Component; });+ if (Existing != INDEX_NONE)+ {+ LaterEntries[Existing].Add(Entry);+ continue;+ }+ if (OutCrossings.Num() >= MaxSurfacesPerQuery)+ {+ OutCrossings.Last().bTruncated = true;+ break;+ }+ FVersePenetrationCrossing& Crossing = OutCrossings.AddDefaulted_GetRef();+ Crossing.Component = Component;+ Crossing.BoneName = Hit.BoneName;+ Crossing.PhysMaterial = Hit.PhysMaterial;+ Crossing.Entry = Entry;+ LaterEntries.AddDefaulted();+ }+ for (int32 Index = 0; Index < OutCrossings.Num(); ++Index)+ {+ FVersePenetrationCrossing& Crossing = OutCrossings[Index];+ FindSolidRuns(*Crossing.Component, Crossing.Entry, Direction, LaterEntries[Index], Crossing.Runs);+ Crossing.Exit = Crossing.Runs.Last().Exit;+ Crossing.SolidCm = 0.0;+ for (const FVersePenetrationRun& Run : Crossing.Runs)+ {+ Crossing.SolidCm += FVector::Dist(Run.Entry, Run.Exit);+ }+ }+}++bool UVersePenetrationSubsystem::PassesHoles(const FVersePieceProxyInfo& Info, const FVector& EntryWorld, const FVector& ExitWorld) const+{+ const UVerseBoltHoleComponent* Holes = HoleSource.Get();+ const USceneComponent* Frame = Info.Frame.Get();+ if (!Holes || !Frame)+ {+ return false;+ }+ if (Holes->NumOnPiece(Info.PieceIndex) == 0)+ {+ return false;+ }+ const FTransform& PieceToWorld = Frame->GetComponentTransform();+ return Holes->RayPassesPieceHoles(Info.PieceIndex, PieceToWorld.InverseTransformPosition(EntryWorld),+ PieceToWorld.InverseTransformPosition(ExitWorld));+}++bool UVersePenetrationSubsystem::PassesHoles(const FVersePieceProxyInfo& Info, const FVersePenetrationCrossing& Crossing) const+{+ // Every solid run of the proxy must lie inside a hole; one solid run without a hole blocks.+ for (const FVersePenetrationRun& Run : Crossing.Runs)+ {+ if (!PassesHoles(Info, Run.Entry, Run.Exit))+ {+ return false;+ }+ }+ return !Crossing.Runs.IsEmpty();+}++TArray<FVersePenetrationHit> UVersePenetrationSubsystem::TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power,+ float Damage, uint8 RadiusMm, int32 MaxPieces) const+{+ TArray<FVersePenetrationHit> Result;+ const FVector Direction = Dir.GetSafeNormal();+ if (!GetWorld() || !Table || Direction.IsNearlyZero() || MaxDist <= 0.f)+ {+ return Result;+ }+ const int32 Limit = VersePenetration::EffectiveMaxPieces(MaxPieces);+ FVersePenetrationCrossings Crossings;+ CollectCrossings(Origin, Origin + Direction * MaxDist, VerseCollision::Bolt, SCENE_QUERY_STAT_NAME_ONLY(VerseTraceBolt), Crossings);++ float PowerLeft = Power;+ float DamageLeft = Damage;+ int32 Passes = 0;+ for (const FVersePenetrationCrossing& Crossing : Crossings)+ {+ const UPrimitiveComponent* Component = Crossing.Component;+ const FVersePieceProxyInfo* Info = FindPieceProxy(Component);+ if (Info && PassesHoles(*Info, Crossing))+ {+ // Flown through an existing hole: no cost, no damage, not a piece of this bolt.+ continue;+ }+ // World geometry: gameplay collision is simple collision (art-pipeline.md 5), so the body's+ // simple physical material is the one that applies; the hit's own material is the fallback.+ const UPhysicalMaterial* PhysMat = nullptr;+ if (!Info)+ {+ const FBodyInstance* Body = Component->GetBodyInstance(Crossing.BoneName);+ PhysMat = Body ? Body->GetSimplePhysicalMaterial() : nullptr;+ if (!PhysMat || VersePenetration::ResolveWorldMaterial(PhysMat) == EVersePenetrationMaterial::Concrete)+ {+ PhysMat = Crossing.PhysMaterial.IsValid() ? Crossing.PhysMaterial.Get() : PhysMat;+ }+ }+ const EVersePenetrationMaterial Material = Info ? Info->Material : VersePenetration::ResolveWorldMaterial(PhysMat);+ const FVersePenetrationRow* Row = Table->FindRow(uint8(Material));+ if (!Row)+ {+ Row = Table->FindRow(uint8(EVersePenetrationMaterial::Concrete));+ }++ // One entry per piece: a proxy of several convex shapes, or a concave Holed proxy, is+ // charged once for the solid it holds along the ray; the air between its shapes is free.+ FVersePenetrationHit& Out = Result.AddDefaulted_GetRef();+ Out.PieceIndex = Info ? Info->PieceIndex : VersePenetration::NoPiece;+ Out.MaterialWireId = uint8(Material);+ Out.Entry = Crossing.Entry;+ Out.Exit = Crossing.Exit;+ Out.TracedThicknessCm = float(Crossing.SolidCm);+ if (!Row)+ {+ break;+ }+ const FVersePenetrationStep Step = VersePenetration::EvaluatePiece(*Row, Out.TracedThicknessCm, PowerLeft, DamageLeft, Passes >= Limit);+ Out.bPassed = Step.bPassed;+ Out.PowerLeft = Step.PowerLeft;+ Out.DamageLeft = Step.DamageLeft;+ if (!Step.bPassed || Crossing.bTruncated)+ {+ break;+ }+ PowerLeft = Step.PowerLeft;+ DamageLeft = Step.DamageLeft;+ ++Passes;+ }+ return Result;+}++bool UVersePenetrationSubsystem::TestSight(const FVector& Eye, const FVector& Target) const+{+ if (!GetWorld() || (Target - Eye).IsNearlyZero())+ {+ return true;+ }+ FVersePenetrationCrossings Crossings;+ CollectCrossings(Eye, Target, VerseCollision::Sight, SCENE_QUERY_STAT_NAME_ONLY(VerseTestSight), Crossings);+ for (const FVersePenetrationCrossing& Crossing : Crossings)+ {+ const FVersePieceProxyInfo* Info = FindPieceProxy(Crossing.Component);+ bool bSeeThrough = false;+ if (!Info)+ {+ // World geometry blocks; an overlap on the sight channel (unregistered glazing) does not.+ bSeeThrough = Crossing.Component->GetCollisionResponseToChannel(VerseCollision::Sight) != ECR_Block;+ }+ else+ {+ const EVersePieceState State = PieceState(Info->PieceIndex);+ bSeeThrough = State == EVersePieceState::Destroyed || Info->Material == EVersePenetrationMaterial::CatwalkGrating+ || (Info->Material == EVersePenetrationMaterial::Glass && State == EVersePieceState::Intact)+ || PassesHoles(*Info, Crossing);+ }+ if (!bSeeThrough || Crossing.bTruncated)+ {+ return false;+ }+ }+ return true;+}++int32 UVersePenetrationSubsystem::RecordBoltHoles(TConstArrayView<FVersePenetrationHit> Hits, const FVector& Dir, uint8 RadiusMm,+ uint32 ServerTimeMs) const+{+ UVerseBoltHoleComponent* Holes = HoleSource.Get();+ if (!Holes)+ {+ return 0;+ }+ int32 Added = 0;+ for (const FVersePenetrationHit& Hit : Hits)+ {+ if (!Hit.bPassed)+ {+ // A bolt that stops in a piece leaves a dent decal, no hole (destruction.md 5).+ break;+ }+ FTransform PieceToWorld;+ if (Hit.PieceIndex == VersePenetration::NoPiece || !GetPieceFrame(Hit.PieceIndex, PieceToWorld))+ {+ continue;+ }+ const FVector Mid = PieceToWorld.InverseTransformPosition((Hit.Entry + Hit.Exit) * 0.5);+ const FVector Axis = PieceToWorld.InverseTransformVectorNoScale(Dir.GetSafeNormal());+ if (Holes->AddHole(Hit.PieceIndex, EVersePenetrationMaterial(Hit.MaterialWireId), Mid, Axis, RadiusMm, ServerTimeMs)+ == EVerseHoleAddResult::Added)+ {+ ++Added;+ }+ }+ return Added;+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableImport.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableImport.cppnew file mode 100644index 0000000000..d427b84e33--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableImport.cpp@@ -0,0 +1,227 @@+#include "Penetration/VersePenetrationTableImport.h"++#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "Penetration/VersePenetrationJson.h"+#include "Penetration/VersePenetrationMath.h"+#include "VerseGameplayTags.h"+#include "VerseLog.h"++namespace VersePenetrationImport+{+ FString DefaultTablePath()+ {+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Data"), TEXT("destruction"), TEXT("penetration.json"));+ }++ FSoftObjectPath TableAssetPath()+ {+ return FSoftObjectPath(TEXT("/Game/Verse/Destruction/_Holes/DA_PenetrationTable.DA_PenetrationTable"));+ }++ UVersePenetrationTable* LoadRuntimeTable(UObject* Outer)+ {+ const FString JsonPath = DefaultTablePath();+ if (UVersePenetrationTable* Asset = Cast<UVersePenetrationTable>(TableAssetPath().TryLoad()))+ {+#if WITH_EDITOR+ TArray<FVersePenetrationRow> JsonRows;+ TArray<FString> Errors;+ FString Text;+ if (FPaths::FileExists(JsonPath) && FFileHelper::LoadFileToString(Text, *JsonPath) && ParseTableJson(Text, JsonRows, Errors))+ {+ const TArray<FString> Diffs = DiffRows(Asset->Rows, JsonRows);+ if (!Diffs.IsEmpty())+ {+ UE_LOG(LogVerseDestruction, Warning,+ TEXT("DA_PenetrationTable differs from %s (%s); re-run Content/Verse/Test/WP03/Python/wp03_content.py"), *JsonPath,+ *FString::Join(Diffs, TEXT("; ")));+ }+ }+#endif+ return Asset;+ }+ UVersePenetrationTable* Table = NewObject<UVersePenetrationTable>(Outer, TEXT("DA_PenetrationTable_Runtime"), RF_Transient);+ if (!FPaths::FileExists(JsonPath))+ {+ UE_LOG(LogVerseDestruction, Warning, TEXT("neither %s nor %s found; using the contract table"), *TableAssetPath().ToString(),+ *JsonPath);+ return Table;+ }+ TArray<FString> Errors;+ if (!ImportIntoTable(*Table, JsonPath, Errors))+ {+ UE_LOG(LogVerseDestruction, Error, TEXT("penetration table %s rejected, using the contract table: %s"), *JsonPath,+ *FString::Join(Errors, TEXT("; ")));+ }+ else+ {+ UE_LOG(LogVerseDestruction, Warning, TEXT("%s missing; using %s directly (not staged in cooked builds)"),+ *TableAssetPath().ToString(), *JsonPath);+ }+ return Table;+ }++ bool CheckWireOrder(TConstArrayView<FVersePenetrationRow> Rows, TArray<FString>& OutErrors)+ {+ const TConstArrayView<const TCHAR*> Ids = VersePenetration::FrozenMaterialIds();+ const TConstArrayView<FGameplayTag> Tags = VerseTags::AllMaterialTags();+ bool bOk = true;+ if (Rows.Num() < Ids.Num())+ {+ OutErrors.Add(FString::Printf(TEXT("%d rows; the frozen table has %d (materials only append)"), Rows.Num(), Ids.Num()));+ bOk = false;+ }+ for (int32 Wire = 0; Wire < FMath::Min(Rows.Num(), Ids.Num()); ++Wire)+ {+ if (int32(Rows[Wire].WireId) != Wire)+ {+ OutErrors.Add(FString::Printf(TEXT("row %d carries wire id %d"), Wire, int32(Rows[Wire].WireId)));+ bOk = false;+ }+ if (Rows[Wire].MaterialTag != Tags[Wire])+ {+ OutErrors.Add(FString::Printf(TEXT("row %d is %s, the frozen order wants Verse.Material.%s"), Wire,+ *Rows[Wire].MaterialTag.ToString(), Ids[Wire]));+ bOk = false;+ }+ }+ return bOk;+ }++ bool ParseTableJson(const FString& JsonText, TArray<FVersePenetrationRow>& OutRows, TArray<FString>& OutErrors)+ {+ OutRows.Reset();+ const int32 ErrorsBefore = OutErrors.Num();+ FVerseJson Doc;+ FString ParseError;+ if (!FVerseJson::Parse(JsonText, Doc, ParseError) || !Doc.IsObject())+ {+ OutErrors.Add(ParseError.IsEmpty() ? FString(TEXT("not a JSON object")) : ParseError);+ return false;+ }+ const FVerseJson* Root = &Doc;+ FString SchemaText;+ if (!Root->TryString(TEXT("schema"), SchemaText) || SchemaText != Schema)+ {+ OutErrors.Add(FString::Printf(TEXT("schema must be %s"), Schema));+ }+ double Anchor = 0.0;+ if (!Root->TryNumber(TEXT("power_anchor"), Anchor) || Anchor != 100.0)+ {+ OutErrors.Add(TEXT("power_anchor must be 100 (the assault rifle, destruction.md 2)"));+ }+ double MaxPieces = 0.0;+ if (!Root->TryNumber(TEXT("max_pieces"), MaxPieces) || int32(MaxPieces) != Verse::Destruction::MaxPenetrations)+ {+ OutErrors.Add(TEXT("max_pieces must be 3 (destruction.md 2)"));+ }+ const TArray<FVerseJson>* Materials = Root->FindArray(TEXT("materials"));+ if (!Materials)+ {+ OutErrors.Add(TEXT("materials array missing"));+ return false;+ }++ const TConstArrayView<const TCHAR*> Ids = VersePenetration::FrozenMaterialIds();+ const TConstArrayView<FGameplayTag> Tags = VerseTags::AllMaterialTags();+ const UEnum* DebrisEnum = StaticEnum<EVerseDebrisType>();+ for (int32 Index = 0; Index < Materials->Num(); ++Index)+ {+ const FVerseJson& M = (*Materials)[Index];+ if (!M.IsObject())+ {+ OutErrors.Add(FString::Printf(TEXT("materials[%d] is not an object"), Index));+ continue;+ }+ FString Id;+ FString Debris;+ double Wire = -1.0;+ double Ref = 0.0;+ double Cost = 0.0;+ double Mult = 0.0;+ bool bBullets = false;+ bool bBreach = false;+ const bool bComplete = M.TryNumber(TEXT("wire"), Wire) && M.TryString(TEXT("id"), Id)+ && M.TryNumber(TEXT("ref_thickness_cm"), Ref) && M.TryNumber(TEXT("cost"), Cost)+ && M.TryNumber(TEXT("damage_multiplier"), Mult) && M.TryBool(TEXT("breakable_by_bullets"), bBullets)+ && M.TryBool(TEXT("breakable_by_breach"), bBreach) && M.TryString(TEXT("debris"), Debris);+ if (!bComplete)+ {+ OutErrors.Add(FString::Printf(TEXT("materials[%d] misses a column"), Index));+ continue;+ }+ // An appended material needs its Core tag and enum value first (a contract change), so+ // every row must name a known id.+ const int32 KnownIndex = Ids.IndexOfByPredicate([&Id](const TCHAR* Known) { return Id == Known; });+ if (KnownIndex == INDEX_NONE)+ {+ OutErrors.Add(FString::Printf(TEXT("materials[%d]: unknown material id %s"), Index, *Id));+ continue;+ }+ if (Ref <= 0.0 || Cost < 0.0 || Mult < 0.0 || Mult > 1.0 || Wire < 0.0 || Wire > 255.0)+ {+ OutErrors.Add(FString::Printf(TEXT("materials[%d] %s: wire 0..255, ref > 0, cost >= 0, multiplier in [0, 1]"), Index, *Id));+ continue;+ }+ const int64 DebrisValue = DebrisEnum->GetValueByNameString(Debris);+ if (DebrisValue == INDEX_NONE)+ {+ OutErrors.Add(FString::Printf(TEXT("materials[%d] %s: unknown debris type %s"), Index, *Id, *Debris));+ continue;+ }+ FVersePenetrationRow Row;+ Row.MaterialTag = Tags[KnownIndex];+ Row.WireId = EVersePenetrationMaterial(uint8(Wire));+ Row.RefThicknessCm = float(Ref);+ Row.PenetrationCost = float(Cost);+ Row.DamageMultiplier = float(Mult);+ Row.bBreakableByBullets = bBullets;+ Row.bBreakableByBreach = bBreach;+ Row.DebrisType = EVerseDebrisType(uint8(DebrisValue));+ OutRows.Add(Row);+ }+ CheckWireOrder(OutRows, OutErrors);+ return OutErrors.Num() == ErrorsBefore;+ }++ bool ImportIntoTable(UVersePenetrationTable& Table, const FString& Path, TArray<FString>& OutErrors)+ {+ FString Text;+ if (!FFileHelper::LoadFileToString(Text, *Path))+ {+ OutErrors.Add(FString::Printf(TEXT("cannot read %s"), *Path));+ return false;+ }+ TArray<FVersePenetrationRow> Rows;+ if (!ParseTableJson(Text, Rows, OutErrors))+ {+ return false;+ }+ Table.Rows = MoveTemp(Rows);+ return true;+ }++ TArray<FString> DiffRows(TConstArrayView<FVersePenetrationRow> A, TConstArrayView<FVersePenetrationRow> B, float Tolerance)+ {+ TArray<FString> Diffs;+ if (A.Num() != B.Num())+ {+ Diffs.Add(FString::Printf(TEXT("row count %d vs %d"), A.Num(), B.Num()));+ }+ auto Near = [Tolerance](float L, float R) { return FMath::Abs(L - R) <= Tolerance; };+ for (int32 I = 0; I < FMath::Min(A.Num(), B.Num()); ++I)+ {+ const FVersePenetrationRow& X = A[I];+ const FVersePenetrationRow& Y = B[I];+ if (X.MaterialTag != Y.MaterialTag || X.WireId != Y.WireId || !Near(X.RefThicknessCm, Y.RefThicknessCm)+ || !Near(X.PenetrationCost, Y.PenetrationCost) || !Near(X.DamageMultiplier, Y.DamageMultiplier)+ || X.bBreakableByBullets != Y.bBreakableByBullets || X.bBreakableByBreach != Y.bBreakableByBreach+ || X.DebrisType != Y.DebrisType)+ {+ Diffs.Add(FString::Printf(TEXT("row %d (%s) differs"), I, *X.MaterialTag.ToString()));+ }+ }+ return Diffs;+ }+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableLibrary.cpp b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableLibrary.cppnew file mode 100644index 0000000000..112b6e03a9--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Penetration/VersePenetrationTableLibrary.cpp@@ -0,0 +1,81 @@+#include "Penetration/VersePenetrationTableLibrary.h"++#include "Components/StaticMeshComponent.h"+#include "Destruction/VersePenetrationTable.h"+#include "Engine/StaticMeshActor.h"+#include "Engine/World.h"+#include "Misc/FileHelper.h"+#include "Penetration/VersePenetrationTableImport.h"++bool UVersePenetrationTableLibrary::ImportPenetrationJson(UVersePenetrationTable* Table, const FString& Path, FString& OutErrors)+{+ OutErrors.Reset();+ if (!Table)+ {+ OutErrors = TEXT("no table");+ return false;+ }+ TArray<FString> Errors;+ const FString Source = Path.IsEmpty() ? VersePenetrationImport::DefaultTablePath() : Path;+ if (!VersePenetrationImport::ImportIntoTable(*Table, Source, Errors))+ {+ OutErrors = FString::Join(Errors, TEXT("\n"));+ return false;+ }+ Table->MarkPackageDirty();+ return true;+}++FString UVersePenetrationTableLibrary::DiffPenetrationJson(const UVersePenetrationTable* Table, const FString& Path)+{+ if (!Table)+ {+ return TEXT("no table");+ }+ const FString Source = Path.IsEmpty() ? VersePenetrationImport::DefaultTablePath() : Path;+ FString Text;+ if (!FFileHelper::LoadFileToString(Text, *Source))+ {+ return FString::Printf(TEXT("cannot read %s"), *Source);+ }+ TArray<FVersePenetrationRow> Rows;+ TArray<FString> Errors;+ if (!VersePenetrationImport::ParseTableJson(Text, Rows, Errors))+ {+ return FString::Join(Errors, TEXT("\n"));+ }+ return FString::Join(VersePenetrationImport::DiffRows(Table->Rows, Rows), TEXT("\n"));+}++AActor* UVersePenetrationTableLibrary::SpawnFixturePiece(UWorld* World, UStaticMesh* Mesh, UMaterialInterface* Material, const FTransform& Transform,+ FName Profile,+ const TArray<FName>& Tags, const FString& Label)+{+ if (!World || !Mesh)+ {+ return nullptr;+ }+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ AStaticMeshActor* Actor = World->SpawnActor<AStaticMeshActor>(AStaticMeshActor::StaticClass(), Transform, Params);+ if (!Actor)+ {+ return nullptr;+ }+ UStaticMeshComponent* Component = Actor->GetStaticMeshComponent();+ Component->SetStaticMesh(Mesh);+ for (int32 Slot = 0; Material && Slot < Component->GetNumMaterials(); ++Slot)+ {+ Component->SetMaterial(Slot, Material);+ }+ Component->SetCollisionProfileName(Profile);+ Actor->SetActorTransform(Transform);+ Actor->Tags = Tags;+#if WITH_EDITOR+ if (!Label.IsEmpty())+ {+ Actor->SetActorLabel(Label);+ }+#endif+ return Actor;+}diff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleCapsTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleCapsTest.cppnew file mode 100644index 0000000000..1cebfe3550--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleCapsTest.cpp@@ -0,0 +1,269 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Destruction/VerseDestructionTuning.h"+#include "GameFramework/Actor.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Holes/VerseHoleGlow.h"+#include "Holes/VerseHoleRenderComponent.h"+#include "Misc/AutomationTest.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ FVector HolePoint(int32 I)+ {+ return FVector(0.0, -40.0 + 3.0 * (I % 25), -30.0 + 3.0 * (I / 25));+ }++ float HueOf(const FLinearColor& Linear)+ {+ return Linear.LinearRGBToHSV().R;+ }+}++// A3.4: hole 25 on a wall makes it Holed and clears its holes; the arena cap drops the oldest+// hole of the fullest piece; glass keeps its newest 24; resets bump the epoch.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleCapsTest, "Verse.Destruction.Holes.Caps", WP03Flags)++bool FVerseHoleCapsTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ UVerseBoltHoleComponent* Holes = W.Holes;+ const UVerseDestructionTuning* Tuning = GetDefault<UVerseDestructionTuning>();+ Holes->ApplyTuning(*Tuning);+ TestEqual(TEXT("24 holes per piece"), Holes->GetHolesPerPiece(), 24);+ TestEqual(TEXT("512 holes per arena"), Holes->GetHolesPerArena(), 512);++ uint16 CapPiece = 0xFFFF;+ FVector CapCentroid = FVector::ZeroVector;+ int32 CapCalls = 0;+ Holes->OnPieceHoleCap.AddLambda([&](uint16 Piece, const FVector& Centroid) {+ CapPiece = Piece;+ CapCentroid = Centroid;+ ++CapCalls;+ });++ // Wall: 24 holes stay, hole 25 turns it Holed and clears them.+ FVector Sum = FVector::ZeroVector;+ for (int32 I = 0; I < 24; ++I)+ {+ TestEqual(FString::Printf(TEXT("wall hole %d"), I + 1),+ Holes->AddHole(7, EVersePenetrationMaterial::ContainerWall, HolePoint(I), FVector::ForwardVector, 15, 100 + I), EVerseHoleAddResult::Added);+ Sum += HolePoint(I);+ }+ TestEqual(TEXT("24 holes on the wall"), Holes->NumOnPiece(7), 24);+ TestEqual(TEXT("hole 25 turns the wall Holed"),+ Holes->AddHole(7, EVersePenetrationMaterial::ContainerWall, HolePoint(24), FVector::ForwardVector, 15, 200), EVerseHoleAddResult::PieceHoled);+ Sum += HolePoint(24);+ TestEqual(TEXT("wall holes cleared"), Holes->NumOnPiece(7), 0);+ TestEqual(TEXT("cap fired once"), CapCalls, 1);+ TestEqual(TEXT("cap names the piece"), CapPiece, uint16(7));+ TestTrue(TEXT("cap centroid is the mean of the 25 holes (1 mm records)"), CapCentroid.Equals(Sum / 25.0, 0.06));++ // Glass and ceiling are not walls: the 25th hole drops the piece's oldest.+ for (int32 I = 0; I < 25; ++I)+ {+ Holes->AddHole(8, EVersePenetrationMaterial::Glass, HolePoint(I), FVector::ForwardVector, 15, 300 + I);+ }+ TestEqual(TEXT("glass keeps 24"), Holes->NumOnPiece(8), 24);+ TestEqual(TEXT("glass dropped its oldest"), Holes->GetPieceHoles(8)[0].ServerTimeMs, uint32(301));+ TestEqual(TEXT("no cap event for glass"), CapCalls, 1);++ // Materials without holes.+ TestEqual(TEXT("grating keeps no holes"),+ Holes->AddHole(9, EVersePenetrationMaterial::CatwalkGrating, FVector::ZeroVector, FVector::ForwardVector, 15, 1), EVerseHoleAddResult::NotHoleMaterial);+ TestEqual(TEXT("concrete keeps no holes"),+ Holes->AddHole(9, EVersePenetrationMaterial::Concrete, FVector::ZeroVector, FVector::ForwardVector, 15, 1), EVerseHoleAddResult::NotHoleMaterial);+ TestEqual(TEXT("armor steel keeps no holes"),+ Holes->AddHole(9, EVersePenetrationMaterial::ArmorSteel, FVector::ZeroVector, FVector::ForwardVector, 15, 1), EVerseHoleAddResult::NotHoleMaterial);++ // Arena cap: fill to 512, the fullest piece (ties: the older one) loses its oldest hole.+ Holes->ResetAll(3);+ TestEqual(TEXT("reset clears"), Holes->Num(), 0);+ TestEqual(TEXT("reset sets the epoch"), Holes->GetEpoch(), uint16(3));+ uint32 Time = 1000;+ for (uint16 Piece = 0; Piece < 21; ++Piece)+ {+ for (int32 I = 0; I < 24; ++I)+ {+ Holes->AddHole(Piece, EVersePenetrationMaterial::SheetMetal, HolePoint(I), FVector::ForwardVector, 15, Time++);+ }+ }+ for (int32 I = 0; I < 8; ++I)+ {+ Holes->AddHole(21, EVersePenetrationMaterial::SheetMetal, HolePoint(I), FVector::ForwardVector, 15, Time++);+ }+ TestEqual(TEXT("arena at 512"), Holes->Num(), 512);+ const uint32 Piece0Second = Holes->GetPieceHoles(0)[1].ServerTimeMs;+ TestEqual(TEXT("hole 513 is added"),+ Holes->AddHole(30, EVersePenetrationMaterial::SheetMetal, FVector::ZeroVector, FVector::ForwardVector, 15, Time++), EVerseHoleAddResult::Added);+ TestEqual(TEXT("arena stays at 512"), Holes->Num(), 512);+ TestEqual(TEXT("the oldest of the fullest piece went"), Holes->NumOnPiece(0), 23);+ TestEqual(TEXT("piece 0 now starts with its second hole"), Holes->GetPieceHoles(0)[0].ServerTimeMs, Piece0Second);+ TestEqual(TEXT("other full pieces keep theirs"), Holes->NumOnPiece(1), 24);+ TestEqual(TEXT("the smallest piece keeps its holes"), Holes->NumOnPiece(21), 8);+ Holes->AddHole(31, EVersePenetrationMaterial::SheetMetal, FVector::ZeroVector, FVector::ForwardVector, 15, Time++);+ TestEqual(TEXT("next eviction: piece 1 (fullest, oldest)"), Holes->NumOnPiece(1), 23);+ TArray<FVerseBoltHole> All;+ Holes->GetAllHoles(All);+ TestTrue(TEXT("every record carries the epoch"), All.ContainsByPredicate([](const FVerseBoltHole& H) { return H.Epoch != 3; }) == false);++ // Clear on a state change.+ Holes->ClearPiece(2);+ TestEqual(TEXT("clear piece"), Holes->NumOnPiece(2), 0);++ // Holes from a traced bolt: one record per passed piece that keeps holes, none after a stop.+ Holes->ResetAll(4);+ W.SpawnPiece(100, EVersePenetrationMaterial::ContainerWall, FVector(100.f, 0, 0), 0.4f);+ W.SpawnPiece(101, EVersePenetrationMaterial::CatwalkGrating, FVector(150.f, 0, 0), 3.f);+ W.SpawnPiece(102, EVersePenetrationMaterial::ContainerWall, FVector(200.f, 0, 0), 0.4f);+ W.SpawnPiece(103, EVersePenetrationMaterial::CladdingPanel, FVector(250.f, 0, 0), 4.f);+ W.Settle();+ const FVector Dir = FVector(1.0, 0.1, 0.0).GetSafeNormal();+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(FVector(0, -10.f, 0), Dir, 1000.f, 100.f, 30.f, 15, 3);+ TestEqual(TEXT("bolt enters four pieces"), Hits.Num(), 4);+ TestEqual(TEXT("two holes recorded (grating keeps none, the cladding stopped it)"),+ W.Penetration->RecordBoltHoles(Hits, Dir, 15, 5000), 2);+ TestEqual(TEXT("first wall has its hole"), Holes->NumOnPiece(100), 1);+ TestEqual(TEXT("second wall has its hole"), Holes->NumOnPiece(102), 1);+ TestEqual(TEXT("stopping piece has none"), Holes->NumOnPiece(103), 0);+ if (Holes->NumOnPiece(100) == 1)+ {+ const FVerseBoltHole& Hole = Holes->GetPieceHoles(100)[0];+ TestTrue(TEXT("hole axis follows the bolt"), FVector::DotProduct(Hole.GetAxisDirection(), Dir) > 0.999);+ TestEqual(TEXT("hole radius from the weapon"), Hole.RadiusMm, uint8(15));+ TestEqual(TEXT("hole epoch"), Hole.Epoch, uint16(4));+ // The same bolt line now flies through the recorded hole of the first wall without cost.+ const TArray<FVersePenetrationHit> Again = W.Penetration->TraceBolt(FVector(0, -10.f, 0), Dir, 1000.f, 100.f, 30.f, 15, 3);+ TestTrue(TEXT("second bolt skips both holed walls"), Again.Num() == 2 && Again[0].PieceIndex == 101 && Again[1].PieceIndex == 103);+ }+ return true;+}++// WP03.6: the glow curve (tau 1.2 s, dull red at 2.5 s, off at 4 s) and its colours never+// fall under the rendered-pixel ban at any exposure.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleGlowTest, "Verse.Destruction.Holes.Glow", WP03Flags)++bool FVerseHoleGlowTest::RunTest(const FString& Parameters)+{+ const FVerseHoleGlowSample Fresh = VerseHoleGlow::Sample(0.f);+ TestTrue(TEXT("fresh hole glows at full"), Fresh.bGlowing && VerseWP03Test::Near(Fresh.Intensity, 1.f, 1e-6f));+ const float FreshHue = HueOf(Fresh.Color);+ TestTrue(FString::Printf(TEXT("fresh hue %.1f is white-amber (25..45 deg)"), FreshHue), FreshHue >= 25.f && FreshHue <= 45.f);+ TestTrue(TEXT("fresh colour is near white (low saturation)"), Fresh.Color.LinearRGBToHSV().G < 0.6f);+ TestTrue(TEXT("tau 1.2 s"), VerseWP03Test::Near(VerseHoleGlow::Sample(1.2f).Intensity, FMath::Exp(-1.f), 1e-4f));+ const FVerseHoleGlowSample Red = VerseHoleGlow::Sample(2.5f);+ TestTrue(TEXT("2.5 s intensity is exp(-2.5 / 1.2)"), VerseWP03Test::Near(Red.Intensity, FMath::Exp(-2.5f / 1.2f), 1e-4f));+ const float RedHue = HueOf(Red.Color);+ TestTrue(FString::Printf(TEXT("2.5 s hue %.1f is dull red (<= 12 deg)"), RedHue), RedHue <= 12.f || RedHue >= 355.f);+ const FVerseHoleGlowSample Off = VerseHoleGlow::Sample(4.f);+ TestTrue(TEXT("glow off at 4 s"), !Off.bGlowing && Off.Intensity == 0.f);+ TestTrue(TEXT("charred after the glow"), Off.Color.Equals(VerseHoleGlow::CharredColor()));++ float Last = 2.f;+ int32 Banned = 0;+ int32 Samples = 0;+ const float Exposures[] = {0.05f, 0.25f, 1.f, 4.f, 40.f};+ for (int32 Ms = 0; Ms <= 4000; Ms += 10)+ {+ const FVerseHoleGlowSample S = VerseHoleGlow::Sample(Ms / 1000.f);+ if (S.Intensity > Last + 1e-7f)+ {+ AddError(FString::Printf(TEXT("glow rises at %d ms"), Ms));+ }+ Last = S.Intensity;+ for (const float Exposure : Exposures)+ {+ // Emissive over the charred rim, clipped like a display would.+ const FLinearColor Pixel = VerseHoleGlow::CharredColor() + S.Color * (S.Intensity * Exposure);+ const FColor Srgb = FLinearColor(FMath::Min(Pixel.R, 1.f), FMath::Min(Pixel.G, 1.f), FMath::Min(Pixel.B, 1.f)).ToFColor(true);+ Banned += VerseHoleGlow::IsBannedPixel(Srgb) ? 1 : 0;+ ++Samples;+ }+ }+ TestEqual(FString::Printf(TEXT("banned pixels over %d glow samples"), Samples), Banned, 0);++ // The ban itself.+ TestTrue(TEXT("cyan is banned"), VerseHoleGlow::IsBannedPixel(FColor(0, 200, 220)));+ TestTrue(TEXT("violet is banned"), VerseHoleGlow::IsBannedPixel(FColor(140, 40, 220)));+ TestTrue(TEXT("info blue is banned"), VerseHoleGlow::IsBannedPixel(FColor(40, 90, 230)));+ TestFalse(TEXT("amber passes"), VerseHoleGlow::IsBannedPixel(FColor(255, 160, 40)));+ TestFalse(TEXT("dark blue below the value floor passes"), VerseHoleGlow::IsBannedPixel(FColor(5, 10, 20)));++ // 128 glowing at most, the oldest cools first, nothing older than 4 s glows.+ TArray<uint32> Times;+ for (int32 I = 0; I < 200; ++I)+ {+ Times.Add(10000 + I * 10);+ }+ Times.Add(1000);+ const uint32 Now = 12000;+ const TArray<int32> Glowing = VerseHoleGlow::SelectGlowing(Times, Now, 128);+ TestEqual(TEXT("128 glowing"), Glowing.Num(), 128);+ TestEqual(TEXT("newest first"), Glowing[0], 199);+ TestFalse(TEXT("the oldest young holes cooled first"), Glowing.Contains(0));+ TestFalse(TEXT("a hole older than 4 s never glows"), Glowing.Contains(200));+ TestEqual(TEXT("nothing glows 4 s after the last hole"), VerseHoleGlow::SelectGlowing(Times, 10000 + 199 * 10 + 4000, 128).Num(), 0);+ return true;+}++// WP03.6: the renderer's bookkeeping, which runs on every client: a mask slot per piece on its+// first hole, a slot per hole, the 128 glowing cap. GPU objects are only made with a real RHI.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleRenderTest, "Verse.Destruction.Holes.Render", WP03Flags)++bool FVerseHoleRenderTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ UVerseHoleRenderComponent* Render = NewObject<UVerseHoleRenderComponent>(W.Manager, TEXT("HoleRender"));+ Render->RegisterComponent();+ uint32 Now = 0;+ Render->SetServerTimeSource([&Now]() { return Now; });+ Render->SetHoleSource(W.Holes);+ const FBox Bounds(FVector(-0.2, -100, -50), FVector(0.2, 100, 50));+ Render->RegisterPieceVisual(4, nullptr, Bounds, W.Manager->GetRootComponent());+ Render->Sync();+ TestEqual(TEXT("no mask before the first hole"), Render->NumMaskSlots(), 0);++ TestTrue(TEXT("hole UV of the centre"), UVerseHoleRenderComponent::HoleUV(Bounds, FVector::ZeroVector).Equals(FVector2D(0.5, 0.5), 1e-6));+ TestTrue(TEXT("hole UV of a corner"), UVerseHoleRenderComponent::HoleUV(Bounds, FVector(0, -100, 50)).Equals(FVector2D(0, 0), 1e-6));+ TestTrue(TEXT("15 mm on a 2 m face is about 1.9 px"), VerseWP03Test::Near(UVerseHoleRenderComponent::HoleRadiusPx(Bounds, 1.5f, 256), 1.92f, 1e-3f));++ Now = 100000;+ for (int32 I = 0; I < 200; ++I)+ {+ const uint16 Piece = uint16(4 + I / 24);+ W.Holes->AddHole(Piece, EVersePenetrationMaterial::Glass, HolePoint(I % 24), FVector::ForwardVector, 15, Now - 199 + I);+ }+ Render->Sync();+ TestEqual(TEXT("a slot per hole"), Render->NumHoleSlots(), W.Holes->Num());+ TestEqual(TEXT("a mask per piece with holes"), Render->NumMaskSlots(), 9);+ TestTrue(TEXT("piece 4 has its mask"), Render->HasMask(4));+ TestFalse(TEXT("an untouched piece has none"), Render->HasMask(40));+ TestEqual(TEXT("128 glowing at most"), Render->NumGlowing(), 128);+ Now += 4000;+ Render->Sync();+ TestEqual(TEXT("all cooled after 4 s"), Render->NumGlowing(), 0);+ W.Holes->ClearPiece(4);+ Render->Sync();+ TestEqual(TEXT("a mask slot survives its holes (cleared, reused)"), Render->NumMaskSlots(), 9);+ if (!UVerseHoleRenderComponent::CanRender(W.World()))+ {+ TestNull(TEXT("no GPU mask without a renderer"), Render->GetMask(5));+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleSlotsTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleSlotsTest.cppnew file mode 100644index 0000000000..18a6208bad--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleSlotsTest.cpp@@ -0,0 +1,184 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "GameFramework/Actor.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Holes/VerseHoleGlow.h"+#include "Holes/VerseHoleRenderComponent.h"+#include "Misc/AutomationTest.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ FVector SlotPoint(int32 I)+ {+ return FVector(0.0, -40.0 + 3.0 * (I % 25), -30.0 + 3.0 * (I / 25));+ }++ TArray<uint32> Sequences(const UVerseBoltHoleComponent& Holes)+ {+ TArray<uint32> Out;+ for (const FVerseBoltHoleSlot& Slot : Holes.GetSlots())+ {+ Out.Add(Slot.Sequence);+ }+ return Out;+ }+}++// WP03.5 replication shape (destruction.md 3.3 and 5, interim for CCR #1134): holes sit at+// stable slot indices, so an eviction rewrites one slot and shifts nothing; the per-piece view+// and the change notification name only the pieces that changed.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleSlotsTest, "Verse.Destruction.Holes.Slots", WP03Flags)++bool FVerseHoleSlotsTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ UVerseBoltHoleComponent* Holes = W.Holes;+ TArray<uint16> Changed;+ int32 AllChanges = 0;+ Holes->OnHolesChanged.AddLambda([&](TConstArrayView<uint16> Pieces, bool bAll) {+ Changed.Append(Pieces.GetData(), Pieces.Num());+ AllChanges += bAll ? 1 : 0;+ });++ // Fill the arena to its cap over 22 pieces.+ uint32 Time = 1000;+ for (int32 I = 0; I < 512; ++I)+ {+ Holes->AddHole(uint16(I % 22), EVersePenetrationMaterial::Glass, SlotPoint(I / 22), FVector::ForwardVector, 15, Time++);+ }+ TestEqual(TEXT("512 holes"), Holes->Num(), 512);+ TestEqual(TEXT("512 slots"), Holes->GetSlots().Num(), 512);++ // At the cap every new hole evicts one: exactly two slots change (the evicted one is reused),+ // nothing shifts and the slot array does not grow.+ for (int32 Round = 0; Round < 50; ++Round)+ {+ const TArray<uint32> Before = Sequences(*Holes);+ Changed.Reset();+ Holes->AddHole(uint16(40 + Round % 3), EVersePenetrationMaterial::Glass, SlotPoint(Round), FVector::ForwardVector, 15, Time++);+ const TArray<uint32> After = Sequences(*Holes);+ int32 Diff = 0;+ for (int32 I = 0; I < FMath::Min(Before.Num(), After.Num()); ++I)+ {+ Diff += Before[I] != After[I] ? 1 : 0;+ }+ if (Diff != 1 || After.Num() != 512)+ {+ AddError(FString::Printf(TEXT("round %d: %d slots changed, %d slots (want 1 and 512)"), Round, Diff, After.Num()));+ break;+ }+ if (!Changed.Contains(uint16(40 + Round % 3)) || Changed.Num() > 2)+ {+ AddError(FString::Printf(TEXT("round %d: change named %d pieces"), Round, Changed.Num()));+ break;+ }+ }+ TestEqual(TEXT("arena stays at 512"), Holes->Num(), 512);++ // The per-piece view stays oldest first and matches the slots.+ TArray<FVerseBoltHole> All;+ Holes->GetAllHoles(All);+ TestEqual(TEXT("every live slot listed"), All.Num(), 512);+ bool bOrdered = true;+ for (int32 I = 1; I < All.Num(); ++I)+ {+ bOrdered &= All[I - 1].ServerTimeMs < All[I].ServerTimeMs;+ }+ TestTrue(TEXT("all holes oldest first"), bOrdered);+ int32 Sum = 0;+ for (uint16 Piece = 0; Piece < 64; ++Piece)+ {+ const TConstArrayView<FVerseBoltHole> PieceHoles = Holes->GetPieceHoles(Piece);+ Sum += PieceHoles.Num();+ for (int32 I = 1; I < PieceHoles.Num(); ++I)+ {+ bOrdered &= PieceHoles[I - 1].ServerTimeMs < PieceHoles[I].ServerTimeMs;+ }+ }+ TestEqual(TEXT("per-piece views add up"), Sum, 512);+ TestTrue(TEXT("per-piece views oldest first"), bOrdered);++ // A clear frees the piece's slots; the next holes reuse them without growing the array.+ const int32 OnPiece3 = Holes->NumOnPiece(3);+ Holes->ClearPiece(3);+ TestEqual(TEXT("clear frees the piece"), Holes->Num(), 512 - OnPiece3);+ for (int32 I = 0; I < OnPiece3; ++I)+ {+ Holes->AddHole(50, EVersePenetrationMaterial::Glass, SlotPoint(I), FVector::ForwardVector, 15, Time++);+ }+ TestEqual(TEXT("freed slots reused"), Holes->GetSlots().Num(), 512);+ Holes->ResetAll(2);+ TestEqual(TEXT("reset empties the slots"), Holes->GetSlots().Num(), 0);+ TestEqual(TEXT("reset notifies everything"), AllChanges, 1);+ return true;+}++// WP03.6 glow clock: records carry server time, so the glow ages against the server clock, and a+// client clock behind the server never lights recent holes as fresh (destruction.md 3.3: late+// joiners see holes already cooled). Each change redraws only the pieces it touched.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleClockTest, "Verse.Destruction.Holes.Clock", WP03Flags)++bool FVerseHoleClockTest::RunTest(const FString& Parameters)+{+ TestTrue(TEXT("a past record ages"), VerseWP03Test::Near(VerseHoleGlow::AgeS(1000, 2500), 1.5, 1e-6));+ TestTrue(TEXT("a record within the skew window is fresh"), VerseHoleGlow::AgeS(2600, 2500) == 0.f);+ TestTrue(TEXT("a record far in the future is long cooled"), VerseHoleGlow::AgeS(60000, 2500) >= VerseHoleGlow::DefaultEndS);++ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ UVerseHoleRenderComponent* Render = NewObject<UVerseHoleRenderComponent>(W.Manager, TEXT("HoleRender"));+ Render->RegisterComponent();+ const uint32 WorldMs = Render->CurrentTimeMs();+ TestTrue(TEXT("default clock: the world (no game state in this world)"),+ WorldMs == uint32(W.World()->GetTimeSeconds() * 1000.0));++ // A late joiner: the server is at 120 s, the client clock still at 2 s.+ uint32 ClientNow = 2000;+ Render->SetServerTimeSource([&ClientNow]() { return ClientNow; });+ Render->SetHoleSource(W.Holes);+ const FBox Bounds(FVector(-0.2, -100, -50), FVector(0.2, 100, 50));+ for (uint16 Piece = 0; Piece < 6; ++Piece)+ {+ Render->RegisterPieceVisual(Piece, nullptr, Bounds, W.Manager->GetRootComponent());+ }+ for (int32 I = 0; I < 60; ++I)+ {+ W.Holes->AddHole(uint16(I % 6), EVersePenetrationMaterial::Glass, SlotPoint(I / 6), FVector::ForwardVector, 15, 118000 + I * 30);+ }+ Render->Sync();+ TestEqual(TEXT("client clock behind: none of the recent server holes glows"), Render->NumGlowing(), 0);+ W.Holes->AddHole(0, EVersePenetrationMaterial::Glass, SlotPoint(20), FVector::ForwardVector, 15, ClientNow + 100);+ Render->Sync();+ TestEqual(TEXT("a hole within the skew window glows"), Render->NumGlowing(), 1);+ ClientNow = 120000;+ Render->Sync();+ TestTrue(TEXT("once the clocks agree the young holes glow"), Render->NumGlowing() > 0);++ // Incremental: one new hole redraws one mask and places one slot.+ const int32 Redraws = Render->NumMaskRedraws();+ const int32 Updates = Render->NumSlotUpdates();+ W.Holes->AddHole(4, EVersePenetrationMaterial::Glass, SlotPoint(21), FVector::ForwardVector, 15, ClientNow);+ Render->Sync();+ TestEqual(TEXT("one change redraws one piece mask"), Render->NumMaskRedraws() - Redraws, 1);+ TestEqual(TEXT("one change places one slot"), Render->NumSlotUpdates() - Updates, 1);+ TestEqual(TEXT("slots follow the records"), Render->NumHoleSlots(), W.Holes->Num());+ W.Holes->ClearPiece(5);+ Render->Sync();+ TestEqual(TEXT("a clear redraws that piece only"), Render->NumMaskRedraws() - Redraws, 2);+ TestEqual(TEXT("slots follow the clear"), Render->NumHoleSlots(), W.Holes->Num());+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleVisualTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleVisualTest.cppnew file mode 100644index 0000000000..25be6ae719--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseHoleVisualTest.cpp@@ -0,0 +1,277 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "AssetCompilingManager.h"+#include "Components/SceneCaptureComponent2D.h"+#include "Components/StaticMeshComponent.h"+#include "Engine/StaticMesh.h"+#include "Engine/TextureRenderTarget2D.h"+#include "Engine/World.h"+#include "GameFramework/Actor.h"+#include "HAL/FileManager.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Holes/VerseHoleGlow.h"+#include "Holes/VerseHoleRenderComponent.h"+#include "ImageUtils.h"+#include "Materials/MaterialInstanceDynamic.h"+#include "Materials/MaterialInterface.h"+#include "Misc/AutomationTest.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"+#include "TextureResource.h"+#include "VerseCollision.h"++namespace+{+ constexpr EAutomationTestFlags WP03VisualFlags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;+ constexpr int32 ShotSize = 512;+ // Engine primitive (100 cm, box collision), not a sample content pack.+ const TCHAR* const BoxPath = TEXT("/Engine/BasicShapes/Cube.Cube");+ const TCHAR* const SurfacePath = TEXT("/Game/Verse/Test/WP03/M_WP03_HoleSurface.M_WP03_HoleSurface");++ struct FShot+ {+ TArray<FColor> Pixels;+ int32 Banned = 0;+ int32 Hot = 0;+ FColor Centre;+ FColor Wall;+ };++ FLinearColor Hsv(const FColor& Pixel)+ {+ return FLinearColor(Pixel.R / 255.f, Pixel.G / 255.f, Pixel.B / 255.f).LinearRGBToHSV();+ }++ /** The visible rim glow: brighter than any lit surface here, white or a warm hue (a fresh rim clips to near white). */+ bool IsHot(const FColor& Pixel)+ {+ const FLinearColor C = Hsv(Pixel);+ return C.B >= 0.92f && (C.G < 0.2f || C.R <= 60.f || C.R >= 340.f);+ }++ AActor* SpawnMesh(FVerseWP03World& W, UStaticMesh* Box, UMaterialInterface* Surface, const FVector& Location, const FVector& SizeCm,+ const FLinearColor& Tint, FName Profile, UStaticMeshComponent*& OutMesh)+ {+ FActorSpawnParameters Params;+ Params.ObjectFlags = RF_Transient;+ AActor* Actor = W.World()->SpawnActor<AActor>(AActor::StaticClass(), FTransform(Location), Params);+ // An unscaled root is the piece frame; the scaled mesh hangs under it.+ USceneComponent* Root = NewObject<USceneComponent>(Actor, TEXT("Frame"));+ Actor->SetRootComponent(Root);+ Root->RegisterComponent();+ UStaticMeshComponent* Mesh = NewObject<UStaticMeshComponent>(Actor, TEXT("Mesh"));+ Mesh->SetStaticMesh(Box);+ Mesh->SetupAttachment(Root);+ Mesh->SetRelativeScale3D(SizeCm / 100.0);+ Mesh->SetCollisionProfileName(Profile);+ UMaterialInstanceDynamic* Mid = UMaterialInstanceDynamic::Create(Surface, Actor);+ Mid->SetVectorParameterValue(TEXT("Tint"), Tint);+ Mesh->SetMaterial(0, Mid);+ Mesh->RegisterComponent();+ Actor->SetActorLocation(Location);+ OutMesh = Mesh;+ return Actor;+ }++ void SavePng(FAutomationTestBase& Test, const FString& Name, const TArray<FColor>& Pixels)+ {+ const FString Dir = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("proof"), TEXT("WP03"), TEXT("holes"));+ IFileManager::Get().MakeDirectory(*Dir, true);+ TArray64<uint8> Png;+ FImageUtils::PNGCompressImageArray(ShotSize, ShotSize, TArrayView64<const FColor>(Pixels.GetData(), Pixels.Num()), Png);+ const FString Path = FPaths::ConvertRelativePathToFull(FPaths::Combine(Dir, Name + TEXT(".png")));+ if (FFileHelper::SaveArrayToFile(Png, *Path))+ {+ Test.AddInfo(FString::Printf(TEXT("shot %s"), *Path));+ }+ }+}++// A3.6 (WP03.6) on the GPU: a bolt hole in a container wall, rendered through the real hole+// mask and rim decal at 0, 1, 2.5 and 4 s after the impact. 0 banned pixels by the rendered-+// pixel rule of art-pipeline.md 8.3 in every frame; the rim glows at impact and is out at 4 s;+// the hole is open from both sides (the backdrop shows through, and TestSight agrees).+// Run: python scripts/unreal/screenshot.py --suite Verse.Visual.Holes+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseHoleVisualTest, "Verse.Visual.Holes", WP03VisualFlags)++bool FVerseHoleVisualTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ if (!UVerseHoleRenderComponent::CanRender(W.World()))+ {+ AddInfo(TEXT("needs a GPU: python scripts/unreal/screenshot.py --suite Verse.Visual.Holes"));+ return true;+ }+ UStaticMesh* Box = LoadObject<UStaticMesh>(nullptr, BoxPath);+ UMaterialInterface* Surface = LoadObject<UMaterialInterface>(nullptr, SurfacePath);+ if (!TestNotNull(TEXT("engine cube"), Box) || !TestNotNull(TEXT("M_WP03_HoleSurface"), Surface))+ {+ return false;+ }++ // A 1.2 cm container wall (3x reference) at x = 300, a warm backdrop behind it, an olive one in front.+ const double WallX = 300.0;+ const double Thickness = 1.2;+ UStaticMeshComponent* WallMesh = nullptr;+ AActor* Wall = SpawnMesh(W, Box, Surface, FVector(WallX, 0, 0), FVector(Thickness, 100, 100), FLinearColor(0.3f, 0.3f, 0.3f),+ VerseCollision::Profile::Destructible, WallMesh);+ UStaticMeshComponent* Unused = nullptr;+ SpawnMesh(W, Box, Surface, FVector(WallX + 400, 0, 0), FVector(10, 300, 300), FLinearColor(0.6f, 0.45f, 0.25f),+ VerseCollision::Profile::NoCollision, Unused);+ SpawnMesh(W, Box, Surface, FVector(WallX - 400, 0, 0), FVector(10, 300, 300), FLinearColor(0.35f, 0.4f, 0.15f),+ VerseCollision::Profile::NoCollision, Unused);+ W.Penetration->RegisterPieceProxy(WallMesh, 1, EVersePenetrationMaterial::ContainerWall, Wall->GetRootComponent());+ W.Query.Materials.Add(1, EVersePenetrationMaterial::ContainerWall);++ uint32 Now = 10000;+ UVerseHoleRenderComponent* Render = NewObject<UVerseHoleRenderComponent>(W.Manager, TEXT("HoleRender"));+ Render->RegisterComponent();+ Render->SetServerTimeSource([&Now]() { return Now; });+ Render->SetHoleSource(W.Holes);+ const FVector Half(Thickness * 0.5, 50.0, 50.0);+ Render->RegisterPieceVisual(1, WallMesh, FBox(-Half, Half), Wall->GetRootComponent());+ // An uncooked game process compiles the mesh asynchronously, and a compiling mesh gets its+ // body only once the build is done: finish it, then tick until the wall blocks a probe ray.+ const FVector ProbeA(WallX - 50.0, 20.0, 0.0);+ const FVector ProbeB(WallX + 50.0, 20.0, 0.0);+ int32 Frames = 0;+ for (; Frames < 60 && W.Penetration->TestSight(ProbeA, ProbeB); ++Frames)+ {+ FAssetCompilingManager::Get().FinishAllCompilation();+ W.World()->SendAllEndOfFrameUpdates();+ W.Settle();+ }+ if (!TestFalse(*FString::Printf(TEXT("the wall collides after %d settles"), Frames), W.Penetration->TestSight(ProbeA, ProbeB)))+ {+ return false;+ }++ const FVector BoltOrigin(WallX - 250.0, 0, 0);+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(BoltOrigin, FVector::ForwardVector, 400.f, 100.f, 30.f, 15, 3);+ for (const FVersePenetrationHit& Hit : Hits)+ {+ AddInfo(FString::Printf(TEXT("bolt hit piece %d material %d entry %s exit %s thickness %.4f cm passed %d power left %.2f"),+ int32(Hit.PieceIndex), int32(Hit.MaterialWireId), *Hit.Entry.ToString(), *Hit.Exit.ToString(), Hit.TracedThicknessCm,+ Hit.bPassed ? 1 : 0, Hit.PowerLeft));+ }+ TestEqual(TEXT("the bolt passes the wall"), Hits.Num() == 1 && Hits[0].bPassed, true);+ TestEqual(TEXT("one hole recorded"), W.Penetration->RecordBoltHoles(Hits, FVector::ForwardVector, 15, Now), 1);++ FActorSpawnParameters Params;+ Params.ObjectFlags = RF_Transient;+ AActor* CameraActor = W.World()->SpawnActor<AActor>(AActor::StaticClass(), FTransform::Identity, Params);+ UTextureRenderTarget2D* Target = NewObject<UTextureRenderTarget2D>(CameraActor);+ Target->RenderTargetFormat = RTF_RGBA8_SRGB;+ Target->ClearColor = FLinearColor::Black;+ Target->InitAutoFormat(ShotSize, ShotSize);+ Target->UpdateResourceImmediate(true);+ USceneCaptureComponent2D* Capture = NewObject<USceneCaptureComponent2D>(CameraActor, TEXT("Capture"));+ Capture->TextureTarget = Target;+ Capture->CaptureSource = SCS_FinalColorLDR;+ Capture->bCaptureEveryFrame = false;+ Capture->bCaptureOnMovement = false;+ Capture->FOVAngle = 30.f;+ Capture->ShowFlags.SetEyeAdaptation(false);+ Capture->ShowFlags.SetMotionBlur(false);+ Capture->ShowFlags.SetAntiAliasing(false);+ Capture->PostProcessSettings.bOverride_AutoExposureMethod = true;+ Capture->PostProcessSettings.AutoExposureMethod = AEM_Manual;+ Capture->PostProcessSettings.bOverride_AutoExposureApplyPhysicalCameraExposure = true;+ Capture->PostProcessSettings.AutoExposureApplyPhysicalCameraExposure = false;+ Capture->PostProcessSettings.bOverride_AutoExposureBias = true;+ Capture->PostProcessSettings.AutoExposureBias = 0.f;+ Capture->PostProcessSettings.bOverride_VignetteIntensity = true;+ Capture->PostProcessSettings.VignetteIntensity = 0.f;+ Capture->PostProcessBlendWeight = 1.f;+ CameraActor->SetRootComponent(Capture);+ Capture->RegisterComponent();++ auto Shoot = [&](const FVector& Eye, const FVector& LookAt) {+ FShot Shot;+ Render->Sync();+ FAssetCompilingManager::Get().FinishAllCompilation();+ W.World()->SendAllEndOfFrameUpdates();+ Capture->SetWorldLocationAndRotation(Eye, (LookAt - Eye).Rotation());+ // The first capture after a change can still miss compiled shaders or the mask draw.+ // ReadPixels flushes the render thread (VerseDestruction does not link RenderCore).+ TArray<FColor> Warmup;+ for (int32 Pass = 0; Pass < 3; ++Pass)+ {+ Capture->CaptureScene();+ Target->GameThread_GetRenderTargetResource()->ReadPixels(Warmup);+ }+ Target->GameThread_GetRenderTargetResource()->ReadPixels(Shot.Pixels);+ for (const FColor& Pixel : Shot.Pixels)+ {+ Shot.Banned += VerseHoleGlow::IsBannedPixel(Pixel) ? 1 : 0;+ Shot.Hot += IsHot(Pixel) ? 1 : 0;+ }+ if (Shot.Pixels.Num() == ShotSize * ShotSize)+ {+ Shot.Centre = Shot.Pixels[(ShotSize / 2) * ShotSize + ShotSize / 2];+ // Wall beside the hole: 150 px (about 8 cm) off the centre, outside the rim decal.+ Shot.Wall = Shot.Pixels[(ShotSize / 2) * ShotSize + ShotSize / 2 + 150];+ }+ return Shot;+ };++ const FVector Front(WallX - 50.0, 0, 0);+ const FVector Back(WallX + 50.0, 0, 0);+ const FVector Hole(WallX, 0, 0);+ const float Ages[] = {0.f, 1.f, 2.5f, 4.f};+ int32 HotAtImpact = 0;+ // Warm-up: the first frames with the rim decal compile its material and draw the mask.+ for (int32 Warm = 0; Warm < 3; ++Warm)+ {+ Shoot(Front, Hole);+ }+ for (const float Age : Ages)+ {+ Now = 10000 + uint32(Age * 1000.f);+ const FShot Shot = Shoot(Front, Hole);+ if (!TestEqual(TEXT("a full frame"), Shot.Pixels.Num(), ShotSize * ShotSize))+ {+ return false;+ }+ SavePng(*this, FString::Printf(TEXT("hole_cooling_%04dms"), int32(Age * 1000.f)), Shot.Pixels);+ TestEqual(*FString::Printf(TEXT("%.1f s: banned pixels"), Age), Shot.Banned, 0);+ AddInfo(FString::Printf(TEXT("%.1f s: %d glowing rim pixels, %d banned"), Age, Shot.Hot, Shot.Banned));+ if (Age == 0.f)+ {+ HotAtImpact = Shot.Hot;+ TestTrue(*FString::Printf(TEXT("the rim glows at impact (%d hot pixels)"), Shot.Hot), Shot.Hot > 20);+ }+ if (Age >= 4.f)+ {+ TestTrue(*FString::Printf(TEXT("the glow is out at 4 s (%d hot pixels)"), Shot.Hot), Shot.Hot * 20 < FMath::Max(HotAtImpact, 1));+ }+ }++ // Through the hole from both sides: the backdrop behind the wall fills the hole's centre.+ const FShot FrontShot = Shoot(Front, Hole);+ const FShot BackShot = Shoot(Back, Hole);+ SavePng(*this, TEXT("hole_through_front"), FrontShot.Pixels);+ SavePng(*this, TEXT("hole_through_back"), BackShot.Pixels);+ auto Differs = [](const FColor& A, const FColor& B) {+ return FMath::Abs(int32(A.R) - int32(B.R)) + FMath::Abs(int32(A.G) - int32(B.G)) + FMath::Abs(int32(A.B) - int32(B.B)) > 40;+ };+ TestTrue(*FString::Printf(TEXT("front: the hole shows the warm backdrop (%s vs wall %s)"), *FrontShot.Centre.ToString(), *FrontShot.Wall.ToString()),+ Differs(FrontShot.Centre, FrontShot.Wall) && FrontShot.Centre.R > FrontShot.Centre.B + 20);+ TestTrue(*FString::Printf(TEXT("back: the hole shows the olive backdrop (%s vs wall %s)"), *BackShot.Centre.ToString(), *BackShot.Wall.ToString()),+ Differs(BackShot.Centre, BackShot.Wall) && BackShot.Centre.G > BackShot.Centre.B + 20);+ TestEqual(TEXT("front and back palettes clean"), FrontShot.Banned + BackShot.Banned, 0);+ TestTrue(TEXT("TestSight sees through the hole front to back"), W.Penetration->TestSight(Front, Back));+ TestTrue(TEXT("TestSight sees through the hole back to front"), W.Penetration->TestSight(Back, Front));+ TestFalse(TEXT("TestSight is blocked beside the hole"), W.Penetration->TestSight(Front + FVector(0, 20, 0), Back + FVector(0, 20, 0)));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseSightHolesTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseSightHolesTest.cppnew file mode 100644index 0000000000..0a20a5bef0--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Holes/VerseSightHolesTest.cpp@@ -0,0 +1,193 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Holes/VerseBoltHoleComponent.h"+#include "Misc/AutomationTest.h"+#include "Penetration/VersePenetrationMath.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"+#include "VerseRng.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ /** Distance of a piece-local point from a hole's (decoded) axis, cm. */+ double AxisDistance(const FVerseBoltHole& Hole, const FVector& Local)+ {+ const FVector Dir = Hole.GetAxisDirection();+ const FVector Rel = Local - Hole.GetAxisPointCm();+ return (Rel - Dir * FVector::DotProduct(Rel, Dir)).Size();+ }++ /** Where a ray crosses the plane x = PlaneX (piece-local, slab faces). */+ FVector CrossPlaneX(const FVector& Start, const FVector& Dir, double PlaneX)+ {+ return Start + Dir * ((PlaneX - Start.X) / Dir.X);+ }+}++// A3.3: a ray through a 15 mm hole in 0.3 cm sheet at 30 deg off the axis passes; the same ray+// through a 4 cm panel fails; 10,000 seeded rays agree with the analytic two-point test.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSightHolesTest, "Verse.Destruction.Sight.Holes", WP03Flags)++bool FVerseSightHolesTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ struct FPanel+ {+ const TCHAR* Name;+ EVersePenetrationMaterial Material;+ float Thickness;+ FVector Center;+ bool bThirtyDegPasses;+ };+ const FPanel Panels[] = {+ {TEXT("0.3 cm sheet metal"), EVersePenetrationMaterial::SheetMetal, 0.3f, FVector(0, 0, 0), true},+ {TEXT("4 cm cladding panel"), EVersePenetrationMaterial::CladdingPanel, 4.f, FVector(0, 1000.f, 0), false},+ };+ const double Rad30 = FMath::DegreesToRadians(30.0);+ const FVector Dir30(FMath::Cos(Rad30), FMath::Sin(Rad30), 0.0);+ uint16 Index = 0;+ for (const FPanel& Panel : Panels)+ {+ W.SpawnPiece(Index, Panel.Material, Panel.Center, Panel.Thickness);+ // A rifle bolt shot straight through the middle left the 15 mm hole.+ TestEqual(FString::Printf(TEXT("%s: hole recorded"), Panel.Name),+ W.Holes->AddHole(Index, Panel.Material, FVector::ZeroVector, FVector::ForwardVector, 15, 1000), EVerseHoleAddResult::Added);+ W.Settle();++ // The ray enters at the centre of the hole's entry face, 30 deg off the hole axis.+ const FVector Entry = Panel.Center - FVector(Panel.Thickness * 0.5f, 0, 0);+ const FVector Eye = Entry - Dir30 * 200.0;+ const FVector Target = Entry + Dir30 * 200.0;+ TestEqual(FString::Printf(TEXT("%s: 30 deg sight through the hole"), Panel.Name), W.Penetration->TestSight(Eye, Target), Panel.bThirtyDegPasses);+ TestEqual(FString::Printf(TEXT("%s: the reverse direction agrees"), Panel.Name), W.Penetration->TestSight(Target, Eye), Panel.bThirtyDegPasses);++ // Straight down the axis both pass; well beside the hole both are blocked.+ TestTrue(FString::Printf(TEXT("%s: on-axis sight"), Panel.Name),+ W.Penetration->TestSight(Panel.Center - FVector(100, 0, 0), Panel.Center + FVector(100, 0, 0)));+ TestFalse(FString::Printf(TEXT("%s: sight beside the hole"), Panel.Name),+ W.Penetration->TestSight(Panel.Center + FVector(-100, 0, 10), Panel.Center + FVector(100, 0, 10)));++ // Bolts use the same test: through the hole is free, the panel itself is not.+ TestEqual(FString::Printf(TEXT("%s: bolt down the hole enters no piece"), Panel.Name),+ W.Penetration->TraceBolt(Panel.Center - FVector(100, 0, 0), FVector::ForwardVector, 200.f, 100.f, 1.f, 15, 3).Num(), 0);+ const TArray<FVersePenetrationHit> Beside =+ W.Penetration->TraceBolt(Panel.Center - FVector(100, 0, 10), FVector::ForwardVector, 200.f, 100.f, 1.f, 15, 3);+ TestEqual(FString::Printf(TEXT("%s: bolt beside the hole enters the piece"), Panel.Name), Beside.Num(), 1);+ ++Index;+ }++ // 10,000 seeded rays near the holes, both panels: TestSight against the analytic two-point+ // test on the slab faces. Rays whose entry or exit lies within 0.02 cm of the rim are left+ // out (trace precision; about 3 % of rays), and counted.+ FVerseRng Rng(0x5713E03ull);+ int32 Agree = 0;+ int32 Disagree = 0;+ int32 NearRim = 0;+ int32 Passing = 0;+ for (int32 Ray = 0; Ray < 10000; ++Ray)+ {+ const FPanel& Panel = Panels[Ray % 2];+ const uint16 Piece = uint16(Ray % 2);+ const TConstArrayView<FVerseBoltHole> Holes = W.Holes->GetPieceHoles(Piece);+ if (!TestEqual(TEXT("one hole per panel"), Holes.Num(), 1))+ {+ return false;+ }+ const FVerseBoltHole& Hole = Holes[0];+ const FVector2D Disk = Rng.UnitDisk() * 2.5;+ const FVector EntryLocal(-Panel.Thickness * 0.5, Disk.X, Disk.Y);+ const FVector Dir = Rng.ConeDirection(FVector::ForwardVector, 60.0);+ const FVector ExitLocal = CrossPlaneX(EntryLocal, Dir, Panel.Thickness * 0.5);+ const double Radius = Hole.RadiusMm / 10.0;+ const double EntryMargin = Radius - AxisDistance(Hole, EntryLocal);+ const double ExitMargin = Radius - AxisDistance(Hole, ExitLocal);+ if (FMath::Abs(EntryMargin) < 0.02 || FMath::Abs(ExitMargin) < 0.02)+ {+ ++NearRim;+ continue;+ }+ const bool bAnalytic = EntryMargin > 0.0 && ExitMargin > 0.0;+ const FVector EntryWorld = Panel.Center + EntryLocal;+ const bool bTraced = W.Penetration->TestSight(EntryWorld - Dir * 150.0, EntryWorld + Dir * 150.0);+ if (bTraced == bAnalytic)+ {+ ++Agree;+ }+ else+ {+ ++Disagree;+ if (Disagree <= 5)+ {+ AddError(FString::Printf(TEXT("ray %d on %s: traced %d, analytic %d (margins %.4f, %.4f)"), Ray, Panel.Name, bTraced, bAnalytic,+ EntryMargin, ExitMargin));+ }+ }+ Passing += bAnalytic ? 1 : 0;+ }+ AddInfo(FString::Printf(TEXT("seeded rays: %d agree, %d disagree, %d near the rim left out, %d see through"), Agree, Disagree, NearRim, Passing));+ TestEqual(TEXT("no seeded ray disagrees"), Disagree, 0);+ TestTrue(TEXT("rim band stays small (< 5 %)"), NearRim < 500);+ TestTrue(TEXT("both outcomes are exercised"), Passing > 500 && Passing < Agree - 500);+ return true;+}++// destruction.md 5: intact glass and grating never block sight, damaged glass blocks except+// through its holes, other pieces and world geometry block.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSightRulesTest, "Verse.Destruction.Sight.Rules", WP03Flags)++bool FVerseSightRulesTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ const FVector Eye(-200.f, 0, 0);+ const FVector Target(200.f, 0, 0);+ TestTrue(TEXT("empty world: clear"), W.Penetration->TestSight(Eye, Target));++ AActor* Glass = W.SpawnPiece(1, EVersePenetrationMaterial::Glass, FVector::ZeroVector, 2.4f);+ W.Settle();+ TestTrue(TEXT("intact glass is see-through"), W.Penetration->TestSight(Eye, Target));+ W.Query.States.Add(1, EVersePieceState::Damaged);+ TestFalse(TEXT("damaged glass blocks"), W.Penetration->TestSight(Eye, Target));+ W.Holes->AddHole(1, EVersePenetrationMaterial::Glass, FVector::ZeroVector, FVector::ForwardVector, 15, 10);+ TestTrue(TEXT("damaged glass: sight through its hole"), W.Penetration->TestSight(Eye, Target));+ TestFalse(TEXT("damaged glass: beside its hole"), W.Penetration->TestSight(Eye + FVector(0, 0, 20), Target + FVector(0, 0, 20)));+ TestEqual(TEXT("bolts still stop or pass by the table at intact glass"),+ W.Penetration->TraceBolt(Eye + FVector(0, 0, 20), FVector::ForwardVector, 400.f, 100.f, 1.f, 15, 3).Num(), 1);+ W.Query.States.Add(1, EVersePieceState::Destroyed);+ TestTrue(TEXT("destroyed glass never blocks"), W.Penetration->TestSight(Eye + FVector(0, 0, 20), Target + FVector(0, 0, 20)));+ W.DestroyActor(Glass);++ AActor* Grating = W.SpawnPiece(2, EVersePenetrationMaterial::CatwalkGrating, FVector::ZeroVector, 3.f);+ W.Settle();+ TestTrue(TEXT("grating is see-through"), W.Penetration->TestSight(Eye, Target));+ const TArray<FVersePenetrationHit> GratingHits = W.Penetration->TraceBolt(Eye, FVector::ForwardVector, 400.f, 100.f, 1.f, 15, 3);+ TestTrue(TEXT("a bolt is charged by the grating"), GratingHits.Num() == 1 && GratingHits[0].bPassed+ && VerseWP03Test::Near(GratingHits[0].PowerLeft, 90.f, 1e-3f));++ AActor* Wall = W.SpawnPiece(3, EVersePenetrationMaterial::ContainerWall, FVector(50.f, 0, 0), 0.4f);+ W.Settle();+ TestFalse(TEXT("a container wall behind grating blocks"), W.Penetration->TestSight(Eye, Target));+ W.Query.States.Add(3, EVersePieceState::Damaged);+ TestFalse(TEXT("a damaged wall without holes blocks"), W.Penetration->TestSight(Eye, Target));+ W.DestroyActor(Wall);+ W.DestroyActor(Grating);++ const EVerseWorldSurface Surface = EVerseWorldSurface::StructuralWall;+ W.SpawnWorldBox(&Surface, FVector::ZeroVector, 30.f);+ W.Settle();+ TestFalse(TEXT("world geometry blocks"), W.Penetration->TestSight(Eye, Target));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.cppnew file mode 100644index 0000000000..c440fd9605--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.cpp@@ -0,0 +1,198 @@+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Components/BoxComponent.h"+#include "Components/StaticMeshComponent.h"+#include "Engine/StaticMesh.h"+#include "PhysicsEngine/BodySetup.h"+#include "Engine/World.h"+#include "GameFramework/Actor.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Misc/Paths.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "PhysicalMaterials/PhysicalMaterial.h"+#include "VerseCollision.h"++EVersePieceState FFakePieceQuery::GetPieceState(uint16 PieceIndex) const+{+ const EVersePieceState* Found = States.Find(PieceIndex);+ return Found ? *Found : EVersePieceState::Intact;+}++EVersePenetrationMaterial FFakePieceQuery::GetPieceMaterial(uint16 PieceIndex) const+{+ const EVersePenetrationMaterial* Found = Materials.Find(PieceIndex);+ return Found ? *Found : EVersePenetrationMaterial::Concrete;+}++FBox FFakePieceQuery::GetPieceBounds(uint16 PieceIndex) const+{+ const FBox* Found = Bounds.Find(PieceIndex);+ return Found ? *Found : FBox(ForceInit);+}++TArray<uint16> FFakePieceQuery::GetPiecesInBox(const FBox& WorldBox) const+{+ TArray<uint16> Out;+ for (const TPair<uint16, FBox>& Pair : Bounds)+ {+ if (Pair.Value.Intersect(WorldBox))+ {+ Out.Add(Pair.Key);+ }+ }+ return Out;+}++FVerseWP03World::~FVerseWP03World()+{+ if (Penetration)+ {+ Penetration->SetPieceQuery(nullptr);+ }+}++bool FVerseWP03World::Create()+{+ if (!CreateTestWorld(EWorldType::Game))+ {+ return false;+ }+ Penetration = TestWorld->GetSubsystem<UVersePenetrationSubsystem>();+ if (!Penetration)+ {+ return false;+ }+ FActorSpawnParameters Params;+ Params.ObjectFlags = RF_Transient;+ Manager = TestWorld->SpawnActor<AActor>(AActor::StaticClass(), FTransform::Identity, Params);+ Holes = NewObject<UVerseBoltHoleComponent>(Manager, TEXT("BoltHoles"));+ Holes->RegisterComponent();+ Penetration->SetHoleSource(Holes);+ Penetration->SetPieceQuery(&Query);+ return true;+}++void FVerseWP03World::Settle()+{+ for (int32 Frame = 0; Frame < 3; ++Frame)+ {+ TickTestWorld(1.f / 60.f);+ }+}++AActor* FVerseWP03World::SpawnBox(const FVector& Center, const FRotator& Rotation, const FVector& HalfExtent, FName Profile, UPhysicalMaterial* PhysMat)+{+ FActorSpawnParameters Params;+ Params.ObjectFlags = RF_Transient;+ AActor* Actor = TestWorld->SpawnActor<AActor>(AActor::StaticClass(), FTransform(Rotation, Center), Params);+ UBoxComponent* Box = NewObject<UBoxComponent>(Actor, TEXT("Proxy"));+ Box->SetBoxExtent(HalfExtent, false);+ Box->SetCollisionProfileName(Profile);+ if (PhysMat)+ {+ Box->BodyInstance.SetPhysMaterialOverride(PhysMat);+ }+ Actor->SetRootComponent(Box);+ Box->RegisterComponent();+ Actor->SetActorLocationAndRotation(Center, Rotation);+ return Actor;+}++AActor* FVerseWP03World::SpawnPiece(uint16 PieceIndex, EVersePenetrationMaterial Material, const FVector& Center, float ThicknessCm,+ float WidthCm, float HeightCm, const FRotator& Rotation)+{+ const FName Profile = Material == EVersePenetrationMaterial::Glass ? VerseCollision::Profile::Glass : VerseCollision::Profile::Destructible;+ AActor* Actor = SpawnBox(Center, Rotation, FVector(ThicknessCm, WidthCm, HeightCm) * 0.5, Profile, nullptr);+ UBoxComponent* Box = BoxOf(Actor);+ Penetration->RegisterPieceProxy(Box, PieceIndex, Material);+ Query.Materials.Add(PieceIndex, Material);+ Query.Bounds.Add(PieceIndex, Box->Bounds.GetBox());+ return Actor;+}++AActor* FVerseWP03World::SpawnCompoundPiece(uint16 PieceIndex, EVersePenetrationMaterial Material, const FVector& Center,+ TConstArrayView<TPair<FVector, FVector>> Shapes)+{+ UStaticMesh* Mesh = NewObject<UStaticMesh>(GetTransientPackage(), NAME_None, RF_Transient);+ Mesh->CreateBodySetup();+ UBodySetup* Setup = Mesh->GetBodySetup();+ Setup->CollisionTraceFlag = CTF_UseSimpleAsComplex;+ Setup->bNeverNeedsCookedCollisionData = true;+ FBox Local(ForceInit);+ for (const TPair<FVector, FVector>& Shape : Shapes)+ {+ FKBoxElem Elem(Shape.Value.X * 2.0, Shape.Value.Y * 2.0, Shape.Value.Z * 2.0);+ Elem.Center = Shape.Key;+ Setup->AggGeom.BoxElems.Add(Elem);+ Local += FBox(Shape.Key - Shape.Value, Shape.Key + Shape.Value);+ }+ Mesh->SetExtendedBounds(FBoxSphereBounds(Local));+ PhysMats.Emplace(static_cast<UObject*>(Mesh));++ FActorSpawnParameters Params;+ Params.ObjectFlags = RF_Transient;+ AActor* Actor = TestWorld->SpawnActor<AActor>(AActor::StaticClass(), FTransform(Center), Params);+ UStaticMeshComponent* Proxy = NewObject<UStaticMeshComponent>(Actor, TEXT("Proxy"));+ Proxy->SetStaticMesh(Mesh);+ Proxy->SetCollisionProfileName(Material == EVersePenetrationMaterial::Glass ? VerseCollision::Profile::Glass : VerseCollision::Profile::Destructible);+ Actor->SetRootComponent(Proxy);+ Proxy->RegisterComponent();+ Actor->SetActorLocation(Center);+ Penetration->RegisterPieceProxy(Proxy, PieceIndex, Material);+ Query.Materials.Add(PieceIndex, Material);+ Query.Bounds.Add(PieceIndex, Proxy->Bounds.GetBox());+ return Actor;+}++AActor* FVerseWP03World::SpawnWorldBox(const EVerseWorldSurface* Surface, const FVector& Center, float ThicknessCm, float WidthCm, float HeightCm)+{+ UPhysicalMaterial* PhysMat = nullptr;+ if (Surface)+ {+ PhysMat = VerseWP03Test::MakePhysicalMaterial(VersePenetration::PhysicalMaterialName(*Surface));+ PhysMats.Emplace(static_cast<UObject*>(PhysMat));+ }+ return SpawnBox(Center, FRotator::ZeroRotator, FVector(ThicknessCm, WidthCm, HeightCm) * 0.5, VerseCollision::Profile::Architecture, PhysMat);+}++UBoxComponent* FVerseWP03World::BoxOf(AActor* Actor) const+{+ return Actor ? Cast<UBoxComponent>(Actor->GetRootComponent()) : nullptr;+}++void FVerseWP03World::DestroyActor(AActor* Actor)+{+ if (Actor)+ {+ if (UBoxComponent* Box = BoxOf(Actor))+ {+ Penetration->UnregisterPieceProxy(Box);+ }+ Actor->Destroy();+ }+}++namespace VerseWP03Test+{+ UPhysicalMaterial* MakePhysicalMaterial(const FString& BaseName)+ {+ // By class path: VerseDestruction does not link PhysicsCore (architecture.md 2).+ UClass* Class = FindObject<UClass>(nullptr, TEXT("/Script/PhysicsCore.PhysicalMaterial"));+ if (!Class)+ {+ return nullptr;+ }+ const FName Name = MakeUniqueObjectName(GetTransientPackage(), Class, FName(*BaseName));+ UObject* Object = NewObject<UObject>(GetTransientPackage(), Class, Name, RF_Transient);+ return static_cast<UPhysicalMaterial*>(Object);+ }++ FString GoldenFixturePath()+ {+ return FPaths::Combine(FPaths::ProjectContentDir(), TEXT("Verse"), TEXT("Test"), TEXT("WP03"), TEXT("penetration_golden.json"));+ }+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.h b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.hnew file mode 100644index 0000000000..65e3dc9d00--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/Fakes/VerseWP03Fakes.h@@ -0,0 +1,95 @@+#pragma once++#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Destruction/VerseDestructionInterfaces.h"+#include "Penetration/VersePenetrationPhysicalMaterial.h"+#include "Tests/AutomationCommon.h"+#include "UObject/StrongObjectPtr.h"++class AActor;+class UPhysicalMaterial;+class UBoxComponent;+class UVerseBoltHoleComponent;+class UVersePenetrationSubsystem;++/**+ * Piece truth for WP03 tests, standing in for WP06's destruction manager (work-packages.md 0.3).+ * Implements IVersePieceQuery exactly; unknown pieces answer Intact, concrete, an invalid box.+ */+class FFakePieceQuery : public IVersePieceQuery+{+public:+ TMap<uint16, EVersePieceState> States;+ TMap<uint16, EVersePenetrationMaterial> Materials;+ TMap<uint16, FBox> Bounds;++ virtual EVersePieceState GetPieceState(uint16 PieceIndex) const override;+ virtual EVersePenetrationMaterial GetPieceMaterial(uint16 PieceIndex) const override;+ virtual FBox GetPieceBounds(uint16 PieceIndex) const override;+ virtual TArray<uint16> GetPiecesInBox(const FBox& WorldBox) const override;+};++/**+ * A manually ticked game world with the penetration subsystem, a hole component on a stand-in+ * manager actor and the fake piece query wired in. Pieces are AFakePiece-style solid boxes:+ * a plain actor whose root is a box proxy registered with a piece index and material id.+ */+class FVerseWP03World : public FTestWorldWrapper+{+public:+ ~FVerseWP03World();++ bool Create();+ /** Steps physics so new and moved proxies are visible to scene queries. */+ void Settle();++ UWorld* World() const { return TestWorld; }++ /** A solid box piece; Thickness along the actor's X axis, Height along Z, Width along Y (cm). */+ AActor* SpawnPiece(uint16 PieceIndex, EVersePenetrationMaterial Material, const FVector& Center, float ThicknessCm,+ float WidthCm = 100.f, float HeightCm = 100.f, const FRotator& Rotation = FRotator::ZeroRotator);++ /**+ * A piece whose proxy is one body of several boxes, like a convex-decomposed or a concave+ * Holed proxy: a static mesh component whose transient mesh has only simple collision.+ * Shapes are (actor-local centre, half extent) in cm.+ */+ AActor* SpawnCompoundPiece(uint16 PieceIndex, EVersePenetrationMaterial Material, const FVector& Center,+ TConstArrayView<TPair<FVector, FVector>> Shapes);++ /** Non-destructible world geometry; null Surface = no Verse physical material at all. */+ AActor* SpawnWorldBox(const EVerseWorldSurface* Surface, const FVector& Center, float ThicknessCm, float WidthCm = 200.f,+ float HeightCm = 200.f);++ UBoxComponent* BoxOf(AActor* Actor) const;+ void DestroyActor(AActor* Actor);++ UVersePenetrationSubsystem* Penetration = nullptr;+ UVerseBoltHoleComponent* Holes = nullptr;+ AActor* Manager = nullptr;+ FFakePieceQuery Query;++private:+ AActor* SpawnBox(const FVector& Center, const FRotator& Rotation, const FVector& HalfExtent, FName Profile, UPhysicalMaterial* PhysMat);+ TArray<TStrongObjectPtr<UObject>> PhysMats;+};++namespace VerseWP03Test+{+ /** |A - B| <= Tolerance in double precision (mixed float and double arguments). */+ inline bool Near(double A, double B, double Tolerance)+ {+ return FMath::Abs(A - B) <= Tolerance;+ }++ /** Path of the WP03.1 golden fixture. */+ FString GoldenFixturePath();++ /** A transient physical material with that base name (a unique suffix is added). */+ UPhysicalMaterial* MakePhysicalMaterial(const FString& BaseName);+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationAssetsTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationAssetsTest.cppnew file mode 100644index 0000000000..bab133f449--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationAssetsTest.cpp@@ -0,0 +1,128 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Destruction/VersePenetrationTable.h"+#include "Engine/Level.h"+#include "Engine/World.h"+#include "GameFramework/Actor.h"+#include "Materials/Material.h"+#include "Materials/MaterialInterface.h"+#include "Misc/AutomationTest.h"+#include "Misc/FileHelper.h"+#include "Penetration/VersePenetrationMath.h"+#include "Penetration/VersePenetrationTableImport.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ FString TagValue(const AActor& Actor, const FString& Prefix)+ {+ for (const FName& Tag : Actor.Tags)+ {+ const FString Text = Tag.ToString();+ if (Text.StartsWith(Prefix))+ {+ return Text.RightChop(Prefix.Len());+ }+ }+ return FString();+ }+}++// The committed WP03 content (Content/Verse/Test/WP03/Python/wp03_content.py): the cooked+// table matches the JSON, the hole materials carry their parameters, and the fixture map holds every material at 0.5x, 1x and+// 3x reference thickness plus the hole angle rig and a container row.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationAssetsTest, "Verse.Destruction.Penetration.Assets", WP03Flags)++bool FVersePenetrationAssetsTest::RunTest(const FString& Parameters)+{+ // WP03.2: DA_PenetrationTable is what the game loads; it must equal the JSON.+ const UVersePenetrationTable* Asset = Cast<UVersePenetrationTable>(VersePenetrationImport::TableAssetPath().TryLoad());+ if (TestNotNull(TEXT("DA_PenetrationTable exists"), Asset))+ {+ FString Text;+ TArray<FVersePenetrationRow> JsonRows;+ TArray<FString> Errors;+ TestTrue(TEXT("penetration.json parses"), FFileHelper::LoadFileToString(Text, *VersePenetrationImport::DefaultTablePath())+ && VersePenetrationImport::ParseTableJson(Text, JsonRows, Errors));+ const TArray<FString> Diffs = VersePenetrationImport::DiffRows(Asset->Rows, JsonRows);+ TestTrue(FString::Printf(TEXT("DA_PenetrationTable equals penetration.json (%s)"), *FString::Join(Diffs, TEXT("; "))), Diffs.IsEmpty());+ TestTrue(TEXT("the runtime loads the asset"), VersePenetrationImport::LoadRuntimeTable(GetTransientPackage()) == Asset);+ }++ // WP03.7 physical material assets wait for a physical material prefix in art-pipeline 3+ // (request #1161); the mapping by name is covered by Verse.Destruction.Penetration.WorldMaterials.++ // WP03.6: the rim decal and the test surface master carry the parameters the renderer sets.+ const UMaterialInterface* Rim = LoadObject<UMaterialInterface>(nullptr, TEXT("/Game/Verse/Destruction/_Holes/M_HoleRim_Decal.M_HoleRim_Decal"));+ if (TestNotNull(TEXT("M_HoleRim_Decal exists"), Rim))+ {+ float Glow = -1.f;+ FLinearColor Color;+ TestTrue(TEXT("rim decal has RimGlow"), Rim->GetScalarParameterValue(FHashedMaterialParameterInfo(TEXT("RimGlow")), Glow));+ TestTrue(TEXT("rim decal has RimGlowColor"), Rim->GetVectorParameterValue(FHashedMaterialParameterInfo(TEXT("RimGlowColor")), Color));+ TestTrue(TEXT("rim decal is a deferred decal"), Rim->GetMaterial()->MaterialDomain == EMaterialDomain::MD_DeferredDecal);+ }+ const UMaterialInterface* Surface = LoadObject<UMaterialInterface>(nullptr, TEXT("/Game/Verse/Test/WP03/M_WP03_HoleSurface.M_WP03_HoleSurface"));+ if (TestNotNull(TEXT("M_WP03_HoleSurface exists"), Surface))+ {+ UTexture* Mask = nullptr;+ TestTrue(TEXT("test surface has HoleMask"), Surface->GetTextureParameterValue(FHashedMaterialParameterInfo(TEXT("HoleMask")), Mask));+ }+ // WP03.8: the fixture map.+ const UWorld* Map = LoadObject<UWorld>(nullptr, TEXT("/Game/Verse/Test/WP03/LV_WP03_Penetration.LV_WP03_Penetration"));+ if (!TestNotNull(TEXT("LV_WP03_Penetration exists"), Map) || !Map->PersistentLevel)+ {+ return false;+ }+ const UVersePenetrationTable* Contract = GetDefault<UVersePenetrationTable>();+ TSet<FString> Found;+ int32 Rig = 0;+ int32 Row = 0;+ for (const AActor* Actor : Map->PersistentLevel->Actors)+ {+ if (!Actor)+ {+ continue;+ }+ const FString Wire = TagValue(*Actor, TEXT("verse.wp03.wire:"));+ const FString Thickness = TagValue(*Actor, TEXT("verse.wp03.thickness_cm:"));+ if (Wire.IsEmpty() || Thickness.IsEmpty())+ {+ continue;+ }+ const FString Label = Actor->GetName();+ const FString Role = TagValue(*Actor, TEXT("verse.wp03.role:"));+ Rig += Role == TEXT("hole_rig") ? 1 : 0;+ Row += Role == TEXT("container_row") ? 1 : 0;+ const float ThicknessCm = FCString::Atof(*Thickness);+ TestTrue(*FString::Printf(TEXT("%s: scale gives the tagged thickness"), *Label),+ VerseWP03Test::Near(Actor->GetActorScale3D().X * 100.0, ThicknessCm, 1e-3));+ const FVersePenetrationRow* RowData = Contract->FindRow(uint8(FCString::Atoi(*Wire)));+ if (RowData)+ {+ for (const float Factor : {0.5f, 1.f, 3.f})+ {+ if (VerseWP03Test::Near(ThicknessCm, RowData->RefThicknessCm * Factor, 1e-3))+ {+ Found.Add(FString::Printf(TEXT("%s@%g"), *Wire, Factor));+ }+ }+ }+ }+ for (int32 Wire = 0; Wire < VersePenetration::FrozenMaterialIds().Num(); ++Wire)+ {+ for (const float Factor : {0.5f, 1.f, 3.f})+ {+ TestTrue(*FString::Printf(TEXT("fixture map has material %d at %gx"), Wire, Factor), Found.Contains(FString::Printf(TEXT("%d@%g"), Wire, Factor)));+ }+ }+ TestEqual(TEXT("hole angle rig: sheet and panel"), Rig, 2);+ TestEqual(TEXT("container row: three walls"), Row, 3);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationCompoundTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationCompoundTest.cppnew file mode 100644index 0000000000..c4dc36bc5a--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationCompoundTest.cpp@@ -0,0 +1,129 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "GameFramework/Actor.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Misc/AutomationTest.h"+#include "Penetration/VersePenetrationMath.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ using FShape = TPair<FVector, FVector>;++ /** A slab across the X axis: X from MinX to MaxX, 100 x 100 cm face. */+ FShape Slab(double MinX, double MaxX)+ {+ return FShape(FVector((MinX + MaxX) * 0.5, 0.0, 0.0), FVector((MaxX - MinX) * 0.5, 50.0, 50.0));+ }+}++// WP03.3 on real proxy shapes (art-pipeline.md 5: up to 16 convex shapes; Holed and Breached+// proxies are concave): the shapes of one proxy are one piece, charged once for the solid along+// the ray, and the air between its shapes is free. The sight hole test checks every solid run.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationCompoundTest, "Verse.Destruction.Penetration.Compound", WP03Flags)++bool FVersePenetrationCompoundTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ const EVersePenetrationMaterial Cladding = EVersePenetrationMaterial::CladdingPanel;+ const double LaneY = 300.0;++ // Lane 0: three touching shapes, 3 cm of solid; lane 1: one 3 cm box for reference.+ const FShape Touching[] = {Slab(-0.5, 0.5), Slab(0.5, 1.5), Slab(1.5, 2.5)};+ if (!TestNotNull(TEXT("compound proxy"), W.SpawnCompoundPiece(1, Cladding, FVector(100, 0 * LaneY, 0), Touching)))+ {+ return false;+ }+ W.SpawnPiece(2, Cladding, FVector(101, 1 * LaneY, 0), 3.f);+ // Lane 2: overlapping shapes (a convex decomposition with overlap), 3 cm of solid.+ const FShape Overlapping[] = {Slab(-0.5, 1.2), Slab(0.8, 2.5)};+ W.SpawnCompoundPiece(3, Cladding, FVector(100, 2 * LaneY, 0), Overlapping);+ // Lane 3: concave, two 1 cm runs with 3 cm of air between; lane 4: a 2 cm box for reference.+ const FShape Gap[] = {Slab(-0.5, 0.5), Slab(3.5, 4.5)};+ W.SpawnCompoundPiece(4, Cladding, FVector(100, 3 * LaneY, 0), Gap);+ W.SpawnPiece(5, Cladding, FVector(100, 4 * LaneY, 0), 2.f);+ // Lane 5: a four-run compound, then three single pieces: the compound counts as one piece.+ const FShape Four[] = {Slab(-0.5, -0.3), Slab(1.0, 1.2), Slab(2.5, 2.7), Slab(4.0, 4.2)};+ W.SpawnCompoundPiece(6, EVersePenetrationMaterial::SheetMetal, FVector(100, 5 * LaneY, 0), Four);+ for (int32 I = 0; I < 3; ++I)+ {+ W.SpawnPiece(uint16(7 + I), EVersePenetrationMaterial::SheetMetal, FVector(150 + 30 * I, 5 * LaneY, 0), 0.2f);+ }+ W.Settle();++ auto Fire = [&W](int32 Lane, float Power = 150.f, double Z = 0.0) {+ return W.Penetration->TraceBolt(FVector(0, Lane * LaneY, Z), FVector::ForwardVector, 1000.f, Power, 30.f, 15, 3);+ };++ const TArray<FVersePenetrationHit> Ref3 = Fire(1);+ const TArray<FVersePenetrationHit> Touch = Fire(0);+ if (TestEqual(TEXT("touching shapes: one piece entry"), Touch.Num(), 1) && TestEqual(TEXT("reference: one entry"), Ref3.Num(), 1))+ {+ TestEqual(TEXT("touching shapes: the piece"), Touch[0].PieceIndex, uint16(1));+ TestTrue(FString::Printf(TEXT("touching shapes: 3 cm traced (%.4f)"), Touch[0].TracedThicknessCm),+ VerseWP03Test::Near(Touch[0].TracedThicknessCm, 3.0, 1e-3));+ TestTrue(TEXT("touching shapes: entry and exit on the outer faces"),+ VerseWP03Test::Near(Touch[0].Entry.X, 99.5, 1e-3) && VerseWP03Test::Near(Touch[0].Exit.X, 102.5, 1e-3));+ TestTrue(TEXT("touching shapes cost what one 3 cm box costs"), VerseWP03Test::Near(Touch[0].PowerLeft, Ref3[0].PowerLeft, 1e-3)+ && VerseWP03Test::Near(Touch[0].DamageLeft, Ref3[0].DamageLeft, 1e-4));+ }+ const TArray<FVersePenetrationHit> Over = Fire(2);+ if (TestEqual(TEXT("overlapping shapes: one piece entry"), Over.Num(), 1))+ {+ TestTrue(FString::Printf(TEXT("overlapping shapes: 3 cm traced (%.4f)"), Over[0].TracedThicknessCm),+ VerseWP03Test::Near(Over[0].TracedThicknessCm, 3.0, 1e-3));+ }++ const TArray<FVersePenetrationHit> Ref2 = Fire(4);+ const TArray<FVersePenetrationHit> Concave = Fire(3);+ if (TestEqual(TEXT("concave proxy: one piece entry"), Concave.Num(), 1) && TestEqual(TEXT("2 cm reference: one entry"), Ref2.Num(), 1))+ {+ TestTrue(FString::Printf(TEXT("concave proxy: 2 cm of solid traced, the 3 cm of air left out (%.4f)"), Concave[0].TracedThicknessCm),+ VerseWP03Test::Near(Concave[0].TracedThicknessCm, 2.0, 1e-3));+ TestTrue(TEXT("concave proxy: exit on the far run"), VerseWP03Test::Near(Concave[0].Exit.X, 104.5, 1e-3));+ TestTrue(TEXT("concave proxy costs what 2 cm of solid costs"), VerseWP03Test::Near(Concave[0].PowerLeft, Ref2[0].PowerLeft, 1e-3));+ }++ const TArray<FVersePenetrationHit> Limit = Fire(5, 1000.f);+ if (TestEqual(TEXT("four-run proxy and three pieces: four entries"), Limit.Num(), 4))+ {+ TestEqual(TEXT("the four-run proxy is the first piece"), Limit[0].PieceIndex, uint16(6));+ TestTrue(TEXT("three pieces pass"), Limit[0].bPassed && Limit[1].bPassed && Limit[2].bPassed);+ TestFalse(TEXT("the 4th piece stops the bolt (the proxy counted once)"), Limit[3].bPassed);+ TestTrue(TEXT("four-run proxy: 0.8 cm of solid"), VerseWP03Test::Near(Limit[0].TracedThicknessCm, 0.8, 1e-3));+ }++ // Sight through a concave sheet proxy: thin runs 4 cm apart. A hole is a cylinder along its+ // axis; a ray at 30 deg off the axis passes the hole in the first run but meets solid in the+ // second, so it is blocked until the second run has a hole where the ray crosses it.+ W.Holes->ResetAll(1);+ const FShape Sheets[] = {Slab(-0.15, 0.15), Slab(3.85, 4.15)};+ W.SpawnCompoundPiece(20, EVersePenetrationMaterial::SheetMetal, FVector(100, 6 * LaneY, 0), Sheets);+ W.Settle();+ const FVector Eye(0, 6 * LaneY, 0);+ const FVector Slant = FRotator(0.0, 30.0, 0.0).RotateVector(FVector::ForwardVector);+ const FVector SlantEye = FVector(100, 6 * LaneY, 0) - Slant * 100.0;+ TestFalse(TEXT("no holes: the sheets block"), W.Penetration->TestSight(Eye, Eye + FVector(200, 0, 0)));+ W.Holes->AddHole(20, EVersePenetrationMaterial::SheetMetal, FVector::ZeroVector, FVector::ForwardVector, 15, 1000);+ TestTrue(TEXT("one hole on the axis: both runs lie inside its cylinder"), W.Penetration->TestSight(Eye, Eye + FVector(200, 0, 0)));+ TestFalse(TEXT("30 deg ray: passes the first run's hole, the second run blocks"),+ W.Penetration->TestSight(SlantEye, SlantEye + Slant * 200.0));+ const double Lateral = 4.0 * FMath::Tan(FMath::DegreesToRadians(30.0));+ W.Holes->AddHole(20, EVersePenetrationMaterial::SheetMetal, FVector(4.0, Lateral, 0.0), FVector::ForwardVector, 15, 1001);+ TestTrue(TEXT("30 deg ray with a hole in each run: see-through"), W.Penetration->TestSight(SlantEye, SlantEye + Slant * 200.0));+ const TArray<FVersePenetrationHit> Through =+ W.Penetration->TraceBolt(SlantEye, Slant, 200.f, 100.f, 30.f, 15, 3);+ TestEqual(TEXT("the bolt flies through both holes without cost"), Through.Num(), 0);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationTableTest.cpp b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationTableTest.cppnew file mode 100644index 0000000000..b163ad2f1c--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Private/Tests/Penetration/VersePenetrationTableTest.cpp@@ -0,0 +1,508 @@+#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "HAL/PlatformTime.h"+#include "Holes/VerseBoltHoleComponent.h"+#include "Misc/AutomationTest.h"+#include "Misc/FileHelper.h"+#include "Penetration/VersePenetrationJson.h"+#include "Penetration/VersePenetrationMath.h"+#include "Penetration/VersePenetrationPhysicalMaterial.h"+#include "Penetration/VersePenetrationSubsystem.h"+#include "Penetration/VersePenetrationTableImport.h"+#include "Tests/Penetration/Fakes/VerseWP03Fakes.h"+#include "Components/BoxComponent.h"+#include "Engine/World.h"+#include "PhysicalMaterials/PhysicalMaterial.h"+#include "VerseCollision.h"+#include "VerseLog.h"++namespace+{+ constexpr EAutomationTestFlags WP03Flags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ EVersePenetrationMaterial MaterialById(const FString& Id)+ {+ const TConstArrayView<const TCHAR*> Ids = VersePenetration::FrozenMaterialIds();+ for (int32 Wire = 0; Wire < Ids.Num(); ++Wire)+ {+ if (Id == Ids[Wire])+ {+ return EVersePenetrationMaterial(Wire);+ }+ }+ return EVersePenetrationMaterial::Concrete;+ }++ bool LoadJson(const FString& Path, FVerseJson& Out)+ {+ FString Text;+ FString Error;+ return FFileHelper::LoadFileToString(Text, *Path) && FVerseJson::Parse(Text, Out, Error) && Out.IsObject();+ }++ /** Imported rows of Data/destruction/penetration.json (what the runtime uses). */+ bool ImportedRows(FAutomationTestBase& Test, TArray<FVersePenetrationRow>& OutRows)+ {+ FString Text;+ TArray<FString> Errors;+ if (!Test.TestTrue(TEXT("penetration.json readable"), FFileHelper::LoadFileToString(Text, *VersePenetrationImport::DefaultTablePath())))+ {+ return false;+ }+ const bool bOk = VersePenetrationImport::ParseTableJson(Text, OutRows, Errors);+ for (const FString& Error : Errors)+ {+ Test.AddError(Error);+ }+ return bOk;+ }+}++// WP03.2: the importer reads the propose-only JSON into exactly the contract rows and refuses+// anything that breaks the frozen wire order or a column.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationImportTest, "Verse.Destruction.Penetration.Import", WP03Flags)++bool FVersePenetrationImportTest::RunTest(const FString& Parameters)+{+ TArray<FVersePenetrationRow> Rows;+ if (!ImportedRows(*this, Rows))+ {+ return false;+ }+ for (const FString& Diff : VersePenetrationImport::DiffRows(Rows, UVersePenetrationTable::MakeContractRows()))+ {+ AddError(FString::Printf(TEXT("penetration.json vs destruction.md 2: %s"), *Diff));+ }++ FString Text;+ FFileHelper::LoadFileToString(Text, *VersePenetrationImport::DefaultTablePath());+ struct FBad+ {+ const TCHAR* What;+ FString Json;+ };+ const TArray<FBad> BadInputs = {+ {TEXT("swapped wire order"), Text.Replace(TEXT("\"id\": \"sheet_metal\""), TEXT("\"id\": \"TMP\""))+ .Replace(TEXT("\"id\": \"container_wall\""), TEXT("\"id\": \"sheet_metal\""))+ .Replace(TEXT("\"id\": \"TMP\""), TEXT("\"id\": \"container_wall\""))},+ {TEXT("wrong wire number"), Text.Replace(TEXT("\"wire\": 7"), TEXT("\"wire\": 9"))},+ {TEXT("unknown material"), Text.Replace(TEXT("\"armor_steel\""), TEXT("\"steel_plate\""))},+ {TEXT("missing column"), Text.Replace(TEXT("\"damage_multiplier\": 0.95,"), TEXT(""))},+ {TEXT("power anchor"), Text.Replace(TEXT("\"power_anchor\": 100"), TEXT("\"power_anchor\": 40"))},+ {TEXT("piece limit"), Text.Replace(TEXT("\"max_pieces\": 3"), TEXT("\"max_pieces\": 2"))},+ {TEXT("schema"), Text.Replace(TEXT("verse.penetration/1"), TEXT("verse.penetration/2"))},+ {TEXT("not json"), TEXT("{")},+ };+ for (const FBad& Bad : BadInputs)+ {+ TestNotEqual(FString::Printf(TEXT("%s: mutation applied"), Bad.What), Bad.Json, Text);+ TArray<FVersePenetrationRow> Out;+ TArray<FString> Errors;+ TestFalse(FString::Printf(TEXT("%s is refused"), Bad.What), VersePenetrationImport::ParseTableJson(Bad.Json, Out, Errors));+ TestTrue(FString::Printf(TEXT("%s names an error"), Bad.What), Errors.Num() > 0);+ }++ // A table with a removed row fails the frozen order check.+ TArray<FVersePenetrationRow> Short = UVersePenetrationTable::MakeContractRows();+ Short.RemoveAt(3);+ TArray<FString> Errors;+ TestFalse(TEXT("removed row fails the wire order check"), VersePenetrationImport::CheckWireOrder(Short, Errors));++ // ImportIntoTable leaves the table untouched on failure.+ UVersePenetrationTable* Table = NewObject<UVersePenetrationTable>();+ Table->Rows[0].PenetrationCost = 99.f;+ Errors.Reset();+ TestFalse(TEXT("missing file refused"), VersePenetrationImport::ImportIntoTable(*Table, TEXT("Z:/no/such/penetration.json"), Errors));+ TestEqual(TEXT("table untouched on failure"), Table->Rows[0].PenetrationCost, 99.f);+ Errors.Reset();+ TestTrue(TEXT("default file imports"), VersePenetrationImport::ImportIntoTable(*Table, VersePenetrationImport::DefaultTablePath(), Errors));+ TestEqual(TEXT("imported sheet metal cost"), Table->Rows[0].PenetrationCost, 15.f);+ return true;+}++// A3.1: 8 materials x 3 thicknesses x 3 power levels against the hand-computed golden table to+// 1e-4, first as arithmetic, then as real traces through solid boxes of those thicknesses.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationTableTest, "Verse.Destruction.Penetration.Table", WP03Flags)++bool FVersePenetrationTableTest::RunTest(const FString& Parameters)+{+ TArray<FVersePenetrationRow> Rows;+ if (!ImportedRows(*this, Rows))+ {+ return false;+ }+ FVerseJson GoldenDoc;+ if (!TestTrue(TEXT("golden fixture loads"), LoadJson(VerseWP03Test::GoldenFixturePath(), GoldenDoc)))+ {+ return false;+ }+ const FVerseJson* Golden = &GoldenDoc;+ const double Tol = Golden->NumberOr(TEXT("tolerance"), 0.0);+ TestTrue(TEXT("tolerance is 1e-4"), VerseWP03Test::Near(Tol, 1e-4, 1e-12));+ static const TArray<FVerseJson> Empty;+ const TArray<FVerseJson>& Cases = Golden->FindArray(TEXT("cases")) ? *Golden->FindArray(TEXT("cases")) : Empty;+ TestEqual(TEXT("8 x 3 x 3 cases"), Cases.Num(), 72);++ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }++ int32 Checked = 0;+ uint16 PieceIndex = 0;+ for (const FVerseJson& Value : Cases)+ {+ const FVerseJson* Case = &Value;+ const FString Id = Case->StringOr(TEXT("material"));+ const EVersePenetrationMaterial Material = MaterialById(Id);+ const FVersePenetrationRow& Row = Rows[uint8(Material)];+ const float Thickness = float(Case->NumberOr(TEXT("thickness_cm"), 0.0));+ const float Power = float(Case->NumberOr(TEXT("power"), 0.0));+ const FString Label = FString::Printf(TEXT("%s %.2f cm power %.0f"), *Id, Thickness, Power);++ const FVersePenetrationStep Step = VersePenetration::EvaluatePiece(Row, Thickness, Power, 1.f, false);+ TestTrue(Label + TEXT(" cost"), VerseWP03Test::Near(Step.Cost, Case->NumberOr(TEXT("cost"), 0.0), Tol));+ TestEqual(Label + TEXT(" passed"), Step.bPassed, Case->BoolOr(TEXT("passed"), false));+ TestTrue(Label + TEXT(" power left"), VerseWP03Test::Near(Step.PowerLeft, Case->NumberOr(TEXT("power_left"), 0.0), Tol));+ TestTrue(Label + TEXT(" damage left"), VerseWP03Test::Near(Step.DamageLeft, Case->NumberOr(TEXT("damage_left"), 0.0), Tol));++ // The same case through a real solid of that thickness, traced on VerseBolt.+ const FVector Center(500.f + 200.f * PieceIndex, 0.f, 0.f);+ AActor* Piece = W.SpawnPiece(PieceIndex, Material, Center, Thickness);+ W.Settle();+ const FVector Origin = Center - FVector(Thickness * 0.5f + 5.f, 0, 0);+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(Origin, FVector::ForwardVector, Thickness + 10.f, Power, 1.f, 15, 3);+ if (TestEqual(Label + TEXT(" traced pieces"), Hits.Num(), 1))+ {+ const FVersePenetrationHit& Hit = Hits[0];+ TestEqual(Label + TEXT(" traced piece index"), Hit.PieceIndex, PieceIndex);+ TestEqual(Label + TEXT(" traced wire id"), Hit.MaterialWireId, uint8(Material));+ TestTrue(Label + FString::Printf(TEXT(" traced thickness %.6f"), Hit.TracedThicknessCm),+ VerseWP03Test::Near(Hit.TracedThicknessCm, Thickness, Tol));+ TestEqual(Label + TEXT(" traced passed"), Hit.bPassed, Case->BoolOr(TEXT("passed"), false));+ TestTrue(Label + TEXT(" traced power left"), VerseWP03Test::Near(Hit.PowerLeft, Case->NumberOr(TEXT("power_left"), 0.0), Tol * 10.0));+ TestTrue(Label + TEXT(" traced damage left"), VerseWP03Test::Near(Hit.DamageLeft, Case->NumberOr(TEXT("damage_left"), 0.0), Tol));+ }+ W.DestroyActor(Piece);+ ++PieceIndex;+ ++Checked;+ }+ TestEqual(TEXT("every case checked"), Checked, 72);++ // Chains: several pieces, the 3-piece limit and the rifle through two container walls.+ const TArray<FVerseJson>& Chains = Golden->FindArray(TEXT("chains")) ? *Golden->FindArray(TEXT("chains")) : Empty;+ TestEqual(TEXT("six chains"), Chains.Num(), 6);+ for (const FVerseJson& Value : Chains)+ {+ const FVerseJson* Chain = &Value;+ const FString Name = Chain->StringOr(TEXT("name"));+ const TArray<FVerseJson>& Pieces = Chain->FindArray(TEXT("pieces")) ? *Chain->FindArray(TEXT("pieces")) : Empty;+ const TArray<FVerseJson>& Passed = Chain->FindArray(TEXT("passed")) ? *Chain->FindArray(TEXT("passed")) : Empty;+ const TArray<FVerseJson>& PowerLeft = Chain->FindArray(TEXT("power_left")) ? *Chain->FindArray(TEXT("power_left")) : Empty;+ const TArray<FVerseJson>& DamageLeft = Chain->FindArray(TEXT("damage_left")) ? *Chain->FindArray(TEXT("damage_left")) : Empty;+ if (!TestTrue(Chain->StringOr(TEXT("name")) + TEXT(": arrays line up"), Passed.Num() == Pieces.Num() && PowerLeft.Num() == Pieces.Num() && DamageLeft.Num() == Pieces.Num()))+ {+ continue;+ }+ const int32 MaxPieces = int32(Chain->NumberOr(TEXT("max_pieces"), 0.0));+ const float Power = float(Chain->NumberOr(TEXT("power"), 0.0));++ // Arithmetic.+ float P = Power;+ float D = 1.f;+ int32 Passes = 0;+ for (int32 I = 0; I < Pieces.Num(); ++I)+ {+ const FVerseJson* PieceSpec = &Pieces[I];+ const FVersePenetrationRow& Row = Rows[uint8(MaterialById(PieceSpec->StringOr(TEXT("material"))))];+ const FVersePenetrationStep Step = VersePenetration::EvaluatePiece(Row, float(PieceSpec->NumberOr(TEXT("thickness_cm"), 0.0)), P, D,+ Passes >= VersePenetration::EffectiveMaxPieces(MaxPieces));+ TestEqual(FString::Printf(TEXT("%s: piece %d passed"), *Name, I), Step.bPassed, Passed[I].Bool);+ TestTrue(FString::Printf(TEXT("%s: piece %d power"), *Name, I), VerseWP03Test::Near(Step.PowerLeft, PowerLeft[I].Number, Tol));+ TestTrue(FString::Printf(TEXT("%s: piece %d damage"), *Name, I), VerseWP03Test::Near(Step.DamageLeft, DamageLeft[I].Number, Tol));+ if (!Step.bPassed)+ {+ break;+ }+ P = Step.PowerLeft;+ D = Step.DamageLeft;+ ++Passes;+ }++ // Traced: the pieces stand 50 cm apart on the bolt's line.+ TArray<AActor*> Spawned;+ for (int32 I = 0; I < Pieces.Num(); ++I)+ {+ const FVerseJson* PieceSpec = &Pieces[I];+ Spawned.Add(W.SpawnPiece(uint16(1000 + I), MaterialById(PieceSpec->StringOr(TEXT("material"))), FVector(3000.f + 50.f * I, 0, 0),+ float(PieceSpec->NumberOr(TEXT("thickness_cm"), 0.0))));+ }+ W.Settle();+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(FVector(2950.f, 0, 0), FVector::ForwardVector, 1000.f, Power, 1.f, 15, MaxPieces);+ if (TestEqual(Name + TEXT(": traced pieces"), Hits.Num(), Passed.Num()))+ {+ for (int32 I = 0; I < Hits.Num(); ++I)+ {+ TestEqual(FString::Printf(TEXT("%s: traced %d passed"), *Name, I), Hits[I].bPassed, Passed[I].Bool);+ TestTrue(FString::Printf(TEXT("%s: traced %d damage %.6f"), *Name, I, Hits[I].DamageLeft),+ VerseWP03Test::Near(Hits[I].DamageLeft, DamageLeft[I].Number, Tol));+ }+ }+ for (AActor* Actor : Spawned)+ {+ W.DestroyActor(Actor);+ }+ }+ return true;+}++// A3.2: concrete, armor steel and the hall floor never pass; the 4th piece always stops a bolt;+// a weapon may lower the limit, never raise it.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationBudgetTest, "Verse.Combat.Penetration.Budget", WP03Flags)++bool FVersePenetrationBudgetTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ const EVerseWorldSurface Floor = EVerseWorldSurface::HallFloor;+ const EVerseWorldSurface Wall = EVerseWorldSurface::StructuralWall;+ const EVerseWorldSurface Beam = EVerseWorldSurface::StructuralBeam;+ struct FSurfaceCase+ {+ const TCHAR* Name;+ const EVerseWorldSurface* Surface;+ EVersePenetrationMaterial Expected;+ };+ const FSurfaceCase Surfaces[] = {+ {TEXT("hall floor"), &Floor, EVersePenetrationMaterial::Concrete},+ {TEXT("structural wall"), &Wall, EVersePenetrationMaterial::Concrete},+ {TEXT("structural beam"), &Beam, EVersePenetrationMaterial::ArmorSteel},+ {TEXT("unmapped geometry"), nullptr, EVersePenetrationMaterial::Concrete},+ };+ const float Thicknesses[] = {0.5f, 1.f, 2.5f, 10.f, 30.f, 90.f};+ const float Powers[] = {50.f, 100.f, 150.f, 199.f};+ // Every box gets its own spot: a destroyed body can linger in the scene query structure+ // for a frame, and a fresh box on the same spot would answer with the old one.+ float Lane = 0.f;+ for (const FSurfaceCase& Surface : Surfaces)+ {+ for (const float Thickness : Thicknesses)+ {+ Lane += 400.f;+ AActor* Box = W.SpawnWorldBox(Surface.Surface, FVector(1000.f, Lane, 0), Thickness);+ W.Settle();+ for (const float Power : Powers)+ {+ const FString Label = FString::Printf(TEXT("%s %.1f cm power %.0f"), Surface.Name, Thickness, Power);+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(FVector(900.f, Lane, 0), FVector::ForwardVector, 500.f, Power, 1.f, 15, 3);+ if (TestEqual(Label + TEXT(": one surface"), Hits.Num(), 1))+ {+ TestFalse(Label + TEXT(": never passes"), Hits[0].bPassed);+ TestEqual(Label + TEXT(": row"), Hits[0].MaterialWireId, uint8(Surface.Expected));+ TestEqual(Label + TEXT(": no piece"), Hits[0].PieceIndex, VersePenetration::NoPiece);+ TestEqual(Label + TEXT(": no damage left"), Hits[0].DamageLeft, 0.f);+ }+ }+ W.DestroyActor(Box);+ }+ }++ // Four laminated panes cost 5 each: power is no object, the limit is.+ TArray<AActor*> Panes;+ for (int32 I = 0; I < 4; ++I)+ {+ Panes.Add(W.SpawnPiece(uint16(I), EVersePenetrationMaterial::Glass, FVector(2000.f + 40.f * I, 0, 0), 2.4f));+ }+ W.Settle();+ struct FLimitCase+ {+ int32 WeaponMax;+ int32 Stops;+ };+ const FLimitCase Limits[] = {{3, 3}, {7, 3}, {100, 3}, {2, 2}, {1, 1}, {0, 0}};+ for (const FLimitCase& Limit : Limits)+ {+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(FVector(1900.f, 0, 0), FVector::ForwardVector, 1000.f, 1.0e6f, 1.f, 15, Limit.WeaponMax);+ const FString Label = FString::Printf(TEXT("weapon limit %d"), Limit.WeaponMax);+ if (TestEqual(Label + TEXT(": pieces entered"), Hits.Num(), Limit.Stops + 1))+ {+ for (int32 I = 0; I < Limit.Stops; ++I)+ {+ TestTrue(FString::Printf(TEXT("%s: piece %d passes"), *Label, I), Hits[I].bPassed);+ }+ TestFalse(Label + TEXT(": the next piece stops it"), Hits.Last().bPassed);+ TestEqual(Label + TEXT(": stopped piece index"), Hits.Last().PieceIndex, uint16(Limit.Stops));+ }+ }+ for (AActor* Pane : Panes)+ {+ W.DestroyActor(Pane);+ }+ return true;+}++// WP03.7: non-destructible world geometry maps to table rows through its physical material.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationWorldMaterialsTest, "Verse.Destruction.Penetration.WorldMaterials", WP03Flags)++bool FVersePenetrationWorldMaterialsTest::RunTest(const FString& Parameters)+{+ TestEqual(TEXT("hall floor is concrete"), VersePenetration::WorldSurfaceMaterial(EVerseWorldSurface::HallFloor), EVersePenetrationMaterial::Concrete);+ TestEqual(TEXT("structural wall is concrete"), VersePenetration::WorldSurfaceMaterial(EVerseWorldSurface::StructuralWall),+ EVersePenetrationMaterial::Concrete);+ TestEqual(TEXT("structural beam is armor steel"), VersePenetration::WorldSurfaceMaterial(EVerseWorldSurface::StructuralBeam),+ EVersePenetrationMaterial::ArmorSteel);+ TestEqual(TEXT("no physical material is concrete"), VersePenetration::ResolveWorldMaterial(nullptr), EVersePenetrationMaterial::Concrete);+ TestEqual(TEXT("a foreign physical material is concrete"),+ VersePenetration::ResolveWorldMaterial(VerseWP03Test::MakePhysicalMaterial(TEXT("PM_Rubber"))), EVersePenetrationMaterial::Concrete);+ TestEqual(TEXT("a near-miss name is concrete"),+ VersePenetration::ResolveWorldMaterial(VerseWP03Test::MakePhysicalMaterial(TEXT("PM_Verse_StructuralBeamish"))), EVersePenetrationMaterial::Concrete);+ const UEnum* Surfaces = StaticEnum<EVerseWorldSurface>();+ for (int32 I = 0; I < Surfaces->NumEnums() - 1; ++I)+ {+ const EVerseWorldSurface Surface = EVerseWorldSurface(Surfaces->GetValueByIndex(I));+ const FString Name = VersePenetration::PhysicalMaterialName(Surface);+ UPhysicalMaterial* Mat = VerseWP03Test::MakePhysicalMaterial(Name);+ if (!TestNotNull(TEXT("physical material class"), Mat))+ {+ return false;+ }+ TestEqual(Name + TEXT(" maps to its row"), VersePenetration::ResolveWorldMaterial(Mat), VersePenetration::WorldSurfaceMaterial(Surface));+ UPhysicalMaterial* Variant = VerseWP03Test::MakePhysicalMaterial(Name + TEXT("_Painted"));+ TestEqual(Name + TEXT("_Painted maps to the same row"), VersePenetration::ResolveWorldMaterial(Variant), VersePenetration::WorldSurfaceMaterial(Surface));+ EVerseWorldSurface Back;+ TestTrue(Name + TEXT(" round trip"), VersePenetration::SurfaceFromPhysicalMaterialName(Name, Back) && Back == Surface);+ }++ // Through a real trace: the hit's physical material picks the row.+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ for (int32 I = 0; I < Surfaces->NumEnums() - 1; ++I)+ {+ const EVerseWorldSurface Surface = EVerseWorldSurface(Surfaces->GetValueByIndex(I));+ const float Lane = 500.f * (I + 1);+ AActor* Box = W.SpawnWorldBox(&Surface, FVector(300.f, Lane, 0), 20.f);+ W.Settle();+ {+ FHitResult Probe;+ FCollisionQueryParams ProbeParams(SCENE_QUERY_STAT(VerseWP03Probe), false);+ ProbeParams.bReturnPhysicalMaterial = true;+ W.World()->LineTraceSingleByChannel(Probe, FVector(0, Lane, 0), FVector(600.f, Lane, 0), VerseCollision::Bolt, ProbeParams);+ const UBoxComponent* BoxComp = W.BoxOf(Box);+ AddInfo(FString::Printf(TEXT("%s: hit physical material %s, override %s"), *VersePenetration::PhysicalMaterialName(Surface),+ Probe.PhysMaterial.IsValid() ? *static_cast<const UObject*>(Probe.PhysMaterial.Get())->GetName() : TEXT("none"),+ BoxComp && BoxComp->BodyInstance.GetPhysMaterialOverride() ? *static_cast<const UObject*>(BoxComp->BodyInstance.GetPhysMaterialOverride())->GetName() : TEXT("none")));+ }+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(FVector(0, Lane, 0), FVector::ForwardVector, 600.f, 150.f, 1.f, 15, 3);+ if (TestEqual(TEXT("one surface"), Hits.Num(), 1))+ {+ TestEqual(VersePenetration::PhysicalMaterialName(Surface) + TEXT(" traced row"), Hits[0].MaterialWireId,+ uint8(VersePenetration::WorldSurfaceMaterial(Surface)));+ }+ W.DestroyActor(Box);+ }+ return true;+}++// A3.5: 64 TraceBolt calls per tick, each through three pieces, at most 0.3 ms game thread.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePenetrationCostTest, "Verse.Destruction.Penetration.Cost", WP03Flags)++bool FVersePenetrationCostTest::RunTest(const FString& Parameters)+{+ FVerseWP03World W;+ if (!TestTrue(TEXT("test world"), W.Create()))+ {+ return false;+ }+ // A container row: three walls, then a structural wall behind them.+ for (int32 I = 0; I < 3; ++I)+ {+ W.SpawnPiece(uint16(I), EVersePenetrationMaterial::SheetMetal, FVector(200.f + 100.f * I, 0, 0), 0.3f, 400.f, 400.f);+ }+ const EVerseWorldSurface Wall = EVerseWorldSurface::StructuralWall;+ W.SpawnWorldBox(&Wall, FVector(800.f, 0, 0), 30.f, 600.f, 600.f);+ W.Settle();++ // Under fire: the walls carry holes, the arena is near its cap, and every bolt records its+ // holes inside the tick, so per-piece caps, wall Holed events and arena evictions all run.+ uint32 ServerMs = 1000;+ for (int32 I = 0; I < 480; ++I)+ {+ W.Holes->AddHole(uint16(3 + I % 20), EVersePenetrationMaterial::SheetMetal, FVector(0, -40.0 + 4.0 * (I / 20), 0),+ FVector::ForwardVector, 15, ServerMs++);+ }+ for (int32 I = 0; I < 3; ++I)+ {+ for (int32 H = 0; H < 12; ++H)+ {+ W.Holes->AddHole(uint16(I), EVersePenetrationMaterial::SheetMetal, FVector(0, 190.0, -190.0 + 10.0 * H), FVector::ForwardVector, 15,+ ServerMs++);+ }+ }++ constexpr int32 Ticks = 41;+ constexpr int32 CallsPerTick = 64;+ TArray<double> TickMs;+ TArray<double> RecordMs;+ TArray<double> TraceMs;+ int32 Entered = 0;+ int32 Recorded = 0;+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ const double Start = FPlatformTime::Seconds();+ double InRecord = 0.0;+ double InTrace = 0.0;+ for (int32 Call = 0; Call < CallsPerTick; ++Call)+ {+ const FVector Origin(0.f, -150.f + 300.f * Call / CallsPerTick, -100.f + 3.f * Tick);+ const double TraceStart = FPlatformTime::Seconds();+ const TArray<FVersePenetrationHit> Hits = W.Penetration->TraceBolt(Origin, FVector::ForwardVector, 1500.f, 100.f, 30.f, 15, 3);+ InTrace += FPlatformTime::Seconds() - TraceStart;+ Entered += Hits.Num();+ const double RecordStart = FPlatformTime::Seconds();+ Recorded += W.Penetration->RecordBoltHoles(Hits, FVector::ForwardVector, 15, ServerMs++);+ InRecord += FPlatformTime::Seconds() - RecordStart;+ }+ TickMs.Add((FPlatformTime::Seconds() - Start) * 1000.0);+ RecordMs.Add(InRecord * 1000.0);+ TraceMs.Add(InTrace * 1000.0);+ }+ TickMs.Sort();+ RecordMs.Sort();+ TraceMs.Sort();+ UE_LOG(LogVerseDestruction, Display, TEXT("WP03 cost: RecordBoltHoles share of a tick: median %.4f ms, p90 %.4f ms"), RecordMs[Ticks / 2],+ RecordMs[Ticks * 9 / 10]);+ // Wall time on a box shared by many agents and builds: a preempted tick says nothing about+ // the code, so the gate reads the median and the log keeps the tail.+ const double Q25 = TickMs[Ticks / 4];+ const double Median = TickMs[Ticks / 2];+ const double P90 = TickMs[Ticks * 9 / 10];+ UE_LOG(LogVerseDestruction, Display,+ TEXT("WP03 cost: 64 TraceBolt + RecordBoltHoles per tick, %d holes live, min %.4f ms, q25 %.4f ms, median %.4f ms, p90 %.4f ms, max %.4f ms"),+ W.Holes->Num(), TickMs[0], Q25, Median, P90, TickMs.Last());+ TestEqual(TEXT("every call enters three walls and the structural wall"), Entered, Ticks * CallsPerTick * 4);+ TestTrue(FString::Printf(TEXT("holes recorded under fire (%d)"), Recorded), Recorded > Ticks * CallsPerTick);+ TestTrue(TEXT("the arena stays at or under its cap"), W.Holes->Num() <= W.Holes->GetHolesPerArena());+ // A3.5 is about the 64 TraceBolt calls: 0.3 ms, read as the median of their share of each+ // tick (holes present, records written in the same ticks). RecordBoltHoles has its own budget.+ const double TraceMedian = TraceMs[Ticks / 2];+ const double RecordMedian = RecordMs[Ticks / 2];+ UE_LOG(LogVerseDestruction, Display, TEXT("WP03 cost: TraceBolt share of a tick: median %.4f ms, p90 %.4f ms"), TraceMedian,+ TraceMs[Ticks * 9 / 10]);+ TestTrue(FString::Printf(TEXT("A3.5: 64 TraceBolt calls, median %.4f ms <= 0.3 ms"), TraceMedian), TraceMedian <= 0.3);+ TestTrue(FString::Printf(TEXT("RecordBoltHoles for 64 bolts, median %.4f ms <= 0.1 ms"), RecordMedian), RecordMedian <= 0.1);+ AddInfo(FString::Printf(TEXT("full tick (TraceBolt + RecordBoltHoles) median %.4f ms"), Median));+ AddInfo(FString::Printf(TEXT("TraceBolt cost per 64 calls: min %.4f ms, q25 %.4f ms, median %.4f ms, p90 %.4f ms, max %.4f ms"), TickMs[0], Q25, Median,+ P90, TickMs.Last()));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseBoltHoleComponent.h b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseBoltHoleComponent.hnew file mode 100644index 0000000000..80850a8f7d--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseBoltHoleComponent.h@@ -0,0 +1,175 @@+#pragma once++#include "Components/ActorComponent.h"+#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++#include "VerseBoltHoleComponent.generated.h"++class UVerseBoltHoleComponent;+class UVerseDestructionTuning;++/** What AddHole did. */+UENUM()+enum class EVerseHoleAddResult : uint8+{+ /** The hole is recorded. */+ Added,+ /** Hole 25 on a wall: the piece's holes are cleared and OnPieceHoleCap fired; the piece goes Holed. */+ PieceHoled,+ /** Grating, concrete and armor steel keep no holes (dents and scorches only). */+ NotHoleMaterial,+ /** Only the server records holes (DR1). */+ NotAuthority+};++/**+ * One replicated slot of the arena's hole records. A slot keeps its index for the life of its+ * hole, so adding or evicting a hole changes one slot and replication sends only that slot.+ * Sequence orders holes by age (server insertion order); 0 marks a free slot.+ */+USTRUCT()+struct VERSEDESTRUCTION_API FVerseBoltHoleSlot+{+ GENERATED_BODY()++ UPROPERTY()+ FVerseBoltHole Hole;++ UPROPERTY()+ uint32 Sequence = 0;++ bool IsUsed() const { return Sequence != 0; }++ bool operator==(const FVerseBoltHoleSlot& Other) const+ {+ return Sequence == Other.Sequence && Hole.PieceIndex == Other.Hole.PieceIndex && Hole.Epoch == Other.Hole.Epoch+ && Hole.ServerTimeMs == Other.Hole.ServerTimeMs;+ }+};++/** (PieceIndex, hole centroid piece-local cm). The piece owner turns the wall Holed with the variant nearest the centroid. */+DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVersePieceHoleCap, uint16, const FVector&);+/**+ * A change of the hole set, on server and clients (the renderer listens): the pieces whose holes+ * changed, or bAll after a reset or an epoch change.+ */+DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVerseHolesChanged, TConstArrayView<uint16> /*Pieces*/, bool /*bAll*/);++/**+ * Bolt hole records of one arena (destruction.md 5, WP03.5). Lives on AVerseDestructionManager+ * (always relevant). Caps: 24 per piece, 512 per arena. Hole 25 on a wall piece clears its+ * holes and asks the owner to turn it Holed; on glass and ceiling panels the piece's oldest hole+ * goes. At the arena cap the oldest hole of the piece with the most holes is dropped. A reset+ * bumps the epoch and clears everything.+ *+ * Replication: the contract asks for an FFastArraySerializer, which needs NetCore, and the+ * module edges of architecture.md 2 give VerseDestruction only Core, CoreUObject, Engine and+ * VerseCore (CCR #1134). Until that edge exists the records are a slot array with stable indices+ * and a free list: an add, an eviction or a clear rewrites only the slots it touches, nothing+ * shifts, and property replication sends exactly those slots. The per-piece view is kept up to+ * date incrementally on the server and from a slot diff on clients.+ */+UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))+class VERSEDESTRUCTION_API UVerseBoltHoleComponent : public UActorComponent+{+ GENERATED_BODY()++public:+ UVerseBoltHoleComponent();++ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;++ /** Takes the hole caps from DA_DestructionTuning. */+ void ApplyTuning(const UVerseDestructionTuning& Tuning);++ /** Server: record a hole whose axis passes AxisPointLocalCm along AxisDirectionLocal (piece-local). */+ EVerseHoleAddResult AddHole(uint16 PieceIndex, EVersePenetrationMaterial Material, const FVector& AxisPointLocalCm,+ const FVector& AxisDirectionLocal, uint8 RadiusMm, uint32 ServerTimeMs);++ /** Server: the piece went Holed, Breached or Destroyed, or was repaired. */+ void ClearPiece(uint16 PieceIndex);++ /** Server: full reset (destruction.md 11). Every hole goes, the epoch becomes NewEpoch. */+ void ResetAll(uint16 NewEpoch);++ /** Holes of one piece, oldest first (current epoch only). */+ TConstArrayView<FVerseBoltHole> GetPieceHoles(uint16 PieceIndex) const;++ /** Every hole of the current epoch, oldest first. */+ void GetAllHoles(TArray<FVerseBoltHole>& OutHoles) const;++ /**+ * The two-point hole test of FVerseBoltHole::RayPassesHoles on one piece, with each hole's axis+ * decoded once when it is recorded instead of on every query (the same arithmetic).+ */+ bool RayPassesPieceHoles(uint16 PieceIndex, const FVector& EntryLocalCm, const FVector& ExitLocalCm) const;++ /** The raw slots (free ones included); a slot index identifies one hole while it lives. */+ TConstArrayView<FVerseBoltHoleSlot> GetSlots() const { return Slots; }+ /** True when a slot holds a hole of the current epoch. */+ bool IsLiveSlot(int32 SlotIndex) const;++ int32 Num() const { return LiveCount; }+ int32 NumOnPiece(uint16 PieceIndex) const;+ uint16 GetEpoch() const { return Epoch; }+ int32 GetHolesPerPiece() const { return HolesPerPiece; }+ int32 GetHolesPerArena() const { return HolesPerArena; }++ FOnVersePieceHoleCap OnPieceHoleCap;+ FOnVerseHolesChanged OnHolesChanged;++protected:+ UFUNCTION()+ void OnRep_Slots();++ UFUNCTION()+ void OnRep_Epoch();++private:+ /** Every hole of the arena at a stable index; free slots have Sequence 0. */+ UPROPERTY(ReplicatedUsing = OnRep_Slots)+ TArray<FVerseBoltHoleSlot> Slots;++ UPROPERTY(ReplicatedUsing = OnRep_Epoch)+ uint16 Epoch = 0;++ UPROPERTY(EditAnywhere, Category = "Verse")+ int32 HolesPerPiece = 24;++ UPROPERTY(EditAnywhere, Category = "Verse")+ int32 HolesPerArena = 512;++ /** One piece's live holes, oldest first, and the slot each one sits in. */+ /** A hole axis as FVerseBoltHole::ContainsPoint reads it, decoded once. */+ struct FHoleAxis+ {+ FVector PointCm = FVector::ZeroVector;+ FVector Direction = FVector::ForwardVector;+ double RadiusSq = 0.0;++ explicit FHoleAxis(const FVerseBoltHole& Hole);+ bool Contains(const FVector& PieceLocalCm) const;+ };++ struct FPieceHoles+ {+ TArray<FVerseBoltHole> Holes;+ TArray<int32> SlotIndices;+ TArray<FHoleAxis> Axes;+ };++ TMap<uint16, FPieceHoles> ByPiece;+ TArray<int32> FreeSlots;+ uint32 NextSequence = 1;+ int32 LiveCount = 0;+ /** Clients: the slots as last seen, to find which pieces a replication update touched. */+ TArray<FVerseBoltHoleSlot> SeenSlots;++ bool HasServerAuthority() const;+ void RemoveSlot(int32 SlotIndex);+ void EvictForArenaCap();+ void RebuildPieces(TConstArrayView<uint16> Pieces);+ void RebuildAll();+ void Broadcast(TConstArrayView<uint16> Pieces, bool bAll);+};diff --git a/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleGlow.h b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleGlow.hnew file mode 100644index 0000000000..69f437fe81--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleGlow.h@@ -0,0 +1,59 @@+#pragma once++#include "CoreMinimal.h"++// The hole rim glow of destruction.md 5 (WP03.6): incandescent white-amber at impact,+// exponential cooling with tau 1.2 s, dull red at about 2.5 s, off at 4 s, then a permanent+// charred rim. Never cyan or violet (art-pipeline.md 8.3). Pure functions, so the renderer,+// the palette test and the bot's glow cue read the same curve.++/** One sample of the rim glow. */+struct FVerseHoleGlowSample+{+ /** Emissive colour, linear, hue only (multiply by Intensity). */+ FLinearColor Color = FLinearColor::Black;+ /** 1 at impact, exp(-age / tau), faded to 0 at the end. */+ float Intensity = 0.f;+ bool bGlowing = false;+};++namespace VerseHoleGlow+{+ inline constexpr float DefaultTauS = 1.2f;+ inline constexpr float DefaultEndS = 4.f;+ /** The last stretch before the end over which the glow fades to exactly 0. */+ inline constexpr float EndFadeS = 0.5f;+ /** Emissive multiplier of a fresh hole in the rim material (scene-referred). */+ inline constexpr float PeakEmissive = 40.f;++ /** White-amber at impact, amber at 1 s, dull red from 2.5 s on. */+ VERSEDESTRUCTION_API FLinearColor ColorAt(float AgeS);++ VERSEDESTRUCTION_API FVerseHoleGlowSample Sample(float AgeS, float TauS = DefaultTauS, float EndS = DefaultEndS);++ /** The charred rim colour after the glow ends (dark, nearly neutral). */+ VERSEDESTRUCTION_API FLinearColor CharredColor();++ /** How far a record may lie in the future of the local server clock and still count as fresh (clock skew). */+ inline constexpr uint32 DefaultMaxFutureMs = 250;++ /**+ * Age in seconds of a hole stamped TimeMs at server time NowMs. A record up to MaxFutureMs in+ * the future is 0 s old; one further ahead is treated as long cooled (MAX_flt), so a client+ * whose clock lags never lights every recent hole at once.+ */+ VERSEDESTRUCTION_API float AgeS(uint32 TimeMs, uint32 NowMs, uint32 MaxFutureMs = DefaultMaxFutureMs);++ /**+ * Which holes may glow: the newest `Cap` of those younger than EndS (the oldest cools first).+ * Times in ms of server time, NowMs the current server time. Returns indices into TimesMs.+ */+ VERSEDESTRUCTION_API TArray<int32> SelectGlowing(TConstArrayView<uint32> TimesMs, uint32 NowMs, int32 Cap, float EndS = DefaultEndS,+ uint32 MaxFutureMs = DefaultMaxFutureMs);++ /**+ * The rendered-pixel ban of art-pipeline.md 8.3 for one sRGB pixel: hue in 160..330 deg with+ * saturation above 0.25 and value above 0.08.+ */+ VERSEDESTRUCTION_API bool IsBannedPixel(const FColor& Srgb);+}diff --git a/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleRenderComponent.h b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleRenderComponent.hnew file mode 100644index 0000000000..e03392e52d--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Holes/VerseHoleRenderComponent.h@@ -0,0 +1,153 @@+#pragma once++#include "Components/ActorComponent.h"+#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++#include "VerseHoleRenderComponent.generated.h"++class UDecalComponent;+class UMaterialInstanceDynamic;+class UMaterialInterface;+class UMeshComponent;+class USceneComponent;+class UTextureRenderTarget2D;+class UVerseBoltHoleComponent;++/**+ * Client presentation of bolt holes (destruction.md 5, WP03.6). Draws exactly the replicated+ * hole records, so what the person sees through a hole is what the bot can see:+ *+ * - a 256 x 256 opacity mask per piece in piece UV space, created on the piece's first hole and+ * bound to the piece mesh's `HoleMask` texture parameter (black discs = open);+ * - one rim decal per hole, spanning the piece's thickness along the hole axis, with the rim+ * glow of VerseHoleGlow (white-amber, tau 1.2 s, dull red at 2.5 s, off at 4 s, then charred);+ * - at most 128 glowing holes; the oldest cools first. No dynamic light per hole.+ *+ * Bookkeeping (mask slots, decal slots, the glowing set) runs everywhere; GPU objects are made+ * only where something renders (not on a dedicated server, not under -nullrhi).+ */+UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))+class VERSEDESTRUCTION_API UVerseHoleRenderComponent : public UActorComponent+{+ GENERATED_BODY()++public:+ UVerseHoleRenderComponent();++ virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;+ virtual void EndPlay(const EEndPlayReason::Type Reason) override;++ void SetHoleSource(UVerseBoltHoleComponent* InHoles);++ /**+ * A piece's visible mesh. LocalBounds is the piece's solid in its frame; the mask maps the+ * piece's largest face of those bounds to UV 0..1 (the UV layout the piece builder authors).+ */+ void RegisterPieceVisual(uint16 PieceIndex, UMeshComponent* Mesh, const FBox& LocalBounds, USceneComponent* Frame = nullptr);++ /**+ * Server time in ms the glow ages against. Default: the replicated server clock+ * (AGameStateBase::GetServerWorldTimeSeconds), the world's own time only without a game state.+ */+ void SetServerTimeSource(TFunction<uint32()> InNow);++ /** The server time in ms the glow ages against right now. */+ uint32 CurrentTimeMs() const;++ /** Brings masks, decals and glow up to date now (normally on the next tick). */+ void Sync();++ /** UV of a piece-local point on the largest face of LocalBounds. */+ static FVector2D HoleUV(const FBox& LocalBounds, const FVector& LocalPointCm);+ /** Mask pixels of a hole radius on that face. */+ static float HoleRadiusPx(const FBox& LocalBounds, float RadiusCm, int32 MaskSize);++ /** True where GPU objects are made (client with a real RHI). */+ static bool CanRender(const UWorld* World);++ int32 NumMaskSlots() const { return MaskPieces.Num(); }+ /** Holes drawn (one decal slot each). */+ int32 NumHoleSlots() const { return LiveSlots; }+ /** Piece masks queued for a redraw since the start (a change redraws only the pieces it touched). */+ int32 NumMaskRedraws() const { return MaskRedraws; }+ /** Hole slots (decals) placed since the start (only holes that are new, or whose piece visual changed). */+ int32 NumSlotUpdates() const { return SlotUpdates; }+ int32 NumGlowing() const { return GlowingCount; }+ bool HasMask(uint16 PieceIndex) const { return MaskPieces.Contains(PieceIndex); }+ UTextureRenderTarget2D* GetMask(uint16 PieceIndex) const;++ UPROPERTY(EditAnywhere, Category = "Verse")+ TSoftObjectPtr<UMaterialInterface> RimDecalMaterial;++ UPROPERTY(EditAnywhere, Category = "Verse")+ FName MaskParameter = TEXT("HoleMask");++ UPROPERTY(EditAnywhere, Category = "Verse")+ FName GlowParameter = TEXT("RimGlow");++ UPROPERTY(EditAnywhere, Category = "Verse")+ FName GlowColorParameter = TEXT("RimGlowColor");++ UPROPERTY(EditAnywhere, Category = "Verse")+ int32 MaskSize = 256;++ UPROPERTY(EditAnywhere, Category = "Verse")+ int32 GlowingCap = 128;++ UPROPERTY(EditAnywhere, Category = "Verse")+ float GlowTauS = 1.2f;++ UPROPERTY(EditAnywhere, Category = "Verse")+ float GlowEndS = 4.f;++private:+ struct FPieceVisual+ {+ TWeakObjectPtr<UMeshComponent> Mesh;+ TWeakObjectPtr<USceneComponent> Frame;+ FBox LocalBounds = FBox(ForceInit);+ };++ /** Mirrors one slot of the hole component (same index); Sequence 0 = empty. */+ struct FHoleSlot+ {+ FVerseBoltHole Hole;+ uint32 Sequence = 0;+ TWeakObjectPtr<UDecalComponent> Decal;+ TWeakObjectPtr<UMaterialInstanceDynamic> Material;+ bool bGlowing = false;+ };++ TWeakObjectPtr<UVerseBoltHoleComponent> HoleSource;+ FDelegateHandle HolesChangedHandle;+ TFunction<uint32()> NowMs;+ TMap<uint16, FPieceVisual> Pieces;+ TSet<uint16> MaskPieces;+ TArray<FHoleSlot> HoleSlots;+ /** Pieces whose holes changed since the last sync; their masks are redrawn. */+ TSet<uint16> DirtyPieces;+ /** Pieces whose visual changed; their decals are placed again. */+ TSet<uint16> DirtyVisuals;+ int32 LiveSlots = 0;+ int32 GlowingCount = 0;+ int32 MaskRedraws = 0;+ int32 SlotUpdates = 0;+ bool bDirty = true;+ bool bAllDirty = true;+ bool bWarnedNoMaterial = false;++ UPROPERTY(Transient)+ TMap<uint16, TObjectPtr<UTextureRenderTarget2D>> Masks;++ UPROPERTY(Transient)+ TArray<TObjectPtr<UDecalComponent>> DecalPool;++ void HandleHolesChanged(TConstArrayView<uint16> InPieces, bool bAll);+ void MarkAllDirty();+ void RebuildSlots();+ void PlaceDecal(int32 Index, UMaterialInterface* RimMaterial);+ void RedrawMasks(const TSet<uint16>& PiecesToDraw);+ void UpdateGlow();+ UDecalComponent* AcquireDecal(int32 Index);+};diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationJson.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationJson.hnew file mode 100644index 0000000000..6a874ef4d0--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationJson.h@@ -0,0 +1,48 @@+#pragma once++#include "CoreMinimal.h"++// A minimal JSON reader for the penetration table and its golden fixture. VerseDestruction+// links only Core, CoreUObject, Engine and VerseCore (architecture.md 2), and the engine's Json+// module is not among them, so this reads the subset those files use: objects, arrays,+// strings (with the usual escapes), numbers, true, false and null.++struct VERSEDESTRUCTION_API FVerseJson+{+ enum class EType : uint8+ {+ Null,+ Bool,+ Number,+ String,+ Array,+ Object+ };++ EType Type = EType::Null;+ bool Bool = false;+ double Number = 0.0;+ FString String;+ TArray<FVerseJson> Array;+ /** Keys in file order. */+ TArray<TPair<FString, FVerseJson>> Object;++ /** Parses Text; false and an error with the character offset on malformed input or trailing text. */+ static bool Parse(const FString& Text, FVerseJson& Out, FString& OutError);++ bool IsObject() const { return Type == EType::Object; }+ bool IsArray() const { return Type == EType::Array; }++ /** Member of an object, nullptr when absent or not an object. */+ const FVerseJson* Find(const TCHAR* Key) const;++ bool TryNumber(const TCHAR* Key, double& Out) const;+ bool TryString(const TCHAR* Key, FString& Out) const;+ bool TryBool(const TCHAR* Key, bool& Out) const;+ /** The member as an array, nullptr when absent or not an array. */+ const TArray<FVerseJson>* FindArray(const TCHAR* Key) const;++ double NumberOr(const TCHAR* Key, double Default) const;+ FString StringOr(const TCHAR* Key, const FString& Default = FString()) const;+ bool BoolOr(const TCHAR* Key, bool Default) const;+};diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationMath.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationMath.hnew file mode 100644index 0000000000..93c0c5d42c--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationMath.h@@ -0,0 +1,45 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VersePenetrationTable.h"++// The pure arithmetic of destruction.md 2 and combat-state.md 6: one piece, one bolt.+// TraceBolt, the golden table test and the bot's wall-shot check all use these functions,+// so the formula exists exactly once.++/** What one piece does to a bolt that entered it. */+struct FVersePenetrationStep+{+ /** row.cost x clamp(traced / ref, 0.5, 3.0) */+ float Cost = 0.f;+ bool bPassed = false;+ /** Power after the piece; 0 when the piece stopped the bolt. */+ float PowerLeft = 0.f;+ /** Damage after the piece; 0 when the piece stopped the bolt. */+ float DamageLeft = 0.f;+};++namespace VersePenetration+{+ /** PieceIndex of a FVersePenetrationHit on non-destructible world geometry (no piece, no damage call). */+ inline constexpr uint16 NoPiece = 0xFFFF;++ /** The weapon's MaxPenetrations clamped to the contract limit of 3 (never raised). */+ VERSEDESTRUCTION_API int32 EffectiveMaxPieces(int32 WeaponMaxPieces);++ /**+ * One piece. bLimitReached: the bolt already passed its MaxPieces, so this piece stops it+ * whatever the power (destruction.md 2: the 4th piece stops it).+ */+ VERSEDESTRUCTION_API FVersePenetrationStep EvaluatePiece(const FVersePenetrationRow& Row, float TracedThicknessCm,+ float Power, float Damage, bool bLimitReached);++ /** True for the materials whose pieces keep bolt holes (destruction.md 5). */+ VERSEDESTRUCTION_API bool KeepsBoltHoles(EVersePenetrationMaterial Material);++ /** True for wall materials: hole 25 turns the piece Holed (destruction.md 5). */+ VERSEDESTRUCTION_API bool IsWallMaterial(EVersePenetrationMaterial Material);++ /** The frozen material ids of destruction.md 2 in wire order (`sheet_metal`, ...). */+ VERSEDESTRUCTION_API TConstArrayView<const TCHAR*> FrozenMaterialIds();+}diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationPhysicalMaterial.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationPhysicalMaterial.hnew file mode 100644index 0000000000..620933f6af--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationPhysicalMaterial.h@@ -0,0 +1,44 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++#include "VersePenetrationPhysicalMaterial.generated.h"++/** Roles of non-destructible world geometry (destruction.md 2: "through its physical material"). */+UENUM(BlueprintType)+enum class EVerseWorldSurface : uint8+{+ /** The hangar hall floor (DR4: never changes state, never passes). */+ HallFloor,+ /** Structural walls, columns, slabs. */+ StructuralWall,+ /** Structural beams and frames. */+ StructuralBeam+};++// WP03.7: non-destructible world geometry gets its row of DA_PenetrationTable through its+// physical material. The physical material is named for its surface role+// (`PM_Verse_HallFloor`, `PM_Verse_StructuralWall`, `PM_Verse_StructuralBeam`, optionally with a+// suffix such as `_Painted`); the zone owners assign those to their architecture. Hall floor and+// structural walls are `concrete`, structural beams `armor_steel`. Destructible pieces never+// use this: their row comes from the piece itself. Matching by name keeps VerseDestruction+// inside its module edges (architecture.md 2), which do not include PhysicsCore.++namespace VersePenetration+{+ /** The frozen mapping of world surfaces to table rows (destruction.md 2). */+ VERSEDESTRUCTION_API EVersePenetrationMaterial WorldSurfaceMaterial(EVerseWorldSurface Surface);++ /** `PM_Verse_<Role>`: the physical material name of a surface role. */+ VERSEDESTRUCTION_API FString PhysicalMaterialName(EVerseWorldSurface Surface);++ /** The surface role a physical material name stands for; false when it names none. */+ VERSEDESTRUCTION_API bool SurfaceFromPhysicalMaterialName(const FString& Name, EVerseWorldSurface& OutSurface);++ /**+ * Row for a hit on geometry that is not a registered piece: the row of its Verse physical+ * material, else `concrete`. Unmapped blocking geometry therefore never lets a bolt through.+ */+ VERSEDESTRUCTION_API EVersePenetrationMaterial ResolveWorldMaterial(const UObject* PhysicalMaterial);+}diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationSubsystem.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationSubsystem.hnew file mode 100644index 0000000000..7150550ca2--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationSubsystem.h@@ -0,0 +1,146 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionInterfaces.h"+#include "Engine/EngineTypes.h"+#include "Engine/HitResult.h"+#include "Subsystems/WorldSubsystem.h"++#include "VersePenetrationSubsystem.generated.h"++class UPhysicalMaterial;+class UPrimitiveComponent;+class USceneComponent;+class UVerseBoltHoleComponent;+class UVersePenetrationTable;+struct FHitResult;++/** A registered piece proxy: which piece and table row a collision component stands for. */+struct FVersePieceProxyInfo+{+ uint16 PieceIndex = 0;+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::Concrete;+ /** The frame hole records are stored in (piece-local, destruction.md 3.3). */+ TWeakObjectPtr<USceneComponent> Frame;+};++/** One stretch of solid along a ray inside one proxy: where the ray enters and leaves it. */+struct FVersePenetrationRun+{+ FVector Entry = FVector::ZeroVector;+ FVector Exit = FVector::ZeroVector;+};++using FVersePenetrationRuns = TArray<FVersePenetrationRun, TInlineAllocator<4>>;++/** What one query met on one component: its first hit and its solid runs, in ray order. */+struct FVersePenetrationCrossing+{+ const UPrimitiveComponent* Component = nullptr;+ /** Of the first hit: the body it hit and that hit's physical material. */+ FName BoneName;+ TWeakObjectPtr<UPhysicalMaterial> PhysMaterial;+ FVector Entry = FVector::ZeroVector;+ /** Exit of the last solid run. */+ FVector Exit = FVector::ZeroVector;+ /** Sum of the solid runs in cm: the traced thickness, air between shapes left out. */+ double SolidCm = 0.0;+ FVersePenetrationRuns Runs;+ /** More components lay behind this one than one query visits. */+ bool bTruncated = false;+};++/** The crossings of one query; a bolt rarely meets more than a few components. */+using FVersePenetrationCrossings = TArray<FVersePenetrationCrossing, TInlineAllocator<4>>;++/**+ * The penetration and sight queries of destruction.md 2 and 5 (WP03.3, WP03.4), one per world.+ *+ * TraceBolt walks the bolt segment on `VerseBolt` against the current proxies. One overlap-mode+ * multi trace lists every shape; the shapes of one component merge into one piece entry whose+ * traced thickness is the solid along the ray (one reverse component trace per solid run, so a+ * proxy of several convex shapes or a concave Holed proxy is charged once and air is free). It+ * looks up the row (registered pieces by their material, everything else through its physical+ * material, unmapped geometry as `concrete`) and applies the reference-thickness cost formula and+ * the 3-piece limit. A piece whose bolt holes contain the entry and exit point of every solid run+ * is flown through without cost and is not reported.+ *+ * TestSight walks `VerseSight`: intact glass (an overlap on that channel) and catwalk grating are+ * see-through, damaged glass and every other piece block unless the two-point hole test passes,+ * world geometry blocks. Server and bot use exactly this function; the client renders the same+ * hole records.+ *+ * The piece owner (WP06's destruction manager) registers each piece proxy, hands in its+ * IVersePieceQuery and the hole component. Without them every proxy is an anonymous world+ * surface and every piece answers Intact (the Core null stub).+ */+UCLASS()+class VERSEDESTRUCTION_API UVersePenetrationSubsystem : public UWorldSubsystem, public IVersePenetrationQuery+{+ GENERATED_BODY()++public:+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;+ virtual void Deinitialize() override;++ // IVersePenetrationQuery+ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power, float Damage,+ uint8 RadiusMm, int32 MaxPieces) const override;+ virtual bool TestSight(const FVector& Eye, const FVector& Target) const override;++ /** The table in use. Starts as the contract table, replaced by Data/destruction/penetration.json when it imports cleanly. */+ const UVersePenetrationTable* GetTable() const { return Table; }+ void SetTable(UVersePenetrationTable* InTable);++ /** Piece truth for the sight rules (glass state). Not owned; pass nullptr before the owner goes. */+ void SetPieceQuery(const IVersePieceQuery* InPieceQuery);++ /** The arena's bolt holes. Not owned. */+ void SetHoleSource(UVerseBoltHoleComponent* InHoles);+ UVerseBoltHoleComponent* GetHoleSource() const { return HoleSource.Get(); }++ void RegisterPieceProxy(UPrimitiveComponent* Proxy, uint16 PieceIndex, EVersePenetrationMaterial Material, USceneComponent* Frame = nullptr);+ void UnregisterPieceProxy(UPrimitiveComponent* Proxy);+ const FVersePieceProxyInfo* FindPieceProxy(const UPrimitiveComponent* Proxy) const;++ /** World to piece-local transform of a piece, from any of its registered proxies. */+ bool GetPieceFrame(uint16 PieceIndex, FTransform& OutPieceToWorld) const;++ /**+ * Server: records the holes a traced bolt leaves (destruction.md 5): one record per passed+ * piece that keeps holes, axis through the entry and exit midpoint along the bolt.+ * Returns how many records were added.+ */+ int32 RecordBoltHoles(TConstArrayView<FVersePenetrationHit> Hits, const FVector& Dir, uint8 RadiusMm, uint32 ServerTimeMs) const;++ /** Exit of the outermost solid of Component on a ray that entered at Entry, when no other shape entries are known. */+ static bool FindExit(const UPrimitiveComponent& Component, const FVector& Entry, const FVector& Dir, FVector& OutExit);++ /**+ * Solid runs of Component along Dir from Entry. LaterEntries are the entry points of the+ * component's other shapes on the same ray, ascending; a run ends where the point just in+ * front of the next entry is in air. Returns false when the last run found no exit.+ */+ static bool FindSolidRuns(const UPrimitiveComponent& Component, const FVector& Entry, const FVector& Dir,+ TConstArrayView<FVector> LaterEntries, FVersePenetrationRuns& OutRuns);++ /** The components on Start..End for Channel, one crossing each, in ray order (at most MaxSurfacesPerQuery). */+ void CollectCrossings(const FVector& Start, const FVector& End, ECollisionChannel Channel, FName StatName,+ FVersePenetrationCrossings& OutCrossings) const;++ /** Most components one query visits before it gives up (bolt or sight). */+ static constexpr int32 MaxSurfacesPerQuery = 16;++private:+ UPROPERTY(Transient)+ TObjectPtr<UVersePenetrationTable> Table;++ TWeakObjectPtr<UVerseBoltHoleComponent> HoleSource;+ const IVersePieceQuery* PieceQuery = nullptr;+ TMap<TObjectKey<UPrimitiveComponent>, FVersePieceProxyInfo> Proxies;+ TMap<uint16, TWeakObjectPtr<USceneComponent>> PieceFrames;++ EVersePieceState PieceState(uint16 PieceIndex) const;+ bool PassesHoles(const FVersePieceProxyInfo& Info, const FVector& EntryWorld, const FVector& ExitWorld) const;+ bool PassesHoles(const FVersePieceProxyInfo& Info, const FVersePenetrationCrossing& Crossing) const;+};diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableImport.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableImport.hnew file mode 100644index 0000000000..584015896a--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableImport.h@@ -0,0 +1,42 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VersePenetrationTable.h"+#include "UObject/SoftObjectPath.h"++// Importer from unreal/Verse/Data/destruction/penetration.json (schema verse.penetration/1,+// propose-only: it changes only through the destruction contract's change rule) into the rows+// of DA_PenetrationTable. The wire order is frozen: row i must carry wire i and the i-th id of+// destruction.md 2; new materials only append.++namespace VersePenetrationImport+{+ inline const TCHAR* const Schema = TEXT("verse.penetration/1");++ /** <ProjectDir>/Data/destruction/penetration.json */+ VERSEDESTRUCTION_API FString DefaultTablePath();++ /** DA_PenetrationTable, the cooked table the game loads (written from the JSON by the WP03.2 import step). */+ VERSEDESTRUCTION_API FSoftObjectPath TableAssetPath();++ /**+ * The table the game uses: the DA_PenetrationTable asset, which cooks and ships with every+ * build, dedicated servers included. Editor builds warn when the asset and the JSON disagree+ * (the import step was not re-run after a retune). Without the asset: the JSON when it is on+ * disk, else the contract table, and both fallbacks log.+ */+ VERSEDESTRUCTION_API UVersePenetrationTable* LoadRuntimeTable(UObject* Outer);++ /** Parses the JSON text. Returns false and fills OutErrors on any schema, value or wire order error. */+ VERSEDESTRUCTION_API bool ParseTableJson(const FString& JsonText, TArray<FVersePenetrationRow>& OutRows, TArray<FString>& OutErrors);++ /** The frozen wire order check alone: ids and wire numbers of the first 8 rows, nothing removed. */+ VERSEDESTRUCTION_API bool CheckWireOrder(TConstArrayView<FVersePenetrationRow> Rows, TArray<FString>& OutErrors);++ /** Reads and parses the file and replaces Table.Rows. Leaves the table untouched on failure. */+ VERSEDESTRUCTION_API bool ImportIntoTable(UVersePenetrationTable& Table, const FString& Path, TArray<FString>& OutErrors);++ /** Human-readable differences between two row sets (empty = equal within Tolerance). */+ VERSEDESTRUCTION_API TArray<FString> DiffRows(TConstArrayView<FVersePenetrationRow> A, TConstArrayView<FVersePenetrationRow> B,+ float Tolerance = 1e-6f);+}diff --git a/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableLibrary.h b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableLibrary.hnew file mode 100644index 0000000000..27854a21cc--- /dev/null+++ b/unreal/Verse/Source/VerseDestruction/Public/Penetration/VersePenetrationTableLibrary.h@@ -0,0 +1,41 @@+#pragma once++#include "CoreMinimal.h"+#include "Kismet/BlueprintFunctionLibrary.h"++#include "VersePenetrationTableLibrary.generated.h"++class AActor;+class UMaterialInterface;+class UStaticMesh;+class UVersePenetrationTable;+class UWorld;++/**+ * The WP03.2 import step, callable from editor Python (Content/Verse/Test/WP03/Python/wp03_content.py):+ * Data/destruction/penetration.json into the rows of the DA_PenetrationTable asset, with the+ * frozen wire order check. The game loads the asset (VersePenetrationImport::LoadRuntimeTable).+ */+UCLASS()+class VERSEDESTRUCTION_API UVersePenetrationTableLibrary : public UBlueprintFunctionLibrary+{+ GENERATED_BODY()++public:+ /** Reads Path (empty = Data/destruction/penetration.json) into Table. False leaves Table untouched; OutErrors says why. */+ UFUNCTION(BlueprintCallable, Category = "Verse|Penetration")+ static bool ImportPenetrationJson(UVersePenetrationTable* Table, const FString& Path, FString& OutErrors);++ /** Differences between Table and the JSON at Path (empty = the default), one per line; empty when they agree. */+ UFUNCTION(BlueprintCallable, Category = "Verse|Penetration")+ static FString DiffPenetrationJson(const UVersePenetrationTable* Table, const FString& Path);++ /**+ * WP03.8 fixture map step: a static mesh actor in World with Mesh (Material on every slot when+ * given), Transform, the collision Profile and Tags. Spawned directly in the world, so it works in the headless commandlet+ * (the editor actor subsystem places through a level viewport).+ */+ UFUNCTION(BlueprintCallable, Category = "Verse|Penetration")+ static AActor* SpawnFixturePiece(UWorld* World, UStaticMesh* Mesh, UMaterialInterface* Material, const FTransform& Transform, FName Profile, const TArray<FName>& Tags,+ const FString& Label);+};