diff --git a/AGENTS.md b/AGENTS.md index bafbfd3..82c81f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,12 @@ The broader priority remains Jimmy movement stabilization, with gadgets paused. JN-Engine native/Godot movement. Use its original decompiler index only as leads, verified with REA/authoritative originals. See docs/gameplay/jimmy-movement-stabilization.md. +Pair continuation: docs/checkpoint/pair-lifecycle.md records28 complete original/ +C# cases and20 VR04 class bindings. OriginalPairCollision is a bounded component, +not live scene admission. Next recover full physical registration/activation and +helpers, real actor responses and shared dynamic reclip before replacing existing +collision. Gated pairs retain contacts; sphere exclusions use the earlier actor. + 2026-11-06 continuation: the earlier292 original component cases plus50 derived- caller cases and body/visual-sync audit supply no extra reset. Startup diagnostics now observe backgroundLevel1D/Jimmy allocation after an explicit OS repaint diff --git a/docs/architecture.md b/docs/architecture.md index 1c520de..b0ba938 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -93,6 +93,12 @@ composes that static path for ordinary Jimmy flags/contacts and is used in VR04; the live bridge supplies zero angular velocity, variable source radius60/100 and separate published160 speed. Lab/outside retain the capsule. Special callbacks, other original actor pair eligibility and shared dynamic reclipping remain gated. +`OriginalPairCollision` now expresses47A430's ordered physical-list pass and +47B3E0's sphere/exclusion query. It takes live actor callbacks and an explicit +mode2 solver, and preserves contacts when eligibility skips a pair.28 complete +original-component comparisons support it. It is not connected to the grouped +SceneInteractions loop: full registration/activation, real actor responses and +shared dynamic reclip state remain prerequisites. See checkpoint/pair-lifecycle.md. Source root and modern feet/sole rendering are distinct adapters; F3 exit still uses modern capsule occupancy. See checkpoint/collision-body-implementation.md. The source-root upward ray is supplied separately from the camera debug query: diff --git a/docs/checkpoint/coverage.md b/docs/checkpoint/coverage.md index 0c43d73..20b630e 100644 --- a/docs/checkpoint/coverage.md +++ b/docs/checkpoint/coverage.md @@ -61,13 +61,19 @@ payload ordering.100 new complete original comparisons and six callback-state comparisons pass. Special callback mechanics, actor mode persistence and scene-wide dynamic/shared context remain separate gates; lab/outside capsule is preserved. +[Ordered pair lifecycle](pair-lifecycle.md) adds28 complete original/C# component +comparisons: physical-list pair order, one-sided sphere exclusions, gate retention, +callback-mutated roots/membership and enter/stay/leave. The component has explicit +mode2 injection and is not admitted to live scenes. VR04's6 inspected actor records +and20 bindings do not yet constitute the full physical/helper registration list. + | ID / system | Recovered contract / anchors | Port implementation | Evidence / remaining gap | Next bounded action | |---|---|---|---|---| | LOOP | Viewport47E4F0 physics before registry473740, including input44DF80; second sync473770; construction order and selective retained-character/new-game ordering. Separate engine morph clock. | Player now integrates prior body state, then fresh input/player/fire or retained player/fire/input. Uncontrolled body/fire now continue while movement/input are gated. Other systems remain grouped; fixed60Hz policy. | S/M/R. Controlled player partial order implemented; bounded raw-owner preparation implemented; full wrapper/registry/cadence open. | C3 continue other callbacks and morph/control phases; C4 support/response remains separate. | | INPUT | Game interface+8C slot3C4→44DF80→475A70 reads controlled5099E4 and calls3CC; Jimmy interface+C0→426030. | SDL arrows/jump aliases; control gate, modern debug override; mouse/controller incomplete. | S/M/R, user Windows route. Input occurs in object traversal after physics; device sampling/focus and latency open. | Trace event pump, key/mouse and focus gates alongside retained registry order. | | MOVE |437940/439900 ground/air;479D20 impulse→acceleration→gravity; authored114→26C body speed separate from controller608. | Body/fire continue without control; input/controller gated. VR04 uses ordinary source static body and variable radius; lab/outside capsule retained. Fresh/retained order and overhead wrapper explicit. | S/P/M/R. Source body references/phase checks and native VR04 flight pass; complete registry/base/transform/cadence open. | Continue dynamic/special C4 contracts and C3 base transforms; preserve published speed ownership across preparation/Init. | | JET |437F90 controller;421FB0 effect; fresh constructor order places fire after Jimmy, both after global physics. States0..5, hold>.4,8s, energy. | Explicit state table with post-collision effect ticking and VR immunity. | S/M/R. Fresh same-pass countdown recovered; retained child lifecycle, sound and expiry→animation open. | Trace retained Jimmy/fire resets and phase end events before scheduler integration. | -| COLL |479D20/47BD80 body;47B4B0 FIFO grid/retries;370/374/37C; signed material IDs; separate160 friction; radius60/100 and support/suppression. | VR04 uses ordinary source static body/support/friction; lab/outside keep24-unit capsule. Root+150 wrapper live for route. Dynamic response remains provisional. | S/P/M/R. Ten original kernel, seven dispatcher, ten body references matched in managed composition;20 body groups and native/headless VR04 replay. Special/dynamic classes and visual transform open. | C4: recover original actor physical/pair eligibility and shared dynamic context; lab/outside need160/164/FENCE/LADDER before solver expansion. | +| COLL |479D20/47BD80 body;47B4B0 FIFO grid/retries;370/374/37C; signed materials/friction; radius60/100;47A430 ordered pairs/47CA90 one-sided sphere exclusions. | VR04 uses ordinary source static body; lab/outside keep24-unit capsule.28-case pair component remains separate; live dynamic response provisional. | S/P/M/R. Prior kernel/dispatcher/body comparisons and native VR04 pass;28 complete pair observations now match. Real actor callbacks, full physical list and shared reclip remain open. | C4: complete VR04 physical registration/activation/helpers, then shared dynamic context; lab/outside need160/164/FENCE/LADDER before solver expansion. | | ANIM | Engine morph10002DB0; linear interpolation10002F9A; game logical→OMT sync4624B0. | ASE sample timing, unconditional loop closure, pose/action aliases,1/60 advance. | S/P/M/R. Playback flags, rate, completion callbacks, transition order open. | Recover one-shot/loop/end notifications before more aliases. | | SCRIPT | Source AI/CAM/MCA dispatch and chains; task45F990 objective406F50 BEFORE records BEFORE per-entity424. | Pre-assignment objective selection and per-actor Carl override implemented; bounded synchronous director. | S/M/R. Script callbacks recovered for route; generic class coverage and reentrancy incomplete. | Continue other class-specific callbacks and reentrancy under the recovered owner/phase boundaries. | | CONTROL | Global5099E4 null during valid CAM/MCA; PlayerControlled completion target; DEFAULT447D..447F restores camera/UI/music. | Director raw ownership plus explicit debug effective override; eligible player body/fire continue; only input/controller tail is gated. | S/M/R. Raw/effective control and ordered preparation are implemented; full base/class wrappers and scheduler remain incomplete. | Continue full wrapper/base and collision contact phases around deferred LOAD. | diff --git a/docs/checkpoint/next-work-plan.md b/docs/checkpoint/next-work-plan.md index 9c2d6ed..6e148a3 100644 --- a/docs/checkpoint/next-work-plan.md +++ b/docs/checkpoint/next-work-plan.md @@ -23,6 +23,11 @@ Windows comparison remains a step5 obligation, not a completed claim. Step4's derived-caller/body-transform investigation is also recorded, with broader dynamic/special contacts and playback dependencies still open. +Step4 continuation: [ordered pair lifecycle](pair-lifecycle.md) now has28 complete +original/C# comparisons,6 new REA pseudocode results and20 guarded VR04 class +bindings. The pair component is verified separately; scene admission remains +gated on full physical registration/activation, real callbacks and shared reclip. + ## Objective Establish the original ownership and timing of player state across gameplay, diff --git a/docs/checkpoint/pair-lifecycle.md b/docs/checkpoint/pair-lifecycle.md new file mode 100644 index 0000000..3965a37 --- /dev/null +++ b/docs/checkpoint/pair-lifecycle.md @@ -0,0 +1,153 @@ +# Physical pair ordering and contact lifecycle + +2026-11-06. Continues step4 of the movement plan after the Carl story-entry fix. +This closes a bounded pair-dispatch contract. It does not admit new live scene +physics, implement special Jimmy terrain callbacks or establish whole-game fidelity. + +## Recovered source and structures + +Canonical Neutron.exe SHA256: +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +`tools/binary/pair_lifecycle.py` guards8 complete source ranges and20 virtual +bindings, records PE file offsets and retains the matching original instruction +Evidence `ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904`. +The generated probe relocates11 explicit absolute operands in private memory. +The supplied originals are read only; the executable entry point is not invoked. + +New local REA/Ghidra pseudocode Evidence: + +| Original VA / file offset | Role | Evidence ID suffix (all prefixed `ev_`) | +|---|---|---| +|479BC0 /79BC0|Physics scheduler; nonzero seconds, body pass then pair pass|56b7e074ec8509d1c5b3576d02361ff051963b777d7ccb8259ed9c65dc2db52f| +|47A430 /7A430|Ordered pair eligibility and notifications|8756a4c51d0c9215d3a36b86b673a2529bf74ed86bb9dcf630f66cbc398259b3| +|47B3E0 /7B3E0|Strict root-sphere overlap and callbacks|b98a1806c11507d5105d6fb22e259efafd141fe3c862eb4bb6602468a93a658d| +|47CA90 /7CA90|Earlier body's exclusion list|3f2613369c1259cba7aadfc00b7383dbf7bd37def7085f003daf81802dddbc4e| +|470B20 /70B20|Base leave, optional wake, contact removal|ae39adff84ac253cd370a2fd3f04ee7e9c00a6a6210d4f0222e938103a114d72| +|470BC0 /70BC0|Base stay/game callback cache|c3f377c29e0818cb43ed7bcc58d4db3871ab34d1b54c329421591438b79f0d00| + +Complete replies/export and closed snapshot: `artifacts/pair-lifecycle/rea/`. +Ghidra did not recognize470A60/470BF0 as requested procedures; error replies are +retained. Its47B3E0 pseudocode misidentifies the first argument as a return-address +value. Calling convention, stack arguments and the omitted leaf bodies therefore +use guarded instructions plus actual copied-code execution, not that pseudocode. +No repeated query is presented as successful decompilation of those two leaves. + +The physical list at695D3C is a circular sentinel list of12-byte nodes: +next+0, previous+4, game-interface pointer+8. This differs from the ordinary update +registry50999C. Re-registration and repeated Init are documented separately in +[body registration](body-root-registration.md). +Each actor owns contact-list sentinel pointer+260/count+264 and exclusion-list +sentinel pointer+254. These are interface-relative fields, not radius slot260. +Base contact game-callback result caches are+408 enter,+40C stay,+410 leave. + +## State transitions and ordering + +- Viewport47E554 calls479BC0 before ordinary registry updates. Nonzero delta and + global4F69E7 admit body integration479D20 followed by47A430. Pair global4F69E4 + gates the latter independently; raw control5099E4 is not queried here. +- 47A430 traverses each earlier physical node against itself and subsequent nodes. + Identical actor pointers are skipped, with no reverse pair traversal. A duplicate + physical node can cause another test of the same actor pair; it is not deduplicated. +- Own220 is sampled once at the outer boundary; each inner actor's220 is read + again. Mutual3A0 permissions follow. Rejected flags/permissions skip the pair + **without removing stored contacts or emitting leave**. An outer actor disabled + by its first enter callback can still contact later actors in that traversal. +- First actor mode178=2 selects47A5E0(first,second); otherwise second mode2 + selects47A5E0(second,first). Both mode2 preserves first-first selection. Other + modes use47B3E0(first,second). Box geometry is a distinct contract. +- Sphere query reads second root, first root, both radii and quick_magnitude. + Contact requires strict distanceLive callbacks of an original physical-list member, not render visibility or raw control. +public interface IOriginalPairBody +{ + bool PairCollisionEnabled { get; } + int CollisionMode { get; } + Vector3 Root { get; } + float Radius { get; } + bool AllowsPair(IOriginalPairBody other); + bool Excludes(IOriginalPairBody other); + bool HasContact(IOriginalPairBody other); + void SphereOverlap(IOriginalPairBody other, float distance); + void Enter(IOriginalPairBody other); + void Stay(IOriginalPairBody other); + void Leave(IOriginalPairBody other); +} + +/// +/// EXE47A430/47B3E0/47CA90 ordered pair and notification contract. The caller +/// supplies physical registration order and real actor callbacks. Mode2 geometry +/// remains a separate injected solver. Not yet admitted to the live scene loop. +/// +public static class OriginalPairCollision +{ + /// + /// This bounded component requires a stable list during the pass. Source + /// linked-list insertion/deletion during callbacks is not reconstructed here. + /// Eligibility gates retain existing contacts; they do not synthesize leaves. + /// + public static void Step(IReadOnlyList bodies, + Func? boxContact = null, bool enabled = true) + { + ArgumentNullException.ThrowIfNull(bodies); + if (!enabled) return; + for (var i = 0; i < bodies.Count; i++) + { + var first = bodies[i]; + //47A46E: sampled once for this outer traversal, before its callbacks. + if (!first.PairCollisionEnabled) continue; + for (var j = i; j < bodies.Count; j++) + { + var second = bodies[j]; + if (!second.PairCollisionEnabled || ReferenceEquals(first, second) + || !first.AllowsPair(second) || !second.AllowsPair(first)) continue; + bool contact; + if (first.CollisionMode == 2) contact = Box(first, second); + else if (second.CollisionMode == 2) contact = Box(second, first); + else contact = SphereContact(first, second); + + Notify(first, second, contact); + //The first callback can alter the second actor's membership. + Notify(second, first, contact); + } + } + + bool Box(IOriginalPairBody box, IOriginalPairBody other) => + (boxContact ?? throw new InvalidOperationException("Mode2 requires an explicit source box solver"))(box, other); + } + + public static bool SphereContact(IOriginalPairBody first, IOriginalPairBody second) + { + //Source queries second root first, then first root and both radii. + var secondRoot = second.Root; + var firstRoot = first.Root; + var firstRadius = first.Radius; + var radius = second.Radius + firstRadius; + var distance = OriginalBodySupport.QuickMagnitude(secondRoot - firstRoot); + //47CA90 checks only the earlier body's exclusions, after strict overlap. + if (!(distance < radius) || first.Excludes(second)) return false; + first.SphereOverlap(second, distance); + second.SphereOverlap(first, distance); + return true; + } + + private static void Notify(IOriginalPairBody self, IOriginalPairBody other, bool contact) + { + if (!contact) + { + if (self.HasContact(other)) self.Leave(other); + } + else if (self.HasContact(other)) self.Stay(other); + else self.Enter(other); + } +} diff --git a/tests/GamePort.PairLifecycleTests/GamePort.PairLifecycleTests.csproj b/tests/GamePort.PairLifecycleTests/GamePort.PairLifecycleTests.csproj new file mode 100644 index 0000000..e1fd427 --- /dev/null +++ b/tests/GamePort.PairLifecycleTests/GamePort.PairLifecycleTests.csproj @@ -0,0 +1,12 @@ + + + Exenet10.0 + enableenable + false + + + + + + + diff --git a/tests/GamePort.PairLifecycleTests/Program.cs b/tests/GamePort.PairLifecycleTests/Program.cs new file mode 100644 index 0000000..10ff6bf --- /dev/null +++ b/tests/GamePort.PairLifecycleTests/Program.cs @@ -0,0 +1,190 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Game; + +var fixture = new Fixture(); +var rows = new List(); +void Tick(string name) => rows.Add(fixture.Tick(name)); +fixture.Reset(0,1);Tick("enter");Tick("stay");fixture.Actors[1].Position.X=20;Tick("tangent_leave"); +fixture.Actors[0].Integration=false;fixture.Actors[0].Authored=true;fixture.Actors[1].Position.X=19;Tick("reenter_sleeping"); +fixture.Actors[1].Position.X=21;Tick("leave_wakes_authored"); +fixture.Reset(0,1);fixture.Actors[0].Exclusions.Add(fixture.Actors[1]);Tick("earlier_excludes"); +fixture.Reset(0,1);fixture.Actors[1].Exclusions.Add(fixture.Actors[0]);Tick("later_excludes"); +fixture.Order(1,0);Tick("reordered_exclusion_leaves"); +fixture.Reset(0,1);Tick("before_disable");fixture.Actors[1].Enabled=false;Tick("disabled_retains_contact"); +fixture.Actors[1].Enabled=true;fixture.Actors[0].Allowed=false;Tick("permission_retains_contact"); +fixture.Actors[0].Allowed=true;fixture.Enabled=false;Tick("global_off_retains_contact"); +fixture.Reset(0,1);fixture.Actors[1].Allowed=false;Tick("later_permission_rejects"); +fixture.Reset(0,1);fixture.Actors[1].Position.X=19.999f;Tick("inside"); +fixture.Reset(0,1);fixture.Actors[1].Position.X=20.001f;Tick("outside"); +fixture.Reset(0,1,2);Tick("three_actor_order"); +fixture.Reset(0,1,2);fixture.Mutation=1;Tick("response_moves_root"); +fixture.Reset(0,1,2);fixture.Mutation=2;Tick("enter_disables_outer"); +fixture.Reset(0,1,2);fixture.Mutation=3;Tick("enter_disables_later"); +fixture.Reset(0,1);fixture.Mutation=4;Tick("enter_changes_counterpart_membership"); +fixture.Reset(0,0,1);Tick("duplicate_body_identity"); +fixture.Reset(0,1);fixture.Actors[1].Inhibit=true;Tick("other_inhibits_response"); +fixture.Reset(0,1);fixture.Actors[0].Integration=false;Tick("sleeping_still_contacts"); +fixture.Reset(0,1);fixture.Actors[0].Mode=2;Tick("box_first"); +fixture.Reset(0,1);fixture.Actors[1].Mode=2;Tick("box_second"); +fixture.Reset(0,1);fixture.Actors[0].Mode=fixture.Actors[1].Mode=2;Tick("both_box_keep_order"); +fixture.BoxHit=false;Tick("box_separation"); +fixture.Reset(0);Tick("single_actor"); + +if (args.Length == 2 && args[0] == "--native") +{ + using var original=JsonDocument.Parse(File.ReadAllText(args[1])); + var references=original.RootElement.GetProperty("cases").EnumerateArray().ToArray(); + if(references.Length!=rows.Count)throw new Exception("Original case count"); + for(var i=0;iv.GetInt32())),row.Name+" "+field); + Check(row.RootX.SequenceEqual(expected.GetProperty("rootX").EnumerateArray().Select(v=>v.GetSingle())),row.Name+" roots"); + } + Console.WriteLine($"Matched {rows.Count} complete original pair observations."); +} +else if(args.Length!=0)throw new ArgumentException("Use --native "); + +//Fixed reference expectations are checked even when generated traces are absent. +var events = new Dictionary +{ + ["enter"]="R01;P01;R10;P10;E01;E10;", + ["stay"]="R01;P01;R10;P10;S01;S10;", + ["tangent_leave"]="L01;L10;", + ["reenter_sleeping"]="R01;R10;P10;E01;E10;", + ["leave_wakes_authored"]="L01;L10;", + ["earlier_excludes"]="", + ["later_excludes"]="R01;P01;R10;P10;E01;E10;", + ["reordered_exclusion_leaves"]="L10;L01;", + ["before_disable"]="R01;P01;R10;P10;E01;E10;", + ["disabled_retains_contact"]="", + ["permission_retains_contact"]="", + ["global_off_retains_contact"]="", + ["later_permission_rejects"]="", + ["inside"]="R01;P01;R10;P10;E01;E10;", + ["outside"]="", + ["three_actor_order"]="R01;P01;R10;P10;E01;E10;R02;P02;R20;P20;E02;E20;R12;P12;R21;P21;E12;E21;", + ["response_moves_root"]="R01;P01;R10;P10;E01;E10;R12;P12;R21;P21;E12;E21;", + ["enter_disables_outer"]="R01;P01;R10;P10;E01;E10;R02;P02;R20;P20;E02;E20;R12;P12;R21;P21;E12;E21;", + ["enter_disables_later"]="R01;P01;R10;P10;E01;E10;", + ["enter_changes_counterpart_membership"]="R01;P01;R10;P10;E01;S10;", + ["duplicate_body_identity"]="R01;P01;R10;P10;E01;E10;R01;P01;R10;P10;S01;S10;", + ["other_inhibits_response"]="R01;R10;P10;E01;E10;", + ["sleeping_still_contacts"]="R01;R10;P10;E01;E10;", + ["box_first"]="B01;E01;E10;", + ["box_second"]="B10;E01;E10;", + ["both_box_keep_order"]="B01;E01;E10;", + ["box_separation"]="B01;L01;L10;", + ["single_actor"]="", +}; +foreach(var row in rows) +{ + if(events.TryGetValue(row.Name,out var expected))Check(row.Events==expected,row.Name+" reference order"); + else throw new Exception("Missing saved reference: "+row.Name); + //Complete finite state observations, retained independently of the local capture. + int[] contacts=row.Name switch + { + "three_actor_order" or "enter_disables_outer"=>[6,5,3], + "response_moves_root"=>[2,5,2], + "tangent_leave" or "leave_wakes_authored" or "earlier_excludes" or + "reordered_exclusion_leaves" or "later_permission_rejects" or "outside" or + "box_separation" or "single_actor"=>[0,0,0], + _=>[2,1,0] + }; + int[] integration=row.Name is "reenter_sleeping" or "sleeping_still_contacts" ? [0,1,1] : [1,1,1]; + int[] enabled=row.Name switch + { + "disabled_retains_contact"=>[1,0,1],"enter_disables_outer"=>[0,1,1], + "enter_disables_later"=>[1,1,0],_=>[1,1,1] + }; + float[] roots=row.Name switch + { + "tangent_leave"=>[0,20,0],"reenter_sleeping"=>[0,19,0],"leave_wakes_authored"=>[0,21,0], + "inside"=>[0,19.999f,0],"outside"=>[0,20.001f,0],"response_moves_root"=>[1000,0,0],_=>[0,0,0] + }; + Check(row.Contacts.SequenceEqual(contacts)&&row.Integration.SequenceEqual(integration) + &&row.Enabled.SequenceEqual(enabled)&&row.RootX.SequenceEqual(roots),row.Name+" complete saved state"); +} +Check(rows.Single(r=>r.Name=="disabled_retains_contact").Contacts.SequenceEqual(new[]{2,1,0}),"disabled contact retention"); +Check(rows.Single(r=>r.Name=="global_off_retains_contact").Contacts.SequenceEqual(new[]{2,1,0}),"global contact retention"); +Check(rows.Single(r=>r.Name=="leave_wakes_authored").Integration[0]==1,"leave wakes authored integration"); +Check(rows.Single(r=>r.Name=="response_moves_root").RootX[0]==1000,"response publishes live root before next pair"); +fixture.Reset(0,1);fixture.Actors[0].Mode=2; +try {OriginalPairCollision.Step(fixture.Bodies);throw new Exception("Missing box solver accepted");} +catch(InvalidOperationException) { } +Console.WriteLine("PASS:28 pair lifecycle cases, retained contacts, callback mutations and explicit box admission."); +static void Check(bool condition,string message){if(!condition)throw new Exception(message);} + +sealed record Observation(string Name,string Events,int[] Contacts,int[] Integration,int[] Enabled,float[] RootX); +sealed class Fixture +{ + public Actor[] Actors {get;} + public IOriginalPairBody[] Bodies {get;private set;}=[]; + public string Events=""; + public int Mutation; + public bool Enabled=true,BoxHit=true; + public Fixture()=>Actors=Enumerable.Range(0,3).Select(i=>new Actor(this,i)).ToArray(); + public void Reset(params int[] order) + { + foreach(var actor in Actors)actor.Reset(); + Mutation=0;Enabled=BoxHit=true;Order(order); + } + public void Order(params int[] order)=>Bodies=order.Select(i=>(IOriginalPairBody)Actors[i]).ToArray(); + public Observation Tick(string name) + { + Events=""; + OriginalPairCollision.Step(Bodies,(a,b)=>{Log('B',(Actor)a,(Actor)b);return BoxHit;},Enabled); + return new(name,Events,Actors.Select(a=>a.Contacts.Aggregate(0,(mask,b)=>mask|1<a.Integration?1:0).ToArray(),Actors.Select(a=>a.Enabled?1:0).ToArray(),Actors.Select(a=>a.Position.X).ToArray()); + } + public void Log(char kind,Actor a,Actor b)=>Events+=$"{kind}{a.Id}{b.Id};"; +} +sealed class Actor(Fixture fixture,int id):IOriginalPairBody +{ + public int Id=>id; + public bool Enabled,Allowed,Integration,Authored,Inhibit; + public int Mode; + public Vector3 Position; + public HashSet Contacts=[]; + public HashSet Exclusions=[]; + public bool PairCollisionEnabled=>Enabled; + public int CollisionMode=>Mode; + public Vector3 Root=>Position; + public float Radius=>10; + public bool AllowsPair(IOriginalPairBody other)=>Allowed; + public bool Excludes(IOriginalPairBody other)=>Exclusions.Contains((Actor)other); + public bool HasContact(IOriginalPairBody other)=>Contacts.Contains((Actor)other); + public void Reset(){Enabled=Allowed=Integration=true;Authored=Inhibit=false;Mode=0;Position=default;Contacts.Clear();Exclusions.Clear();} + public void SphereOverlap(IOriginalPairBody other,float distance) + { + var b=(Actor)other;fixture.Log('R',this,b); + //Actual470BF0 invokes414 only if the other body's1E0 is false and own210 is true. + if(!b.Inhibit&&Integration) + { + fixture.Log('P',this,b); + if(fixture.Mutation==1&&id==0)Position.X=1000; + } + } + public void Enter(IOriginalPairBody other) + { + var b=(Actor)other;fixture.Log('E',this,b);Contacts.Add(b); + if(id==0&&b.Id==1) + switch(fixture.Mutation) + { + case 2: Enabled=false;break; + case 3: fixture.Actors[2].Enabled=false;break; + case 4: b.Contacts.Add(this);break; + } + } + public void Stay(IOriginalPairBody other)=>fixture.Log('S',this,(Actor)other); + public void Leave(IOriginalPairBody other) + { + var b=(Actor)other;fixture.Log('L',this,b); + if(!Integration&&Authored)Integration=true; + Contacts.Remove(b); + } +} diff --git a/tests/test_pair_lifecycle.py b/tests/test_pair_lifecycle.py new file mode 100644 index 0000000..1edaeb5 --- /dev/null +++ b/tests/test_pair_lifecycle.py @@ -0,0 +1,31 @@ +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT/'tools/binary')) +from pair_lifecycle import collect + + +class PairLifecycleTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.report = collect(ROOT.parent/'Original') + + def test_complete_source_functions(self): + self.assertEqual(len(self.report['ranges']), 8) + self.assertEqual(len(self.report['relocations']), 11) + self.assertEqual(self.report['ranges'][0]['file_offset'], '0x7a430') + + def test_vr04_candidates_and_common_permissions(self): + candidates = self.report['vr04_candidates'] + self.assertEqual([row['kind'] for row in candidates], ['3JIM','3ROC','3SOL','3TRO','3SOL','3SOL']) + self.assertEqual([row['file_offset'] for row in candidates], ['0x8','0x1e5','0x4431','0x546a','0x582c','0x67c5']) + self.assertEqual(len(self.report['bindings']), 20) + permissions = [row['target'] for row in self.report['bindings'] if row['slot'] == '0x3a0'] + self.assertEqual(permissions, ['0x472f80']*4) + self.assertTrue(all(row['has_collision'] == 1 for row in candidates if row['kind'] == '3SOL')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/binary/pair_lifecycle.py b/tools/binary/pair_lifecycle.py new file mode 100644 index 0000000..e573373 --- /dev/null +++ b/tools/binary/pair_lifecycle.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Guard the original ordered pair pass; generate a copied-code contact probe.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import struct + +from checkpoint_script_state import EXE_SHA256, find_case, read_va +from pe_inspect import PE +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels')) +from gam import parse + +REA_ID = 'ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904' +RANGES = ( + (0x47a430, 0x47a5de, '68ff890cd3f3526f8d4dd936b72748fdeb549cc97b56068ccc75c23df2c81ae6'), + (0x47b3e0, 0x47b4a1, '008cc7fa18ca1b59567f4388928045dcdfc9ac85d25dce277d2270378b18f5df'), + (0x47ca90, 0x47caba, '1d5618a99b80fec594c14a36b837e10456790bc44cac4306f8f7e66fd3a757b2'), + (0x470a60, 0x470a88, '6fd5f554e28bd9d733f561a1e755689f11d86997c2fda2ccefdbeab6946fe9f3'), + (0x470a90, 0x470b19, 'bfc56f226eb97077379bbb4f273ae47f0c0c1f97a1ec335996435a5c4f650038'), + (0x470b20, 0x470bb8, 'a84cc049930fd1301bb89a6a84255ebc4fe9515e26ce1d7be75c743574e31202'), + (0x470bc0, 0x470bea, '09bfd61be8128cdbf9c1f1aed7a416cd5ae3c735abf588106d17d744a233951a'), + (0x470bf0, 0x470c44, '5211f48735716c7a7426486f0b44ae9e93388546d825437edc6ef3f787e2aa8d'), +) +TARGETS = (0x4f69e4, 0x695d3c, 0x695d47, 0x4f6b08, 0x48d104, 0x509948) +TABLES = {'3JIM': 0x4a373c, '3ROC': 0x4b25ac, '3SOL': 0x4c19c4, '3TRO': 0x4be404} +COMMON = {0x178: 0x471720, 0x210: 0x4719f0, 0x220: 0x471a30, + 0x3a0: 0x472f80, 0x4c: 0x470bf0} + + +def collect(original): + original = Path(original) + pe = PE(find_case(original, 'Neutron.exe')) + if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256: + raise ValueError('Original identity mismatch') + ranges, relocations, bindings = [], [], [] + for start, end, digest in RANGES: + code = read_va(pe, start, end-start) + if hashlib.sha256(code).hexdigest() != digest: + raise ValueError(f'Changed source body {start:#x}') + ranges.append(dict(va=hex(start), file_offset=hex(pe.offset(start-pe.base)), + length=end-start, sha256=digest)) + for target in TARGETS: + encoded = struct.pack('id,b->id); +} +static void list_init(Node*n){n->next=n->previous=n;n->value=NULL;} +static void append(Node*list,Actor*a){ + Node*n=calloc(1,sizeof(*n));require(n!=NULL,"node");n->value=a; + n->next=list;n->previous=list->previous;list->previous->next=n;list->previous=n; +} +static void clear(Node*n){while(n->next!=n){Node*p=n->next;n->next=p->next;free(p);}list_init(n);} +static int TC enabled(Actor*a){return a->enabled;} +static int TC mode(Actor*a){return a->mode;} +static int TC allows(Actor*a,Actor*b){(void)b;return a->allowed;} +static float TC radius(Actor*a){return a->radius;} +static Vec*TC root(Actor*a,Vec*out){*out=a->root;return out;} +static int TC integration(Actor*a){return a->integration;} +static int TC authored(Actor*a){return a->authored;} +static void TC set_integration(Actor*a,int v){a->integration=v;} +static int TC inhibit(Actor*a){return a->inhibit;} +static int TC no(Actor*a){(void)a;return 0;} +static void TC response(Actor*a,Actor*b,float distance){ + require(distance>=0,"distance");event('P',a,b); + if(mutation==1&&a->id==0)a->root.x=1000; +} +static void TC overlap(Actor*a,Actor*b,float distance){ + event('R',a,b);((void(TC*)(Actor*,Actor*,float))AT(0x470bf0))(a,b,distance); +} +static void TC enter(Actor*a,Actor*b){ + event('E',a,b);((Contact)AT(0x470a90))(a,b); + if(a->id==0&&b->id==1){ + if(mutation==2)a->enabled=0; + if(mutation==3)actors[2].enabled=0; + if(mutation==4)append(&b->contacts,a); + } +} +static void TC leave(Actor*a,Actor*b){event('L',a,b);((Contact)AT(0x470b20))(a,b);} +static void TC stay(Actor*a,Actor*b){event('S',a,b);((Contact)AT(0x470bc0))(a,b);} +static int box(Actor*a,Actor*b){event('B',a,b);return box_hit;} +static void*allocate(size_t size){require(size==12,"source contact allocation");return malloc(size);} +static void release(void*p){free(p);} +static void reset(void){ + for(int i=0;i<3;i++){ + if(actors[i].contacts.next){clear(&actors[i].contacts);clear(&actors[i].exclusions);} + Actor*a=&actors[i];memset(a,0,sizeof(*a));a->id=i;a->enabled=a->allowed=a->integration=1;a->radius=10; + list_init(&a->contacts);list_init(&a->exclusions); + *(void**)a=a->table;*(void**)(a->raw+0x260)=&a->contacts;*(void**)(a->raw+0x254)=&a->exclusions; +#define SLOT(s,f) a->table[(s)/4]=(uintptr_t)(f) + SLOT(0x220,enabled);SLOT(0x178,mode);SLOT(0x3a0,allows);SLOT(0x260,radius);SLOT(0x310,root); + SLOT(0x3c,AT(0x470a60));SLOT(0x40,enter);SLOT(0x44,leave);SLOT(0x48,stay);SLOT(0x4c,overlap); + SLOT(0x210,integration);SLOT(0xb4,authored);SLOT(0x214,set_integration);SLOT(0x1e0,inhibit); + SLOT(0x1f8,no);SLOT(0x414,response); +#undef SLOT + } + list_init(&head);mutation=0;box_hit=1;*(unsigned char*)AT(0x4f69e4)=1; +} +static void order(int a,int b,int c){ + list_init(&head);int ids[]={a,b,c}; + for(int i=0;i<3&&ids[i]>=0;i++){ + Node*n=&nodes[i];n->value=&actors[ids[i]];n->next=&head;n->previous=head.previous; + head.previous->next=n;head.previous=n; + } + *(void**)AT(0x695d3c)=&head; +} +static void tick(const char*name){ + used=0;events[0]=0;((void(__cdecl*)(float))AT(0x47a430))(1.f/60); + printf("PAIR {\"name\":\"%s\",\"events\":\"%s\",\"contacts\":[",name,events); + for(int i=0;i<3;i++){ + unsigned mask=0;for(Node*n=actors[i].contacts.next;n!=&actors[i].contacts;n=n->next)mask|=1u<<((Actor*)n->value)->id; + printf("%s%u",i?",":"",mask); + } + printf("],\"integration\":[%d,%d,%d],\"enabled\":[%d,%d,%d],\"rootX\":[%.9g,%.9g,%.9g]}\n", + actors[0].integration,actors[1].integration,actors[2].integration, + actors[0].enabled,actors[1].enabled,actors[2].enabled,actors[0].root.x,actors[1].root.x,actors[2].root.x); +} +int main(void){ + setbuf(stdout,NULL);map_source(); + static const struct{unsigned va,target;} relocations[]={/* RELOCATIONS */}; + for(unsigned i=0;i