Recover and verify static collision traversal and body contracts

This commit is contained in:
UnixNight committed 2026-10-26 21:45:57 -04:00
1 parent 7c0d1a4b0c
commit df0263b26e
34 files changed
+1962 -17

No files matched your search

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,103 @@
using System.Numerics;
using GamePort.Game;
using GamePort.Assets;
using System.Text.Json;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(Vector3 actual, Vector3 expected, string message)
{ Check(Vector3.Distance(actual, expected) < .002f, $"{message}: {actual} != {expected}"); }
var wall = new CameraRayPolygon(new(new(-100,-100,0),new(-100,100,0),new(100,100,0),0,0),Vector3.UnitZ);
var world = new OriginalStaticCollision([wall]);
(StaticCollisionMove Move, StaticCollisionContext Context) Run(OriginalStaticCollision scene, Vector3 before, Vector3 delta,
bool edges=true, bool lower=false)
{
var context = new StaticCollisionContext(10);
return (scene.Move(before, delta, 10, context, edges, lower), context);
}
// References are copied-original dispatcher47B4B0 results, not just the kernel.
var face=Run(world,new(0,20,20),new(0,0,-15));
Near(face.Move.Position,new(0,20,10),"source face retry");
Check(face.Context.Passes==2 && face.Context.TriangleTests==4 && face.Move.CallbackPolygon==wall,
"source retry count, duplicate visits and final callback");
Console.WriteLine("PASS original face retry/publication and per-cell duplicate visits");
var edge=Run(world,new(105,100,20),new(0,0,-15));
Near(edge.Move.Position,new(107.071068f,100,7.07106781f),"source edge retry");
Check(edge.Context.Passes==2 && edge.Context.TriangleTests==2,"original edge retry statistics");
var disabled=Run(world,new(105,100,20),new(0,0,-15),edges:false);
Near(disabled.Move.Position,new(105,100,5),"source disabled edge");
Check(disabled.Context.Passes==1 && disabled.Context.TriangleTests==1 && disabled.Move.CallbackPolygon==null,
"disabled edges still scan and publish");
Console.WriteLine("PASS original edge and edge-disabled dispatcher references");
var zero=Run(world,new(0,20,20),Vector3.Zero);
Check(zero.Context.Passes==0 && !zero.Move.Published,"zero delta early exit");
var forced=Run(world,new(0,20,20),Vector3.Zero,lower:true);
Check(forced.Context.Passes==1 && forced.Context.TriangleTests==2 && forced.Move.Published,"source member42C forced zero");
Console.WriteLine("PASS zero-motion and forced-processing source boundaries");
var side=new CameraRayPolygon(new(new(0,-100,-100),new(0,-100,100),new(0,100,100),1,0),Vector3.UnitX);
var corner=Run(new([wall,side]),new(20,20,20),new(-30,0,-30));
Near(corner.Move.Position,new(5,20,10.000001f),"source corner/edge-below rejection");
Check(corner.Context.Passes==2 && corner.Context.TriangleTests==8 && corner.Move.CallbackPolygon==wall,
"terminal normal belongs to last accepted polygon, not last tested polygon");
Console.WriteLine("PASS original corner order and retained last polygon");
var ceiling=new CameraRayPolygon(new(new(-100,100,-100),new(100,100,100),new(100,100,-100)), -Vector3.UnitY);
var under=Run(new([ceiling]),new(0,80,0),new(0,15,0));
Near(under.Move.Position,new(0,90,0),"source ceiling retry");
Check(under.Context.Passes==2 && under.Context.TriangleTests==8 && under.Move.CallbackPolygon==ceiling,
"source ceiling terminal callback");
Console.WriteLine("PASS original ceiling dispatch reference");
Check(OriginalStaticCollision.Bounds(Vector3.Zero,new(1000,0,1000),1010)==new CollisionCells(127,134,127,132),
"source asymmetric Z upper bound");
var masked=new OriginalStaticCollision([wall with { ShapeName="ncwall" },side with { MaterialName="cstart" }]);
Check(masked.PolygonCount==0 && masked.TraceSupport(new(0,20,20),new(0,20,-20))==null,"source registration masks");
Console.WriteLine("PASS asymmetric source bounds and registration exclusions");
var floor=new CameraRayPolygon(new(new(-100,0,-100),new(100,0,-100),new(0,0,100),3,0),Vector3.UnitY);
var supported=new OriginalStaticCollision([floor]);
Check(supported.WallPolygonCount==0 && supported.TraceSupport(new(0,100,0),new(0,-100,0))?.ShapeId==3,
"general support grid remains separate from wall registration");
Console.WriteLine("PASS separate general-grid nearest support query");
var retained = new StaticCollisionContext(10);
world.Move(new(0,20,20),new(0,0,-15),10,retained);
var retainedNearest = retained.Nearest;
var withoutGeometry = world.Move(new(0,20,10),new(0,0,-15),10,retained,geometryEnabled:false);
Near(withoutGeometry.Position,new(0,20,-5),"disabled geometry publishes unclipped candidate");
Check(withoutGeometry.CallbackPolygon==wall && retained.TriangleTests==4 && retained.Nearest==retainedNearest,
"disabled geometry preserves retained last-polygon callback without testing triangles");
Console.WriteLine("PASS disabled geometry and retained callback state");
Check(new OriginalStaticCollision([wall with {MaterialId=61}]).HasSpecialPlayerContacts,
"fence material archive ID must require special callback handling");
Check(!new OriginalStaticCollision([wall with {MaterialId=17}]).HasSpecialPlayerContacts
&& !new OriginalStaticCollision([ceiling with {MaterialId=61}]).HasSpecialPlayerContacts
&& !new OriginalStaticCollision([wall with {MaterialId=61,ShapeName="ncwall"}]).HasSpecialPlayerContacts,
"ordinary material, ceiling370 and excluded shapes cannot trigger player374 special handling");
var fixture = Path.Combine(Path.GetTempPath(), $"neutron-material-{Guid.NewGuid():N}.json");
try
{
var source = new { vertices=new[] {new[]{0,0,0},new[]{1,0,0},new[]{0,1,0}},indices=new[]{0,1,2},
collisionPolygons=new[]{new{shapeId=0,polygonIndex=0,normal=new[]{0,0,1},materialName="fence",materialId=61}} };
File.WriteAllText(fixture,JsonSerializer.Serialize(source));
var loaded=Mesh.LoadSceneJson(fixture);
Check(loaded.HasCollisionMaterialIds && OriginalStaticCollision.FromRouteScene(loaded,"LV1B").HasSpecialPlayerContacts,
"prepared material identity must survive loader and source grid construction");
File.WriteAllText(fixture,File.ReadAllText(fixture).Replace(",\"materialId\":61", ""));
loaded=Mesh.LoadSceneJson(fixture);
Check(!loaded.HasCollisionMaterialIds,"legacy metadata must remain distinguishable from unresolved material");
try { OriginalStaticCollision.FromRouteScene(loaded,"LV1B"); throw new Exception("legacy metadata silently accepted"); }
catch(InvalidDataException) { }
}
finally { File.Delete(fixture); }
Console.WriteLine("PASS material policy IDs and legacy prepared-data rejection");
foreach(var (level,directory,special) in new[]{("LV1B","level1b",true),("VR04","VR04",false),("LEV1","level1",true)})
{
var scene=Mesh.LoadSceneJson(Path.Combine("artifacts/extracted",directory,"scene.json"));
Check(OriginalStaticCollision.FromRouteScene(scene,level).HasSpecialPlayerContacts==special,
$"actual {level} special-contact coverage differs from original archive inventory");
}
Console.WriteLine("PASS prepared lab/tutorial/outside contact coverage");
var tiedFloor = floor with {Triangle=floor.Triangle with {ShapeId=4}};
var supportTies = new OriginalStaticCollision([tiedFloor,floor]);
Check(supportTies.TraceSupport(new(0,100,0),new(0,-100,0))?.ShapeId==3,
"equal-distance support retains original shape/cell/FIFO order");
Check(supportTies.TraceSupport(Vector3.Zero,Vector3.Zero)==null,
"zero-length support has no strictly nearer hit");
Console.WriteLine("PASS support nearest ties and zero-length limit");
Console.WriteLine("Static dispatcher:11 groups passed; source whole-body/scene integration remains separate.");
+21
View File
@@ -0,0 +1,21 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from body_step_evidence import collect
class BodyStepEvidenceTests(unittest.TestCase):
def test_guarded_source_bodies_and_explicit_relocations(self):
report = collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']), 15)
operands = report['probe_operands']
self.assertEqual(len({item['va'] for item in operands}), len(operands))
targets = {item['target'] for item in operands}
self.assertTrue({0x4f69e5, 0x5cfc7c, 0x695d54, 0x695d58}.issubset(targets))
if __name__ == '__main__':
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
"""Bounded contact/friction source signatures and state boundary fixtures."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from collision_contact_callbacks import (
collect, normal_callback, NORMAL_Y_THRESHOLD, ceiling_projection,
player_material_actions, jimmy_contact_actions, friction_projection, landing_phases,
)
class CollisionContactCallbacksTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_exact_source_identity_targets_and_complete_callbacks(self):
self.assertEqual(len(self.report['sites']), 50)
self.assertEqual(len(self.report['tables']), 20)
self.assertEqual(len(self.report['bodies']), 6)
self.assertFalse(any(b['raw_control_reference'] for b in self.report['bodies']))
targets = {(t['owner'], t['slot']): t['target'] for t in self.report['tables']}
self.assertEqual(targets['Jimmy', '0x374'], '0x42a660')
self.assertEqual(targets['Object', '0x374'], '0x458890')
self.assertEqual(targets['Jimmy', '0x37c'], '0x472970')
def test_ceiling_callback_dispatch_has_strict_threshold(self):
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD), 0x370)
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD-.00001), 0x370)
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD+.00001), 0x374)
def test_ceiling_changes_only_independently_positive_y(self):
self.assertEqual(ceiling_projection((1, 5, 3, 7), (4, -2, 6, 8)),
((1, 0, 3, 7), (4, -2, 6, 8)))
self.assertEqual(ceiling_projection((1, -5, 3, 7), (4, 2, 6, 8)),
((1, -5, 3, 7), (4, 0, 6, 8)))
self.assertEqual(ceiling_projection((1, 0, 3, 7), (4, 0, 6, 8)),
((1, 0, 3, 7), (4, 0, 6, 8)))
def test_ordinary_material_is_not_generic_velocity_projection(self):
for elapsed in (0, 3, 4):
self.assertEqual(player_material_actions(17, elapsed, 0), ())
self.assertEqual(player_material_actions(120, 3, 0), ())
self.assertEqual(player_material_actions(120, 3.01, 1), ('complete160',))
self.assertEqual(player_material_actions(119, 4, 1), ('complete164',))
self.assertEqual(player_material_actions(60, 4, 0), ('fence_query',))
self.assertEqual(player_material_actions(69, 4, 1), ())
self.assertEqual(player_material_actions(180, 4, 0), ('ladder_query',))
for material in (-1, 59, 70, 109, 130, 179, 181):
self.assertEqual(player_material_actions(material, 4, 0), ())
def test_friction_is_gated_by_support_published_speed_and_linear_motion(self):
velocity, angular = (10, -5, 20, 7), (2, -4, 6, 8)
self.assertEqual(friction_projection(velocity, angular, .8, .25),
((8, -5, 16, 7), (1.6, -3.2, 4.8, 8)))
for options in ({'support': False}, {'published_speed': 2}, {'published_speed': -2}):
self.assertEqual(friction_projection(velocity, angular, .8, .25, **options),
(velocity, angular))
# No planar motion still damps angular velocity when vertical motion exists.
self.assertEqual(friction_projection((0, 5, 0), (2, 4, 6), .8, .25),
((0, 5, 0), (1.6, 3.2, 4.8)))
self.assertEqual(friction_projection((0, 0, 0), angular, .8, .25),
((0, 0, 0), angular))
# The source multiplier is not clamped to prevent reversal.
self.assertEqual(friction_projection((10, 5, 20), (2, 4, 6), 2, 1),
((-10, 5, -20), (-2, -4, -6)))
def test_no_selection_and_jetpack_bypass_extra_gadget_effects(self):
for selected in (-1, 3):
for mode in (0, 1):
self.assertEqual(jimmy_contact_actions(selected, 17, 4, mode), ())
self.assertEqual(jimmy_contact_actions(selected, 17, 4, mode,
gadget7_active=True), ())
self.assertEqual(jimmy_contact_actions(7, 17, 4, 0), ())
self.assertEqual(jimmy_contact_actions(7, 17, 4, 0, gadget7_active=True),
('gadget7_unresolved',))
def test_material_discriminator_is_linked_chunk_id_and_route_has_specials(self):
identity = self.report['material_identity']
self.assertEqual(len(identity['dll_sites']), 11)
expected = {
'level1b.omt': {61: 20, 62: 24, 63: 4, 120: 4, 121: 20, 122: 3, 180: 6},
'VR04.omt': {},
'level1.omt': {60: 62, 61: 38, 62: 26, 180: 20},
}
for archive in identity['archives']:
# Every used material payload has the same trailing value; the
# distinct source callback policy comes from its linked chunk ID.
self.assertEqual({m['payload_trailing'] for m in archive['materials']}, {3})
counts = {}
for polygon in archive['special_polygons']:
if polygon['potential374_wall']:
mid = polygon['material_id']
counts[mid] = counts.get(mid, 0) + 1
self.assertEqual(counts, expected[archive['name']])
material = next(m for m in archive['materials'] if m['id'] == 0)
self.assertNotEqual(material['table_id_offset'], material['payload_offset'])
def test_landing_callback_observes_old_velocity_and_support(self):
phases = landing_phases(False)
self.assertEqual(phases, ['root318', 'acceleration278_Y0',
'landing37C_noop_for_Jimmy', 'velocity2C4_Y0',
'support21C_true', 'shape34C', 'polygon33C'])
self.assertNotIn('landing37C_noop_for_Jimmy', landing_phases(True))
if __name__ == '__main__':
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from collision_dispatch import collect
class DispatcherProbeTests(unittest.TestCase):
def test_source_callgraph_and_fixture_relocations(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),10)
operands=report['probe_operands']
self.assertEqual(len({p['va'] for p in operands}),len(operands))
self.assertTrue(any(p['target']==0x509B24 for p in operands))
self.assertTrue(any(p['target']==0x695D4C for p in operands))
if __name__=='__main__':unittest.main()
+79
View File
@@ -0,0 +1,79 @@
"""Static dispatcher source guards and independent ordering/state fixtures."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from collision_grid_traversal import (
EPSILON, NearestProjection, append_registration, cell, cells, collect,
scan_projection, traversal_bounds, visits,
)
class CollisionGridTraversalTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_source_retry_and_asymmetric_upper_bound_are_guarded(self):
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['z_upper_uses_min']['bytes'], '663bf8897c2418ddd87c0489442418')
self.assertEqual(sites['retry_flag_branch']['bytes'], '8a44241384c00f8597000000')
self.assertEqual(sites['retry_call_same_dispatcher']['file_offset'], '0x7b877')
self.assertEqual(sites['wrapper_stores_last_polygon_and_retry']['bytes'], '89354c5d6900c60101')
bodies = {b['name']: b for b in self.report['bodies']}
self.assertEqual(bodies['static_dispatcher']['length'], 0x3D9)
self.assertEqual(self.report['constants']['0x4d5e40'], EPSILON)
self.assertAlmostEqual(self.report['constants']['0x4a3148'], -.7, places=7)
def test_extent_and_z_upper_min_are_distinct_from_x_upper_max(self):
self.assertEqual(cell(0), 130)
self.assertEqual(cell(-65001), 0, 'Truncate toward zero before signed-short storage')
self.assertEqual(traversal_bounds((0,0,0), (0,0,500), 50, 500), (128,131,128,131))
self.assertEqual(traversal_bounds((0,0,0), (500,0,0), 50, 500), (128,132,128,131))
self.assertEqual(traversal_bounds((0,0,0), (0,0,-500), 50, 500), (128,131,127,130))
def test_inclusive_x_outer_z_inner_and_skipped_outside_cells(self):
self.assertEqual(cells((1,2,4,5)), [(1,4),(1,5),(2,4),(2,5)])
self.assertEqual(cells((-1,1,258,260)), [(0,258),(0,259),(1,258),(1,259)])
self.assertEqual(cells((2,1,0,1)), [])
def test_polygon_only_per_cell_dedup_and_fifo_across_cells(self):
grid = {}
self.assertTrue(append_registration(grid, (1,2), 100, 20))
self.assertFalse(append_registration(grid, (1,2), 100, 99))
self.assertTrue(append_registration(grid, (1,2), 200, 20))
self.assertTrue(append_registration(grid, (1,3), 100, 20))
self.assertEqual(visits(grid, (1,1,2,3)), [
((1,2),(100,20)), ((1,2),(200,20)), ((1,3),(100,20)),
])
def test_mutable_candidate_and_nearest_survive_duplicate_visits_and_retry(self):
grid = {(1,2): [(100,20),(200,20)], (1,3): [(100,20)]}
nearest = NearestProjection(130000, 10)
observed = []
def first_pass(xy, polygon, candidate, state):
observed.append((xy, polygon[0], candidate, state.face, state.last_polygon))
self.assertIs(state, nearest)
if len(observed) == 1:
state.face = 3
return (8,9,10), True
return candidate, False
candidate, retry = scan_projection(grid, (1,1,2,3), (0,0,0), nearest, first_pass)
self.assertTrue(retry)
self.assertEqual(candidate, (8,9,10))
self.assertEqual(observed[1][2:], ((8,9,10),3,100))
self.assertEqual(observed[2][1], 100, 'A repeated cell visit is retained')
candidate, retry = scan_projection(
grid, (1,1,2,3), candidate, nearest,
lambda xy, polygon, current, state: (current, False))
self.assertFalse(retry)
self.assertEqual((nearest.face, nearest.edge, nearest.last_polygon), (3,10,100))
self.assertEqual(candidate, (8,9,10))
if __name__ == '__main__':
unittest.main()
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
from types import SimpleNamespace
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/extractors'))
from omt import Entry, export_scene
class CollisionMaterialIdentityTests(unittest.TestCase):
def export(self, link, identity=61):
shape = dict(vertices=[(0, 0, 0), (1, 0, 0), (0, 1, 0)], normals=[],
polygons=[dict(corners=[dict(vertex=i, normal=0, uv=(0, 0)) for i in range(3)],
normal=(0, 0, 1), material=link)])
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
database = SimpleNamespace(path=root/'input'/'fixture.omt', data=b'fixture',
entries=[Entry('3DSh', 0, 0, 0, 'wall'), Entry('3DMa', identity, 0, 0, 'fence')],
payload=lambda entry: b'')
with patch('omt.read_shape', return_value=shape), patch('omt.read_material', return_value={}):
return export_scene(database, root/'output')['collisionPolygons'][0]
def test_archive_identity_is_preserved_independently_of_render_index(self):
polygon = self.export(dict(type='3DMa', id=61))
self.assertEqual((polygon['materialId'], polygon['materialName']), (61, 'fence'))
def test_null_missing_and_wrong_type_links_are_not_materials(self):
for link in (None, dict(type='3DMa', id=999), dict(type='3DSh', id=61)):
with self.subTest(link=link):
polygon = self.export(link)
self.assertIsNone(polygon['materialId'])
self.assertIsNone(polygon['materialName'])
def test_callback_identity_is_a_signed_long(self):
self.assertEqual(self.export(dict(type='3DMa', id=0xffffffff), 0xffffffff)['materialId'], -1)
if __name__ == '__main__':
unittest.main()