Apply recovered player phases, static camera query and level availability

This commit is contained in:
UnixNight committed 2026-10-25 19:56:44 -04:00
1 parent 117db77c7b
commit 09cf1172bf
33 files changed
+1500 -99

No files matched your search

+4 -2
View File
@@ -9,8 +9,10 @@ services are used.
[checkpoint review](docs/checkpoint/review.md), [coverage map](docs/checkpoint/coverage.md)
and [implementation plan](docs/checkpoint/implementation-plan.md) compare source
owners, update order and lifecycles with the port. Clean69d0187 and its packages
are preserved locally as the playable baseline. Task/objective and Carl callback
ordering are the first verified corrections from this investigation.
are preserved locally as the playable baseline. Corrections now include task/Carl
callbacks, controlled player phase ordering, source static camera queries for the
first route and gadget availability through tutorial/return. Full scene scheduling,
collision and shared camera state remain incomplete.
**Current milestone: original lab story, interactions and jet pack practice flow.**
The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
+4
View File
@@ -14,6 +14,10 @@ primary ownership. Follow-ups cover [lab registry](lab-registry.md),
[scene loader](scene-loader.md). All investigators have returned file ownership.
Primary owns integration/runtime corrections. [Exit review](review.md) records
checkpoint completion, verified changes and the next evidence gates.
Implementation continuation: [level-game lifetime](level-game-lifetime.md),
[retained character resets](retained-character-reset.md), and
[player phase implementation](player-phase-implementation.md). These supersede
the old-game-removal question and record the first C3/C5/C7 implementation chunks.
Evidence labels used throughout:
+11
View File
@@ -15,6 +15,17 @@ nearest-hit support query or swept camera sphere would produce a different
algorithm. Full follow-camera integration still requires camera state continuity,
source angle/previous-eye handling and the remaining input-mode branches.
**Implementation continuation:** `OriginalCameraRay` now implements these source
grids and shares the individual segment kernel with `OriginalBodySupport` while
preserving support's nearest-hit reducer. Program uses this query for LV1B/VR04/
LEV1. Player follow consumes one query per input callback, source hit adjustment
and1.5 gain; the post-interpolation sphere sweep is removed for these scenes.
Other scene filters and synthetic fixtures keep the explicit provisional adapter.
Eleven managed groups verify route registration counts and synthetic order/kernel/
filter cases; a separate movement consumer check asserts origin, gain and absence
of a second query. Shared viewport/DEFAULT handoff and full follow state remain
open, so this is static-obstruction recovery rather than whole-camera fidelity.
## Actual caller arguments and unused actor getter
Jimmy complete vtable4A3BDC, slot16C at4A3D48 (fileA3D48), resolves43B820.
+16 -11
View File
@@ -2,15 +2,17 @@
Checkpoint scope: lab → tutorial VR04 → lab → outside, including intro,
explanation, pickup/practice, RETURN, Carl conversation and exit. This compares
source contracts with playable baseline69d0187, not all gameplay in all levels.
source contracts with the current port and preserved playable baseline69d0187,
not all gameplay in all levels. Rows marked “now” include the implementation
continuation; the original baseline remains a separate comparison point.
Address details/PE offsets and source-byte extractors are in the linked reports.
**S**=static/data recovery, **P**=isolated original component probe,
**M**=managed port regression, **R**=port runtime. No row has full original-game
runtime comparison. Coverage does not mean implementation completeness.
| ID / system | Recovered contract / anchors | Baseline implementation | Evidence / remaining gap | Next bounded action |
| ID / system | Recovered contract / anchors | Port implementation | Evidence / remaining gap | Next bounded action |
|---|---|---|---|---|
| LOOP | Viewport47E4F0: physics479BC0 before registry473740, including game input44DF80; second sync473770; list50999C construction order. Separate millisecond engine logic/morph clock100F9B10. | Fixed60Hz grouped controller→physics→NPC→director→UI→morph. | S/M/R. Source pass/input bridge recovered; actual cadence and retained/spawned-object order still open. | C3: construction/reuse registry trace before changing scheduler. |
| 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. |
| 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. | Recovered arithmetic placed in same-tick controller→physics; fixed dt, custom yaw/model conventions. | S/P/M/R. Local arithmetic evidence does not validate enclosing phase. | Split pending velocity/impulse only after C3 oracle. |
| 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. |
@@ -18,10 +20,11 @@ runtime comparison. Coverage does not mean implementation completeness.
| 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. |
| CAMERA | Shared viewport; strict>1000 DEFAULT snap;43B820 ray correction;47C210 first wall-grid hit then first general-grid hit, FIFO cells; source per-level far planes. | Shot-time interpolation, separate chase eye stale during cutscenes, fixed follow gains and nearest sphere obstruction; merged max far plane. | S/M/R. Static grid predicate/filters now recovered; x87 boundaries, source angle/previous-eye and input branches open. | C5: static source adapter then shared camera handoff/follow; no nearest-hit substitution. |
| 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+74C/+74D deferred scene request; selective teardown/reuse;Jimmy/Goddard retention; per-object28→40C. RETURN root+9A8/flags954/9A5, restore423A90, STRT suppress4427F2. | RuntimeCheckpoint carried root/return bool, reconstructed actors/audio, app-owned presentation. | S/M/R. Core loader chain recovered; per-field resets, retained helper/current-game lifetime and fades open.50988A is editor R input, not load reset. | C7: retained-field/route lifecycle trace, then state-container integration; keep modern presentation. |
| 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. | Snapshot/reconstructed scene state with retained input-order identity; app-owned presentation. | S/M/R. Old-game removal closed. Per-field/helper resets and fades remain;50988A is editor R input. | C7: retained-field/route lifecycle fixtures, then state-container integration. |
| INVENTORY | PostLoad423DEF..423EC1 enables eight owned gadgets4→1, then VR01..08 disables1→4; other values/items 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 retained scalar state remain incomplete. | 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. |
@@ -42,18 +45,20 @@ runtime comparison. Coverage does not mean implementation completeness.
## Assumptions and symptom-level adapters to replace
1. Fixed60Hz and controller-before-physics currently make tests deterministic;
they are not recovered original scheduling. Preserve arithmetic tests but do
not treat existing travel measurements as the source oracle.
1. Fixed60Hz remains a deterministic port policy. Baseline controller-before-
physics has now been replaced for the controlled player; other grouped scene
callbacks and morph timing remain incomplete. Preserve arithmetic tests but
do not treat existing travel measurements as the source oracle.
2. Floor snap/visual sole correction and24-unit swept capsule solve visible
penetration/navigation symptoms. They do not recover Jimmy's body/root geometry
or47BD80 response. Keep rendering pivot and physics support investigations separate.
3. Carl activation is applied after a generic actor batch in the baseline;
source virtual callbacks execute per actor in registry order. C2 replaces this
adapter without inventing full NPC sensing.
4. Chase interpolation/sphere clipping and DEFAULT's simple camera reset mask
camera ownership gaps. Per-level far limits are recovered; merged-layer maximum
is a rendering policy pending masks/fog, not complete clipping recovery.
4. Route static sphere clipping is now replaced by source grids/kernel. Chase
state and DEFAULT's simple camera reset still mask ownership gaps. Per-level
far limits are recovered; merged-layer maximum is a rendering policy pending
masks/fog, not complete clipping recovery.
5. File duration is a cutscene completion estimate. The source also uses software
duration, but integer elapsed boundaries, repeat, invalid/stopped channels,
clock pause and effects-bank ownership remain lifecycle inputs. SDL queue-empty
+23
View File
@@ -53,3 +53,26 @@ allowed where it resolves a core-system question, without waiting for every leve
- Exit review: core architecture checkpoint documented in `review.md`; feature
expansion remains paused. C1/C2 full integration passes; final follow-up Python
discovery and original hashes recorded under artifacts/re-checkpoint/.
- C3/C7 gate closed: normal Init copies stored+11 to live+139, restoring the
level game's deletion predicate. Destructor explicitly unlinks its registry
node. `level-game-lifetime.md` and three byte regressions retain that proof.
- C3 first implementation: controlled player physics consumes prior motion/queued
impulse before input/player/fire callbacks. Fresh versus retained input order
follows proven registration; stored mode and same-frame landing reset are
explicit. Twenty movement groups, input-only routes and GPU RETURN pass targeted
checks. Full-scene scheduling, uncontrolled-body and collision response remain open.
- C5 static adapter implemented/integrated for LV1B/VR04/LEV1: source cell/FIFO/
wall-first predicate and single-triangle kernel, source eye adjustment/gain,
one query per input callback. Eleven camera groups and existing support groups
pass; full camera handoff/input state remains open.
- C7 availability correction: level entry enables state4→1 for the recovered eight
gadgets, then VR01..08 disables owned1→4. Unknown states/other groups preserved;
tutorial bypass unchanged. Source anchors and boundary/round-trip tests cover it.
Arbitrary retained scalar/mode/fire state is still gated by the streamer/lifecycle
fixture; no blanket carry was introduced.
- Full integration passes: artifacts/implementation/integration-final.log.
Seventy Python checks, all managed groups including20 movement/11 camera/
13 support, GPU story/route/practice/RETURN/jetpack/animation with zero validation
errors, SDL dummy lifecycle and539 unchanged hashes. RETURN also verifies
retained input order and tutorial availability normalization. Packages rebuilt
after the implementation milestone; platform runtime claims remain separate.
+99
View File
@@ -0,0 +1,99 @@
# C3/C7: old level-game deletion is restored by ordinary initialization
Static source recovery,2026-10-25. Original Neutron.exe SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below are EXE addresses. Their physical offsets are VA−400000;
the read-only helper independently uses PE section mapping and emits both.
No original was modified or executed. No modern runtime code was edited here.
## Resolved distinction: stored defaults versus live state
The prior loader report correctly found the lab class-default initializer's
virtual204(0) at44D472, but that writes **live interface+139 only**. The
constructor-reachable class-default stage is not the final lifetime state.
The normal initialization pass subsequently restores live state from a separate
stored field, **interface+11**. This resolves the apparent preserved-old-game
contradiction without inferring destruction from overwriting509948.
| Stage | Original instruction / function | Effect |
|---|---|---|
| Generic constructor |46FDB3 pushes1;46FDB7 →470F40 | Setter writes stored+11 and dispatches204 to set live+139 |
| Class defaults |44D456 pushes0;44D472 invokes204 | Live+139 becomes0, stored+11 remains1 |
| Normal per-object initialization |46E5C3 invokes slot28 | Lab/tutorial/outside game slot28 is44D4E0 |
| Game base initialization |44D4E0 jumps4587F0;4587F3 calls470540 | Enters the common initialization bridge |
| Restore effective lifecycle state |4705B3 invokes8C getter470F30, pushes result4705B9,4705BC invokes204 setter4719C0 | Reads stored+11 and writes live+139 |
| PostLoad |46E61A invokes40C after28 for each object | Game has already restored its ordinary live teardown predicate1 |
| Ordinary departure |46E032/46E06F/46E0AC call200 getter4719B0 | Getter reads live+139; game qualifies for all three teardown passes |
This common initializer also copies other stored/editor configuration fields to
live fields. Do not generalize every corresponding field as persisted gameplay
state: the +11→+139 bridge is specifically proven here.
Route game interface tables:
- Lab4C386C, tutorial VR04 4CE4AC, outside4C561C all resolve28→44D4E0,
8C→470F30 and204→4719C0.
- 470F30 reads byte[interface+11].4719C0 writes byte[interface+139] from its
argument.4719B0 reads that live field for the teardown predicate.
- The usual game interface is complete+8C for level-game objects, unlike Jimmy's
complete+C0. Pointer bases must remain explicit.
## Actual deletion and registry removal
For initialized old level games with live+139=1, ordinary transition46DFF0:
1. Calls slot20 in the first filtered traversal at46E054.
2. Calls slot34 in the second filtered traversal at46E091.
3. Sets interface+6=1 in the third traversal at46E0CA.
4. Calls473710 at46E0D9. That sweep finds marked objects, invokes interface
slot0 with argument1 at473733..737, then restarts the global list scan.
Lab slot0 at4C386C points44F610: subtract5C converts game interface+8C to the
destructor's complete+30 subobject, then jumps44F3F0. That scalar deleting
wrapper calls44F420; its base call44F499→44D390 jumps44D3C2→4746E0.
The game destructor calls4587E0 at47476A with its game interface, and4587E0
jumps470060, the common interface destructor.
The common destructor explicitly scans registry50999C at4700E5, matches the
dying interface against node+8 at4700F2, and erases matching nodes using
469490 at470106 with list object509998. This is the actual old-game registry
removal edge. It precedes allocation/registration of the destination game in
46E170. Existing current-game pointer509948 can temporarily refer to the old
object during teardown; destination construction overwrites it later, but that
overwrite is not the operation responsible for deletion.
There is no need to model accumulating old level-game input callbacks for the
normal route: the initialized live flag selects ordinary deletion. Abnormal
paths that bypass normal Init or mutate the stored/live flags require separate
evidence and are outside this successful-load case.
## Why Jimmy and Goddard differ
Jimmy4226B5..BF and Goddard41C99B..9E invoke470F40 with0. Unlike the game's
class-default virtual204(0), this updates **both** stored+11 and live+139.
Common Init therefore restores0 for these retained characters, and their
positive reusable+9 fields allow GAM/object lookup reuse without re-appending
their nodes. Those constructor values, their reuse flag and any later field
resets are separate concepts.
Fresh lab order game→Jimmy→fire remains proven by lab-registry.md. On a
successful later ordinary load the old game is deleted, retained nodes keep
their order, and the new game is appended afterward. Thus relative input versus
Jimmy order can differ from fresh construction. Complete retained helper-node
and per-field reset coverage is still needed before claiming all callback
ordering or all transition state is recovered.
## Verification and implementation consequence
`checkpoint_level_game_lifetime.py ../Original` checks the binary identity,
decisive stored/live flag, initialization, teardown and destructor/unlink bytes,
plus route vtable targets. Its tests guard the actual source contract rather
than a speculative lifecycle simulation. This is static evidence, not observed
original gameplay.
The normal old-level-game removal gate is now closed. C3 can preserve retained
object insertion order while deleting/replacing the level-game callback owner,
instead of freezing fresh game-before-Jimmy order for every transition. Keep
the port's application-owned window/Vulkan session as the authorized modern
presentation policy. Remaining source gates are per-field character/helper
reset rules, exact timer/event-pump behavior and original runtime comparison.
@@ -0,0 +1,79 @@
# C3 implementation: player phase boundaries
The first implementation chunk separates the controlled player's prior-body
physics, game input, player controller, owned fire effect and camera-input update.
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`.
## Source contract and implementation
EXE47E554 calls479BC0 physics before473740 game-object callbacks47E582;473770
sync follows47E587. A fresh game registers before Jimmy, and Jimmy before his
owned fire. Retained Jimmy/fire precede the newly appended destination game.
The level-game deletion predicate is restored by normal initialization; a
constructor-default zero is not the final gameplay lifetime flag. The focused
lifetime report records the complete vtable/field provenance.
`LabSimulation.Step` now integrates **existing** velocity, acceleration and queued
impulse first. Fresh input then produces speed/destination yaw, the player update
produces velocity/impulse for the next physics pass, and fire ticks afterward.
On scene continuation, the player/fire update precedes the destination input
callback. `InputAfterPlayerUpdate` records this specific retained registry relation;
it does not claim all source objects are retained by the current port.
Input uses the stored movement mode, as438B1E..438B2A does, rather than deriving
it from current physical support. Held jump selects air mode at437A96. Grounded
released-jump reset437B9E..437BAC clears jump state, mode and turn in the **player**
callback. Landing can therefore clear turn on the same frame physics finds support.
Jump queues impulse after physics and requests its pose; it does not retroactively
move the body or falsely clear its physical supported state that frame.
Source addresses above have EXE raw offsets VA−400000. The helper verifies the
hashed supplied EXE, maps PE offsets and checks9 decisive instruction sequences.
No original code was executed for these source assertions.
## Verification and remaining limits
Movement regressions assert old velocity before current input, one-time delayed
impulse consumption, fresh versus retained ordering, independent movement mode,
landing reset and unchanged fixed-step presentation independence. Input-only lab
navigation still reaches SCENE35→50→60 and the outside LOAD. This is port evidence,
not original timing/latency fidelity. Source nominal frame rate remains unproven;
the port keeps its explicit60Hz policy.
The existing capsule/gravity adapter remains. Source479DF7..479E54 can cancel
gravity on a support hit before a queued jump, giving a different first takeoff
velocity. Applying that cancellation to the provisional capsule's prior support
flag caused false support transitions in the port; it must be integrated with
the recovered pre-integration support/response in C4, not bolted onto that flag.
No source-fidelity claim is made for jump apex, stairs, wall response or visual
pivot. The underground replay checks clearance of the recovered radius60 body,
not raw209-unit standing-mesh bounds, which are a separate provisional render
scale/pivot policy. Closed-gate collision and both directional crossings remain
required. This clarifies the physical assertion rather than inferring a collider
from the render mesh.
Other scene callbacks still run in subsystem groups. Uncontrolled player physics
and control-release body preparation need their own source trace before changing
cutscene behavior. Engine morph logic remains on the port animation clock. These
are explicit next scheduler boundaries, not claimed solved by this player chunk.
Bounded follow-up anchors for that next boundary (static reads, not implemented
here): Jimmy game vtable4A373C+410→42AFC0 calls43A750 at42AFC3.43A758 clears
speed interface608;43A76C calls2C4 with three zero arguments. That target471F40
writes interface1A4/1A8/1AC. Map this preparation to the body consumer before
changing uncontrolled physics or resumption. Slot438→42AE00 additionally calls
complete178→427FF0 and sets interface1D65/global4F8182. These callbacks belong
to CAM/MCA ownership transfer, rather than interpreting null control as a whole
world pause. Lateral input complete870 is written by walking input43915D/4391B1/
439226; its cross-mode lifetime is another scalar coupling to verify when filling
out the phase state model. The present chunk does not claim all controller fields.
Final verification: full scripts/test.sh passes, log
`artifacts/implementation/integration-final.log`;20 movement groups and the new
11 camera groups, existing support/interaction/route suites, all GPU replays with
zero enabled-validation errors, SDL dummy tests and539 original hashes unchanged.
The70 Python checks include the new mode/phase and lifecycle source anchors.
Baseline69d0187 and current240-step completed walks have essentially identical
travel/final position; within-frame producer/consumer timing is tested separately.
+151
View File
@@ -0,0 +1,151 @@
# Retained character resets: bounded C3/C7 contract
Static investigation,2026-10-25. Originals remain read-only and were not executed.
Neutron.exe SHA256 is
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
All code/vtable anchors below are preferred-base EXE VAs; PE-mapped raw file
offset is VA−400000 for these sites. The new helper prints both coordinates and
checks individual bytes, virtual targets and source route GAM properties.
This report distinguishes proven local resets from fields whose enclosing
retention/property/callback semantics remain unresolved. No runtime code changed.
## Enclosing ordinary-load phases
The common loader evidence remains `scene-loader.md`: selective teardown, GAM
factory/reuse/property stream, then registry per-object28 followed immediately
by40C. Jimmy/Goddard can survive and be reused; that alone does not imply every
field survives. Jimmy uses game-interface complete+C0; shadow uses complete+C8.
Keep constructor/default-class initialization separate from callbacks28/40C.
The object property read at46E3FD uses IAT48D190, imported
`OMediaStreamOperators::operator>>(OMediaClassStreamer*)`. Route JIM1 property
records contain authored position/rotation/flags/StartPoint and no serialized
jump/movement-mode/burn timer field. This is a statement about decoded records,
not proof the read implementation cannot indirectly invoke another callback.
Full streamer virtual call provenance is still a separate gate.
## Jimmy initialization: exact resets and a coordinate correction
Jimmy interface vtable4A373C+28→437890. It first calls4587F0 at437896;
4587F0→470540 applies generic authored/live-property setters, then calls
interface68(1). Jimmy-specific43789B..4378C1 then:
| Instruction / raw offset | Field and recovered effect |
|---|---|
|4378A1 /378A1|Clear interface608 = complete6C8 (movement speed in existing recovery)|
|4378A7 /378A7|Clear interface614 = complete6D4 (air turning accumulator)|
|4378AD /378AD|Clear interface618 = complete6D8; full semantic name unresolved here|
|4378B8 /378B8|Invoke interface328 =4723F0, the logical Euler-vector getter|
|4378BE..4378C1 /378BE..378C1|Copy that vector's Y into interface61C = complete6DC|
**Correction:** interface328 is not velocity.4723F0 copies interface224/228/
22C/230, the logical Euler vector (position is214/218/21C/220). Therefore the
earlier scene-loader wording “captures another velocity component” is stale.
The clear618/capture61C pair should remain unnamed or associated with yaw
tracking until its consumers are traced; do not carry it as vertical velocity.
Generic470540 additionally clears interface274/278/27C and298 at4709CA..9DC,
then sets byte5=1 and bytesA/6=0. This report does not name that vector as impulse
without tracing the actual body consumer. It also re-applies authored defaults
through virtual getters/setters, so absence of a direct scalar write in437890
alone is not proof of scalar preservation.
## Jimmy PostLoad40C
Vtable4A373C+40C→423610. Selected proven effects relevant to transition state:
| Site | State transition / ownership |
|---|---|
|42363B|Clear interface1D91; semantic name not assigned|
|423642..423656|Load default SoundEffects.omt, set current bank696008; gate4F8434 initially clear|
|4236A3/4236AA|Set current interaction/body radius60 through interface110|
|4236B3/4236BA|Set support factor1.265f through interface100|
|4236C0|Clear interface938 (tutorial flag later set for VR01..08)|
|4236FF|Current game virtual168(0), a gameplay/modal state callback; do not equate every control state with world pause|
|42370A and423729|Complete11C(0) for Jimmy and existing companion; both resolve40D350 and disable morph animation pause flag complete654, not jump/movement mode|
|42375E/423778|Stop associated saved effect handles through458A00, mark handles974/988 as−1|
|42378B /2378B|Clear WORD interface728 = complete7E8, the jump state, to0|
|423792|Clear interface970 temporary object pointer before later allocation|
|42399D/4239E6|Apply matching STRT root and Euler rotation|
|423A90..423B1E|Consume pending RETURN flag, override Jimmy with saved departure root, apply identical companion root|
|423B3D|Grant control through current game virtual118|
|423B43..423C67|Write shared viewport: authored STRT camera occurs inside match loop, later unconditional actor-local(0,200,−300) overwrites viewport eye|
|423CD4..423CE2|When companion already exists, call its interface174(0,0,0); constructor is not repeated|
The final viewport assignment explains why merely carrying the old chase-eye
cache would not reproduce source scene entry. Full orientation/follow cache
setup remains in the camera investigation. The unconditional final eye uses
local(0,200,−300), distinct from DEFAULT's local(0,500,−500) conditional snap.
### Movement mode, fire and transition staging limits
Player constructor43748A initializes complete7C4 movement mode0, but the inspected
JimmyInit28 and JimmyPostLoad40C do not establish an unconditional reset of this
field. PostLoad does explicitly reset jump state7E8 as above. Stage43B5A0 is
called with the complete player pointer; its complete148 call43B7FB resolves
429A00, which stops sound handle completeA44 and assigns−1. That callback does
not reset movement mode or fire time. Stage also clears complete7FC at43B5EE.
Do not promote absence of writes in these bounded local functions to a complete
preservation proof: game/streamer/control callbacks and class-specific gadget
cleanup can change player state elsewhere. In particular RETURN457FF7 performs
gadget cleanup before flags/staging, distinct from ordinary stage. Carrying raw
movement mode, held input, physics vectors or arbitrary jump timers across scenes
is not yet justified by this report. The current port's blanket constructor
zeroing is likewise an implementation policy, not a recovered reset contract.
## Retained fire/shadow/companion callbacks
| Object | Constructor-only state | Ordinary per-object28 /40C |
|---|---|---|
|Jetpack fire complete+C0 interface4A3160|421E51 calls470F40(0), selecting retention;421E62 zeros complete6BC owner and421E68 zeros complete6C0 timer; player437525 later assigns owner interface to6BC|28=4587F0 generic Init;40C=40E7B0 generic visibility/animation policy. Neither local path assigns owner6BC or timer6C0. No repeated constructor assumed.|
|Shadow complete+C8 interface4B37B8|43F767 calls470F40(0); authored size/owner are separate from runtime position|28=4587F0;40C=43F810→4354C0, then copies authored size words to completeAC/B0, resets completeB4=2/B8=0 and optional visibility flag. More base4354C0 effects remain open.|
|Goddard complete+C0 interface49F480|Ctor sets retention/reuse and owns shadow; aliases/defaults are constructor state|28=41E6A0→407EB0→4587F0; then byteA=1, AIstate608=authored87C, current waypoint800=null.40C=41E590→409480, then level-specific visibility/collision/radius policy.|
Fire421FB0 later queries its owner and, when grounded, clears timer interface600
(complete6C0) at421FE9, then subtracts dt. That is an **effect tick**, not an
initialization reset. It can observe the controller's same-pass changes according
to the recovered registry ordering. Timer preservation through local28/40C does
not prove it survives the entire transition unchanged without an intervening
owner/gadget/frame callback; exact first destination tick remains a lifecycle test.
Goddard's ordinary PostLoad sets radius130 and enables normal body behavior for
LV1B/VR04/LEV1; source-level hide branches cover other levels. Its existing-instance
callback174 is4716D0, not a constructor. Full rotation/AI resource resets in
409480 are not recovered here; retain the earlier patrol approximations explicitly.
## Directly evidenced implementation candidate: gadget availability
JimmyPostLoad **always first enables** group0 gadgets in source order
`7,3,0,5,1,6,2,4` via403870(false), calls423DEF..423E3F. For numeric
VR01..VR08 it then calls403870(true) for those same indices at423E71..423EC1.
At40389E, disabling changes only owned state1→4; at4038AA enabling changes only
4→1. All other values are preserved, including unowned0 and unknown wire values.
This is availability state, not ownership acquisition or inventory reset.
For the route: lab entry converts disabled-owned4→1; practice VR04 converts
owned1→4; return lab converts4→1. The VR04 powered-jump path bypasses the normal
inventory state guard, so source state4 here does not imply the tutorial jetpack
should fail. Lab→outside similarly normalizes these group0 entries; tasks, score
and acquired-table state remain independent. The audited baseline lacked this
availability pass. Continuation now calls `SceneInventory.ApplyLevelAvailability`
once on level entry, before starting the authored sequence, and preserves raw
values in constructors/snapshots and arbitrary task assignments. Managed tests
cover every VR01..08 code, all relevant/unknown state boundaries, both untouched
inventory regions and TSK round-trip back to lab. GPU practice/RETURN smoke also
asserts state4 in VR04 and state1 on lab return. This correction does not invent
persistence for arbitrary physics/mode/fire fields.
## Verification and remaining gates
Run `python3 -m unittest discover -s tests -p test_checkpoint_character_reset.py -v`
and `python3 tools/binary/checkpoint_character_reset.py ../Original`. Tests verify
31 immutable instruction anchors,11 callback/vtable targets,16 exact gadget-call
arguments, source route player property names, and conditional1/4 conversion
boundaries. The state oracle tests interpretation, not execution of source code.
Remaining gates: complete property-streamer callback chain; RETURN gadget cleanup
versus ordinary departure; movement-mode/fire/hold/extra-acceleration writer
provenance through all destination callbacks; physical body re-registration/reset;
full shadow base reset and Goddard409480 policy; source camera orientation/cache
reset. Do not carry these fields merely because object identity persists.
+6
View File
@@ -1,5 +1,11 @@
# Checkpoint exit and implementation continuation
Implementation has since continued: the old-game Init/deletion gate is resolved,
controlled player phases are split, the route static camera query is integrated,
and PostLoad gadget availability is applied. 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 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
+14 -10
View File
@@ -79,7 +79,7 @@ retention and the current-level global509948 are distinct: GAM loading assigns
Further class-specific lifecycle flags or later predicate changes require their
own evidence; do not generalize the constructor default into a full object map.
**Critical integration consistency gate: old level-game ownership.** The lab game
**Resolved follow-up: old level-game ownership.** The lab game
is initialized for preservation (interface4C386C slots200/204 resolve
4719B0/C0; defaults bridge above reaches44D456's push0/44D472's dispatch204).
Later changes to that predicate remain part of the lifetime audit. GAM loading then
@@ -95,12 +95,16 @@ The lab constructor chain44F300→44F358/44D2B0→44D306/4745A0 was also inspect
destructor/removal was established in this inspected chain. **Overwriting the
current-game pointer does not remove an old game from registry50999C.**
Consequently the remaining contract must include the old level-game registry
membership and callback eligibility: locate its explicit removal/deactivation
or account for its retained28/40C/update callbacks. Do not infer a clean sequence
containing only Jimmy/Goddard plus the new game from selective deletion alone.
Possible later class/OMT ownership effects remain open; this negative bounded
audit does not prove that old games accumulate or remain active at runtime.
The subsequent audit in `level-game-lifetime.md` closes this gap: normal Init28
calls470540, whose4705B3 getter8C reads stored interface+11 through470F30;
4705BC setter204 copies it to live+139. Generic game construction stored+11=1;
the direct defaults204(0) never changed that stored value. Thus initialized level
games qualify for selective teardown. Their destructor reaches470060 and
explicitly removes their registry node at470106→469490. Jimmy/Goddard instead
use470F40(0), setting both stored/live fields, so initialization preserves their
retention. The earlier bounded prefix/constructor search was incomplete; pointer
overwrite is still not deletion, but Init and destructor now establish actual
old-game removal and retained-character/new-game ordering.
## GAM construction/reuse and initialization
@@ -127,7 +131,7 @@ registry in order. It invokes object28, handles attached render-object state,
then object40C, handles attached render state again, then advances registry.
These are per-object boundaries, not “initialize all, then PostLoad all.” Jimmy's
28 is437890; it calls4587F0→470540 and resets movement fieldsinterface+608/+614/
+618 and captures another velocity component+61C. Jimmy40C423610 applies:
+618 and captures logical Euler.Y (yaw) into+61C, not body velocity. Jimmy40C423610 applies:
1. Matching source STRT root42399D and rotation4239E6.
2. Existing companion source root423A36.
@@ -176,8 +180,8 @@ force original editor R semantics into the game's current R reset control.
## Bounded continuation gate
1. Resolve old level-game removal/deactivation and callback eligibility across
destination construction. Then trace a retained Jimmy through one departure,
1. Old level-game removal is now resolved by the Init stored/live flag bridge and
destructor unlink. Trace a retained Jimmy through one departure,
identifying every mutation
from property load, initialization and PostLoad. Constructor evidence closes
byte+9 ownership; it does not substitute for this per-field reset trace.
+10
View File
@@ -3,6 +3,16 @@
Compilation, native runtime, original behavior and full feature completion are
separate evidence categories. **The game is not fully reconstructed/playable yet.**
Latest implementation continuation: controlled player phase ordering, route static
camera query and PostLoad gadget availability pass the full `scripts/test.sh`.
Evidence: artifacts/implementation/integration-final.log;70 Python regressions,
20 movement groups,11 new camera groups,13 existing support groups, remaining
managed groups, GPU story/practice/RETURN/Carl/objective/jetpack/animation checks,
SDL dummy lifecycle and539 unchanged original hashes. GPU validation is enabled
and every run reports zero errors. Native Windows runtime and original-game
comparison are not added by these tests. Known limits remain explicit in the
current checkpoint coverage/implementation reports.
Architecture checkpoint: see `checkpoint/review.md` for coverage and remaining
gates. C1 objective/task order and C2 per-actor Carl callback corrections pass the
full `scripts/test.sh` integration, all GPU runs with zero Vulkan validation
+16
View File
@@ -112,3 +112,19 @@
pre-assignment notification rather than relying on subscriber registration
order. Preserve repeated/missing assignment dispatch. Source loader's additional
task callbacks/PostLoad are a distinct lifecycle question, not implied by this fix.
25. **Consume prior player motion before callbacks.** Split controlled player
physics, input, controller and fire effect phases. Fresh input precedes Jimmy;
retained Jimmy/fire precede the appended destination game/input. Track this
relation explicitly across scene continuations. Mode-based input and the
player's grounded-release reset are separate boundaries. Keep fixed60Hz,
capsule/support and other grouped scene callbacks explicit approximations.
26. **Use the source static camera predicate on proven route scenes.** Build
sparse grids in source shape/polygon order, prefer the first wall-grid hit,
then the first all-grid hit. Use the individual source segment kernel without
nearest reduction; apply source desired-eye weighting and gain before follow
interpolation. Only LV1B/VR04/LEV1 filters are proven. Shared camera handoff,
special follow/input state and exact x87 boundaries remain separate work.
27. **Apply gadget availability at level entry.** Source PostLoad enables eight
group0 gadgets4→1, then disables owned1→4 in VR01..08. Preserve unknown states,
item8 and group1. This is availability, not acquisition or save normalization;
snapshots/constructors retain raw wire data. VR04's source jetpack bypass remains.
+33
View File
@@ -1,5 +1,38 @@
# Progress — 2026-10-25
## Evidence-led implementation continuation
Old level-game removal is resolved by `checkpoint/level-game-lifetime.md`: class
defaults briefly clear live+139, but normal Init restores it from stored+11=1;
the destructor explicitly removes the registry node. Jimmy/Goddard instead store
0 and remain retained/reusable. Three new immutable-source regressions guard it.
Implemented controlled player prior-body physics → fresh input/player/fire, or
retained player/fire/input after scene continuation. Jump impulses wait for the
next body pass; input uses stored mode, and grounded release clears turn inside
the player callback. Current fixed60Hz, capsule/grounding, uncontrolled-body and
other grouped scene phases remain provisional. Twenty targeted movement groups
and lab/underground routes pass; GPU lab→VR04→lab verifies retained input order.
Implemented `OriginalCameraRay` for LV1B/VR04/LEV1: source static grids, FIFO
wall-first hit, individual segment kernel, source eye weighting/gain and one query
per input callback. Eleven camera groups and existing13 support groups pass.
Camera shared-state handoff and full follow/input modes remain open.
Implemented PostLoad gadget availability1↔4 for the recovered eight group0 items;
tutorial entry/normal return, unknown values, untouched regions and TSK round-trip
are tested. VR04 bypass remains. Arbitrary retained mode/fire state is not carried
without the remaining property/control callback proof. Details and exact limits:
`checkpoint/player-phase-implementation.md`, `retained-character-reset.md`.
Full `scripts/test.sh` passes (artifacts/implementation/integration-final.log):
70 Python checks, all managed groups including20 movement/11 camera/13 support,
GPU route/story/practice/RETURN/jetpack/animation with zero validation errors,
SDL dummy lifecycle and539 unchanged original hashes. RETURN smoke confirms
retained input ordering and enabled gadget state1 after tutorial state4. The
preserved baseline's240-step walk and new phase implementation have essentially
identical completed travel/final position, with the intended within-frame delay
verified separately. No native Windows/original runtime comparison is claimed.
## Architecture reverse-engineering checkpoint
User direction supersedes feature-expansion priorities below. Full `prompt.MD`
+10 -3
View File
@@ -58,9 +58,16 @@ plan in verified chunks. Earlier priorities below are a backlog.
- [x] C2 per-actor Carl override; full integration and route checks pass.
- [x] C3 input/frame/fresh construction, C5 grid predicate, C6 software voice clock
and C7 ordinary selective-loader evidence follow-ups.
- [ ] Next: current-game registry removal/eligibility and retained Jimmy/helper
resets; then split scheduler phases against a source route lifecycle trace.
Static camera adapter can proceed independently with source first-hit rules.
- [x] Old level-game lifetime resolved: normal Init restores stored+11→live+139;
ordinary destructor explicitly unlinks its registry node.
- [x] Controlled player phase split and retained input order; delayed impulses,
stored movement mode and same-frame landing reset. Full-scene scheduler open.
- [x] Static first-hit camera adapter integrated for LV1B/VR04/LEV1 with shared
segment kernel and source hit weighting/gain. Full camera handoff/state open.
- [x] Source PostLoad gadget availability through tutorial/normal level entry.
- [ ] Next: retained mode/fire/body reset fixture through the full property/control
callback chain, remaining scene callback/morph phases, shared viewport/DEFAULT
handoff and C4 collision. C6 source channel allocation/clock/banks remains separate.
1. Lab regressions are corrected and republished, with user verification of their
own Windows build. Keep comprehensive native Windows driver/audio/input
+1
View File
@@ -9,6 +9,7 @@ dotnet run --project tests/GamePort.MovementTests -- ../Original
dotnet run --project tests/GamePort.DirectorTests -- ../Original
dotnet run --project tests/GamePort.PatrolTests -- ../Original
dotnet run --project tests/GamePort.SupportTests -- ../Original
dotnet run --project tests/GamePort.CameraRayTests
dotnet run --project tests/GamePort.InteractionTests -- ../Original
dotnet run --project tests/GamePort.CheckpointTests -- ../Original
dotnet run --project tests/GamePort.DebugMenuTests -- ../Original
+2 -2
View File
@@ -21,8 +21,8 @@ public readonly record struct JetpackEffectResult(
/// <summary>
/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0.
/// Controller and effect phases are separate: their full-scene order has not
/// been recovered. The caller must explicitly choose an order. Horizontal
/// Controller and effect phases are separate. The normal route registry places
/// Jimmy before his retained fire; other full-scene phases remain incomplete. Horizontal
/// movement, shadow queries, visuals and sound callbacks belong to the caller.
/// </summary>
public static class JetpackBurst
+83 -29
View File
@@ -15,9 +15,12 @@ public sealed class LabSimulation
{
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision;
private readonly Func<Vector3, Vector3, SupportHit?>? cameraRay;
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance;
private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution;
private Vector3 pendingImpulse;
private int movementMode;
private JetpackBurstState jumpState;
private bool forceFall;
public Func<int>? JetpackInventoryState { get; set; }
@@ -31,11 +34,17 @@ public sealed class LabSimulation
public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; }
public Vector3 PendingImpulse => pendingImpulse;
public int MovementMode => movementMode;
// Fresh game registers before Jimmy. A retained Jimmy precedes the newly
// appended destination game, whose input callback therefore runs later.
public bool InputAfterPlayerUpdate { get; set; }
public float Yaw { get; private set; }
public float Speed { get; private set; }
public float TurnRate { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
public PlayerPose Pose => pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; }
@@ -51,9 +60,11 @@ public sealed class LabSimulation
public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw)
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw,
Func<Vector3, Vector3, SupportHit?>? cameraRay = null)
{
this.collision = collision;
this.cameraRay = cameraRay;
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
@@ -76,13 +87,14 @@ public sealed class LabSimulation
Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw;
Speed = TurnRate = extraAirAcceleration = shadowDistance = 0;
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
jumpState = default;
forceFall = JetpackEffectVisible = false;
InteractionRadius = 60; Bursts = 0;
Grounded = true;
Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0;
CameraEye = DesiredEye();
CameraEye = DesiredEye().Eye;
}
/// <summary>Jimmy PostLoad423A90..423ABF restores the saved RETURN root.
@@ -92,7 +104,7 @@ public sealed class LabSimulation
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z))
throw new ArgumentOutOfRangeException(nameof(root));
Position = root - Vector3.UnitY * rootHeight;
CameraEye = DesiredEye();
CameraEye = DesiredEye().Eye;
}
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
@@ -105,19 +117,29 @@ public sealed class LabSimulation
}
public void Step(PlayerInput input)
{
//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);
var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode);
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
if (InputAfterPlayerUpdate) StepInput(input);
Steps++;
}
private void StepInput(PlayerInput input)
{
const float dt = FixedStepClock.Step;
var wasGrounded = Grounded;
float lateral = 0;
if (Grounded)
lateralContribution = 0;
//438A60 dispatches by stored movement mode, not current support.
if (movementMode == 0)
{
//437B9E..437BAC uses an interface pointer: interface+614 is
//complete+6D4. Normal grounded/released input clears air turn.
if (!input.Jump) TurnRate = 0;
InteractionRadius = 60; // Jimmy's ordinary grounded update42469B.
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Left) { yawDelta += 20; lateralContribution = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateralContribution = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
@@ -131,15 +153,29 @@ public sealed class LabSimulation
//438011..43802B adds the independent turn rate directly to yaw.
targetYaw = Yaw;
}
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
}
private void StepPlayer(PlayerInput input)
{
const float dt = FixedStepClock.Step;
var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 360;
if (Velocity.LengthSquared() != 0 || Grounded && lateral != 0)
//437A96 selects air mode on held jump;437B9E..BAC resets jump/mode/turn
//only in the player's grounded/released update, after input when fresh.
if (input.Jump) movementMode = 1;
else if (Grounded)
{
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);
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
//437CDx ground uses /45 then dt;43803B air uses /55 without dt.
const float friction = .8f;
var sideSpeed = Grounded ? (TurnRate * (1 - friction) * Speed / 45 + lateral) * dt
var sideSpeed = movementMode == 0 ? (TurnRate * (1 - friction) * Speed / 45 + lateralContribution) * dt
: TurnRate * (1 - friction) * Speed * .0181818176060915f;
velocity += new Vector3(cos, 0, sin) * sideSpeed;
if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
@@ -147,14 +183,26 @@ public sealed class LabSimulation
var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
var impulse = new Vector3(0, air.ImpulseY, 0);
if (air.ImpulseY != 0) { Grounded = false; Jumps++; }
pendingImpulse += new Vector3(0, air.ImpulseY, 0);
if (air.ImpulseY != 0) Jumps++;
if (air.MovementModeOverride is { } mode) movementMode = mode;
if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
if (air.RadiusOverride is { } radius) InteractionRadius = radius;
if (air.Pose == JetpackPose.Fall) forceFall = true;
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (air.StartGadget) Bursts++;
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
Velocity = velocity; // Produced body state is consumed by the next physics pass.
}
private void StepPhysics()
{
const float dt = FixedStepClock.Step;
var wasGrounded = Grounded;
var velocity = Velocity;
// Keep the existing capsule/gravity adapter until C4 recovers Jimmy's
// pre-integration support/response. Source479DF7..479E54 can cancel
// gravity before a supported impulse; this adapter does not model that.
var displacement = RecoveredMotion.Integrate(ref velocity, ref pendingImpulse,
Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
@@ -175,24 +223,30 @@ public sealed class LabSimulation
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
Velocity = velocity;
// Explicit port phase policy: controller, collision, then effect update.
// Original global object iteration order has not yet been matched.
var effect = JetpackBurst.StepEffect(jumpState, Grounded, dt, Energy, LevelCode);
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
if (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
Steps++;
var desired = DesiredEye();
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
CameraEye = collision.ClipCamera(CameraTarget, CameraEye + delta);
}
private Vector3 DesiredEye()
private void StepCamera()
{
const float dt = FixedStepClock.Step;
var desired = DesiredEye();
var delta = (desired.Eye - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * desired.Gain * dt;
CameraEye = cameraRay == null ? collision.ClipCamera(CameraTarget, CameraEye + delta) : CameraEye + delta;
}
private (Vector3 Eye, float Gain) DesiredEye()
{
var (sin, cos) = Trig(Yaw);
return collision.ClipCamera(CameraTarget, ActorRoot + new Vector3(sin * 350, 180, -cos * 350));
var eye = ActorRoot + new Vector3(sin * 350, 180, -cos * 350);
if (cameraRay == null) return (collision.ClipCamera(CameraTarget, eye), 1);
//43B820: query from the computed look target; first accepted static hit
//moves desired eye25% toward look and returns follow gain1.5. No radius
//or second sweep after interpolation occurs in that source callback.
return cameraRay(CameraTarget, eye) is { } hit
? (CameraTarget - (CameraTarget - hit.Position) * .75f, 1.5f) : (eye, 1);
}
public static PlayerInput SmokeInput(int step) => new(step < 120, false, false,
+43 -25
View File
@@ -107,35 +107,53 @@ public static class OriginalBodySupport
var nearestDistance = length;
foreach (var triangle in triangles)
{
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
var edge1 = triangle.B - triangle.A;
var edge2 = triangle.C - triangle.A;
var p = Cross(direction, edge2);
var determinant = Dot(edge1, p);
// Source indices use the opposite sign from a conventional right-
// handed visible-front-face test. Preserve the actual serialized order.
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
continue;
var inverse = 1 / determinant;
var relative = start - triangle.A;
var u = Dot(relative, p) * inverse;
if (u < 0 || u > 1) continue;
var q = Cross(relative, edge1);
var v = Dot(q, direction) * inverse;
if (v < 0 || u + v > 1) continue;
var distance = Dot(q, edge2) * inverse;
// Source accepts the beginning, but rejects its endpoint and equal
// distance candidates. No invented extra ray distance or skin is used.
if (distance < 0 || distance >= length) continue;
var position = start + direction * distance;
var fromStart = QuickMagnitude(position - start);
if (fromStart >= nearestDistance) continue;
nearestDistance = fromStart;
nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart);
var hit = IntersectSegment(triangle, start, direction, length, twoSided);
if (hit is not { } candidate || candidate.Distance >= nearestDistance) continue;
nearestDistance = candidate.Distance;
nearest = candidate;
}
return nearest;
}
/// <summary>
/// EXE469B70's individual source-winding triangle test, without47C6E0's
/// nearest-hit reduction. Camera47C210 instead accepts the first grid hit.
/// </summary>
public static SupportHit? IntersectSegment(SupportTriangle triangle,
Vector3 start, Vector3 end, bool twoSided = false)
{
RequireFinite(start); RequireFinite(end);
var direction = end - start;
var length = QuickMagnitude(direction);
if (length == 0) return null;
return IntersectSegment(triangle, start, direction / length, length, twoSided);
}
private static SupportHit? IntersectSegment(SupportTriangle triangle,
Vector3 start, Vector3 direction, float length, bool twoSided)
{
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
var edge1 = triangle.B - triangle.A;
var edge2 = triangle.C - triangle.A;
var p = Cross(direction, edge2);
var determinant = Dot(edge1, p);
// Preserve serialized winding, opposite to the conventional visible front.
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
return null;
var inverse = 1 / determinant;
var relative = start - triangle.A;
var u = Dot(relative, p) * inverse;
if (u < 0 || u > 1) return null;
var q = Cross(relative, edge1);
var v = Dot(q, direction) * inverse;
if (v < 0 || u + v > 1) return null;
var distance = Dot(q, edge2) * inverse;
// Beginning accepted, endpoint rejected; no invented camera radius/skin.
if (distance < 0 || distance >= length) return null;
var position = start + direction * distance;
return new SupportHit(position, triangle.ShapeId, triangle.PolygonId, QuickMagnitude(position - start));
}
private static float Dot(Vector3 a, Vector3 b) =>
(float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z);
private static Vector3 Cross(Vector3 a, Vector3 b) => new(
+151
View File
@@ -0,0 +1,151 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public readonly record struct CameraRayPolygon(SupportTriangle Triangle, Vector3 StoredNormal,
string? ShapeName = null, string? MaterialName = null);
public readonly record struct CameraRayResult(Vector3 Eye, float Gain, SupportHit? Hit);
/// <summary>
/// Source47C210 static camera predicate: first accepted wall-grid polygon, then
/// first general-grid polygon. Cell rectangle order and FIFO registration matter;
/// this is not the support query's nearest-hit reducer or a camera sphere sweep.
/// See checkpoint/camera-ray-predicate.md for addresses and approximation limits.
/// </summary>
public sealed class OriginalCameraRay
{
public const int GridSize = 260;
public const float CellScale = 0.0020000000949949026f; //4D6A04.
public const float CellOrigin = 130; //49B1FC.
private readonly Dictionary<int, List<SupportTriangle>> walls = [];
private readonly Dictionary<int, List<SupportTriangle>> all = [];
public bool Enabled { get; set; } = true; //4F69E5.
public int PolygonCount { get; }
public int WallPolygonCount { get; }
/// <summary>Modern query diagnostic; repeated cells are intentionally counted.</summary>
public int LastTriangleTests { get; private set; }
/// <summary>
/// Caller supplies raw, untranslated static source triangles. Registration
/// follows shape resource ID then polygon array index, not render-draw order.
/// Game-specific polygon exclusion must be resolved by the caller.
/// </summary>
public OriginalCameraRay(IEnumerable<CameraRayPolygon> polygons)
{
ArgumentNullException.ThrowIfNull(polygons);
var identities = new HashSet<(int Shape, int Polygon)>();
foreach (var polygon in polygons.OrderBy(p => p.Triangle.ShapeId).ThenBy(p => p.Triangle.PolygonId))
{
if (polygon.ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) == true
|| IsCheckpoint(polygon.MaterialName)) continue;
var triangle = polygon.Triangle;
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
RequireFinite(polygon.StoredNormal);
if (!identities.Add((triangle.ShapeId, triangle.PolygonId)))
throw new InvalidDataException("Camera query needs one source triangle per polygon; fan-triangulated polygons are unsupported");
var wall = polygon.StoredNormal.Y < .7f; //4798B3; equality excluded.
var min = Vector3.Min(triangle.A, Vector3.Min(triangle.B, triangle.C));
var max = Vector3.Max(triangle.A, Vector3.Max(triangle.B, triangle.C));
foreach (var cell in CellsBetween(min, max))
{
Append(all, cell, triangle);
if (wall) Append(walls, cell, triangle);
}
PolygonCount++;
if (wall) WallPolygonCount++;
}
}
/// <summary>
/// LV1B/VR04/LEV1 complete game slot134 is475CD0 (false), so only the proven
/// NC/checkpoint gates apply. Reject other levels rather than inventing masks.
/// Prepared source metadata is required; raw render visibility is irrelevant.
/// </summary>
public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode)
{
ArgumentNullException.ThrowIfNull(mesh);
if (levelCode is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery currently covers LV1B, VR04 and LEV1");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original camera query requires source polygon metadata");
var polygons = new CameraRayPolygon[mesh.CollisionPolygons.Length];
for (var i = 0; i < polygons.Length; i++)
{
var source = mesh.CollisionPolygons[i];
var a = mesh.Indices[i * 3]; var b = mesh.Indices[i * 3 + 1]; var c = mesh.Indices[i * 3 + 2];
if (a >= mesh.Vertices.Length || b >= mesh.Vertices.Length || c >= mesh.Vertices.Length)
throw new InvalidDataException("Camera triangle index outside vertex table");
polygons[i] = new(new(mesh.Vertices[a].Position, mesh.Vertices[b].Position, mesh.Vertices[c].Position,
source.ShapeId, source.PolygonIndex), source.Normal, source.ShapeName, source.MaterialName);
}
return new(polygons);
}
/// <summary>47C210/47C280/47C4B0: increasing X, increasing Z, FIFO first hit.</summary>
public SupportHit? Trace(Vector3 start, Vector3 end, bool twoSided = false)
{
RequireFinite(start); RequireFinite(end);
LastTriangleTests = 0;
if (!Enabled) return null;
foreach (var grid in new[] { walls, all })
foreach (var cell in CellsBetween(start, end))
if (grid.TryGetValue(cell, out var triangles))
foreach (var triangle in triangles)
{
LastTriangleTests++;
if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit)
return hit;
}
return null;
}
/// <summary>43B820: ray originates at computed look target, never actor root.</summary>
public CameraRayResult Constrain(Vector3 lookPoint, Vector3 desiredEye)
{
var hit = Trace(lookPoint, desiredEye);
return hit is { } accepted
? new(lookPoint - (lookPoint - accepted.Position) * .75f, 1.5f, accepted)
: new(desiredEye, 1, null);
}
/// <summary>
///47F940 truncation then signed16. Double intermediates approximate source
/// x87, not bit-exact boundary emulation. Conversion overflow is unsupported.
/// </summary>
public static short CellCoordinate(float value)
{
if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value));
var scaled = (double)value * CellScale + CellOrigin;
if (scaled <= long.MinValue || scaled >= long.MaxValue)
throw new ArgumentOutOfRangeException(nameof(value), "Original x87 integer-overflow behavior is not recovered");
return unchecked((short)(long)Math.Truncate(scaled));
}
private static IEnumerable<int> CellsBetween(Vector3 a, Vector3 b)
{
var ax = (int)CellCoordinate(a.X); var bx = (int)CellCoordinate(b.X);
var az = (int)CellCoordinate(a.Z); var bz = (int)CellCoordinate(b.Z);
var minX = Math.Max(0, Math.Min(ax, bx)); var maxX = Math.Min(GridSize - 1, Math.Max(ax, bx));
var minZ = Math.Max(0, Math.Min(az, bz)); var maxZ = Math.Min(GridSize - 1, Math.Max(az, bz));
for (var x = minX; x <= maxX; x++)
for (var z = minZ; z <= maxZ; z++) yield return GridSize * x + z;
}
private static void Append(Dictionary<int, List<SupportTriangle>> grid, int cell, SupportTriangle triangle)
{
if (!grid.TryGetValue(cell, out var list)) grid.Add(cell, list = []);
list.Add(triangle);
}
private static bool IsCheckpoint(string? material) => material is not null
&& (material.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase)
&& material[6] is >= '1' and <= '9');
private static void RequireFinite(Vector3 vector)
{
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
throw new ArgumentOutOfRangeException(nameof(vector), "Finite source coordinates required");
}
}
+18
View File
@@ -24,6 +24,24 @@ public sealed class SceneInventory
public void SetState(int group, int item, int state) => states[Offset(group, item)] = state;
/// <summary>
/// Jimmy PostLoad423DEF..423EC1: enable these eight owned gadgets, then
/// disable them in numeric VR01..VR08. State4 is unavailable ownership,
/// distinct from unowned0. Other wire values and item8 remain unchanged.
/// </summary>
public void ApplyLevelAvailability(string levelCode)
{
ArgumentNullException.ThrowIfNull(levelCode);
ReadOnlySpan<int> items = [7, 3, 0, 5, 1, 6, 2, 4];
foreach (var item in items)
if (states[item] == 4) states[item] = 1;
// Exactly the eight original FourCC values in the source numeric range.
if (levelCode.Length == 4 && levelCode.StartsWith("VR0", StringComparison.Ordinal)
&& levelCode[3] is >= '1' and <= '8')
foreach (var item in items)
if (states[item] == 1) states[item] = 4;
}
public void SelectGadget(int item)
{
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
+13 -4
View File
@@ -300,8 +300,14 @@ internal static class Program
throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y)
{ LevelCode = level!.Code };
if (walking)
{
var cameraRay = level!.Code is "LV1B" or "VR04" or "LEV1"
? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y,
cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye))
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
}
if (walking && returning) simulation!.RestoreReturnRoot(returnRoot);
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model;
@@ -321,6 +327,7 @@ internal static class Program
storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save);
interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy;
@@ -442,13 +449,15 @@ internal static class Program
&& Vector3.Distance(simulation.ActorRoot, returnRoot) < .001f
&& Vector2.Distance(new(returnRoot.X, returnRoot.Z), new(originalStart!.Position.X, originalStart.Position.Z)) > 100;
var companionRestored = director.FindActor("C3DGODDARD")?.Position == returnRoot;
restored &= companionRestored;
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}.");
restored &= companionRestored && simulation.InputAfterPlayerUpdate && interactions.Inventory.State(0, 3) == 1;
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) { sceneAudio?.StopSpeech(); director.Skip(); }
if (practiceReturnSmoke && level.Code == "VR04")
{
if (interactions!.Inventory.State(0, 3) != 4)
throw new InvalidOperationException("Tutorial PostLoad did not disable the owned gadget before VR04's bypass");
director.Skip();
interactions!.Update(level.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest is not { Returning: true }) throw new InvalidOperationException("VR04 exit did not preserve RETURN identity");
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/OriginalCameraRay.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" />
<Compile Include="../../src/GamePort/Assets/AssetPath.cs" />
</ItemGroup>
</Project>
+151
View File
@@ -0,0 +1,151 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
var count = 0;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: {actual} != {expected}");
void Test(string name, Action action) { action(); count++; Console.WriteLine($"PASS {name}"); }
void Reject<T>(Action action, string message) where T : Exception
{
try { action(); } catch (T) { return; }
throw new Exception(message);
}
SupportTriangle Horizontal(float y, int shape = 1, int polygon = 0) =>
new(new(-10, y, -10), new(10, y, -10), new(0, y, 10), shape, polygon);
CameraRayPolygon Wall(float y, int shape = 1, int polygon = 0) => new(Horizontal(y, shape, polygon), Vector3.Zero);
CameraRayPolygon Floor(float y, int shape = 1, int polygon = 0) => new(Horizontal(y, shape, polygon), Vector3.UnitY);
var high = new Vector3(0, 100, 0);
var low = Vector3.Zero;
Test("farther FIFO wall hit wins over nearer wall and general-grid floor", () =>
{
var ray = new OriginalCameraRay([Wall(20, 1), Wall(80, 2), Floor(90, 0)]);
var hit = ray.Trace(high, low);
Check(hit?.ShapeId == 1 && hit?.PolygonId == 0, "camera used nearest rather than first source wall");
Near(hit!.Value.Position.Y, 20, .00001f, "first wall point");
Near(hit.Value.Distance, 80, .00001f, "first wall distance");
var nearest = OriginalBodySupport.Trace([Horizontal(20, 1), Horizontal(80, 2), Horizontal(90, 0)], high, low);
Check(nearest?.ShapeId == 0, "support nearest reduction changed while extracting the shared kernel");
var result = ray.Constrain(high, low);
Near(result.Eye.Y, 40, .00001f, "source .25look+.75hit point");
Check(result.Gain == 1.5f && result.Hit == hit, "obstructed gain/identity");
});
Test("registration uses shape and polygon identities rather than render order", () =>
{
var ray = new OriginalCameraRay([Wall(80, 7, 2), Wall(20, 7, 1), Wall(90, 8, 0)]);
Check(ray.Trace(high, low)?.PolygonId == 1, "source polygon registration FIFO changed");
ray = new([Wall(80, 7), Wall(20, 3)]);
Check(ray.Trace(high, low)?.ShapeId == 3, "source shape registration order changed");
});
Test("inclusive cell rectangle scans increasing X and Z even against ray direction", () =>
{
SupportTriangle PlaneX(float x, int id) => new(new(x, -10, -10), new(x, -10, 10), new(x, 10, 0), id);
var rayX = new OriginalCameraRay([new(PlaneX(900, 1), Vector3.Zero), new(PlaneX(100, 2), Vector3.Zero)]);
Check(rayX.Trace(new(1000, 0, 0), Vector3.Zero)?.ShapeId == 2,
"grid rectangle should test farther lower-X cell first");
SupportTriangle PlaneZ(float z, int id) => new(new(-10, -10, z), new(0, 10, z), new(10, -10, z), id);
var rayZ = new OriginalCameraRay([new(PlaneZ(900, 1), Vector3.Zero), new(PlaneZ(100, 2), Vector3.Zero)]);
Check(rayZ.Trace(new(0, 0, 1000), Vector3.Zero)?.ShapeId == 2,
"inner grid rectangle should test farther lower-Z cell first");
});
Test("missed polygons are tested again in each cell and in fallback grid", () =>
{
var triangle = new SupportTriangle(new(-10, 0, 0), new(10, 0, 0), new(0, 0, 600));
var ray = new OriginalCameraRay([new(triangle, Vector3.Zero)]);
Check(ray.Trace(new(0, 10, 1), new(0, 10, 501)) == null, "parallel segment fabricated hit");
Check(ray.LastTriangleTests == 4, "query silently deduplicated source repeated-cell candidates");
});
Test("general grid fallback, stored-normal threshold and source winding", () =>
{
var ray = new OriginalCameraRay([new(Horizontal(50), new(0, .7f, 0))]);
Check(ray.PolygonCount == 1 && ray.WallPolygonCount == 0, "normal.Y equality must be excluded from wall grid");
Check(ray.Trace(high, low).HasValue && ray.LastTriangleTests == 1, "general grid fallback missing");
Check(ray.Trace(low, high) == null, "source backface accepted");
Check(ray.Trace(low, high, true).HasValue, "two-sided source override rejected");
var reverse = Horizontal(50) with { B = Horizontal(50).C, C = Horizontal(50).B };
Check(new OriginalCameraRay([new(reverse, Vector3.UnitY)]).Trace(high, low) == null, "serialized winding was reversed");
});
Test("beginning accepted, endpoint rejected, zero-length and degenerate triangles miss", () =>
{
var ray = new OriginalCameraRay([Floor(0)]);
Check(ray.Trace(new(0, 20, 0), low) == null, "strict segment endpoint accepted");
Check(ray.Trace(low, new(0, -20, 0)).HasValue, "beginning was rejected by an invented skin");
Check(ray.Trace(low, low) == null, "zero segment fabricated hit");
var degenerate = new OriginalCameraRay([new(new(Vector3.Zero, Vector3.Zero, Vector3.Zero), Vector3.Zero)]);
Check(degenerate.Trace(high, low) == null, "degenerate triangle fabricated hit");
Check(ray.Trace(new(0, 20, 0), new(0, .001f, 0)) == null, "triangle beyond segment accepted");
});
Test("NC shapes and checkpoint materials filter registration, null material remains", () =>
{
var ray = new OriginalCameraRay([
new(Horizontal(90, 1), Vector3.Zero, "NCwater"),
new(Horizontal(80, 2), Vector3.Zero, null, "CSTART"),
new(Horizontal(70, 3), Vector3.Zero, null, "cCHECK9"),
new(Horizontal(60, 4), Vector3.Zero, "ordinary", null),
new(Horizontal(50, 5), Vector3.Zero, null, "ccheck0"),
new(Horizontal(40, 6), Vector3.Zero, null, "ccheck10")]);
Check(ray.PolygonCount == 3 && ray.WallPolygonCount == 3, "source registration filters differ");
Check(ray.Trace(high, low)?.ShapeId == 4, "invisible null-material proxy was excluded");
});
Test("source enable flag and unobstructed gain leave desired eye unchanged", () =>
{
var ray = new OriginalCameraRay([Wall(50)]) { Enabled = false };
var result = ray.Constrain(high, low);
Check(result.Eye == low && result.Gain == 1 && result.Hit == null && ray.LastTriangleTests == 0,
"disabled predicate queried geometry or moved eye");
ray.Enabled = true;
result = ray.Constrain(new(100, 100, 100), new(100, 0, 100));
Check(result.Eye == new Vector3(100, 0, 100) && result.Gain == 1 && result.Hit == null, "miss changed eye or gain");
});
Test("stored float cell scale, negative truncation, signed16 domain and out-of-grid misses", () =>
{
Check(BitConverter.SingleToInt32Bits(OriginalCameraRay.CellScale) == 0x3b03126f, "source cell scale changed");
Check(OriginalCameraRay.CellCoordinate(-1) == 129 && OriginalCameraRay.CellCoordinate(0) == 130,
"negative coordinate cell conversion changed");
Check(OriginalCameraRay.CellCoordinate(-65000) == 0 && OriginalCameraRay.CellCoordinate(-65500) == -1,
"source truncation near negative grid edge differs");
Check(OriginalCameraRay.CellCoordinate(1_000_000) == 2130, "out-of-grid conversion incorrectly clamps cells");
var ray = new OriginalCameraRay([Floor(50)]);
Check(ray.Trace(new(1_000_000, 100, 1_000_000), new(1_000_000, 0, 1_000_000)) == null,
"out-of-grid source query fabricated hit");
});
Test("malformed, nonfinite and unsupported scene contracts reject explicitly", () =>
{
Reject<InvalidDataException>(() => new OriginalCameraRay([Wall(20), Wall(80)]), "ambiguous source polygon identity accepted");
Reject<ArgumentOutOfRangeException>(() => new OriginalCameraRay([new(Horizontal(20), new(float.NaN, 0, 0))]), "nonfinite normal accepted");
var ray = new OriginalCameraRay([Wall(50)]);
Reject<ArgumentOutOfRangeException>(() => ray.Trace(new(float.NaN, 0, 0), low), "nonfinite segment accepted");
Reject<ArgumentOutOfRangeException>(() => OriginalCameraRay.CellCoordinate(float.MaxValue), "unknown x87 overflow silently emulated");
var empty = new Mesh([], []);
Reject<NotSupportedException>(() => OriginalCameraRay.FromRouteScene(empty, "LV2A"), "unrecovered game filter silently assumed false");
Reject<InvalidDataException>(() => OriginalCameraRay.FromRouteScene(new Mesh(new MeshVertex[3], [0, 1, 2]), "LV1B"),
"missing polygon source metadata accepted");
});
Test("original route geometry registration counts and retained invisible polygons", () =>
{
var prepared = Path.GetFullPath(args.Length > 0 ? args[0] : "artifacts/extracted");
foreach (var (scene, code, polygons, walls) in new[] {
("level1b", "LV1B", 2851, 2483), ("VR04", "VR04", 508, 420), ("level1", "LEV1", 5231, 3860) })
{
var mesh = Mesh.LoadSceneJson(AssetPath.Resolve(prepared, scene + "/scene.json"));
var ray = OriginalCameraRay.FromRouteScene(mesh, code);
Check(ray.PolygonCount == polygons && ray.WallPolygonCount == walls,
$"{scene} original polygon/wall registration differs: {ray.PolygonCount}/{ray.WallPolygonCount}");
if (scene == "level1b")
Check(mesh.Draws.Sum(d => (long)d.IndexCount) < mesh.Indices.Length, "lab proxy visibility fixture changed");
}
});
Console.WriteLine($"Camera ray checks: {count} groups passed. Source ordering/kernel translation verified; original runtime and x87 boundary equivalence remain unverified.");
+50
View File
@@ -0,0 +1,50 @@
# Static source camera query checks
Run from GamePort:
```sh
source scripts/env.sh
dotnet run --project tests/GamePort.CameraRayTests
dotnet run --project tests/GamePort.SupportTests
```
Optional first argument selects the prepared-scene root (default
`artifacts/extracted`). Original geometry is prepared separately; these tests
do not modify or execute original files.
`OriginalCameraRay.FromRouteScene(mesh, levelCode)` accepts only LV1B, VR04 and
LEV1, whose original game polygon-filter slot134 is475CD0 (false). It retains
source shape/polygon identity and stored normals, excludes NC/checkpoint records,
and rejects included fan-triangulated polygon identities rather than changing the
original first-three-corner rule. All included polygons in these three original
scenes are triangles. Original registration counts are2851/2483 wall (lab),
508/420 (VR04),5231/3860 (outside).
Source anchors and exact file offsets are recorded in
`docs/checkpoint/camera-ray-predicate.md` and checked by
`tests/test_checkpoint_camera_ray.py`. Critical contracts are47C210 wall-first
then general-grid fallback;47C280/47C4B0 inclusive ascending X/Z rectangle and
FIFO first accepted polygon;479800 tail insertion and4798B3 normal.Y<.7;
469A10/469B70 one-sided segment/triangle kernel and strict endpoint rejection.
43B820 applies `.25*look+.75*hit` and returns gain1.5; a miss leaves eye/gain1.
API: `Trace(start,end,twoSided=false)` returns optional SupportHit;
`Constrain(look,desired)` returns CameraRayResult(Eye,Gain,Hit). Enabled is the
per-adapter representation of source global4F69E5. PolygonCount/WallPolygonCount
and LastTriangleTests are modern diagnostics; repeated cells count repeated
triangle tests. OriginalBodySupport.IntersectSegment shares the recovered
individual kernel while its existing Trace retains nearest reduction.
The checks exercise source route counts and deliberately non-nearest results,
cell direction, FIFO identity, repeated candidates, fallback, normal threshold,
winding/sidedness, beginning/end, degenerate segments, filters, proxy retention,
enable flag, look-point weighting, negative/signed16 cells and malformed inputs.
They verify this port implementation and source data, not original running-game
behavior or whole-camera integration.
Limits: grid conversion uses double intermediates in place of x87 extended
precision; exact boundary equivalence and integer overflow remain unrecovered.
Finite values outside supported signed64 conversion throw. Lookup tables retain
the existing support module's modern-trig limitation. Other level-specific
polygon filters, missing shape IDs, nonidentity terrain transforms, camera input
modes and shared viewport/follow update state remain outside this adapter.
@@ -155,6 +155,34 @@ inventory.SetState(0, 3, 0); Throws(() => inventory.SelectGadget(3));
inventory.SetState(0, 3, 1); inventory.SelectGadget(3); Check(inventory.SelectedGadget == 3, "Owned gadget selection");
Console.WriteLine("PASS inventory bounds, ownership, unknown-state preservation and gadget availability");
foreach (var state in new[] { int.MinValue, -1, 0, 1, 2, 3, 4, 5, int.MaxValue })
{
foreach (var tutorial in Enumerable.Range(1, 8).Select(i => "VR0" + i))
{
var availability = new SceneInventory(Enumerable.Repeat(state, 19));
availability.ApplyLevelAvailability(tutorial);
var disabled = state is 1 or 4 ? 4 : state;
Check(Enumerable.Range(0, 8).All(i => availability.State(0, i) == disabled),
"Tutorial PostLoad only disables owned states1/4");
Check(availability.State(0, 8) == state && Enumerable.Range(0, 10).All(i => availability.State(1, i) == state),
"PostLoad availability preserves gadget8 and the independent inventory group");
var carried = OriginalSave.Parse((original with { InventoryStates = availability.Snapshot() }).Encode());
var returned = new SceneInventory(carried.InventoryStates);
returned.ApplyLevelAvailability("LV1B");
Check(Enumerable.Range(0, 8).All(i => returned.State(0, i) == (state is 1 or 4 ? 1 : state)),
"Serialized tutorial state returns to enabled owned gadgets in lab");
}
}
foreach (var normal in new[] { "LV1B", "LEV1", "VR00", "VR09", "vr04" })
{
var availability = new SceneInventory(Enumerable.Repeat(4, 19));
availability.ApplyLevelAvailability(normal);
Check(availability.State(0, 3) == 1 && availability.State(0, 8) == 4,
"Normal/fourcc-boundary PostLoad enables selected owned gadgets only");
}
Check(JetpackBurst.CanStart("VR04", -1, 4, 20), "Tutorial jetpack bypass still works with disabled inventory state4");
Console.WriteLine("PASS source PostLoad gadget availability, tutorial boundaries and lab RETURN round-trip");
// Independently recover the original SCENE setter's two dispatch tables rather
// than testing the port's switch against another manually copied switch.
var exe = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe"));
+80 -9
View File
@@ -8,6 +8,8 @@ var tests = new (string Name, Action Check)[]
{
("60 simulation calls across 60/120/144 Hz presentation", ClockRates),
("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries),
("physics consumes prior motion; fresh versus retained input order", FrameOrdering),
("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer),
("turn-only speed, forward acceleration/cap and release", SpeedLimits),
("backpedal cap and release", Backpedal),
("yaw sign, forward half-turn and left precedence", Turning),
@@ -59,6 +61,69 @@ static void ClockBoundaries()
Throws<ArgumentOutOfRangeException>(() => clock.Advance(elapsed));
}
static void FrameOrdering()
{
var fresh = FlatSimulation();
var origin = fresh.Position;
var forward = new PlayerInput(true, false, false, false, false);
fresh.Step(forward);
NearVector(fresh.Position, origin, .0001f, "input cannot move an already integrated body");
Near(fresh.Speed, 30, 0, "fresh input runs before player callback");
Near(fresh.Velocity.Z, 30, 0, "player produces velocity for the next physics pass");
fresh.Step(forward);
Near(fresh.Position.Z - origin.Z, 30 * FixedStepClock.Step, .0001f, "next physics consumes previous30, not current60");
var retained = FlatSimulation();
retained.InputAfterPlayerUpdate = true;
retained.Step(forward);
Near(retained.Speed, 30, 0, "new level game updates retained player's input later");
Near(retained.Velocity.Z, 0, 0, "retained player callback preceded first destination input");
retained.Step(forward);
NearVector(retained.Position, origin, .0001f, "second retained physics still sees old zero velocity");
Near(retained.Velocity.Z, 30, 0, "retained player now produces prior input speed");
retained.Step(forward);
Near(retained.Position.Z - origin.Z, 30 * FixedStepClock.Step, .0001f, "retained third physics consumes first input");
var jump = FlatSimulation();
jump.Step(new(false, false, false, false, true));
NearVector(jump.Position, origin, .0001f, "queued jump cannot retroactively change physics");
Near(jump.PendingImpulse.Y, 550, 0, "jump impulse remains pending until next body pass");
Check(jump.Grounded && jump.Pose == PlayerPose.Jump, "jump animation request does not change physical support");
jump.Step(default);
Near(jump.PendingImpulse.Y, 0, 0, "next body pass consumes queued impulse exactly once");
Near(jump.Velocity.Y, 550 - 800 * 1.33f * FixedStepClock.Step, .0001f,
"next body pass applies one impulse plus the retained provisional gravity adapter");
Check(!jump.Grounded && jump.Position.Y > origin.Y, "queued jump takes off on following body pass");
jump.Step(default);
Check(jump.Velocity.Y < 550 && jump.Velocity.Y > 500, "later body pass adds acceleration without repeating impulse");
jump.Reset();
NearVector(jump.PendingImpulse, Vector3.Zero, 0, "reset clears pending physical work");
Check(jump.MovementMode == 0, "reset restores stored walking input mode");
}
static void CameraQueryConsumer()
{
var enabled = false;
var queries = 0;
var lastLook = Vector3.Zero;
var lastDesired = Vector3.Zero;
SupportHit? Query(Vector3 look, Vector3 desired)
{
queries++; lastLook = look; lastDesired = desired;
return enabled ? new SupportHit((look + desired) / 2, 7, 9, 0) : null;
}
var simulation = FlatSimulation(cameraRay: Query);
var before = simulation.CameraEye;
var beforeQueries = queries;
enabled = true;
simulation.Step(default);
NearVector(lastLook, simulation.CameraTarget, .0001f, "ray origin is look target rather than actor root");
var adjusted = lastLook + (lastDesired - lastLook) * .375f;
var expected = before + (adjusted - before) * new Vector3(1.6f, 1.2f, 1.6f) * 1.5f * FixedStepClock.Step;
NearVector(simulation.CameraEye, expected, .0001f, "source hit weighting and follow gain feed interpolation");
Check(queries == beforeQueries + 1, "no additional camera obstruction query after interpolation");
}
static void SpeedLimits()
{
var turn = FlatSimulation();
@@ -102,7 +167,8 @@ static void Turning()
Near(left.Yaw, -right.Yaw, .00001f, "opposed keyboard yaw symmetry");
Near(forwardLeft.Yaw, left.Yaw / 2, .00001f, "Up halves target turn offset");
Near(forwardLeft.Speed, 60, 0, "Up plus turn performs both speed increments");
Check(left.Position.X < 0 && right.Position.X > 0, "keyboard side-velocity signs");
Check(left.Velocity.X < 0 && right.Velocity.X > 0, "keyboard side-velocity signs for next physics pass");
Near(left.Position.X, 0, .0001f, "turn input waits for subsequent physics");
var both = FlatSimulation();
var leftOnly = FlatSimulation();
@@ -138,8 +204,8 @@ static void JumpLanding()
var simulation = FlatSimulation();
var floor = simulation.Position.Y;
simulation.Step(new(false, false, false, false, true));
Check(!simulation.Grounded && simulation.Velocity.Y > 500 && simulation.Jumps == 1 && simulation.Pose == PlayerPose.Jump,
"jump takes off with one queued impulse");
Check(simulation.Grounded && simulation.PendingImpulse.Y == 550 && simulation.Jumps == 1 && simulation.Pose == PlayerPose.Jump,
"jump queues once after physics and requests its animation");
var sawFall = false;
var largestHeight = simulation.Position.Y;
for (var i = 0; i < 120; i++)
@@ -164,7 +230,7 @@ static void HeldJump()
for (var i = 0; i < 150; i++) simulation.Step(default);
Check(simulation.Jumps == jumpCount && simulation.Grounded, "release stops held repetition and lands");
simulation.Step(new(false, false, false, false, true));
Check(simulation.Jumps == jumpCount + 1 && !simulation.Grounded, "new grounded press starts another jump");
Check(simulation.Jumps == jumpCount + 1 && simulation.PendingImpulse.Y == 550, "new grounded press queues another jump");
}
static void AirArithmetic()
@@ -196,6 +262,7 @@ static void AirControl()
{
var simulation = FlatSimulation();
simulation.Step(new(false, false, false, false, true));
simulation.Step(default); // Consume the queued takeoff before airborne input.
var origin = simulation.Position;
for (var i = 0; i < 20; i++)
{
@@ -262,10 +329,14 @@ static void LandingTurn()
{
var simulation = FlatSimulation();
simulation.Step(new(true, false, false, false, true));
for (var i = 0; i < 120 && !simulation.Grounded; i++)
var largestAirTurn = 0f;
for (var i = 0; i < 120 && (i == 0 || !simulation.Grounded); i++)
{
simulation.Step(new(true, false, initialLeft, !initialLeft, false));
Check(simulation.Grounded && MathF.Abs(simulation.TurnRate) > 20,
"Landing fixture retains an opposing air turn before outer grounded reset");
largestAirTurn = MathF.Max(largestAirTurn, MathF.Abs(simulation.TurnRate));
}
Check(simulation.Grounded && largestAirTurn > 20 && simulation.TurnRate == 0,
"Physics landing precedes the same-frame player update clearing air turn");
var before = simulation.Yaw;
simulation.Step(new(true, false, !initialLeft, initialLeft, false));
Near(simulation.TurnRate, 0, 0, "grounded released-jump reset clears shared air-turn field");
@@ -376,7 +447,7 @@ static void OriginalLab(string project, string originals)
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor");
}
static LabSimulation FlatSimulation(float yaw = 0)
static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, SupportHit?>? cameraRay = null)
{
var positions = new[]
{
@@ -386,7 +457,7 @@ static LabSimulation FlatSimulation(float yaw = 0)
var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One),
new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw, cameraRay);
}
static void SameState(LabSimulation actual, LabSimulation expected, string message)
@@ -136,14 +136,15 @@ void Tick(PlayerInput input)
director.Touch(level.Player.Tag!, simulation.ActorRoot);
interactions.Update(simulation.ActorRoot, simulation.InteractionRadius);
mechanisms.Update(simulation.ActorRoot, simulation.InteractionRadius);
// Test actual aperture clearance when crossing the gate plane, before this
// frame's mechanism movement. The resolver uses this same current transform.
// Test the recovered radius60 root body when crossing the gate plane,
// before mechanism movement. Raw standing mesh height is a provisional
// visual/pivot policy, not the dynamic collider used by the source adapter.
if ((previous.Z - bars.Position.Z) * (simulation.ActorRoot.Z - bars.Position.Z) < 0)
{
var box = visuals.DoorColliders().Single();
var minimumY = DynamicSceneCollision.Corners(box).Min(p => p.Y);
Require(minimumY > simulation.Position.Y + simulation.BodyHeight,
"Replay crossed the bars before the moving doorway cleared the player");
Require(minimumY > simulation.ActorRoot.Y + simulation.InteractionRadius,
"Replay crossed the bars before the moving doorway cleared the recovered body");
crossings++;
}
mechanisms.Step(FixedStepClock.Step);
+49
View File
@@ -0,0 +1,49 @@
"""Retained-character source evidence and state-conversion boundaries."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from checkpoint_character_reset import collect, gadget_postload
class CharacterResetEvidenceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_source_identity_reset_and_callback_provenance(self):
self.assertTrue(self.report['known_binary'])
for key in ('sites', 'vtables', 'gadget_calls'):
for item in self.report[key]:
with self.subTest(key=key, item=item):
self.assertTrue(item['matches'])
def test_euler_capture_is_not_body_velocity(self):
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['euler_getter_y']['actual'], '8b9128020000')
self.assertEqual(sites['player_init_yaw_capture']['actual'], '8b500489961c060000')
tables = {s['name']: s['target'] for s in self.report['vtables']}
self.assertEqual(tables['Jimmy Euler getter'], '0x4723f0')
def test_gadget_postload_disables_owned_only_and_restores_on_return(self):
original = [0, 1, 4, 2, 3, -1, 99, 1, 123]
disabled = gadget_postload(original, True)
self.assertEqual(disabled, [0, 4, 4, 2, 3, -1, 99, 4, 123])
self.assertEqual(gadget_postload(disabled, False), [0, 1, 1, 2, 3, -1, 99, 1, 123])
self.assertEqual(original, [0, 1, 4, 2, 3, -1, 99, 1, 123])
self.assertEqual(gadget_postload(disabled, True), disabled)
with self.assertRaises(ValueError):
gadget_postload([0] * 7, False)
def test_route_properties_do_not_serialize_mode_or_burn_timer(self):
self.assertEqual([x['code'] for x in self.report['route']], ['LV1B', 'VR04', 'LEV1'])
for item in self.report['route']:
self.assertIn('StartPoint', item['player_properties'])
self.assertFalse(any('jump' in p.casefold() or 'mode' in p.casefold()
or 'burn' in p.casefold() for p in item['player_properties']))
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,39 @@
"""Guard source stored/live lifecycle fields and the old-game deletion path."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from checkpoint_level_game_lifetime import collect
class LevelGameLifetimeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_instruction_and_vtable_identity(self):
self.assertTrue(self.report['known_binary'])
for item in self.report['sites'] + self.report['vtables']:
with self.subTest(item=item):
self.assertTrue(item['matches'])
def test_route_level_games_share_initialization_contract(self):
slots = {(x['owner'], x['slot']): x['target'] for x in self.report['vtables']}
for owner in ('lab', 'tutorial', 'outside'):
self.assertEqual(slots[owner, '0x28'], '0x44d4e0')
self.assertEqual(slots[owner, '0x8c'], '0x470f30')
self.assertEqual(slots[owner, '0x204'], '0x4719c0')
def test_actual_initializer_precedes_postload_and_teardown_calls_sweep(self):
sites = {x['label']: x for x in self.report['sites']}
self.assertLess(int(sites['loader_init_slot']['va'], 16), int(sites['loader_postload_slot']['va'], 16))
self.assertEqual(sites['base_init_to_common']['target'], '0x470540')
self.assertEqual(sites['teardown_delete_sweep']['target'], '0x473710')
self.assertEqual(sites['lab_destructor_base']['target'], '0x44d390')
self.assertEqual(sites['game_destructor_interface']['target'], '0x4587e0')
if __name__ == '__main__':
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from player_phase_evidence import collect
class PlayerPhaseEvidenceTests(unittest.TestCase):
def test_original_mode_and_frame_boundaries(self):
evidence = collect(ROOT.parent / 'Original')
self.assertEqual(len(evidence['sites']), 9)
self.assertEqual([s['va'] for s in evidence['sites'][-3:]],
['0x47e554', '0x47e582', '0x47e587'])
if __name__ == '__main__':
unittest.main()
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Read-only retained-character initialization and PostLoad evidence."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from checkpoint_script_state import EXE_SHA256, find_case, read_va, rel_call_target
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
import gam
SITES = (
('player_init_base', 0x437896, 'e8550f0200'),
('player_init_speed_zero', 0x4378A1, '898608060000'),
('player_init_turn_zero', 0x4378A7, '898614060000'),
('player_init_618_zero', 0x4378AD, '898618060000'),
('player_init_euler_getter', 0x4378B8, 'ff9028030000'),
('player_init_yaw_capture', 0x4378BE, '8b500489961c060000'),
('euler_getter_y', 0x4723FC, '8b9128020000'),
('postload_jump_zero', 0x42378B, '6689bd28070000'),
('postload_normal_radius60', 0x4236A3, '6800007042'),
('postload_normal_support_factor', 0x4236B3, '6885eba13f'),
('postload_animation_pause_disable', 0x42370A, 'ff901c010000'),
('stage_sound_stop', 0x43B7FB, 'ff9248010000'),
('sound_stop_only_handle', 0x429A19, 'c786440a0000ffffffff'),
('fire_constructor_preservation', 0x421E51, 'e8eaf00400'),
('fire_constructor_owner_zero', 0x421E62, '899ebc060000'),
('fire_constructor_timer_zero', 0x421E68, '899ec0060000'),
('fire_owner_assignment', 0x437525, '8981bc060000'),
('fire_grounded_owner_clear', 0x421FE9, 'c7860006000000000000'),
('fire_timer_tick', 0x421FF3, 'd98600060000d8642418'),
('player_constructor_mode_zero', 0x43748A, '66899dc4070000'),
('goddard_init_base_jump', 0x41E6A0, 'e90b98feff'),
('goddard_init_authored_state', 0x407EBC, '8b867c080000898608060000'),
('goddard_init_waypoint_clear', 0x407EC8, 'c7860008000000000000'),
('goddard_postload_base', 0x41E593, 'e8e8aefeff'),
('goddard_reuse_callback', 0x423CE2, 'ff9074010000'),
('inventory_disable_compare_one', 0x40389E, '66833801751166c7000400'),
('inventory_enable_compare_four', 0x4038AA, '66833804750566c7000100'),
('tutorial_level_lower_bound', 0x423E52, '3d31305256'),
('tutorial_level_upper_bound', 0x423E5D, '3d38305256'),
('tutorial_mode_flag', 0x423E6A, 'c6853809000001'),
('tutorial_objective_hidden', 0x423EC6, 'c70588814f000000a041'),
)
VTABLES = (
('Jimmy Init', 0x4A373C, 0x28, 0x437890),
('Jimmy PostLoad', 0x4A373C, 0x40C, 0x423610),
('Jimmy Euler getter', 0x4A373C, 0x328, 0x4723F0),
('Jimmy transition stop sound', 0x4A3BDC, 0x148, 0x429A00),
('Jimmy animation pause', 0x4A3BDC, 0x11C, 0x40D350),
('Fire Init', 0x4A3160, 0x28, 0x4587F0),
('Fire PostLoad', 0x4A3160, 0x40C, 0x40E7B0),
('Goddard Init', 0x49F480, 0x28, 0x41E6A0),
('Goddard PostLoad', 0x49F480, 0x40C, 0x41E590),
('Shadow Init', 0x4B37B8, 0x28, 0x4587F0),
('Shadow PostLoad', 0x4B37B8, 0x40C, 0x43F810),
)
GADGET_INDICES = (7, 3, 0, 5, 1, 6, 2, 4)
ENABLE_CALLS = (0x423DEF, 0x423DFA, 0x423E05, 0x423E10,
0x423E1B, 0x423E26, 0x423E34, 0x423E3F)
DISABLE_CALLS = (0x423E71, 0x423E7C, 0x423E87, 0x423E92,
0x423E9D, 0x423EA8, 0x423EB6, 0x423EC1)
def gadget_postload(states, tutorial):
"""Bounded state oracle: source403870 preserves values other than1/4."""
values = list(states)
if len(values) < 8:
raise ValueError('Need all eight group0 gadget entries')
for index in GADGET_INDICES:
if values[index] == 4:
values[index] = 1
if tutorial:
for index in GADGET_INDICES:
if values[index] == 1:
values[index] = 4
return values
def collect(root: Path):
pe = PE(find_case(root, 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
sites = []
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
item = dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
expected=expected, actual=actual, matches=actual == expected)
if actual.startswith('e8'):
item['direct_call_target'] = hex(rel_call_target(pe, va))
sites.append(item)
tables = []
for name, table, slot, expected in VTABLES:
actual = struct.unpack('<I', read_va(pe, table + slot, 4))[0]
tables.append(dict(name=name, table=hex(table), slot=hex(slot),
file_offset=hex(pe.offset(table+slot-pe.base)),
target=hex(actual), matches=actual == expected))
calls = []
for disabled, addresses in ((0, ENABLE_CALLS), (1, DISABLE_CALLS)):
for index, va in zip(GADGET_INDICES, addresses, strict=True):
target = rel_call_target(pe, va)
# Each site is preceded by push bool; push item; push group0.
expected = bytes((0x6A, disabled, 0x6A, index, 0x6A, 0))
# First tutorial call inserts its mode flag write after the pushes.
argument_start = va - (13 if va == 0x423E71 else 6)
actual = read_va(pe, argument_start, 6)
calls.append(dict(va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
group=0, index=index, disabled=disabled,
target=hex(target), matches=actual == expected and target == 0x403870))
route = []
for relative in ('gam/level1b.gam', 'gam/VR04.gam', 'gam/level1.gam'):
path = find_case(root, relative)
level = gam.parse(path.read_bytes())
jimmy = next(e for e in level.entities if e.kind == '3JIM')
route.append(dict(file=relative, code=level.code, offset=hex(jimmy.offset),
sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
player_properties=sorted(jimmy.values())))
return dict(known_binary=digest == EXE_SHA256, sha256=digest,
sites=sites, vtables=tables, gadget_calls=calls, route=route,
scope='Static source bytes/data only; no original runtime execution.')
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
result = collect(cli.parse_args().original)
print(json.dumps(result, indent=2))
if not result['known_binary'] or not all(x['matches'] for key in ('sites', 'vtables', 'gadget_calls') for x in result[key]):
raise SystemExit(1)
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Read-only proof that ordinary initialization restores a level game's teardown flag."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from checkpoint_script_state import EXE_SHA256, find_case, read_va, rel_call_target
from pe_inspect import PE
SITES = (
("generic_stored_flag_one", 0x46FDB3, "6a018bcde884110000"),
("stored_flag_getter", 0x470F30, "8a4111c3"),
("stored_flag_setter", 0x470F47, "884111ff9204020000"),
("live_flag_getter", 0x4719B0, "8a8139010000c3"),
("live_flag_setter", 0x4719C0, "8a442404888139010000c20400"),
("defaults_only_live_zero", 0x44D456, "6a00"),
("defaults_live_setter", 0x44D472, "ff9004020000"),
("lab_init_to_base", 0x44D4E0, "e90bb30000"),
("base_init_to_common", 0x4587F3, "e8487d0100"),
("common_init_get_stored", 0x4705B3, "ff978c000000"),
("common_init_set_live", 0x4705B9, "508bceff9704020000"),
("loader_init_slot", 0x46E5C3, "ff5228"),
("loader_postload_slot", 0x46E61A, "ff920c040000"),
("teardown_first_predicate", 0x46E032, "ff920002000084c0741b"),
("teardown_second_predicate", 0x46E06F, "ff900002000084c0741b"),
("teardown_third_predicate", 0x46E0AC, "ff900002000084c07418"),
("teardown_delete_mark", 0x46E0CA, "c6460601"),
("teardown_delete_sweep", 0x46E0D9, "e832560000"),
("delete_sweep_flag", 0x473720, "8a590684db7508"),
("delete_sweep_virtual_destructor", 0x473733, "8b016a01ff10ebd6"),
("lab_destructor_thunk", 0x44F610, "83e95ce9d8fdffff"),
("lab_destructor_base", 0x44F499, "e8f2deffff"),
("game_destructor_base", 0x44D3C2, "e919730200"),
("game_destructor_interface", 0x47476A, "e87140feff"),
("interface_destructor_base", 0x4587E6, "e975780100"),
("common_destructor_registry", 0x4700E5, "a19c995000"),
("common_destructor_payload_match", 0x4700F2, "397e087516"),
("common_destructor_registry_erase", 0x470101, "b998995000e88593ffff"),
("jimmy_stored_zero", 0x4226B5, "538bcf66899d0c0a0000e87ce80400"),
("goddard_stored_zero", 0x41C99B, "538bcfe89d450500"),
)
TABLES = (
("lab", 0x4C386C, 0x28, 0x44D4E0),
("tutorial", 0x4CE4AC, 0x28, 0x44D4E0),
("outside", 0x4C561C, 0x28, 0x44D4E0),
("lab", 0x4C386C, 0x8C, 0x470F30),
("tutorial", 0x4CE4AC, 0x8C, 0x470F30),
("outside", 0x4C561C, 0x8C, 0x470F30),
("lab", 0x4C386C, 0x200, 0x4719B0),
("lab", 0x4C386C, 0x204, 0x4719C0),
("tutorial", 0x4CE4AC, 0x204, 0x4719C0),
("outside", 0x4C561C, 0x204, 0x4719C0),
("lab", 0x4C386C, 0, 0x44F610),
("Jimmy", 0x4A373C, 0x8C, 0x470F30),
("Jimmy", 0x4A373C, 0x204, 0x4719C0),
)
def collect(original: Path) -> dict:
pe = PE(find_case(original, "Neutron.exe"))
digest = hashlib.sha256(pe.data).hexdigest()
sites = []
for label, va, expected in SITES:
actual = read_va(pe, va, len(expected) // 2).hex()
item = dict(label=label, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
expected=expected, actual=actual, matches=actual == expected)
if actual.startswith("e8"):
item["target"] = hex(rel_call_target(pe, va))
sites.append(item)
tables = []
for name, table, slot, expected in TABLES:
va = table + slot
actual, = struct.unpack("<I", read_va(pe, va, 4))
tables.append(dict(owner=name, table=hex(table), slot=hex(slot),
va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
target=hex(actual), matches=actual == expected))
return dict(sha256=digest, known_binary=digest == EXE_SHA256, sites=sites,
vtables=tables, scope="Static source bytes only; no original runtime execution.")
if __name__ == "__main__":
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument("original", type=Path)
result = collect(cli.parse_args().original)
print(json.dumps(result, indent=2))
if not result["known_binary"] or not all(s["matches"] for s in result["sites"] + result["vtables"]):
raise SystemExit(1)
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Read-only anchors for the implemented player/input/body phase boundary."""
import argparse
import hashlib
import json
from pathlib import Path
from pe_inspect import PE
SHA256 = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
ANCHORS = [
(0x438B1E, '0fbf8604070000', 'input dispatch reads stored interface704 mode'),
(0x438B2A, 'ff2485a48b4300', 'input dispatch uses mode table'),
(0x437A96, '66c786040700000100', 'held jump selects air mode during player update'),
(0x437B9E, '66899e2807000066899e04070000899e14060000',
'grounded release resets jump state, mode, then turn rate'),
(0x437BC5, 'ff9034010000', 'player air apply virtual134'),
(0x437C1C, 'ff9230010000', 'player ground apply virtual130'),
(0x47E554, 'e867b6ffff', 'physics before object registry'),
(0x47E582, 'e8b951ffff', 'object registry callback pass'),
(0x47E587, 'e8e451ffff', 'logical-to-visual sync after callbacks'),
]
def collect(original):
root = Path(original)
paths = [p for p in root.iterdir() if p.name.casefold() == 'neutron.exe']
if len(paths) != 1:
raise ValueError('Original EXE missing or ambiguous')
pe = PE(paths[0])
if hashlib.sha256(pe.data).hexdigest() != SHA256:
raise ValueError('Unsupported EXE identity')
result = []
for va, expected, label in ANCHORS:
offset = pe.offset(va - pe.base)
raw = bytes.fromhex(expected)
if pe.data[offset:offset + len(raw)] != raw:
raise ValueError(f'Changed source contract at {va:#x}')
result.append(dict(va=hex(va), file_offset=hex(offset), bytes=expected, label=label))
return {'sha256': SHA256, 'sites': result,
'limits': 'Static source anchors; port capsule/grounding and cadence remain provisional.'}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
print(json.dumps(collect(parser.parse_args().original), indent=2))