From 35a2a66606ba7a4e7ca0d1e732f271ee796d74ff Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Mon, 26 Oct 2026 22:22:42 -0400 Subject: [PATCH] Compose source body physics and enable tutorial static response --- AGENTS.md | 7 +- README.md | 3 + docs/architecture.md | 11 +- docs/checkpoint/README.md | 5 + .../collision-body-composition-source.md | 171 ++++++++++++++++ .../collision-body-implementation-review.md | 92 +++++++++ .../collision-body-implementation.md | 86 +++++++++ docs/checkpoint/collision-body-probe.md | 5 + docs/checkpoint/coverage.md | 2 +- docs/checkpoint/implementation-plan.md | 8 + docs/compatibility.md | 13 ++ docs/decisions.md | 8 + docs/progress.md | 46 +++++ docs/reverse-engineering.md | 4 + docs/tasks.md | 7 +- scripts/package.sh | 2 + scripts/test.sh | 1 + src/GamePort/Game/LabSimulation.cs | 44 ++++- src/GamePort/Game/OriginalBodyPhysics.cs | 121 ++++++++++++ src/GamePort/Program.cs | 12 +- .../GamePort.BodyPhysicsTests.csproj | 9 + tests/GamePort.BodyPhysicsTests/Program.cs | 123 ++++++++++++ .../GamePort.InteractionTests.csproj | 4 + .../GamePort.PatrolTests.csproj | 4 + tests/test_body_composition_contract.py | 93 +++++++++ tools/binary/body_composition_contract.py | 182 ++++++++++++++++++ 26 files changed, 1045 insertions(+), 18 deletions(-) create mode 100644 docs/checkpoint/collision-body-composition-source.md create mode 100644 docs/checkpoint/collision-body-implementation-review.md create mode 100644 docs/checkpoint/collision-body-implementation.md create mode 100644 src/GamePort/Game/OriginalBodyPhysics.cs create mode 100644 tests/GamePort.BodyPhysicsTests/GamePort.BodyPhysicsTests.csproj create mode 100644 tests/GamePort.BodyPhysicsTests/Program.cs create mode 100644 tests/test_body_composition_contract.py create mode 100644 tools/binary/body_composition_contract.py diff --git a/AGENTS.md b/AGENTS.md index 7a7abe0..4a0830f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,7 @@ body-root-registration and camera-handoff reports. The source sphere kernel is isolated/probed; do not treat it as live capsule replacement. Next integration report is collision-body-probe.md: source grid/retry component and seven original dispatcher comparisons, contact/material/friction contracts and ten ordinary-body -observations are recorded. Next: compose ordinary body against those references, -then explicit VR04 live integration. Lab/outside additionally need special contacts -and dynamic reclip/shared-state ownership; shared camera state remains separate. +observations are recorded. collision-body-implementation.md now records matched +ordinary composition and VR04 static-only live integration. Next: original dynamic +actor eligibility/pair state and special contacts before lab/outside expansion; +shared camera state remains separate. Retain modern render/noclip boundaries. diff --git a/README.md b/README.md index 8f51e29..47608d1 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,9 @@ are preserved locally as the playable baseline. Corrections now include task/Car callbacks, controlled player phase ordering, source static camera queries for the first route and gadget availability through tutorial/return. Full scene scheduling, collision and shared camera state remain incomplete. +VR04 now uses recovered static body response/support/friction with original-code +numeric references. Lab/outside retain the capsule until special contacts and +dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md). **Current milestone: original lab story, interactions and jet pack practice flow.** The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard diff --git a/docs/architecture.md b/docs/architecture.md index 7bfc0ba..2174544 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -26,13 +26,18 @@ fly camera or rendered model alone does not satisfy the playable-scene requireme Collision continuation separates the recovered one-triangle47BD80 kernel (`OriginalSphereResponse`) from the live capsule adapter. Its explicit nearest state is caller-owned. `OriginalStaticCollision` composes source FIFO cell visits, -retry and support-grid reduction as an isolated component. Its caller owns body +retry and support-grid reduction. Its caller owns body integration, terminal callbacks and shared nearest/last-polygon reset timing. Prepared collision metadata retains signed material archive identities and an explicit completeness flag; source body callers must account for special contacts. Seven original dispatcher comparisons and ten original ordinary-body reference -observations are in checkpoint/collision-body-probe.md. Live body composition, -special callbacks and dynamic reclipping remain gated. +observations are in checkpoint/collision-body-probe.md. `OriginalBodyPhysics` +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. +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: Jimmy's wrapper reflects upward velocity/cancels mode1 jump/fire before movement, including while uncontrolled. Fresh input precedes this wrapper; retained input diff --git a/docs/checkpoint/README.md b/docs/checkpoint/README.md index 8afde72..1ac3ae1 100644 --- a/docs/checkpoint/README.md +++ b/docs/checkpoint/README.md @@ -39,6 +39,11 @@ The next C4 chunk adds [grid traversal](collision-grid-traversal.md), is implemented and compared with isolated original outputs; whole-body/live integration and special contacts remain gated. [Independent review](collision-integration-review.md) records corrections and remaining limits. +The [ordinary-body implementation](collision-body-implementation.md) composes the +ten numeric references and enables the static subset in VR04. Its +[source contract](collision-body-composition-source.md) closes phase/radius fields; +[implementation review](collision-body-implementation-review.md) preserves remaining +dynamic, special-contact, initialization and modern noclip/render boundaries. Evidence labels used throughout: diff --git a/docs/checkpoint/collision-body-composition-source.md b/docs/checkpoint/collision-body-composition-source.md new file mode 100644 index 0000000..07a3905 --- /dev/null +++ b/docs/checkpoint/collision-body-composition-source.md @@ -0,0 +1,171 @@ +# Ordinary body composition479D20 + +2026-10-27 UTC. Independent source investigation for the managed composition +chunk. The EXE SHA256 is +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Preferred VAs below are PE-mapped by body_composition_contract.py; text raw +offsets equal VA−400000 for these supplied bytes. The helper guards the entire +479D20..47A329 body plus81 decisive instruction sites and12 Jimmy vtable targets. + +## Evidence and scope + +Retained REA479D20 Evidence +`ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0` +is in artifacts/collision-response/rea-response/01.evidence.json. Its incomplete +prototype/local-variable reconstruction must be checked against instructions; +the actual caller supplies actor interface and dt. Reviewed disassembly is saved +to artifacts/collision-integration/body-composition.instructions.txt; fixed source +anchors/offsets are in body-composition-contract.json. No original executable +entry point or original routine was executed in this independent investigation. +The ten prior copied-code body observations remain separate in +[collision-body-probe.md](collision-body-probe.md). + +Focused new REA/Ghidra session used the existing generated EXE copy, exported +Evidence, then closed normally under artifacts/collision-integration/rea-body-radius/: + +| Procedure | REA Evidence | +|---|---| +|471240, authored/current radius setter|ev_d77d8a0d308e4d9b71dbb0cccfcf68771bd4552a9d4a09c50d14225ec171b058| +|471B40, live body-radius setter|ev_97d21014bcdac4f44484c1c079e957f22d449b60efd7c2a31be450deddc38871| + +437F90 was not recognized as a Ghidra procedure; the complete error remains in +00.json. Its burst call site is supported by reviewed instructions/fixed guards, +not attributed to successful pseudocode. No unchanged failed query was retried. + +## Recovered phase order + +The body pointer is the game interface, complete-object+C0 for Jimmy. Slot offsets +in this report are interface-relative. + +| VA / raw offset | Source operation and ownership | +|---|---| +|479D2E /79D2E|Read support218 and cache previous support in global695D49.| +|479D3D..4E /79D3D|If support handling1C8 is enabled, write current support21C(false).| +|479D58..60 /79D58|Only now test integration210; false returns with the preceding support side effects intact.| +|479D6F..479DD4 /79D6F|Read current root310 and old previous root2F8; compute quick magnitude of their difference and discard its result. This is not a pre-support/gravity cancellation query.| +|479DDA..479E54 /79DDA|Test global geometry4F69E5, independently of prior support. Enabled: anchor2F4(0,−25000,0). Disabled: support21C(true), anchor(0,current-root-Y,0), acceleration278(0,−gravity.Y,0), velocity2C4(oldX,0,oldZ).| +|479E63..479EAC /79E63|Read angular velocity2AC, rotate334(angularXYZ×dt) before consuming impulse.| +|479EBB..479EF2 /79EBB|Read pending impulse284, add XYZ through velocity2CC, clear impulse28C(0,0,0) once.| +|479F01..479F4A /79F01|Read acceleration270, add accelerationXYZ×dt to velocity.| +|479F50..479F7E /79F50|Separately add global gravityXYZ×dt.| +|479F8D..479FD2 /79F8D|Read resulting velocity; store displacementXYZ=velocityXYZ×dt.| +|479FD6..479FF0 /79FD6|Read collision flag220, then world-response1D0 when collision is enabled. These gates are distinct from global geometry and support.| +|47A038..47A096 /7A038|World branch clears last polygon695D4C, sets face695D5C=130000 and edge5CFBE0=radius260, copies current root into previous-root2FC, clears auxiliary695D84.| +|47A090..47A11F /7A090|If displacement.Y>0, dispatch47B4B0 with fullXYZ. If Y<=0, dispatch with XZ/zeroY, then add original falling displacement.Y to candidate.Y. Edges flag is true in both paths.| +|47A123..47A181 /7A123|After terminal contact callback, read fresh previous-root2F8 and live root310 and compare all four floats. Only equality permits final candidate publication.| +|47A187..47A1C4 /7A187|Clamp candidate **Y** below−25000 to−25000, then publish Vec4 via314; if any previous/live component differs, skip clamp/publication.| +|47A22A..47A235 /7A22A|If1C8, run support47B890 after displacement/callback/publication. It uses the original previous support695D49 for landing transition.| +|47A241..47A25A /7A241|Read published scalar268/live160. Equal zero invokes friction47A330; this is not controller scalar608 or a raw-control test.| +|47A298..47A2D1 /7A298|Read suppression scale230/live144. Angular quick magnitude×scale<=0.1 zeros angular velocity2B4.| +|47A2E0..47A31D /7A2E0|Linear quick magnitude×scale<=0.1 plus a fresh268==0 zeros linear velocity2C4.| + +Publication from the dispatcher means writing the caller's candidate stack vector, +not necessarily changing actor root310. The later Vec4 equality check preserves +contact-owned transform changes. It compares freshly read previous/live roots; +it is not a comparison with a stale local copy and must include W. Ordinary +370 and nonspecial Jimmy374 do not move the root, so a bounded ordinary adapter +can keep W=1 explicitly. A future special callback must preserve this boundary. + +The body does not automatically reset movement mode/jump/fire on support. Source +landing37C for Jimmy is a no-op; later controller/fire callbacks own those states. +Landing observer order and friction details are in +[collision-contact-callbacks.md](collision-contact-callbacks.md). +The rotate334 call's order and XYZ arguments are recovered here; this does not +recover generic334 angle wrapping or logical/render transform synchronization. +The original body fixture substitutes a simple Euler-add virtual, so its angular +cases cannot independently prove the real transform implementation. An ordinary +live bridge supplying zero angular velocity remains within a narrower contract. + +## Flag branches and shared state + +If220 is true but1D0 is false, source47A1CC..47A220 copies current root to +previous2FC and translates31C(displacement). Support and published-speed friction +still run afterward. It does not initialize/query the static context in this path. + +If220 is false,47A264 tests228. When228 is false, it translates31C(displacement); +when true it does not translate. Both skip support and friction, but still run +the suppression tail. The initial support clear remains, if1C8 was enabled. +Treating all of these modes as a single collision/noclip boolean would lose +source state changes. Modern F3 noclip is a separate user-requested policy. + +Prior source guards establish ordinary defaults: support1C8/live13B=true, +world1D0/live13C=true, integration210/live13E=true, collision220/live140=true, +228/live141=false. Player overrides prevent-lowering208/live13A=true; direct +dispatcher member42C defaults0. Generic suppression-scale default0.5 is +46FE01→471120→234, and Player friction default0.8 is4373B0→4711B0→24C→live150. +These are initialization contracts, not invariants after authored/script setters. + +Static context resets occur once before body world traversal. Retries retain +nearest/last polygon. Dynamic response uses its own face/edge initialization and +can retain the last-polygon global; it remains a separate shared-scene contract. +No new meaning is assigned to auxiliary695D84 in this bounded investigation. + +## Init restores authored speed separately from current publication + +Retained REA470540 Evidence +`ev_c16f95e608194a8f9fb029430f1c6a01512d34099ebf447cf944946c79631166` +in artifacts/collision-integration/rea-support/02.json covers generic Init's scalar +copy. It is independently linked to Jimmy's vtable and the guarded leaf bodies: + +| Source site | Initialization contract | +|---|---| +|4706CF /706CF|Calls Jimmy interface114→471260, reads authored float interface38.| +|4706DB /706DB|Passes that value to interface26C→471B60, writes current published160.| +|46FC08 /6FC08|Constructor zeroes EBX.| +|46FE51..54 /6FE51|Pushes EBX=0, invokes471270 (authored-speed setter).| +|471270 /71270|Stores authored38, then forwards the same value to26C/live160.| +|471B50/471B60 /71B50/71B60|268 reads and26C writes current published160 only.| + +Controller437C22..2D publishes through26C after applying movement, so it changes +current160 without changing authored38. Preparation43A750 clears controller608 +and velocity but not either speed field38/160. Ordinary/retained Init through +437890→4587F0→470540 therefore reapplies authored speed; constructor default is0 +and the current route's Jimmy properties do not assign another authored speed. +The bounded bridge's per-scene PublishedSpeed=0 follows this initialization +chain, rather than being inferred from controller608's separate Init reset. + +Init is a copy of authored38, not an unconditional zero invariant. A future caller +of interface118→471270 with a nonzero authored value must preserve that value +through subsequent Init. No new source execution is claimed for this follow-up; +the retained REA Init result plus fixed getter/setter/constructor bytes establish +the route/default contract. + +## Burst radius is the same live physics radius + +There is no independent interaction-only100 radius in this source path: + +| Source link | Structure/write | +|---|---| +|437FA3|Air helper obtains EDI=complete object+C0, the same game interface.| +|4384E4 /4384F3|Allowed burst with an effect pushes100, calls interface264.| +|Jimmy table4A373C+264→471B40|Writes interface15C, current body radius.| +|Table+260→471B30|Reads exactly interface15C;479D20 and47B890 both consume260.| +|PostLoad4236A3→110→471240|Writes authored34 then invokes264, initializing current radius60.| +|Held-state3 landing4386C1..C8|Writes current radius60 directly through264.| +|PostLoad4236B3→100→4711E0→254→471B00|Sets live support factor154=1.265;250→471AF0 reads it.| + +Thus radius100 changes both sphere response and radius×factor support clearance +and root offset, to126.5 with the ordinary factor. Grounded Jimmy's ordinary +wrapper restores60 in its later object phase; physics/support must not perform +that restoration early or clear it merely because control is absent. Other +gadget radii (for example scooter160) remain outside the ordinary−1/3 subset. + +## Verification and remaining integration questions + +`python3 -m unittest discover -s tests -p test_body_composition_contract.py -v` +passes eight groups: original body/site identity; disabled-integration support +clear; phase order; descending split; three distinct flag gates; four-component +publication predicate; shared burst/support radius targets; Init authored/current +speed separation. These fixtures are +explicit source control-flow projections, not original execution or managed body +numeric verification. Existing ten isolated body observations and primary's +managed comparisons provide separate numeric evidence recorded by primary. + +Before VR04 live use, compare root/support while radius changes60→100→60, retain +separate published160 versus controller608 across control loss, and verify the +phase owner for restoring radius. Source collision root and modern render foot +translation remain separate: no new capsule height or visual sole correction is +derived here. Full wrapper/registry, exact x87 cell/quick-magnitude boundaries, +special160/164/FENCE/LADDER callbacks, dynamic global context and whole original +game comparison remain open. An ordinary component passing numeric fixtures does +not establish those broader contracts. diff --git a/docs/checkpoint/collision-body-implementation-review.md b/docs/checkpoint/collision-body-implementation-review.md new file mode 100644 index 0000000..ce48779 --- /dev/null +++ b/docs/checkpoint/collision-body-implementation-review.md @@ -0,0 +1,92 @@ +# Ordinary body and VR04 bridge review + +2026-10-27 UTC. Independent read-only review of primary's current +OriginalBodyPhysics.cs, LabSimulation.cs and Program.cs against +[the source contract](collision-body-composition-source.md). This investigator +owns only this report. No new original execution or REA session was necessary; +existing retained body/radius Evidence and guards establish the reviewed facts. + +## Result + +No directly evidenced mismatch was found within the stated subset: enabled +integration/support/collision/world flags, prevent-lowering enabled, lower-edge +override disabled, ordinary Jimmy contacts, fixed factor1.265 and zero angular +velocity in the live bridge. The implemented composition preserves source +impulse→acceleration→gravity, positive-Y/full versus nonpositive-Y/horizontal-first +motion, terminal370 positive-Y clearing, support/landing order, independent +published160 friction gate and final suppression. Fresh per-body nearest context +agrees with the source world branch's explicit resets. + +The absence of special Player374 behavior is enforced conservatively by rejecting +any source scene with potentially eligible special-contact material IDs. Omitting +the source Vec4 previous/live-root reentrancy test is justified only inside this +bounded no-root-changing-contact subset; the explanatory source comment says so. +Generic334 angle wrapping/transform behavior remains outside the zero-angular +bridge, and the component's nonzero-angular numeric fixtures use the original +probe's substituted Euler-add virtual rather than real source334 execution. + +## Integration checks + +- Program selects the source body only for actual VR04; lab/outside keep their + existing adapter. OriginalBodyPhysics rejects special-contact geometry and + StepOriginalPhysics rejects attaching the provisional dynamic resolver. +- The live radius passed to body/support is InteractionRadius. This correctly + incorporates burst100 and later wrapper restoration60, rather than retaining + the old capsule24 radius or treating100 as interaction-only. Constant75.9 is + a conversion between modern feet storage and actor root, not the solver's + variable support offset. Rendering's sole correction remains a modern policy. +- Physics still runs before Jimmy input/controller/fire. Grounded radius60 is + restored in the wrapper before ownership checks. Preparing a script clears + controller speed/velocity while preserving body published160, pending impulse + and independent acceleration. A new scene resets published speed separately. +- The bridge supplies zero angular velocity and derives the next state from + current actor root/velocity/acceleration/impulse/support/published speed each + body pass. Dropping the component's angular output does not lose live angular + state inside this declared zero-angular subset. +- Camera debug enable remains camera-only; the body's geometry and overhead + query do not use it. Modern noclip bypasses the body while enabled and resumes + it with cleared motion through the existing debug policy. + +## Scope risks and next gates + +1. **Prepared doors are not every original dynamic body.** Program rejects a + nonempty StaticSceneVisuals.DoorColliders sequence in the source subset. This + establishes only absence of those prepared doors. Actual VR04 entities include + 3SOL,3ROC,3TRO and other classes; their complete original physical-list and + pair-collision eligibility is not closed by that check. Preserve the explicit + no-dynamic-body-pass limitation and recover source registry/flags before + claiming complete tutorial collision fidelity or extending the adapter. +2. **Modern noclip exit uses the old occupancy policy.** SetNoclip(false) still + checks SceneCollision.CanOccupy with capsule24/render-derived height. Source + body response can subsequently reposition a root that this debug test admitted. + The ordinary flight/return test does not establish radius60/100 admission at + walls or tight gaps. Keep this as a documented debug policy; a later source + occupancy check needs an explicit supported contract rather than silently + treating zero-motion dispatch as a complete overlap query. +3. **Initial/visual placement is still bounded.** SceneCollision.GroundHeight and + floor-derived rendering are used to initialize the modern bridge. The stable + VR04 root/sole tests verify port consistency, not original transform/pivot + equivalence. Source spawn/root settling and wrapper/base logical-to-render + synchronization remain separate comparisons. +4. **Shared dynamic context remains unimplemented.** Fresh source body contexts + must not later be reused for dynamic reclipping without the recovered reset/ + last-polygon schedule. Special contact root writes require the source Vec4 + publication condition; a generic wall reflection is not an adequate substitute. +5. **Gadget scope remains−1/3.** Source gadget7 has additional374 side effects; + source scooter uses another radius policy. The current bridge does not carry + those contracts into OriginalBodyPhysics. Future gadget-selection expansion + must restrict or implement them before broadening this solver's claim. + +These are retained integration boundaries, not failures of the ten-reference +ordinary composition. They do not require changing the verified source arithmetic. + +## Verification + +`source scripts/env.sh && dotnet run --project tests/GamePort.BodyPhysicsTests -- +../Original` passes20 groups independently during this review, logged to +artifacts/collision-integration/body-implementation-review-tests.log. Coverage +includes ten original copied-body references, positive/nonpositive split, +ceiling370, radius100 support, unclamped friction, actual VR04 root/visual +consistency, preparation/published speed, control-independent impulse, retained +flight/landing and ordinary noclip return. These are managed port checks; +primary's headless/native/GPU/whole-route results are recorded separately. diff --git a/docs/checkpoint/collision-body-implementation.md b/docs/checkpoint/collision-body-implementation.md new file mode 100644 index 0000000..c5748e6 --- /dev/null +++ b/docs/checkpoint/collision-body-implementation.md @@ -0,0 +1,86 @@ +# Ordinary body implementation and tutorial bridge + +2026-10-27 UTC. This chunk composes the recovered static dispatcher with ordinary +Jimmy body integration and enables that bounded path in VR04. It does not close +all collision, dynamic bodies, special contacts or original visual comparison. + +## Evidence and implementation + +[Source composition](collision-body-composition-source.md) records the whole-body +hash,81 guarded sites,12 virtual targets, callers, offsets, flags, source root +publication condition and new REA radius Evidence. [Original component results](collision-body-probe.md) +provide ten copied479D20/support numeric references. No original game entry point +or full Jimmy instance was executed by this implementation chunk. + +OriginalBodyPhysics implements the true210/1C8/220/1D0, false228/42C, +prevent-lowering subset. It clears current support, consumes impulse once, adds +acceleration and gravity separately, splits nonpositive-Y motion into horizontal +response then fallingY, and preserves source callback/support/friction/suppression +order.370 clears positive vertical velocity/acceleration independently. Ordinary +374 and inherited37C do not move the root; special-contact worlds are rejected. +This justifies the fixed-W1/no-root-changing-contact publication subset. Future +special callbacks must implement fresh previous/live Vec4 comparison before314. + +Landing diagnostics observe new root/zero acceleration and old velocity/support. +Published speed160 is separate from controller608, copied at the controlled tail. +Script preparation clears controller speed/velocity while preserving published +speed, pending impulse and acceleration. Friction reads the preserved body scalar; +control ownership does not suspend physics. The generic scale0.5 suppression and +unclamped friction0.8 follow source contracts. Nonzero angular component tests use +the probe's substituted334 Euler-add contract; the live bridge passes angular0. + +Program selects source body only for VR04. Lab/outside retain their prior capsule +because they contain special contact materials and pending dynamic integration. +The source body rejects attaching the provisional dynamic resolver; Program also +asserts no prepared door colliders in this subset. This does not prove absence of +every original dynamic class: VR04 has3SOL/3ROC/3TRO and other eligibility questions. + +Live radius is the existing InteractionRadius, which source260/264 prove is the +same body field15C. Burst60→100 changes both sphere response and support offset +75.9→126.5; later grounded wrapper restoration60 stays after physics and outside +the input ownership gate. The replay now records two support landings rather than +the previous capsule's one; radius/support transitions are retained, not flattened +to preserve the old diagnostic count. Maximum rise changes418.98→418.93 because +the source path removes the modern floor skin. Travel remains403.88 in this input +fixture. These are port observations, not original whole-game trajectory metrics. + +ActorRoot/feet conversion remains constant75.9 and sole-based rendering remains +the existing modern bridge. Initial placement still uses the bounded floor query; +this does not derive original visual pivot/height or generic transform semantics. +Modern F3 noclip bypasses source physics and clears motion on exit; admission still +uses the capsule24/render-height occupancy check. It is a debug policy, not a +recovered radius60/100 overlap query. Full wrapper/registry remains open. + +## Verification + +Twenty managed body groups pass, independently reviewed: all ten original-code +numeric references; prior support/landing ownership; angular-before-suppression; +published-speed cutoffs; special-scene rejection; positive/nonpositive split; +ceiling370; radius100 support/unclamped friction; actual VR04 root/render bridge; +pending jump while uncontrolled; preparation/publication; retained jetpack/steering/ +landing and noclip return. These tests compile into GamePort.BodyPhysicsTests and +are included in scripts/test.sh. Two existing explicit-source test projects now +include the new dependencies; the initial suite compilation failure is retained +in artifacts/body-composition/integration-initial.log, not reported as a pass. + +Headless VR04300-frame replay and native Linux GTX1070/private Xvfb replay at +1920x1080 both pass with zero enabled Vulkan validation errors. Native SDL receives +move/brake/turn/jump and resizes800x600. Both end supported with one burst, +travel403.88, max rise418.93 and energy20 (VR04 exemption). Saved readback shows +the modern standing-foot bridge remains above the visible floor at the final +replay position; this is a port image check, not source pivot comparison. + +Logs/readbacks: artifacts/body-composition/body-tests.log, tutorial-jetpack.log, +tutorial-jetpack.png and native/jetpack.log. Independent review is in +[collision-body-implementation-review.md](collision-body-implementation-review.md). +Full-suite, package and preservation results are recorded in progress.md after +their completion. No native Windows runtime result is inferred from cross-builds. + +## Next bounded work + +Recover original physical-list and pair-collision eligibility for VR04 actor +classes, plus dynamic nearest/last-polygon/reset order. Recover lab/outside's +Player160/164/FENCE/LADDER policies, including control and root ownership, before +using this body solver there. Keep the existing capsule baseline available for +comparison. Shared camera eye/DEFAULT handoff remains the next independent C5 +contract; audio clock/banks and later implementation chunks retain their gates. diff --git a/docs/checkpoint/collision-body-probe.md b/docs/checkpoint/collision-body-probe.md index 036816d..268c6c4 100644 --- a/docs/checkpoint/collision-body-probe.md +++ b/docs/checkpoint/collision-body-probe.md @@ -91,6 +91,11 @@ jump fixture applies acceleration and gravity normally. ## Implementation and remaining gate +This section records the dispatcher-only stage. The subsequent +[ordinary-body implementation](collision-body-implementation.md) compares all ten +body references and enables the static subset in VR04; special/dynamic/root gates +below remain explicit for further expansion. + OriginalStaticCollision is currently an isolated source dispatcher/support-grid component, invoked by tests. It preserves duplicate visits, retry state, negative Z upper-bound quirk and terminal publication. Its explicit geometry-enable input diff --git a/docs/checkpoint/coverage.md b/docs/checkpoint/coverage.md index 12768fc..7e7a1d9 100644 --- a/docs/checkpoint/coverage.md +++ b/docs/checkpoint/coverage.md @@ -16,7 +16,7 @@ runtime comparison. Coverage does not mean implementation completeness. | 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 arithmetic; physics479D20 consumes queued impulse once before acceleration/gravity. | Player body/fire continue without ownership; input/controller gated; fresh/retained input order explicit. Root overhead wrapper now runs before movement/fire. Fixed dt and custom yaw/model conventions remain. | S/P/M/R. Bounded phases/ceiling implemented; complete base/registry and body response open. | Continue C4 traversal/callback/support integration and C3 base transforms. | | 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 gate; support/suppression; overhead; dynamic boxes. | Source sphere and static dispatcher/support grid implemented as isolated components; route overhead wrapper live. Prepared IDs retained. Live24-unit capsule/feet and dynamic response remain provisional. | S/P/M/R. Ten original kernel, seven dispatcher and ten ordinary-body observations; managed dispatcher comparisons. Special contacts, live body composition, dynamic shared context and root rendering open. | C4: compose ordinary-body adapter against ten references, then explicit VR04 live subset. Lab/outside need special160/164/FENCE/LADDER and dynamic reclip ownership. | +| 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. | | 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/implementation-plan.md b/docs/checkpoint/implementation-plan.md index 92af939..90f497c 100644 --- a/docs/checkpoint/implementation-plan.md +++ b/docs/checkpoint/implementation-plan.md @@ -171,3 +171,11 @@ allowed where it resolves a core-system question, without waiting for every leve horizontal-first split,370, landing-before-velocity-clear, published160 friction and suppression; then VR04 live root/input/ceiling/RETURN checks. Trace special callbacks and dynamic reclip/global context before lab/outside replacement. +- C4 ordinary-body composition implemented and matched against all ten copied + body references. VR04 now selects the source static subset with live radius + 60/100, separate published160, control-independent body work and source landing/ + friction order. Twenty managed groups and native/headless300-frame jetpack + replay pass; lab/outside capsule retained. Source and independent review: + collision-body-composition-source.md, collision-body-implementation.md and + collision-body-implementation-review.md. Other original VR04 dynamic class + eligibility, special Player callbacks and shared dynamic contexts remain open. diff --git a/docs/compatibility.md b/docs/compatibility.md index 0887859..3cdac9a 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -3,6 +3,19 @@ Compilation, native runtime, original behavior and full feature completion are separate evidence categories. **The game is not fully reconstructed/playable yet.** +C4 ordinary body (2026-10-27 UTC): all ten original-code body references match +managed composition. VR04 uses source static response/support/friction and live +radius60/100; lab/outside retain the capsule. Twenty body groups plus full suite +pass:129 Python+2 HUD, managed checks,27 zero-error enabled-validation GPU renders, +SDL dummy lifecycle and539 unchanged originals. Native GTX1070/private Xvfb at +1920x1080 passes300-frame jetpack input/resize/steering/landing. Logs/readback: +artifacts/body-composition/. Source scope/independent review are linked from +checkpoint/collision-body-implementation.md. Original dynamic actor eligibility, +special callbacks, logical/render pivot and modern noclip occupancy remain open. +Native Windows and whole-original-game comparisons remain unverified. +The final expanded Python suite passes130 checks after the Init authored/live +speed closure; the129-check full-integration log predates that extra regression. + C4 static composition follow-up: seven copied-original dispatcher fixtures match the isolated managed grid/retry component; ten copied479D20/support fixtures complete as references for future body composition. No live capsule replacement diff --git a/docs/decisions.md b/docs/decisions.md index 09255e6..1a60990 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -182,3 +182,11 @@ must explicitly own shared nearest/last-polygon state. Keep source published speed160 separate from controller608. Geometry-off gravity cancellation must not be reinterpreted as an ordinary prior-grounded jump rule. +35. **Enable the tested static body subset in VR04.** Compose verified traversal, + support and friction using original body-reference outputs. Reject special + scenes/provisional dynamic resolver and keep lab/outside on the baseline. + Preserve source60/100 radius changes through both sphere response and support; + restore60 in the later Jimmy wrapper. Published speed160 survives control + preparation separately from controller608. No dynamic-door geometry does not + establish absence of other source dynamic actor classes. Modern feet/sole and + noclip admission remain explicit policies; this is not whole-tutorial fidelity. diff --git a/docs/progress.md b/docs/progress.md index 6bd3284..c994cdb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,51 @@ # Progress — 2026-10-26 +## C4 ordinary body implementation — 2026-10-27 UTC + +OriginalBodyPhysics composes the source static dispatcher, positive-Y versus +horizontal-first split, ordinary contact370/374, support/landing, published160 +friction and suppression. All ten retained original-code body references match. +VR04 now uses this source static subset; lab/outside retain the capsule pending +special contacts and dynamic integration. The bridge uses actual radius60/100 for +both sphere response and support, with grounded restoration in the later wrapper. +Published body speed is separate from controller speed and survives script +preparation/control loss until a controlled publication; Init restores authored +speed (route default0). Ordinary callbacks cannot change root, so this subset +permits fixedW1 publication; full callback reentrancy remains a special-policy gate. + +An independent investigator cross-checked source phase/flag branches, rootY clamp, +radius setter/getter and authored/live field chains with REA Evidence and guarded +instructions. The same investigator reviewed the implementation and independently +ran twenty body groups. No directly evidenced mismatch was found within the +declared zero-angular/ordinary/static subset. Other original VR04 dynamic classes, +generic rotations, initial/visual root and modern noclip capsule admission remain +explicit gaps. Reports: checkpoint/collision-body-composition-source.md, +collision-body-implementation.md and collision-body-implementation-review.md. + +Full scripts/test.sh passes129 Python plus2 HUD tests, all managed groups including +20 body and11 dispatcher,27 GPU completions with zero enabled validation errors, +SDL dummy lifecycle and539 unchanged original hashes. Lab→tutorial→lab→outside, +RETURN/scalar/input ordering, control lock, objective/save and jetpack regressions +pass. Initial suite compile failed because two explicitly linked test projects +needed the new body dependencies; fixed and rerun successfully. Logs under +artifacts/body-composition/ retain both attempts. +After the final authored/live speed guards were added, the complete Python suite +passes130 tests in python-final.log (eight body-source groups,81 sites/12 targets). +The prior full integration run's129 count precedes that extra source regression; +no runtime implementation changed after its successful completion. + +Native Linux GTX1070/private Xvfb at1920x1080 passes the300-frame VR04 SDL move/ +brake/turn/jump replay and resize800x600, with zero Vulkan validation errors. +Native/headless source-body runs end grounded with travel403.88, one burst, +max rise418.93, energy20 and two support landings; radius-dependent support is +retained instead of flattening this diagnostic count. Final readback inspected; +modern sole bridge is consistent, not original pivot verification. No new native +Windows or whole-original-game comparison claimed. Baseline69d0187 remains intact. + +Next: original dynamic actor/pair eligibility and shared reclip context, then +Player160/164/FENCE/LADDER for lab/outside; C5 shared eye/DEFAULT remains separate. +New package results will be recorded after the verified source milestone. + ## C4 static dispatcher, contacts and ordinary-body probe Independent REA investigations and primary integration recover47B4B0's reachable diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 185739e..9787208 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -23,6 +23,10 @@ probes and modern runtime checks are recorded separately. `collision-body-probe.md`, `collision-integration-review.md`: REA/static grid, contact material linkage/landing/friction and seven dispatcher/ten ordinary-body component observations. Managed dispatcher is isolated; live capsule remains. +- `checkpoint/collision-body-composition-source.md`, `collision-body-implementation.md`, + `collision-body-implementation-review.md`: exact source phase/radius guards, + ordinary body composition matching ten original references, VR04 static subset + and retained dynamic/special/transform boundaries. Radius100 changes support too. - `save-format.md`: full supplied TSK layout, task query/assignment and activation gates. - `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas. - `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence. diff --git a/docs/tasks.md b/docs/tasks.md index 07bd2b6..cfdaf53 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -90,8 +90,11 @@ plan in verified chunks. Earlier priorities below are a backlog. compared against seven original fixtures; route material IDs and metadata gate. - [x] Contact/landing/published-speed/friction contracts and actual special material coverage recovered with REA. Ten isolated original body fixtures completed. -- [ ] Next: C4 ordinary body composition against ten numeric references, then - VR04 live integration; special contact policies/dynamic reclip before lab/outside; +- [x] C4 ordinary body composition matches ten numeric references; VR04 uses the + recovered static subset with source radius/support/friction and published speed. + Twenty managed groups and native/headless powered-flight replays pass. +- [ ] Next: C4 original dynamic actor/pair eligibility and shared reclip context; + special160/164/FENCE/LADDER contact policies before lab/outside replacement; full Jimmy/base wrapper/helper traversal and shared viewport/DEFAULT handoff. Physical re-registration chain is recovered; full implementation/order remains. C6 source channel allocation/ diff --git a/scripts/package.sh b/scripts/package.sh index 6c8f1ce..fc54217 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -73,6 +73,8 @@ Tutorial RETURN restores the departure position and suppresses the lab intro. Original actor/model/sprite props, common patrol, buttons/moving bars, lab task route, objectives, practice flow and checkpoint CLI are integrated. Collision, 60Hz cadence, pivots, rendering states and animation timing remain provisional. +VR04 now uses recovered static body response, support and friction. Lab/outside +retain the capsule pending special contact and dynamic collision recovery. Full combat, AI, progression, menus and runtime saves remain incomplete. The user confirms lab/tutorial/lab/outside and that their corrected Windows build works; comprehensive native Windows input/physics/audio/driver validation remains pending. diff --git a/scripts/test.sh b/scripts/test.sh index c3d40ce..dd8385e 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -11,6 +11,7 @@ dotnet run --project tests/GamePort.PatrolTests -- ../Original dotnet run --project tests/GamePort.SupportTests -- ../Original dotnet run --project tests/GamePort.SphereResponseTests dotnet run --project tests/GamePort.StaticCollisionTests +dotnet run --project tests/GamePort.BodyPhysicsTests dotnet run --project tests/GamePort.CameraRayTests dotnet run --project tests/GamePort.InteractionTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index 62e8afe..99ef596 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -9,7 +9,7 @@ public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } /// /// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in -/// movement-checkpoint.md. Capsule, floor-derived pivot and 60Hz are port policies; +/// movement-checkpoint.md. Legacy capsule, floor-derived pivot and60Hz are port policies; /// original collision, intro, object interactions and animation timing remain open. /// public sealed class LabSimulation @@ -18,6 +18,7 @@ public sealed class LabSimulation private readonly SceneCollision collision; private readonly Func? cameraRay; private readonly Func? ceilingRay; + private readonly OriginalBodyPhysics? originalBody; private readonly Vector3 sourceStart; private readonly float startYaw, modelMinimumY, rootHeight, startFloor; private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution; @@ -34,6 +35,8 @@ public sealed class LabSimulation public string LevelCode { get; set; } = "LV1B"; public int GadgetMode { get; set; } = -1; public float Energy { get; set; } = 20; + //Source260/live15C serves both body collision and contact tests. The name + //predates source-body integration; burst100 is not an interaction-only size. public float InteractionRadius { get; private set; } = 60; public bool JetpackEffectVisible { get; private set; } public float JetpackRemaining => jumpState.EffectRemaining; @@ -50,6 +53,8 @@ public sealed class LabSimulation public bool InputAfterPlayerUpdate { get; set; } public float Yaw { get; private set; } public float Speed { get; private set; } + public float PublishedSpeed { get; private set; } + public bool UsesOriginalBody => originalBody != null; public float TurnRate { get; private set; } public bool Grounded { get; private set; } public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle @@ -76,11 +81,13 @@ public sealed class LabSimulation public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw, Func? cameraRay = null, - Func? ceilingRay = null) + Func? ceilingRay = null, + OriginalStaticCollision? originalCollision = null) { this.collision = collision; this.cameraRay = cameraRay; this.ceilingRay = ceilingRay; + originalBody = originalCollision == null ? null : new OriginalBodyPhysics(originalCollision); sourceStart = start; startYaw = yaw; var bounds = standingPose.Bounds(); @@ -99,10 +106,10 @@ public sealed class LabSimulation public void Reset() { var floor = collision.GroundHeight(sourceStart, 2500)!.Value; - Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z); + Position = new(sourceStart.X, floor + (UsesOriginalBody ? 0 : SceneCollision.Skin), sourceStart.Z); Velocity = Vector3.Zero; Yaw = targetYaw = startYaw; - Speed = TurnRate = extraAirAcceleration = shadowDistance = 0; + Speed = PublishedSpeed = TurnRate = extraAirAcceleration = shadowDistance = 0; lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0; jumpState = default; forceFall = JetpackEffectVisible = false; @@ -222,7 +229,7 @@ public sealed class LabSimulation public void StopDebugMotion() { Velocity = pendingImpulse = Vector3.Zero; - Speed = TurnRate = extraAirAcceleration = lateralContribution = 0; + Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0; jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false; targetYaw = Yaw; } @@ -316,12 +323,18 @@ public sealed class LabSimulation else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false; if (air.StartGadget) Bursts++; Velocity = velocity; // Produced body state is consumed by the next physics pass. + PublishedSpeed = Speed; //437C22..437C2D: controller608 -> body160. } private void StepPhysics() { PhysicsSteps++; const float dt = FixedStepClock.Step; + if (originalBody != null) + { + StepOriginalPhysics(); + return; + } var wasGrounded = Grounded; var velocity = Velocity; // Keep the existing capsule/gravity adapter until C4 recovers Jimmy's @@ -355,6 +368,25 @@ public sealed class LabSimulation MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor); } + private void StepOriginalPhysics() + { + if (DynamicRootResolver != null) + throw new NotSupportedException("Original ordinary-body subset cannot use the provisional dynamic resolver"); + var before = Position; + var result = originalBody!.Step(new(ActorRoot, Velocity, Vector3.UnitY * extraAirAcceleration, + pendingImpulse, Grounded, PublishedSpeed), FixedStepClock.Step, InteractionRadius); + Position = result.Body.Position - Vector3.UnitY * rootHeight; + Velocity = result.Body.Velocity; + pendingImpulse = result.Body.Impulse; + extraAirAcceleration = result.Body.Acceleration.Y; + Grounded = result.Body.Supported; + if (Grounded) forceFall = false; + if (result.Landing != null) Landings++; + if (result.Contact is { StoredNormal.Y: > -.7f }) WallHits++; + Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z)); + MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor); + } + private void StepCamera() { const float dt = FixedStepClock.Step; @@ -383,5 +415,5 @@ public sealed class LabSimulation step is >= 80 and < 120, step is >= 60 and < 95, false, step < 180); public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded; - public string Report => $"Walk checkpoint: steps={Steps}, controller={ControllerSteps}, physics={PhysicsSteps}, effect={EffectSteps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, ceiling hits={CeilingHits}, grounded={Grounded}, feet={Position}."; + public string Report => $"Walk checkpoint: steps={Steps}, controller={ControllerSteps}, physics={PhysicsSteps}, effect={EffectSteps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, ceiling hits={CeilingHits}, grounded={Grounded}, feet={Position}, body={(UsesOriginalBody ? "source ordinary" : "provisional capsule")}."; } diff --git a/src/GamePort/Game/OriginalBodyPhysics.cs b/src/GamePort/Game/OriginalBodyPhysics.cs new file mode 100644 index 0000000..453e538 --- /dev/null +++ b/src/GamePort/Game/OriginalBodyPhysics.cs @@ -0,0 +1,121 @@ +using System.Numerics; + +namespace GamePort.Game; + +public readonly record struct OrdinaryBodyState(Vector3 Position, Vector3 Velocity, + Vector3 Acceleration, Vector3 Impulse, bool Supported = false, float PublishedSpeed = 0, + Vector3 AngularVelocity = default, Vector3 Rotation = default); + +public readonly record struct BodyLandingObservation(Vector3 Position, Vector3 Velocity, + Vector3 Acceleration, bool Supported); + +public readonly record struct OrdinaryBodyStep(OrdinaryBodyState Body, Vector3 PreviousPosition, + Vector3 SupportAnchor, SupportHit? SupportHit, BodyLandingObservation? Landing, + CameraRayPolygon? Contact, int CollisionPasses, int TriangleTests); + +/// +/// Bounded479D20 composition: enabled integration/support/pairs/static flags, +/// prevent-lowering true, ordinary Jimmy370/374/37C and no dynamic body pass. +/// Special Player374 policies are rejected at construction. This is independent +/// of controller ownership and published speed is distinct from input speed608. +/// Euler addition follows the probe's334 fixture contract; actual generic angle +/// wrapping is not recovered. The live player bridge supplies zero angular speed. +/// See collision-body-probe.md and collision-body-composition-source.md. +/// +public sealed class OriginalBodyPhysics +{ + private readonly OriginalStaticCollision collision; + + public OriginalBodyPhysics(OriginalStaticCollision collision) + { + ArgumentNullException.ThrowIfNull(collision); + if (collision.HasSpecialPlayerContacts) + throw new NotSupportedException("Ordinary body composition requires recovered special-contact policies for this scene"); + this.collision = collision; + } + + public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds, + float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor, + float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true) + { + Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse); + Finite(body.AngularVelocity); Finite(body.Rotation); + if (!float.IsFinite(body.PublishedSpeed) || !float.IsFinite(friction) || !float.IsFinite(suppressionScale) + || !float.IsFinite(factor)) throw new ArgumentOutOfRangeException(nameof(body)); + if (!float.IsFinite(radius) || radius <= 0) throw new ArgumentOutOfRangeException(nameof(radius)); + if (!float.IsFinite(seconds) || seconds <= 0 || seconds >= 1) + throw new ArgumentOutOfRangeException(nameof(seconds)); + + var previous = body.Position; + var wasSupported = body.Supported; + body = body with { Supported = false }; + var anchor = new Vector3(0, -25000, 0); + if (!geometryEnabled) + { + //479DF7..479E5A: global geometry-off policy, not prior support. + anchor.Y = previous.Y; + body = body with { Supported = true, Acceleration = new(0, -RecoveredMotion.Gravity.Y, 0), + Velocity = body.Velocity with { Y = 0 } }; + } + body = body with { Rotation = body.Rotation + body.AngularVelocity * seconds }; + var velocity = body.Velocity; + var impulse = body.Impulse; + var delta = RecoveredMotion.Integrate(ref velocity, ref impulse, body.Acceleration, + RecoveredMotion.Gravity, seconds); + var context = new StaticCollisionContext(radius); + var horizontalFirst = delta.Y <= 0; + var move = collision.Move(previous, horizontalFirst ? delta with { Y = 0 } : delta, + radius, context, geometryEnabled: geometryEnabled); + var acceleration = body.Acceleration; + //47B80F/47B82E -> Jimmy ordinary374 or positive-Y-only370. + // Neither supported callback moves the actor root, so the source's + // post-callback previous/live-root equality test permits publication. + if (move.CallbackPolygon is { } contact && contact.StoredNormal.Y <= -.7f) + { + if (velocity.Y > 0) velocity.Y = 0; + if (acceleration.Y > 0) acceleration.Y = 0; + } + var position = move.Position; + if (horizontalFirst) position.Y += delta.Y; + position.Y = MathF.Max(position.Y, -25000); + body = body with { Position = position, Velocity = velocity, Acceleration = acceleration, Impulse = impulse }; + + SupportHit? supportHit = null; + BodyLandingObservation? landing = null; + if (geometryEnabled) + { + var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor), + wasSupported, (start, end, sides) => collision.TraceSupport(start, end, sides)); + if (support.Supported) + { + //37C observes new root/zero acceleration but old velocity/support. + //Jimmy's inherited37C is a no-op; the observation is diagnostic. + if (support.Landed) landing = new(support.Body.Position, velocity, support.Body.Acceleration, false); + body = body with { Position = support.Body.Position, Velocity = support.Body.Velocity, + Acceleration = support.Body.Acceleration, Supported = true }; + anchor = support.SupportAnchor; + supportHit = support.Hit; + } + } + if (body.PublishedSpeed == 0 && body.Supported && OriginalBodySupport.QuickMagnitude(body.Velocity) > 0) + { + var v = body.Velocity; + var w = body.AngularVelocity; + body = body with { + Velocity = v + new Vector3(-v.X * friction * seconds, 0, -v.Z * friction * seconds), + AngularVelocity = w + new Vector3(-w.X * friction * seconds, -w.Y * friction * seconds, -w.Z * friction * seconds) + }; + } + if (OriginalBodySupport.QuickMagnitude(body.AngularVelocity) * suppressionScale <= .1f) + body = body with { AngularVelocity = Vector3.Zero }; + if (body.PublishedSpeed == 0 && OriginalBodySupport.QuickMagnitude(body.Velocity) * suppressionScale <= .1f) + body = body with { Velocity = Vector3.Zero }; + return new(body, previous, anchor, supportHit, landing, move.CallbackPolygon, context.Passes, context.TriangleTests); + } + + private static void Finite(Vector3 value) + { + if (!float.IsFinite(value.X) || !float.IsFinite(value.Y) || !float.IsFinite(value.Z)) + throw new ArgumentOutOfRangeException(nameof(value)); + } +} diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index b22923d..962f521 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -325,7 +325,8 @@ internal static class Program debugCameraRay = cameraRay; simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y, cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye), - cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end)) + cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end), + level.Code == "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null) { LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null }; if (carriedPlayer != null) { @@ -396,8 +397,13 @@ internal static class Program mesh = spriteVisuals.Mesh; staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models")); mesh = staticVisuals.Mesh; - simulation!.DynamicRootResolver = (previous, position, radius) => - DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius); + if (simulation!.UsesOriginalBody) + { + if (staticVisuals.DoorColliders().Any()) + throw new NotSupportedException("Source ordinary-body scene has unsupported dynamic door colliders"); + } + else simulation.DynamicRootResolver = (previous, position, radius) => + DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius); jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."))); mesh = jetpackVisuals.Mesh; hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json")); diff --git a/tests/GamePort.BodyPhysicsTests/GamePort.BodyPhysicsTests.csproj b/tests/GamePort.BodyPhysicsTests/GamePort.BodyPhysicsTests.csproj new file mode 100644 index 0000000..6c4ead0 --- /dev/null +++ b/tests/GamePort.BodyPhysicsTests/GamePort.BodyPhysicsTests.csproj @@ -0,0 +1,9 @@ + + Exenet10.0 + enableenable + false + + + + + diff --git a/tests/GamePort.BodyPhysicsTests/Program.cs b/tests/GamePort.BodyPhysicsTests/Program.cs new file mode 100644 index 0000000..0196160 --- /dev/null +++ b/tests/GamePort.BodyPhysicsTests/Program.cs @@ -0,0 +1,123 @@ +using System.Numerics; +using GamePort.Game; +using GamePort.Assets; + +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 floor=new CameraRayPolygon(new(new(-1000,0,-1000),new(1000,0,-1000),new(0,0,1000)),Vector3.UnitY); +var physics=new OriginalBodyPhysics(new([floor])); +OrdinaryBodyState Initial() => new(new(0,75.9f,0),Vector3.Zero,Vector3.Zero,Vector3.Zero); +// References observed from copied479D20/support, body-probe/wine.log. +var cases=new (string Name,OrdinaryBodyState Input,Vector3 Position,Vector3 Velocity,float AngularY,bool Supported,float? LandingY,bool Geometry)[] { + ("floor_support",Initial(),new(0,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true), + ("spawn_settle",Initial() with {Position=new(0,26,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true), + ("pending_jump",Initial() with {Supported=true,Impulse=new(0,550,0),Acceleration=new(0,-264,0)},new(0,84.7711105f,0),new(0,532.266663f,0),0,false,null,true), + ("fall_above_floor",Initial() with {Position=new(0,100,0),Velocity=new(0,-200,0)},new(0,96.4444427f,0),new(0,-213.333328f,0),0,false,null,true), + ("fall_land",Initial() with {Position=new(0,76,0),Velocity=new(0,-200,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,-213.333328f,true), + ("ground_friction",Initial() with {Velocity=new(100,0,50),AngularVelocity=new(0,12,0)},new(1.66666675f,75.9000015f,.833333373f),new(98.6666641f,0,49.3333321f),11.8400002f,true,-13.333334f,true), + ("published_speed",Initial() with {Velocity=new(100,0,50),AngularVelocity=new(0,12,0),PublishedSpeed=100},new(1.66666675f,75.9000015f,.833333373f),new(100,0,50),12,true,-13.333334f,true), + ("stationary_angular",Initial() with {AngularVelocity=new(0,12,0)},new(0,75.9000015f,0),Vector3.Zero,12,true,-13.333334f,true), + ("small_motion",Initial() with {Velocity=new(.125f,0,0)},new(.00208333344f,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true), + ("geometry_disabled",Initial() with {Velocity=new(0,200,0),Acceleration=new(0,-264,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,null,false) +}; +foreach(var test in cases) +{ + var result=physics.Step(test.Input,1f/60,geometryEnabled:test.Geometry); + Near(result.Body.Position,test.Position,$"{test.Name} root"); + Near(result.Body.Velocity,test.Velocity,$"{test.Name} velocity"); + Near(result.Body.AngularVelocity,new(0,test.AngularY,0),$"{test.Name} angular velocity"); + Near(result.Body.Impulse,Vector3.Zero,$"{test.Name} consumes impulse"); + var expectedAcceleration=test.Geometry ? test.Supported ? Vector3.Zero : test.Input.Acceleration : new Vector3(0,800,0); + Near(result.Body.Acceleration,expectedAcceleration,$"{test.Name} acceleration"); + Check(result.Body.Supported==test.Supported && result.Landing.HasValue==test.LandingY.HasValue,$"{test.Name} support/landing"); + if(test.LandingY is {} vy) + { + var observation=result.Landing!.Value; + Check(!observation.Supported && MathF.Abs(observation.Velocity.Y-vy)<.002f,$"{test.Name} callback sees old velocity/support"); + Check(observation.Acceleration.Y==0 && observation.Position==result.Body.Position,$"{test.Name} callback sees new root/acceleration"); + } + Console.WriteLine($"PASS original ordinary-body reference {test.Name}"); +} +var resting=physics.Step(Initial() with {Supported=true},1f/60); +Check(resting.Body.Supported && resting.Landing==null,"already supported must not emit landing37C again"); +Console.WriteLine("PASS prior support suppresses repeated landing callback"); +var empty=new OriginalBodyPhysics(new([])); +var rotation=empty.Step(Initial() with {AngularVelocity=new(0,.1f,0)},.5f); +Near(rotation.Body.Rotation,new(0,.05f,0),"rotation is integrated before small angular motion is suppressed"); +Check(rotation.Body.AngularVelocity==Vector3.Zero,"small angular suppression"); +var moving=empty.Step(Initial() with {Velocity=new(.125f,0,0),PublishedSpeed=1},1f/60,geometryEnabled:false); +Check(moving.Body.Velocity.X!=0,"nonzero published speed suppresses friction and small linear cutoff"); +Console.WriteLine("PASS angular integration and independent published speed cutoff"); +try { new OriginalBodyPhysics(new([floor with {StoredNormal=Vector3.UnitZ,MaterialId=61}])); + throw new Exception("unsupported special contacts accepted"); } +catch(NotSupportedException) { } +Console.WriteLine("PASS unsupported special-contact scene rejected"); +var falling=empty.Step(Initial(),1f/60); +var rising=empty.Step(Initial() with {Impulse=new(0,550,0)},1f/60); +Check(falling.CollisionPasses==0 && rising.CollisionPasses==1, + "falling vertical motion is added after horizontal dispatcher; rising motion is dispatched whole"); +Console.WriteLine("PASS positive-Y versus horizontal-first split"); +var ceiling=new CameraRayPolygon(new(new(-100,100,-100),new(100,100,100),new(100,100,-100)), -Vector3.UnitY); +var roof=new OriginalBodyPhysics(new([ceiling])); +var roofHit=roof.Step(new(new(0,80,0),new(0,920,0),new(0,100,0),Vector3.Zero),1f/60,10,1); +Near(roofHit.Body.Position,new(0,90,0),"ceiling candidate published after terminal callback370"); +Check(roofHit.Contact==ceiling && roofHit.Body.Velocity.Y==0 && roofHit.Body.Acceleration.Y==0, + "370 clears positive vertical velocity and acceleration without landing"); +Check(!roofHit.Body.Supported && roofHit.Landing==null,"ceiling does not invent floor support"); +Console.WriteLine("PASS composed ceiling370 and support ownership"); +var wide=physics.Step(Initial(),1f/60,100); +Near(wide.Body.Position,new(0,126.5f,0),"live radius100 changes support offset as well as collision"); +var unclamped=empty.Step(Initial() with {Velocity=new(100,0,0)},.5f,friction:4,geometryEnabled:false); +Near(unclamped.Body.Velocity,new(-100,0,0),"source friction multiplier is not clamped"); +Console.WriteLine("PASS radius-dependent support and unclamped friction"); +var original=Path.GetFullPath(args.Length==1?args[0]:"../Original"); +var world=Mesh.LoadSceneJson("artifacts/extracted/VR04/scene.json"); +var level=GamLevel.Load(AssetPath.Resolve(original,"gam/VR04.gam")); +var start=level.FindStart()!; +var standing=AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase")); +var geometry=OriginalCameraRay.FromRouteScene(world,"VR04"); +LabSimulation Simulation(bool retained=false) => new(new(world),standing,start.Position,start.Rotation.Y, + (a,b)=>geometry.Trace(a,b),(a,b)=>geometry.TraceGeometry(a,b),OriginalStaticCollision.FromRouteScene(world,"VR04")) + {LevelCode="VR04",InputAfterPlayerUpdate=retained}; +var player=Simulation(); +Check(player.UsesOriginalBody && player.PublishedSpeed==0,"tutorial explicitly selects source body"); +for(var i=0;i<120;i++)player.Step(default); +Check(player.Grounded && player.Landings==0,"steady source support must not chatter"); +var sole=standing.Vertices.Min(v=>Vector3.Transform(v.Position,player.Model).Y); +Check(MathF.Abs(sole-player.Position.Y)<.001f,"modern sole/root render bridge remains explicit and stable"); +var rootBefore=player.ActorRoot; +player.Step(new(false,false,false,false,true)); +Check(player.PendingImpulse.Y==550 && player.Grounded,"controller queues takeoff after body"); +player.Step(default,false); +Check(player.PendingImpulse==Vector3.Zero && !player.Grounded && player.ActorRoot.Y>rootBefore.Y + && player.ControllerSteps==121 && player.PhysicsSteps==122,"body consumes jump without control ownership"); +Console.WriteLine("PASS tutorial root/visual bridge and control-independent pending jump"); +player=Simulation(); +for(var i=0;i<8;i++)player.Step(new(true,false,false,false,false)); +var published=player.PublishedSpeed; +Check(published>0 && published==player.Speed,"controlled tail publishes controller speed"); +player.PrepareForScript(); +Check(player.Speed==0 && player.PublishedSpeed==published,"preparation preserves previously published speed160"); +player.Step(default,false); +Check(player.PublishedSpeed==published,"raw control gate prevents new publication"); +player.Step(default); +Check(player.PublishedSpeed==player.Speed,"resumed controlled tail publishes again"); +Console.WriteLine("PASS tutorial published speed/preparation/control boundaries"); +player=Simulation(true); +Check(player.ApplyRetainedLevelState(new("LV1B",3,1,.6f,4)),"retained tutorial scalar state accepted"); +Check(player.PublishedSpeed==0 && player.Velocity==Vector3.Zero,"scene Init resets published body/controller motion"); +for(var i=0;i<300;i++)player.Step(LabSimulation.JetpackSmokeInput(i)); +Check(player.Bursts>0 && player.Travel>50 && player.MaximumRise>100 && player.Energy==20, + "retained input ordering keeps powered steering and VR04 energy exemption"); +Check(player.Grounded && player.Landings>0,"source tutorial powered flight returns to support"); +Console.WriteLine("PASS retained tutorial jetpack/steering/landing phases"); +player=Simulation(); +player.SetNoclip(true); +player.Step(new(false,false,false,false,false,Rise:true)); +var physicsSteps=player.PhysicsSteps; +player.SetNoclip(false); +player.Step(default,false); +Check(player.PhysicsSteps==physicsSteps+1 && player.PublishedSpeed==0,"modern noclip exits into source body with cleared motion"); +Console.WriteLine("PASS tutorial noclip returns to source body"); +Console.WriteLine("Ordinary body:20 groups passed; dynamic actors and special Player contacts remain separate."); diff --git a/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj b/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj index bf53ae0..c506e64 100644 --- a/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj +++ b/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj @@ -9,6 +9,10 @@ + + + + diff --git a/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj b/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj index 2271cbf..c5b17df 100644 --- a/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj +++ b/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj @@ -13,6 +13,10 @@ + + + + diff --git a/tests/test_body_composition_contract.py b/tests/test_body_composition_contract.py new file mode 100644 index 0000000..5fb930f --- /dev/null +++ b/tests/test_body_composition_contract.py @@ -0,0 +1,93 @@ +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT/'tools/binary')) +from body_composition_contract import can_publish, collect, phase_order + + +class BodyCompositionContractTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.report = collect(ROOT.parent/'Original') + + def test_original_body_identity_and_decisive_sites(self): + self.assertEqual(self.report['body']['file_offset'], '0x79d20') + sites = {site['name']: site for site in self.report['sites']} + self.assertEqual(sites['clamp_candidate_y']['bytes'], 'd9442420d81d086a4d00') + self.assertEqual(sites['delta_y_nonpositive_branch']['bytes'], 'f6c441753d') + self.assertEqual(sites['root_compare_w']['file_offset'], '0x7a176') + self.assertEqual(len(sites), 81) + + def test_disabled_integration_still_clears_support(self): + self.assertEqual(phase_order(integration_enabled=False), + ['read_previous_support', 'clear_current_support', 'integration_gate']) + self.assertEqual(phase_order(support_enabled=False, integration_enabled=False), + ['read_previous_support', 'integration_gate']) + + def test_rotation_impulse_acceleration_gravity_and_suppression_order(self): + order = phase_order(upward=True) + names = ('rotate', 'impulse_add', 'impulse_clear', 'acceleration_add', 'gravity_add', + 'velocity_to_delta', 'full_dispatch', 'support47b890', + 'published_speed_zero_friction', 'angular_suppression', + 'published_speed_zero_linear_suppression') + self.assertEqual(sorted(order.index(name) for name in names), [order.index(name) for name in names]) + + def test_nonpositive_vertical_motion_is_added_after_horizontal_response(self): + down = phase_order(upward=False) + up = phase_order(upward=True) + self.assertLess(down.index('horizontal_dispatch'), down.index('add_fall_y')) + self.assertLess(down.index('add_fall_y'), down.index('compare_previous_live_root_vec4')) + self.assertNotIn('add_fall_y', up) + self.assertNotIn('horizontal_dispatch', up) + + def test_collision_world_and_global_geometry_are_separate_gates(self): + collision_off = phase_order(collision_enabled=False) + world_off = phase_order(world_enabled=False) + geometry_off = phase_order(geometry_enabled=False) + self.assertNotIn('support47b890', collision_off) + self.assertNotIn('published_speed_zero_friction', collision_off) + self.assertIn('translate31c', collision_off) + self.assertNotIn('translate31c', phase_order(collision_enabled=False, translation_locked=True)) + self.assertIn('support47b890', world_off) + self.assertIn('published_speed_zero_friction', world_off) + self.assertNotIn('reset_static_context', world_off) + self.assertIn('reset_static_context', geometry_off) + self.assertIn('geometry_off_support_anchor_acceleration_velocity', geometry_off) + + def test_publication_compares_fresh_previous_and_live_root_vec4(self): + root = (1.0, 2.0, 3.0, 1.0) + self.assertTrue(can_publish(root, root)) + for component in range(4): + changed = list(root) + changed[component] += 1 + self.assertFalse(can_publish(root, changed)) + with self.assertRaises(ValueError): + can_publish(root[:3], root[:3]) + + def test_burst_and_support_share_live_radius_and_factor(self): + targets = {entry['slot']: entry['target'] for entry in self.report['tables']} + self.assertEqual(targets['0x110'], '0x471240') + self.assertEqual(targets['0x260'], '0x471b30') + self.assertEqual(targets['0x264'], '0x471b40') + self.assertEqual(targets['0x250'], '0x471af0') + self.assertEqual(targets['0x254'], '0x471b00') + self.assertAlmostEqual(self.report['constants']['factor'], 1.265, places=6) + + def test_init_restores_authored_speed_separately_from_controller_publication(self): + targets = {entry['slot']: entry['target'] for entry in self.report['tables']} + self.assertEqual(targets['0x114'], '0x471260') + self.assertEqual(targets['0x118'], '0x471270') + self.assertEqual(targets['0x268'], '0x471b50') + self.assertEqual(targets['0x26c'], '0x471b60') + sites = {site['name']: site for site in self.report['sites']} + self.assertEqual(sites['init_authored_speed114']['file_offset'], '0x706cf') + self.assertEqual(sites['init_publish_speed26c']['file_offset'], '0x706db') + self.assertIn('894138', sites['authored_speed_setter118_to_live26c']['bytes']) + self.assertNotIn('894138', sites['published_speed_setter26c']['bytes']) + self.assertEqual(self.report['constants']['constructor_authored_speed'], 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/binary/body_composition_contract.py b/tools/binary/body_composition_contract.py new file mode 100644 index 0000000..bdb31f1 --- /dev/null +++ b/tools/binary/body_composition_contract.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Read-only479D20 composition guards, grounded in retained REA body evidence.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import struct + +from checkpoint_script_state import EXE_SHA256, find_case, read_va +from pe_inspect import PE + +BODY_START = 0x479D20 +BODY_END = 0x47A32A +BODY_SHA256 = '5f4b05518bef5e5f0ecc3909ff0de0b43d2c7350c6beae0c4f797d3238a77fa1' +REA_BODY = 'ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0' + +SITES = ( + ('read_previous_support', 0x479D2E, 'ff9018020000'), + ('cache_previous_support', 0x479D34, 'a2495d6900'), + ('read_support_enabled_before_integration_gate', 0x479D3D, 'ff92c8010000'), + ('clear_current_support', 0x479D4E, 'ff901c020000'), + ('integration_gate', 0x479D58, 'ff9210020000'), + ('disabled_integration_return', 0x479D60, '0f84bd050000'), + ('geometry_global_gate', 0x479DDA, '381de5694f00'), + ('geometry_enabled_anchor', 0x479DE4, '8b1653680050c3c6538bceff92f4020000'), + ('geometry_disabled_support_true', 0x479DF9, '6a018bceff901c020000'), + ('geometry_disabled_anchor_current_y', 0x479E03, '8b4424408b165350538bceff92f4020000'), + ('geometry_disabled_inverse_gravity_y', 0x479E14, 'd90504fc5c00'), + ('geometry_disabled_acceleration_xyz', 0x479E26, 'ff9278020000'), + ('geometry_disabled_velocity_y_zero', 0x479E54, 'ff97c4020000'), + ('read_angular_velocity', 0x479E63, 'ff92ac020000'), + ('rotate_before_impulse', 0x479EAC, 'ff9034030000'), + ('read_pending_impulse', 0x479EBB, 'ff9284020000'), + ('add_pending_impulse', 0x479EE5, 'ff97cc020000'), + ('consume_pending_impulse', 0x479EF2, 'ff928c020000'), + ('read_acceleration', 0x479F01, 'ff9070020000'), + ('add_acceleration', 0x479F4A, 'ff92cc020000'), + ('add_gravity', 0x479F7E, 'ff90cc020000'), + ('read_final_velocity', 0x479F8D, 'ff92bc020000'), + ('collision220_gate', 0x479FD6, 'ff9020020000'), + ('world1d0_gate', 0x479FE8, 'ff92d0010000'), + ('reset_last_polygon', 0x47A038, '891d4c5d6900'), + ('reset_nearest_face130000', 0x47A03E, 'c7055c5d690000e8fd47'), + ('reset_nearest_edge_radius', 0x47A062, 'd91de0fb5c00'), + ('capture_previous_root', 0x47A084, 'ff90fc020000'), + ('delta_y_compare_zero', 0x47A08A, 'd90514d94800d9442430d8d9'), + ('reset_auxiliary_collision_state', 0x47A096, '891d845d6900'), + ('delta_y_nonpositive_branch', 0x47A09E, 'f6c441753d'), + ('positive_full_dispatch', 0x47A0D6, 'e8d5130000'), + ('nonpositive_horizontal_dispatch', 0x47A10F, 'e89c130000'), + ('add_vertical_after_horizontal', 0x47A114, 'd944243cd844244c83c41cd95c2420'), + ('read_previous_root_after_callback', 0x47A12C, 'ff92f8020000'), + ('read_live_root_after_callback', 0x47A13D, 'ff9210030000'), + ('root_compare_x', 0x47A143, 'd9078bc8d819'), + ('root_compare_y', 0x47A154, 'd94704d85904'), + ('root_compare_z', 0x47A165, 'd94708d85908'), + ('root_compare_w', 0x47A176, 'd9470cd8590c'), + ('clamp_candidate_y', 0x47A187, 'd9442420d81d086a4d00'), + ('clamp_candidate_y_store', 0x47A198, 'c74424200050c3c6'), + ('publish_candidate314', 0x47A1C4, 'ff9014030000'), + ('world_disabled_capture_previous', 0x47A1FA, 'ff92fc020000'), + ('world_disabled_translate', 0x47A220, 'ff921c030000'), + ('post_motion_support_gate', 0x47A22A, 'ff90c8010000'), + ('post_motion_support', 0x47A235, 'e856160000'), + ('read_published_speed_for_friction', 0x47A241, 'ff9268020000'), + ('friction', 0x47A25A, 'e8d1000000'), + ('collision_disabled228_gate', 0x47A264, 'ff9228020000'), + ('collision_disabled_translate', 0x47A28E, 'ff921c030000'), + ('suppression_scale', 0x47A298, 'ff9030020000'), + ('angular_suppression_inclusive', 0x47A2C5, 'f6c441740d'), + ('angular_suppression_zero', 0x47A2D1, 'ff92b4020000'), + ('linear_suppression_inclusive', 0x47A2FA, 'f6c4417424'), + ('linear_suppression_published_speed', 0x47A303, 'ff9268020000'), + ('linear_suppression_zero', 0x47A31D, 'ff90c4020000'), + ('ctor_suppression_scale_half', 0x46FE01, '680000003f8bcde813130000'), + ('player_friction_point8', 0x4373B0, '68cdcc4c3f'), + ('player_friction_setter', 0x4373BD, 'e8ee9d0300'), + ('friction_authored_to_live24c', 0x4711B0, '8b4424048b1150894128ff924c020000c20400'), + ('jimmy_postload_radius60', 0x4236A3, '6800007042'), + ('jimmy_postload_factor1265', 0x4236B3, '6885eba13f'), + ('air_helper_complete_to_interface', 0x437FA3, '8dbec0000000'), + ('burst_radius100', 0x4384E4, '680000c842'), + ('burst_live_radius264', 0x4384F3, 'ff9264020000'), + ('held_landing_radius60', 0x4386C1, '6800007042'), + ('held_landing_live_radius264', 0x4386C8, 'ff9264020000'), + ('authored_radius_to_live264', 0x471240, '8b4424048b1150894134ff9264020000c20400'), + ('live_radius260', 0x471B30, 'd9815c010000c3'), + ('live_radius264', 0x471B40, '8b44240489815c010000c20400'), + ('live_support_factor250', 0x471AF0, 'd98154010000c3'), + ('live_support_factor254', 0x471B00, '8b442404898154010000c20400'), + ('ctor_zero_register', 0x46FC08, '33db'), + ('ctor_authored_speed_zero', 0x46FE51, '538bcde817140000'), + ('authored_speed_getter114', 0x471260, 'd94138c3'), + ('authored_speed_setter118_to_live26c', 0x471270, '8b4424048b1150894138ff926c020000c20400'), + ('init_authored_speed114', 0x4706CF, 'ff9714010000'), + ('init_publish_speed26c', 0x4706DB, 'ff976c020000'), + ('published_speed_getter268', 0x471B50, 'd98160010000c3'), + ('published_speed_setter26c', 0x471B60, '8b442404898160010000c20400'), +) + +TABLES = ((0x100, 0x4711E0), (0x110, 0x471240), (0x248, 0x471AD0), + (0x24C, 0x471AE0), (0x250, 0x471AF0), (0x254, 0x471B00), + (0x260, 0x471B30), (0x264, 0x471B40), (0x114, 0x471260), + (0x118, 0x471270), (0x268, 0x471B50), (0x26C, 0x471B60)) + + +def phase_order(*, support_enabled=True, integration_enabled=True, + geometry_enabled=True, collision_enabled=True, world_enabled=True, + translation_locked=False, upward=False): + """Control-flow projection only; no numeric/body or native execution claim.""" + phases = ['read_previous_support'] + if support_enabled: + phases.append('clear_current_support') + phases.append('integration_gate') + if not integration_enabled: + return phases + phases.append('anchor_far_below' if geometry_enabled else 'geometry_off_support_anchor_acceleration_velocity') + phases.extend(('rotate', 'impulse_add', 'impulse_clear', 'acceleration_add', 'gravity_add', 'velocity_to_delta')) + if collision_enabled: + if world_enabled: + phases.extend(('reset_static_context', 'capture_previous_root', + 'full_dispatch' if upward else 'horizontal_dispatch')) + if not upward: + phases.append('add_fall_y') + phases.extend(('compare_previous_live_root_vec4', 'conditional_clamp_y_publish314')) + else: + phases.extend(('capture_previous_root', 'translate31c')) + if support_enabled: + phases.append('support47b890') + phases.append('published_speed_zero_friction') + elif not translation_locked: + phases.append('translate31c') + phases.extend(('angular_suppression', 'published_speed_zero_linear_suppression')) + return phases + + +def can_publish(previous_root, live_root): + """Finite Vec4 equality predicate47A143..47A181, after contact callback.""" + if len(previous_root) != 4 or len(live_root) != 4: + raise ValueError('Source publication comparison is Vec4') + return all(a == b for a, b in zip(previous_root, live_root, strict=True)) + + +def collect(original): + pe = PE(find_case(Path(original), 'Neutron.exe')) + digest = hashlib.sha256(pe.data).hexdigest() + if digest != EXE_SHA256: + raise ValueError('Unexpected original executable identity') + body = read_va(pe, BODY_START, BODY_END-BODY_START) + if hashlib.sha256(body).hexdigest() != BODY_SHA256: + raise ValueError('Changed body integration instructions') + sites = [] + for name, va, expected in SITES: + actual = read_va(pe, va, len(bytes.fromhex(expected))) + if actual.hex() != expected: + raise ValueError(f'Changed source site {name} at {va:x}') + sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=expected)) + factor = struct.unpack('