Preserve contact-owned roots and independent body modes

This commit is contained in:
UnixNight committed 2026-11-05 11:06:13 -05:00
1 parent 3845ea7114
commit c9d0c5be59
25 files changed
+16388 -74

No files matched your search

@@ -0,0 +1,7 @@
<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"/>
<None Include="../body-modes-reference.json" Link="body-modes-reference.json" CopyToOutputDirectory="PreserveNewest"/>
<None Include="../body-root-publication-reference.json" Link="body-root-publication-reference.json" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>
</Project>
@@ -0,0 +1,129 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Game;
using var modes=JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"body-modes-reference.json")));
int full=0,mutations=0;
foreach(var c in modes.RootElement.GetProperty("cases").EnumerateArray())
{
var p=c.GetProperty("input");var f=c.GetProperty("flags");var o=c.GetProperty("observed");
string name=c.GetProperty("name").GetString()!;int mutation=c.GetProperty("mutation").GetInt32();
bool geometry=f.GetProperty("geometry").GetBoolean();
var initial=new OrdinaryBodyState(V3(p,"position"),V3(p,"velocity"),V3(p,"acceleration"),V3(p,"impulse"),
p.GetProperty("supported").GetBoolean(),F(p,"published_speed"),V3(p,"angular"),V3(p,"rotation"),
V4(p,"position").W,V4(p,"previous"),V3(p,"anchor"),new(
f.GetProperty("integration").GetBoolean(),f.GetProperty("support").GetBoolean(),
f.GetProperty("collision").GetBoolean(),f.GetProperty("world_response").GetBoolean(),f.GetProperty("alternate").GetBoolean()));
bool worldMutation=mutation is >=1 and <=6;
//The native mode probe substitutes a linear dispatcher. For its six
//mutation cases, a real wall supplies our callback, so clipped XYZ is
//deliberately excluded while state and branch ownership are compared.
var polygons=new List<CameraRayPolygon>{Floor()};
if(worldMutation)polygons.Add(new(new(new(61,-1000,-1000),new(61,1000,-1000),new(61,0,1000),2),-Vector3.UnitX));
var physics=new OriginalBodyPhysics(new(polygons));int contacts=0,landings=0;
var result=physics.Step(initial,F(p,"seconds"),F(p,"radius"),F(p,"factor"),F(p,"friction"),F(p,"suppression_scale"),
geometryEnabled:geometry,wallContact:(body,_)=>
{
contacts++;
var flags=body.EffectiveModes;
if(mutation is 1 or 6)flags=flags with{Support=false};
if(mutation is 2 or 6)flags=flags with{WorldResponse=false};
if(mutation is 3 or 6)flags=flags with{Collision=false};
if(mutation is 4 or 6)flags=flags with{Integration=false};
if(mutation==5)geometry=false;
return body with{Modes=flags};
},landingContact:(body,_)=>
{
landings++;
return mutation switch
{
10=>body with{Modes=body.EffectiveModes with{Support=false}},
11=>body with{Modes=body.EffectiveModes with{Collision=false}},
12=>body with{PublishedSpeed=100},
13=>body with{Modes=body.EffectiveModes with{Integration=false}},
14=>body with{Velocity=new(7,123,9)},
15=>body with{Acceleration=new(7,123,9)},
16=>body with{Position=new(77,88,99),PositionW=2},
17=>body with{Impulse=new(7,123,9)},
18=>body with{SupportAnchor=new(7,123,9)},
19=>body with{AngularVelocity=new(7,123,9)},
20=>body with{Supported=false},
_=>body
};
},geometryState:()=>geometry);
var actual=result.Body;
if(!worldMutation){Near4(actual.Root,V4(o,"position"),name+" root");full++;}
else{Check(contacts==1&&result.CandidatePublished,name+" current world branch continues after mode mutation");mutations++;}
Near4(actual.PreviousRoot??initial.Root,V4(o,"previous"),name+" previous");
Near3(actual.Velocity,V3(o,"velocity"),name+" velocity");Near3(actual.Acceleration,V3(o,"acceleration"),name+" acceleration");
Near3(actual.Impulse,V3(o,"impulse"),name+" impulse");Near3(actual.AngularVelocity,V3(o,"angular"),name+" angular");
Near3(actual.Rotation,V3(o,"rotation"),name+" rotation");Near3(actual.SupportAnchor,V3(o,"anchor"),name+" anchor");
Near3(result.SupportAnchor,actual.SupportAnchor,name+" anchor diagnostic");
Near(actual.PublishedSpeed,F(o,"speed"),name+" speed");Check(actual.Supported==(F(o,"supported")!=0),name+" supported");
Check(landings==(int)F(o,"landings")&&result.Landing.HasValue==(landings!=0),name+" landing callbacks");
var final=o.GetProperty("final_flags").EnumerateArray().Select(x=>x.GetInt32()!=0).ToArray();var flagsAfter=actual.EffectiveModes;
Check(final.SequenceEqual(new[]{flagsAfter.Integration,flagsAfter.Support,flagsAfter.WorldResponse,flagsAfter.Collision,flagsAfter.HoldPosition,geometry}),name+" final flags");
}
Check(full==81&&mutations==6,"complete mode fixture coverage");
Console.WriteLine("PASS81 copied-original full numeric body mode/landing cases;6 callback-mode ownership cases compare state with explicit real-wall candidate difference");
using var roots=JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"body-root-publication-reference.json")));
int rootCases=0;
foreach(var c in roots.RootElement.GetProperty("cases").EnumerateArray())
{
var p=c.GetProperty("input").EnumerateArray().Select(x=>x.GetSingle()).ToArray();var o=c.GetProperty("observed");
string name=c.GetProperty("name").GetString()!;int kind=(int)p[0];bool support=p[3]!=0;
var wall=new CameraRayPolygon(new(new(-1000,-100000,0),new(-1000,100000,0),new(100000,0,0),2),Vector3.UnitZ);
var physics=new OriginalBodyPhysics(new([wall,Floor()]));
var entry=new Vector4(0,p[1],20,1);var previous=kind==11?new Vector4(999,999,999,3):entry;
//Native17 isolation cases no-op47B890; the managed support gate isolates
//the same publication outputs. The other2 cases execute real support.
var input=new OrdinaryBodyState(new(0,p[1],20),new(0,p[2],-900),Vector3.Zero,new(0,p[4]!=0?30:0,0),
PublishedSpeed:100,PreviousRoot:previous,Modes:BodyModes.Ordinary with{Support=support});
Vector4 seen=default,seenPrevious=default;Vector3 seenVelocity=default;int contacts=0;
var result=physics.Step(input,1f/60,radius:10,wallContact:(body,_)=>
{
contacts++;seen=body.Root;seenPrevious=body.PreviousRoot!.Value;seenVelocity=body.Velocity;
return kind switch
{
1=>body with{Position=body.Position+Vector3.UnitX*100},
2=>body with{PreviousRoot=body.PreviousRoot!.Value+new Vector4(100,0,0,0)},
3=>body with{PositionW=2},4=>body with{PreviousRoot=body.PreviousRoot!.Value with{W=2}},
5=>body with{Position=new(101,-30000,303)},
6=>body with{Position=new(101,250,303),PreviousRoot=new Vector4(101,250,303,1)},
7=>body with{PositionW=2,PreviousRoot=body.PreviousRoot!.Value with{W=2}},
8=>body with{Velocity=new(9,8,7),Acceleration=new(4,5,6),Impulse=new(0,77,0)},
9=>body with{Position=new(101,5,303)},
10=>body with{Position=body.Position+Vector3.UnitX*100,PreviousRoot=body.PreviousRoot!.Value+new Vector4(100,0,0,0),Velocity=new(9,8,7),Impulse=new(0,77,0)},
_=>body
};
});
Near4(result.Body.Root,V4(o,"live"),name+" live");Near4(result.Body.PreviousRoot!.Value,V4(o,"previous"),name+" previous");
Near3(result.Body.Velocity,V3(o,"velocity"),name+" velocity");Near3(result.Body.Acceleration,V3(o,"acceleration"),name+" acceleration");
Near3(result.Body.Impulse,V3(o,"impulse"),name+" impulse");Near4(seen,V4(o,"seen"),name+" callback sees live root");
Near4(seenPrevious,V4(o,"seenPrevious"),name+" callback sees entry previous");Near3(seenVelocity,V3(o,"seenVelocity"),name+" callback velocity");
var flags=o.GetProperty("flags").EnumerateArray().Select(x=>x.GetSingle()).ToArray();
Check(contacts==flags[0]&&result.CandidatePublished==(flags[1]!=0)&&result.Body.Supported==(flags[5]!=0)
&&result.Landing.HasValue==(flags[6]!=0),name+" publication/landing");rootCases++;
}
Check(rootCases==19,"complete native root fixture");
Console.WriteLine("PASS19 copied-original live/previous Vec4 publication cases, callback visibility, clamping and real support after root changes");
//A disabled world/body pass preserves the context needed by a later attached query.
var empty=new OriginalBodyPhysics(new([]));var state=new OrdinaryBodyState(new(0,100,0),Vector3.One,Vector3.Zero,Vector3.Zero);
var active=empty.Step(state,1f/60);var saved=empty.LastStaticContext;
foreach(var flags in new[]{BodyModes.Ordinary with{WorldResponse=false},BodyModes.Ordinary with{Collision=false},BodyModes.Ordinary with{Integration=false}})
{
var inactive=empty.Step(active.Body with{Modes=flags},1f/60);
Check(ReferenceEquals(saved,empty.LastStaticContext)&&inactive.CollisionPasses==0&&inactive.TriangleTests==0,"inactive path retains context without traversing stale geometry");
}
Console.WriteLine("PASS independent disabled gates preserve the prior static context");
static CameraRayPolygon Floor()=>new(new(new(-1000,0,-1000),new(1000,0,-1000),new(0,0,1000),1),Vector3.UnitY);
static float F(JsonElement e,string key)=>e.GetProperty(key).GetSingle();
static Vector3 V3(JsonElement e,string key){var a=e.GetProperty(key).EnumerateArray().Select(x=>x.GetSingle()).ToArray();return new(a[0],a[1],a[2]);}
static Vector4 V4(JsonElement e,string key){var a=e.GetProperty(key).EnumerateArray().Select(x=>x.GetSingle()).ToArray();return new(a[0],a[1],a[2],a[3]);}
static void Near(float a,float b,string name){if(!float.IsFinite(a)||MathF.Abs(a-b)>.004f)throw new Exception($"{name}: {a} != {b}");}
static void Near3(Vector3 a,Vector3 b,string name){Near(a.X,b.X,name+" X");Near(a.Y,b.Y,name+" Y");Near(a.Z,b.Z,name+" Z");}
static void Near4(Vector4 a,Vector4 b,string name){Near3(new(a.X,a.Y,a.Z),new(b.X,b.Y,b.Z),name);Near(a.W,b.W,name+" W");}
static void Check(bool value,string name){if(!value)throw new Exception(name);}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+78
View File
@@ -0,0 +1,78 @@
"""Original body mode/landing phase guards and retained native observations."""
from pathlib import Path
import hashlib,json,sys,tempfile,unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from body_modes import collect,generate
class BodyModeEvidence(unittest.TestCase):
def fixture(self):
return json.loads((ROOT/'tests/body-modes-reference.json').read_text())
def test_original_source_and_provenance(self):
fixture=self.fixture();source=collect(ROOT.parent/'Original')
for key in ('sha256','bodies','probe_operands','rea_evidence_id','flag_slots','scope'):
self.assertEqual(source[key],fixture['source'][key])
for row in source['bodies']:
self.assertEqual(int(row['file_offset'],16),int(row['va'],16)-0x400000)
for file,digest in fixture['files'].items():
self.assertEqual(len(digest),64)
if file.startswith('tools/'):
self.assertEqual(hashlib.sha256((ROOT/file).read_bytes()).hexdigest(),digest)
self.assertEqual(len(fixture['cases']),87)
def test_all_sixty_four_original_flag_combinations(self):
cases={c['name']:c for c in self.fixture()['cases']}
for bits in range(64):
c=cases[f'flags_{bits:02}'];f=c['flags'];o=c['observed'];calls=o['calls']
integrate=f['integration'];collision=f['collision'];world=f['world_response'];support=f['support'];geometry=f['geometry']
self.assertEqual(calls[0],int(integrate and collision and world))
self.assertEqual(calls[1],int(integrate and ((collision and not world) or (not collision and not f['alternate']))))
self.assertEqual(calls[2],int(integrate and collision))
self.assertEqual(calls[3],int(integrate and collision and world))
self.assertEqual(calls[4],1+int(integrate and collision))
self.assertEqual(calls[5],int(integrate and collision and (not support or not geometry)))
self.assertEqual(calls[6],int(integrate and collision and support and geometry))
self.assertEqual(calls[7],int(integrate));self.assertEqual(calls[8],int(integrate))
self.assertEqual(o['supported'],int(not support if not integrate else not geometry or not support))
reset=integrate and collision and world
self.assertEqual(o['context'],[0,130000,60,0] if reset else [0x11111111,1234,5678,0x22222222])
if not integrate:
self.assertEqual(o['impulse'],[0,20,0]);self.assertEqual(o['velocity'],[100,200,50])
self.assertEqual(o['events'],'GSFI' if support else 'GSI')
else:
self.assertLess(o['events'].index('R'),o['events'].index('Q'))
self.assertLess(o['events'].index('Q'),o['events'].index('C'))
def test_callback_mutation_and_suppression_observations(self):
cases={c['name']:c['observed'] for c in self.fixture()['cases']}
self.assertEqual(cases['world_mutation_1']['calls'][6],0)
self.assertEqual(cases['world_mutation_5']['acceleration'],[0,0,0])
self.assertLess(cases['world_mutation_5']['velocity'][1],-200)
for index in (2,3,4):
c=cases[f'world_mutation_{index}'];self.assertEqual(c['calls'][0],1);self.assertEqual(c['calls'][5],1)
for index in range(10,21):self.assertEqual(cases[f'landing_mutation_{index}']['landings'],1)
normal=cases['landing_mutation_10']
self.assertEqual(cases['landing_mutation_14']['velocity'],normal['velocity'])
self.assertEqual(cases['landing_mutation_15']['acceleration'],[7,123,9])
self.assertEqual(cases['landing_mutation_16']['position'],[77,88,99,2])
self.assertEqual(cases['landing_mutation_17']['impulse'],[7,123,9])
self.assertEqual(cases['landing_mutation_18']['anchor'],[7,123,9])
self.assertEqual(cases['landing_mutation_20']['supported'],1)
self.assertEqual(cases['landing_mutation_12']['calls'][5],0)
self.assertEqual(cases['landing_mutation_12']['speed'],100)
for name in ('world_off_below_floor','collision_off_below_floor'):
self.assertLess(cases[name]['position'][1],-25000)
for name in ('collision_off_linear_suppression','frozen_linear_suppression'):
self.assertEqual(cases[name]['velocity'],[0,0,0]);self.assertEqual(cases[name]['angular'],[0,0,0])
self.assertGreater(cases[name]['rotation'][1],0)
def test_generated_output_separation(self):
original=ROOT.parent/'Original'
for output in (original,original/'generated',ROOT.parent):
with self.assertRaises(ValueError):generate(original,output)
with tempfile.TemporaryDirectory() as directory:
output=Path(directory);(output/'body_modes_probe.c').symlink_to(original/'Neutron.exe')
with self.assertRaises(ValueError):generate(original,output)
if __name__=='__main__':unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Original body/contact Vec4 publication source and native observation guards."""
from pathlib import Path
import hashlib,json,sys,tempfile,unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from body_root_publication import collect,generate
class BodyRootPublicationEvidence(unittest.TestCase):
def fixture(self):
return json.loads((ROOT/'tests/body-root-publication-reference.json').read_text())
def test_original_identity_ranges_sites_and_offsets(self):
actual=collect(ROOT.parent/'Original');fixture=self.fixture()
for key in ('sha256','bodies','probe_operands','publication_sites','root_bindings','root_leaf_ranges','rea_evidence_id'):
self.assertEqual(actual[key],fixture[key])
self.assertEqual(len(actual['publication_sites']),12)
for row in actual['publication_sites']:
self.assertEqual(int(row['file_offset'],16),int(row['va'],16)-0x400000)
def test_nineteen_native_boundaries_and_callback_order(self):
fixture=self.fixture();self.assertEqual(len(fixture['cases']),19)
cases={c['name']:c for c in fixture['cases']}
for c in fixture['cases']:
o=c['observed'];self.assertEqual(o['seen'],[0,c['input'][1],20,1])
self.assertEqual(o['seenPrevious'],o['seen'])
self.assertEqual(o['flags'][0],1)
self.assertEqual(o['flags'][2],1)
self.assertTrue(o['events'].startswith('CRLP' if o['flags'][1] else 'CRLS'))
self.assertEqual(cases['live_w_down']['observed']['live'],[0,20,20,2])
self.assertEqual(cases['previous_w_down']['observed']['live'],[0,20,20,1])
self.assertEqual(cases['both_w_equal']['observed']['previous'][3],2)
self.assertEqual(cases['both_w_equal']['observed']['live'][3],1)
self.assertEqual(cases['both_xyz_equal']['observed']['live'],cases['unchanged_down']['observed']['live'])
self.assertEqual(cases['stale_previous_reset']['observed']['live'],cases['unchanged_down']['observed']['live'])
self.assertEqual(cases['below_clamp_unchanged']['observed']['live'][1],-25000)
self.assertEqual(cases['live_below_floor']['observed']['live'][1],-30000)
self.assertEqual(cases['below_clamp_live_x']['observed']['live'][1],-26000)
motion=cases['callback_motion']['observed']
self.assertEqual(motion['velocity'],[9,8,7,0]);self.assertEqual(motion['acceleration'],[4,5,6,0])
self.assertEqual(motion['impulse'],[0,77,0,0])
support=cases['support_after_live_change']['observed']
self.assertEqual(support['flags'][1],0);self.assertEqual(support['flags'][5:],[1,1])
self.assertAlmostEqual(support['live'][1],12.65,places=5)
self.assertEqual(support['velocity'][1],0)
def test_probe_provenance(self):
for name,digest in self.fixture()['files'].items():
self.assertEqual(len(digest),64)
if name.startswith('tools/'):
self.assertEqual(hashlib.sha256((ROOT/name).read_bytes()).hexdigest(),digest)
def test_output_isolation_and_symlink_rejection(self):
original=ROOT.parent/'Original'
for target in (original,original/'generated',ROOT.parent):
with self.assertRaises(ValueError):generate(original,target)
with tempfile.TemporaryDirectory() as directory:
target=Path(directory);(target/'body_root_publication_probe.c').symlink_to(original/'Neutron.exe')
with self.assertRaises(ValueError):generate(original,target)
if __name__=='__main__':unittest.main()