diff --git a/AGENTS.md b/AGENTS.md index 591e454..8ac23f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,3 +41,10 @@ documented in docs/checkpoint/review.md. Pause feature expansion; use the playab docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay changes. Only evidence probes or directly evidenced corrections belong in this checkpoint; distinguish static recovery, port tests and original runtime evidence. + +Local REA/Ghidra is available through scripts/rea.sh; see docs/rea.md for the +ignored launcher environment and JDK paths. Existing client MCP registration was +not changed. Use generated copies, preserve complete Evidence/snapshots, and keep +static decompilation distinct from source execution. Current C3 continuation: +docs/checkpoint/control-phase-implementation.md; remaining body/wrapper/camera gates +are in its final section and the implementation ledger. diff --git a/README.md b/README.md index 3dd086a..3232f31 100644 --- a/README.md +++ b/README.md @@ -175,3 +175,8 @@ use Wine, DirectX or OpenGL. See `docs/reference-testing.md` for actual results. All generated extraction output, local SDK/native dependencies, captures and packages are ignored by the nested local Git repository. Never configure a remote, upload assets, or overwrite the original installation. + +Native reverse engineering uses the local REA/Ghidra launcher separately from +runtime builds; see [local analysis setup](docs/rea.md). Current source-backed +cutscene control/body phase findings are in +[control-phase implementation](docs/checkpoint/control-phase-implementation.md). diff --git a/docs/architecture.md b/docs/architecture.md index f35be5b..b59574b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -190,3 +190,16 @@ all physics/AI/render fields. The detailed contract, phase limits and original component probe are in checkpoint/retained-player-body.md; companion/shadow resets and full availability tails have separate reports. Uncontrolled physics and exact appended-helper traversal remain next scheduler boundaries. + +## Player control versus frame ownership + +PlayerSceneBinding connects authored preparation/transform events to the player +adapter. Body integration and owned fire run without player control; only input +and movement math are gated. CAM/MCA/AI preparation has distinct order and operates +on the prior raw owner, while Force Control affects effective input. Ordinary +frame/modal/debug pauses stop all these phases. Scripted AI roots/yaw flow into +physics, and physical roots flow back to director/camera targets. Destination yaw +and queued work are not cleared by a transform setter. The original full wrapper, +registry, body response and morph clock are still not reconstructed by this bridge. +See checkpoint/control-phase-implementation.md. REA tooling is separate from +runtime architecture; setup/provenance are in rea.md. diff --git a/docs/checkpoint/README.md b/docs/checkpoint/README.md index 772aadf..ea5e150 100644 --- a/docs/checkpoint/README.md +++ b/docs/checkpoint/README.md @@ -23,6 +23,11 @@ The retained-field continuation adds [property reader](retained-streamer.md), [player body/scalar boundary](retained-player-body.md) and [companion/shadow resets](retained-companion.md). It corrects the earlier availability-prefix interpretation and implements bounded route scalar carry. +The next C3 continuation is [control phases](control-phase-implementation.md), +backed by [uncontrolled player](uncontrolled-player.md), +[physics eligibility](uncontrolled-physics.md) and +[cutscene preparation](cutscene-preparation.md). [REA setup](../rea.md) records +local Ghidra/JDK and Evidence/snapshot use. Evidence labels used throughout: diff --git a/docs/checkpoint/control-phase-implementation.md b/docs/checkpoint/control-phase-implementation.md new file mode 100644 index 0000000..6ebaf65 --- /dev/null +++ b/docs/checkpoint/control-phase-implementation.md @@ -0,0 +1,80 @@ +# C3 continuation: uncontrolled body and fire + +Implementation2026-10-26. Source contracts: uncontrolled-player.md, +uncontrolled-physics.md and cutscene-preparation.md. This replaces the port's +whole-player freeze on control loss with a bounded phase split. + +LabSimulation.Step consumes prior body state first. Input/controller math runs +only when Jimmy has effective control; fire ticks independently afterward. +The existing fresh/retained input ordering remains. Ordinary grounded radius60 +is reasserted before the movement gate, matching the supported wrapper path. +Grounded fire can expire while mode/jump/hold remain untouched by the skipped +controller. Queued impulses survive camera preparation and are consumed once by +the following body pass. Neither control loss nor restoration invents a key flush. + +PlayerSceneBinding connects raw-owner preparation events to speed/velocity and +supported gadget cleanup, and publishes the simulated root while uncontrolled. +Authored AI transforms update the body too, preventing a later physics publish +from overwriting the script's teleport. Destination yaw is preserved. Pitch/roll +remain director-owned; Jimmy's render/controller still uses the existing yaw +adapter. Initial MCA preparation occurs once, with its first-name guard; later +shots do not repeat it. AI and CAM use their own callback order. STOP notification +follows physical preparation. DEFAULT grants control without preparation. + +Force Control is a modern effective-input override; raw ownership still selects +source preparations/music. Noclip keeps its separate flight path. F1/modal/inspect +boundaries stop the whole frame, so body/fire do not accrue paused time. +Contact-triggered interactions retain the existing control gate pending C4. + +Counters now distinguish total Steps, PhysicsSteps, ControllerSteps and EffectSteps. +Total Steps also counts modern flight, which bypasses the physical/effect phases. +The console report exposes these counts; a cutscene's nonzero total count does +not mean Jimmy accepted input. `--smoke-carl-cutscene` asserts zero controlled +updates/jumps/turn/speed while physical/effect callbacks continue. The new +`--smoke-control-phases` seeds an airborne retained-fire fixture, holds movement +and jump through15 locked frames, checks falling/fire/energy without input, then +skips/restores control and verifies held-input movement resumes. This is a port +fixture, not an original end-to-end recording. Headless story pre-roll uses the +same binding/phase policy. + +## Verification and limits + +New managed tests cover queued impulse across preparation, uncontrolled fire and +tutorial immunity, independent grounded resets, CAM/MCA/AI order, body-before-STOP +observation, raw/effective ownership, later-shot behavior, held jump restoration +and authored teleport synchronization. Python adds9 source/projection tests. +The input-only lab replay now uses the same binding and waits through live +cutscenes with body/fire ticking. Its old coasting turn missed the narrow exit: +port snapshot root(318.11124,75.02122,770.8816), yaw47.52308, controlJIM1, +no shot/block and2290 wall hits. Braking with the actual Down input before large +heading changes restores the route (score150, owned jetpack, one practice No, +zero jumps,6 wall hits). No physics or task gate was changed to make that replay +pass. The provisional corner response remains a useful C4 investigation case. +Native Linux GTX1070 at1280x720 passes Carl/control-phase and F1/F3 tools/menu +checks with zero enabled Vulkan validation errors. Full integration/package +results are recorded in progress.md; native Windows remains separate. + +REA6.8.0/Ghidra12.1.4 source Evidence is retained under +artifacts/uncontrolled-phases/rea/. IDs: + +| Procedure | Evidence ID | +|---|---| +|475CA0 gameplay gate|ev_aa0b7db46894c10d2f28f76d0da1e568ef06253f3d6c8cf6b06fbef299602bab| +|479BC0 body traversal|ev_56b7e074ec8509d1c5b3576d02361ff051963b777d7ccb8259ed9c65dc2db52f| +|437940 movement gate|ev_de7097867d129a4232318e667e9496c6868cdb1da4b37a1f3304c94b0b101677| +|40E050 animated base|ev_03a109302788b85597e253293bbcb535c4080732e41cc828bb33d01d2b2da09a| +|462520 base body/rotation bridge|ev_f0a2e1fd465472295b272f2fdbfb6be4651aeb8c35d90dc2ca02a495ed359edd| + +These are static decompiler observations with unknown C++ types, not original +source or runtime.421FB0 maps correctly from file21FB0 but lacks an analyzed +procedure in this Ghidra profile; its pseudocode is unavailable, not evidence +that the source callback is absent. Existing guarded bytes/vtable/body hash remain +the authority for that callback. Partial batches preserve successful Evidence. + +Remaining: full424600 wrapper timers/UI/sound cleanup, base40E050/462520 +resource/transform/morph policies, collision-triggered ceiling cancellation, +scooter radius160 and other gadget/class cases, original body registration and +response, complete registry and engine cadence, shared viewport handoff and +original whole-game comparison. Calling the entire controller with empty input +would not implement these missing phases. Existing capsule/yaw/camera adapters +remain explicit; this chunk does not certify a complete scene scheduler. diff --git a/docs/checkpoint/coverage.md b/docs/checkpoint/coverage.md index 9927d9d..8b9aa5b 100644 --- a/docs/checkpoint/coverage.md +++ b/docs/checkpoint/coverage.md @@ -12,18 +12,18 @@ runtime comparison. Coverage does not mean implementation completeness. | 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. Other systems remain grouped; fixed60Hz policy. | S/M/R. Controlled player partial order implemented; full registry/cadence and uncontrolled-body preparation open. | C3 continue other callbacks and morph/control phases; C4 support/response remains separate. | +| 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 arithmetic; physics479D20 consumes queued impulse once before acceleration/gravity. | Controlled player consumes prior body state before callbacks; fresh/retained input order explicit. Fixed dt and custom yaw/model conventions remain. | S/P/M/R. Controlled partial phase split verified; uncontrolled/full registry and body response open. | Continue C3 uncontrolled phases, then C4 support/response. | | 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 response; support and quick magnitude; dynamic boxes; NC-shape registration exclusion. | Source support and box pieces around modern swept24-unit capsule, feet/root grounding and slide. | S/P/M/R. Response/masks/stairs/contact order not fully recovered; source radius60 is not port capsule24. | C4: isolate response and root convention; replace adapter behind route tests. | | 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. | Bounded synchronous director; baseline objective after records/actor batch. | S/M/R. Script callbacks recovered for route; generic class coverage and reentrancy incomplete. | C1: ordered objective notification; C2: per-actor Carl override. | -| CONTROL | Global5099E4 null during valid CAM/MCA; PlayerControlled completion target; DEFAULT447D..447F restores camera/UI/music. | Director raw ownership plus explicit debug effective override; player physics stops when uncontrolled. | S/M/R. Null control is not proof all objects/physics stop; scheduler gap remains. | Map raw ownership transitions against phase gates and deferred LOAD. | +| 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. | | CAMERA | Shared viewport; strict>1000 DEFAULT snap; source eye correction/gain; first wall-grid hit then general-grid FIFO; per-level far planes. | Static source query now integrated for the three route scenes; other scenes use provisional sweep. Separate chase/script eyes and merged clip maximum remain. | S/M/R. Query/kernel/counts tested; x87 boundaries, shared handoff/previous-eye and input branches open. | C5 next shared viewport/DEFAULT and complete follow state. | | AUDIO | CAM416776..E1 stops music; DEFAULT447F12..45 restarts; bank696008 / gate4F8434; handle47D890 polls inherited software duration and repeat+30. | Separate SDL streams, floating-file-duration cutscene completion, independent per-file SFX. | S/M/R (dummy streams). Source duration/allocation/play-failure/bank/attenuation lifecycle incomplete; speakers/native Windows timing not verified. | C6: explicit bank owner and software channel-clock tests; SDL queue-empty is not the source oracle. | | UI |406F50 selector/timer;4043D9 controlled clock;407070/O edge;404D97 practice resume.44 objective flags distinct from selector. | Timed objective subset, modal practice, modern UiViewport/debug. | S/M/R. Other flags/gadgets/highlights/cursor/energy/layout transitions open; source widescreen not recovered. | Keep modern scale policy separate; recover UI dispatcher/mode gates before expanding. | -| LOAD | CEditor deferred scene request; selective teardown/reuse; Init stored+11→live+139 resolves old-game deletion; Jimmy/Goddard retained. RETURN root/flags and per-object28→40C. | Reconstructed scene with retained input-order identity and bounded mode/hold/fire container; app-owned presentation. | S/P/M/R. Property stream and bounded scalar/companion resets closed; full body/helper timing and fades remain.50988A is editor R input. | Continue body registration/helper traversal and uncontrolled scheduling; other gadget/level branches remain gated. | +| LOAD | CEditor deferred scene request; selective teardown/reuse; Init stored+11→live+139 resolves old-game deletion; Jimmy/Goddard retained. RETURN root/flags and per-object28→40C. | Reconstructed scene with retained input-order identity and bounded mode/hold/fire container; app-owned presentation. | S/P/M/R. Property stream and bounded scalar/companion resets closed; full body/helper timing and fades remain.50988A is editor R input. | Continue full wrapper/body registration/helper traversal; other gadget/level branches remain gated. | | INVENTORY | PostLoad common prefix enables eight owned gadgets4→1, then VR01..08 disables1→4; full tail re-enables the practice gadget. LV1B disables1/7; other wire values preserved. | Availability pass now applied at level entry and verified across TSK tutorial/return; snapshots preserve raw values. | S/M/R. Full selected-gadget/UI and other level tails remain incomplete; bounded route mode/hold/fire carry is implemented. | Keep availability separate from ownership, task changes and arbitrary state carry. | | SAVE | TSK45FEE0 writer /4603F0 reader; records, arrays, return strings, stored departure root; queued460E70→460EA0. | Original-format round-trip and CLI save, scene snapshots; no full source save UI/load lifecycle. | S/M. Source reader duplicates matching task callback then all-entity420 post-task hook; this is distinct from Jimmy placement PostLoad423A90. Current fresh-director path differs. | C7 after C1/C2; test repeated callbacks before adopting loader behavior. | | CHECKPOINT | Pickup42AF00 stores+1E38 root/+1E48 level separately from+9A8 RETURN root. | Capture exposed, not used for return; source capture consumers unknown. | S/M. Do not interpret as death/respawn until read consumer found. | Track unresolved consumer; no speculative gameplay. | diff --git a/docs/checkpoint/cutscene-preparation.md b/docs/checkpoint/cutscene-preparation.md new file mode 100644 index 0000000..3831750 --- /dev/null +++ b/docs/checkpoint/cutscene-preparation.md @@ -0,0 +1,40 @@ +# Cutscene preparation and control handoff + +2026-10-26, static EXE evidence. SHA256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +VAs below use400000 preferred base; raw offset=VA−400000 at these sites. +cutscene_preparation.py records exact bytes/virtual targets; its projection is +interpretation, not source execution. Primary completed the investigator's helper, +corrected its sign-extended byte−1 comparison anchor and added tests/report. + +| Boundary | Proven order and source sites | +|---|---| +|CAM with PlayerControlled=NULL|Guard prior raw owner416635;43841665D→41041666B→flatten logical/cached Euler(0,yaw,0)41667E..4166E5→game118(NULL)4166F4. Target lookup occurs later416754. Preparation can precede a missing target/sound failure.| +|Initial MCA activation|First target name `none` guard431300 exits before preparation. A non-none name reaches initial target/animation prelude; missing lookup can continue. Prior owner guard431502;410431512→flatten Euler431525..431578→438431598→game118(NULL)4315A7. Per-shot helper invoked431600.| +|Later MCA shot|CompleteE0→431750; target/sound/animation work, no410/438 or raw control clear. The sound−1 check431771 sign-extends one immediate byte, not a four-byte immediate.| +|AI PlayerControlled=NULL|Prior raw owner guard40C4AD→41040C4B9→game118(NULL)40C527; no438 or flatten. Named AI ownership remains an older port interpretation requiring broader proof.| +|DEFAULT|447D5C checks whether Jimmy already owns raw control;447E27 restores via118 without410/438. No new key-release boundary is implemented. Music uses authored ownership independently of debug force.| + +Jimmy410→42AFC0 calls43A750 first: clear speed608 and velocity XYZ2C4; stop +saved sound148; then request complete150(`STOP`) at42AFDE/E5. Body changes precede +the STOP animation notification. Mode, jump, hold, pending impulse, acceleration +and fire timer are separate. Existing isolated43A750 probe validates its limited +write set with invalid sound handle; it does not execute full camera activation. + +Jimmy438→42AE00 invokes selected-gadget cleanup178→427FF0 and sets interface1D65 +and global4F8182. Supported no-selection/jetpack cleanup clears selection; other +gadget cases are not blanket resets (retained-return-cleanup.md). The port exposes +these ordered boundaries, implements supported player motion/selection and logical +orientation changes, and leaves other class/UI/resource side effects explicit. + +Authored AI movement has separate setters: marker root310 at40C732→target314 +at40C757; yaw40C88F..40C961 uses174→4716D0, writes authored/live Euler and cached +Euler, and does not write movement destination yaw61C. PlayerSceneBinding applies +root/yaw to the simulation without erasing pending motion or destination yaw. +Only actual transform writes emit that event; animation-only changes do not. + +The port's skip fast-forward, malformed/reentrant activations, MCA's initial +animation prelude, all other class virtual effects and full shared camera state +are not certified by this chunk. Existing named control behavior is preserved, +not newly recovered here. Three byte/projection tests and coupled managed +director/body tests guard the implemented ordering and boundaries. diff --git a/docs/checkpoint/implementation-plan.md b/docs/checkpoint/implementation-plan.md index 729b8ad..bd17e91 100644 --- a/docs/checkpoint/implementation-plan.md +++ b/docs/checkpoint/implementation-plan.md @@ -105,3 +105,20 @@ allowed where it resolves a core-system question, without waiting for every leve Linux launch from /tmp verifies nondefault tutorial/RETURN scalar boundaries and body resets. Release validation unavailable; source GPU checks enabled. Native Windows runtime remains unverified for this chunk. Preserved baseline untouched. + +- C3 control continuation: gated movement/input independently of eligible body and + fire; explicit CAM/MCA/AI raw-owner preparations and body-before-STOP order; + initial MCA target-none returns, later shots do not repeat preparation. Scripted + player transforms synchronize into body state. Grounded ordinary radius is outside + the control gate. Full wrapper/base/ceiling/class effects remain open. +- Same binding is exercised by the input-only lab route; modern replay now brakes + before large turns instead of coasting past the narrow door. Task/score/inventory/ + contact assertions remain. The observed corner behavior is retained as C4 input. +- Local REA/Ghidra/full-JDK setup and batch Evidence/snapshot workflow verified. + Five selected source procedures cross-check gates/base calls. Missing analyzed + fire entry is recorded; no target execution or client registration change. + +- Final C3 integration: full scripts/test.sh passes with93 Python checks,24 movement + groups, remaining managed checks and the binding-based input-only lab route, + 27 zero-error enabled-validation GPU renders, SDL dummy lifecycle and539 hashes. + Native GTX1070 Carl/control/F1/F3 commands pass; native Windows remains separate. diff --git a/docs/checkpoint/player-phase-implementation.md b/docs/checkpoint/player-phase-implementation.md index bb2189c..8b5b4c8 100644 --- a/docs/checkpoint/player-phase-implementation.md +++ b/docs/checkpoint/player-phase-implementation.md @@ -6,6 +6,11 @@ It does not replace the entire scene scheduler, collision response or animation clock. Evidence is in `input-frame-bridge.md`, `lab-registry.md`, the new `player_phase_evidence.py`, and the follow-up `level-game-lifetime.md`. +Continuation: `control-phase-implementation.md` now separates uncontrolled body/ +fire from controlled movement, with source-specific preparation boundaries. The +older unresolved-control wording below describes this chunk's original boundary; +full wrapper/base/morph work and the scene scheduler still remain open. + ## Source contract and implementation EXE47E554 calls479BC0 physics before473740 game-object callbacks47E582;473770 diff --git a/docs/checkpoint/retained-player-body.md b/docs/checkpoint/retained-player-body.md index 006ecd1..8233926 100644 --- a/docs/checkpoint/retained-player-body.md +++ b/docs/checkpoint/retained-player-body.md @@ -6,6 +6,10 @@ Preferred-base EXE VAs below map to raw offset VA−400000; the helper independe maps PE sections. Originals remain untouched. Static recovery, isolated component execution and port tests are separate evidence categories. +Continuation: uncontrolled body/fire and cutscene preparation are now implemented +in a bounded C3 chunk; see control-phase-implementation.md. Full wrapper/base +policies, body response and scene scheduling remain separate gates. + ## Closed callback chain Read `retained-streamer.md`, `retained-return-cleanup.md` and diff --git a/docs/checkpoint/review.md b/docs/checkpoint/review.md index 5c7bdbd..c63ef87 100644 --- a/docs/checkpoint/review.md +++ b/docs/checkpoint/review.md @@ -10,6 +10,11 @@ availability conclusions are superseded. See `player-phase-implementation.md`, `level-game-lifetime.md` and the current ledger. The exit review below preserves the evidence/verification boundary at the original checkpoint milestone. +The control-phase continuation now separates uncontrolled body/fire from controlled +movement and implements bounded ordered preparations. Local REA/Ghidra static +Evidence cross-checks the original gates. See control-phase-implementation.md and +rea.md; full wrapper/collision/camera work is still outstanding. + The initial architecture checkpoint is complete: all requested core systems have source anchors, state owners/lifetimes, route interactions, baseline comparison, explicit unknowns and bounded implementation actions. Feature expansion remains diff --git a/docs/checkpoint/uncontrolled-physics.md b/docs/checkpoint/uncontrolled-physics.md new file mode 100644 index 0000000..a59bfa3 --- /dev/null +++ b/docs/checkpoint/uncontrolled-physics.md @@ -0,0 +1,49 @@ +# Physics eligibility while control is absent + +Static C3 follow-up,2026-10-26. Original EXE SHA256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Preferred-base VAs map to raw offset VA−400000 here; the helper independently +PE-maps and guards19 instruction sites and6 virtual targets. Investigator supplied +the initial trace; primary completed/checked it after investigator capacity ended. +No original physics routine was executed for these assertions. + +## Separate owners and gates + +47E531 invokes475CA0 before the frame's physics pass47E554→479BC0.475CA0 reads +5099AB and4F641C only: return `!5099AB ||4F641C`. It does not read controlled +pointer5099E4. The viewport additionally requires a supervisor and supervisor+8C +clear; valid QPC dt remains a separate frame condition (loop-motion.md). + +Route game complete168 resolves44E450 on LV1B/VR04/LEV1. It stores its argument +to5099AB at44E458 and clears4F641C at44E465. Jimmy PostLoad calls168(0), while +modal callers use this state separately. Control118 instead resolves475A40 and +writes5099E4. Clearing control is not equivalent to calling168 to suspend play. + +479BC0 tests body-list enable4F69E7 at479BE9, walks registered payloads rooted +695D3C and calls479D20 at479C2B. No raw-owner predicate selects that traversal. +479D58 calls body210→4719F0, reading interface13E; false skips integration. +Generic construction calls471030(1) at46FDDF..46FDE3, storing authored byte16 +and invoking214→471A00 to set live13E. Init470612/47061B copies authored16 +through getterB4→471020 and setter214. This is the integration gate, not the +similarly named GAM `CanMove` descriptor used by animated-object behavior. + +When eligible, the body consumes pending impulse479EBB..479EF2, acceleration +479F01 and velocity479F8D regardless of Jimmy's raw ownership.43A750 camera +preparation clears speed/velocity XYZ but does not clear queued impulse or +acceleration; the earlier isolated body probe covers that narrow write contract. +CAM/MCA control transfer does not disable13E in the inspected paths. + +## Implementation boundary + +The port now runs its existing player body adapter during ordinary cutscene +control locks, skips controlled movement/input, and still ticks owned fire. +F1, practice, inspection and inactive-window policy remain whole-frame boundaries. +This does not reconstruct all supervisor/override/body-list modes, contact masks, +registration cleanup, static/dynamic response or source cadence. Source support +flags can differ from the provisional capsule's grounded flag. Other actor bodies +still use their existing subsystem adapters; this is not a full-scene scheduler. + +`test_uncontrolled_physics.py` checks immutable gates/targets and a deliberately +separate predicate projection across NULL/Jimmy/other control and disabled gates. +Projection tests are not original execution. REA/Ghidra independently decompiled +475CA0 and479BC0; see rea.md and control-phase-implementation.md for Evidence IDs. diff --git a/docs/checkpoint/uncontrolled-player.md b/docs/checkpoint/uncontrolled-player.md new file mode 100644 index 0000000..ec64c81 --- /dev/null +++ b/docs/checkpoint/uncontrolled-player.md @@ -0,0 +1,122 @@ +# Uncontrolled Jimmy and owned jetpack-fire callbacks + +Static C3 continuation,2026-10-26. Original `Neutron.exe` SHA256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +All addresses below are preferred-base EXE VAs; inspected raw offsets are +VA−400000, independently checked through PE sections by the helper. No original +code was executed for this report. Original files remain read-only. No runtime +files were changed by this independent investigation. + +## Result + +Null control is not a gate on the entire Jimmy object or on his owned fire object. +Jimmy's movement math has an explicit **identity** gate inside437940. Fire421FB0 +does not read the raw controlled pointer at all: after the common gameplay gate +and base work, it tests its owner/support/timer and follows the owner. Physics is +an earlier separate pass; its exact activation gates belong to the companion +physics investigation. Do not infer physics freeze from the movement return. + +## Jimmy caller chain and work before the movement gate + +Registry473740 invokes interface slot10→470280, which stores dt and dispatches +normal3C4→424600 (table4A373C). Source editor/supervisor mode uses3C8 instead; +this report covers normal gameplay. Jimmy game-interface pointer is complete+C0. + +424600 increments global4F8408 by dt before inspecting control. At42460A it +loads5099E4;424622 bypasses only a cleanup prefix when that pointer is nonnull. +Raw NULL therefore performs UI/resource cleanup, resets interface1D74 and stops +saved sounds interface974/97C through47D7A0, assigning−1. It does **not** return +from the object update. Other actors being controlled skip this NULL-only prefix +but still fail Jimmy's later identity gate. + +42469F then queries support218→458960 regardless of control. On support, gadget0 +uses radius160; ordinary selected gadget uses radius60 at4246DC. The callback +also has its own menu/modal branch42471F..424751, character timers and class +callbacks. Those are separate from ownership. At424C34 it calls437940; after +that returns, it continues through complete1C8→424E80 and position/history/class +callbacks. Complete1C8 has a raw-NULL menu-hide early return of its own. + +Consequently “skip all Jimmy update when uncontrolled” and “call the whole +controller with no keys” are both broader policies than the source gate. + +## Movement437940: exact gate placement + +| Order / site | Recovered operation | +|---|---| +|437946..43794D|Call475CA0; false jumps straight437C33. This is a common gameplay predicate, not the controlled pointer.475CA0 returns false only when5099AB!=0 and4F641C==0; meanings of these two flags are not assigned here.| +|437953..437964|Increment interface774 timer before raw ownership comparison.| +|43796A|Base40E050 update runs before raw ownership comparison. Its own resource/transform/animation-end policies remain separate.| +|43796F..437A0F|Conditional interface7A8 timer/restore work precedes ownership. This is not the jump-hold7B4 field.| +|437A1B..437A2B|Compare raw5099E4 with Jimmy's game interface; mismatch jumps437C33, the return epilogue. Normal allocated complete pointer is nonzero, so the source complete-to-interface idiom gives this+C0 interface exactly.| +|437A31..437A43|Two additional flag guards4F83E0 and4F8181 can skip the same controller tail even when Jimmy is controlled. Their full semantics are outside this bounded audit.| +|437A49 onward|Read movement mode704, jump-held callback and support; choose ground/air application. Grounded released path437B9E clears jump728, mode704 and turn614. These writes are **after** the ownership gate.| +|437BC5 /437C1C|Invoke complete134→437F90 air/jetpack math or complete130→437C40 ground math. These are complete-object slots, not same-numbered game-interface getters.| +|437C2D|Write final speed via game-interface26C only after the controlled tail.| + +Uncontrolled movement therefore does not itself consume held jump, clear grounded +jump/mode/turn, compute new steering/velocity/extra acceleration, or perform the +final speed publication. Existing body state can still be consumed by the earlier +physics pass. Control-preparation410's explicit speed/velocity clear is a different +event and must not be expanded into a per-frame reset of every field. + +## Fire421FB0: independent owner and timer + +Owned fire uses complete+C0 interface4A3160; its normal3C4 target is421FB0. +Owner is interface5FC=complete6BC; timer is interface600=complete6C0. + +| Site | Recovered operation | +|---|---| +|421FB6..421FBD|Same475CA0 gate. False returns4220BC.| +|421FCA|Base40E050 callback before owner test.| +|421FCF..421FD7|Read owner5FC; no owner skips timer/energy/follow.| +|421FDF..421FE9|Query owner's support218; true sets remaining time0. Jimmy's support218 resolves458960, which accepts force-support interface4A0 or reads cached support13F via471A10.| +|421FF3..422003|Subtract dt and store timer, including when already zero/negative.| +|422009..422049|Strict positive result takes active visibility/energy path; nonpositive hides through complete58(1). Positive path may request complete58(0), then calls42A920 with−dt×.5. The complete70 visibility-related check is not a control gate.| +|42204C..4220B6|Copy owner logical position310 and Euler328 into fire314/32C even when timer is inactive/hidden.| + +Energy helper42A920 skips numeric VR01..VR08, otherwise adjusts global4F83D4 and +clamps0..100; no controlled-pointer condition. A running timer can continue with +zero energy, and landing zeroes it before subtracting dt. A controller that is +skipped while raw NULL does not make the effect skip as well. The full421FB0 +body checksum and absence of the5099E4 address are guarded by the helper; base +resource/animation work is not replaced with a claim that all indirect operations +are independent of every global state. + +## Collision-side cancellation still runs outside movement ownership + +Before calling437940,424600 reads vertical velocity and, if positive, invokes +complete1A4→425170. This source ceiling-ray/response path is outside raw ownership +gates. On a hit it can change body velocity and invoke complete1E0→425120. In +mode1,425120 clears jump complete7E8, requests `FALL`, zeros owned fire6C0 if +present, then invokes complete140. Thus fire can be cancelled by collision during +a cutscene even though ownership alone does not cancel it. Complete1A8→4252E0 +also refreshes a source distance cache before437940. These are not yet a recovered +full collision implementation, and must not be silently replaced by calling +controlled air math during a cutscene. + +After movement, complete1B0→425490 can maintain/replay a position history under +its own flag; complete1B4→4255C0 has another flagged class-specific effect. Their +full behavior remains outside this movement/effect split. A limited implementation +must state that it does not reproduce every branch of424600. + +## Port consequence and verification boundary + +The audited port gates its entire LabSimulation.Step on effective control, so it +freezes both body and fire when uncontrolled. A justified partial correction is +an explicit body/effect tick while suppressing Jimmy input/controller math, with +control preparation applied at the actual CAM/MCA events. Do not send default +input through StepPlayer: the grounded-release and steering changes above would +run despite the source early return. Do not treat raw NULL as F1/practice pause. +Modern force-control/noclip policy stays distinguishable from original ownership. + +Four Python tests verify47 instruction sites,12 vtable targets and two whole-body +hashes, plus source-gate/state projections with nondefault timers, absent owner, +raw NULL/other actor, strict expiry and VR energy immunity. Run +`python3 -m unittest discover -s tests -p test_uncontrolled_player.py -v` or +`python3 tools/binary/uncontrolled_player.py ../Original` for reproducible JSON. +These tests interpret immutable code; they do not execute the original callback, +validate original cadence, prove full body response or compare complete cutscenes. + +Remaining: full class-specific424600 branches, pre-control base/timer semantics, +source collision-side ceiling/distance behavior, complete animation-end timing, +global475CA0 flag owners and original end-to-end runtime comparison. diff --git a/docs/compatibility.md b/docs/compatibility.md index fa03445..ad5ef27 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -3,6 +3,23 @@ Compilation, native runtime, original behavior and full feature completion are separate evidence categories. **The game is not fully reconstructed/playable yet.** +Control-phase continuation (2026-10-26): body/fire eligibility and ordered raw +preparations are source-byte guarded separately from port behavior. Targeted24 +movement groups, coupled director/preparation tests and the airborne control +fixture pass. Native Linux GTX1070 at1280x720 passes Carl/control-phase, F1 pause/ +Force Control and F3/tools/same-window checkpoint checks, all with enabled Vulkan +validation and zero errors. The input-only route uses the actual binding and +Down braking at turns; source score/task/inventory/contact checks still pass. +Detailed gaps: checkpoint/control-phase-implementation.md. Native Windows and +original whole-game comparisons remain unverified for this chunk. +Full scripts/test.sh passes in artifacts/uncontrolled-phases/integration-final.log: +93 Python checks,24 movement groups plus remaining managed groups,27 zero-error +GPU renders with enabled validation, SDL dummy checks and539 unchanged hashes. +REA6.8.0/Ghidra12.1.4 decompiled five selected procedures locally using a generated +copy; complete Evidence is retained.421FB0 lacked a recognized procedure; that +limit is recorded without replacing its existing byte/vtable evidence. Static +pseudocode is not original execution. See rea.md for local installation and CLI. + Retained-state continuation (2026-10-26):14 new source-evidence tests and22 movement groups cover named property loading, cleanup/Init/PostLoad/control boundaries and bounded route scalar carry. Corrected full tutorial/lab gadget diff --git a/docs/decisions.md b/docs/decisions.md index 6e6e368..272661e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -151,3 +151,17 @@ practice gadget after the shared disable pass; LV1B disables1/7. Correct the implementation and expectations from the later dispatch/call evidence and retain the earlier report as a scoped historical audit with a correction. + +31. **Control identity gates movement, not the whole player.** Run eligible body + physics and owned fire while raw control is absent; skip input/controller + tail. Preserve queued work and distinct resets. Apply source-specific ordered + preparations at CAM/MCA/AI activation; initial MCA target-none returns without + completion, and later shots do not repeat preparation. STOP notification follows + body clear. Authored transforms update the real player body. Keep modern + Force/Noclip and frame pauses separate from raw ownership. Other wrapper/class + callbacks and collision remain evidence gates rather than empty-input guesses. +32. **Use local REA as an additional static evidence source.** Keep Ghidra/JDK + and process environment local, analyze generated copies, retain complete + Evidence/profile/hash/snapshots and close owned sessions. CLI avoids changing + the existing MCP registration. Unknown procedure definitions remain unknown; + they do not invalidate byte/vtable evidence or imply missing game code. diff --git a/docs/progress.md b/docs/progress.md index 587dcb0..f4f3ea9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,54 @@ # Progress — 2026-10-26 +## Uncontrolled-player implementation and REA + +Continued C3 into source control/body/fire boundaries. Original475CA0/frame/body +eligibility is separate from controlled pointer5099E4. Movement437940 has an +identity gate after base/timer work;421FB0 fire has no raw-control gate. CAM, +initial MCA and AI preparation order differ; later MCA shots do not repeat it. +Source-byte reports/helpers/tests: uncontrolled-player.md, uncontrolled-physics.md +and cutscene-preparation.md under checkpoint/. Investigators supplied independent +player/control traces; primary completed physics and preparation work when agent +capacity ended. All file ownership is now primary. + +Implemented LabSimulation controlled-input/controller gates while existing body +physics and owned fire continue. Preparation clears speed/velocity only; queued +impulse/acceleration and mode/jump/hold/fire are independent. Ordinary grounded +radius60 is outside the movement gate. PlayerSceneBinding connects ordered raw +preparations and authored AI root/yaw; STOP observation follows physical clear. +An initial MCA with first target none returns instead of executing completion. +Force Control stays an effective override; preparations use authored ownership. +Headless story pre-roll uses the same phases; F1/practice/inspect still pause them. +Full wrapper/base transforms/ceiling response, other gadget/class effects and +registry/cadence remain explicit gaps in control-phase-implementation.md. + +Targeted movement24 groups, coupled director tests and the32-frame airborne +control fixture pass. Native Linux GTX1070 at1280x720 passes Carl/control phases, +F1 menu/Force Control and F3/tools/checkpoint reload, with zero enabled Vulkan +validation errors. The input-only lab replay now uses the actual binding; its +old coasting turn missed the narrow exit. Down braking before large turns reaches +outside with score150, one practice No, owned jetpack, zero jumps and6 wall hits. +No physical response/task gate was changed for that replay. A corner snapshot +is retained for C4. Logs: artifacts/uncontrolled-phases/. + +REA MCP connected but lacked native providers. Installed the verified official +Ghidra12.1.4 ZIP locally and extracted matching full Ubuntu JDK21 packages under +.tools (system Java21 was runtime-only). Existing Node24/public REA6.8.0 launcher +is selected by ignored .tools/rea.env and scripts/rea.sh. Client registration was +not changed. Local Unix IPC needed the approved execution allowance. Five source +procedures were decompiled and byte-cross-checked; complete Evidence/snapshots are +on disk.421FB0 maps correctly but has no recognized Ghidra procedure in this +profile; existing byte/vtable evidence remains authoritative. See docs/rea.md and +the control-phase report's Evidence IDs. No original game execution or new native +Windows runtime comparison is claimed by this setup. + +Final C3 validation: full scripts/test.sh passes (integration-final.log):93 +Python checks, all managed groups including24 movement, updated input-only route, +27 GPU render completions with zero enabled Vulkan validation errors, SDL dummy +lifecycle and539 unchanged originals. Coupled director tests include body-before- +STOP observation and the initial empty-MCA return. Four native window commands +pass (five scene renders) in native/*.log. No native Windows runtime is added. + ## Retained-state implementation continuation Read prompt.MD in full and resumed C3/C7. Three independent investigators owned diff --git a/docs/rea.md b/docs/rea.md new file mode 100644 index 0000000..65f39d3 --- /dev/null +++ b/docs/rea.md @@ -0,0 +1,59 @@ +# Local REA and Ghidra + +REA is an analysis dependency, absent from the packaged game's runtime. The +installed MCP tools connected successfully and opened a generated EXE copy with +the authoritative hash. Native decompilation initially lacked an engine. The +project-local CLI setup now works without changing the client's MCP registration. + +- REA6.8.0: existing public `scripts/rea.mjs` launcher in the user's npm cache. +- Existing Node24.22.1: configured through ignored `.tools/rea.env`; the login + shell's Node20 cannot load this CLI's zstd imports. +- Ghidra12.1.4: `.tools/ghidra_12.1.4_PUBLIC`, from the + [official pinned release](https://github.com/NationalSecurityAgency/ghidra/releases/tag/Ghidra_12.1.4_build). + Download ZIP SHA256 `ddac49f903da9d5bac833e5cc79395098b9c33cfd3279be5f31bd00387d2d4db` + verified before extraction. Its pinned README requires a full JDK21. +- Full OpenJDK21.0.12.1+1-1~24.04.4: matching Ubuntu JDK/JRE headless packages + downloaded with apt and extracted under `.tools/java`; no system installation. + JAVA_HOME is `.tools/java/usr/lib/jvm/java-21-openjdk-amd64`. The pre-existing + system Java21 was runtime-only. Adoptium metadata endpoint returned403; no + archive from that endpoint was installed. + +scripts/rea.sh reads local launcher settings from ignored `.tools/rea.env`, sets +local GHIDRA_INSTALL_DIR/JAVA_HOME and invokes the public launcher. For another +machine set NEUTRON_REA_NODE and NEUTRON_REA_LAUNCHER there, or provide `rea` on +PATH. This environment does not alter the already-running MCP server; native MCP +tools need those environment paths when that server next starts. CLI use is +already verified. No registration/setup rewrite was performed. + +```bash +mkdir -p artifacts/rea-copy +cp ../Original/Neutron.exe artifacts/rea-copy/Neutron.exe +scripts/rea.sh decompile "$PWD/artifacts/rea-copy/Neutron.exe" 0x475ca0 \ + --provider ghidra --snapshot "$PWD/artifacts/rea-copy/snapshot.json" \ + --format json --full-output > artifacts/rea-copy/gate.json +``` + +Use generated copies and keep complete Evidence with binary/profile identities. +For several functions, one local stdio session avoids re-importing the EXE for +each query: + +```bash +python3 tools/binary/rea_decompile_batch.py artifacts/rea-copy/Neutron.exe \ + artifacts/rea-batch-NEW 0x40e050 0x437940 0x479bc0 +``` + +The output directory must be new. The helper saves each complete reply, exports +successful Evidence and closes/snapshots its owned session. A per-function error +is retained separately; inspect it before claiming complete coverage. REA's +Ghidra bridge needs a local Unix socket, which the default Codex sandbox blocked; +the approved local execution allowance worked. This was a host IPC restriction, +not an analysis-timeout or engine-install failure. Target executable code is not +run by these static operations. Retained primitive queries are not a complete +Ghidra database or proof every function is recognized. + +Five selected routines were decompiled and cross-checked against existing byte +evidence. Fire421FB0 was not recognized as a procedure even with the correct +file-offset selector; keep that limitation explicit. Actual Evidence IDs and +gameplay interpretation are in checkpoint/control-phase-implementation.md. +Logs, readiness errors, complete replies, export bundles and snapshots are under +artifacts/uncontrolled-phases/rea/. Temporary native sessions were closed. diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 4a05153..3fea4b3 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -5,6 +5,10 @@ offsets, virtual addresses, API symbols or observed behavior. Decompiled output evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL probes and modern runtime checks are recorded separately. +- `checkpoint/control-phase-implementation.md`, `uncontrolled-player.md`, + `uncontrolled-physics.md`, `cutscene-preparation.md`: frame/body versus identity + gates, ordered CAM/MCA/AI preparation and bounded implementation. `rea.md` records + local tooling, Evidence and procedure-recognition limits. - `checkpoint/retained-player-body.md`, `retained-streamer.md`, `retained-return-cleanup.md`, `retained-companion.md`: complete named property read chain, bounded ordinary-load scalar/body resets, full tutorial availability diff --git a/docs/tasks.md b/docs/tasks.md index bae98bf..2052a44 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -74,9 +74,15 @@ plan in verified chunks. Earlier priorities below are a backlog. - [x] Full tutorial gadget re-enable tails and LV1B item1/7 restrictions; replaces previous prefix-only availability. Other level tails/selection remain open. - [x] Companion/shadow reset trace and equal-state AI guard; no blanket AI carry. -- [ ] Next: uncontrolled body/controller/fire scheduling, body registration and - appended-helper callback timing; then C4 support/response and shared viewport/ - DEFAULT handoff. C6 source channel allocation/clock/banks remains separate. +- [x] Bounded uncontrolled body/fire versus controlled movement, ordered CAM/MCA/ + AI preparation, no repeated later-shot reset, held input restoration and authored + player-transform synchronization; managed/GPU/native Linux checks. +- [x] Local REA6.8.0/Ghidra12.1.4/full JDK21 launcher, selected native pseudocode + Evidence/snapshot export; client MCP configuration unchanged. See rea.md. +- [ ] Next: full Jimmy/base wrapper and body registration/helper timing; C4 support/ + response/root and shared viewport/DEFAULT handoff. C6 source channel allocation/ + clock/banks remains separate. Fire's missing Ghidra procedure definition is an + analysis limitation; its immutable source-byte contract is already guarded. 1. Lab regressions are corrected and republished, with user verification of their own Windows build. Keep comprehensive native Windows driver/audio/input diff --git a/scripts/rea.sh b/scripts/rea.sh new file mode 100755 index 0000000..5d3677b --- /dev/null +++ b/scripts/rea.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Local REA launcher. Setup paths live in ignored .tools/rea.env; no client edits. +set -euo pipefail +NEUTRON_REA_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$NEUTRON_REA_ROOT" +if [[ -f .tools/rea.env ]]; then source .tools/rea.env; fi +export GHIDRA_INSTALL_DIR="${GHIDRA_INSTALL_DIR:-$NEUTRON_REA_ROOT/.tools/ghidra_12.1.4_PUBLIC}" +export JAVA_HOME="${NEUTRON_REA_JAVA_HOME:-$NEUTRON_REA_ROOT/.tools/java/usr/lib/jvm/java-21-openjdk-amd64}" +NEUTRON_REA_NODE="${NEUTRON_REA_NODE:-node}" +if [[ ! -x "$JAVA_HOME/bin/javac" || ! -x "$GHIDRA_INSTALL_DIR/support/analyzeHeadless" ]]; then + echo 'REA requires the local Ghidra/full JDK setup; see docs/rea.md.' >&2 + exit 2 +fi +if [[ -n "${NEUTRON_REA_LAUNCHER:-}" ]]; then + exec "$NEUTRON_REA_NODE" "$NEUTRON_REA_LAUNCHER" "$@" +elif command -v rea >/dev/null; then + exec rea "$@" +else + echo 'Set NEUTRON_REA_LAUNCHER to the installed public scripts/rea.mjs; see docs/rea.md.' >&2 + exit 2 +fi diff --git a/scripts/test.sh b/scripts/test.sh index ee6ab71..870270e 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -41,6 +41,7 @@ dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1 dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm dotnet run --no-build -- --headless --story --smoke-lab-route dotnet run --no-build -- --headless --smoke-carl-cutscene --frames 60 --screenshot artifacts/test-carl-cutscene.ppm +dotnet run --no-build -- --headless --smoke-control-phases dotnet run --no-build -- --headless --smoke-objective-panel --story-time 1 --screenshot artifacts/test-objective-visible.ppm dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --screenshot artifacts/test-objective-hidden.ppm dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.ppm diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index c0458f1..2270357 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -57,6 +57,9 @@ public sealed class LabSimulation : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly : !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; public int Steps { get; private set; } + public int PhysicsSteps { get; private set; } + public int ControllerSteps { get; private set; } + public int EffectSteps { get; private set; } public int Jumps { get; private set; } public int Landings { get; private set; } public int WallHits { get; private set; } @@ -103,6 +106,7 @@ public sealed class LabSimulation Grounded = true; Noclip = HasNoclipEntry = false; Steps = Jumps = Landings = WallHits = 0; + PhysicsSteps = ControllerSteps = EffectSteps = 0; Travel = MaximumRise = 0; CameraEye = DesiredEye().Eye; } @@ -144,21 +148,41 @@ public sealed class LabSimulation return ((float)Math.Sin(radians), (float)Math.Cos(radians)); } - public void Step(PlayerInput input) + public void Step(PlayerInput input, bool controlled = true) { if (Noclip) { StepNoclip(input); return; } //47E554 global body integration precedes473740 registry callbacks. // This reconstructs the player/input/fire partial order, not the full // scene registry, original cadence or original collision response. StepPhysics(); - if (!InputAfterPlayerUpdate) StepInput(input); - StepPlayer(input); + //42469F..4246DC reasserts ordinary grounded radius before ownership + //checks. The scooter's separate radius160 policy remains unimplemented. + if (Grounded) InteractionRadius = 60; + if (controlled && !InputAfterPlayerUpdate) StepInput(input); + if (controlled) StepPlayer(input); var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode); jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible; - if (InputAfterPlayerUpdate) StepInput(input); + EffectSteps++; + if (controlled && InputAfterPlayerUpdate) StepInput(input); Steps++; } + /// 43A750 preparation clears speed and velocity XYZ only. Queued + /// impulse, acceleration, mode, jump/hold and owned fire timer survive. + public void PrepareForScript() + { + Speed = 0; Velocity = Vector3.Zero; + } + + /// Authored AI root/Euler writes. They do not reset body motion or + /// destination yaw61C; the full logical/render Euler model remains separate. + public void ApplyAuthoredTransform(Vector3 root, float yaw) + { + if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z) || !float.IsFinite(yaw)) + throw new ArgumentOutOfRangeException(nameof(root)); + Position = root - Vector3.UnitY * rootHeight; Yaw = yaw; + } + /// Modern debug movement; never serialized into original save state. public bool SetNoclip(bool enabled) { @@ -239,6 +263,7 @@ public sealed class LabSimulation private void StepPlayer(PlayerInput input) { + ControllerSteps++; const float dt = FixedStepClock.Step; var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360); Yaw = (Yaw + yawError * dt * 3.7f) % 360; @@ -249,7 +274,6 @@ public sealed class LabSimulation { movementMode = 0; TurnRate = 0; } - if (Grounded) InteractionRadius = 60; if (Velocity.LengthSquared() != 0 || movementMode == 0 && lateralContribution != 0) Yaw = (Yaw + TurnRate * dt) % 360; var (sin, cos) = Trig(Yaw); @@ -277,6 +301,7 @@ public sealed class LabSimulation private void StepPhysics() { + PhysicsSteps++; const float dt = FixedStepClock.Step; var wasGrounded = Grounded; var velocity = Velocity; @@ -338,5 +363,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}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, 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}, grounded={Grounded}, feet={Position}."; } diff --git a/src/GamePort/Game/PlayerSceneBinding.cs b/src/GamePort/Game/PlayerSceneBinding.cs new file mode 100644 index 0000000..77d0572 --- /dev/null +++ b/src/GamePort/Game/PlayerSceneBinding.cs @@ -0,0 +1,56 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// Connect recovered raw-owner preparations and authored transforms to +/// the port's player body. Full scene scheduling/other actor classes stay separate. +public sealed class PlayerSceneBinding : IDisposable +{ + private readonly SceneDirector director; + private readonly LabSimulation player; + private readonly SceneInventory inventory; + private readonly string tag; + public int UnsupportedGadgetCleanups { get; private set; } + + public PlayerSceneBinding(SceneDirector director, LabSimulation player, SceneInventory inventory, string tag) + { + this.director = director; this.player = player; this.inventory = inventory; this.tag = tag; + director.ActorPreparing += Prepare; + director.AuthoredTransformChanged += Transform; + } + + public bool Step(PlayerInput input) + { + var acceptsInput = director.Controlled || player.Noclip; + player.Step(input, acceptsInput); + var rotation = director.FindActor(tag)?.Rotation ?? Vector3.Zero; + director.SyncActor(tag, player.ActorRoot, rotation with { Y = player.Yaw }); + return acceptsInput; + } + + private void Prepare(DirectorActor actor, ScriptPreparation action) + { + if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return; + if (action == ScriptPreparation.StopMotion) player.PrepareForScript(); + else if (action == ScriptPreparation.ReleaseGadget) + { + //427FF0 has distinct cases. Only no-selection/jetpack cleanup is + //implemented; do not turn the other gadget cases into blanket resets. + if (inventory.SelectedGadget is -1 or 3) + { inventory.SelectGadget(-1); player.GadgetMode = -1; } + else UnsupportedGadgetCleanups++; + } + } + + private void Transform(DirectorActor actor) + { + if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) + player.ApplyAuthoredTransform(actor.Position, actor.Rotation.Y); + } + + public void Dispose() + { + director.ActorPreparing -= Prepare; + director.AuthoredTransformChanged -= Transform; + } +} diff --git a/src/GamePort/Game/SceneDirector.cs b/src/GamePort/Game/SceneDirector.cs index 5fe54d6..718fe35 100644 --- a/src/GamePort/Game/SceneDirector.cs +++ b/src/GamePort/Game/SceneDirector.cs @@ -37,6 +37,7 @@ public sealed class DirectorActor } public sealed record DirectorIssue(string Tag, string Kind, string Detail); +public enum ScriptPreparation { StopMotion, ReleaseGadget, FlattenOrientation } /// /// Recovered synchronous AI-trigger dispatch and audio-duration-driven CAM/MCA @@ -71,6 +72,7 @@ public sealed class SceneDirector public List Actors { get; } = []; public IReadOnlyList Issues => issues; private string? controlledTag; + public string? AuthoredControlledTag => controlledTag; /// Modern debug override; leaves authored control/camera transitions intact. public bool DebugForceControl { get; set; } public bool Controlled => Equal(ControlledTag, level.Player?.Tag); @@ -90,6 +92,8 @@ public sealed class SceneDirector public event Action? MusicStopped; public event Action? MusicRestarted; public event Action? ActorChanged; + public event Action? ActorPreparing; + public event Action? AuthoredTransformChanged; public event Action? Unsupported; public SceneDirector(GamLevel level, TaskStates tasks, Func soundDuration) @@ -277,7 +281,7 @@ public sealed class SceneDirector var number = activations.GetValueOrDefault(entity.Offset) + 1; activations[entity.Offset] = number; if (times != -1 && number > times) return; - SetControl(entity); + SetControl(entity, prepareOwner: true); var targetTag = entity.Text("AITarget"); if (!IsNone(targetTag)) @@ -286,12 +290,13 @@ public sealed class SceneDirector Report(entity.Tag!, entity.Kind, $"AI target {targetTag} absent"); else { + var transformed = false; var hide = entity.Integer("AIHideObj", -1); if (hide != -1) target.Visible = hide == 0; var positionTag = entity.Text("AINewPos"); if (!IsNone(positionTag)) { - if (actors.TryGetValue(positionTag!, out var marker)) target.Position = marker.Position; + if (actors.TryGetValue(positionTag!, out var marker)) { target.Position = marker.Position; transformed = true; } else Report(entity.Tag!, entity.Kind, $"AINewPos {positionTag} absent"); } var animation = entity.Text("AIAnim"); @@ -302,7 +307,8 @@ public sealed class SceneDirector var patrol = entity.Text("AIPatrol"); if (!IsNone(patrol)) target.Patrol = patrol; var yaw = entity.Number("AINewRotY", -1); - if (yaw != -1) target.Rotation = target.Rotation with { Y = yaw }; + if (yaw != -1) { target.Rotation = target.Rotation with { Y = yaw }; transformed = true; } + if (transformed) AuthoredTransformChanged?.Invoke(target); ActorChanged?.Invoke(target); if (target.AIstate == 3 && (target.Kind is "3DOG" or "3CAR") && !patrolConsumers.Contains(target.Tag)) Report(target.Tag, target.Kind, "Patrol motion/arrival is not yet reconstructed; actor-state callback emitted"); @@ -331,15 +337,26 @@ public sealed class SceneDirector private void StartMulti(GamEntity entity) { // MCA's PlayerControlled is its completion target (4311F0), not an - // activation grant. Each valid shot clears control at43159E..4315A7. + // activation grant. Only initial activation clears control; later shots + //use431750 without repeating431502..4315A7 preparation. Toggle(entity); + if (IsNone(entity.Text("CameraTarget0"))) return; //431300→431668 returns, not completion. if (skipping) { FinishMulti(entity); return; } + //431502 initial activation only. Subsequent431750 shots do not repeat + //preparation or clear control. The raw owner guard ignores debug force. + PrepareOwner(ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation, ScriptPreparation.ReleaseGadget); + ControlledTag = null; StartCamera(entity, 0, applyCommon: false); } private void StartCamera(GamEntity entity, int index, bool applyCommon = true) { - if (applyCommon) { SetControl(entity); Toggle(entity); } + if (applyCommon) + { + if (Equal(entity.Text("PlayerControlled"), "NULL")) + PrepareOwner(ScriptPreparation.ReleaseGadget, ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation); + SetControl(entity); Toggle(entity); + } if (entity.Integer("DeactivateInv") != 0) InventoryEnabled = false; if (skipping) { @@ -361,7 +378,6 @@ public sealed class SceneDirector Block(entity, $"Camera target {targetTag} absent", entity.Text("NextTrigger")); return; } - if (index >= 0) ControlledTag = null; var database = entity.Text("SoundDatabase") ?? "none"; var duration = soundDuration(database, sound); if (!double.IsFinite(duration) || duration < 0) @@ -478,11 +494,33 @@ public sealed class SceneDirector return target.Position + new Vector3(x * cy - pitchedZ * sy, pitchedY, x * sy + pitchedZ * cy); } - private void SetControl(GamEntity entity) + private void PrepareOwner(params ScriptPreparation[] actions) + { + if (controlledTag == null || !actors.TryGetValue(controlledTag, out var owner)) return; + foreach (var action in actions) + { + // Only Jimmy's derived preparation is modeled here; other classes + //receive the boundary without inventing their virtual side effects. + if (action == ScriptPreparation.StopMotion && owner.Kind == "3JIM") + owner.Speed = 0; + else if (action == ScriptPreparation.FlattenOrientation) + owner.Rotation = new Vector3(0, owner.Rotation.Y, 0); + ActorPreparing?.Invoke(owner, action); + //42AFC0 invokes43A750 before the derived STOP animation request. + if (action == ScriptPreparation.StopMotion && owner.Kind == "3JIM") + { owner.Animation = "STOP"; ActorChanged?.Invoke(owner); } + } + } + + private void SetControl(GamEntity entity, bool prepareOwner = false) { var control = entity.Text("PlayerControlled"); if (IsNone(control)) return; - if (Equal(control, "NULL")) ControlledTag = null; + if (Equal(control, "NULL")) + { + if (prepareOwner) PrepareOwner(ScriptPreparation.StopMotion); //40C4AD; no438/flatten. + ControlledTag = null; + } else if (actors.ContainsKey(control!)) ControlledTag = control; else Report(entity.Tag!, entity.Kind, $"PlayerControlled target {control} absent"); } diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index 5780dff..8a9cc24 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -87,6 +87,7 @@ internal static class Program --smoke-jetpack 300-step powered steering/jump check in VR04 --smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse --smoke-carl-cutscene Verify input stays locked during the lab conversation + --smoke-control-phases Airborne cutscene body/fire and restoration fixture --smoke-objective-panel Show original lab objective; --story-time tests timeout --smoke-objective-window SDL O-key reopen/close/timeout check --debug-menu Start with the F1 debug menu open @@ -251,6 +252,7 @@ internal static class Program var walkSmoke = args.Contains("--smoke-walk"); var jetpackSmoke = args.Contains("--smoke-jetpack"); var carlSmoke = args.Contains("--smoke-carl-cutscene"); + var controlPhaseSmoke = args.Contains("--smoke-control-phases"); var objectiveWindowSmoke = args.Contains("--smoke-objective-window"); var objectiveSmoke = args.Contains("--smoke-objective-panel") || objectiveWindowSmoke; var jumpBinding = Option(args, "--smoke-jump-key") ?? "shift"; @@ -268,7 +270,7 @@ internal static class Program var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") && animationPath == null && !args.Contains("--time"); var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time") - || args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || objectiveSmoke; + || args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window"))) throw new ArgumentException("Story playback requires its own simulation mode."); if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode."); @@ -428,7 +430,9 @@ internal static class Program var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); - var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); + var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); + if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null)) + throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames"); if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) throw new ArgumentException("Debug tools smoke requires a fresh windowed lab and at least16 frames"); if (debugSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) @@ -450,6 +454,8 @@ internal static class Program var width = uint.Parse(Option(args, "--width") ?? "960"); var height = uint.Parse(Option(args, "--height") ?? "720"); if (width is < 64 or > 8192 || height is < 64 or > 8192) throw new ArgumentException("Viewport dimensions must be64..8192"); + using var playerBinding = director == null ? null + : new PlayerSceneBinding(director, simulation!, interactions!.Inventory, level!.Player!.Tag!); var renderer = presentation.LoadScene(mesh, texture, headless, walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", width, height, !args.Contains("--no-validation")); @@ -490,7 +496,15 @@ internal static class Program Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}."); if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions"); } - if (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } + if (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } + if (controlPhaseSmoke) + { + interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3); + simulation.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f)); + simulation.RestoreReturnRoot(simulation.ActorRoot + Vector3.UnitY * 200); + director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, new(0, simulation.Yaw, 0)); + director.Trigger("neutron1a"); + } if (practiceReturnSmoke && level.Code == "VR04") { if (interactions!.Inventory.State(0, 3) != 1) @@ -540,6 +554,8 @@ internal static class Program } for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++) { + playerBinding!.Step(default); + interactions!.UpdateEnergy(simulation!.Energy); foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step); mechanisms!.Step(FixedStepClock.Step); director.Step(FixedStepClock.Step); @@ -595,6 +611,8 @@ internal static class Program var debugPausedSteps = simulation?.Steps ?? 0; var toolsPaused = false; var toolsMoved = false; var toolsStopped = false; var toolsSaved = false; var toolsSystems = false; var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero; + var controlEntry = simulation?.ActorRoot ?? Vector3.Zero; + var phasesLocked = false; var phasesResumed = false; void ResetScene() { if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; } @@ -846,28 +864,29 @@ internal static class Program if (debugMenu.Open) animationStarted += elapsed; if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke)) { - var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); + var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); for (var step = 0; step < steps; step++) { - var input = carlSmoke ? new PlayerInput(true, false, true, false, true) + var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true) : jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps) : walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79), mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98), keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20), keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229)); - if (director?.Controlled != false || simulation.Noclip) + var before = simulation.Position; + var powered = simulation.JetpackEffectVisible && !simulation.Grounded; + bool acceptsInput; + if (playerBinding != null) acceptsInput = playerBinding.Step(input); + else { simulation.Step(input); acceptsInput = true; } + if (jetpackSmoke && powered) + { + poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); + poweredAirTurn |= MathF.Abs(simulation.TurnRate) > 1; + } + interactions?.UpdateEnergy(simulation.Energy); + if (acceptsInput) { - var before = simulation.Position; - var powered = simulation.JetpackEffectVisible && !simulation.Grounded; - simulation.Step(input); - if (jetpackSmoke && powered) - { - poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); - poweredAirTurn |= MathF.Abs(simulation.TurnRate) > 1; - } - interactions?.UpdateEnergy(simulation.Energy); - director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); if (!simulation.Noclip) { director?.Touch(level!.Player!.Tag!, simulation.ActorRoot); @@ -976,6 +995,16 @@ internal static class Program diagnostics.ObserveFrame(presentedAt - lastPresentedAt); lastPresentedAt = presentedAt; count++; + if (controlPhaseSmoke && count == 15) + { + phasesLocked = director is { Controlled: false, Playing: true } + && simulation is { ControllerSteps: 0, PhysicsSteps: 15, EffectSteps: 15, Jumps: 0, Speed: 0, TurnRate: 0 } + && simulation.ActorRoot.Y < controlEntry.Y && simulation.JetpackRemaining is > 0 and < 6.125f + && simulation.Energy < 20 && Vector2.Distance(new(simulation.ActorRoot.X, simulation.ActorRoot.Z), new(controlEntry.X, controlEntry.Z)) < .001f; + director!.Skip(); + } + if (controlPhaseSmoke && count == 30) + phasesResumed = director!.Controlled && simulation!.ControllerSteps == 15 && simulation.Travel > 1; audio?.Pump(); sceneAudio?.Pump(); if (toolsSmoke) @@ -1198,10 +1227,17 @@ internal static class Program } if (carlSmoke) { - var locked = director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" } && simulation!.Steps == 0; - Console.WriteLine($"Carl cutscene input lock with held move/turn/jump: {locked}."); + var locked = director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" } + && simulation is { ControllerSteps: 0, Jumps: 0, Speed: 0, TurnRate: 0 } + && simulation.PhysicsSteps == simulation.Steps && simulation.EffectSteps == simulation.Steps && simulation.Steps >= frames; + Console.WriteLine($"Carl cutscene input lock with held move/turn/jump: {locked}; body/fire continue={simulation!.PhysicsSteps}/{simulation.EffectSteps}."); if (!locked) return 2; } + if (controlPhaseSmoke) + { + Console.WriteLine($"Control-phase fixture: locked input with body/fire/energy continuing={phasesLocked}; held-input resumption={phasesResumed}."); + if (!phasesLocked || !phasesResumed) return 2; + } if (objectiveSmoke) Console.WriteLine($"Objective panel: time={objectivePanel!.Elapsed:F3}, pad={objectivePanel.PadVisible}, content={objectivePanel.ContentVisible}, offset={objectivePanel.YOffset:F3}."); if (objectiveWindowSmoke) { diff --git a/tests/GamePort.DirectorTests/Program.cs b/tests/GamePort.DirectorTests/Program.cs index afc6cdf..fe88886 100644 --- a/tests/GamePort.DirectorTests/Program.cs +++ b/tests/GamePort.DirectorTests/Program.cs @@ -139,6 +139,96 @@ Check(carlBytes.AsSpan(0x3159e, 15).SequenceEqual(Convert.FromHexString("8B0D489 "Source MCA clears game controlled pointer before playback"); Console.WriteLine("PASS end-of-lab Carl cutscene input lock and natural/skip control restoration"); +foreach (var kind in new[] { "3CAM", "3MCA", "3AIT" }) +{ + var jim = Entity("3JIM", "JIM1", ("RotationX", 12f), ("RotationZ", 22f)); + var command = Entity(kind, "command", ("PlayerControlled", "NULL"), + ("CameraTarget", "JIM1"), ("CameraTarget0", "JIM1"), ("CameraTarget1", "JIM1"), + ("SoundIndex", 1), ("SoundIndex0", 1), ("SoundIndex1", 1), ("SoundDatabase", "voice"), + ("NextTrigger", "default")); + var scene = new SceneDirector(new("LV1B", [jim, command]), new TaskStates([]), (_, _) => .1); + var body = ControlBody(); + var bag = new SceneInventory(new int[19]); bag.SetState(0, 3, 1); bag.SelectGadget(3); + using var binding = new PlayerSceneBinding(scene, body, bag, "JIM1"); + for (var tick = 0; tick < 5; tick++) binding.Step(new(true, false, false, false, false)); + var callbacks = new List(); + scene.ActorPreparing += (actor, action) => + { + Check(actor.Tag == "JIM1" && scene.AuthoredControlledTag == "JIM1", "Preparation observes the prior raw owner"); + callbacks.Add(action); + }; + var stopObserved = false; + scene.ActorChanged += actor => + { + if (actor.Tag == "JIM1" && actor.Animation == "STOP") + { + Check(body.Velocity == Vector3.Zero && body.Speed == 0, "Body preparation precedes derived STOP notification"); + stopObserved = true; + } + }; + scene.Trigger("command"); + var expected = kind switch + { + "3CAM" => new[] { ScriptPreparation.ReleaseGadget, ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation }, + "3MCA" => new[] { ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation, ScriptPreparation.ReleaseGadget }, + _ => new[] { ScriptPreparation.StopMotion } + }; + Check(stopObserved && callbacks.SequenceEqual(expected) && body.Speed == 0 && body.Velocity == Vector3.Zero, + "CAM/MCA/AI retain their own ordered preparation boundaries"); + Check(bag.SelectedGadget == (kind == "3AIT" ? 3 : -1), "AI control loss does not imply camera gadget cleanup"); + Check(scene.FindActor("JIM1")!.Rotation.X == (kind == "3AIT" ? 12 : 0), "Only camera preparation flattens pitch/roll"); + if (kind == "3AIT") continue; // Its DEFAULT next trigger has already restored control. + var controllers = body.ControllerSteps; + binding.Step(new(true, false, true, false, true)); + Check(body.ControllerSteps == controllers && body.Jumps == 0 && body.PhysicsSteps > controllers, + "Input lock leaves body/effect callbacks running"); + scene.DebugForceControl = true; + binding.Step(new(true, false, false, false, false)); + var speed = body.Speed; + scene.Step(.11f); + Check(callbacks.SequenceEqual(expected), "Later MCA shots/CAM completion do not replay initial preparations"); + Check(body.Speed == speed && scene.Controlled, "Force control does not become the raw preparation owner"); + scene.DebugForceControl = false; + scene.Trigger("default"); + var jumps = body.Jumps; + binding.Step(new(false, false, false, false, true)); + Check(body.Jumps == jumps + 1, "DEFAULT restores held jump without an invented fresh-key boundary"); +} +Console.WriteLine("PASS ordered CAM/MCA/AI preparations, body continuation, raw-owner force override and held-input restoration"); + +{ + var jim = Entity("3JIM", "JIM1"); + var command = Entity("3AIT", "move", ("PlayerControlled", "NULL"), ("AITarget", "JIM1"), + ("AINewPos", "marker"), ("AINewRotY", 75f)); + var marker = Entity("DUMY", "marker", ("PositionX", 200f), ("PositionY", 500f), ("PositionZ", 300f)); + var scene = new SceneDirector(new("LV1B", [jim, command, marker]), new TaskStates([]), (_, _) => 1); + var body = ControlBody(); + using var binding = new PlayerSceneBinding(scene, body, new SceneInventory(new int[19]), "JIM1"); + scene.Trigger("move"); + Near(body.ActorRoot, marker.Position, "Authored AI position is applied to the actual player body"); + Check(body.Yaw == 75 && !scene.Controlled, "Authored AI yaw follows the logical setter during control loss"); + binding.Step(new(true, false, true, false, true)); + Check(body.ActorRoot.Y < marker.Position.Y && body.ActorRoot.X == marker.Position.X && body.ControllerSteps == 0, + "Body settles at the scripted location without accepting movement input"); + Near(scene.FindActor("JIM1")!.Position, body.ActorRoot, "Physics publishes the new logical player root"); +} +Console.WriteLine("PASS authored player teleport/yaw survives uncontrolled body synchronization"); + +{ + var jim = Entity("3JIM", "JIM1"); + var empty = Entity("3MCA", "empty", ("CameraTarget0", "none"), ("PlayerControlled", "NULL"), ("NextTrigger", "default")); + var missing = Entity("3CAM", "missing", ("CameraTarget", "absent"), ("SoundIndex", 1), ("PlayerControlled", "NULL")); + var scene = new SceneDirector(new("LV1B", [jim, empty, missing]), new TaskStates([]), (_, _) => 1); + var callbacks = new List(); scene.ActorPreparing += (_, action) => callbacks.Add(action); + scene.Trigger("empty"); + Check(callbacks.Count == 0 && scene.AuthoredControlledTag == "JIM1" && !scene.Playing, + "Initial MCA none target returns without preparation or invoking completion ownership"); + scene.Trigger("missing"); + Check(callbacks.Count == 3 && scene.AuthoredControlledTag == null && scene.Blocked, + "CAM preparation precedes target-lookup failure"); +} +Console.WriteLine("PASS first-MCA none return and CAM failure preparation boundaries"); + foreach(var type in new[]{0,1,2,3,4}) { var camera=Entity("3MCA","camera",("CameraTarget0","actor"),("SoundDatabase","voice"),("SoundIndex0",1),("CameraType0",type),("LookatVOffset0",100f),("NextTrigger","default")); @@ -268,6 +358,15 @@ var returnGate=vr.Entities.First(e=>e.Kind=="LOAD");interactions.Update(returnGa Check(transitions==1 && returned!.Returning && returned.LevelFile==save.ReturnLevel && returned.StartPoint==save.ReturnStart,"RETURN uses stored destination, restore flag and contact-enter gating"); Console.WriteLine("PASS original VR01 star/trophy score, strict contact entry, acquired-state save/reload and RETURN request"); +static LabSimulation ControlBody() +{ + var points = new[] { new Vector3(-10000, 0, -10000), new Vector3(-10000, 0, 10000), + new Vector3(10000, 0, 10000), new Vector3(10000, 0, -10000) }; + var floor = new Mesh(points.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 0, 2, 3]); + var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []); + return new(new SceneCollision(floor), standing, new(0, 25, 0), 0); +} + static GamEntity Entity(string kind,string tag,params (string Name,object Value)[] values) { var properties=new Dictionary(); diff --git a/tests/GamePort.LabRouteTests/Program.cs b/tests/GamePort.LabRouteTests/Program.cs index bf01f10..ecf8c84 100644 --- a/tests/GamePort.LabRouteTests/Program.cs +++ b/tests/GamePort.LabRouteTests/Program.cs @@ -41,6 +41,7 @@ interactions.PracticeRequested += practice.Show; var prompts = 0; LevelTransition? destination = null; interactions.Transition += request => destination ??= request; +using var playerBinding = new PlayerSceneBinding(director, simulation, interactions.Inventory, level.Player!.Tag!); director.Begin(start); interactions.Reset(); mechanisms.Reset(); director.Skip(); @@ -70,12 +71,18 @@ for (var leg = 0; leg < route.Length && destination == null; leg++) if (difference.Length() < 90) { arrived = true; break; } var desiredYaw = MathF.Atan2(-difference.X, difference.Y) * 180 / MathF.PI; var error = MathF.IEEERemainder(desiredYaw - simulation.Yaw, 360); - if (director.Controlled) + var previous = simulation.ActorRoot; + // This is a modern input driver, not original navigation. Brake before + //large heading changes; coasting turns can miss the narrow exit opening + //when the recovered cutscene preparation changes the arrival speed. + var brake = MathF.Abs(error) > 15 && simulation.Speed > 0; + var input = brake ? new PlayerInput(false, true, false, false, false) + : new PlayerInput(MathF.Abs(error) < 10, false, error > 1, error < -1, false); + var acceptsInput = playerBinding.Step(input); + Require(Vector3.Distance(previous, simulation.ActorRoot) < 100, "Player warped during input replay"); + interactions.UpdateEnergy(simulation.Energy); + if (acceptsInput) { - var previous = simulation.ActorRoot; - simulation.Step(new(MathF.Abs(error) < 30, false, error > 1, error < -1, false)); - Require(Vector3.Distance(previous, simulation.ActorRoot) < 100, "Player warped during input replay"); - director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, new(0, simulation.Yaw, 0)); director.Touch(level.Player!.Tag!, simulation.ActorRoot); interactions.Update(simulation.ActorRoot, simulation.InteractionRadius); if (practice.Active) continue; // Same modal activation boundary as Program. @@ -86,7 +93,7 @@ for (var leg = 0; leg < route.Length && destination == null; leg++) director.Step(FixedStepClock.Step); if (destination != null) break; } - Require(arrived || destination != null, $"Input route blocked at leg{leg}: {simulation.ActorRoot}"); + Require(arrived || destination != null, $"Input route blocked at leg{leg}: {simulation.Report}; yaw={simulation.Yaw}, control={director.AuthoredControlledTag}, shot={director.CurrentTag}, blocked={director.Blocked}, goal={route[leg]}"); Require(tasks.Get("SCENE") == sceneStates[leg], $"Wrong task state after walking leg{leg}"); Console.WriteLine($"PASS walked leg{leg}: SCENE={tasks.Get("SCENE")}, root={simulation.ActorRoot}"); } diff --git a/tests/GamePort.MovementTests/Program.cs b/tests/GamePort.MovementTests/Program.cs index 3162d70..2b794c5 100644 --- a/tests/GamePort.MovementTests/Program.cs +++ b/tests/GamePort.MovementTests/Program.cs @@ -10,6 +10,8 @@ var tests = new (string Name, Action Check)[] ("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries), ("physics consumes prior motion; fresh versus retained input order", FrameOrdering), ("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState), + ("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics), + ("uncontrolled fire ticks while movement and grounded-release reset are gated", UncontrolledFire), ("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer), ("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip), ("turn-only speed, forward acceleration/cap and release", SpeedLimits), @@ -103,6 +105,60 @@ static void FrameOrdering() Check(jump.MovementMode == 0, "reset restores stored walking input mode"); } +static void UncontrolledPhysics() +{ + var cameraQueries = 0; + var simulation = FlatSimulation(cameraRay: (_, _) => { cameraQueries++; return null; }); + simulation.Step(new(true, false, false, false, true)); + var pending = simulation.PendingImpulse; + var mode = simulation.MovementMode; var jump = simulation.JumpState; + var hold = simulation.JumpHoldSeconds; var fire = simulation.JetpackRemaining; + var before = simulation.Position; + simulation.PrepareForScript(); + Check(simulation.Speed == 0 && simulation.Velocity == Vector3.Zero && simulation.PendingImpulse == pending, + "43A750 zeros speed/velocity while queued impulse survives"); + Check(simulation.MovementMode == mode && simulation.JumpState == jump && simulation.JumpHoldSeconds == hold + && simulation.JetpackRemaining == fire, "Preparation does not invent a mode/jump/hold/fire reset"); + var queries = cameraQueries; + for (var tick = 0; tick < 8; tick++) simulation.Step(new(true, false, true, false, true), controlled: false); + Check(simulation.Position.Y > before.Y && simulation.PendingImpulse == Vector3.Zero, + "Uncontrolled body consumes the queued impulse once and keeps integrating"); + Check(simulation.Jumps == 1 && simulation.ControllerSteps == 1 && simulation.Speed == 0 && simulation.TurnRate == 0 + && simulation.JumpState == jump && simulation.MovementMode == mode && simulation.JumpHoldSeconds == hold, + "Held movement/turn/jump cannot enter the uncontrolled controller"); + Check(simulation.PhysicsSteps == 9 && simulation.EffectSteps == 9 && simulation.Steps == 9, + "Body and fire callbacks remain distinct from controlled movement count"); + Check(cameraQueries == queries, "Uncontrolled input does not advance the follow-camera query"); + simulation.ApplyAuthoredTransform(simulation.ActorRoot + new Vector3(25, 0, 30), 85); + Check(simulation.Velocity.Y > 0 && simulation.Jumps == 1, + "Authored transform write is separate from body preparation"); +} + +static void UncontrolledFire() +{ + foreach (var code in new[] { "LV1B", "VR04" }) + { + var simulation = FlatSimulation(); simulation.LevelCode = code; + simulation.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f)); + simulation.RestoreReturnRoot(simulation.ActorRoot + Vector3.UnitY * 500); + var energy = simulation.Energy; + simulation.PrepareForScript(); + simulation.Step(new(true, false, true, false, true), controlled: false); + Near(simulation.JetpackRemaining, 6.125f - FixedStepClock.Step, .00001f, "Owned fire time continues during control lock"); + Near(simulation.Energy, code == "VR04" ? energy : energy - FixedStepClock.Step * .5f, .00001f, + "Fire drain and tutorial immunity do not depend on raw control"); + Check(simulation.ControllerSteps == 0 && simulation.JumpState == 0 && simulation.MovementMode == 1 + && simulation.JumpHoldSeconds == .625f && simulation.JetpackEffectVisible, "Controller scalars untouched while fire remains visible"); + } + var grounded = FlatSimulation(); + grounded.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f)); + grounded.Step(default, controlled: false); + Check(grounded.Grounded && grounded.MovementMode == 1 && grounded.JetpackRemaining < 0 + && grounded.Energy == 20, "Grounded fire clears independently of the gated grounded-release controller"); + grounded.Step(default); + Check(grounded.MovementMode == 0 && grounded.ControllerSteps == 1, "Normal grounded-release reset resumes with control"); +} + static void RetainedLevelState() { var state = new PlayerLevelState("LV1B", 3, 1, .625f, 6.125f); diff --git a/tests/test_cutscene_preparation.py b/tests/test_cutscene_preparation.py new file mode 100644 index 0000000..ba7fed0 --- /dev/null +++ b/tests/test_cutscene_preparation.py @@ -0,0 +1,36 @@ +from dataclasses import replace +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tools/binary')) +from cutscene_preparation import collect, preparation_events, JetpackPreparationState, project_jetpack_preparation + + +class CutscenePreparationTests(unittest.TestCase): + def test_source_bytes_and_virtual_targets(self): + self.assertEqual(collect(ROOT.parent / 'Original')['sha256'], + 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8') + + def test_distinct_preparation_order_and_later_shot_boundary(self): + self.assertEqual(preparation_events('cam_null', 'JIM1'), + ['JIM1:438', 'JIM1:410', 'JIM1:flatten_euler', 'control:NULL']) + self.assertEqual(preparation_events('mca_activation', 'JIM1'), + ['JIM1:410', 'JIM1:flatten_euler', 'JIM1:438', 'control:NULL']) + self.assertEqual(preparation_events('ai_null', 'JIM1'), ['JIM1:410', 'control:NULL']) + self.assertEqual(preparation_events('mca_next_shot', 'JIM1'), []) + self.assertEqual(preparation_events('default_restore', 'JIM1'), []) + self.assertEqual(preparation_events('mca_activation', None), []) + + def test_bounded_jetpack_state_does_not_become_blanket_reset(self): + before = JetpackPreparationState() + self.assertEqual(project_jetpack_preparation(before, 'cam_null'), + replace(before, speed=0, velocity=(0, 0, 0), selected_gadget=-1, euler=(0, 150, 0))) + self.assertEqual(project_jetpack_preparation(before, 'ai_null'), replace(before, speed=0, velocity=(0, 0, 0))) + with self.assertRaises(ValueError): + project_jetpack_preparation(replace(before, selected_gadget=0), 'cam_null') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_uncontrolled_physics.py b/tests/test_uncontrolled_physics.py new file mode 100644 index 0000000..0096d1b --- /dev/null +++ b/tests/test_uncontrolled_physics.py @@ -0,0 +1,25 @@ +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tools/binary')) +from uncontrolled_physics import collect, eligible + + +class UncontrolledPhysicsTests(unittest.TestCase): + def test_source_field_and_virtual_gate_provenance(self): + self.assertEqual(len(collect(ROOT.parent / 'Original')['tables']), 6) + + def test_raw_control_does_not_replace_frame_and_body_flags(self): + for control in (None, 0x1000, 0x2000): + self.assertTrue(eligible(raw_control=control)) + for gate in ('frame_valid', 'supervisor', 'bodies_enabled', 'registered', 'body_integration'): + self.assertFalse(eligible(raw_control=control, **{gate: False}), gate) + self.assertFalse(eligible(raw_control=control, editor=True)) + self.assertFalse(eligible(raw_control=control, flag5099ab=True)) + self.assertTrue(eligible(raw_control=control, flag5099ab=True, override4f641c=True)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_uncontrolled_player.py b/tests/test_uncontrolled_player.py new file mode 100644 index 0000000..8540c8d --- /dev/null +++ b/tests/test_uncontrolled_player.py @@ -0,0 +1,53 @@ +"""Original ownership-gate evidence and independent controller/effect boundaries.""" +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tools/binary')) +from uncontrolled_player import collect, controller_phases, fire_projection + + +class UncontrolledPlayerTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.report = collect(ROOT.parent / 'Original') + + def test_source_instruction_virtual_and_whole_body_provenance(self): + self.assertEqual(len(self.report['sites']), 47) + bodies = {x['name']: x for x in self.report['bodies']} + self.assertFalse(bodies['complete_fire_callback']['raw_control_reference']) + self.assertTrue(bodies['complete_movement_callback']['raw_control_reference']) + + def test_null_and_other_control_skip_only_gated_controller_tail(self): + for raw in (None, 0, 0x2000): + phases = controller_phases(raw) + self.assertIn('base40E050', phases) + self.assertIn('conditional_timer7A8', phases) + self.assertNotIn('controller_modes', phases) + self.assertNotIn('jump_ground_air', phases) + self.assertIn('jump_ground_air', controller_phases(0x1000)) + self.assertNotIn('controller_modes', controller_phases(0x1000, status83e0=True)) + self.assertNotIn('controller_modes', controller_phases(0x1000, modal8181=True)) + self.assertEqual(controller_phases(0x1000, game_enabled=False), ['game_gate']) + + def test_fire_timer_is_not_controller_or_cutscene_ownership_state(self): + # The exact same owned-fire tick can follow any controller ownership + # projection: raw control is not an input to the original fire callback. + for raw in (None, 0x1000, 0x2000): + controller_phases(raw) + self.assertEqual(fire_projection(2, .25, 20, 0x4C563142), (1.75, 19.875, True, True)) + self.assertEqual(fire_projection(.25, .25, 20, 0x4C563142), (0, 20, False, True)) + self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, grounded=True), (-.25, 20, False, True)) + self.assertEqual(fire_projection(-1, .25, 20, 0x4C563142), (-1.25, 20, False, True)) + + def test_fire_gate_owner_and_tutorial_energy_are_independent_boundaries(self): + self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, owner=False), (2, 20, False, False)) + self.assertEqual(fire_projection(2, .25, 20, 0x4C563142, game_enabled=False), (2, 20, False, False)) + for code in range(0x56523031, 0x56523039): + self.assertEqual(fire_projection(2, .25, 20, code), (1.75, 20, True, True)) + self.assertEqual(fire_projection(2, .25, .01, 0x4C563142), (1.75, 0, True, True)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/binary/cutscene_preparation.py b/tools/binary/cutscene_preparation.py new file mode 100644 index 0000000..cb3658c --- /dev/null +++ b/tools/binary/cutscene_preparation.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Read-only CAM/MCA/AI preparation provenance and bounded event projection.""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass, replace +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 + + +SITES = ( + ('cam_already_active_guard', 0x4165AB, '389e800900000f856c040000'), + ('cam_control_none_branch', 0x4165F8, '0f84fc000000'), + ('cam_control_null_compare', 0x4165FE, '6864d04e00'), + ('cam_named_control', 0x41662A, 'ff9218010000'), + ('cam_raw_owner_guard', 0x416635, 'a1e49950003bc30f84a9000000'), + ('cam_owner438', 0x41665D, 'ff9038040000'), + ('cam_owner410', 0x41666B, 'ff9210040000'), + ('cam_owner_euler', 0x41667E, 'ff9028030000'), + ('cam_cached_euler', 0x4166A0, '81c174020000'), + ('cam_flatten_logical_euler', 0x4166E5, 'ff922c030000'), + ('cam_clear_control', 0x4166F4, 'ff9018010000'), + ('cam_target_resolution_after_control', 0x416754, 'e817d90500'), + ('mca_activation_index_reset', 0x4312A7, '899ea40e0000'), + ('mca_first_none_guard', 0x431300, '0f8462030000'), + ('mca_first_none_return', 0x431668, '5f5e5d5b83c420c3'), + ('mca_first_target_lookup', 0x43131A, 'e8512d0400'), + ('mca_first_target_missing_continues', 0x431330, '0f84e9000000'), + ('mca_target_animation_prelude', 0x431417, 'ff92e0000000'), + ('mca_raw_owner_guard', 0x431502, '8b0de49950003bcb0f849d000000'), + ('mca_owner410', 0x431512, 'ff9210040000'), + ('mca_owner_euler', 0x431525, 'ff9028030000'), + ('mca_flatten_logical_euler', 0x431565, 'ff922c030000'), + ('mca_cached_euler', 0x431578, '0574020000'), + ('mca_owner438', 0x431598, 'ff9038040000'), + ('mca_clear_control', 0x4315A7, 'ff9218010000'), + ('mca_start_first_shot', 0x431600, 'ff90e0000000'), + ('mca_later_shot_dispatch', 0x430E87, 'ff90e0000000'), + ('mca_finish_dispatch', 0x430ED8, 'ff92e4000000'), + ('mca_shot_sound_guard', 0x431771, '83bc86e40d0000ff'), + ('mca_shot_target_lookup', 0x4317C1, 'e8aa280400'), + ('mca_shot_sound_start', 0x431838, 'e853bb0400'), + ('mca_shot_target_animation', 0x431909, 'ff92e0000000'), + ('mca_completion_null_compare', 0x4311F4, '6864d04e00'), + ('mca_completion_control', 0x431222, 'ff9218010000'), + ('ai_interface_to_complete', 0x40CA72, '81c138ffffffe883f8ffff'), + ('ai_control_descriptor', 0x40C1A5, '8d868c0900006a01506818ce4e00'), + ('ai_null_control_guard', 0x40C4AD, '8b0de499500085c97466'), + ('ai_owner410', 0x40C4B9, 'ff9210040000'), + ('ai_clear_control', 0x40C527, 'ff9218010000'), + ('ai_marker_root', 0x40C732, 'ff9010030000'), + ('ai_set_root', 0x40C757, 'ff9214030000'), + ('ai_yaw_sentinel', 0x40C88F, '81bd940b0000000080bf'), + ('ai_set_authored_yaw', 0x40C93E, 'ff9274010000'), + ('ai_set_cached_euler', 0x40C94C, '81c334030000'), + ('jimmy_prepare_base', 0x42AFC3, 'e888f70000'), + ('jimmy_prepare_stop', 0x42AFDE, '6840d04e008bceff9250010000'), + ('prepare_speed_zero', 0x43A758, 'c7860806000000000000'), + ('prepare_velocity_xyz', 0x43A764, '6a006a006a008bceff90c4020000'), + ('jimmy438_cleanup', 0x42AE08, '8b8640ffffff8d8e40ffffffff9078010000'), + ('jimmy438_runtime_flags', 0x42AE1A, 'b0018886651d0000a282814f00'), + ('default_already_owned', 0x447D5C, '3bc6753f'), + ('default_restore_control', 0x447E27, 'ff9018010000'), + ('default_snap_strict', 0x447E9D, 'd81dace54800dfe0f6c441'), + ('input_owner_guard', 0x475A9C, '8b0de499500085c97409'), + ('input_owner_dispatch', 0x475AA9, 'ff92cc030000'), + ('jump_held_raw_checks', 0x4378DC, 'a06598500084c0751fa048985000'), +) + +TABLES = ( + ('CAM activation', 0x498060, 0xD8, 0x4165A0), + ('MCA activation', 0x4A93C8, 0xD8, 0x431280), + ('MCA per-shot', 0x4A93C8, 0xE0, 0x431750), + ('MCA completion', 0x4A93C8, 0xE4, 0x4311F0), + ('Jimmy410', 0x4A373C, 0x410, 0x42AFC0), + ('Jimmy438', 0x4A373C, 0x438, 0x42AE00), + ('Jimmy Euler getter', 0x4A373C, 0x328, 0x4723F0), + ('Jimmy Euler setter', 0x4A373C, 0x32C, 0x472450), + ('Jimmy position setter', 0x4A373C, 0x314, 0x472360), + ('Jimmy authored Euler setter', 0x4A373C, 0x174, 0x4716D0), + ('Jimmy stop sound', 0x4A3BDC, 0x148, 0x429A00), + ('Jimmy action request', 0x4A3BDC, 0x150, 0x43AFF0), + ('Jimmy gadget cleanup', 0x4A3BDC, 0x178, 0x427FF0), + ('Jimmy held jump', 0x4A3BDC, 0x158, 0x4378D0), +) + +# Full body identity guards negative claims as well as selected positive sites. +BODY_RANGES = (('MCA per-shot', 0x431750, 0x4319A2), + ('held jump getter', 0x4378D0, 0x43793A)) + + +def preparation_events(kind: str, raw_owner: str | None) -> list[str]: + """Local source-event projection, not an original routine execution. + + Activation preconditions have already reached the inspected preparation + block. Real target, sound and skip handling are intentionally not simulated. + """ + events = [] + if kind == 'cam_null': + if raw_owner: + events += [raw_owner + ':438', raw_owner + ':410', raw_owner + ':flatten_euler'] + events += ['control:NULL'] + elif kind == 'mca_activation': + if raw_owner: + events += [raw_owner + ':410', raw_owner + ':flatten_euler', raw_owner + ':438', 'control:NULL'] + elif kind == 'ai_null': + if raw_owner: + events += [raw_owner + ':410'] + events += ['control:NULL'] + elif kind in ('mca_next_shot', 'default_restore'): + pass # Neither boundary dispatches410/438. + else: + raise ValueError('Unknown preparation boundary') + return events + + +@dataclass(frozen=True) +class JetpackPreparationState: + speed: float = 350 + velocity: tuple[float, float, float] = (10, 20, 30) + impulse: tuple[float, float, float] = (1, 2, 3) + acceleration: tuple[float, float, float] = (4, 5, 6) + mode: int = 1 + jump: int = 3 + hold: float = .625 + fire: float = 6.125 + selected_gadget: int = 3 + euler: tuple[float, float, float] = (15, 150, 25) + + +def project_jetpack_preparation(state: JetpackPreparationState, kind: str): + """Bounded−1/3 selected-gadget projection; do not generalize other gadgets.""" + if state.selected_gadget not in (-1, 3): + raise ValueError('Other gadget cleanup policies are outside this fixture') + result = state + for event in preparation_events(kind, 'JIM1'): + if event.endswith(':410'): + result = replace(result, speed=0, velocity=(0, 0, 0)) + elif event.endswith(':438'): + result = replace(result, selected_gadget=-1) + elif event.endswith(':flatten_euler'): + result = replace(result, euler=(0, result.euler[1], 0)) + return result + + +def collect(root): + pe = PE(find_case(Path(root), 'Neutron.exe')) + if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256: + raise ValueError('Unsupported source EXE') + sites = [] + for name, va, expected in SITES: + actual = read_va(pe, va, len(bytes.fromhex(expected))).hex() + if actual != expected: + raise ValueError(f'{name} changed at {va:#x}: {actual}') + sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual)) + tables = [] + for name, table, slot, target in TABLES: + actual, = struct.unpack(' 0 + if active and not 0x56523031 <= level_code <= 0x56523038: + energy = max(0, min(100, energy - delta * .5)) + return remaining, energy, active, True + + +def collect(root): + pe = PE(find_case(Path(root), 'Neutron.exe')) + if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256: + raise ValueError('Unsupported original EXE') + sites = [] + for name, va, expected in SITES: + actual = read_va(pe, va, len(bytes.fromhex(expected))).hex() + if actual != expected: + raise ValueError(f'Changed instruction {name} at {va:#x}: {actual}') + sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual)) + tables = [] + for name, table, slot, target in TABLES: + if struct.unpack('