Compare commits

..
9 Commits
109 changed files with 7506 additions and 206 deletions

No files matched your search

+6 -2
View File
@@ -35,5 +35,9 @@ other agents' active changes. Keep updates concise, save detailed evidence to di
Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests, Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests,
and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`, and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`,
`docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions. `docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions.
Current priority is exact asset recovery and one reconstructed original scene; Current mode is evidence-led architecture continuation. The initial checkpoint is
read those documents for actual completion status and next actions. documented in docs/checkpoint/review.md. Pause feature expansion; use the playable
69d0187 baseline as a comparison tool. Read
docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay
changes. Only evidence probes or directly evidenced corrections belong in this
checkpoint; distinguish static recovery, port tests and original runtime evidence.
+27 -3
View File
@@ -2,7 +2,17 @@
Local reconstruction of the supplied **Jimmy Neutron: Boy Genius** installation Local reconstruction of the supplied **Jimmy Neutron: Boy Genius** installation
using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain
untouched in `../Original`. There are no Git remotes or runtime online services. untouched in `../Original`. Work is local; no remote operations or runtime online
services are used.
**Current direction: architecture recovery; feature expansion paused.** The
[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. 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.** **Current milestone: original lab story, interactions and jet pack practice flow.**
The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
@@ -33,18 +43,29 @@ The lab camera sequence stops background music and DEFAULT restarts it when
control returns, including after skipping. control returns, including after skipping.
**F1** opens the debug menu and pauses gameplay and audio. Use Up/Down to select, **F1** opens the debug menu and pauses gameplay and audio. Use Up/Down to select,
Left/Right to change values, Enter to apply, and F1/Escape to close. It includes Left/Right to change values, Enter to apply, Tab to switch General/Player/Systems
pages, and F1/Escape to close. It includes
live diagnostics, camera switching, cutscene skip, energy refill, jet-pack grant, live diagnostics, camera switching, cutscene skip, energy refill, jet-pack grant,
SCENE task editing, all 33 prepared levels and their original startpoints, and SCENE task editing, all 33 prepared levels and their original startpoints, and
reset. Page Up/Down changes the staged SCENE value by 10. reset. Page Up/Down changes the staged SCENE value by 10.
The Force Control toggle keeps Jimmy controllable during scripted control locks. See The Force Control toggle keeps Jimmy controllable during scripted control locks. See
[debug menu controls](docs/debug-menu.md). [debug menu controls](docs/debug-menu.md). Player/System pages add movement and
jetpack state controls, camera obstruction, audio category mutes, objective/practice
controls and checkpoint save/load. **F3** toggles noclip: WASD moves/strafe, arrows
move/turn, Space/E rises, Ctrl/Q descends and Shift triples flight speed. Noclip
bypasses collision and contact triggers; reset or a new level disables it.
**F2** toggles a compact live debug overlay without pausing play. It shows frame **F2** toggles a compact live debug overlay without pausing play. It shows frame
timing, position/velocity, movement, control/force state, tasks, camera/clipping timing, position/velocity, movement, control/force state, tasks, camera/clipping
and error counters. F1 also has a Live Overlay toggle. Visibility stays selected and error counters. F1 also has a Live Overlay toggle. Visibility stays selected
across scene changes during the session; `--debug-overlay` enables it at startup. across scene changes during the session; `--debug-overlay` enables it at startup.
Level changes keep the same window and Vulkan renderer, preserving window bounds,
focus and fullscreen state. UI scales uniformly on widescreen: prompts/F1 stay
centered, objectives stay bottom-right and F2 stays top-left. Use
`--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11
update UI placement and clicks.
The original lab pickup is internally tagged `shrinkray`; the original objective The original lab pickup is internally tagged `shrinkray`; the original objective
art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click
on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the
@@ -107,6 +128,9 @@ scripts/build-windows.sh
scripts/package.sh scripts/package.sh
``` ```
After building, `scripts/test-window-transitions.sh` runs a local Linux fullscreen/
ultrawide regression using installed Xvfb, Xfwm, D-Bus and xprop.
The publish scripts perform equivalent self-contained publishes: The publish scripts perform equivalent self-contained publishes:
```bash ```bash
+3 -1
View File
@@ -70,7 +70,9 @@ The follow-up below recovers and implements the actual contact/talk dispatcher
and the internally named shrinkray jet pack checkpoint/inventory/practice/gadget effects. General AI sensing, and the internally named shrinkray jet pack checkpoint/inventory/practice/gadget effects. General AI sensing,
weapon behavior and all special pickups remain incomplete. weapon behavior and all special pickups remain incomplete.
LOAD LABTONEIGH GAM0xA43 goes tolevel1.gam/startlevel1, SCENE60/radius200. LOAD LABTONEIGH GAM0xA43 goes tolevel1.gam/level1, SCENE60/radius200.
The destination start tag is `level1`; the earlier `startlevel1` spelling was a
documentation error. Checkpoint helper re-reads the original GAM field directly.
Underground LOAD0x8360 requires scene65, start riverlab. Binary0x457F32..7F5F: Underground LOAD0x8360 requires scene65, start riverlab. Binary0x457F32..7F5F:
none requiredtask bypasses; taskvalue-1 bypasses; otherwise >=RequiredLevel and none requiredtask bypasses; taskvalue-1 bypasses; otherwise >=RequiredLevel and
ExactLevel!=-1 additionally requires equality to that numeric ExactLevel. ExactLevel!=-1 additionally requires equality to that numeric ExactLevel.
+24 -4
View File
@@ -68,8 +68,9 @@ remain provisional.
TaskStates and TaskActivation retain original case/sentinel/numeric gates. TaskStates and TaskActivation retain original case/sentinel/numeric gates.
OriginalSave accounts for every TSK byte and preserves unknown data. SceneInteractions OriginalSave accounts for every TSK byte and preserves unknown data. SceneInteractions
implements star/trophy/lab jetpack contacts, Carl dialogue dispatch and LOAD requests, tracking implements star/trophy/lab jetpack contacts, Carl dialogue dispatch and LOAD requests, tracking
contact entry by source offset (duplicate tags remain distinct). Main disposes contact entry by source offset (duplicate tags remain distinct). Main owns a
renderer/window/audio before rebuilding the next scene, carrying task/items/score. RenderSession across loads, replacing scene resources and per-level audio while
preserving the window/Vulkan core and carrying task/items/score.
Checkpoint CLI saves use atomic replacement outside asset directories; complete Checkpoint CLI saves use atomic replacement outside asset directories; complete
runtime saves, menus and configuration are not yet implemented. runtime saves, menus and configuration are not yet implemented.
@@ -98,8 +99,9 @@ PracticePrompt implements source strict Yes/No regions and keyboard dispatch;
Program pauses simulation while modal, clears held input and rebuilds VR04 on Yes. Program pauses simulation while modal, clears held input and rebuilds VR04 on Yes.
SceneHud appends source640x480 screen quads; the Vulkan overlay pipeline disables SceneHud appends source640x480 screen quads; the Vulkan overlay pipeline disables
depth and draws after world geometry using identity transforms. Full HUD state depth and draws after world geometry using identity transforms. Full HUD state
and practice highlighting remain incomplete. Fixed-size authored art and practice highlighting remain incomplete. UiViewport applies uniform art scale
is scaled with the viewport; input uses matching logical-window coordinates. and explicit anchors; input maps logical coordinates into actual drawable pixels
before inverse modal mapping.
Prepared effects/effects.json preserves251 original SoundEffects.omt identities Prepared effects/effects.json preserves251 original SoundEffects.omt identities
and RIFF payloads, including one MPEG-in-RIFF resource whose playback is unverified. and RIFF payloads, including one MPEG-in-RIFF resource whose playback is unverified.
@@ -170,3 +172,21 @@ key and never enters the menu's pause/input-reset boundary. F1 selects the full
menu layout while open, otherwise the same overlay ranges display compact live menu layout while open, otherwise the same overlay ranges display compact live
diagnostics. The source viewport/projection decision supplies actual camera/far diagnostics. The source viewport/projection decision supplies actual camera/far
data. No debug visibility state is written into the original TSK wire format. data. No debug visibility state is written into the original TSK wire format.
RenderSession owns presentation until exit. Renderer replacement stages scene
buffers/textures/descriptors, preserving device/surface/swapchain/layouts/pipelines
and current targets. Resize/fullscreen replace size-dependent resources. Revision
and native identities support checks. See presentation-and-ui.md for rollback,
widescreen policy and runtime verification boundaries.
## Bounded ordinary-load character state
PlayerLevelState is separate from OriginalSave: it carries only mode, jump-hold
and owned-fire timer across proven LV1B/VR04/LEV1 no-gadget/jetpack transitions.
Run reconstructs destination resources/body and applies these scalars before
playback. Source jump state resets independently; TSK/debug checkpoint loads get
no transient carry container. Source retained identity does not justify persisting
all physics/AI/render fields. The detailed contract, phase limits and original
component probe are in checkpoint/retained-player-body.md; companion/shadow
resets and full availability tails have separate reports. Uncontrolled physics
and exact appended-helper traversal remain next scheduler boundaries.
+49
View File
@@ -0,0 +1,49 @@
# Architecture checkpoint
Feature expansion is paused. The existing port is a preserved baseline and a tool
for testing interpretations. This checkpoint connects original state ownership,
update order and lifecycle to the lab → VR04 → lab → outside route; it does not
require recovering every level or certify complete gameplay fidelity.
Start with [baseline](baseline.md), [coverage map](coverage.md),
[loop and motion](loop-motion.md), [script/state route](script-state-route.md),
[camera/audio/UI](camera-audio-ui.md), and [implementation plan](implementation-plan.md).
Core reports and [input/frame bridge](input-frame-bridge.md) have returned to
primary ownership. Follow-ups cover [lab registry](lab-registry.md),
[camera ray](camera-ray-predicate.md), [voice clock](voice-clock.md), and
[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.
The retained-field continuation adds [property reader](retained-streamer.md),
[RETURN cleanup and full availability tails](retained-return-cleanup.md),
[player body/scalar boundary](retained-player-body.md) and
[companion/shadow resets](retained-companion.md). It corrects the earlier
availability-prefix interpretation and implements bounded route scalar carry.
Evidence labels used throughout:
- **Recovered:** static instructions, serialized original data, or a specifically
named isolated-original probe. Preferred image VAs and PE-mapped file offsets
refer to the hashed supplied binaries, not ASLR runtime addresses.
- **Inference:** an interpretation whose missing callers, ordering or filters are
explicitly listed. It is not promoted to fact because a replay looks plausible.
- **Implementation:** what this port currently does, including modern policies.
- **Verification:** state separately whether a source-byte check, managed test,
port runtime, isolated original component, or full original runtime was tested.
Earlier analysis documents retain useful evidence but can describe older
implementations. This checkpoint supersedes their architecture/priority summaries;
focused reports remain authoritative for their cited instructions/data. In
particular, movement mode1 reaches the airborne fall-through path, TSK writing is
recovered, and source per-level far planes are recovered; broad older statements
that those are wholly unknown are stale.
Checkpoint exit requires every requested core system to have an evidence anchor,
owner/lifetime, interaction mapping, baseline comparison, explicit unknowns and a
bounded next action. Completion means enough architectural coverage to execute the
plan, not complete disassembly or original gameplay comparison. Preserve unresolved
questions as gates on individual plan chunks, not a reason to block all work.
+25
View File
@@ -0,0 +1,25 @@
# Preserved playable baseline
Baseline: `69d0187a2178deab1edff961d5126dad1cce3a05`, clean source tree at checkpoint
entry, local annotated tag `baseline-re-checkpoint-2026-10-25`. Existing Linux and
Windows packages were copied, without hard links, to
`artifacts/re-checkpoint/baseline/{linux-x64,win-x64}`. Their BuildInfo records
identify69d0187 and clean source. These ignored local copies are comparison tools;
subsequent builds must not overwrite them.
`artifacts/re-checkpoint/original-preservation-start.log` verifies all539 original
files against `docs/original-manifest.json`. Originals were read, never modified or
executed in place. All work remains local. A pre-existing `Gitea` Git remote is
configured; it was not contacted or changed. No fetch/push/remote-service operation
was performed. Older notes saying the repository has no remotes are stale.
The user has traversed lab → tutorial → lab → outside in their Windows build.
Earlier Linux managed, GPU and SDL tests demonstrate port behavior; package
cross-compilation and Wine checks do not establish native Windows verification.
No usable running-original gameplay capture exists. Static code evidence and
isolated DLL probes must not be reported as original end-to-end verification.
Modern authorized baseline policies include F1/F2 diagnostics, persistent SDL/Vulkan
presentation across level changes and uniform widescreen UI. They are not claims
about the original. Fixed60Hz simulation, provisional player capsule/feet grounding,
grouped system phases and duration-driven camera completion remain fidelity gaps.
+278
View File
@@ -0,0 +1,278 @@
# Camera, audio and UI architecture checkpoint
Scope: playable baseline `69d0187`, lab → VR04 → lab → outside. Read `prompt.MD`
all1281 lines and both AGENTS files. This checkpoint changes no runtime behavior.
Original files were read only. Source-byte checks below are static evidence,
not original-game runtime comparison. Existing Linux GPU/SDL smoke tests and user
Windows reports describe the port, not a recovered original reference recording.
## Evidence identity and reproduction
| Module | SHA-256 |
| --- | --- |
| Neutron.exe | f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8 |
| OMT2.dll | 3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943 |
`python3 tools/binary/checkpoint_camera_audio_ui.py ../Original` verifies25
selected instruction sequences and7 constants against those identities and prints
mapped physical offsets. `python3 -m unittest discover -s tests -p
'test_checkpoint_camera_audio_ui.py' -v` also checks ray-adjustment algebra.
Fresh bounded objdump reads corroborate the cached `artifacts/binary/neutron.asm`;
RTTI was checked with `tools/binary/rtti_map.py`.
All EXE code/constant VAs in this report have physical offsets VA−0x400000.
Examples and decisive ranges are listed explicitly. **The globals below occupy
PE zero-fill and have no physical file offset**; subtracting the image base from
their VA does not produce an original-file byte location.
| Runtime owner/global | VA | Meaning supported by consumers |
| --- | --- | --- |
| Controlled game-interface pointer | 0x5099E4 | Input ownership; null also suppresses objective clock/draw |
| Shared viewport pointer | 0x509A50 | Position+44/+48/+4C; signed angle words+50/+52/+54 |
| Current music database | 0x696004 | Separate from current Wave/effects/speech bank |
| Current Wave database | 0x696008 | CAM/MCA replace it with authored speech bank; DEFAULT restores effects |
| Sound engine | 0x69600C | Channel array+40; virtual24 returns channel count |
| Default positional-effect gate | 0x4F8434 | Wrapper4589C0 tests it; cutscenes clear, DEFAULT enables |
| Objective time / selector | 0x4F8188 / 0x4F8194 | Separate transient presentation and persistent selection |
| Objective44 flags | 0x4F7D00 | Independent per-row visibility/selection state |
| Modal active / type | 0x4F8198 / 0x4F8048 | UI continues handling modal while main gameplay is paused |
## Shared camera state and ownership
**Recovered fact.** There is a shared viewport, not independent original
"gameplay eye" and "cutscene eye" objects selected by renderer priority.
CAM/MCA and player callbacks write that same position/orientation. MCA helper
431670 (file31670) writes eye+44/+48/+4C at431677/431683/431694, derives angles
using imported angle routine48D108 at4316F9, writes words+50/+52 and roll0 at
43170D..431717, and mirrors camera globals4F8418..4F842C. CAM formulas are at
4161CD..416585 (file161CD..16585), MCA formulas431027..4311C1
(file31027..311C1). Their authored transforms are already documented in
`../analysis/lab-progression.md` and represented by SceneDirector.UpdateCamera.
CAM activation4165E2..4166FA (file165E2..166FA) resolves PlayerControlled:
`none` preserves, `NULL` clears, a named found actor grants control through game
virtual118. Before clear, it calls controlled actor virtual410/438 and rewrites
transform state. MCA431502..4315A7 (file31502..315A7) similarly prepares prior
controlled actor then clears through game virtual118(NULL). Its PlayerControlled
field is completion ownership at4311F0..431228, not an activation grant.
Control loss does not prove all physics/actors should stop. Main-loop report owns
the enclosing update pass and any per-actor active gates.
**New recovered DEFAULT handoff.** DEFAULT447CF0 has a Jimmy-already-controlled
early branch447D5C..447D9C (file47D5C..47D9C). Even that branch reloads the
default effects bank; it skips camera reposition and music restart. Otherwise
447E1E..447E27 restores control, then447E2D..447EC3
(file47E2D..47EC3) computes actor-local point `(0,500,-500)` using game-interface
virtual384, compares distance from current viewport position against float1000
at48E5AC (file8E5AC), and writes the point to viewport only when distance is
**strictly greater than1000**. At equality the original `fcomp; test ah,41; jne`
skips the snap. Non-Jimmy mode-dependent restore targets also exist447DAC..447E1E;
the port's unconditional Jimmy restore is only the route subset.
**Current implementation.** Program selects LabSimulation.CameraEye then replaces
it with SceneDirector.CameraEye while a shot exists. `RestoreControl` clears the
shot eye; it neither transfers current viewport state into follow state nor
performs the source conditional snap. LabSimulation only advances when Jimmy
controls input. Calling its eye "always advanced" is inaccurate; it remains a
separate stale state during ordinary uncontrolled cutscenes. This is an ownership
mismatch, not a reason to add another transition easing heuristic.
## Follow camera, obstruction and clipping
**Recovered fact.** Jimmy complete-object vtable4A3BDC (fileA3BDC), slot124 →
438BC0 walking, slot128 →439900 airborne, slot16C at4A3D48 (fileA3D48) →
43B820 camera ray callback, slot170 →437740 default camera setup. The separate
game-interface vtable4A373C (fileA373C) has complete-object displacement+C0;
do not apply complete-object offsets directly to an interface pointer.
| Complete-player field | Source initialization/use |
| --- | --- |
| +7C8/+7CC/+7D0 | Eye local0,200,−350 at437740..43776D (file37740..3776D) |
| +7D8/+7DC/+7E0 | Look local0,80,0 at437752..437774 |
| +854/+858/+85C | Axis gains1.6,1,1.6 at43775E..437787 |
| +804..+810 | Cached desired eye when special-state branch retains it439658..4396A5 |
| +714/+718/+71C | Prior camera position used by follow deltas43971E..439748 |
| +828, +830, +84C, +851 | Additional state affects offsets/gains; complete semantic names unresolved |
4395CF..4398E4 (file395CF..398E4) does not simply follow a fixed local offset.
Normal eye height is `eyeY−2*self[84C]`; target height is
`lookY+1.9*self[84C]` at439625..4396DA. Special+828/+830 branches use cached
eye or flip/scale backward distance by3.7 after threshold1.7. Float64 constants
are4AFCE8/4AFCF0/495338 (filesAFCE8/AFCF0/95338). Do not rename84C to ground
height or infer its units without tracing writers.
**New ray contract.** Caller439702..439714 passes look-point by value and
desired-eye pointer through complete-object virtual16C. Callee43B820..43B90C
(file3B820..3B90C) calls ray predicate47C210 at43B874; on hit reads16-byte hit
global5CFC60 and mutates desired eye to
`lookPoint−0.75*(lookPoint−hitPoint)`, i.e. `.25*look+.75*hit`. It returns1.5
on hit (float4A3138,fileA3138), otherwise1.0. Predicate layer/filter/ordering and
its use of actor-query virtual310 still require recovery; this algebra alone
does not authorize replacing its ray with the port capsule sweep.
Normal interpolation4397B1..4397F1 multiplies X/Z delta by axis gain, ray return
gain and dt; Y uses `(gainY+0.2)*rayGain*dt`. +851 selects a0.2 branch and
+828 selects another branch without these axis multipliers. Position is added
to current viewport4397F8..43982D, then look angles derive from prior-position
fields and wrap with mask3FFF at439865..4398E4. This order matters and needs an
isolated trace before replacing the source adapter.
**Current approximation.** LabSimulation.DesiredEye uses root+(yaw-rotated
0,180,−350), target root+99, fixed gains1.6/1.2/1.6 and modern sphere/capsule
obstruction before and after interpolation. 180/99 match only an inferred
selected offset state, not the complete field-driven algorithm above.
**Clipping fact versus policy.** OMT2 layer constructor1004D340
(DLL file4D340) defaults near20/far3200/FOV0xAAA. Source initializers override
geometry-layer far values: LV1B44F5A5/44F5B1 (files4F5A5/4F5B1)=10000,
VR04456C04/456C4A (files56C04/56C4A)=50000, outside45086F
(file5086F) sets layer509A3C to28000 while509A30 retains3200. Full35-scene
table is `../analysis/camera-clipping.md`. SceneProjection's maximum of two
layers is a documented merged-renderer policy; layer masks/clip/fog and dynamic
LV4B clip transition are incomplete. Orbit scene-radius far distance only hid
the earlier wrong gameplay3200 range. Widescreen aspect is a modern policy.
## Audio owns cutscene completion, banks and channel lifetime
RTTI disambiguates the camera callback structures: C3DCutSceneCamera complete
vtable498060 (file98060), slotD8 at498138 →4165A0 activation; its **+C8**
game-interface vtable497BFC (file97BFC), slot3C4 at497FC0 →415F90 update.
Thus update-relative handle+8B4/active+8B8/elapsed+8F0 are complete-object
+97C/+980/+9B8 respectively. C3DMultiCutSceneCamera complete vtable4A93C8
(fileA93C8), slotD8 at4A94A0 →431280; its+C8 game-interface vtable4A8F64
(fileA8F64), slot3C4 at4A9328 →430DA0. MCA update-relative handle+DC0,
active+DC4, elapsed+DE0 are complete+E88/+E8C/+EA8. Camera's interface
displacement is C8, whereas Jimmy's is C0; conflating them shifts every field.
**Recovered fact.** CAM415F90 calls base update463090, increments elapsed+8F0
at415FB2..415FBC, then polls sound handle+8B4 at415FC2..415FD3
(file15FC2..15FD3) with47D890. While sound reports active it updates camera and
skip handling. When inactive it stops/releases handle, changes target animation,
deactivates and invokes next trigger4160A4..4160E2. MCA uses the same predicate
at430DD2 before advancing shot; per-shot elapsed reset43190F. Animation is an
effect of activation/completion, not the recovered cutscene clock owner.
47D890..47D8E6 (file7D890..7D8E6) validates engine, nonnegative index and channel
count, reads voice at `engine[40][handle]`, calls voice virtual14 with two outputs,
and reports active if the second output is nonzero **or voice byte+30 is nonzero**.
Missing engine/index/voice returns false. Follow-up [voice-clock.md](voice-clock.md)
resolves both derived vtables: slot14 is inherited software elapsed/duration,
and+30 is repeat/loop state. This is not a hardware-playing or audibility query.
The ordinary one-shot clock is duration-based, but source integer boundaries,
invalid handles, engine clock pause, play failure and stop still need modeling.
47D7A0..47D849 (file7D7A0..7D849) stops voice virtual0C, optionally releases its
resource from selected database via virtual38, clears handle resource table
695EC0[handle], and clears global music handle4F6B30 when equal. Parameter0
still stops/clears handle association; parameter1 additionally releases database
resource. These are source runtime handles, not original Wave identity numbers.
| Lifecycle | Original transition / offsets | Port boundary |
| --- | --- | --- |
| Jimmy PostLoad |423642..423656 (file23642..23656) loads SoundEffects.omt into696008; selected music stored complete+A4C, handle+A38 | Per-scene prepared files; selectedMusic tuple held by SceneAudio |
| CAM takes audio |416776..4167E1 stops Jimmy music handle with47D7A0(handle,0), unloads selected archive, clears696004 | MusicStopped event disposes stream; tuple retained for restart |
| CAM takes Wave bank |4167FD..416830 (file167FD..16830) unloads default bank, clears696008/gate4F8434, loads authored speech bank | Speech opens explicit independent WAV; SFX default gate absent |
| MCA takes Wave bank |4315AD..4315F5 (file315AD..315F5) performs analogous bank/gate replacement; does not establish universal music stop | Standalone MCA intentionally does not mute all music |
| DEFAULT resumes |447F12..447F45 (file47F12..47F45) reloads selected archive, starts Wave0 and stores new music handle | Restart selected track from start; independent streams |
| DEFAULT restores effects |447F4B..447F6F (file47F4B..47F6F) restores volume/bank/gate; early Jimmy-owned branch447D60..447D76 also restores bank/gate | No explicit bank switch; always SoundEffects.omt Effect(id) |
| Level teardown/reset | Full global sound reset is not proven by these callbacks alone | SceneAudio.Dispose destroys every per-scene stream; RenderSession survives |
458980→47D390 is nonpositional wrapper;4589C0→47D640 checks default gate4F8434.
Therefore "mute every effect during every speech" would be a false generalization.
Recover wrapper call sites before suppressing objective216 or mechanism effects.
Original volume, attenuation, spatial pan, voice limits/allocation and stream
pause ownership remain incomplete. Source general-bank switching is broader than
the narrow fixed default bank in `../analysis/sound-effects.md`.
**Current implementation.** SceneDirector consumes prepared PCM sample duration,
including leftover dt across shots; no SDL voice status participates. SceneAudio
uses independent SDL streams for speech/music/one-shots/owner loops. SdlAudio.Pump
queues loop data below one source-buffer length; bytes queued are not proof all
converted output reached the speaker. Debug SetPaused is a modern menu feature.
The lab16-cue SDL dummy smoke validates port stream bookkeeping only. Physical
speaker output and native Windows end timing remain separate verification.
## UI update, modal timing and layout
**Recovered fact.** UI dispatcher404080 (file4080) calls base473240 first at
40408E, normalizes pointer using original1/640 and1/480 at4040B7/4040C5, processes
cursor repeat state when mode flag4F8181 or modal4F8198 is active, then invokes
UI virtual4E4/4DC at40420B..40421B. Notification timers4F8154/58/5C are separate
from objective timer. After virtual4E0 at4043D3, controlled-pointer condition
4043D9 advances objective time and invokes virtual4D0; null-control branch
40447A..4044BD hides art without advancing. Modal branch4044C2 follows this,
so its forced objective time8.7 overrides any earlier increment that UI tick.
This is a recovered local ordering, not proof of frame-wide input/UI scheduling.
Objective407070 (file7070) has .7 entry, stationary until7, exit until8.7; O
edge toggles timer0/7, not layout. Positive Select406F50 resets timer even when
selection repeats; initialization4018A8 and423EC6 sets20 hidden. Exact timings,
sound216 latch, fields, art identities and byte checks are in
`../analysis/objective-timing.md`. UI row flags are44 independently selected
entries; single selector digit and visible flag set are not interchangeable.
Practice406F90 (file6F90) guards existing modal, shows chosen art and cursor,
then407022..407031 invokes game virtual168(1) and stores type. UI continues to
accept selection while gameplay is paused.4044CE excludes type12 from forced
objective hide. No404D1E..404D97 hides modal, restores main game and resets
objective time0. Yes type0 stages VR04/PHONEBOOTH and departure context;
source mode1/2/3 map VR03/02/01. Exact keyboard/pointer strict bounds are in
`../analysis/ui.md`; controller navigation/highlight/cursor ownership remain open.
**Current implementation.** ObjectivePanel correctly separates timer/selector
and controlled/modal gates for the implemented objective subset. Program.Key
adds Jimmy-owned/inventory/focus/inspection/debug gates; original local clock
checks any nonnull controlled entity. Modern focus/orbit/debug gates are not
recovered source rules. PracticePrompt implements only modes0..3 and no source
highlight/controller state. SceneHud shows only lab objectives1..3, pad/digit and
practice art; gadget inventories and layout callbacks406590/406650 are absent.
Original402CC0/402D70 (files2CC0/2D70) scale horizontal/vertical positions with
width/640 and height/480 separately. Current UiViewport deliberately uses uniform
minimum scale with centered modal/bottom-right anchors and inverse DPI-aware
pointer mapping, following the user's widescreen requirement. This is an
intentional modern policy, not a claim that the original had anchored ultrawide
layout. F1/F2 debug UI is likewise modern; keep its state out of source save/UI
fields. The objective pad extending off reference viewport is authored clipping.
## Route interaction and reset map
| Route point | Camera/audio/UI dependencies and ownership |
| --- | --- |
| Lab NewGame/STARTEXP | Loaded selector does not imply visible pad: timer20. STRT/intro activates CAM/MCA chain, takes shared viewport/control; CAM stops music and replaces effects bank. First CAM bank gate persists through chained MCA until DEFAULT. |
| Intro DEFAULT | Restores actor control, conditionally snaps existing viewport only for distance>1000, restarts music if control was not already Jimmy, restores effects bank/gate. UI objective clock resumes with nonnull control; task selector changes remain separate. |
| Jetpack pickup/practice | Objective changes reset timer; practice modal pauses main game and forces objective hidden. No unpauses/reopens timer0. Yes stages VR04/PHONEBOOTH plus return context; script-state report owns persistent departure root/strings. |
| VR04 | Initial geometry layer far50000; scene-specific camera/speech/music state rebuilt by port. Original full teardown/global reset needs loader recovery; do not infer all fields persist because TSK does. |
| RETURN lab | Source return applies STRT/root/one-time trigger suppression; intro should not replay solely because scene rebuilt. Viewport/music/UI reset ordering depends on PostLoad and retained task state, not generic "resume previous audio". Current port constructs fresh SceneAudio, ObjectivePanel and director. |
| Carl → outside | CAM/MCA null control suppresses input/objective time, not all actor advancement. DEFAULT/LOAD order owns camera/music restoration vs scene destruction. Outside geometry far28000 is layer-specific, while current combined renderer uses28000 globally. |
## Coverage, assumptions and next bounded chunks
| Area | Recovered | Remaining source gap / evidence gate | Current implementation gap |
| --- | --- | --- | --- |
| Script cameras | Local transforms, elapsed, shared viewport writes, control handoff | Vtable caller phase/target transforms after actor motion; full skip/loader ordering | Separate eye state and duration clock |
| Follow | Fields, branches, ray mutation/return gain, viewport/angle writes |47C210 layer masks/nearest-hit semantics;84C writers; cached camera updates | Fixed offsets/gains and capsule clipping |
| DEFAULT | Strict>1000 snap, existing viewport retention, effect/music reset | Mode-dependent control targets outside route | Unconditional Jimmy restore and discarded scripted eye |
| Projection | Source layer defaults/all35 initial limits | Assignment/masks/fog, dynamic transitions | Merged maximum and orbit policy |
| Audio | Handle polling, software duration/repeat, bank/gate ownership, stop/reload | Source duration conversion/allocation/play failures, engine pause | Per-file independent streams, floating-duration/leftover-dt completion |
| UI | Local dispatch order/objective/modal gates and resource coords | Mode4F8181/4F8430 semantics, full flags/gadget/highlights/controller | Lab subset, modern input gating and uniform anchors |
1. C5: trace47C210 filter/caller contract; build shared viewport handoff tests
using source snap999.99/1000/1000.01 and ray-hit weighting. Preserve viewport
at control return, apply source conditional snap, then follow. Do not transplant
gains while leaving its previous-position/angle/collision dependencies guessed.
2. C6: voice-clock follow-up resolves virtual14/+30; recover allocation/failure
and source duration conversion before modeling the channel clock. Model
explicit bank/gate state separately from independent stream transport.
Test invalid/missing handle, delayed start, natural end, skip, paused playback,
DEFAULT already controlled, and level disposal before switching CAM/MCA clock.
3. C8: recover UI mode/pause callback boundaries and44 flags; preserve existing
tested timer rules. Add source gadget/layout/controller state only with call
evidence. Uniform widescreen/debug policy remains intentional and independently
tested. Recover animation end notifications separately from speech end.
These support the primary `coverage.md` and `implementation-plan.md`; they do not
claim all systems faithful or require every level/original GPU capture before a
bounded implementation correction. Stale broad binary.md mode1-no-action and
universal3200 clipping claims are superseded by movement/clipping reports. Broad
"camera recovered"/"audio implemented" labels must retain the boundaries above.
+222
View File
@@ -0,0 +1,222 @@
# C5 gate: source camera obstruction predicate
This is a bounded static continuation of `camera-audio-ui.md`, against the
unchanged Neutron.exe SHA-256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Originals were read only; no original instructions were executed. Modern runtime
code is unchanged. Preferred EXE VA → file offset is VA−0x400000 for all code,
vtable and initialized constants below. Zero-fill grid/output globals have no
physical file offset.
**Decision:** enough source evidence now exists to construct a separate static
camera segment-query adapter. It must preserve wall-grid priority, source cell
and insertion order, one-sided winding and first-hit return. Reusing the existing
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.
Its caller439702..439714 (files39702..39714) supplies computed look target by
value and a pointer to computed desired eye. At43B820 entry let stack pointer beS:
| Entry address | Argument / location |
| --- | --- |
| S+4..S+13 |16-byte input look-target vector |
| S+14 | Desired-eye pointer |
| S−18 | Stack pointer after `sub14; push esi` |
| S−10..S−1 | Local16-byte actor-position getter output |
| S−14 | Local float return gain initialized1.0 |
Hex numbers in this table are offsets, e.g. S+14 means20 decimal bytes.
Both virtual310 calls43B83F and43B84E (files3B83F/3B84E) write local scratch.
Jimmy interface vtable4A373C slot310 at4A3A4C (fileA3A4C) is472300
(file71300), which copies interface fields214/218/21C/220 to its output and
returns with `ret4`; it has no callback or mutation side effect. The local
position vector is not copied to the ray arguments.
After loading end pointer `[esp+2C]` at43B854, caller pushes0 then copies the
desired eye to a16-byte argument. It reserves another16 and uses
`lea edx,[esp+40]` at43B868: this is exactlyS+4, the **incoming look target**,
not the getter output.43B874 calls47C210 with
`(lookPoint, desiredEye, twoSided=false)` and cleans24 hex bytes. The source
therefore has no actor-root ray origin or actor exclusion pointer here.
On hit43B884..43B8F4 reads shared hitXYZ5CFC60/64/68 and changes the pointed eye
to `lookPoint−.75*(lookPoint−hit)`. It returns1.5; miss returns initial1.0.
This caller-level fact corrects any description of25% movement toward actor root.
## Query priority: first wall hit, then first general hit
| Function | File offset | Contract |
| --- | --- | --- |
|47C210..47C279 |7C210..7C279 | Global enable gate; call wall query; immediate return on hit; otherwise all query |
|47C280..47C4A4 |7C280..7C4A4 | Rectangle scan of wall/ceiling static grid509B24 |
|47C4B0..47C6D4 |7C4B0..7C6D4 | Same scan of all-polygon static grid5CFC7C |
|469530..4695A9 |69530..695A9 | Build48-byte segment: start+0, delta+10, end/hit+20 |
|469A10..469B66 |69A10..69B66 | Fetch first three polygon corners, add supplied translation, call triangle kernel |
|469B70..469E26 |69B70..69E26 | Source-winding segment/triangle kernel; recovered earlier for support |
47C210 passes unchanged start/end and sidedness to both queries; the second is
**not a reverse-direction retry**. Wall call47C23D (file7C23D) returns immediately
47C249..47C24C on success; all-grid fallback is47C26C. Both scan functions reset
shared hit polygon/shape identity695D54/695D58 at entry and rebuild global segment
5CFC40. Camera hit output5CFC60 is that segment's+20 vector.
Within each scan,469A10 returns a bool and shared hit point. A true branch at
47C44C or47C67C immediately stores current polygon and shape pointers to
695D54/695D58 then returns true. There is **no nearest-distance comparison**.
Thus a farther wall polygon in the first eligible cell can win over a nearer wall
later in that list, or a nearer floor in the second grid. A successful wall pass
prevents the all-grid pass entirely. This is materially different from47C6E0
used by body support, which retains strictly nearer hits.
Global enable byte4F69E5 is initialized1 at physical fileF69E5, unlike the
zero-fill grids.47C210/280/4B0 independently test it; zero returns false. No
entity-radius, dynamic actor-pair query, visibility, renderer-layer mask, camera
near/far, or material-alpha test appears in the predicate or triangle-call path.
Those static lists were filtered at registration instead.
## Grid coordinates, traversal and insertion order
Float cell scale4D6A04 (fileD6A04) is exactly
`0.0020000000949949026f`, origin49B1FC (file9B1FC) is130.0f. Nominal cell width
is500 world units; use the stored float rather than exact decimal1/500 when
testing source boundaries. For X and Z independently:
```
index = int16(truncate_toward_zero(worldComponent * storedScale + 130))
```
47F940 (file7F940) changes x87 control rounding to truncation, converts through
signed64 and returns low32; query comparisons retain low signed16. Multiplication
and addition remain x87 intermediates before conversion. This matters for exact
cell boundaries and extreme coordinates; Python's double order oracle below is
not an original x87 execution probe. Normal route coordinates fit the grid.
47C2E2..47C386 converts both endpointX/Z values, takes componentwise minima and
maxima, and scans the full inclusive **axis-aligned endpoint-cell rectangle**,
not a DDA path or intersecting-cell distance order. Outer indexX increases;
inner indexZ increases.47C3A4..47C3C6 rejects index<0 or>=260. Cell record stride
is12 bytes; list-pointer address is `gridBase+12*(260*x+z)` with gridBase509B24
or5CFC7C. Record pointer addresses differ from their structure starts by4 bytes.
47C3DF..47C3EA fetches cell sentinel then first node. Node layout is next+0,
previous+4, polygon-registration pointer+8. Each polygon registration record
has polygon pointer+0 and shape pointer+4. Traversal follows next until sentinel;
47C44E..47C459 and47C67E..47C689 continue only after miss. A polygon spanning
multiple cells can be tested multiple times; there is no per-query visited set.
479800..47991B (file79800..7991B) registers into the general grid, rejects
duplicate polygon pointers **within that cell**, and appends new nodes at the
tail.479897..4798A8 sets new.next=sentinel/new.previous=oldTail then links it;
the query therefore visits FIFO registration order, not reversed insertion.
It also appends to the wall grid when **stored polygon normal.Y<0.7f** at
4798B3..4798CF; equality is excluded. Threshold48D974 (file8D974) is the same
float used elsewhere for objective timing, which does not establish shared logic.
479140 (file79140) iterates the source shape polygon array in48-byte increments
at479473..479482. It calculates each polygon's XZ vertex bounds, converts extrema
with the same scale/origin/truncation, and registers the polygon in every cell of
that inclusive rectangle479336..479400. Centroid/radius data are retained in the
registration record, but this camera scan does not consult them for nearestness.
Shared scene loader44DBF0 uses shape resource ID/index initialized0 at44DC21,
fetches with477BA0, increments at44DEAF and tests existence through477C10. For
the three route archives shape IDs are ascending; current file enumeration order
also happens to be ascending, but an adapter should use source shape IDs and
polygon array indices explicitly. Port merged render-draw order is not evidence
for source registration order. The source's behavior at a missing intermediate
shape ID should be preserved or separately investigated before generic reuse.
## Registration filters and route asset coverage
Shared loader lowercases the first two shape-name characters and skips terrain
InitPhysics for NC prefix:44DD2F/44DD64/44DD67 (files4DD2F/4DD64/4DD67).
The ordinary path calls terrain interface2C at44DD6D →464B00 →479140 at464B18.
This excludes a complete NC shape from **both** grids, without removing its draw
geometry. Details and exact source shape payload offsets are in
`../analysis/water-collision.md`.
For remaining shapes4791C7..4791E5 first excludes checkpoint materials via
4794C0 then calls game polygon callback4797A0/virtual134. Null material causes
checkpoint filter false at4794E8; retain such polygons. Route game complete
vtables CLevel01BGame4C3CD0, CLevelVR044CE910 and CLevel01Game4C5A80 all have
slot134→475CD0, which returns false. These three scenes add no exclusion through
that hook. Do not generalize to every level callback.
Fresh decoded data from originals, after NC/checkpoint gates:
| Archive | Registered polygons | Wall-grid eligible | NC excluded | Checkpoint excluded |
| --- | --- | --- | --- | --- |
|level1b.omt |2851 |2483 |18 |0 |
|VR04.omt |508 |420 |0 |0 |
|level1.omt |5231 |3860 |24 |0 |
All remaining route polygons have exactly3 corners.469A10 fetches only first
three corners through477F10 (file77F10); registration bounds use all corners.
This distinction is immaterial for these archives, but cannot justify blindly
fan-triangulating larger original polygons for a future source camera query.
477F10 indexes polygon corner data then raw shape vertices+68; it applies no
terrain transform.469A10 adds supplied translation, which these grid queries
pass as identity vector(0,0,0,1). Runtime moving-body collision is separate.
Route OMT hashes and counts are printed by the new helper; source files remain
untouched. Layer509A30 versus509A3C far masks belong to rendering, not these
camera-obstruction grids.
## Triangle acceptance and offset84C clarification
Camera passesfalse sidedness.469B70 normalizes segment direction using the
recovered OMT quick magnitude, accepts source determinant<=−epsilon, barycentric
u/v edges inclusive, t>=0 but **t<segmentLength**. Constants4D5E40/44 are
±1.1920928955078125e−7. Source endpoint rejection469DDF..469DEE is strict;
do not invent a camera-radius skin or reject t=0. Full kernel/math evidence is
in `../analysis/original-collision.md`; its managed support implementation already
contains the winding/quick-magnitude algorithm, but its nearest-hit reducer must
not be reused unchanged for this query.
Offset84C is a camera-input adjustment, not recovered ground clearance. It is
initialized10 in Player437602 and Jimmy4228DE (files37602/228DE); walking resets
10 at438CC6 when complete virtual15C is false and controller mode4F0588!=6.
When virtual15C is true and mode6,438C64..438C7E adds mouse-relative vertical
delta*dt (mouse delta reader46A460); analog/forward/back paths438C86..438CB4
adjust by ±20*dt (constant495324,file95324). Other state/reset writers exist
428723 and class-specific4083A2/408685; do not rename the flag15C or claim the
whole camera-input mode recovered. At default10, source formulas produce
eye200−2*10=180 and look80+1.9*10=99, explaining the port's fixed offsets.
## Verification, remaining gates and implementation boundary
`tools/binary/checkpoint_camera_ray.py ../Original` verifies33 source anchors,
prints mapped constants/hashes/counts and exposes a bounded order reference.
`python3 -m unittest discover -s tests -p 'test_checkpoint_camera_ray.py' -v`
passes4 tests: source+route data, inclusive X/Z ordering/truncation, deliberately
farther wall-first result, and duplicate-cell tests/fallback/disabled gate.
Synthetic acceptance callbacks test query ownership/order, not original ray
arithmetic execution. No GPU/runtime/original timing fidelity is claimed.
A coherent adapter can now preserve source registration IDs, stored normals and
filters; construct sparse12-byte-equivalent cell lists in FIFO order; reuse the
source segment kernel with first-hit reduction; and expose source-enabled flag,
hit identity/point and gain. Verify synthetic farther-before-nearer, wall-before-
floor, winding/endpoint, repeated cells, negative coordinate and NC cases before
camera integration. Test route against the current playable baseline separately.
Still open: source x87 boundary equality on exact grid thresholds; negative/extreme
integer conversion overflow; missing intermediate shape IDs; explicit nonidentity
terrain transform consumers; further84C/input modes; and shared viewport/previous
camera update phase during control handoff. These limit whole-camera fidelity,
but do not justify retaining nearest-sphere behavior as the source static query.
+78
View File
@@ -0,0 +1,78 @@
# Core architecture coverage map
Checkpoint scope: lab → tutorial VR04 → lab → outside, including intro,
explanation, pickup/practice, RETURN, Carl conversation and exit. This compares
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 | Port implementation | Evidence / remaining gap | Next bounded action |
|---|---|---|---|---|
| LOOP | Viewport47E4F0 physics before registry473740, including input44DF80; second sync473770; construction order and selective retained-character/new-game ordering. Separate engine morph clock. | Player now integrates prior body state, then fresh input/player/fire or retained player/fire/input. Other systems remain grouped; fixed60Hz policy. | S/M/R. Controlled player partial order implemented; full registry/cadence and uncontrolled-body preparation open. | C3 continue other callbacks and morph/control phases; C4 support/response remains separate. |
| INPUT | Game interface+8C slot3C4→44DF80→475A70 reads controlled5099E4 and calls3CC; Jimmy interface+C0→426030. | SDL arrows/jump aliases; control gate, modern debug override; mouse/controller incomplete. | S/M/R, user Windows route. Input occurs in object traversal after physics; device sampling/focus and latency open. | Trace event pump, key/mouse and focus gates alongside retained registry order. |
| MOVE |437940/439900 ground/air arithmetic; physics479D20 consumes queued impulse once before acceleration/gravity. | Controlled player consumes prior body state before callbacks; fresh/retained input order explicit. Fixed dt and custom yaw/model conventions remain. | S/P/M/R. Controlled partial phase split verified; uncontrolled/full registry and body response open. | Continue C3 uncontrolled phases, then C4 support/response. |
| JET |437F90 controller;421FB0 effect; fresh constructor order places fire after Jimmy, both after global physics. States0..5, hold>.4,8s, energy. | Explicit state table with post-collision effect ticking and VR immunity. | S/M/R. Fresh same-pass countdown recovered; retained child lifecycle, sound and expiry→animation open. | Trace retained Jimmy/fire resets and phase end events before scheduler integration. |
| COLL |479D20/47BD80 body response; support and quick magnitude; dynamic boxes; NC-shape registration exclusion. | Source support and box pieces around modern swept24-unit capsule, feet/root grounding and slide. | S/P/M/R. Response/masks/stairs/contact order not fully recovered; source radius60 is not port capsule24. | C4: isolate response and root convention; replace adapter behind route tests. |
| ANIM | Engine morph10002DB0; linear interpolation10002F9A; game logical→OMT sync4624B0. | ASE sample timing, unconditional loop closure, pose/action aliases,1/60 advance. | S/P/M/R. Playback flags, rate, completion callbacks, transition order open. | Recover one-shot/loop/end notifications before more aliases. |
| SCRIPT | Source AI/CAM/MCA dispatch and chains; task45F990 objective406F50 BEFORE records BEFORE per-entity424. | Bounded synchronous director; baseline objective after records/actor batch. | S/M/R. Script callbacks recovered for route; generic class coverage and reentrancy incomplete. | C1: ordered objective notification; C2: per-actor Carl override. |
| CONTROL | Global5099E4 null during valid CAM/MCA; PlayerControlled completion target; DEFAULT447D..447F restores camera/UI/music. | Director raw ownership plus explicit debug effective override; player physics stops when uncontrolled. | S/M/R. Null control is not proof all objects/physics stop; scheduler gap remains. | Map raw ownership transitions against phase gates and deferred LOAD. |
| CAMERA | Shared viewport; strict>1000 DEFAULT snap; source eye correction/gain; first wall-grid hit then general-grid FIFO; per-level far planes. | Static source query now integrated for the three route scenes; other scenes use provisional sweep. Separate chase/script eyes and merged clip maximum remain. | S/M/R. Query/kernel/counts tested; x87 boundaries, shared handoff/previous-eye and input branches open. | C5 next shared viewport/DEFAULT and complete follow state. |
| AUDIO | CAM416776..E1 stops music; DEFAULT447F12..45 restarts; bank696008 / gate4F8434; handle47D890 polls inherited software duration and repeat+30. | Separate SDL streams, floating-file-duration cutscene completion, independent per-file SFX. | S/M/R (dummy streams). Source duration/allocation/play-failure/bank/attenuation lifecycle incomplete; speakers/native Windows timing not verified. | C6: explicit bank owner and software channel-clock tests; SDL queue-empty is not the source oracle. |
| UI |406F50 selector/timer;4043D9 controlled clock;407070/O edge;404D97 practice resume.44 objective flags distinct from selector. | Timed objective subset, modal practice, modern UiViewport/debug. | S/M/R. Other flags/gadgets/highlights/cursor/energy/layout transitions open; source widescreen not recovered. | Keep modern scale policy separate; recover UI dispatcher/mode gates before expanding. |
| LOAD | CEditor deferred scene request; selective teardown/reuse; Init stored+11→live+139 resolves old-game deletion; Jimmy/Goddard retained. RETURN root/flags and per-object28→40C. | Reconstructed scene with retained input-order identity and bounded mode/hold/fire container; app-owned presentation. | S/P/M/R. Property stream and bounded scalar/companion resets closed; full body/helper timing and fades remain.50988A is editor R input. | Continue body registration/helper traversal and uncontrolled scheduling; other gadget/level branches remain gated. |
| INVENTORY | PostLoad common prefix enables eight owned gadgets4→1, then VR01..08 disables1→4; full tail re-enables the practice gadget. LV1B disables1/7; other wire values preserved. | Availability pass now applied at level entry and verified across TSK tutorial/return; snapshots preserve raw values. | S/M/R. Full selected-gadget/UI and other level tails remain incomplete; bounded route mode/hold/fire carry is implemented. | Keep availability separate from ownership, task changes and arbitrary state carry. |
| SAVE | TSK45FEE0 writer /4603F0 reader; records, arrays, return strings, stored departure root; queued460E70→460EA0. | Original-format round-trip and CLI save, scene snapshots; no full source save UI/load lifecycle. | S/M. Source reader duplicates matching task callback then all-entity420 post-task hook; this is distinct from Jimmy placement PostLoad423A90. Current fresh-director path differs. | C7 after C1/C2; test repeated callbacks before adopting loader behavior. |
| CHECKPOINT | Pickup42AF00 stores+1E38 root/+1E48 level separately from+9A8 RETURN root. | Capture exposed, not used for return; source capture consumers unknown. | S/M. Do not interpret as death/respawn until read consumer found. | Track unresolved consumer; no speculative gameplay. |
## Interaction and ownership map
| State / owner | Changes when / consumers | Persists or resets |
|---|---|---|
| Task records4FC5FC, name+0/state+64 |45F990 objective hook → record mutation → matching actor424; queries gate triggers/LOAD/NPC | TSK serialized; carried snapshots in port. Same-value assignments still dispatch. |
| Current controlled entity5099E4 | Input dispatch, Jimmy behavior, UI clock, script/camera handoff | Runtime ownership; not interchangeable with task state or whole-world pause. Port F1 override is separate modern state. |
| Scene actor game interface, body, OMT morph | Physics prior body state → registry update → logical/visual sync; animation on engine path | Level-owned construction/destruction; exact spawned effects order not yet recovered. |
| Objective selector4F8194 / transient timing and flags | Task hook406F50, O and practice modal; UI dispatcher reads control | Selector serialized; timer starts hidden20 and is runtime-only. Port implements one selected objective rather than full flags. |
| Departed root complete+9A8 | Ordinary43B5A0 captures; RETURN preserves; PostLoad consumes pending flag | TSK StoredVector persists; pending+954/+9A5 not serialized. STRT yaw remains authored. |
| Return level/start strings | Practice choice records origin; RETURN LOAD selects them | TSK persists strings independently of root and pickup capture. |
| Pickup checkpoint complete+1E38/+1E48 | Pickup callback42AF00 writes; read consumer not proven | Do not equate with departure root or invent reset/respawn semantics. |
| Music/effects/cutscene voice | CAM takes bank/voice and stops music; DEFAULT restores source defaults | Runtime bank/handle lifetime, not task ownership; current port independently opens WAVs. |
| Viewport/camera target | CAM/MCA target/eye; DEFAULT snap and follow; clip/layer resource settings | Original camera handoff is shared viewport state; baseline chase and scripted cameras diverge. |
| Jimmy mode/hold/owned-fire timer | Constructor, controller/fire ticks; property/Init/PostLoad/cleanup boundaries traced for supported route states | Ordinary route container retains these scalars; jump/body reset independently. TSK/debug checkpoint load carries none. First grounded tick can clear retained mode/timer. |
| Modern application presentation and debug | RenderSession keeps window/GPU; debug visibility across loads | User-authorized session policy, outside original TSK or gameplay claims. Scene audio/gameplay disposed/recreated. |
## Assumptions and symptom-level adapters to replace
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. 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
is not a better source oracle. Dummy playback does not verify original timing
or physical speaker output. See `voice-clock.md` for the resolved vtable evidence.
6. Current RETURN root, MCA control target, NC exclusion, air-turn clear and
objective timeout have direct evidence. Retain those rules, but revalidate their
phase/owner when the surrounding scheduler changes; don't discard them as guesses.
## Limits and unresolved gates
Route coverage is stronger than later levels, but still lacks original end-to-end
runtime comparison. No feature-expansion work is justified by this map alone.
The source's UI/task/return state boundaries are sufficient for C1/C2 now. Scheduler,
physics, camera, audio and loader chunks each require their specified probe before
changing behavior. See the linked reports for exact offsets and additional questions.
+107
View File
@@ -0,0 +1,107 @@
# Evidence-based continuation
Checkpoint exit is architecture coverage, not full-game completion. Preserve
baseline69d0187 and original hashes, finish reports/byte checks, then execute these
chunks in dependency order. Each chunk gets its own evidence, regression result
and local milestone; a failed gate triggers further bounded investigation rather
than invented behavior or new levels/features.
| Chunk | Concrete change / evidence gate | Verification and completion condition |
|---|---|---|
| C1 |45F990: notify objectives before changing task records; then dispatch actors. Expose explicit pre-assignment boundary. | Byte assertions45FB5B/7F/D9; observers see old task during objective selection and new task during actor notification; repeat/missing tasks still broadcast. Run Data/Interaction/Director/route regressions. |
| C2 | Preserve per-actor virtual task override boundary. Generic activation then Carl override413F30 before advancing to next actor, rather than applying all Carl overrides after all actors. | Confirm base/derived call bytes; check actor notification sees final per-actor state and authored marker; regression task50→60 conversation/control and lab route. Do not add other class overrides without evidence. |
| C3 | Build original registry/construction/input/frame phase oracle for lab. Split pending motion/controller/effect phases only when registration order and engine callback bridge are recovered. | Assert physics before normal object update, next-node timing, transform sync after callbacks. Compare input→impulse→next-physics→ground/pose trace; test pause/control loss/return. Keep cadence as unresolved policy until engine timer evidence. |
| C4 | Recover47BD80 and Jimmy root/body fields. Replace provisional capsule/feet and wall response behind bounded source adapter. Depends on C3 phase semantics. | Isolated original collision probes plus deterministic wall/step/ceiling/floor/dynamic-body cases; no invisible NC terrain; lab/tutorial route and visual root checks. |
| C5 | Recover follow ray47C210 filtering and coefficients, then implement shared viewport handoff/DEFAULT snap and follow43B820. | Source byte/probe predicate, below/equal/above1000 eye-distance boundary (snap strictly above), obstruction hit adjustment, controlled/scripted/return camera continuity, per-level projection. Port GPU checks remain separate from original visual comparison. |
| C6 | Recover source allocation/failure and sound+44 duration conversion. Source slot14 uses software duration milliseconds and repeat+30, not hardware status. Model that channel state plus current SFX bank/default gate, then connect CAM/MCA completion. | Strict elapsed>duration boundary, repeat/stop/invalid handle/clock pause; bank unload/reload/default/scene disposal. SDL dummy tests validate transport only; queue-empty is not source timing. Physical/native Windows output remains separate. |
| C7 | Queued TSK load460E70→460EA0→4603F0: repeated task424 and all-entity420 post-task hooks. Ordinary scene placement separately uses46E61A→Jimmy40C423610. Recover enclosing loader, RETURN flags/root/STRT and acquired-reset gate50988A. | C1/C2 first. Trace source duplicate-callback effect before adopting; original12-save byte round-trip; fresh load vs RETURN vs practice No/Yes; persistent arrays/score/energy/strings vs reset timers/handles/actors. |
| C8 | Morph playback flags/rate/end events and UI dispatcher mode/layout gates. | Original clip/end-state probes; action interruption/landing/cutscene restoration; objective/practice controls. Preserve modern widescreen/debug policy and test pointer anchors separately. |
Implementation expansion into later levels, gadgets/combat, menus and full save UI
resumes only after these core contracts support it. Later-level investigation is
allowed where it resolves a core-system question, without waiting for every level.
## Execution ledger
- Entry: baseline69d0187 preserved;539 original hashes verified. Dedicated
investigators assigned independent loop/motion, script/state and camera/audio/UI
files. Main loop findings integrated by primary after investigator usage limit.
- C1: implemented pre-assignment objective boundary. Data/Interaction/Director,
input-only lab route and RETURN regressions pass. Source45FB5B/7F/D9 checked
independently and retained in the script/state helper. No scheduler changes.
- C2: captured SCENE before generic activation, moved LV1B Carl override into the
same per-actor director callback, and removed the interactions-layer batch fix.
Original413F3D/413F4E/414068..414118 independently checked. Director callback
observers now see the final derived state before later actors. Director,
Interaction and input-only lab route regressions pass; broader checks pending.
- C3 investigation: input/frame bridge and fresh lab partial construction order
recovered and byte-checked. Fresh game input→Jimmy controller→fire runs after
global physics. Retained registry/lifecycle remains the integration gate; no
speculative global reorder applied.
- C6 investigation: `voice-clock.md` resolves derived slot14 to inherited software
elapsed/duration and+30 to repeat. Replaced the proposed hardware/SDL-playing
interpretation before changing runtime. Original bytes and one new regression pass.
- C5 investigation: `camera-ray-predicate.md` recovers static grid registration,
wall priority, FIFO first-hit and source kernel, with four order/data regressions.
A static adapter is now justified; complete camera handoff still needs its state.
- C7 investigation: `scene-loader.md` closes app deferred request→teardown→GAM→
per-object initialization/PostLoad. Jimmy/Goddard retention/reuse is proven;
per-field reset/old-game/helper lifetime remains a bounded next trace. Editor R
reset distinguished from ordinary load. Consistency review leaves old-game
removal/eligibility explicit rather than treating current pointer overwrite as
deletion. Five evidence regressions pass. This is the next C3/C7 integration gate.
- 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.
- Packages: clean09cf117 Linux/Windows self-contained outputs; Linux launch from
/tmp passes practice/RETURN and outside scene load. Release validation layers
unavailable; source full integration validated above. Package evidence recorded
separately without changing runtime. Continue the remaining source-state and
shared-camera/control/collision gates rather than resuming feature expansion.
- Retained-field continuation2026-10-26: property extraction has no hidden reset
callback; generic Init re-applies authored body vectors, final preparation clears
velocity/speed, Jimmy jump state resets separately from mode/hold/fire. Bounded
route/no-gadget/jetpack PlayerLevelState now carries only those three scalars
through ordinary transitions, never TSK loads. Companion/shadow reset fields and
same-state AI guard are documented; body registration/new-helper timing remain.
- Corrected C7 prefix-only availability: full VR01..08 tails re-enable the practice
gadget0..7, so owned VR04 jetpack finishes1. LV1B disables gadgets1/7. Managed
state boundaries/unknown values and GPU practice/RETURN guard the correction.
Other level-specific selection/availability tails remain an explicit gate.
- Retained continuation validation:84 Python,22 movement plus remaining managed
groups,26 enabled-validation GPU renders, final nondefault tutorial/RETURN
boundary replay, four final SDL dummy checks and539 original hashes pass.
Original43A750/vector leaf component probe passes in isolated Wine32; this is
separate from whole-loader/original-game/native-Windows validation. Next gates:
uncontrolled body/controller/fire scheduling, body registration/helper traversal,
C4 response/root and shared camera handoff. See progress.md for sampling-check details.
- Release evidence: both self-contained packages from clean9ad5a8e; standalone
Linux launch from /tmp verifies nondefault tutorial/RETURN scalar boundaries and
body resets. Release validation unavailable; source GPU checks enabled. Native
Windows runtime remains unverified for this chunk. Preserved baseline untouched.
+135
View File
@@ -0,0 +1,135 @@
# Input dispatch belongs to the viewport game-object pass
Static recovery, 2026-10-25. This follow-up resolves the input/world-logic bridge
left open in [loop-motion.md](loop-motion.md). Originals were read, never executed
or changed. SHA256: Neutron.exe
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`;
OMT2.dll `3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
The helper maps original bytes through PE sections and verifies30 decisive
anchors, direct calls and vtable entries. File offsets below are hexadecimal.
## Recovered dispatch bridge
The level game receives input dispatch during the same viewport callback that
integrates physics. It is **not** called by the engine world's OMT logic update.
There are two distinct update interfaces, with different ownership and clocks.
| Step | Module VA / file offset | Evidence |
|---|---|---|
| Viewport first integrates physics | EXE47E554 /7E554 →479BC0 | Direct call before game-object pass |
| Viewport updates registry | EXE47E582 /7E582 →473740 | Registry50999C, node+8 payload, slot10 call at473758 /73758 |
| Lab game interface enters normal update | EXE4C387C /C387C =470280;4C3C30 /C3C30 =44DF80 | CLevel01BGame interface vtable4C386C: slot10 wrapper; slot3C4 actual callback |
| Base game has identical dispatch | EXE4C2C94 /C2C94 =470280;4C3048 /C3048 =44DF80 | CJimmyGame interface vtable4C2C84 |
| Wrapper supplies frame argument | EXE47028E /7028E;4702C5 /702C5 | Stores dt at interface+294; calls slot3C4 unless supervisor+8C selects3C8 |
| Game updates timer/event records first | EXE44DF89 /4DF89 →45F510 | Direct call before input;45F5BF..D3 advances record float+10 by dt*owner+8 |
| Game dispatches input | EXE44DF94 /4DF94 →475A70 | Same dt argument propagated |
| Dispatcher obtains controlled object | EXE475A9C /75A9C;475AA9 /75AA9 | Global5099E4 null skips input; nonnull calls its interface slot3CC |
| Jimmy receives input | EXE4A3B08 /A3B08 =426030;426084 /26084 →438A60 | Jimmy vtable4A373C slot3CC; guards precede base movement input |
| Later logical objects update | EXE4A3B00 /A3B00 =424600 | Jimmy slot3C4 eventually calls437940 at424C34 /24C34 |
| Entire registry synchronizes transforms | EXE47E587 /7E587 →473770 | Separate traversal after all ordinary callbacks |
| Base viewport draws | EXE47E6DF /7E6DF imports48D304 | Named import OMediaViewPort::render_viewport |
**Pointer coordinates:** CJimmyGame and CLevel01BGame game-interface pointers
are **complete+8C**, whereas C3DJimmy is **complete+C0**. RTTI locators
EXE4E0768 /E0768 (base game) and4E08F0 /E08F0 (lab game) hold displacement8C.
Instruction475A8A /75A8A explicitly reads the complete vptr from interface-8C
and475A90 forms that complete pointer. Do not apply Jimmy's-C0 conversion here.
For the game, interface+294 is complete+320; for Jimmy it is complete+354.
The registry constructor appends to the tail, so input relative to Jimmy's
ordinary update depends on insertion order. The recovered guarantee is:
```text
physics of registered bodies
-> game-object registry traversal in insertion order
game object: event timers -> controlled object's input callback
Jimmy object: base/rotation -> movement/jump/jetpack controller
other objects/effects in their actual registered positions
-> whole-registry logical-to-visual synchronization -> draw
```
Game-before-Jimmy ordering for an actual loaded lab still requires a bounded
construction trace, including constructor-created shadow/fire objects. The
diagram deliberately does not assert that relative order. Even without it,
Jimmy's current controller cannot change the physics pass that already ran.
Queued jump impulses are consumed by a later physics invocation. A separate
class-specific collision query/update during an object callback must not be
mistaken for replaying the earlier global physics pass.
## Engine OMT logic is separate, and runs before render broadcast
DLL100215C0 /215C0 sends logic message-604 at100215D4 /215D4 when global
1013D6DC is zero, then sends render message-605 at100215E8 /215E8, passing
that global as the render-message argument. These are synchronous virtual
broadcaster calls. World listener100F9C40 /F9C40 converts its listener pointer
by-30 and calls complete world slot30, update_logic100F9B10 /F9B10.
World update_elements100F9C80 /F9C80 invokes complete OMT element slot3C,
parent before descendants, preserving its pre-callback next-node pointer.
For CLevel01BGame, complete OMT vtable4C3CD0 slot3C at4C3D0C /C3D0C is
4747A0; this forwards through IAT48D230 at4747A5 /747A5 to
OMediaElement::update_logic, DLL100EFF20 /EFF20, a `ret4` no-op. Thus this
path does not dispatch44DF80 or player input. For Jimmy, complete vtable4A3BDC
slot3C at4A3C18 /A3C18 is462260; it forwards at462265 /62265 through48D244
to OMedia3DMorphAnim::update_logic10002DB0 /2DB0. That calls
OMediaAnim::update_logic10020CF0 /20CF0 with the morph subobject at complete+90.
Eligible animation updates therefore run through OMT logic before the ensuing
render message's game callbacks select/change poses. Logic can be skipped by the
periodical flag, world pause or timer gate. Exact displayed first-frame and
completion effects still require analysis of animation flags and listener order.
The render message reaches engine listener1006BCB0 /6BCB0, which converts its
listener by-10 and calls engine slot14 at1006BCCA /6BCCA. The full renderer
backend/surface/viewport route remains a separately bounded follow-up; the
viewport's own physics→registry→draw order is already established independently.
## Timer units, defaults and limits
| Owner/field | Source VA / file offset | Recovered value or transition |
|---|---|---|
| World pause count+44 | DLL100F9B18 /F9B18 | Nonzero returns without world logic |
| Timer begins world+48 | DLL100F9B26 /F9B26 | Elapsed obtained by100FA0A0 /FA0A0 unless timer byte+0D is set |
| Timer mode world+58 | DLL100F989D /F989D | Constructor writes1 |
| Timer period world+5C | DLL100F98A0 /F98A0 | Constructor writes40 |
| Maximum elapsed world+60 | DLL100F98A7 /F98A7 | Constructor writes500;100F9B42..47 clamps larger elapsed if max nonzero |
| Minimum elapsed world+64 | DLL100F98AE /F98AE | Constructor writes1;100F9B51..5B skips below this if timer is running |
| Engine clock | DLL100F8D18 /F8D18 | GetTickCount import1011410C, minus global epoch1017A308 in ordinary path; optional override/pause branches exist |
| Engine elapsed passed to elements | DLL100F9BCC..E6 /F9BCC | Unsigned integer elapsed converted to float, no seconds division before world slot3C traversal |
| Viewport game clock | EXE47E490 /7E490;47E502 /7E502 | QPC delta/frequency float seconds stored696030; accepted only0<dt<1 |
The **engine elapsed units are milliseconds** in the ordinary GetTickCount path.
These constructor values are defaults, not proof no game/setup writes replace
them. Mode1 passes the elapsed value when it reaches the minimum. Mode0 and2
also compare elapsed with period; mode2 invokes100FA120 /FA120 to adjust period
using accumulated elapsed samples (initial/reset40). Neither establishes a60Hz
gameplay cadence. World max/min elapsed govern the OMT logic/animation route;
they do not directly clamp the QPC seconds consumed by viewport physics and input.
No recovered fixed1/60 accumulator or Sleep-based frame limiter exists in the
bounded application/periodical/viewport routines inspected here. Presentation,
backend blocking and driver synchronization can still constrain actual cadence.
## Current implementation, verification and concrete C3 next action
Baseline69d0187 samples SDL keys and runs grouped fixed60Hz simulation with
controller before physics; Program then updates mechanisms, patrols, director,
objective state and poses. This is an implementation policy and differs from
the directly recovered order above. Do not describe the source world timer's
1ms minimum or40ms period default as the port's intended fixed rate.
`python3 tools/binary/checkpoint_input_frame.py` and
`python3 -m unittest discover -s tests -p test_checkpoint_input_frame.py -v`
check immutable module hashes, fresh source bytes, direct calls and virtual
slots. They provide static verification only. No original gameplay cadence,
native Windows timing, or source input latency was runtime-verified here.
C3 can now define a traceable frame interface with separate **engine animation**,
**body integration**, **insertion-order object callbacks**, and **visual sync**
phases. Before changing the playable controller, recover the lab construction
sequence through object registration46FF4A..7F, and list game/Jimmy/shadow/fire/
Goddard registry positions. Replay that list with a trace asserting physics
precedes all input/controller callbacks and input uses current5099E4. Then split
LabSimulation's input/velocity production from body integration in one bounded
change, preserving the existing route as a regression. Keep fixed60Hz explicitly
chosen until original timing observation or a recovered game frame-cap mechanism
supports replacing it. Also trace event-pump ordering/focus transitions and
pause/invalid-dt boundaries before claiming end-to-end source equivalence.
+129
View File
@@ -0,0 +1,129 @@
# Fresh laboratory construction and registry ordering
Static recovery,2026-10-25. Originals remain untouched; no legacy code executed.
Neutron.exe SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`;
gam/level1b.gam SHA256
`316fff40db565c2add5b07cbccdef640ddb67c64d6625fea1429ce2a0542a234`.
All addresses below are preferred-base EXE VAs; their verified PE file offsets
are VA-400000. The helper emits both coordinates and checks39 source anchors.
## Recovered fresh-load partial order
For a fresh lab with no matching reusable Jimmy, the source establishes:
```text
LV1B game interface+8C enters registry
-> Jimmy interface+C0 enters registry
-> owned jetpack fire interface+C0
-> other Jimmy constructor helpers
-> owned Jimmy shadow interface+C8
-> additional constructor helpers
-> remaining serialized lab entities in file order, with their own helpers
-> postload callbacks in registry order
Jimmy creates absent Goddard interface+C0
-> Goddard shadow interface+C8, then other Goddard helpers
```
This is a **partial order**, not adjacent nodes or absolute list indices. The
helper intentionally does not manufacture a full registry from the GAM alone:
constructor-owned objects are not serialized entity records. Geometry/other
postload objects can also intervene. The ordering does establish that normal
fresh-lab input from the game object runs before Jimmy's controller, Jimmy runs
before his fire effect, and Goddard follows both in the game callback pass.
| Boundary | Calls / source instructions (VA; file offset follows VA-400000) |
|---|---|
| Header first | Loader46E319..32B reads initial FourCC through imported stream operator48D3E0;46E335 /6E335 calls factory459CB0 before entity count read46E36A /6E36A |
| LV1B class allocation | Factory45D3FD /5D3FD →44F300, allocating5C0 bytes; constructor44F3B8 /4F3B8 sets LV1B |
| Game base chain |44F358 →44D2B0;44D306 →4745A0;474602 forms complete+8C;47460A →4586F0;458712 →46FBE0 |
| Common registry insert |46FF4A..7F /6FF4A: global50999C sentinel; alloc12; node.next=sentinel;node.prev=oldtail;sentinel.prev=node;oldtail.next=node;node+8=interface |
| First entity | Lab GAM has129 records; first is3JIM/JIM1 at file000008;46E37F reads its code and fresh branch46E3B9 calls factory459CB0 |
| Jimmy factory/base chain |45B1E2 →422160;4221B1 →437280;4372DA →40D110;40D162 →462040;4620A2 forms complete+C0;4620AA →4586F0 →46FBE0 |
| Fire during player base construction |4374DF →421D80;421DD2 →40D110, so it registers after Jimmy;4374EF stores fire complete pointer at Jimmy complete+7F8 |
| Jimmy shadow |42250C →43F640;43F692 →4352F0;435341 →463F10;463F6C forms complete+C8;463F74 →4586F0 →46FBE0;42251C stores shadow at Jimmy complete+A2C |
| Remaining GAM records |46E3FD invokes stream extraction48D190 on the current interface;46E426 reads next code;fresh branch46E49A calls factory;46E4BA loops to46E3D1 |
| Postload after records |46E4FF invokes supervisor slot128. Vtable4D5EA0 entry4D5FC8 /D5FC8 resolves46E570, which traverses registry and invokes interface40C at46E61A |
| Jimmy postload |Vtable4A373C entry4A3B48 /A3B48 resolves423610. This callback contains the Goddard construction below |
| Goddard is runtime-owned |Lab GAM contains zero3GOD records.423C6A..72 tests Jimmy interface+95C; if absent,423C98 →41C810;423CAE stores Goddard complete pointer at interface+95C (complete+A1C) |
| Goddard registers before his shadow |41C861 →407A40;407A92 →40D110 →462040 →4586F0;41C95F →43F640 builds his shadow afterward;41C96F stores shadow complete pointer at Goddard complete+994 |
The postload traversal reads next after the callback at46E668, so a newly
tail-appended Goddard is eligible to receive postload later in that same traversal.
This follows from the linked-list operations; it is not an original runtime
capture. Allocation failure and callbacks that remove/reorder nodes need separate
handling and are not silently interpreted as the normal successful load.
## Fresh input/controller/effect frame consequence
[input-frame-bridge.md](input-frame-bridge.md) establishes that viewport47E4F0
first calls global physics479BC0, then registry updater473740, then transform
synchronization473770, then base draw. Combining that with the fresh partial
order gives the bounded interaction:
1. Physics consumes existing Jimmy velocity/acceleration/queued impulse.
2. Game44DF80 advances timer records and dispatches input475A70 to current5099E4.
3. Jimmy424600 updates base/rotation/controller437940, which may queue a jump or
start/stop/change a burst.
4. Owned fire421FB0 runs later, observes that controller state and decrements
its timer/energy according to its already recovered rules.
5. Goddard's ordinary game update occurs later in the same registry pass.
6. All surviving logical actor transforms are synchronized before rendering.
Thus a fresh controller-created impulse waits until a later global physics pass,
while a newly assigned positive fire timer can be decremented by its effect
callback in the same game-object pass. This resolves the previous open
Jimmy-versus-fire ordering without inventing a nominal60Hz source cadence.
The baseline port's combined controller→physics→effect call differs at the first
boundary. Splitting pending body inputs is directly supported for this fresh-load
case; actual gameplay comparison remains required for latency/apex fidelity.
## Reuse and transition ordering remain a separate gate
Source explicitly supports existing-object reuse:
- Jimmy constructor42275A writes complete+C9=1, or interface+09. Goddard
constructor41C9C0 writes the equivalent flag. Common constructor46FFAE starts
interface+09 at0. This is an observed reuse flag; it alone does not prove
lifetime across any particular level transition.
- Supervisor vtable4D5EA0 slot11C at4D5FBC /D5FBC resolves46E6A0. It walks
registry50999C and requires matching interface+404 class code **and** nonzero
interface+09 at46E6B9..C6. Slot110 at4D5FB0 /D5FB0 resolves46E6E0, returning
the first matching existing object without moving/re-appending its node.
- Loader46E38B /6E38B and46E45A /6E45A use this predicate before choosing the
fresh factory branch. Reusing Jimmy therefore does not repeat his constructor
or append his fire/shadow again. Jimmy postload separately reuses his existing
Goddard pointer if present.
**Follow-up for lab→tutorial→lab:** `scene-loader.md` now proves Jimmy/Goddard's
zero teardown predicate and positive reuse flag together. Their retention/reuse
contract is recovered, but the complete retained helper set, field resets and
old current-game removal/eligibility remain open. Deferred transition46DFF0 queries each object's
slot200, calls lifecycle slots20/34, marks some interface+06 for deletion and
calls473710.473710 deletes flagged nodes through interface slot0 and restarts
the list scan. A complete retained-set proof needs each relevant slot200 getter
and flag write, plus each object's lifecycle callbacks and owned-child cleanup.
Slot200 for Jimmy/Goddard is4719B0, reading interface+139; **it is not** the
reuse flag+09. Conflating those two fields would fabricate persistent ordering.
Do not assume the fresh game-before-Jimmy relation after a transition: the new
game appends later, while old-game callback eligibility needs its own proof.
## Verification and bounded next implementation
`python3 tools/binary/checkpoint_lab_registry.py` verifies source hashes,
12 decisive instruction ranges,23 direct calls and4 virtual entries, then parses
the original lab GAM for its header/count/first record and absent3GOD record.
`python3 -m unittest discover -s tests -p test_checkpoint_lab_registry.py -v`
passes the original-data regression. This is static evidence; no port or original
gameplay runtime verification was performed for this follow-up.
Baseline69d0187 groups simulation, mechanisms, patrols, director and effects by
subsystem. A C3 scheduler can now model the fresh lab's proven input→Jimmy→fire
ordering after global physics, with logical-to-visual synchronization last.
Keep initial source-order replay separate from current playable policy while
covering queued jump, same-pass burst countdown, landing and control transfer.
For the tutorial return, first trace cleanup46DFF0→lifecycle20/34→473710 and
prove the surviving node sequence; use that sequence when serializing/rebuilding
the scheduler. Other Jimmy/Goddard helper identities, construction-time nested
spawns and later runtime appends still need an explicit registry trace before
claiming the complete list or all-level ordering is recovered.
+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.
+113
View File
@@ -0,0 +1,113 @@
# Main loop, input, motion and animation
Static recovery from supplied Neutron.exe (SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`) and
OMT2.dll (`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`).
Investigated independently, integrated and byte-checked by primary. No original
whole-game runtime comparison. `checkpoint_loop_motion.py` reports PE-mapped
file offsets and verifies decisive calls/vtable anchors. For the EXE anchors below,
file offset is VA minus400000; do not apply that shortcut to DLL addresses.
## Recovered loop and ownership
| Boundary / owner | Original evidence | Interaction |
|---|---|---|
| Application pump | EXE4802F2 CRT →4789B0 WinMain →46A4A0 bootstrap; DLL100218A0 application start →10060720 devote_time | Engine periodicals own dispatch; not an established60Hz game loop |
| Engine animation periodical | DLL100215C0 emits -604 logic and -605 animation/render; world100F9B10 →100F9C80, world+48 timer and pause/min/max periods | Engine logic and game render callback are separate timing paths; exact interleaving needs trace |
| Game frame entry | EXE47E374 (file7E374) assigns viewport vtable4D74C4; slot+B8 at4D757C points to47E4F0 | This is a viewport render override, not an ordinary world logic tick |
| Frame time | 47E4FC virtual+D4;47E502 stores float seconds696030; guards47E508..52A accept0<dt<1; QPC reset47E470/elapsed47E490 | No source fixed1/60 accumulator recovered; do not choose original cadence from port tests |
| Conditional first passes | 47E554 →479BC0 physics;47E560 →462A20 transient pass;47E56B →4693A0 frame-list pass | All three require475CA0 true, supervisor509980 nonnull and supervisor+8C clear |
| Remaining passes |47E57A →47D8F0 sound;47E582 →473740 objects;47E587 →473770 transform sync;47E6B1 →477DB0 | These calls are outside that first-pass gate but inside valid-dt branch |
| Draw and post-draw |47E6DF imports viewport render via IAT48D304;47E6E5 →468600;47E6EF increments696028 | Draw occurs after game update/sync; invalid dt skips game passes but still reaches base render |
The object registry is a circular doubly linked list at50999C. Node layout:
next+0, previous+4, game-interface payload+8; allocation12 bytes at46FF50.
Constructor46FF4A..46FF7F appends to tail. Thus473740 walks construction/insertion
order, not grouped actor types. It invokes payload.vtable+10 at473758, then
reads next at47375B: appends during a callback can be visited in that same pass.
Deletion/reentrancy safety is not fully recovered.
Common slot10 wrapper470280 stores dt at interface+294 and invokes slot3C4 in
normal mode (4702C5), slot3C8 when supervisor+8C is set (4702B5).
Jimmy's3C4 is424600; movement path437940 executes during that object update.
Physics479BC0 has already consumed the existing body state. This establishes
prior-velocity/prior-impulse integration before the current controller computes
new motion. It does not alone establish the complete input/engine interleaving.
473770 is a second whole-list traversal invoking interface3DC then3E0. Jimmy
3DC4624B0 gets logical position through slot310 and writes interface-7C/-78/-74
(complete object+44/+48/+4C). Slot3E04624F0 →473540 synchronizes Euler angles.
Many objects expose multiple inheritance interfaces: the usual game interface
is complete+0xC0. Label every field by its pointer base; never merge equal-looking
offsets from unrelated interfaces.
## Input, controller and physics boundaries
Input arrives through game update44DF80 →475A70;475A9C reads controlled pointer
5099E4, null skips dispatch;475AA9 invokes its slot3CC (Jimmy426030).
Follow-up [input-frame-bridge.md](input-frame-bridge.md) proves44DF80 itself is a
normal registry3C4 callback on the level game interface (complete+8C). Thus input
is inside473740 after physics, distinct from Jimmy's own424600 callback but not
an independent world-logic tick. The game's OMT3C callback4747A0 only forwards to
base element no-op. SDL sampling/fixed ticks remain implementation policy.
Previously recovered detailed arithmetic remains in `analysis/jetpack.md`,
`analysis/original-collision.md`, `analysis/dynamic-collision.md` and
`analysis/patrol.md`:
- Jimmy movement437940/437F90 and air fall-through439900 own speed/turn/jump state.
Mode1 does reach airborne steering; the old binary report's “no action” label is
superseded. Grounded/released clears interface+614 (complete+6D4).
-479BC0 visits bodies;479D20/479EBB..479EF2 consumes queued impulse once,
then acceleration/gravity and displacement479F8D. This is a per-body algorithm,
not proof of the port's surrounding controller order.
- Jetpack controller437F90 and effect421FB0 have distinct owners. Timers,
state0..5, radius100/60, impulse550, hold>.4,8s burst and.5/s energy drain
are narrowly recovered. Registry insertion order of Jimmy/effect must be traced
before deciding same-frame vs next-frame effect expiry and impulse application.
- Source support/ray/magnitude and dynamic box broadphase have byte/DLL evidence.
Static response47BD80, stairs, all body masks and contact side effects remain
incomplete. NC shape exclusion is a recovered registration gate, not a water fix.
## Animation
There is a separate OMT logic/morph path: EXE462260 forwards its argument through
IAT48D244 to OMT morph update10002DB0. Common logical/visual transforms are copied
by the later registry sync. Morph interpolation is recovered at DLL10002F9A;
original mode2 probes for tested standing/jump clips return zero dynamic-point
offsets. These probes do not establish full animation scheduling or collision pose.
Port `MorphAnimation` samples extracted ASE timing with linear interpolation,
loops the final sample to first unconditionally, and rejects irregular samples.
`PreviewAnimationLibrary` chooses from pose/action aliases; Program resets poseTime
on clip change and adds1/60 every port tick. Actor visuals likewise run after the
grouped gameplay passes. Playback-end callbacks, one-shot vs looping flags,
class-specific speed, state transitions and interrupt rules remain unresolved.
## Baseline comparison and verification
Baseline69d0187 runs `LabSimulation.Step` controller → physics → jetpack effect →
camera, then contacts/mechanisms → patrols → director → objective timer → animation.
This contradicts the recovered physics-before-object-update contract and replaces
construction-order callbacks with subsystem groups. A global reorder now would
invent ordering for spawned effects, scripts and NPCs. First build a lab registry
and phase trace and assert source contracts; only then split simulation phases.
The helper and Python regression verify exact original bytes/call order; managed
tests verify port arithmetic and deterministic route outcomes. Neither proves source
cadence, input latency or original end-to-end gameplay. Keep both traces separate.
## Explicit unresolved questions / next work
1. Input bridge is resolved: registry3C4→44DF80 after physics. Exact event-pump,
pause/focus/invalid-dt/multiple-viewport behavior remains open. Engine world
timer is milliseconds, default mode1/min1/max500, distinct from QPC game seconds;
see the follow-up before interpreting the40ms period or choosing a cadence.
2. Capture lab construction registry including Goddard, jetpack effect, transient
objects and deletions; identify462A20/4693A0/477DB0 dependencies precisely.
3. Recover47BD80 response, Jimmy body/root/capsule relationship and source contact
ordering before replacing provisional feet grounding/sweep-slide collision.
4. Trace morph flags/end events and class animation selection, including cutscene
exit, jump→fall→land and jetpack state/energy transitions.
5. Probe isolated source components where possible; full original timing remains
unverified until a usable original runtime exists. Do not use nominal60Hz as fact.
@@ -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.
+162
View File
@@ -0,0 +1,162 @@
# 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.
## Superseding continuation (2026-10-26)
The bounded investigation below was an initial local-prefix audit. Its old claim
that VR04 finishes with jetpack state4 is incomplete: the full level-specific
PostLoad tail re-enables the practice gadget, so owned jetpack finishes state1.
LV1B additionally disables gadgets1/7. See retained-return-cleanup.md for all
VR01..08 tail calls. Runtime/tests now apply those complete tutorial/route rules.
Property callbacks and bounded scalar carry are closed by retained-streamer.md,
retained-player-body.md and retained-companion.md. Later sections preserve the
initial evidence and explicitly limited scope, not the current final-state claim.
## 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. The first continuation called `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.
+127
View File
@@ -0,0 +1,127 @@
# Retained Goddard and shadow: ordinary-load reset trace
Static investigation,2026-10-26. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
All VAs below are in this EXE at preferred base400000; inspected raw offsets are
**VA−400000**, independently PE-mapped by `tools/binary/retained_companion.py`.
No original code was executed. No runtime implementation was changed.
## Identity, caller and property boundary
Goddard complete vtable49F920 is installed at41C866; its game-interface table
49F480 is installed at41C883 with complete+C0 receiver. Shadow complete table
4B3C1C/game-interface4B37B8 are installed at43F6A0/43F6AD, interface complete+C8.
Constructor retention/reuse writes remain as recovered in scene-loader.md:
Goddard41C99B..41C99E passes0 to470F40, and41C9C0 sets complete+C9=1.
These are constructor facts, not repeated initialization.
The route GAMs level1b.gam/LV1B, VR04.gam/VR04 and level1.gam/LEV1 contain **no
3DOG or3SHA serialized records**. Their bounded GAM parses/hashes are emitted by
the helper. Consequently ordinary reuse on this route does not stream a new
Goddard/shadow property record. The app's per-object Init28→PostLoad40C registry
pass still runs on their retained interfaces (scene-loader.md). A fresh companion
is dynamically constructed by Jimmy PostLoad when his interface95C pointer is
null:423C6A tests it;423C98 calls Goddard constructor41C810;423CAE stores it.
Existing pointer takes423CD4..423CE2 instead, discussed below. Exact same-pass
handling of a newly appended companion remains a registry-order question.
## Goddard Init and PostLoad
49F480+28→41E6A0 tail-jumps407EB0. At407EB3 it calls generic4587F0;407EB8 sets
interface byteA=1;407EBC..407EC2 copies authored87C→current AIstate608;
407EC8 clears current waypoint800. Complete offsets add C0. This replaces current
AI state and waypoint, not all AI fields. In constructor41C90E/41C914, current
complete6C8 and authored complete93C both start4.
49F480+40C→41E590 calls shared actor409480 at41E593. Its local work, in order:
| Source VA / raw coordinate | Reset or refresh |
|---|---|
|409486 /9486|Call generic40E7B0 visibility/animation policy; not a constructor.|
|40948B..40949A /948B..949A|Resolve tag string interface6AC through474070; always assign resulting pointer to600.|
|4094A0..4094FD /94A0..94FD|Only if pointer nonnull: refresh610 from target+404 (identity) and828/82C/830 from target logical root310. Null pointer leaves those cached fields untouched locally.|
|409503..40951E /9503..951E|Snapshot current608→authored87C; invoke complete124(current608), target4089B0.|
|40952D..409552 /952D..9552|Read authored Euler via interface170→4716A0 (FC/100/104/108), write logical Euler via32C→472450 (224/228/22C/230).|
|409561..409580 /9561..9580|Read authored Euler again and copy all four words into interface274/278/27C/280. This is an Euler-cache write, not sufficient evidence to name274 a queued physical impulse.|
The state setter4089B0 is not an unconditional state-entry callback. After its
special complete970 guard for requested states0/6,4089F8 copies current6C8 to
previous6CC and assigns requested6C8;408A18 skips transition cases when equal.
Init has already assigned current from authored, and PostLoad passes that exact
current value back. Therefore this chain does not justify replaying arbitrary AI
state-entry side effects at scene load. Intervening source callbacks could change
state; those require their own ordered fixture.
Goddard's derived41E590 then applies level policy:
| Source | Normal LV1B/VR04/LEV1 branch |
|---|---|
|41E598|interface918=1500 (range; exact consumer semantics remain separate). VR06 substitutes3500 at41E5EE.|
|41E608..41E613|If render attachment exists, set complete70=1 and dispatch complete58(0), the existing show/unhide path.|
|41E618/41E624|interfaceD0(1) and214(1); setters4710C0→471A40 and471A00 write authored/live movement/collision flags.|
|41E632|interface2C initialization/sync dispatch42AB50, which gates4623D0 on interface49E. Body re-registration internals remain in the physics investigation.|
|41E637..41E63B|complete17C(0)→41CC30: select submode0, copy globals4F8200/204/208 into complete6D4/6D8/6DC, set WORD complete9A0=0. These are table-sourced resets; do not invent numerical values from uninitialized file storage.|
|41E641/41E64A..651|interface914=1; interface110(130)→471240 writes authored34 and264→471B40 writes live15C.|
|41E657|interface928=0.|
Hidden branch41E661 applies to LEV6,LEV7,LV1C,LV1D,LV4A,LV6A. It calls complete58(1),
interfaceD0(0),214(0), and sets928=1. It does **not** locally assign130 radius or
submode0; carrying an old radius is not equivalent to resetting it to0. The helper
includes exact comparison immediates and a bounded branch oracle, with neighbors
tested. These later-level predicates are recovered locally, not proof of those
levels' full behavior.
## Existing companion174: rotation, not velocity
Jimmy423CD4 addsC0 to the existing companion pointer and passes three zeroes to
its interface174 at423CE2. 49F480+174→4716D0 writes authored EulerFC/100/104,
dispatches330→472420 to logical Euler224/228/22C, then3E0→4624F0→473540 to convert
logical Euler and dispatch render angle sync3E4. It is a rotation reset. Calling
it a velocity reset would conflate distinct coordinate fields.
Thus the source can zero Goddard's authored orientation before his own retained
PostLoad later copies authored→logical/cache. This report establishes both local
mutations; precise registry placement must determine their temporal order. Jimmy's
separate STRT/RETURN root placement still owns companion position, as already
documented. No broad body-velocity reset is inferred from174.
## Shadow PostLoad and resource lifetime
4B37B8+28→4587F0 generic Init;40C→43F810 first calls4354C0 at43F814. That base:
-4354C3..4354CA resolves authored database name interface4BC using46ACC0.
-If found,4354D6..4354F5 calls completeC8→464430 with resolved database,
authored interface4B8 resource selector and float-converted4B4. If a resulting
attached object exists at complete8C (interface−3C),435503..435513 sets its60/64
to1 and calls its embedded interface24 slot10.
-If the first database lookup fails,435518 tries literal4F02C0
`permanenticons.omt`; if found43553F..435542 attaches selector3 with the same
float-converted4B4. If both fail, no attachment dispatch occurs locally.
43F819..43F844 then converts signed authored WORDs interface520/522 into complete
AC/B0 runtime size;43F84A/43F854 resets completeB4=2 andB8=0. If global509A13 is
set,43F867..43F86B calls complete58(1) to hide. This refreshes visual-resource
references and size/flags, so retained identity does not mean retaining the old
scene's texture/database handle. No local owner-pointer reset is proven; full
database teardown/reattachment internals are separate.
## Implementation and remaining gates
Current port reconstructs companion/animation/patrol objects on scene continuation
and explicitly restores RETURN roots. It does not model this complete retained
Goddard/shadow lifecycle. Existing patrol remains a subset: state4 follow, source
angle/render sync, shadow resource identity and per-object ordering are incomplete.
Direct fixture contracts now supported: no route property reload for companion;
Init restores AIstate/clears waypoint; target caches refresh conditionally;
authored rotation controls PostLoad and174; normal route reapplies130/flags/
submode0; shadow resources/sizes refresh. Unknown fields must remain unknown,
not be silently copied or zeroed. Full body registration4623D0 and exact newly
appended/retained registry callback timing gate live retained-container integration.
Validation: `python3 -m unittest discover -s tests -p test_retained_companion.py -v`
checks EXE identity, exact instruction/vtable targets, route record absence,
rotation-setter provenance and level-branch boundaries. Helper JSON:
`python3 tools/binary/retained_companion.py ../Original`. This is immutable static
evidence plus an interpretation oracle, not original runtime execution or port
gameplay validation.
+90
View File
@@ -0,0 +1,90 @@
# Retained player: body reset and ordinary-load scalar boundary
2026-10-26. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred-base EXE VAs below map to raw offset VA−400000; the helper independently
maps PE sections. Originals remain untouched. Static recovery, isolated component
execution and port tests are separate evidence categories.
## Closed callback chain
Read `retained-streamer.md`, `retained-return-cleanup.md` and
`retained-companion.md` alongside this report. Together they close the bounded
no-selected-gadget/jetpack route path through deferred load, property read,
generic Init, Jimmy PostLoad and final control preparation. The property reader
does named descriptor writes without an implicit constructor/reset callback.
Route game Init28 resolves44D4E0→4587F0→470540. Game control118 resolves475A40,
which writes global5099E4; it does not itself reset Jimmy's movement mode.
Generic Init470540 re-applies authored vectors through virtual getters/setters:
| Quantity | Authored interface field / getter | Live field / setter | Init caller / physics consumer |
|---|---|---|---|
| Acceleration |3C..48 /11C→471290|164..170 /274→471BD0|4706EA→47070F;479F01 reads270→471B70,479F4A adds acceleration×dt to velocity|
| Queued impulse |4C..58 /124→4712E0|174..180 /288→471CC0|47071E→470743;479EBB reads284→471C60,479EE5 adds it,479EF2 clears via28C→471C90|
| Velocity |7C..88 /13C→4713D0|1A4..1B0 /2C0→471F70|4707BA→4707DF;479F8D reads2BC→471F10|
All copied vectors have four float components. These are authored→live copies,
not unconditional zero writes and not arbitrary preservation of the prior live
body. Route GAM JIM1 records do not contain these authored vector properties;
their source constructor/class defaults remain distinct from property extraction.
The port currently initializes its provisional body vectors to zero.
Jimmy PostLoad's common tail424472 grants control;42447D invokes410→42AFC0.
42AFC3 calls43A750, which clears speed608 at43A758 and invokes2C4(0,0,0) at
43A764..43A76C. Target471F40 writes velocity1A4/1A8/1AC; it does not overwrite
the fourth component1B0. Complete148 stops the saved sound, then the derived
preparation requests `STOP` animation. Neither null control nor this preparation
means all scene physics stops. Uncontrolled-body scheduling remains a next chunk.
Generic Init also clears274/278/27C and298; these are separate cached fields,
**not** the acceleration/impulse vectors above. Do not confuse a virtual slot
number with a same-numbered member offset.
## Bounded retained-state contract
| State | Boundary behavior and evidence |
|---|---|
|Movement mode complete7C4/interface704|Constructor zero is not repeated; absent from route GAM, generic Init and resolved no-gadget/jetpack cleanup/PostLoad writes. Retain.|
|Jump hold complete874/interface7B4|Same bounded absence after closing property/control paths. Retain; later state0 takeoff resets it independently.|
|Owned fire timer complete6C0/interface600|Fire retained object; generic28/40C do not reset it; jetpack cleanup does not own it. Retain. First grounded fire tick421FE9 zeros it before subtracting dt.|
|Jump state complete7E8/interface728|PostLoad42378B resets WORD to0. Do not carry with mode/hold.|
|Speed608, turn614, scalar618, destination yaw61C|Jimmy Init437890 clears first three and captures authored logical Euler.Y; final preparation clears speed again.|
|Body vectors, support, radius, collision contacts|Re-apply their own initialization/PostLoad policy; not copied in the scalar container. Source radius60/factor1.265 reasserted. Full registration/response remains open.|
|Selected gadget|Cleanup and destination selection have their own state machine; not persisted by this scalar container.|
|Goddard/shadow|Identity survives; Init/PostLoad restore specific authored AI, waypoint, target, rotation/resource/visibility state. No blanket AI or shadow-state carry.|
This is a **boundary** contract. A first destination controller/effect callback can
change the same scalar immediately. Observing the timer after grounding is not a
test of whether the loader reset it. Other gadget cleanup branches explicitly
change movement mode; other level tails remain unported and need separate proof.
The full ordinary loader and original route have not been executed end to end.
## Port implementation and verification
`PlayerLevelState` carries only mode/hold/fire in memory for LV1B/VR04/LEV1 and
selected gadget−1/3. Apply follows new scene construction and precedes scene
playback. Destination jump state starts0; body, presentation and debug settings
initialize independently. Noclip does not capture a carry state. Unsupported
levels/gadget cases use the existing reconstruction policy, explicitly unproven.
TSK/CLI/debug checkpoint load gets no scalar container; no wire format changed.
R reset remains the authorized modern reset, clearing these transient fields.
Movement tests use nondefault mode/hold/fire sentinels, then independently verify
body/jump reset, airborne first tick, grounded release/effect reset, unsupported
scope and explicit reset. The GPU practice/RETURN fixture seeds nondefault values
and asserts the actual cross-scene bridge before the destination's first tick.
These are port regressions, not original cadence or whole-route fidelity evidence.
Static helper: `python3 tools/binary/retained_player_body.py ../Original`.
Two evidence tests guard26 instruction sites and16 virtual targets. The C probe
maps an isolated copied EXE without entry point/import initialization, calls the
original vector leaf accessors and43A750 with sound handle−1, and compares all
other sentinel bytes. Synthetic fixture vtables use byte-guarded source targets
in a rebased copy; selected paths use no absolute globals or unresolved imports.
The isolated Wine32 probe passes; it is intentionally narrower than full Init/PostLoad.
Runtime probe outcome and full integration/package evidence are in progress.md.
Remaining: body registration4623D0, original support/response and cadence,
uncontrolled controller/fire phases, exact registry traversal of newly appended
helpers, other selected gadgets/level tails and original end-to-end comparison.
+122
View File
@@ -0,0 +1,122 @@
# RETURN cleanup and complete PostLoad route tail
Static C3/C7 continuation,2026-10-26. Read-only source is Neutron.exe SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
All preferred-base EXE VAs below map to raw file offset VA−400000 for these sites.
The helper maps PE sections independently and emits actual offsets/bytes and
virtual targets. No original code was executed; no runtime implementation changed
in this investigation. This report supersedes the earlier **prefix-only** gadget
availability interpretation in retained-character-reset.md.
## Result: cleanup is selected-gadget policy, not a universal motion reset
RETURN457FED adjusts Jimmy's game interface−C0 to complete, then457FF7/9 invokes
complete178. Table4A3BDC+178 resolves427FF0. After cleanup,458014 setscomplete954,
458028 sets9A5, and45815C dispatches complete168→43B5A0. Cleanup therefore runs
before RETURN flags and ordinary transition staging.
427FF0 first updates the C2DInGameMenu at completeA18, if present. Provenance:
Jimmy42238D calls401430,4223A6 stores its result inA18,401464 installs48D414;
literal4EF05C identifies `C2DInGameMenu`. Cleanup calls its4B0(3) at42800C, then
4C4 at42801A; those resolve405FB0 (menu selection/resource visibility) and406590
(close/free menu resources). The receiver is not the owned C3DJetpackFire.
428020 loads signed WORD selected gadget4F0588. Unsigned bound428027..2A rejects
values outside0..7, including−1, to the common epilogue. Table428844 has:
| Selected gadget | Case target | Relevant distinction |
|---|---|---|
|0|428037|If completeA14 exists, explicitly writes movement mode7C4=0 at42804F and restores radius/support.|
|1|4284FB|Writes mode7C4=1 at4286EA after companion/gadget cleanup.|
|2|42810C|Other gadget/companion policy.|
|3 (jetpack)|42882F|Directly the common epilogue: selected gadget4F0588=−1.|
|4|4281B3|Other gadget/companion policy.|
|5|4280CC|Conditional companion/gadget policy.|
|6|42871D|Other gadget/companion policy.|
|7|4287AC|Other gadget/companion policy.|
The jetpack/no-selection branch does not zero movement mode7C4, jump7E8, hold874
or owned fire6C0. This is a local caller projection, not proof that every later
load callback preserves those fields. Generic cleanup must not be modeled as
“clear all movement”; gadgets0/1 demonstrate different behavior.
Ordinary43B5A0 does not use this selected-gadget dispatch. It stages strings,
clears7FC, conditionally copies departure root9A8 unless9A5, queues the scene
request at43B7F1, then calls complete148 at43B7FB. That target429A00 only stops
saved sound handleA44 via458A00 and writes−1. Practice Yes40470D uses this ordinary
stage. Ordinary LOAD uses it at458276. RETURN adds its preceding cleanup/flags.
## Critical correction: read the entire Jimmy PostLoad
The generic prefix423DEF..423E3F enables the eight group0 gadgets, then
VR01..08 prefix423E71..423EC1 disables them. **That is not the final state.**
Jimmy PostLoad continues through424557 and has level-specific overrides:
| Destination | Tail behavior and source call VAs |
|---|---|
|LV1B|423FBB..423FCB recognizes LV1A..LV1C.424108 disables group0 item1;424113 disables item7.|
|VR01|4242BB cleanup;4242C7 enables item0.|
|VR02|424319 cleanup;424325 enables item1.|
|VR03|4242F0 cleanup;4242FC enables item2;424408 selects item2.|
|VR04|424340 cleanup;42434C enables item3;42435A selects item3.|
|VR05|424380 enables item4;424394 cleanup.|
|VR06|4243A8 cleanup;4243B4 enables item5.|
|VR07|4243CA cleanup;4243D6 enables item6.|
|VR08|4243EE cleanup;4243FA enables item7;424408 selects item7.|
|LEV1|Falls through to common42440E without those per-level overrides.|
VR05..08 branch424365 subtracts56523035, bounds0..3, then dispatches table424558
to42437A/42439C/4243BE/4243E0. Every enable call pushes `(disabled=false,item,group0)`
in reverse argument order and targets403870; conversion remains only4→1. Thus
every tutorial enables its corresponding practice gadget0..7 after disabling the
others. Unknown/unowned wire values remain unchanged. LV1B owned items1/7 finish4.
Source VR04 owned jetpack3 finishes1, not4; lab return leaves it1. The earlier
port tests asserting VR04 jetpack4 validated an incomplete source prefix.
Other ordinary-level branches also exist in423EE1..42440E; their availability,
selection and automatic save policies are outside this bounded route correction.
Do not present a route-specific implementation as a full PostLoad reconstruction.
## Remaining callback closure for retained fields
Common PostLoad42373E cleans selected gadget5 specifically, not every gadget.
Jump state is separately cleared at42378B (interface728=complete7E8). The route
tails above run after that reset. VR04's complete174(3) resolves428D50; its table
4298E8 is indexed item+1 and maps both−1 and3 to428DE0. That branch tests global
inventory item9==2, conditionally schedules another practice level, and otherwise
returns. It does not initialize movement/hold/fire time. Its UI prelude uses the
same menu-selection405FB0 and does not own the effect timer.
The common tail424472 grants control through game118, then42447D invokes Jimmy410
→42AFC0. That calls43A750 (speed0/body velocity2C4(0,0,0), separately recovered by
primary), stops sound148, then complete150(`STOP`) at42AFDE..E5. Complete150 is
43AFF0: a conditional animation/action request; it dispatches completeE0→40DD90,
which updates morph selection/alias strings and animation flags through base
targets. It contains no movement-mode/hold/owned-fire write. `STOP` is literal
4ED040, distinct from `RUN`4ECA64. This final control preparation does not mean
movement mode is walking0.
Owned fire has its own subsequent tick421FB0. It queries owner support218 at421FDF,
zeros interface600=complete6C0 only if grounded421FE9, then subtracts dt421FF3.
This is an effect tick, not a loader reset. Takeoff separately zeros the timer at
438391. Initialization can preserve a timer that the first destination tick then
changes; comparisons must observe the same phase.
**Confidence:** high for exact cleanup/table arguments and final route availability;
high for absence of direct scalar reset in these resolved local paths. Mode/hold/
fire preservation through a complete transition additionally requires the sibling
property-stream/Init proof and enclosing control/loader order. Retaining only
these bounded scalars after that closure is justified for no-selection/jetpack
route states; retaining arbitrary gadget modes, physics vectors or effect handles
is not justified by object identity. Body reset, selected gadget and jump state
must remain independent state dimensions. Original runtime comparison remains open.
## Verification
`python3 -m unittest discover -s tests -p test_retained_return_cleanup.py -v`
passes5 tests covering immutable source identity, exact instructions/vtables,
cleanup table, all eight tutorial tail argument/dispatch sites, and a deliberately
nondefault sentinel projection for selected jetpack/no-selection cleanup. The
projection checks interpretation only; it does not execute the original routine.
`python3 tools/binary/retained_return_cleanup.py ../Original` emits the evidence;
local generated copy: artifacts/retained-return-cleanup.json. No originals modified.
+99
View File
@@ -0,0 +1,99 @@
# Retained Jimmy: GAM property-stream boundary
Static C3/C7 follow-up,2026-10-26. Read-only analysis of supplied Neutron.exe
SHA256`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`
and OMT2.dll SHA256`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
EXE preferred base400000; DLL preferred base10000000. All listed raw offsets
map to VA−module base, checked through the PE sections by retained_streamer.py.
No original code was executed. This report closes the property-streamer's hidden
callback question; it does not by itself prove preservation through all loading.
## Recovered call chain
| Source VA / raw | Edge / state |
|---|---|
|46E38B/6E38B,46E3AC/6E3AC|Ordinary loader tests/looks up reusable class; otherwise46E3B9 calls factory459CB0. Both paths converge at46E3C1.|
|46E3CB/6E3CB|Load EBX from IAT48D190, whose imported decorated symbol is OMediaStreamOperators pointer extraction of OMediaClassStreamer.|
|46E3FC/6E3FC|Push current game interface and call EBX, stream receiver in ECX.|
|OMT2 10073E00/73E00|Exported extraction saves stream receiver, loads supplied object into ECX, passes stream and dispatches **receiver slot4** at10073E0A. Returns stream; no constructor, default or Init call.|
|EXE4A373C+4,4A3160+4,49F480+4|Jimmy, fire and Goddard receiver read slots all resolve473B30.|
|473B30/73B30|Generic registered-property reader. Reads count, then property name at473B94; dispatches receiver slot400 at473BA3 to lookup descriptor.|
|4A373C+400 →473EB0/73EB0|Lookup scans interface+26C list; descriptor name is at+8, returns matching descriptor pointer at473F8F, or null. No field setter/initialization callback.|
|473BBC..473BC0|Reads serialized wire type and stores it into descriptor+4, selects typed case at473BD0.|
|473BEE..473BF4|String destination is descriptor+48; imported primitive extraction writes there directly.|
|473C43..473C4A|Integer case reads temporary and copies it to descriptor+48.|
|473C5F..473C65|Float case passes descriptor+48 directly to primitive extraction.|
|473CA7..473CAD|32-bit long case passes descriptor+48 to primitive extraction.|
|473E4D..473E75|Read checksum, compare/log, return. There is no end-of-read Init28, PostLoad40C, class-default or control callback.|
The complete840-byte473B30..473E77 reader and239-byte473EB0..473F9E lookup are
hashed by the helper, in addition to individual decisive instruction checks.
The caller of their stream primitives is the stream, not the character; the
reader's only character virtual dispatch is slot400. Missing-property branches
consume data into local temporaries and log; they do not add properties or invoke
character callbacks. Serialized type mutates descriptor metadata, so this is a
trusted-original-data reader contract, not a claim of hardened arbitrary input.
## Registered destinations for the route's20 JIM1 fields
Offsets below are relative to Jimmy's game interface complete+C0. These are the
pointers passed to registration3FC, not live setters inferred from key names.
| GAM name | Interface field | Registration pointer VA / raw |
|---|---|---|
|ObjectTag|3A0 string|470403/70403|
|RotateToDest|A,4 raw bytes via type2|470427/70427|
|ObjectID|404|47043E/7043E|
|PositionX/Y/Z|EC/F0/F4 floats|470458/70458,470472/70472,47048C/7048C|
|RotationX/Y/Z|FC/100/104 floats|4704A6/704A6,4704C0/704C0,4704DA/704DA|
|TaskName|430 string|45883F/5883F|
|Debug|4A4|458859/58859|
|RequiredLevel/ExactLevel/RemoveLevel|578/57C/580|40D3CC/D3CC,40D3E6/D3E6,40D400/D400|
|HasCollision/InitiallyVisible/CanMove|584/588/58C|40D41A/D41A,40D434/D434,40D44E/D44E|
|SecondPass|590|40D468/D468|
|PickupLink|595 string|40D482/D482|
|StartPoint|664 string|43784F/3784F|
Each row's exact LEA, pushed wire type/name literal and original name bytes are
checked. These destinations explain why property loading changes authored
position/rotation/configuration before Init re-applies them to live state. No
route descriptor points at mode interface704/complete7C4, jump728/7E8, live body
velocity1A4, acceleration274 or impulse288. No authored velocity, acceleration,
impulse, hold or fire-time property occurs in the route JIM1 records.
The lab LV1B, VR04 and outside LEV1 JIM1 records all have this exact20-name set.
Their record offsets and original GAM hashes are emitted by the helper. Their
placement values differ and are intentionally applied on each load. Jimmy's
constructor422245 calls422AC0, whose parent registration chain is
422AD7→437830,437846→40D3C0,40D3C3→462340,462356→458820,
458836→4703B0. Reusable-object property extraction does not repeat that constructor
chain.473FA0 registration stores the passed destination pointer in descriptor+48
at473FFE; descriptor layout and reader ownership therefore agree independently.
## What this resolves and what it does not
**Recovered:** Route GAM property extraction is a named, direct-write pass into
authored/configuration fields. It has no hidden character reset/init/default/end
callback. It does not zero or serialize mode, jump or body vectors on these GAMs.
The fire read slot shares the same primitive reader; the inspected JIM1 record
never reaches the fire object's timer through that reader.
**Inference limited by enclosing callbacks:** Runtime scalars not in these records
reach Init unchanged by this extraction pass. They may still be reset by generic
Init, Jimmy PostLoad, RETURN gadget cleanup, control handoff or an intervening tick.
Absence from GAM is not proof that they survive the complete transition. Generic
Init's authored→live vector copies are covered by the primary body investigation;
constructors can initialize authored fields even when GAM has no corresponding key.
Do not carry live velocity merely because the GAM lacks a velocity property.
**Current implementation:** The port parses GAM values and reconstructs scene
objects from snapshots. This report changes no runtime behavior. It supports a
field-specific state container, not blanket copying or rerunning constructors.
**Verification:** Three deterministic Python groups verify both module hashes,
20 decisive instruction anchors,6 vtable targets,20 descriptors, the two full
function bodies and the three exact route property sets. Run
`python3 -m unittest discover -s tests -p test_retained_streamer.py -v` and
`python3 tools/binary/retained_streamer.py ../Original`. Static source-byte/data
checks are separate from original-component execution, port runtime and full
original route comparison; none of the latter are added here.
+98
View File
@@ -0,0 +1,98 @@
# 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. The later retained-field chunk adds
bounded route mode/hold/fire carry, closes property-reader and companion reset
paths, and corrects full VR practice re-enable tails/LV1B restrictions. See
`retained-player-body.md` and the three linked follow-ups; older prefix-only
availability conclusions are superseded. See `player-phase-implementation.md`,
`level-game-lifetime.md` and the current ledger. The exit review below preserves
the evidence/verification boundary at the original checkpoint milestone.
The 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
paused. This is an architecture milestone, not complete original-game fidelity.
## Exit criteria and evidence
| Criterion | Durable result |
|---|---|
| Entire specification/current findings/code reviewed | Full1281-line prompt.MD, both AGENTS files, runtime and focused prior findings reviewed; stale architecture claims reconciled through checkpoint index |
| Preserve playable port and originals | Clean69d0187 local baseline tag and independent Linux/Windows package copies;539 original hashes unchanged at entry and final verification |
| Main loop/input/motion/jump/jetpack/collision/animation | loop-motion.md, input-frame-bridge.md, lab-registry.md; source frame order, two clocks, pointer interfaces, controller/effect ownership, pending collision/morph gaps |
| Scripts/tasks/cutscene/control/progression | script-state-route.md; synchronous objective→records→per-actor callbacks, raw control ownership and route-specific script/task transitions |
| Camera/clipping/audio/UI | camera-audio-ui.md, camera-ray-predicate.md, voice-clock.md; shared viewport, strict snap, first-hit grid order, software audio clock/bank lifecycle, modal/objective timers and modern layout policy |
| Level transitions/persistence/checkpoints/save-load | scene-loader.md and script-state-route.md; deferred ordinary load vs TSK load, selective retention/reuse, placement vs post-task callbacks, distinct pickup capture/RETURN root |
| First route case study | lab STARTEXP/intro→explanation35→pickup50/practice→VR04→RETURN lab→Carl60/dialogue→level1.gam/level1; state/owner/reset boundaries recorded |
| Coverage/assumption audit and concrete plan | coverage.md and implementation-plan.md; source facts, inference, port behavior and verification separated; explicit per-chunk gates rather than waiting for every level |
Three independent investigators used exclusive files; primary reviewed decisive
bytes and integrated reports. All ownership has returned. No new levels, gadgets,
combat or gameplay features were added. No originals were modified/executed in
place. Existing remote configuration was left unused; work stayed local.
## Implemented and verified chunks
**C1:** `TaskStates.Assigning` selects objectives before records change. Entity
callbacks still follow mutation, including repeated and missing-name assignments.
Tests assert old-state observation at objective notification and new-state
observation afterward. This corrects original45FB5B/45FB7F/45FBD9 ordering.
**C2:** Carl's LV1B override now belongs to his director task callback: capture
SCENE, apply generic activation, then marker/state/visibility override before the
next actor. Removed the interactions-layer post-batch fix and redundant level-code
argument. Tests cover callback observation, source activation boundaries and
existing lab/Carl/RETURN routes. Other class overrides remain unported.
`artifacts/re-checkpoint/integration.log`: full `scripts/test.sh` passed, including
49 Python checks at its start, all managed groups, GPU story/practice/return/Carl/
objective/jetpack/animation replays, SDL dummy audio and539 original hashes.
All GPU runs report zero Vulkan validation errors. Additional follow-up byte tests
were added afterward; final Python discovery passes62 tests, recorded separately
in `artifacts/re-checkpoint/python-final.log`. Build succeeds without warnings.
These are port/static checks; no new native Windows runtime or original whole-game
runtime verification is claimed. Physical audio and original cadence remain open.
Self-contained Linux/Windows packages were rebuilt by `scripts/package.sh` from
clean531883a; both BUILD-INFO records identify that source and source_dirty=no.
The preserved baseline DLL hash remains distinct from the new binary. Linux
release launch from `/tmp` passes the60-frame Carl cutscene held-input lock check
(`linux-package-carl.log`); validation layers were unavailable in that package
invocation, unlike the enabled full integration runs. Subsequent changes only
refine loader evidence and this validation record, not runtime code.
Final loader consistency review verifies that the lab predicate-zero writer is
in class-default initialization44D3D0, reached from constructor44F3B3 through
4749A0→completeB4→44F4B0. It is not inside base constructor44D2B0. Five targeted
loader regressions pass after adding that provenance. This strengthens the
old-game lifetime question rather than silently assuming pointer overwrite deletes it.
## Plan continuation and exact next gates
C3 investigation recovered fresh game input→Jimmy→fire order after physics. C5
recovered source static obstruction, C6 corrected the proposed audio status model,
and C7 recovered the ordinary loader. These are executed investigation chunks,
not implemented scheduler/camera/audio/loader replacements.
1. Resolve **old level-game registry removal/eligibility**, since constructor
overwrite of509948 is not destruction and its initialization can set the
teardown predicate0. Trace retained Jimmy/fire/shadow/Goddard field resets
through property read and per-object28/40C. Then construct the route's callback
trace and split pending physics/controller/effect/sync phases. Do not impose
fresh insertion order on retained objects.
2. Independently implement/test the static camera query using source shape/polygon
IDs, registration filters, sparse cells and FIFO wall-first reduction. Then
integrate shared viewport handoff and follow state, preserving strict>1000 snap.
Modern nearest-sphere clipping cannot stand in for that source algorithm.
3. Recover sound duration conversion and allocation/play-failure cases, model
software channel duration/repeat/stop/clock pause plus bank ownership, then
change CAM/MCA completion. SDL queued bytes are transport state, not source time.
4. Continue collision response/root, morph end events and UI mode/layout recovery
under the remaining plan gates. Original runtime comparison is still required
before claiming source fidelity, but does not block directly evidenced chunks.
Use implementation-plan.md as the execution ledger. Continue locally and
autonomously; user confirmation is not a gate for the authorized investigations
or directly evidenced corrections.
+207
View File
@@ -0,0 +1,207 @@
# Ordinary scene loader and editor reset boundary
Read-only C7 follow-up, 2026-10-25. Original `Neutron.exe` SHA-256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Every VA in this report is in that module at preferred base400000. The inspected
sites map to file offset **VA−400000**; `checkpoint_scene_loader.py` independently
maps PE sections and emits each VA/raw offset/bytes/vtable dependency. Static
facts do not constitute original runtime verification. No originals were executed
or modified; modern gameplay was not changed for this investigation.
## Main result
The ordinary scene request is owned by the long-lived **CEditor** application
object at global509980, not by the current level game object509948 or the queued
TSK reader. Its deferred loader selectively tears down scene objects, loads GAM
records, then invokes per-object initialization and actual PostLoad. Jimmy and
Goddard constructors explicitly select survival through that teardown predicate
and mark themselves reusable. The enclosing retention/reuse contract is recovered;
class initialization and PostLoad still reset fields independently.
The previously unresolved “reset flag”50988A is **keyboard R** in the input array,
and its acquired-item reset consumer is **Jimmy's editor update**, not ordinary
loading. Do not turn it into a gameplay load/reset policy.
## Receiver, request and consumption chain
| Link / state | Source fact / offset |
|---|---|
|Application identity|Bootstrap46A641 calls constructor46B160; constructor46B200 installs complete vtable4D5EA0 and46B237 stores this in509980. Literal4F57D8 is`CEditor()`. Bootstrap46A654 also stores the returned pointer.|
|Player request|43B7F1 dispatches slot100 on509980 after staging strings and departure root.4D5EA0+100→46DF70.|
|Deferred state|46DF76 writes byte app+74C=1;46DF7D selects filename buffer+74D and copies the argument. This is one pending flag/name, not a demonstrated multi-request queue.|
|Application update|4D5EA0+C4→46BEC0; its final46C052 checks+74C and46C05E invokes104→46DFF0. Earlier update logic includes an alternate signed frame countdown+7FA that can also set+74C at46BEDF.|
|Consume request|46DFF0 checks+74C again and performs teardown;46E152 dispatches app+FC→46E170 with stored filename and−1;46E158 clears+74C after return.|
|Load completion|46E170 reads GAM, creates/reuses records;46E4FF dispatches app128→46E570. This closes the formerly missing source edge to actual placement PostLoad.|
|Placement pass|46E570 registry traversal calls each object's28 at46E5C3, then40C at46E61A; Jimmy4A373C+40C→423610. At traversal end46E681 invokes app10C and46E694 resets the performance timer47E470.|
App10C resolves46E710. Its inspected body traverses registry and logs object
tag/class/id; do not label it a cleanup/free operation solely because callers
surround it with “gcu” logs. App+7A4 receives the currently loading filename at
46E19F; pending+74D and current+7A4 are separate strings.
## Teardown phases and survival predicate
46DFF0 first calls app10C and479000, then makes three registry50999C passes.
Each pass calls object slot200, which for Jimmy/Carl/lab game interfaces resolves
4719B0: return byte **interface+139**.
1. If predicate nonzero, call object20 at46E054 (logs “Uniniting”).
2. If predicate nonzero, call object34 at46E091 (same log).
3. If predicate nonzero, set interface+6=1 at46E0CA (“Delme”).
46E0D9 calls473710, which repeatedly finds a marked interface+6 object and calls
its slot0 with argument1, restarting traversal after deletion. Thus this is
selective teardown; the “Deleted all objects” log is not proof of universal
destruction.4685F0 and app10C run next;46E117 calls46B000, which traverses a
database registry and closes referenced databases. Exact meaning of479000 and
4685F0 is outside this bounded audit and remains unnamed here.
**Survival provenance.** Generic setter470F40 writes supplied byte tointerface+11
then calls slot204; Jimmy/Carl204 resolves4719C0, storinginterface+139. Generic
constructor46FDB3..B7 passes1; Jimmy constructor4226B5..BF passes zero instead,
and Goddard41C99B..99E does likewise. Jimmy and Goddard therefore start with the
non-destructible predicate. This explains why the departure root/RETURN flags
can be fields on the character object across a scene change. It does not prove
every character field remains unchanged: initialization, property loading,
gadget cleanup and PostLoad can reset fields independently.
The lab game object's class-default initializer sets predicate0 at44D456/44D472;
this is **not inside the constructor44D2B0 body** (which returns44D350).
Normal factory construction does nevertheless reach it: LV1B constructor44F300
installs derived vtables44F36A/44F37C, passes its+8C interface to4749A0 at44F3B3,
and4749BE..4749CA converts back to complete and dispatches virtualB4. Complete
vtable4C3CD0+B4 resolves44F4B0, which calls base class-default initializer44D3D0
at44F4D5. Therefore this writer is constructor-reachable through an explicit
virtual defaults bridge, not inferred from proximity or an editor-only caller.
An object's
retention and the current-level global509948 are distinct: GAM loading assigns
509948 to the destination's game object at46E360 after factory construction.
Further class-specific lifecycle flags or later predicate changes require their
own evidence; do not generalize the constructor default into a full object map.
**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
constructs a new destination game. A bounded inspection of46E170 through factory
46E335 found prefix46E26C→4766E0, whose literal is`UnInitCaptions()` and whose
registry is5099FC;46E271→479000 clears physics records rooted509B04. Neither
inspected prefix identifies an old509948 game destructor.
The lab constructor chain44F300→44F358/44D2B0→44D306/4745A0 was also inspected.
4745A0 constructs/links a new OMT element (IAT48D284 is OMediaElement constructor;
48D320 is OMediaElement::link), registers its game interface, clears control via
475A40(0) at474683, then overwrites global509948 at474688. No explicit old-game
destructor/removal was established in this inspected chain. **Overwriting the
current-game pointer does not remove an old game from registry50999C.**
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
46E170 builds`gam\\`+filename, opens a bounded original stream, reads FourCC, and
uses class factory459CB0 for the game. Factory-returned game interface is shifted
by−8C to its complete object and stored as current game509948. It then reads
entity count and serialized objects. For each class/ObjectID it asks app11C
(46E45A), resolving46E6A0: scan registry for matchinginterface+404 and require
interface byte+9 nonzero. App110 (46E46E) resolves46E6E0: return the matching
interface. Otherwise46E49A calls factory459CB0. The object's property stream is
read at46E3FD through IAT48D190 before proceeding to the next record.
**Coordinated constructor proof.** The loop/registry investigator independently
recovered Jimmy42275A and Goddard41C9C0 writing complete+C9=1, which is game
interface+9. Both exact sequences are now guarded by this report's helper too.
Together with their zero destruction predicate, this establishes that Jimmy and
Goddard are retained and can be reused by class code. Factory3JIM branch45B1C1
allocates and calls constructor422160 when no reusable object qualifies; it is
not itself a singleton lookup. Other surviving classes need their own+9 proof.
See [lab-registry.md](lab-registry.md) for insertion order and constructor details.
After successful stream close,46E4FF→app12846E570 processes the resulting live
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 logical Euler.Y (yaw) into+61C, not body velocity. Jimmy40C423610 applies:
1. Matching source STRT root42399D and rotation4239E6.
2. Existing companion source root423A36.
3. Pending RETURN flag test423A90 and clear423A9E.
4. Saved departure root423ABF; identical companion root423B1E.
5. Game control assignment423B3D, followed by viewport camera fields423B43.
STRT's own40C callback and trigger-suppression flag consumption run at its
position in that same registry pass. The exact registry ordering for the
lab/practice route still needs a construction trace. Existing recovered placement
and suppression behavior stays valid; its enclosing temporal interactions must
be tested when implementing retention.
## Acquired reset belongs to editor input
Key handlers46A360/380 read virtual-key byte and set/clear509838[key] at46A370/
46A390.50988A−509838=52hex, ASCII/Windows virtual key **R**. Therefore4235D8
reads R, not a scene-loader-owned flag. If pressed,4235E2 sets count1068hex=4200,
4235E9 chooses4F8438 and4235EE clears4200 integers; it then iterates29 group2
inventory entries through403910.
Jimmy interface slot3C8→4235B0. Wrapper470280 chooses3C8 at4702B5 only when
app509980 exists and byteapp+8C is nonzero; otherwise4702C5 chooses normal3C4
Jimmy424600. This matches the current source naming of editor versus normal
update. The reset routine also handles a saved sound/effect handle before the
key test. It is not present as an unconditional phase in46DFF0/46E170.
## Route persistence versus TSK load
| State / event | Ordinary lab→VR04→lab→outside | TSK reader4603F0 |
|---|---|---|
|Request owner|CEditor app+74C/+74D, consumed in app update|Globals4FC67C/4FC604, consumed by460EA0; distinct request path|
|Character root/RETURN fields|Character stores+9A8 and transient954/9A5; predicate selects retention, PostLoad consumes flags|Reader restores three departure floats; flags are absent from file|
|GAM properties/actors|Selective teardown, class factory/reuse, per-object28→40C|Does not itself execute this ordinary scene teardown/GAM loader|
|Task assignment|Class initialization/task callbacks depend on registry and source task records|Calls45F990, then duplicate matching424; positive task-count path finally invokes all-object420; distinct from40C|
|Acquired items|No unconditional4200 reset found in this chain; R reset is editor-only|Explicit4200 serialized integers read into globaltable|
|Score, energy, inventory, objective|Global ownership; no blanket zeroing in inspected loader. Jimmy construction itself sets energy20 at4226E5, making exact reuse significant.|Reader restores explicit fields/inventory/task data|
|Clocks/render/audio|PostLoad resets performance timer; database closes and render attachment phases exist. Exact per-bank/handle ownership pending.|Reader has its own stream/object callbacks; not a complete scene lifecycle|
**Current implementation at baseline69d0187.** Program carries OriginalSave
snapshots and explicit RETURN root/identity while reconstructing scene actors,
physics and audio, with application-owned RenderSession kept alive. This is a
useful playable testing harness; it is not the recovered retained-object loader.
Keep its presentation ownership as the user-authorized modern policy. Do not
force original editor R semantics into the game's current R reset control.
## Bounded continuation gate
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.
2. Build an event trace covering request, three teardown passes, destructor,
property load, per-object28/40C, STRT suppression and first input/physics tick.
Use source target/vtable evidence; test retained versus recreated objects.
3. Map per-level class constructors/initializers' score/energy/inventory writes
before adopting global persistence beyond the demonstrated route.
4. Contrast ordinary load trace against queued TSK load and its duplicate424/420
callbacks. Preserve full wire data and do not silently serialize transient
RETURN flags or reinterpret StoredVector as immediate position.
The loader retention contract can now support a bounded state-container design;
transferring every arbitrary field unchanged would still be unsupported. The
source chain and editor-reset correction replace an unbounded “loader unknown”
task with these concrete tests.
Validation: five Python tests pass, covering the original hash,42 exact byte
sites,15 virtual targets, object factory/destruction/timer dependencies and R key
identity. Run `python3 -m unittest discover -s tests -p
test_checkpoint_scene_loader.py -v`. Helper JSON is reproducible with
`python3 tools/binary/checkpoint_scene_loader.py ../Original`. These are static
evidence checks, not original or port runtime verification.
+206
View File
@@ -0,0 +1,206 @@
# Script, task and transition ownership checkpoint
Read-only original investigation, 2026-10-25. Baseline audited:
`69d0187a2178deab1edff961d5126dad1cce3a05`. Preserve that playable baseline.
This checkpoint uses **fact** for original bytes/GAM data, **inference** for their
interpretation, **implementation** for modern source, and **runtime** only for an
executed game. No original-game runtime capture was obtained for this report.
## Source identity and reproducible evidence
| Original file | SHA-256 |
|---|---|
|`Neutron.exe`|`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`|
|`gam/level1b.gam`|`316fff40db565c2add5b07cbccdef640ddb67c64d6625fea1429ce2a0542a234`|
|`gam/VR04.gam`|`e34f6b6aa11ba1137dc4410148565b3c29db9d02c5fcc1f145017dafd2f3ca04`|
All executable addresses below are preferred-base Neutron.exe VAs. The inspected
sites have raw file offset **VA−0x400000**, independently checked using PE section
mapping, not assumed by the helper. GAM offsets are raw offsets in the named file.
`tools/binary/checkpoint_script_state.py ../Original` emits hashes, individual
VA/offset/byte records, resolved direct calls/vtable targets, and exact route GAM
fields. It reads originals and writes only stdout. The corresponding Python test
guards the decisive evidence. Cached `artifacts/binary/neutron.asm` was used for
cross-reference discovery; decisive sites were re-disassembled from the original.
## New inconsistency audit: task ordering
**Fact.** `45F990` does more than set a task value. Its phases are:
1. For matching SCENE milestones, call objective helper `406F50` at
**45FB5B / file5FB5B**, before task record mutation.
2. Traverse task list `4FC5FC`; case-insensitive match; store supplied state at
record+64 at **45FB7F / file5FB7F**. It updates existing records, including
repeated values; it does not insert unknown names.
3. Traverse game-object registry `50999C`; compare interface+430 TaskName;
matching objects receive interface slot424 at **45FBD9 / file5FBD9**.
The objective callback can therefore observe the **old task state**. Per-object
task callbacks observe the **new task state**. The call is synchronous: each
derived callback finishes before moving to the next registry object. This is an
ownership/order contract, not merely an eventual-state assertion.
**Baseline implementation mismatch.** `TaskStates.SetExisting` mutated records,
then invoked one `Assigned` event. `SceneDirector` was the first subscriber and
updated a batch of generic actors; `SceneInteractions` subscribed afterward and
selected the objective and applied all Carl overrides. Both objective timing and
derived-callback boundaries differed from the original. This justifies C1/C2 in
[implementation-plan.md](implementation-plan.md). The primary has implemented a
separate pre-assignment objective boundary during this checkpoint; integration
results belong to the primary ledger, not this static evidence report.
**Carl callback detail (new audit).** Interface vtable495364+424 points to413F30.
At **413F3D / file13F3D** it queries current SCENE via45FEA0, saves it in EBX at
413F45, then at **413F4E / file13F4E** calls generic40E340 with the supplied
callback value. Only after that base callback returns does it inspect level code
and run the LV1B override414068..414118. Thus its contract is **capture SCENE →
base activation → derived action**, inside one object callback. The override
uses the captured SCENE value, not a later reread. No reentrant task mutation was
observed in this investigation; this does not prove such mutation impossible.
For LV1B, scene outside0..60 disables Carl; >30 resolves CARLESC3, sets AIstate6
at4140AA and copies marker root via slot314 at4140E0; <60 activates him, exactly60
leaves base activation unchanged. Repeated assignments can therefore reposition
him. Applying this as a post-batch correction masks class behavior and can expose
partially updated state to actor observers.
## State owners, structures and lifetimes
Jimmy has a complete C++ object and a game interface at complete+C0. Mixing those
bases produced earlier apparent contradictions. Constructor4221E8/42220B installs
complete vtable4A3BDC and game-interface vtable4A373C. Player base constructor
437280 initializes inherited transition state. Read/write sites below retain the
base used by the actual instruction.
| Owner / field | Writes, consumers and lifetime |
|---|---|
|Global5099E4, controlled game interface|Game setter475A40; script/control handoffs replace it. Input, UI and player logic consult it. Null is a control state, not evidence that all world updates stop. Not a TSK field.|
|Task list4FC5FC; record name+0/state+64|45F990 mutates/broadcasts synchronously; trigger, actor and LOAD queries consume. Serialized by TSK.|
|Global4F8194 objective selector|406F50 updates selector and transient objective flags before SCENE mutation. TSK serializes selector; flags/timer are separate runtime state.|
|Jimmy complete+724, +774|Transition/start strings, written by43B5A0; writer460057..6F persists both. +774's wider role remains unresolved.|
|Jimmy complete+88C/+8F0|RETURN level/start strings, written by43B5A0, consumed by LOAD RETURN and persisted in TSK.|
|Jimmy complete+955|Staged level-name string, copied43B772..78C; not one of the four TSK strings. Dependency on game loader pending further recovery.|
|Jimmy complete+9A8..9B7|16-byte departure root captured by43B5A0 unless+9A5. First three floats serialize as TSK StoredVector. No yaw/velocity/camera state in this copy.|
|Jimmy complete+954|RETURN sets it; matching STRT consumes it to suppress the initial trigger once. Separate from root restoration; not serialized.|
|Jimmy complete+9A5|RETURN sets it; staging preserves departure root; Jimmy PostLoad consumes it and restores root. Not serialized.|
|Jimmy complete+1E38..1E47/+1E48|Independent pickup capture root/level.42AF00 writes;42AF50 writes plus attached effect callback. Not the TSK departure root. Read consumer unresolved.|
|Globals4FC604 filename/4FC67C pending|460E70 queues TSK load;460EA0 update consumes and clears. One pending filename, not a proven request queue.|
|Acquired table4F8438;19 inventory entries;score4F83C0;energy4F83D4|Global/save-owned data. Pickup/inventory/score actions mutate; TSK persists. Complete state-reset policy for ordinary level load is still open.|
**Vtable provenance.**4A3BDC+168→43B5A0, +1E8→42AF00,
+1EC→42AF50. Carl495364+424→413F30. LOAD4D025C+424→458880 only stores taskstate;
it must not inherit animated activation merely because its base has TaskName.
## First end-to-end source case study
| Route event | Recovered fact and state boundary |
|---|---|
|New game/lab entry|NewGame.tsk has SCENE30. LV1B STRT STARTEXP **GAM5B0E**, yaw155, StartTrigger LABEXP. STRT4426A7 validates the deferred target and clears controlled entity before dispatch.|
|Intro completion|AI/CAM/MCA chain recovered in lab-progression.md; DEFAULT447CF0 restores Jimmy/inventory, clears skip and conditionally restarts music. It does not simply assign SCENE35/60. Speech-end handles drive CAM/MCA update; port sample-duration timing remains an approximation.|
|Explanation|Special AI40CB43..6B maps SCENE30/31→35. Task setter selects objective1 before task records35 and actor callbacks.|
|Jetpack pickup|LV1B3PIC **GAM1799**, internal tagshrinkray, index301,+50,radius125. Generic435CE0 marks acquired/hides; special4365D0 only at SCENE35 calls Jimmy+1E8→42AF00 first; then SCENE50, group0/item3=1,406F90(0) practice prompt, gadget3. Positive score occurs after special hook. Pickup outside35 still has generic acquisition/+50 without those special side effects.|
|Practice No|UI modal resumes current level. It does not stage a departure or overwrite the RETURN root. Modern practice modal behavior is covered separately in camera/audio/UI checkpoint.|
|Practice Yes|4046AF stages VR04/PHONEBOOTH with current level/current STRT as RETURN context via complete+168→43B5A0.43B78E sees no pending RETURN, captures the live root into+9A8, then schedules game slot100 at43B7F1. Capture happens on acceptance, not necessarily on pickup.|
|Tutorial entry|VR04 STRT PHONEBOOTH **GAM48C**, yaw290, trigger sr1. Persistent task/inventory/acquired/score save-like state is distinct from new scene actors and playback handles. Source exact loader teardown order remains unresolved.|
|Tutorial exit|Two VR04 LOAD RETURN gates **GAMB0D7/B4C5**, radii400/350. RETURN457FF7 cleans gadget, sets+954 at458014 and+9A5 at458028; resolves saved level/start and dispatches transition168 at45815C. Staging must preserve lab departure root instead of capturing tutorial exit.|
|Lab RETURN|Jimmy423A90..9E consumes pending+9A5; root setter423ABF receives savedXYZ. Companion423AE3..423B1E receives identical saved root, no offset/yaw. Requested STRT supplies yaw155. STRT4427F2 consumes+954 and suppresses LABEXP entirely; fast-forwarding LABEXP would wrongly execute its actor/task actions.|
|Carl approach|Contact target match40A44C; AIstate6 contact40A676..68D sets0. Friend update41B950 invokes generic AI then41B972..988 dispatches talk when resultingstate0. General sensing/facing remains incomplete in port.|
|Carl conversation|Talk41BB20 chooses first existing matching task/wildcard target, retains it, derived callback413E50 first awards+100 and SCENE50→60, then41B7D3 dispatches selected neutron1a. Score150/SCENE60 precede dialogue. neutron1a **GAME0B** has5 shots, PlayerControlledJIM1 as completion target and NextTriggercarlwalk. Activation43159E clears control; completion4311F0 restores target.|
|Outside exit|LABTONEIGH **GAMA43** requiresSCENE≥60, no exact gate, radius200; destination **level1.gam / level1**. Earlier lab-progression.md's `startlevel1` is a documentation error: the exact GAM value is `level1`. Runtime source-field lookup already uses this value. LOAD contact's required-task gate457F32..5F is separate from generic activation.|
The source route does not require interpreting pickup42AF00 as respawn. It also
does not justify replacing ordinary level load with TSK file load: those are
distinct entry points with different transient flags.
## Save/load boundary: new call and callback audit
**Fact.** Writer45FEE0 locatesJIM1 via474070 at460043; the lookup returns game
interface. Its+8E8/+8EC/+8F0 writes46008B..B0 are complete+9A8/+9AC/+9B0.
Reader460A79 explicitly subtractsC0 from controlled interface, then460BA3/BAD/BBA
stores the same complete-object vector. This proves TSK StoredVector is departure
state; it does not serialize the separate pickup capture or pending954/9A5.
**New queue provenance.**460E70 sets pending4FC67C at**460E7B / file60E7B** and
copies requested name to4FC604. Caller sites include404B54 (NewGame),406E80,
40D08E,4247F0,424BCF,42B1B9..42B21B (slot-name dispatch).460EA0 first executes
its inherited/update logic473240, then460EE1 tests pending,460EF0 calls4603F0
with filename,460EF8 clears pending. These are deferred TSK load calls; menu
request ownership and engine update scheduling require the loop investigation.
**New double-callback fact.** Each valid saved task is sent through45F990 at
**460CE2 / file60CE2**, including its objective and ordinary actor callbacks.
The reader then makes another registry traversal and calls matching non-none
TaskName slot424 again at**460D2E / file60D2E**. Thus duplicate per-task callback
execution is present in the supplied binary. A final all-object slot420 traversal
appears at**460D87 / file60D87**, after positive-count task loading; the no-task
branch460C65 jumps to cleanup460D98 and skips that traversal.
Do **not** call slot420 Jimmy placement PostLoad: vtable4A373C+420 is472970,
the log helper; Carl495364+420 is413EB0. The placement/root code423A90 belongs
to a different initialization path. Exact function names for slot420 remain
unproven; use “post-task slot420” until class-specific behavior is mapped.
**Actual placement PostLoad provenance (new audit).** Jimmy game vtable
4A373C+40C points to423610; its first log literal4EF3B4 explicitly says
`Calling PostLoad for C3DJimmy()`. Registry traversal46E570 invokes each object's
slot28 at46E5C3, conditionally handles an attached/render object, then invokes
slot40C at **46E61A / file6E61A**, before moving to the next registry entry.
Within Jimmy PostLoad, matching STRT lookup42385B..423885 precedes authored root
application42399D, authored rotation4239E6, available companion source-root
application423A36, RETURN test423A90/clear423A9E, saved-root application423ABF,
same-root companion application423B1E, and game control assignment423B3D. Camera
viewport setup follows423B43. This establishes local call order, not the full
caller chain from game slot100 to46E570; the latter remains C7 work.
Separate lifecycle callback4235B0 (Jimmy game slot3C8) conditionally clears4200
acquired integers at4235E9..5EE and calls group2 inventory helper for29 entries
when global50988A is set. Follow-up `scene-loader.md` proves this is R in the
virtual-key table509838, consumed only in editor3C8 mode. It is not an ordinary
loader-reset flag. Ordinary selective retention and per-field PostLoad behavior
must be traced separately before generalizing item reset/persistence.
**Baseline implementation.** `OriginalSave` parses/encodes all12 supplied TSKs;
`TaskStates` and fresh `SceneDirector` construction restore modern state.
CLI `--write-save` serializes existing StoredVector, not necessarily current
player root; this matches the recovered departure-field identity, but is not a
complete original save UI. `Program.SceneContinuation` carries root and explicit
Returning; `SceneInteractions.Snapshot` carries arrays/task/inventory/score/
energy/return strings. New scene actors/audio are reconstructed. The port does
not reproduce the queued TSK reader, duplicate broadcasts or all-object420 path.
These should be investigated before implementing full source resume behavior.
## Independent checkpoint consumer audit
42AF00 captures current game level from509948+490 into+1E48 and root getter310
into+1E38.42AF50 repeats this then attached+ A18 object's slot4B8 effect call.
Constructor4221E2 initializes checkpoint vector fourth component+1E44 to1.
An explicit operand search in the EXE disassembly for complete+1E38/+1E3C/
+1E40/+1E44/+1E48 and interface-relative+1D78/+1D7C/+1D80/+1D84/+1D88 found
capture/constructor writes, but no demonstrated read consumer.42B2A3's subtract
1E48 is a virtual-base adjustment thunk, not a checkpoint read. This bounded
search is negative evidence only: aliases, indexed/member pointers and other
modules can hide consumers. No death/respawn/reset policy is established.
## Coverage, unresolved questions and next gates
| ID | Remaining question / evidence gate | Bounded action |
|---|---|---|
|S1|Full registry order and reentrant mutations unknown; capture-before-base matters for Carl.|C2 preserve per-actor query/base/derived boundary and test notification sees final Carl state. Do not add invented class callbacks.|
|S2|What owns ordinary game slot100 load request and which globals/actors persist?|C7 trace43B7F1 receiver vtable, staged+955 string and loader update through scene construction/destruction. Contrast with460E70 TSK path.|
|S3|Why does TSK reader duplicate callbacks; what does420 do per class?|Build source callback trace for Carl/pickup/LOAD; compare same-value assignment/load before adopting duplicates. Preserve exact no-task branch distinction.|
|S4|Independent pickup root/level consumers unknown.|Trace virtual-base/member aliases and constructor RTTI before labeling respawn. No gameplay change justified now.|
|S5|RETURN flag survival and matching STRT consumption through all loader paths.|Trace actual ordinary scene loader and PostLoad order; test initial trigger suppression independently from placement and TSK resume.|
|S6|Exact script/physics/contact scheduling and sound-handle completion incomplete.|C3/C6 phase and voice trace; avoid treating null control as whole-world pause or file duration as source end event.|
|S7|Persistent energy/inventory/29 counters reset policy beyond route unclear.|Recover load/constructor globals writes; preserve unknown wire values; no normalization or minimum task assumptions.|
Recovered route contracts and these explicit boundaries are sufficient for C1/C2,
and for a concrete C7 investigation. Full source resume, generic scripts and
other levels remain incomplete. Current route managed/headless tests and user
Windows reachability provide port evidence only; they do not prove the original
end-to-end behavior or original runtime timing.
Validation for this report: `python3 -m unittest discover -s tests -p
test_checkpoint_script_state.py -v`; five tests assert binary identity,25 byte
sites,8 vtable dependencies, task/Carl ordering, deferred load call, distinct
source destinations and bounded helper rejection. Source files only were read;
no original executable was run.
+61
View File
@@ -0,0 +1,61 @@
# C6 follow-up: completion is software duration plus repeat
Primary static recovery,2026-10-25; same hashed EXE/DLL identities as the core
camera/audio/UI report. `checkpoint_voice_clock.py` verifies12 DLL instruction
anchors,3 vtable targets and2 constants, emitting PE-mapped physical file offsets.
No original executable was run. This refines the earlier unresolved “voice status”
interpretation; it does not establish transport output or native timing fidelity.
## Recovered call and field provenance
EXE47D890's channel slot14 is **not** a backend hardware-playing query. Both
DirectSound channel vtable10115420+14 (file115434) and WinSound channel
10116B3C+14 (file116B50), as well as base1011629C+14 (file1162B0), point to
DLL10071E40 (file71E40), exported `OMediaSoundChannel::get_playing_sound_info`.
Constructors1003AF58 and100F87DA install the respective derived tables.
10071E40 returns elapsed time through its first unsigned output and stored
duration+1C through the second. If duration is zero both outputs become zero.
When timer running (2C/2D clear), elapsed is engine millisecond clock100F8CF0
plus channel+28 minus channel+20; otherwise it uses frozen+24. At10071E7F..83
only **elapsed > duration** expires and clears duration+1C. Equality still reports
nonzero duration. This is neither a DirectSound GetStatus result nor a speaker
audibility check. The backend may query GetStatus in queue pumping, a different
consumer from this slot14 predicate.
After successful play, DX1003B46E..482 and Win100F891A..92E compute channel+1C
from sound+44 using `durationSeconds*1000 + .5` then integer conversion helper
10104E04. Constants10115450=1000 and10115448=.5. Exact conversion-mode semantics
of10104E04 and sound+44's decoder provenance still need a bounded follow-up;
do not assert PCM sample duration is always its bit-identical source.
Byte+30 is copied from the final boolean play argument: DX1003B32B reads it,
1003B338..343 turns it into the buffer's play flags,1003B46B stores it. Win
100F8893 selects flags2017/201F and100F8917 stores it. This is the **repeat/loop
flag**, not a pending-start flag. DX stop1003B657 clears+30 and+1C; Win stop
100F898F/100F8996 does the same. DX queue pump1003B691 skips its ordinary queued
advance when+30 is set. The interpretation is supported by matching play/stop/
queue branches in both backends; no original playback was observed.
Therefore EXE47D890's final predicate is structurally:
```text
valid engine + in-range handle + existing channel
AND (software duration returned by slot14 != 0 OR channel repeat flag != 0)
```
Calling this “hardware voice status” would be an overclaim. The explicit bank,
handle stop/release, failed play and engine timer pause still matter. The baseline
port's prepared-file-duration clock is closer to the ordinary one-shot source
clock than an SDL queue-empty predicate would be, but differs in integer boundary,
source duration identity, pause/clock ownership, invalid handles and dispatch order.
## Implementation consequence and remaining gate
Do not replace CAM/MCA completion with SDL queued bytes merely because source
polls a handle. First model source channel state (duration milliseconds, elapsed,
repeat, stop/invalid handle and engine clock pause), recover47D060 allocation/
play failure and source sound+44 derivation, then connect director completion to
that state. Independent SDL transport can remain the output mechanism. Current
duration/leftover-dt director behavior stays explicitly approximate until that
contract is tested. This bounded correction changes the C6 plan, not gameplay yet.
+76 -1
View File
@@ -3,6 +3,71 @@
Compilation, native runtime, original behavior and full feature completion are Compilation, native runtime, original behavior and full feature completion are
separate evidence categories. **The game is not fully reconstructed/playable yet.** separate evidence categories. **The game is not fully reconstructed/playable yet.**
Retained-state continuation (2026-10-26):14 new source-evidence tests and22
movement groups cover named property loading, cleanup/Init/PostLoad/control
boundaries and bounded route scalar carry. Corrected full tutorial/lab gadget
availability and TSK/unknown-state tests pass. An isolated Wine32 component probe
executes copied original vector accessors and43A750 with synthetic fixture vtables
and invalid sound handle; source targets are byte-guarded. It confirms body-field
writes and unrelated sentinel preservation, not full loader/gameplay or native
Windows behavior. Evidence: artifacts/retained-lifecycle/original-probe/wine.log.
Integration:84 Python checks, all managed groups and26 GPU render checks pass
with zero enabled-validation errors. Final nondefault mode1/hold.625/fire6.125
ordinary-load replay independently checks jump/body resets on tutorial and RETURN;
all539 original hashes unchanged. A fixed200ms effects-smoke baseline failed under
load; paused stream construction plus a bounded consumption poll removes that
sampling assumption (the initial failure did not record its queue baseline). All four SDL dummy audio checks pass in audio-final.log; final route is in
route-final.log. No new native Windows runtime verification.
Both self-contained packages rebuilt from clean9ad5a8e, source_dirty=no. Linux
standalone launch from /tmp passes nondefault lab→VR04→lab scalar/body/RETURN
assertions, with the same presentation instance retained. That release invocation
has validation unavailable; source GPU enabled-validation evidence remains separate.
Logs: artifacts/retained-lifecycle/package.log and package-route.log.
Debug expansion (2026-10-25): full scripts/test.sh passes, with70 Python checks,
21 movement groups, debug page/overlay groups, real SDL dummy pause/mute timing,
remaining managed/GPU routes and539 unchanged original hashes. Native Linux
GTX1070 at1920x1080 passes F1/Tab/F3, flight during a source cutscene, input capture,
camera/audio controls, checkpoint save/load and same-window rebuild. Enabled Vulkan
validation reports zero errors. Headless Player1920x1080 and Systems2560x1080
screenshots fit; see artifacts/debug-expansion/. SDL_SetAudioStreamGain is present
in the packaged Windows SDL3 DLL export table. Cross-build/export evidence does
not add native Windows runtime or original-game behavior verification.
Both platform packages rebuilt from clean d783898, source_dirty=no. Standalone
Linux package launched from /tmp with Player page/noclip1920x1080 passes on
llvmpipe; that invocation lacks validation layers. Evidence: package.log and
package-smoke.log under artifacts/debug-expansion/.
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.
Both self-contained packages now identify clean09cf117. Linux release smoke from
`/tmp` passes practice/RETURN (including input order and gadget availability) and
outside load; see linux-package-return.log and linux-package-outside.log under
artifacts/implementation/. Those release invocations have validation unavailable;
the enabled-validation evidence is the full integration run above. Windows is
cross-published, with no additional native Windows runtime claim.
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
errors. Final Python discovery passes62 tests including the additional source
evidence follow-ups. All539 original hashes remain unchanged. These checks do not
add native Windows or original whole-game runtime verification; earlier Windows
user reports remain limited to their tested builds and route.
Self-contained Linux/Windows packages rebuilt from clean531883a. The Linux release
package passes the60-frame Carl held-input/control-lock smoke from `/tmp`;
validation layers were unavailable for that invocation. Current Windows release
is cross-published, not newly native-runtime verified. Later loader-provenance
edits affect evidence/tests only; runtime code is unchanged from that package.
| Feature | Implemented / tested | Evidence and limits | | Feature | Implemented / tested | Evidence and limits |
|---|---|---| |---|---|---|
| Original preservation | Verified after extraction/runtime tests | All539 original SHA-256 hashes unchanged | | Original preservation | Verified after extraction/runtime tests | All539 original SHA-256 hashes unchanged |
@@ -23,6 +88,8 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| Null-material visibility | Binary rule implemented/tested | Original DX renderer skips null pointers; proxy geometry retained | | Null-material visibility | Binary rule implemented/tested | Original DX renderer skips null pointers; proxy geometry retained |
| SDL3 presentation/input | Linux Xvfb + GTX1070 | Six frames; injected keyboard event received | | SDL3 presentation/input | Linux Xvfb + GTX1070 | Six frames; injected keyboard event received |
| Swapchain resize | Linux tested | 960x720 ->800x600, zero validation errors | | Swapchain resize | Linux tested | 960x720 ->800x600, zero validation errors |
| Persistent level presentation | Native GTX1070 six-load pass |One window/renderer; stable IDs/core resources, bounds/focus/fullscreen; invalid load retains rendering; zero cumulative Vulkan errors |
| Widescreen HUD/debug UI | Managed matrix + native captures/pointer pass |Uniform proportions, centered modal/F1, anchored HUD/F2;4:3/16:9/21:9/32:9, DPI and strict boundary checks |
| F1 debug menu | Managed/SDL audio tests + native Linux GTX1070 window pass |Pause/actions/input capture/resume/800x600 resize, zero validation errors;33 prepared scene/start choices; intentional modern tools, no new Windows runtime claim | | F1 debug menu | Managed/SDL audio tests + native Linux GTX1070 window pass |Pause/actions/input capture/resume/800x600 resize, zero validation errors;33 prepared scene/start choices; intentional modern tools, no new Windows runtime claim |
| F1 Force Control | Menu/director/interaction checks + native Linux SDL pass |Persistent override through source shots; disable/reset restores normal ownership; actual movement with neutron1a active, zero Vulkan errors; music handoff regression passes | | F1 Force Control | Menu/director/interaction checks + native Linux SDL pass |Persistent override through source shots; disable/reset restores normal ownership; actual movement with neutron1a active, zero Vulkan errors; music handoff regression passes |
| F2 live debug overlay | Managed timing/layout/menu + native Linux SDL pass |Non-pausing movement, visibility/repeat/menu priority and800x600 resize; all checks true, zero Vulkan errors; session persistence; modern tools, no new Windows runtime claim | | F2 live debug overlay | Managed timing/layout/menu + native Linux SDL pass |Non-pausing movement, visibility/repeat/menu priority and800x600 resize; all checks true, zero Vulkan errors; session persistence; modern tools, no new Windows runtime claim |
@@ -40,7 +107,7 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| Dynamic actors/sprites/models | Linux GPU pass |Carl/Goddard/Jimmy morphs, source Canv timing and9 original lab props; billboard/alpha, pivots and playback timing remain provisional | | Dynamic actors/sprites/models | Linux GPU pass |Carl/Goddard/Jimmy morphs, source Canv timing and9 original lab props; billboard/alpha, pivots and playback timing remain provisional |
| Scene music/speech | Linux dummy-device pass |CAM stops music before speech; full lab chain stays silent, DEFAULT restarts on completion/skip; reset tested. Packaged Linux/Wine64 lifecycle checks pass; speakers/latency/native Windows unverified | | Scene music/speech | Linux dummy-device pass |CAM stops music before speech; full lab chain stays silent, DEFAULT restarts on completion/skip; reset tested. Packaged Linux/Wine64 lifecycle checks pass; speakers/latency/native Windows unverified |
| VR01 star/trophy contacts | Source-data tests pass |5-point stars,300 trophy, acquired flags and contact-enter semantics; distance/exclusions/box approximation | | VR01 star/trophy contacts | Source-data tests pass |5-point stars,300 trophy, acquired flags and contact-enter semantics; distance/exclusions/box approximation |
| RETURN / renderer recreation |Source byte/helper/director tests + Linux headless pass |Lab/VR04/lab restores live departure root and companion, retains STRT yaw and suppresses intro once; fresh TSK loading separate; fades/window transition unverified | | RETURN / scene reload |Source/director tests + Linux headless pass |Lab/VR04/lab restores departure root/companion using one renderer, retains STRT yaw and suppresses intro; fresh TSK loading separate; original fades unverified |
| Supplied scene availability |All35 GAMs supplied;33 have OMT geometry |Level3B/E GAMs are duplicate four-entity records apart from level code; registered OMT archives absent, normal gameplay use unverified; no substitution or established blocker | | Supplied scene availability |All35 GAMs supplied;33 have OMT geometry |Level3B/E GAMs are duplicate four-entity records apart from level code; registered OMT archives absent, normal gameplay use unverified; no substitution or established blocker |
| Lab task/contact route | Managed input replay + headless GPU pass |887 input-only movement steps with live contacts/NPC updates reachSCENE60, score150, jetpack andlevel1; separate direct-contact GPU rebuild check | | Lab task/contact route | Managed input replay + headless GPU pass |887 input-only movement steps with live contacts/NPC updates reachSCENE60, score150, jetpack andlevel1; separate direct-contact GPU rebuild check |
| Lab underground passage |2763-step managed input replay pass |Both switches,2 clear crossings and timed reclosure; closed-gate negative sweep; explicit riverlab/SCENE65 fixture, prior progression and original comparison unverified | | Lab underground passage |2763-step managed input replay pass |Both switches,2 clear crossings and timed reclosure; closed-gate negative sweep; explicit riverlab/SCENE65 fixture, prior progression and original comparison unverified |
@@ -94,6 +161,14 @@ pass. See artifacts/live-debug-window.log and live-debug-return.log. No new
Windows runtime claim is made. Windows runtime claim is made.
Both self-contained platform packages rebuild successfully with this addition. Both self-contained platform packages rebuild successfully with this addition.
Persistent presentation/widescreen checkpoint: full regression suite passes in
artifacts/persistent-widescreen-full-tests.log, including539 preserved hashes.
Native6-load/one-window/one-renderer fullscreen/bounds/focus/pointer checks pass
with zero enabled-layer errors (artifacts/window-transition-final.log). F1/force
and F2 input checks still pass. Both packages rebuild; packaged Linux1920x1080
lab/VR04/lab retains one renderer and exact RETURN state with validation unavailable.
No new native Windows runtime claim is made.
Known visual/behavior limits include incomplete lighting/fog/blend/culling/material Known visual/behavior limits include incomplete lighting/fog/blend/culling/material
mapping, inferred model/root pivot, provisional collision/cadence/animation timing, mapping, inferred model/root pivot, provisional collision/cadence/animation timing,
close-wall camera clipping near Jimmy, incomplete class-specific triggers/interactions, close-wall camera clipping near Jimmy, incomplete class-specific triggers/interactions,
+76 -2
View File
@@ -9,8 +9,10 @@ audio. Closing resumes the previous mode. No new assets or dependencies are need
| --- | --- | | --- | --- |
| F1 | Open/close | | F1 | Open/close |
| F2 | Toggle live diagnostics without pausing | | F2 | Toggle live diagnostics without pausing |
| F3 | Toggle noclip |
| Tab | Cycle General, Player and Systems pages |
| Up/Down | Select a row | | Up/Down | Select a row |
| Left/Right | Change selected level, startpoint or staged SCENE task value | | Left/Right | Change selected level, startpoint, staged SCENE, flight speed or jetpack state |
| Page Up/Down | Change staged SCENE value by10 | | Page Up/Down | Change staged SCENE value by10 |
| Enter / numpad Enter | Apply the selected action | | Enter / numpad Enter | Apply the selected action |
| Escape | Close the menu | | Escape | Close the menu |
@@ -22,6 +24,65 @@ the existing task system and its callbacks. Inventory/energy/task actions affect
current runtime state and its normal checkpoint snapshots; they do not write files current runtime state and its normal checkpoint snapshots; they do not write files
by themselves. Debug tools do not imply reconstructed progression or full gameplay. by themselves. Debug tools do not imply reconstructed progression or full gameplay.
## Player and Systems pages
The General page retains the existing actions. Player adds noclip, staged flight
speeds300/600/1200/2400 (Enter applies), clear motion/queued jump, reopen objective,
return to noclip entry, apply source level gadget availability, toggle input after
player, staged jetpack states0/1/4 with a separate Apply row, and energy refill.
State0 means unowned,1 enabled and4 disabled by the level. The full availability
action re-enables the matching VR practice gadget and applies LV1B restrictions
on gadgets1/7 after the common prefix. Other level-specific tails remain incomplete. These controls expose
the current implementation; they are not proof of complete original behavior.
Systems adds the route static camera query toggle, independent music/speech/effects
mutes, restart selected music, stop all effects/loops, checkpoint save/load and the
practice prompt. Camera query control is available on LV1B/VR04/LEV1; elsewhere
it reports unavailable. Audio actions require scene audio (not headless/--mute).
Muting sets stream gain while playback clocks continue; new streams inherit mute.
F1 still pauses all stream clocks. Audio mute preferences reset with the scene.
Input-order override is for comparison; a new scene restores the continuation policy.
The practice action opens the existing prompt and closes F1.
Player diagnostics include velocity, pending impulse, movement mode/input order,
jump/hold/burst timers, jetpack state and objective time. Systems shows camera
polygon/query counts, category mute flags and queued audio bytes. Staged values
are separate from live values. `--debug-page general|player|systems` opens a page.
## Noclip (F3)
A modern investigation mode, enabled from F3 or Player/Noclip (`--noclip` at startup).
W/S or Up/Down move forward/back; A/D strafe; Left/Right turn. Space/E rises,
Ctrl/Q descends, Shift triples speed. Diagonal motion is normalized. Release stops
flight immediately. Gravity, body collision, camera obstruction, jetpack consumption
and contact-triggered script/pickup/mechanism/level actions are bypassed. Script,
actor and mechanism clocks still run; unrelated scripted transitions can still occur.
Flight uses the player camera during cutscenes without changing authored control
ownership. Space rises without skipping a cutscene while flying; Escape keeps its
normal skip action. F1 pauses flight. Toggle boundaries clear queued motion and
capture held input until release, so Space/Shift cannot become a jump on exit.
Reset and level changes clear noclip; it is never written into TSK saves.
Enabling remembers position/yaw. Return Noclip Entry restores them and clears
motion. Disabling retains the new position if the current static capsule adapter
accepts it, otherwise returns to entry. This checks static triangle proximity, not
full solid containment or moving objects; use Return Entry or reset if needed.
Normal gravity/collision resumes when disabled.
## Debug checkpoint
Save writes `debug-checkpoint.tsk` beside the executable using the existing original
TSK encoder and a temporary file replacement. It captures tasks, items, energy,
score, level/start and the existing RETURN departure vector; it does **not** capture
live Jimmy position, cutscene time, physics or debug preferences. Save errors appear
in the menu. Load validates the available prepared scene/start/support and uses the
normal scene rebuild, preserving the application window and renderer. Authored
start actions run normally. A load/reset clears force-control and noclip.
These are explicitly requested modern tools, a scoped exception to the gameplay
feature pause; no original debug-menu or noclip algorithm is claimed.
Force Control toggles a persistent debug override. Set it to TRUE and close the Force Control toggles a persistent debug override. Set it to TRUE and close the
menu to let Jimmy move even while a cutscene or scripted control lock is active. menu to let Jimmy move even while a cutscene or scripted control lock is active.
Subsequent camera shots cannot clear the override. The cutscene, camera and audio Subsequent camera shots cannot clear the override. The cutscene, camera and audio
@@ -72,7 +133,7 @@ without changing their pause state. Visibility persists through resets and scene
loads within the process; it is not stored in TSK. `--debug-overlay` starts enabled. loads within the process; it is not stored in TSK. `--debug-overlay` starts enabled.
Twelve bounded rows show measured FPS/frame milliseconds; level/start; root XYZ; Twelve bounded rows show measured FPS/frame milliseconds; level/start; root XYZ;
velocity XYZ; yaw/speed/turn rate; ground/pose/energy; control/force/pause; SCENE/ velocity XYZ; yaw/speed/turn rate; ground/pose/energy; control/force/pause/noclip; SCENE/
score/jetpack state and burst timer; actual camera mode/far plane; cutscene/shot/ score/jetpack state and burst timer; actual camera mode/far plane; cutscene/shot/
blocked state; movement counters; and reported issue/Vulkan-error/frame counts. blocked state; movement counters; and reported issue/Vulkan-error/frame counts.
STRT, orbit, gameplay and cutscene modes use the actual rendered view selection; STRT, orbit, gameplay and cutscene modes use the actual rendered view selection;
@@ -106,3 +167,16 @@ Native Linux GTX1070 window test passes with zero Vulkan validation errors:
artifacts/debug-window.log. GPU screenshots debug-menu.png and debug-window.open.ppm artifacts/debug-window.log. GPU screenshots debug-menu.png and debug-window.open.ppm
show the menu. Source/build/regression evidence does not constitute new native show the menu. Source/build/regression evidence does not constitute new native
Windows verification. Full regression and package status is in progress.md. Windows verification. Full regression and package status is in progress.md.
Debug text scales uniformly with resolution. F1 uses a centered authored canvas
on widescreen; F2 stays top-left. The window/device survive level changes. See
presentation-and-ui.md for lifecycle, ultrawide and high-DPI pointer checks.
Expansion verification (2026-10-25): full `scripts/test.sh` passes, including70
Python checks,21 movement groups, debug pages and real SDL dummy pause/mute clocks;
539 originals remain unchanged. Native Linux GTX1070 at1920x1080 passes
`--smoke-debug-tools`: F1/Tab, cutscene flight without force-control, F3 repeats,
held-input capture, camera/audio actions, TSK save/load and retained window.
Validation enabled, zero errors. Headless Player1920x1080 and Systems2560x1080
captures fit the existing uniform canvas. Logs/captures: artifacts/debug-expansion/.
No new native Windows runtime verification is claimed.
+59
View File
@@ -92,3 +92,62 @@
across scene rebuilds in memory, independently of TSK state. Reuse the existing across scene rebuilds in memory, independently of TSK state. Reuse the existing
font/buffers, give F1 display priority and measure wall-frame intervals separately font/buffers, give F1 display priority and measure wall-frame intervals separately
from simulation ticks. Report the rendered camera/projection, not a guessed mode. from simulation ticks. Report the rendered camera/projection, not a guessed mode.
21. **Own presentation at application lifetime.** Replace scene GPU resources
transactionally, retaining the SDL window, Vulkan core and user window state.
Size changes may recreate targets/swapchain. Per-level audio/gameplay remain
separate; source fades are still open.
22. **Uniform UI with anchors.** Preserve4:3 source positions, center modal/F1
canvases and anchor objectives bottom/right and F2 top-left. Map logical input
through actual drawable dimensions with double precision for strict bounds.
This is authorized modern widescreen policy, not original algorithm recovery.
23. **Pause feature expansion for architecture recovery.** Preserve clean69d0187
as a local tag and independent package copies. Use the lab/tutorial/return/
outside route to map state owners, callers, phases and persistence before more
gameplay. `checkpoint/` supersedes older architecture/priority summaries.
Evidence probes and directly evidenced corrections are permitted. A documented,
gated implementation plan ends the investigation checkpoint; continue through
it without waiting to understand every level.
24. **Separate task objective and entity phases.** Original45FB5B selects the
objective before task record mutation45FB7F and entity dispatch45FBD9. Expose
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.
28. **Expose implemented systems through modern debug tools.** The user explicitly
requests expansion and noclip during the gameplay feature pause. Preserve
General-page controls; add Player/Systems pages and F3 flight. Keep authored
control ownership separate from flight and bypass player contact triggers.
Clear pending motion/held input at toggles, retain an entry escape position,
and reset transient overrides on scene rebuild. Mute by stream gain so clocks
continue. Debug checkpoint uses the existing TSK/start progression contract,
never pretends to save live physics/cutscene state. These are investigation
features with port verification, not recovered original behavior.
29. **Persist bounded retained scalars independently of resets.** Ordinary route
loads keep movement mode, jump-hold and owned-fire timer in a separate memory
container for proven no-gadget/jetpack states. Reset jump/body/presentation
through their own boundaries; do not serialize these fields in TSK or carry
them through debug checkpoint load. Unsupported levels/gadget cleanup remain
the existing explicit approximation until traced. First destination ticks
can change retained values; boundary and post-tick tests are different.
30. **Read full PostLoad tails before asserting final availability.** The prior
common-prefix interpretation was incomplete. Each VR01..08 re-enables its
practice gadget after the shared disable pass; LV1B disables1/7. Correct the
implementation and expectations from the later dispatch/call evidence and
retain the earlier report as a scoped historical audit with a correction.
+6
View File
@@ -1,5 +1,11 @@
# Native infrastructure and package scope # Native infrastructure and package scope
Presentation now survives level loads: one SDL window/device with scene-resource
replacement. Uniform widescreen UI and input mapping are documented in
presentation-and-ui.md. The optional scripts/test-window-transitions.sh uses
installed Xvfb/Xfwm/D-Bus for isolated Linux fullscreen checks; these are not game
dependencies. --width/--height choose initial window/offscreen dimensions.
Verified environment: Ubuntu 24.04 x86-64; project-local .NET SDK 10.0.402, Verified environment: Ubuntu 24.04 x86-64; project-local .NET SDK 10.0.402,
Silk.NET 2.23.0, SDL 3.4.2 built from official source (Linux) and official x64 Silk.NET 2.23.0, SDL 3.4.2 built from official source (Linux) and official x64
SDL3.dll (Windows). GLSL compiled to Vulkan 1.3 SPIR-V and checked by spirv-val. SDL3.dll (Windows). GLSL compiled to Vulkan 1.3 SPIR-V and checked by spirv-val.
+80
View File
@@ -0,0 +1,80 @@
# Persistent presentation and widescreen UI
User-requested modern presentation/layout, 2026-10-25. Original assets and hashes
remain unchanged. These policies are separate from original fade/progression recovery.
## Presentation lifetime
Program.Main owns RenderSession until application exit. Each Run replaces level,
controller and audio state; SDL window/title changes do not recreate the window.
Position, logical/drawable dimensions, focus and fullscreen state survive loading.
VulkanRenderer.ReplaceScene validates bounds and stages vertex/index buffers,
textures, sampler and descriptor pool/sets after DeviceWaitIdle. Instance, device,
surface, swapchain, targets, pipelines and layouts stay alive. Resize/fullscreen
changes still replace size-dependent swapchain/targets. SceneRevision increments
on success and RendererIdentity exposes core handles for verification.
Old scene resources remain available until staging succeeds. Failure cleans partial
new resources and restores the prior set. Invalid indices/RGBA are runtime-tested
to preserve revision, identities and rendering; allocation-failure rollback is
implemented without fault injection. Loading remains synchronous; source fades
and loading presentation remain unfinished.
## Uniform layout and pointer mapping
UiViewport uses scale=min(drawableWidth/640,drawableHeight/480). Logical dimensions
are drawable dimensions divided by that common scale. Art/glyph X/Y proportions
match while the3D scene fills the viewport.
| UI | Anchor |
| --- | --- |
| Objective pad/text/digit | Bottom-right delta from authored640x480 |
| Practice prompt/F1 menu | Centered authored canvas |
| F2 live panel | Top-left safe inset |
Original4:3 positions, objective edge clipping and strict practice hit regions
remain. Widescreen anchors are an explicit port policy. --width/--height choose
initial window/offscreen dimensions64..8192; subsequent loads retain actual size.
Mouse coordinates map from SDL logical dimensions into actual drawable pixels
before inverse modal mapping. Double precision avoids ultrawide cancellation that
turned boundary225 into225.00003. Fractional DPI with independently rounded pixel
dimensions uses the same mapping.
## Verification
UiViewport/Hud/DebugOverlay tests cover nine aspect/resolution fixtures,4:3
equivalence,16:9/21:9/32:9, square/portrait,1.5x/2x DPI and fractional rounded
drawable dimensions. They verify glyph/art proportions, anchors, centered layouts
and strict Yes/No boundaries. The full suite passes in
artifacts/persistent-widescreen-full-tests.log, including539 unchanged originals.
Actual headless lab/VR04/lab Run transitions retain one renderer with revisions
1/2/3 at1280x720, exact RETURN root/companion and zero Vulkan errors
(artifacts/persistent-practice-return.log).
Native GTX1070: six loads, one window/renderer at960x720,1280x720,1680x720,
2560x720 and fullscreen3440x1440. Checks assert unchanged window ID/bounds/focus,
renderer identities across loading, fullscreen retention/restored windowed bounds,
native practice pointer mapping, rejected-load retention and zero cumulative
validation errors. Captures were visually inspected. Evidence:
artifacts/window-transition-final.log and window-transitions/*.png. Existing F1/
force-control and F2 input checks also pass from widescreen startup sizes.
```
source scripts/env.sh
dotnet build
scripts/test-window-transitions.sh
```
The runner uses installed Xvfb/Xfwm with private X11/D-Bus and artifact-backed
configuration. Bare Xvfb lacks a window manager to honor fullscreen requests.
NEUTRON_WINDOW_TEST=1 scripts/test.sh can use an existing managed display. These
are test dependencies; the game adds none. Linux runtime/cross-publishing does
not establish new native Windows or original visual/gameplay equivalence.
Both platform self-contained builds pass. The packaged Linux executable also
passes1920x1080 lab/VR04/lab with one renderer and exact RETURN root/companion
(artifacts/package-persistent-return.log; validation layers unavailable for this
standalone invocation). Native source/fullscreen checks above enable validation.
+163 -1
View File
@@ -1,9 +1,171 @@
# Progress — 2026-10-25 # Progress — 2026-10-26
## Retained-state implementation continuation
Read prompt.MD in full and resumed C3/C7. Three independent investigators owned
new property-reader, RETURN-cleanup and companion files; all ownership returned.
Reports: checkpoint/retained-streamer.md, retained-return-cleanup.md,
retained-companion.md and retained-player-body.md. Exact source offsets/targets,
structures, callers, scope and unresolved fields are recorded with14 new Python
regressions. Generic Init re-applies authored body vectors; final preparation
clears speed/velocity XYZ; jump state resets independently of retained scalars.
Implemented bounded PlayerLevelState (mode, jump-hold, owned-fire timer) for
ordinary LV1B/VR04/LEV1 transitions in the supported no-gadget/jetpack cases.
Other body/debug state reconstructs separately; TSK/debug checkpoint loads do not
carry transient fields. Modern R reset clears them. Companion AI/target/waypoint/
rotation and shadow resource resets are documented, not blanket-persisted.
Corrected prior prefix-only gadget availability: full VR01..08 PostLoad tails
re-enable the matching practice gadget; owned VR04 jetpack finishes1, not4. LV1B
disables gadgets1/7. Unknown wire states and other inventory regions stay intact.
Other level-specific gadget tails remain explicitly incomplete. Older VR04 state4
claims below describe the superseded partial implementation.
Targeted22 movement groups and inventory tests pass. Isolated original routines
pass under Wine32 in a copied, filesystem/network-isolated installation: authored
vector leaf accessors and43A750 preparation preserve unrelated sentinel bytes.
Synthetic fixture vtables resolve to guarded source targets; no whole-loader,
original-game end-to-end or native Windows verification is implied. Fresh Wine
prefix setup failed; a copied existing generated prefix works. Probe logs and
build/integration artifacts: artifacts/retained-lifecycle/.
Validation:84 Python checks (14 new), all managed groups including22 movement,
26 GPU render checks with zero enabled Vulkan validation errors, and the final
nondefault lab→VR04→lab boundary replay pass. Final boundary logs show mode1,
hold.625/fire6.125 retained independently of jump0/velocity0/speed0 at both loads;
RETURN position/control/companion and jetpack availability1 also pass. The full
suite's original-effects smoke initially failed its fixed200ms sampling window.
It now creates both streams paused before sampling and polls consumption with a
3s bound; all four final SDL dummy audio checks pass separately. No gameplay audio
lifecycle was changed by that harness correction. Logs: integration-final.log,
route-final.log, audio-final.log, evidence-final.log and hashes-final.log. All539
original files verified unchanged. Build succeeds with zero warnings/errors.
Both self-contained platform packages rebuilt from clean9ad5a8e (source_dirty=no).
Linux release launch from /tmp passes both nondefault retained-scalar boundaries
and exact RETURN/control/companion checks. Release validation unavailable, unlike
the enabled source GPU checks. Package evidence: package.log and package-route.log
in artifacts/retained-lifecycle/. Baseline packages remain untouched. Native Windows
runtime/original whole-game comparison are not added by cross-publication.
## Requested debug expansion
F1 now has General/Player/Systems pages (Tab), preserving existing General actions.
Added F3 noclip with vertical/strafe/boost controls, entry restoration and static
exit-overlap fallback; queued motion and held inputs clear at toggles. Flight
bypasses collision/camera obstruction and contacts without changing script control
ownership. Added movement/input-order/availability, objective/practice, camera
query, category audio mutes and original-format checkpoint actions/diagnostics.
Mutes use SDL stream gain so playback clocks continue. Scene/reset lifetimes and
checkpoint limits are documented in debug-menu.md. This user-requested debug work
is a scoped exception; evidence-led gameplay continuation remains the direction.
Full scripts/test.sh passes:70 Python,21 movement groups, remaining managed/GPU/
SDL checks and539 unchanged originals. Native Linux GTX1070 debug-tools smoke
passes at1920x1080 with zero enabled Vulkan validation errors, including flight
during a source cutscene without force control and same-window checkpoint reload.
Widescreen/ultrawide captures fit. Logs: artifacts/debug-expansion/. Windows SDL3
exports the gain API; native Windows runtime remains unverified for these changes.
Both self-contained packages rebuilt from clean d783898 (BUILD-INFO source_dirty=no).
Linux standalone launch from /tmp passes Player page/noclip at1920x1080 on llvmpipe;
validation is unavailable in that release invocation. Native enabled-validation
evidence above remains separate. Package logs: package.log and package-smoke.log
under artifacts/debug-expansion/. Baseline checkpoint package copies untouched.
## 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.
Self-contained Linux/Windows packages rebuilt from clean09cf117
(`artifacts/implementation/package.log`, both BUILD-INFO source_dirty=no).
Linux release runs from `/tmp` pass lab→VR04→lab RETURN assertions and a direct
outside scene load; source static query construction succeeds in all three route
profiles. Release invocations lack validation layers; the full source integration
above runs with validation enabled. Later changes only record this package evidence.
## Architecture reverse-engineering checkpoint
User direction supersedes feature-expansion priorities below. Full `prompt.MD`
read; current code/findings/progress audited. Clean playable69d0187 is preserved
by local tag `baseline-re-checkpoint-2026-10-25` and copied Linux/Windows packages
under `artifacts/re-checkpoint/baseline/`. All539 originals verified unchanged.
The existing Gitea remote configuration was left untouched and unused; older
claims below that no remotes are configured are stale. No remote work occurred.
Canonical continuation: `checkpoint/README.md`, `coverage.md`,
`implementation-plan.md` and the three system reports. New evidence separates
viewport physics/object update/sync from engine logic/morph timing, identifies
construction-order registry traversal, objective-before-task assignment and
per-actor Carl callbacks, DEFAULT camera snap, bank/voice ownership gaps and TSK
queued/duplicate-callback lifecycle. No original full-game runtime verification.
Initial architecture checkpoint exit is recorded in `checkpoint/review.md`.
C1 objective-before-records and C2 per-actor Carl callbacks are implemented;
the full integration suite passes, with zero GPU validation errors and539 hashes
unchanged. C3 fresh registry/input bridge, C5 first-hit static ray, C6 software
duration/repeat clock and C7 selective ordinary loader follow-ups are documented.
All investigator ownership returned. Exact old level-game registry eligibility
and retained-field reset traces gate scheduler integration; camera/audio/physics
chunks have independent concrete evidence gates. See the execution ledger.
Linux/Windows self-contained packages rebuilt from clean531883a; Linux release
Carl held-input smoke passes from `/tmp` (validation unavailable there). Later
loader defaults-bridge provenance corrections pass five targeted byte checks and
do not change runtime. Package and test logs are in artifacts/re-checkpoint/.
**The full reconstruction is incomplete.** The current implementation extends the **The full reconstruction is incomplete.** The current implementation extends the
user-verified Windows rendering checkpoint into an interactive original lab and user-verified Windows rendering checkpoint into an interactive original lab and
jet pack tutorial flow. This is not a verified faithful complete scene or release. jet pack tutorial flow. This is not a verified faithful complete scene or release.
## Persistent window/renderer and widescreen UI
Main now owns one RenderSession. Per-level Run replaces scene resources while
retaining the SDL window and Vulkan core; resize/fullscreen replace size-dependent
targets. Window bounds, focus and fullscreen survive loading. Invalid replacement
validation retains rendering. Per-level audio/gameplay still rebuild; fades remain
unfinished. UiViewport scales art/glyphs uniformly with bottom/right HUD anchors,
centered prompts/F1 and top-left F2. Pointer mapping handles logical/drawable size,
fractional DPI rounding and strict source boundaries.
Nine aspect/resolution fixtures and high-DPI checks pass. Full suite passes with
539 unchanged originals; final targeted viewport checks pass. Native GTX1070:
six loads, one window/renderer, stable native/core IDs and bounds/focus/fullscreen,
restored windowed bounds,4:3 through32:9/fullscreen3440x1440, native Yes/No mapping,
rejected-load retention and zero validation errors (artifacts/window-transition-final.log).
Captures were visually inspected. F1/force and F2 input checks still pass. Actual
headless lab/VR04/lab retains one renderer/revisions1/2/3 and exact RETURN root/
companion at1280x720. Both self-contained packages are rebuilt. The packaged Linux
1920x1080 lab/VR04/lab check also retains one renderer and exact RETURN state
(validation unavailable in that standalone invocation). No new Windows runtime
check is claimed. Details: presentation-and-ui.md.
## User-requested live debug overlay ## User-requested live debug overlay
F2 toggles a compact, non-pausing live diagnostics panel. F1 also offers Live F2 toggles a compact, non-pausing live diagnostics panel. F1 also offers Live
+5
View File
@@ -5,6 +5,11 @@ offsets, virtual addresses, API symbols or observed behavior. Decompiled output
evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL
probes and modern runtime checks are recorded separately. probes and modern runtime checks are recorded separately.
- `checkpoint/retained-player-body.md`, `retained-streamer.md`,
`retained-return-cleanup.md`, `retained-companion.md`: complete named property
read chain, bounded ordinary-load scalar/body resets, full tutorial availability
tails and companion/shadow lifecycle. Source-byte checks and an isolated original
body-routine probe are separate from whole-game/runtime comparison.
- `save-format.md`: full supplied TSK layout, task query/assignment and activation gates. - `save-format.md`: full supplied TSK layout, task query/assignment and activation gates.
- `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas. - `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas.
- `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence. - `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence.
+40
View File
@@ -35,9 +35,49 @@ compile, runtime and original-fidelity verification are separate.
restores authored ownership when disabled, clears on reset/new scene. restores authored ownership when disabled, clears on reset/new scene.
- [x] F2 live diagnostics plus F1 visibility toggle; non-pausing compact overlay, - [x] F2 live diagnostics plus F1 visibility toggle; non-pausing compact overlay,
measured frame timing and session-owned visibility across scene rebuilds. measured frame timing and session-owned visibility across scene rebuilds.
- [x] Application-owned window/Vulkan renderer across loads; bounded scene
replacement and native fullscreen/bounds/focus retention checks.
- [x] Uniform widescreen game/debug UI with anchors and matched native pointer
mapping, strict boundaries and high-DPI rounding checks.
- [x] Requested F1 General/Player/Systems pages, F3 noclip with cutscene flight,
motion/input capture, entry restoration, movement/camera/audio/UI/TSK controls;
full suite plus native Linux1920x1080 SDL regression pass. See debug-menu.md.
## Immediate continuation ## Immediate continuation
**Direction changed: pause feature expansion for the architecture checkpoint.**
Read `checkpoint/README.md`, `coverage.md` and `implementation-plan.md`. Preserved
baseline69d0187 remains the testing tool. The loop/motion, script/state and
camera/audio/UI investigations document the original lab→VR04→lab→outside route.
Complete core owner/order/lifetime evidence and unknowns, then execute the gated
plan in verified chunks. Earlier priorities below are a backlog.
- [x] Preserve clean playable source tag and independent Linux/Windows package copies.
- [x] Verify539 unchanged originals at checkpoint entry.
- [x] Recover frame-before-controller physics and construction-order registry passes.
- [x] Record core-system coverage, state ownership, assumptions and bounded plan.
- [x] Integrate independent reports/original-byte regressions; architecture exit review.
- [x] C1 objective-before-records order; managed and full integration checks pass.
- [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.
- [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.
- [x] Bounded retained mode/hold/fire route fixture through property/Init/PostLoad/
cleanup/control; authored/live body provenance and isolated original routines.
- [x] Full tutorial gadget re-enable tails and LV1B item1/7 restrictions; replaces
previous prefix-only availability. Other level tails/selection remain open.
- [x] Companion/shadow reset trace and equal-state AI guard; no blanket AI carry.
- [ ] Next: uncontrolled body/controller/fire scheduling, body registration and
appended-helper callback timing; then C4 support/response and shared viewport/
DEFAULT handoff. C6 source channel allocation/clock/banks remains separate.
1. Lab regressions are corrected and republished, with user verification of their 1. Lab regressions are corrected and republished, with user verification of their
own Windows build. Keep comprehensive native Windows driver/audio/input own Windows build. Keep comprehensive native Windows driver/audio/input
coverage separate from that report and preliminary Wine checks. Continue coverage separate from that report and preliminary Wine checks. Continue
+10 -1
View File
@@ -46,11 +46,20 @@ to save GPU readback. A Vulkan 1.3 graphics driver/loader is required.
This package includes the .NET runtime, SDL3, shaders and local asset copies. This package includes the .NET runtime, SDL3, shaders and local asset copies.
The default opens the controllable original lab. Arrows walk/backpedal/turn; The default opens the controllable original lab. Arrows walk/backpedal/turn;
Shift, Insert, numpad 0 or right mouse jump. R resets to the original start area; Shift, Insert, numpad 0 or right mouse jump. R resets to the original start area;
F1 opens debug tools: arrows navigate/change, Enter applies, F1/Escape closes. F1 opens debug tools: arrows navigate/change, Enter applies, Tab switches pages,
F1/Escape closes. General/Player/Systems pages cover implemented runtime controls.
The menu pauses gameplay/audio and provides diagnostics, camera/cutscene controls, The menu pauses gameplay/audio and provides diagnostics, camera/cutscene controls,
energy/jetpack/task changes, level/start selection, reset and Force Control toggle. energy/jetpack/task changes, level/start selection, reset and Force Control toggle.
Player/Systems add input ordering, jetpack availability, objective/practice, camera
obstruction, audio category mutes and debug checkpoint save/load. Checkpoints save
level/start/progression, not live position; see docs/debug-menu.md.
F3 toggles noclip: WASD moves/strafe, arrows move/turn, Space/E up, Ctrl/Q down,
Shift boosts speed. Noclip bypasses collision and contact triggers. Reset/new level
disables it; Return Noclip Entry restores the position where it was enabled.
F2 toggles compact live diagnostics without pausing; --debug-overlay enables it F2 toggles compact live diagnostics without pausing; --debug-overlay enables it
at startup. F1's Live Overlay toggle controls the same session preference. at startup. F1's Live Overlay toggle controls the same session preference.
Level changes retain the window, fullscreen and size. HUD/debug UI scales uniformly
on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions.
C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit. C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit.
Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview.
Append --inspect to start directly in the old scene inspector. Append --inspect to start directly in the old scene inspector.
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# Build first with dotnet build, then run this local Linux fullscreen/scene check.
# Requires the installed Xfwm window manager; never downloads dependencies.
set -euo pipefail
source "$(dirname "$0")/env.sh"
for task_tool in xfwm4 xprop dbus-run-session xvfb-run dotnet; do
if ! command -v "$task_tool" >/dev/null 2>&1; then
printf 'Missing window-test dependency: %s\n' "$task_tool" >&2
exit 1
fi
done
umask 077
mkdir -p artifacts/window-test-environment
NEUTRON_WINDOW_TEST_DIR="$(mktemp -d "$NEUTRON_ROOT/artifacts/window-test-environment/run.XXXXXX")"
export NEUTRON_WINDOW_TEST_DIR
export XDG_CONFIG_HOME="$NEUTRON_WINDOW_TEST_DIR/config"
export XDG_CACHE_HOME="$NEUTRON_WINDOW_TEST_DIR/cache"
export XDG_DATA_HOME="$NEUTRON_WINDOW_TEST_DIR/data"
export XDG_STATE_HOME="$NEUTRON_WINDOW_TEST_DIR/state"
export XDG_RUNTIME_DIR="$NEUTRON_WINDOW_TEST_DIR/runtime"
mkdir -p "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" "$XDG_STATE_HOME" "$XDG_RUNTIME_DIR"
export NO_AT_BRIDGE=1 GIO_USE_VFS=local
export GDK_BACKEND=x11 SDL_VIDEODRIVER=x11
unset SESSION_MANAGER
export SDL_AUDIODRIVER="${SDL_AUDIODRIVER:-dummy}"
# A bare Xvfb server cannot honor asynchronous EWMH fullscreen requests. Give
# this private display its own window manager and session bus. XDG paths keep
# all generated preferences/cache under artifacts without changing HOME.
exec xvfb-run -a -s '-screen 0 3440x1440x24' dbus-run-session -- bash -s -- "$@" <<'WINDOW_TEST'
set -euo pipefail
task_wm_log="$NEUTRON_WINDOW_TEST_DIR/xfwm4.log"
xfwm4 --compositor=off > "$task_wm_log" 2>&1 &
task_wm_pid=$!
cleanup() {
kill "$task_wm_pid" 2>/dev/null || true
wait "$task_wm_pid" 2>/dev/null || true
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
task_wm_ready=false
for ((task_try = 0; task_try < 50; task_try++)); do
if ! kill -0 "$task_wm_pid" 2>/dev/null; then
printf 'Window manager exited; see %s\n' "$task_wm_log" >&2
exit 1
fi
if [[ "$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null)" == *"window id"* ]]; then
task_wm_ready=true
break
fi
sleep 0.1
done
if [[ "$task_wm_ready" != true ]]; then
printf 'Window manager did not become ready; see %s\n' "$task_wm_log" >&2
exit 1
fi
dotnet run --no-build -- --smoke-window-transitions "$@"
WINDOW_TEST
+6
View File
@@ -9,10 +9,12 @@ dotnet run --project tests/GamePort.MovementTests -- ../Original
dotnet run --project tests/GamePort.DirectorTests -- ../Original dotnet run --project tests/GamePort.DirectorTests -- ../Original
dotnet run --project tests/GamePort.PatrolTests -- ../Original dotnet run --project tests/GamePort.PatrolTests -- ../Original
dotnet run --project tests/GamePort.SupportTests -- ../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.InteractionTests -- ../Original
dotnet run --project tests/GamePort.CheckpointTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original
dotnet run --project tests/GamePort.DebugMenuTests -- ../Original dotnet run --project tests/GamePort.DebugMenuTests -- ../Original
dotnet run --project tests/GamePort.DebugOverlayTests dotnet run --project tests/GamePort.DebugOverlayTests
dotnet run --project tests/GamePort.UiViewportTests
dotnet run --project tests/GamePort.DebugDiagnosticsTests dotnet run --project tests/GamePort.DebugDiagnosticsTests
SDL_AUDIODRIVER=dummy dotnet run --project tests/GamePort.AudioPauseTests SDL_AUDIODRIVER=dummy dotnet run --project tests/GamePort.AudioPauseTests
dotnet run --project tests/GamePort.LabRouteTests -- ../Original dotnet run --project tests/GamePort.LabRouteTests -- ../Original
@@ -34,6 +36,8 @@ dotnet run --no-build -- --headless --story --smoke-practice-prompt --screenshot
dotnet run --no-build -- --headless --story --smoke-practice-transition dotnet run --no-build -- --headless --story --smoke-practice-transition
dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm
dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm
dotnet run --no-build -- --headless --debug-page player --noclip --width 1920 --height 1080 --screenshot artifacts/test-debug-player.ppm
dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1080 --screenshot artifacts/test-debug-systems.ppm
dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm
dotnet run --no-build -- --headless --story --smoke-lab-route dotnet run --no-build -- --headless --story --smoke-lab-route
dotnet run --no-build -- --headless --smoke-carl-cutscene --frames 60 --screenshot artifacts/test-carl-cutscene.ppm dotnet run --no-build -- --headless --smoke-carl-cutscene --frames 60 --screenshot artifacts/test-carl-cutscene.ppm
@@ -56,6 +60,8 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --smoke-debug-tools
dotnet run --no-build -- --smoke-window-transitions
dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm
dotnet run --no-build -- --smoke-debug-menu --screenshot artifacts/test-debug-window.ppm dotnet run --no-build -- --smoke-debug-menu --screenshot artifacts/test-debug-window.ppm
dotnet run --no-build -- --smoke-objective-window --screenshot artifacts/test-objective-window.ppm dotnet run --no-build -- --smoke-objective-window --screenshot artifacts/test-objective-window.ppm
+1 -1
View File
@@ -63,7 +63,7 @@ public sealed class DebugDiagnostics
I($"VEL X {F(motion.Velocity.X)} Y {F(motion.Velocity.Y)} Z {F(motion.Velocity.Z)}"), I($"VEL X {F(motion.Velocity.X)} Y {F(motion.Velocity.Y)} Z {F(motion.Velocity.Z)}"),
I($"YAW {F(status.Yaw)} SPEED {F(status.Speed)} TURN {F(motion.TurnRate)}"), I($"YAW {F(status.Yaw)} SPEED {F(status.Speed)} TURN {F(motion.TurnRate)}"),
I($"GROUND {B(status.Grounded)} POSE {motion.Pose} ENERGY {F(status.Energy)}"), I($"GROUND {B(status.Grounded)} POSE {motion.Pose} ENERGY {F(status.Energy)}"),
I($"CTRL {B(status.Controlled)} FORCE {B(status.ForcedControl)} PAUSED {B(motion.Paused)}"), I($"CTRL {B(status.Controlled)} FORCE {B(status.ForcedControl)} PAUSED {B(motion.Paused)} NOCLIP {B(status.Systems?.Noclip ?? false)}"),
I($"SCENE {status.SceneTask} SCORE {status.Score} JETPACK {motion.JetpackState} {F(motion.JetpackRemaining)}S"), I($"SCENE {status.SceneTask} SCORE {status.Score} JETPACK {motion.JetpackState} {F(motion.JetpackRemaining)}S"),
I($"CAM {camera} FAR {F(status.FarPlane)}"), I($"CAM {camera} FAR {F(status.FarPlane)}"),
I($"CUT {status.Cutscene} SHOT {motion.Shot} BLOCK {B(motion.Blocked)}"), I($"CUT {status.Cutscene} SHOT {motion.Shot} BLOCK {B(motion.Blocked)}"),
+93 -9
View File
@@ -5,17 +5,55 @@ using GamePort.Assets;
namespace GamePort.Application; namespace GamePort.Application;
public sealed record DebugScene(string LevelFile, string Code, string[] Starts); public sealed record DebugScene(string LevelFile, string Code, string[] Starts);
public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay } public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay,
Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState,
CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice }
public sealed record DebugMenuView(string[] Lines, int SelectedLine); public sealed record DebugMenuView(string[] Lines, int SelectedLine);
public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed, public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed,
bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled, bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled,
int Issues, float FarPlane, bool Inspecting, bool ForcedControl = false, bool DiagnosticsVisible = false, string? CameraMode = null); int Issues, float FarPlane, bool Inspecting, bool ForcedControl = false, bool DiagnosticsVisible = false, string? CameraMode = null,
DebugSystems? Systems = null);
public sealed record DebugSystems
{
public bool Noclip { get; init; }
public float NoclipSpeed { get; init; } = 600;
public Vector3 Velocity { get; init; }
public Vector3 PendingImpulse { get; init; }
public int MovementMode { get; init; }
public bool InputAfterPlayer { get; init; }
public int JumpState { get; init; }
public float JumpHold { get; init; }
public float BurnRemaining { get; init; }
public int JetpackAvailability { get; init; }
public int Objective { get; init; }
public float ObjectiveTime { get; init; }
public bool? CameraObstruction { get; init; }
public int CameraPolygons { get; init; }
public int CameraWallPolygons { get; init; }
public int CameraTests { get; init; }
public bool AudioAvailable { get; init; }
public bool MusicMuted { get; init; }
public bool SpeechMuted { get; init; }
public bool EffectsMuted { get; init; }
public int MusicBytes { get; init; }
public int SpeechBytes { get; init; }
public int EffectBytes { get; init; }
}
/// <summary>Modern investigation tools, deliberately separate from recovered game UI.</summary> /// <summary>Modern investigation tools, deliberately separate from recovered game UI.</summary>
public sealed class DebugMenu public sealed class DebugMenu
{ {
public const uint ToggleKey = 58; // SDL scancode F1; F11 remains fullscreen. public const uint ToggleKey = 58; // SDL scancode F1; F11 remains fullscreen.
public const uint NoclipKey = 60; // F3; F2 remains live diagnostics.
public const int ItemCount = 12; public const int ItemCount = 12;
public const int PageCount = 3;
public int Page { get; private set; }
public int PageItems => Page switch { 1 => 10, 2 => 9, _ => ItemCount };
private static readonly float[] FlySpeeds = [300, 600, 1200, 2400];
private int flySpeedIndex = 1, jetpackStateIndex = 1;
private static readonly int[] JetpackStates = [0, 1, 4];
public float FlySpeed => FlySpeeds[flySpeedIndex];
public int JetpackState => JetpackStates[jetpackStateIndex];
public bool Open { get; private set; } public bool Open { get; private set; }
public int Selected { get; private set; } public int Selected { get; private set; }
public int SceneTask { get; private set; } public int SceneTask { get; private set; }
@@ -24,6 +62,7 @@ public sealed class DebugMenu
private int sceneIndex, startIndex; private int sceneIndex, startIndex;
public DebugScene? Scene => scenes.Length == 0 ? null : scenes[sceneIndex]; public DebugScene? Scene => scenes.Length == 0 ? null : scenes[sceneIndex];
public string? Start => Scene is { } scene ? scene.Starts[startIndex] : null; public string? Start => Scene is { } scene ? scene.Starts[startIndex] : null;
public DebugScene? FindScene(string code) => scenes.FirstOrDefault(s => s.Code == code);
public DebugMenu(IEnumerable<DebugScene> scenes, string? currentLevel, string? currentStart) public DebugMenu(IEnumerable<DebugScene> scenes, string? currentLevel, string? currentStart)
{ {
@@ -47,19 +86,39 @@ public sealed class DebugMenu
{ {
if (!Open) return DebugAction.None; if (!Open) return DebugAction.None;
if (scancode == 41) { Close(); return DebugAction.None; } if (scancode == 41) { Close(); return DebugAction.None; }
if (scancode == 43 && !repeat) { Page = (Page + 1) % PageCount; Selected = 0; return DebugAction.None; }
if (scancode is 82 or 81) if (scancode is 82 or 81)
Selected = (Selected + (scancode == 82 ? ItemCount - 1 : 1)) % ItemCount; Selected = (Selected + (scancode == 82 ? PageItems - 1 : 1)) % PageItems;
else if (scancode is 80 or 79 or 75 or 78) else if (scancode is 80 or 79 or 75 or 78)
{ {
var direction = scancode is 80 or 78 ? -1 : 1; var direction = scancode is 80 or 78 ? -1 : 1;
if (Selected == 5) if (Page == 1 && Selected == 1)
flySpeedIndex = (flySpeedIndex + FlySpeeds.Length + direction) % FlySpeeds.Length;
else if (Page == 1 && Selected == 7)
jetpackStateIndex = (jetpackStateIndex + JetpackStates.Length + direction) % JetpackStates.Length;
else if (Page == 0 && Selected == 5)
SceneTask = (int)Math.Clamp((long)SceneTask + direction * (scancode is 75 or 78 ? 10 : 1), 0, 999); SceneTask = (int)Math.Clamp((long)SceneTask + direction * (scancode is 75 or 78 ? 10 : 1), 0, 999);
else if (Selected == 6 && scenes.Length > 0) else if (Page == 0 && Selected == 6 && scenes.Length > 0)
{ sceneIndex = (sceneIndex + scenes.Length + direction) % scenes.Length; startIndex = 0; } { sceneIndex = (sceneIndex + scenes.Length + direction) % scenes.Length; startIndex = 0; }
else if (Selected == 7 && Scene is { } scene) else if (Page == 0 && Selected == 7 && Scene is { } scene)
startIndex = (startIndex + scene.Starts.Length + direction) % scene.Starts.Length; startIndex = (startIndex + scene.Starts.Length + direction) % scene.Starts.Length;
} }
else if (scancode is 40 or 88 && !repeat) else if (scancode is 40 or 88 && !repeat)
{
if (Page == 1) return Selected switch
{
0 => DebugAction.Noclip, 1 => DebugAction.NoclipSpeed, 2 => DebugAction.StopMotion,
3 => DebugAction.ShowObjective, 4 => DebugAction.ReturnNoclipEntry,
5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder,
8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy, _ => DebugAction.None
};
if (Page == 2) return Selected switch
{
0 => DebugAction.CameraObstruction, 1 => DebugAction.MuteMusic, 2 => DebugAction.MuteSpeech,
3 => DebugAction.MuteEffects, 4 => DebugAction.RestartMusic, 5 => DebugAction.StopEffects,
6 => DebugAction.SaveCheckpoint, 7 => DebugAction.LoadCheckpoint, 8 => DebugAction.Practice,
_ => DebugAction.None
};
return Selected switch return Selected switch
{ {
0 => DebugAction.Resume, 1 => DebugAction.Camera, 2 => DebugAction.SkipCutscene, 0 => DebugAction.Resume, 1 => DebugAction.Camera, 2 => DebugAction.SkipCutscene,
@@ -69,6 +128,7 @@ public sealed class DebugMenu
11 => DebugAction.ToggleOverlay, 11 => DebugAction.ToggleOverlay,
_ => DebugAction.None _ => DebugAction.None
}; };
}
return DebugAction.None; return DebugAction.None;
} }
@@ -77,6 +137,30 @@ public sealed class DebugMenu
if (!Open) return new([], -1); if (!Open) return new([], -1);
var c = CultureInfo.InvariantCulture; var c = CultureInfo.InvariantCulture;
string F(float value) => value.ToString("0.0", c); string F(float value) => value.ToString("0.0", c);
var system = status.Systems ?? new();
if (Page != 0)
{
string V(Vector3 v) => $"{F(v.X)} {F(v.Y)} {F(v.Z)}";
string[] header = ["NEUTRON DEBUG MENU - F1", $"PAUSED - PAGE {Page + 1}/3: {(Page == 1 ? "PLAYER" : "SYSTEMS")}",
$"LEVEL {status.Level} / START {status.Start}", $"ROOT {V(status.Root)} NOCLIP {system.Noclip}",
Page == 1 ? $"VEL {V(system.Velocity)} MODE {system.MovementMode}" : $"STATIC POLYS {system.CameraPolygons} WALLS {system.CameraWallPolygons} TESTS {system.CameraTests}",
Page == 1 ? $"PENDING {V(system.PendingImpulse)}" : $"AUDIO BYTES MUSIC {system.MusicBytes} VOICE {system.SpeechBytes}",
Page == 1 ? $"JUMP {system.JumpState} HOLD {F(system.JumpHold)} BURN {F(system.BurnRemaining)}"
: $"EFFECT BYTES {system.EffectBytes} AUDIO AVAILABLE {system.AudioAvailable}",
$"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}", ""];
string[] items = Page == 1 ? [
$"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)",
$"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE",
"RETURN TO NOCLIP ENTRY POSITION", "APPLY THIS LEVEL'S GADGET AVAILABILITY",
$"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)",
$"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100"] : [
$"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}",
$"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}",
"RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"];
return new([.. header, .. items, "", "TAB NEXT PAGE UP/DOWN SELECT ENTER APPLY",
Page == 1 ? "FLY: WASD/ARROWS SPACE/E UP CTRL/Q DOWN SHIFT FAST" : "CHECKPOINT: DEBUG-CHECKPOINT.TSK BESIDE EXECUTABLE",
"F1 / ESC CLOSE - ACTIONS USE EXISTING SYSTEMS", Message], header.Length + Selected);
}
return new([ return new([
"NEUTRON DEBUG MENU - F1", "NEUTRON DEBUG MENU - F1",
"PAUSED - MODERN DEBUG TOOLS", "PAUSED - MODERN DEBUG TOOLS",
@@ -100,9 +184,9 @@ public sealed class DebugMenu
$"FORCE CONTROL: {status.ForcedControl} (ENTER TOGGLE)", $"FORCE CONTROL: {status.ForcedControl} (ENTER TOGGLE)",
$"LIVE OVERLAY: {status.DiagnosticsVisible} (F2 / ENTER TOGGLE)", $"LIVE OVERLAY: {status.DiagnosticsVisible} (F2 / ENTER TOGGLE)",
"", "",
"UP/DOWN SELECT LEFT/RIGHT CHANGE ENTER APPLY", "TAB NEXT PAGE UP/DOWN SELECT LEFT/RIGHT CHANGE",
"SCENE TASK: PAGE UP/DOWN CHANGES BY 10", "ENTER APPLIES SCENE TASK: PAGE UP/DOWN CHANGES BY 10",
"F1 / ESC CLOSE - GAME INPUT IS CAPTURED WHILE OPEN", "F1 / ESC CLOSE F3 NOCLIP - GAME INPUT CAPTURED",
Message Message
], 9 + Selected); ], 9 + Selected);
} }
+6 -3
View File
@@ -65,7 +65,8 @@ public sealed class DebugMenuOverlay
/// Layout uses the same640x480 reference viewport as the original HUD. /// Layout uses the same640x480 reference viewport as the original HUD.
/// Compact mode uses a corner panel with58 columns and smaller live text. /// Compact mode uses a corner panel with58 columns and smaller live text.
/// </summary> /// </summary>
public void Update(Mesh destination, IReadOnlyList<string> lines, int selectedLine = -1, bool compact = false) public void Update(Mesh destination, IReadOnlyList<string> lines, int selectedLine = -1, bool compact = false,
uint viewportWidth = 640, uint viewportHeight = 480)
{ {
ArgumentNullException.ThrowIfNull(destination); ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(lines); ArgumentNullException.ThrowIfNull(lines);
@@ -73,6 +74,8 @@ public sealed class DebugMenuOverlay
if (selectedLine < -1 || selectedLine >= lines.Count) throw new ArgumentOutOfRangeException(nameof(selectedLine)); if (selectedLine < -1 || selectedLine >= lines.Count) throw new ArgumentOutOfRangeException(nameof(selectedLine));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length) if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits debug overlay ranges", nameof(destination)); throw new ArgumentException("Destination omits debug overlay ranges", nameof(destination));
var viewport = new UiViewport(viewportWidth, viewportHeight);
var anchor = compact ? Vector2.Zero : viewport.CenterOffset;
var background = FindDraw(firstIndex, 6); var background = FindDraw(firstIndex, 6);
var highlight = FindDraw(firstIndex + 6, 6); var highlight = FindDraw(firstIndex + 6, 6);
background.Visible = lines.Count > 0; background.Visible = lines.Count > 0;
@@ -120,9 +123,9 @@ public sealed class DebugMenuOverlay
destination.Vertices[start + 2] = new(Position(x + width, y + height), maxUv, color); destination.Vertices[start + 2] = new(Position(x + width, y + height), maxUv, color);
destination.Vertices[start + 3] = new(Position(x, y + height), new(minUv.X, maxUv.Y), color); destination.Vertices[start + 3] = new(Position(x, y + height), new(minUv.X, maxUv.Y), color);
} }
}
private static Vector3 Position(float x, float y) => new(2 * x / 640 - 1, 2 * y / 480 - 1, 0); Vector3 Position(float x, float y) => viewport.ToNdc(new Vector2(x, y) + anchor);
}
private static PngImage CreateFont() private static PngImage CreateFont()
{ {
+58
View File
@@ -0,0 +1,58 @@
using GamePort.Assets;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
namespace GamePort.Application;
/// <summary>Application-owned presentation; level loads replace only scene resources.</summary>
public sealed class RenderSession : IDisposable
{
private VulkanRenderer? renderer;
private bool videoInitialized;
public nint Window { get; private set; }
public int WindowCreationCount { get; private set; }
public int RendererCreationCount { get; private set; }
public bool Fullscreen => Window != 0 && (Sdl.SDL_GetWindowFlags(Window) & 1) != 0;
public bool HasInputFocus => Window == 0 || (Sdl.SDL_GetWindowFlags(Window) & 0x200) != 0;
public VulkanRenderer LoadScene(Mesh mesh, PngImage fallback, bool headless, string title,
uint width, uint height, bool validation)
{
if (renderer != null)
{
if (headless != (Window == 0)) throw new InvalidOperationException("Cannot change presentation mode during a session");
if (Window != 0 && !Sdl.SDL_SetWindowTitle(Window, title)) throw new InvalidOperationException(Sdl.Error);
renderer.ReplaceScene(mesh, fallback);
return renderer;
}
if (!headless)
{
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
videoInitialized = true;
Window = Sdl.SDL_CreateWindow(title, checked((int)width), checked((int)height),
Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity);
if (Window == 0) throw new InvalidOperationException(Sdl.Error);
WindowCreationCount++;
}
renderer = new(mesh, fallback, width, height, Window, validation);
RendererCreationCount++;
return renderer;
}
public void ToggleFullscreen()
{
if (Window != 0 && !Sdl.SDL_SetWindowFullscreen(Window, !Fullscreen)) throw new InvalidOperationException(Sdl.Error);
}
public void Dispose()
{
var current = renderer;
renderer = null;
try { current?.Dispose(); }
finally
{
if (Window != 0) { Sdl.SDL_DestroyWindow(Window); Window = 0; }
if (videoInitialized) { Sdl.SDL_Quit(); videoInitialized = false; }
}
}
}
+5 -2
View File
@@ -72,12 +72,14 @@ public sealed class SceneHud
/// <summary>Writes the final merged buffer, including when later visual composers copied these vertices.</summary> /// <summary>Writes the final merged buffer, including when later visual composers copied these vertices.</summary>
public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible, public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible,
float objectiveYOffset = -69, bool objectiveContentVisible = true) float objectiveYOffset = -69, bool objectiveContentVisible = true,
uint viewportWidth = 640, uint viewportHeight = 480)
{ {
if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480) if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480)
throw new ArgumentOutOfRangeException(nameof(objectiveYOffset)); throw new ArgumentOutOfRangeException(nameof(objectiveYOffset));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length) if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits HUD ranges", nameof(destination)); throw new ArgumentException("Destination omits HUD ranges", nameof(destination));
var viewport = new UiViewport(viewportWidth, viewportHeight);
foreach (var quad in quads) foreach (var quad in quads)
{ {
var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace
@@ -88,7 +90,8 @@ public sealed class SceneHud
var digit = quad.Canvas is >= 83 and <= 85; var digit = quad.Canvas is >= 83 and <= 85;
var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f; var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f;
var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset; var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset;
Vector3 Position(float px, float py) => new(2 * px / 640 - 1, 2 * py / 480 - 1, 0); var anchor = quad.Canvas == 169 ? viewport.CenterOffset : viewport.BottomRightOffset;
Vector3 Position(float px, float py) => viewport.ToNdc(new Vector2(px, py) + anchor);
destination.Vertices[quad.VertexOffset].Position = Position(x, y); destination.Vertices[quad.VertexOffset].Position = Position(x, y);
destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y); destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y);
destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height); destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height);
+67
View File
@@ -0,0 +1,67 @@
using System.Numerics;
namespace GamePort.Application;
/// <summary>
/// Modern viewport policy for original640x480 UI: uniform art/text scale with
/// explicit anchors. The3D scene still occupies the entire physical viewport.
/// </summary>
public readonly struct UiViewport
{
private readonly double pixelScale, modalPixelX, modalPixelY;
private readonly uint pixelWidth, pixelHeight;
public float Scale { get; }
public float LogicalWidth { get; }
public float LogicalHeight { get; }
public Vector2 CenterOffset => new((LogicalWidth - 640) / 2, (LogicalHeight - 480) / 2);
public Vector2 BottomRightOffset => new(LogicalWidth - 640, LogicalHeight - 480);
public UiViewport(uint width, uint height)
{
if (width == 0 || height == 0) throw new ArgumentOutOfRangeException(nameof(width), "UI viewport must be nonzero");
pixelWidth = width; pixelHeight = height;
pixelScale = Math.Min(width / 640d, height / 480d);
Scale = (float)pixelScale;
LogicalWidth = (float)(width / pixelScale);
LogicalHeight = (float)(height / pixelScale);
modalPixelX = (width - 640 * pixelScale) / 2;
modalPixelY = (height - 480 * pixelScale) / 2;
}
/// <summary>Map anchored logical coordinates into Vulkan overlay NDC, Y down.</summary>
public Vector3 ToNdc(Vector2 logicalPoint)
{
Validate(logicalPoint);
return new(2 * logicalPoint.X / LogicalWidth - 1, 2 * logicalPoint.Y / LogicalHeight - 1, 0);
}
/// <summary>
/// Inverse of centered modal placement. Use SDL logical window dimensions
/// with SDL logical pointer pixels; render using drawable pixel dimensions.
/// Coordinates remain unclamped to preserve strict original Yes/No bounds.
/// </summary>
public Vector2 InverseModal(Vector2 windowPixels)
{
Validate(windowPixels);
// Subtract the physical center before dividing, using double precision.
// Float logical-space cancellation can turn an exact source boundary225
// into225.00003 on ultrawide and incorrectly enter a strict hit region.
return new((float)((windowPixels.X - modalPixelX) / pixelScale),
(float)((windowPixels.Y - modalPixelY) / pixelScale));
}
/// <summary>Map SDL logical mouse coordinates to the actual drawable before
/// hit testing; this also handles fractional DPI sizes rounded by the OS.</summary>
public Vector2 InverseModal(Vector2 windowPoint, uint windowWidth, uint windowHeight)
{
Validate(windowPoint);
if (windowWidth == 0 || windowHeight == 0) throw new ArgumentOutOfRangeException(nameof(windowWidth));
return new((float)(((double)windowPoint.X * pixelWidth / windowWidth - modalPixelX) / pixelScale),
(float)(((double)windowPoint.Y * pixelHeight / windowHeight - modalPixelY) / pixelScale));
}
private static void Validate(Vector2 point)
{
if (!float.IsFinite(point.X) || !float.IsFinite(point.Y)) throw new ArgumentOutOfRangeException(nameof(point));
}
}
@@ -0,0 +1,170 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
namespace GamePort.Application;
/// <summary>Local native presentation/scene-resource regression, not a gameplay replay.</summary>
public static class WindowTransitionSmoke
{
private readonly record struct WindowState(uint Id, int X, int Y, int Width, int Height, bool Fullscreen, bool Focused);
public static int Run(RenderSession session, string assets, string prepared, string output, bool validation)
{
Directory.CreateDirectory(output);
VulkanRenderer? renderer = null;
Mesh? mesh = null;
SceneHud? hud = null;
DebugMenuOverlay? overlay = null;
GamLevel? level = null;
var sceneNumber = 0;
var menu = new DebugMenu([], null, null);
menu.Toggle(30);
var diagnostics = new DebugDiagnostics { Enabled = true };
var viewportCases = new (uint Width, uint Height, string Scene, string Ui)[]
{
(960, 720, "level1b", "menu"),
(1280, 720, "VR04", "practice"),
(1680, 720, "level1b", "objectives"),
(2560, 720, "level1", "live")
};
foreach (var test in viewportCases)
{
if (renderer != null) Resize(test.Width, test.Height);
Replace(test.Scene, test.Width, test.Height);
Render(test.Ui, $"{sceneNumber}-{test.Scene}-{test.Width}x{test.Height}");
if (test.Ui == "practice") CheckPracticePointer();
}
var windowed = State();
session.ToggleFullscreen();
Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
Require(session.Fullscreen, "SDL did not enter fullscreen");
Replace("VR04", renderer!.Width, renderer.Height);
Render("practice", "fullscreen-practice");
CheckPracticePointer();
Replace("level1b", renderer.Width, renderer.Height);
Render("menu", "fullscreen-menu");
session.ToggleFullscreen();
Require(Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
var restored = State();
Require(!restored.Fullscreen && restored.Width == windowed.Width && restored.Height == windowed.Height
&& restored.X == windowed.X && restored.Y == windowed.Y, "Windowed bounds did not survive fullscreen and scene replacement");
var revision = renderer.SceneRevision;
var identity = renderer.Identity;
Reject(() => renderer.ReplaceScene(new Mesh([new(Vector3.Zero, Vector2.Zero, Vector3.One)], [0, 1, 2]), PngImage.White));
Reject(() => renderer.ReplaceScene(mesh!, new PngImage(2, 2, [255])));
Require(renderer.SceneRevision == revision && renderer.Identity == identity, "Rejected replacement changed presentation state");
Render("live", "after-rejected-replacement");
Require(session.WindowCreationCount == 1 && session.RendererCreationCount == 1 && renderer.ValidationErrors == 0,
"Window/renderer were recreated or Vulkan validation failed");
Console.WriteLine($"Window transition check: scenes={sceneNumber}, windows={session.WindowCreationCount}, renderers={session.RendererCreationCount}, fullscreen retained=True, bounds retained=True, invalid scene retained=True, Vulkan errors={renderer.ValidationErrors}.");
return 0;
void Replace(string name, uint width, uint height)
{
level = GamLevel.Load(AssetPath.Resolve(assets, "gam/" + name + ".gam"));
var world = Mesh.LoadSceneJson(AssetPath.Resolve(prepared, name + "/scene.json"));
hud = new(world, Path.Combine(prepared, "ui/ui.json"));
overlay = new(hud.Mesh);
mesh = overlay.Mesh;
var before = renderer == null ? (WindowState?)null : State();
var beforeIdentity = renderer?.Identity;
var beforeRenderer = renderer;
renderer = session.LoadScene(mesh, PngImage.White, false, "Neutron — persistent-window check", width, height, validation);
sceneNumber++;
if (before != null)
{
Require(ReferenceEquals(renderer, beforeRenderer) && renderer.Identity == beforeIdentity,
"Scene replacement recreated the device/surface/swapchain/pipelines");
Require(State() == before.Value, "Scene replacement changed native window state");
}
else
{
Require(Sdl.SDL_SetWindowPosition(session.Window, 37, 53) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
}
Require(renderer.SceneRevision == sceneNumber, "Wrong scene revision after resource replacement");
Console.WriteLine($"PASS retained presentation for{name}: revision={renderer.SceneRevision}, window={Sdl.SDL_GetWindowID(session.Window)}, size={renderer.Width}x{renderer.Height}, fullscreen={session.Fullscreen}.");
}
void Resize(uint width, uint height)
{
Require(Sdl.SDL_SetWindowSize(session.Window, (int)width, (int)height) && Sdl.SDL_SyncWindow(session.Window), Sdl.Error);
DrainAndResize();
Require(Sdl.SDL_GetWindowSize(session.Window, out var logicalWidth, out var logicalHeight), Sdl.Error);
Require(Sdl.SDL_GetWindowSizeInPixels(session.Window, out var pixelWidth, out var pixelHeight), Sdl.Error);
Require(logicalWidth == width && logicalHeight == height && renderer!.Width == pixelWidth && renderer.Height == pixelHeight,
"Window/drawable dimensions did not match resize");
}
void DrainAndResize()
{
while (Sdl.SDL_PollEvent(out var e))
if (e.Type == Sdl.Quit) throw new InvalidOperationException("Window closed during transition check");
if (!Sdl.SDL_GetWindowSizeInPixels(session.Window, out var width, out var height)) throw new InvalidOperationException(Sdl.Error);
if (renderer != null && (renderer.Width != width || renderer.Height != height)) renderer.Resize();
}
WindowState State()
{
if (!Sdl.SDL_GetWindowPosition(session.Window, out var x, out var y)
|| !Sdl.SDL_GetWindowSize(session.Window, out var width, out var height))
throw new InvalidOperationException(Sdl.Error);
return new(Sdl.SDL_GetWindowID(session.Window), x, y, width, height, session.Fullscreen, session.HasInputFocus);
}
void Render(string mode, string filename)
{
var start = level!.FindStart() ?? level.Entities.First(e => e.Kind == "STRT");
hud!.Update(mesh!, 1, mode == "objectives", mode == "practice", -69, true, renderer!.Width, renderer.Height);
var status = new DebugStatus(level.Code, start.Tag!, start.Position, start.Rotation.Y, 0, true,
20, 0, 30, "NONE", true, 0, SceneProjection.FarPlane(level.Code), false);
var view = mode == "menu" ? menu.View(status) : new DebugMenuView([], -1);
var lines = mode == "live" ? diagnostics.Lines(status,
new(Vector3.Zero, 0, "IDLE", 0, 0, 0, 0, 0, -1, false, renderer.ValidationErrors, false)) : view.Lines;
overlay!.Update(mesh!, lines, view.SelectedLine, mode == "live", renderer.Width, renderer.Height);
var projection = SceneProjection.CreateGameplay(level.Code, (float)renderer.Width / renderer.Height);
projection.M22 *= -1;
var camera = Matrix4x4.CreateLookAtLeftHanded(start.CameraPosition, start.Position + new Vector3(0, 80, 0), Vector3.UnitY);
renderer.UpdateVertices(mesh!.Vertices);
renderer.Render(camera * projection);
renderer.SavePpm(Path.Combine(output, filename + ".ppm"));
Require(renderer.ValidationErrors == 0, "Vulkan error during scene/UI render");
}
void CheckPracticePointer()
{
Require(Sdl.SDL_GetWindowSize(session.Window, out var width, out var height), Sdl.Error);
var layout = new UiViewport(renderer!.Width, renderer.Height);
foreach (var yes in new[] { true, false })
{
var authored = new Vector2(yes ? 265 : 355, 270);
var pixel = (authored + layout.CenterOffset) * layout.Scale;
Sdl.SDL_WarpMouseInWindow(session.Window, pixel.X * width / renderer.Width, pixel.Y * height / renderer.Height);
DrainAndResize(); // SDL mouse state reflects the most recent event pump.
Sdl.SDL_GetMouseState(out var x, out var y);
var prompt = new PracticePrompt();
bool? accepted = null;
prompt.Chosen += (_, value) => accepted = value;
prompt.Show(0); prompt.Click(layout.InverseModal(new(x, y), (uint)width, (uint)height));
Require(accepted == yes && !prompt.Active,
$"Scaled native pointer missed practice bounds: expected={yes}, target={pixel}, mouse=<{x},{y}>, authored={layout.InverseModal(new(x, y), (uint)width, (uint)height)}");
}
Console.WriteLine($"PASS native scaled practice pointer at{width}x{height}.");
}
}
private static void Require(bool condition, string message)
{ if (!condition) throw new InvalidOperationException(message); }
private static void Reject(Action action)
{
try { action(); } catch (ArgumentException) { return; }
throw new InvalidOperationException("Expected bounded scene replacement rejection");
}
}
+20 -7
View File
@@ -11,6 +11,9 @@ public sealed class SceneAudio : IDisposable
private readonly List<SdlAudio> effects = []; private readonly List<SdlAudio> effects = [];
private readonly Dictionary<string, SdlAudio> loops = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, SdlAudio> loops = new(StringComparer.OrdinalIgnoreCase);
public bool Paused { get; private set; } public bool Paused { get; private set; }
public bool MusicMuted { get; private set; }
public bool SpeechMuted { get; private set; }
public bool EffectsMuted { get; private set; }
public int EffectCount => effects.Count; public int EffectCount => effects.Count;
public int LoopCount => loops.Count; public int LoopCount => loops.Count;
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes); public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
@@ -27,13 +30,13 @@ public sealed class SceneAudio : IDisposable
{ {
StopMusic(); StopMusic();
if (selectedMusic is { } selection && resources.Wave(selection.Database, selection.Id) is { } wave) if (selectedMusic is { } selection && resources.Wave(selection.Database, selection.Id) is { } wave)
music = new(wave.Path, true, Paused); music = new(wave.Path, true, Paused, MusicMuted);
} }
public void Speech(string database, int id) public void Speech(string database, int id)
{ {
StopSpeech(); StopSpeech();
var wave = resources.Wave(database, id) ?? throw new FileNotFoundException($"Missing prepared speech: {database}:{id}"); var wave = resources.Wave(database, id) ?? throw new FileNotFoundException($"Missing prepared speech: {database}:{id}");
speech = new(wave.Path, paused: Paused); speech = new(wave.Path, paused: Paused, muted: SpeechMuted);
} }
public void StopSpeech() { speech?.Dispose(); speech = null; } public void StopSpeech() { speech?.Dispose(); speech = null; }
// Default current bank set by Jimmy PostLoad423642..656; positional attenuation // Default current bank set by Jimmy PostLoad423642..656; positional attenuation
@@ -42,11 +45,11 @@ public sealed class SceneAudio : IDisposable
{ {
var wave = resources.Wave("SoundEffects.omt", id) var wave = resources.Wave("SoundEffects.omt", id)
?? throw new FileNotFoundException($"Missing original default sound effect {id}"); ?? throw new FileNotFoundException($"Missing original default sound effect {id}");
if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused)); if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted));
else else
{ {
StopLoop(loopOwner); StopLoop(loopOwner);
loops.Add(loopOwner, new(wave.Path, true, Paused)); loops.Add(loopOwner, new(wave.Path, true, Paused, EffectsMuted));
} }
} }
public void StopLoop(string owner) public void StopLoop(string owner)
@@ -70,10 +73,20 @@ public sealed class SceneAudio : IDisposable
/// <summary>Modern debug pause; new streams also inherit this state.</summary> /// <summary>Modern debug pause; new streams also inherit this state.</summary>
public void SetPaused(bool paused) public void SetPaused(bool paused)
{ {
music?.SetPaused(paused); speech?.SetPaused(paused);
foreach (var effect in effects) effect.SetPaused(paused);
foreach (var effect in loops.Values) effect.SetPaused(paused);
Paused = paused; Paused = paused;
ApplyPause();
}
public void SetDebugMute(bool musicMuted, bool speechMuted, bool effectsMuted)
{
MusicMuted = musicMuted; SpeechMuted = speechMuted; EffectsMuted = effectsMuted;
ApplyPause();
}
private void ApplyPause()
{
music?.SetPaused(Paused); speech?.SetPaused(Paused);
music?.SetMuted(MusicMuted); speech?.SetMuted(SpeechMuted);
foreach (var effect in effects) { effect.SetPaused(Paused); effect.SetMuted(EffectsMuted); }
foreach (var effect in loops.Values) { effect.SetPaused(Paused); effect.SetMuted(EffectsMuted); }
} }
public void Dispose() { StopEffects(); StopSpeech(); StopMusic(); } public void Dispose() { StopEffects(); StopSpeech(); StopMusic(); }
} }
+9 -1
View File
@@ -11,6 +11,7 @@ public sealed class SdlAudio : IDisposable
private readonly bool loop; private readonly bool loop;
private bool audioInitialized; private bool audioInitialized;
public bool Paused { get; private set; } public bool Paused { get; private set; }
public bool Muted { get; private set; }
public int QueuedBytes public int QueuedBytes
{ {
get get
@@ -19,7 +20,7 @@ public sealed class SdlAudio : IDisposable
return bytes >= 0 ? bytes : throw new InvalidOperationException(Sdl.Error); return bytes >= 0 ? bytes : throw new InvalidOperationException(Sdl.Error);
} }
} }
public SdlAudio(string path,bool loop=false,bool paused=false) public SdlAudio(string path,bool loop=false,bool paused=false,bool muted=false)
{ {
this.loop=loop; this.loop=loop;
if(!Sdl.SDL_InitSubSystem(Sdl.InitAudio))throw new InvalidOperationException(Sdl.Error); if(!Sdl.SDL_InitSubSystem(Sdl.InitAudio))throw new InvalidOperationException(Sdl.Error);
@@ -34,6 +35,7 @@ public sealed class SdlAudio : IDisposable
// SDL_OpenAudioDeviceStream starts paused. Keep it paused from its // SDL_OpenAudioDeviceStream starts paused. Keep it paused from its
// first sample when created while a debug menu has stopped playback. // first sample when created while a debug menu has stopped playback.
Paused = true; Paused = true;
SetMuted(muted);
SetPaused(paused); SetPaused(paused);
Console.WriteLine($"SDL3 WAV stream: {spec.Frequency} Hz, {spec.Channels} channel(s), {length} source bytes."); Console.WriteLine($"SDL3 WAV stream: {spec.Frequency} Hz, {spec.Channels} channel(s), {length} source bytes.");
} }
@@ -47,6 +49,12 @@ public sealed class SdlAudio : IDisposable
if (!changed) throw new InvalidOperationException(Sdl.Error); if (!changed) throw new InvalidOperationException(Sdl.Error);
Paused = paused; Paused = paused;
} }
public void SetMuted(bool muted)
{
ObjectDisposedException.ThrowIf(stream == 0, this);
if (!Sdl.SDL_SetAudioStreamGain(stream, muted ? 0 : 1)) throw new InvalidOperationException(Sdl.Error);
Muted = muted;
}
private void Queue(){if(!Sdl.SDL_PutAudioStreamData(stream,data,length))throw new InvalidOperationException(Sdl.Error);} private void Queue(){if(!Sdl.SDL_PutAudioStreamData(stream,data,length))throw new InvalidOperationException(Sdl.Error);}
public void Pump(){if(!Paused && loop && QueuedBytes<length)Queue();} public void Pump(){if(!Paused && loop && QueuedBytes<length)Queue();}
public void Dispose() public void Dispose()
+2 -2
View File
@@ -21,8 +21,8 @@ public readonly record struct JetpackEffectResult(
/// <summary> /// <summary>
/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0. /// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0.
/// Controller and effect phases are separate: their full-scene order has not /// Controller and effect phases are separate. The normal route registry places
/// been recovered. The caller must explicitly choose an order. Horizontal /// Jimmy before his retained fire; other full-scene phases remain incomplete. Horizontal
/// movement, shadow queries, visuals and sound callbacks belong to the caller. /// movement, shadow queries, visuals and sound callbacks belong to the caller.
/// </summary> /// </summary>
public static class JetpackBurst public static class JetpackBurst
+166 -30
View File
@@ -3,7 +3,8 @@ using GamePort.Assets;
namespace GamePort.Game; namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump); public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump,
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly }
/// <summary> /// <summary>
@@ -15,11 +16,19 @@ public sealed class LabSimulation
{ {
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension. public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision; private readonly SceneCollision collision;
private readonly Func<Vector3, Vector3, SupportHit?>? cameraRay;
private readonly Vector3 sourceStart; private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor; 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 JetpackBurstState jumpState;
private bool forceFall; private bool forceFall;
private Vector3 noclipEntry;
private float noclipEntryYaw;
public bool Noclip { get; private set; }
public bool HasNoclipEntry { get; private set; }
public float NoclipSpeed { get; set; } = 600;
public Func<int>? JetpackInventoryState { get; set; } public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B"; public string LevelCode { get; set; } = "LV1B";
public int GadgetMode { get; set; } = -1; public int GadgetMode { get; set; } = -1;
@@ -27,15 +36,24 @@ public sealed class LabSimulation
public float InteractionRadius { get; private set; } = 60; public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; } public bool JetpackEffectVisible { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining; public float JetpackRemaining => jumpState.EffectRemaining;
public int JumpState => jumpState.JumpState;
public float JumpHoldSeconds => jumpState.HoldSeconds;
public int Bursts { get; private set; } public int Bursts { get; private set; }
public float BodyHeight { get; } public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root. public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; } 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 Yaw { get; private set; }
public float Speed { get; private set; } public float Speed { get; private set; }
public float TurnRate { get; private set; } public float TurnRate { get; private set; }
public bool Grounded { 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 => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; : !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; } public int Steps { get; private set; }
@@ -51,9 +69,11 @@ public sealed class LabSimulation
public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180) public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0)); * 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.collision = collision;
this.cameraRay = cameraRay;
sourceStart = start; sourceStart = start;
startYaw = yaw; startYaw = yaw;
var bounds = standingPose.Bounds(); var bounds = standingPose.Bounds();
@@ -76,13 +96,15 @@ public sealed class LabSimulation
Velocity = Vector3.Zero; Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw; Yaw = targetYaw = startYaw;
Speed = TurnRate = extraAirAcceleration = shadowDistance = 0; Speed = TurnRate = extraAirAcceleration = shadowDistance = 0;
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
jumpState = default; jumpState = default;
forceFall = JetpackEffectVisible = false; forceFall = JetpackEffectVisible = false;
InteractionRadius = 60; Bursts = 0; InteractionRadius = 60; Bursts = 0;
Grounded = true; Grounded = true;
Noclip = HasNoclipEntry = false;
Steps = Jumps = Landings = WallHits = 0; Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0; Travel = MaximumRise = 0;
CameraEye = DesiredEye(); CameraEye = DesiredEye().Eye;
} }
/// <summary>Jimmy PostLoad423A90..423ABF restores the saved RETURN root. /// <summary>Jimmy PostLoad423A90..423ABF restores the saved RETURN root.
@@ -92,7 +114,25 @@ public sealed class LabSimulation
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z)) if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z))
throw new ArgumentOutOfRangeException(nameof(root)); throw new ArgumentOutOfRangeException(nameof(root));
Position = root - Vector3.UnitY * rootHeight; Position = root - Vector3.UnitY * rootHeight;
CameraEye = DesiredEye(); CameraEye = DesiredEye().Eye;
}
public PlayerLevelState? CaptureLevelState(int selectedGadget) => Noclip ? null
: new(LevelCode, selectedGadget, movementMode, jumpState.HoldSeconds, jumpState.EffectRemaining);
/// <summary>Apply after destination construction. Init re-applies authored
/// body vectors and clears speed/turn; PostLoad resets jump, not these scalars.
/// Grounding and the next controller/fire tick may change them independently.</summary>
public bool ApplyRetainedLevelState(PlayerLevelState state)
{
ArgumentNullException.ThrowIfNull(state);
if (!state.SupportsDestination(LevelCode)) return false;
if (state.MovementMode is < 0 or > 1 || !float.IsFinite(state.HoldSeconds)
|| state.HoldSeconds < 0 || !float.IsFinite(state.EffectRemaining))
throw new ArgumentOutOfRangeException(nameof(state));
movementMode = state.MovementMode;
jumpState = new(0, state.HoldSeconds, state.EffectRemaining);
return true;
} }
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table. // EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
@@ -106,18 +146,81 @@ public sealed class LabSimulation
public void Step(PlayerInput input) public void Step(PlayerInput input)
{ {
if (Noclip) { StepNoclip(input); return; }
//47E554 global body integration precedes473740 registry callbacks.
// This reconstructs the player/input/fire partial order, not the full
// scene registry, original cadence or original collision response.
StepPhysics();
if (!InputAfterPlayerUpdate) StepInput(input);
StepPlayer(input);
var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode);
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
if (InputAfterPlayerUpdate) StepInput(input);
Steps++;
}
/// <summary>Modern debug movement; never serialized into original save state.</summary>
public bool SetNoclip(bool enabled)
{
if (enabled == Noclip) return false;
if (enabled)
{
noclipEntry = Position; noclipEntryYaw = Yaw; HasNoclipEntry = true;
}
var returned = !enabled && !collision.CanOccupy(Position, BodyRadius, BodyHeight);
if (returned) { Position = noclipEntry; Yaw = targetYaw = noclipEntryYaw; }
Noclip = enabled;
StopDebugMotion();
Grounded = false;
CameraEye = DesiredEye().Eye;
return returned;
}
public void StopDebugMotion()
{
Velocity = pendingImpulse = Vector3.Zero;
Speed = TurnRate = extraAirAcceleration = lateralContribution = 0;
jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false;
targetYaw = Yaw;
}
public bool ReturnToNoclipEntry()
{
if (!HasNoclipEntry) return false;
Position = noclipEntry; Yaw = targetYaw = noclipEntryYaw;
StopDebugMotion(); Grounded = false; CameraEye = DesiredEye().Eye;
return true;
}
private void StepNoclip(PlayerInput input)
{
if (!float.IsFinite(NoclipSpeed) || NoclipSpeed <= 0 || NoclipSpeed > 10000)
throw new ArgumentOutOfRangeException(nameof(NoclipSpeed));
const float dt = FixedStepClock.Step; const float dt = FixedStepClock.Step;
var wasGrounded = Grounded; Yaw = targetYaw = (Yaw + ((input.Left ? 1 : 0) - (input.Right ? 1 : 0)) * 90 * dt) % 360;
float lateral = 0; var (sin, cos) = Trig(Yaw);
if (Grounded) var direction = new Vector3(-sin, 0, cos) * ((input.Forward ? 1 : 0) - (input.Backward ? 1 : 0))
+ new Vector3(cos, 0, sin) * ((input.StrafeRight ? 1 : 0) - (input.StrafeLeft ? 1 : 0))
+ Vector3.UnitY * ((input.Rise ? 1 : 0) - (input.Descend ? 1 : 0));
if (direction.LengthSquared() > 1) direction = Vector3.Normalize(direction);
Velocity = direction * NoclipSpeed * (input.Fast ? 3 : 1);
var delta = Velocity * dt;
Position += delta; Travel += new Vector2(delta.X, delta.Z).Length();
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
Grounded = false; Steps++;
CameraEye = DesiredEye().Eye;
}
private void StepInput(PlayerInput input)
{
const float dt = FixedStepClock.Step;
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; float yawDelta = 0;
if (input.Left) { 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; lateral = 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 (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta; if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300); if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
@@ -131,15 +234,29 @@ public sealed class LabSimulation
//438011..43802B adds the independent turn rate directly to yaw. //438011..43802B adds the independent turn rate directly to yaw.
targetYaw = 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); var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 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; Yaw = (Yaw + TurnRate * dt) % 360;
var (sin, cos) = Trig(Yaw); var (sin, cos) = Trig(Yaw);
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed); var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
//437CDx ground uses /45 then dt;43803B air uses /55 without dt. //437CDx ground uses /45 then dt;43803B air uses /55 without dt.
const float friction = .8f; 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; : TurnRate * (1 - friction) * Speed * .0181818176060915f;
velocity += new Vector3(cos, 0, sin) * sideSpeed; velocity += new Vector3(cos, 0, sin) * sideSpeed;
if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor) if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
@@ -147,14 +264,26 @@ public sealed class LabSimulation
var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance, var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration)); JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY; jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
var impulse = new Vector3(0, air.ImpulseY, 0); pendingImpulse += new Vector3(0, air.ImpulseY, 0);
if (air.ImpulseY != 0) { Grounded = false; Jumps++; } if (air.ImpulseY != 0) Jumps++;
if (air.MovementModeOverride is { } mode) movementMode = mode;
if (air.VelocityYOverride is { } vertical) velocity.Y = vertical; if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
if (air.RadiusOverride is { } radius) InteractionRadius = radius; if (air.RadiusOverride is { } radius) InteractionRadius = radius;
if (air.Pose == JetpackPose.Fall) forceFall = true; if (air.Pose == JetpackPose.Fall) forceFall = true;
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false; else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (air.StartGadget) Bursts++; 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); Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
var before = Position; var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight); var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
@@ -175,24 +304,31 @@ public sealed class LabSimulation
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0; if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
if (Grounded) { extraAirAcceleration = 0; forceFall = false; } if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
Velocity = velocity; 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 (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++; if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z)); Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor); 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); 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 (Noclip) return (eye, 1); // Debug exploration also bypasses camera obstruction.
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, public static PlayerInput SmokeInput(int step) => new(step < 120, false, false,
+32 -14
View File
@@ -106,34 +106,52 @@ public static class OriginalBodySupport
SupportHit? nearest = null; SupportHit? nearest = null;
var nearestDistance = length; var nearestDistance = length;
foreach (var triangle in triangles) foreach (var triangle in triangles)
{
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); RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
var edge1 = triangle.B - triangle.A; var edge1 = triangle.B - triangle.A;
var edge2 = triangle.C - triangle.A; var edge2 = triangle.C - triangle.A;
var p = Cross(direction, edge2); var p = Cross(direction, edge2);
var determinant = Dot(edge1, p); var determinant = Dot(edge1, p);
// Source indices use the opposite sign from a conventional right- // Preserve serialized winding, opposite to the conventional visible front.
// handed visible-front-face test. Preserve the actual serialized order.
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon) if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
continue; return null;
var inverse = 1 / determinant; var inverse = 1 / determinant;
var relative = start - triangle.A; var relative = start - triangle.A;
var u = Dot(relative, p) * inverse; var u = Dot(relative, p) * inverse;
if (u < 0 || u > 1) continue; if (u < 0 || u > 1) return null;
var q = Cross(relative, edge1); var q = Cross(relative, edge1);
var v = Dot(q, direction) * inverse; var v = Dot(q, direction) * inverse;
if (v < 0 || u + v > 1) continue; if (v < 0 || u + v > 1) return null;
var distance = Dot(q, edge2) * inverse; var distance = Dot(q, edge2) * inverse;
// Source accepts the beginning, but rejects its endpoint and equal // Beginning accepted, endpoint rejected; no invented camera radius/skin.
// distance candidates. No invented extra ray distance or skin is used. if (distance < 0 || distance >= length) return null;
if (distance < 0 || distance >= length) continue;
var position = start + direction * distance; var position = start + direction * distance;
var fromStart = QuickMagnitude(position - start); return new SupportHit(position, triangle.ShapeId, triangle.PolygonId, QuickMagnitude(position - start));
if (fromStart >= nearestDistance) continue;
nearestDistance = fromStart;
nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart);
}
return nearest;
} }
private static float Dot(Vector3 a, Vector3 b) => private static float Dot(Vector3 a, Vector3 b) =>
+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");
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace GamePort.Game;
/// <summary>
/// Retained scalars proven through route GAM read, Init and PostLoad callbacks.
/// This is in-memory ordinary-load state, never part of the original TSK format.
/// Other gadget cleanup branches/levels need their own lifecycle proof.
/// </summary>
public sealed record PlayerLevelState(string SourceLevel, int SelectedGadget,
int MovementMode, float HoldSeconds, float EffectRemaining)
{
public bool SupportsDestination(string level) => IsRoute(SourceLevel) && IsRoute(level)
&& SelectedGadget is -1 or 3;
private static bool IsRoute(string level) => level is "LV1B" or "VR04" or "LEV1";
}
+12
View File
@@ -17,6 +17,18 @@ public sealed class SceneCollision
private readonly Triangle[] triangles; private readonly Triangle[] triangles;
public int TriangleCount => triangles.Length; public int TriangleCount => triangles.Length;
/// <summary>Modern debug exit check against the current capsule adapter.</summary>
public bool CanOccupy(Vector3 feet, float radius, float height)
{
Validate(feet, Vector3.Zero, radius, height);
CapsuleBounds(feet, radius, height, out var min, out var max);
foreach (var triangle in triangles)
if (Overlaps(min, max, triangle)
&& Closest(feet, radius, height, triangle).DistanceSquared < (radius - Tolerance) * (radius - Tolerance))
return false;
return true;
}
private readonly record struct Triangle(Vector3 A, Vector3 B, Vector3 C, private readonly record struct Triangle(Vector3 A, Vector3 B, Vector3 C,
Vector3 Normal, Vector3 Min, Vector3 Max); Vector3 Normal, Vector3 Min, Vector3 Max);
private readonly record struct Hit(float Time, Vector3 Normal); private readonly record struct Hit(float Time, Vector3 Normal);
+21 -1
View File
@@ -528,8 +528,28 @@ public sealed class SceneDirector
// animated actor's TaskName activation contract. Applying the latter // animated actor's TaskName activation contract. Applying the latter
// here disables the lab exit even when SCENE reaches60. // here disables the lab exit even when SCENE reaches60.
if (source.Kind == "LOAD") return; if (source.Kind == "LOAD") return;
// Carl413F30 captures SCENE before generic40E340, then executes his
// derived policy in the same callback, before the next registry actor.
var carlScene = source.Kind == "3CAR" ? tasks.Get("SCENE") : 0;
var active = source.Kind == "3PIC" ? TaskActivation.Pickup(source, state) : TaskActivation.Animated(source, state); var active = source.Kind == "3PIC" ? TaskActivation.Pickup(source, state) : TaskActivation.Animated(source, state);
if (active.HasValue) { actor.Active = actor.Visible = active.Value; ActorChanged?.Invoke(actor); } if (active.HasValue) actor.Active = actor.Visible = active.Value;
var carlOverride = source.Kind == "3CAR" && level.Code == "LV1B";
if (carlOverride)
{
//414068..414118. Other levels' derived policies remain unported.
if (carlScene is < 0 or > 60) actor.Active = actor.Visible = false;
else
{
if (carlScene > 30 && FindActor("CARLESC3") is { } marker)
{
actor.AIstate = 6;
actor.Position = marker.Position;
}
// At60 retain the generic activation result.
if (carlScene < 60) actor.Active = actor.Visible = true;
}
}
if (active.HasValue || carlOverride) ActorChanged?.Invoke(actor);
} }
private void Block(GamEntity source, string detail, string? next) private void Block(GamEntity source, string detail, string? next)
+7 -25
View File
@@ -15,7 +15,6 @@ public sealed class SceneInteractions
private readonly SceneDirector director; private readonly SceneDirector director;
private readonly TaskStates tasks; private readonly TaskStates tasks;
private readonly OriginalSave initial; private readonly OriginalSave initial;
private readonly string levelCode;
private readonly int[] itemStates; private readonly int[] itemStates;
private readonly HashSet<int> contacts = []; private readonly HashSet<int> contacts = [];
private readonly HashSet<string> unsupported = []; private readonly HashSet<string> unsupported = [];
@@ -34,15 +33,15 @@ public sealed class SceneInteractions
public event Action<DirectorActor, string>? ConversationStarted; public event Action<DirectorActor, string>? ConversationStarted;
public event Action<int>? ObjectiveChanged; public event Action<int>? ObjectiveChanged;
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save, string? levelCode = null) public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save)
{ {
this.director = director; this.tasks = tasks; initial = save; this.director = director; this.tasks = tasks; initial = save;
this.levelCode = levelCode ?? save.LevelCode;
Inventory = new SceneInventory(save.InventoryStates); Inventory = new SceneInventory(save.InventoryStates);
itemStates = save.ItemStates.ToArray(); Score = save.Score; itemStates = save.ItemStates.ToArray(); Score = save.Score;
Energy = save.PlayerValue; Energy = save.PlayerValue;
CurrentObjective = save.OtherCounter; CurrentObjective = save.OtherCounter;
ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart; ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart;
tasks.Assigning += OnTaskAssigning;
tasks.Assigned += OnTaskAssigned; tasks.Assigned += OnTaskAssigned;
Reset(); Reset();
} }
@@ -68,7 +67,6 @@ public sealed class SceneInteractions
{ {
contacts.Clear(); contacts.Clear();
HideCollected(); HideCollected();
ApplyCarlTask();
} }
public void HideCollected() public void HideCollected()
@@ -191,36 +189,20 @@ public sealed class SceneInteractions
} }
} }
private void OnTaskAssigned(string name, int value) private void OnTaskAssigning(string name, int value)
{ {
HideCollected();
if (Equal(name, "SCENE")) if (Equal(name, "SCENE"))
{ {
//45F990 jump tables ->406F50: clear the transient objective flags, //45FB5B ->406F50 runs BEFORE records change at45FB7F and before
//select this objective and set its flag1; TSK writes selector4F8194. //entity slot424 callbacks at45FBD9. TSK writes selector4F8194.
var objective = ObjectiveForScene(value); var objective = ObjectiveForScene(value);
if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); } if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); }
ApplyCarlTask();
} }
} }
private void ApplyCarlTask() private void OnTaskAssigned(string name, int value)
{ {
//Carl's override413F30 follows generic activation; LV1B branch414068. HideCollected();
//Other levels' custom visibility/position policies are not ported here.
if (levelCode != "LV1B") return;
var state = tasks.Get("SCENE");
foreach (var actor in director.Actors.Where(a => a.Kind == "3CAR" && Equal(a.SourceGam?.Text("TaskName"), "SCENE")))
{
if (state is < 0 or > 60) { actor.Visible = actor.Active = false; continue; }
if (state > 30 && director.FindActor("CARLESC3") is { } marker)
{
actor.AIstate = 6;
actor.Position = marker.Position;
}
//At60 the override leaves the generic activation result unchanged.
if (state < 60) actor.Active = actor.Visible = true;
}
} }
private static bool Equal(string? a, string? b) => a is not null && b is not null private static bool Equal(string? a, string? b) => a is not null && b is not null
+30
View File
@@ -24,6 +24,36 @@ public sealed class SceneInventory
public void SetState(int group, int item, int state) => states[Offset(group, item)] = state; public void SetState(int group, int item, int state) => states[Offset(group, item)] = state;
/// <summary>
/// Jimmy PostLoad: enable eight owned gadgets, disable them in VR01..08,
/// then re-enable that tutorial's gadget in the later level-specific tail.
/// LV1B disables gadgets1/7. Other level-specific tails remain unported.
/// State4 is unavailable ownership, distinct from unowned0.
/// </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;
//4242AF..424400: each practice scene enables its matching gadget.
var practiceItem = levelCode[3] - '1';
if (states[practiceItem] == 4) states[practiceItem] = 1;
}
else if (levelCode == "LV1B")
{
//424102: lab restrictions follow the common enable pass.
foreach (var item in new[] { 1, 7 })
if (states[item] == 1) states[item] = 4;
}
}
public void SelectGadget(int item) public void SelectGadget(int item)
{ {
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0)) if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
+4
View File
@@ -6,6 +6,9 @@ namespace GamePort.Game;
public sealed class TaskStates public sealed class TaskStates
{ {
private readonly List<SavedTask> tasks; private readonly List<SavedTask> tasks;
/// <summary>45FB5B objective dispatch, before task records or actor callbacks change.</summary>
public event Action<string, int>? Assigning;
/// <summary>45FBD9 entity dispatch, after all matching task records change.</summary>
public event Action<string, int>? Assigned; public event Action<string, int>? Assigned;
public TaskStates(IEnumerable<SavedTask> initial) => tasks = initial.ToList(); public TaskStates(IEnumerable<SavedTask> initial) => tasks = initial.ToList();
private static bool Equal(string a, string b) => Fold(a) == Fold(b); private static bool Equal(string a, string b) => Fold(a) == Fold(b);
@@ -16,6 +19,7 @@ public sealed class TaskStates
public int Get(string? name) => name == null ? 0 : tasks.FirstOrDefault(t => Equal(t.Name, name))?.State ?? 0; public int Get(string? name) => name == null ? 0 : tasks.FirstOrDefault(t => Equal(t.Name, name))?.State ?? 0;
public void SetExisting(string name, int value) public void SetExisting(string name, int value)
{ {
Assigning?.Invoke(name, value);
for (var i = 0; i < tasks.Count; i++) for (var i = 0; i < tasks.Count; i++)
if (Equal(tasks[i].Name, name)) tasks[i] = tasks[i] with { State = value }; if (Equal(tasks[i].Name, name)) tasks[i] = tasks[i] with { State = value };
// Original broadcasts even repeated assignments and unknown task names. // Original broadcasts even repeated assignments and unknown task names.
+7
View File
@@ -38,6 +38,12 @@ internal static unsafe class Sdl
public static string Error=>Marshal.PtrToStringUTF8(SDL_GetError())??"SDL error"; public static string Error=>Marshal.PtrToStringUTF8(SDL_GetError())??"SDL error";
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] public static extern nint SDL_CreateWindow([MarshalAs(UnmanagedType.LPUTF8Str)]string title,int w,int h,ulong flags); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] public static extern nint SDL_CreateWindow([MarshalAs(UnmanagedType.LPUTF8Str)]string title,int w,int h,ulong flags);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyWindow(nint window); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyWindow(nint window);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern uint SDL_GetWindowID(nint window);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern ulong SDL_GetWindowFlags(nint window);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowPosition(nint window,out int x,out int y);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowPosition(nint window,int x,int y);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SyncWindow(nint window);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_WarpMouseInWindow(nint window,float x,float y);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowTitle(nint window,[MarshalAs(UnmanagedType.LPUTF8Str)]string title); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowTitle(nint window,[MarshalAs(UnmanagedType.LPUTF8Str)]string title);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PollEvent(out Event e); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PollEvent(out Event e);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern byte** SDL_Vulkan_GetInstanceExtensions(out uint count); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern byte** SDL_Vulkan_GetInstanceExtensions(out uint count);
@@ -59,6 +65,7 @@ internal static unsafe class Sdl
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PauseAudioStreamDevice(nint stream); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PauseAudioStreamDevice(nint stream);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PutAudioStreamData(nint stream,nint buffer,int length); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PutAudioStreamData(nint stream,nint buffer,int length);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern int SDL_GetAudioStreamQueued(nint stream); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern int SDL_GetAudioStreamQueued(nint stream);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetAudioStreamGain(nint stream,float gain);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyAudioStream(nint stream); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyAudioStream(nint stream);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_Delay(uint ms); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_Delay(uint ms);
} }
+268 -49
View File
@@ -15,14 +15,17 @@ internal static class Program
{ {
try try
{ {
using var presentation = new RenderSession();
OriginalSave? carriedSave = null; OriginalSave? carriedSave = null;
PlayerLevelState? carriedPlayer = null;
var returning = false; var returning = false;
var diagnostics = new DebugDiagnostics { Enabled = args.Contains("--debug-overlay") }; var diagnostics = new DebugDiagnostics { Enabled = args.Contains("--debug-overlay") };
while (true) while (true)
{ {
var result = Run(args, carriedSave, returning, diagnostics, out var continuation); var result = Run(args, carriedSave, carriedPlayer, returning, diagnostics, presentation, out var continuation);
if (result != 0 || continuation == null) return result; if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning; args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning;
carriedPlayer = continuation.Player;
} }
} }
catch (Exception error) { Console.Error.WriteLine(error); return 1; } catch (Exception error) { Console.Error.WriteLine(error); return 1; }
@@ -37,9 +40,10 @@ internal static class Program
return args[i + 1]; return args[i + 1];
} }
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning); private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning, PlayerLevelState? Player);
private static int Run(string[] args, OriginalSave? carriedSave, bool returning, DebugDiagnostics diagnostics, out SceneContinuation? continuation) private static int Run(string[] args, OriginalSave? carriedSave, PlayerLevelState? carriedPlayer, bool returning, DebugDiagnostics diagnostics,
RenderSession presentation, out SceneContinuation? continuation)
{ {
continuation = null; continuation = null;
if (args.Contains("--help")) if (args.Contains("--help"))
@@ -68,6 +72,7 @@ internal static class Program
--headless Render offscreen through Vulkan --headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM --screenshot PATH Save actual GPU readback as PPM
--frames N Exit after N frames (headless default: 1) --frames N Exit after N frames (headless default: 1)
--width N --height N Initial window/offscreen size (default960x720)
--audio PATH Play recovered WAV; --loop-audio repeats it --audio PATH Play recovered WAV; --loop-audio repeats it
--audio-smoke PATH Verify audio-stream consumption --audio-smoke PATH Verify audio-stream consumption
--scene-audio-smoke PATH Verify music/speech streams from entities.json --scene-audio-smoke PATH Verify music/speech streams from entities.json
@@ -85,9 +90,13 @@ internal static class Program
--smoke-objective-panel Show original lab objective; --story-time tests timeout --smoke-objective-panel Show original lab objective; --story-time tests timeout
--smoke-objective-window SDL O-key reopen/close/timeout check --smoke-objective-window SDL O-key reopen/close/timeout check
--debug-menu Start with the F1 debug menu open --debug-menu Start with the F1 debug menu open
--debug-page NAME Open general, player or systems debug page
--noclip Start modern debug flight (F3 toggles)
--smoke-debug-tools SDL pages/noclip/audio/checkpoint check
--debug-overlay Start with live F2 diagnostics visible --debug-overlay Start with live F2 diagnostics visible
--smoke-debug-menu SDL debug navigation/pause/actions/resize check --smoke-debug-menu SDL debug navigation/pause/actions/resize check
--smoke-debug-overlay SDL live diagnostics/input/menu/resize check --smoke-debug-overlay SDL live diagnostics/input/menu/resize check
--smoke-window-transitions Persistent window/renderer and widescreen UI check
--verify-assets Decode all original PNG/ASE files --verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more) --smoke-window Test keyboard event/resize (requires --frames 6 or more)
--no-validation Disable development validation --no-validation Disable development validation
@@ -100,6 +109,19 @@ internal static class Program
return 0; return 0;
} }
var root = AssetPath.FindOriginal(Option(args, "--assets")); var root = AssetPath.FindOriginal(Option(args, "--assets"));
if (args.Contains("--smoke-window-transitions"))
{
var preparedCandidates = new List<string>();
if (Option(args, "--scene") is { } explicitScene)
preparedCandidates.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(explicitScene)!, "..")));
preparedCandidates.AddRange([Path.Combine(AppContext.BaseDirectory, "scenes"), "artifacts/extracted"]);
var prepared = preparedCandidates
.FirstOrDefault(p => File.Exists(Path.Combine(p, "ui/ui.json")))
?? throw new DirectoryNotFoundException("Prepare scene/UI assets before window transition check");
var output = Option(args, "--screenshot") is { } capture
? Path.Combine(Path.GetDirectoryName(Path.GetFullPath(capture))!, "window-transitions") : "artifacts/window-transitions";
return WindowTransitionSmoke.Run(presentation, root, Path.GetFullPath(prepared), output, !args.Contains("--no-validation"));
}
var saveOutput = Option(args, "--write-save"); var saveOutput = Option(args, "--write-save");
if (saveOutput != null) if (saveOutput != null)
{ {
@@ -140,17 +162,23 @@ internal static class Program
if (Option(args, "--effects-audio-smoke") is { } effectsManifest) if (Option(args, "--effects-audio-smoke") is { } effectsManifest)
{ {
using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest)); using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest));
// Start transport only after both streams exist, so slow stream
// creation cannot consume the entire baseline before it is sampled.
mixer.SetPaused(true);
mixer.Effect(59, "bars"); mixer.Effect(58); mixer.Effect(59, "bars"); mixer.Effect(58);
var before = mixer.QueuedEffectBytes; var before = mixer.QueuedEffectBytes;
Thread.Sleep(200); mixer.SetPaused(false);
var consumed = mixer.QueuedEffectBytes < before; var consumptionClock = Stopwatch.StartNew();
while (mixer.QueuedEffectBytes >= before && consumptionClock.ElapsedMilliseconds < 3000) Thread.Sleep(20);
var after = mixer.QueuedEffectBytes;
var consumed = before > 0 && after < before;
mixer.Pump(); mixer.Pump();
mixer.StopLoop("bars"); mixer.StopLoop("bars");
var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1; var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1;
mixer.Effect(230); mixer.Effect(230);
var mixed = mixer.EffectCount == 2; var mixed = mixer.EffectCount == 2;
mixer.StopEffects(); mixer.StopEffects();
Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}."); Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}; baseline={before}, after={after}.");
return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2; return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2;
} }
if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest) if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest)
@@ -234,6 +262,7 @@ internal static class Program
var practiceWindowSmoke = args.Contains("--smoke-practice-window"); var practiceWindowSmoke = args.Contains("--smoke-practice-window");
var practiceReturnSmoke = args.Contains("--smoke-practice-return"); var practiceReturnSmoke = args.Contains("--smoke-practice-return");
var debugSmoke = args.Contains("--smoke-debug-menu"); var debugSmoke = args.Contains("--smoke-debug-menu");
var toolsSmoke = args.Contains("--smoke-debug-tools");
var diagnosticsSmoke = args.Contains("--smoke-debug-overlay"); var diagnosticsSmoke = args.Contains("--smoke-debug-overlay");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check"); if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
@@ -266,6 +295,10 @@ internal static class Program
ObjectivePanel? objectivePanel = null; ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase); var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null; LevelTransition? transitionRequest = null;
OriginalSave? debugCheckpointToLoad = null;
OriginalCameraRay? debugCameraRay = null;
var debugCheckpointFile = toolsSmoke ? Path.GetFullPath("artifacts/debug-expansion/checkpoint.tsk")
: Path.Combine(AppContext.BaseDirectory, "debug-checkpoint.tsk");
Vector3 returnRoot = loadedSave?.StoredVector ?? Vector3.Zero; Vector3 returnRoot = loadedSave?.StoredVector ?? Vector3.Zero;
void RequestTransition(LevelTransition request) void RequestTransition(LevelTransition request)
{ {
@@ -283,8 +316,25 @@ internal static class Program
throw new ArgumentException("A scene and matching GAM are required to place an animated player."); throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath); animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase")); var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y) if (walking)
{ LevelCode = level!.Code }; {
var cameraRay = level!.Code is "LV1B" or "VR04" or "LEV1"
? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
debugCameraRay = cameraRay;
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 (carriedPlayer != null)
{
var applied = simulation.ApplyRetainedLevelState(carriedPlayer);
if (applied)
Console.WriteLine($"Retained player scalars: mode={simulation.MovementMode}, hold={simulation.JumpHoldSeconds}, fire={simulation.JetpackRemaining}; jump={simulation.JumpState}, velocity={simulation.Velocity}, speed={simulation.Speed}.");
if (practiceReturnSmoke && (!applied || simulation.MovementMode != carriedPlayer.MovementMode
|| simulation.JumpHoldSeconds != carriedPlayer.HoldSeconds || simulation.JetpackRemaining != carriedPlayer.EffectRemaining
|| simulation.JumpState != 0 || simulation.Speed != 0 || simulation.Velocity != Vector3.Zero || simulation.PendingImpulse != Vector3.Zero))
throw new InvalidOperationException("Retained route scalar/body reset boundary changed");
}
}
if (walking && returning) simulation!.RestoreReturnRoot(returnRoot); if (walking && returning) simulation!.RestoreReturnRoot(returnRoot);
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y); var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model; characterModel = placement.Model;
@@ -303,7 +353,8 @@ internal static class Program
var tasks = new TaskStates(save.Tasks); var tasks = new TaskStates(save.Tasks);
storyTasks = tasks; storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration); director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save, level!.Code); interactions = new SceneInteractions(director, tasks, save);
interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective); objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select; interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy; simulation!.Energy = interactions.Energy;
@@ -354,6 +405,14 @@ internal static class Program
? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [], ? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [],
Path.GetFileName(levelPath), originalStart?.Tag); Path.GetFileName(levelPath), originalStart?.Tag);
if (args.Contains("--debug-menu")) debugMenu.Toggle(storyTasks?.Get("SCENE") ?? 0); if (args.Contains("--debug-menu")) debugMenu.Toggle(storyTasks?.Get("SCENE") ?? 0);
if (Option(args, "--debug-page") is { } debugPage)
{
var page = debugPage.ToLowerInvariant() switch { "general" => 0, "player" => 1, "systems" => 2,
_ => throw new ArgumentException("Debug page must be general, player or systems") };
if (!debugMenu.Open) debugMenu.Toggle(storyTasks?.Get("SCENE") ?? 0);
for (var i = 0; i < page; i++) debugMenu.Key(43);
}
if (args.Contains("--noclip") && simulation != null) simulation.SetNoclip(true);
var debugOverlay = new DebugMenuOverlay(mesh); var debugOverlay = new DebugMenuOverlay(mesh);
mesh = debugOverlay.Mesh; mesh = debugOverlay.Mesh;
Console.WriteLine($"Loaded original geometry and overlays: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures."); Console.WriteLine($"Loaded original geometry and overlays: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
@@ -369,7 +428,9 @@ internal static class Program
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
throw new ArgumentException("Debug tools smoke requires a fresh windowed lab and at least16 frames");
if (debugSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) if (debugSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
throw new ArgumentException("Debug SDL smoke requires fresh windowed LV1B, closed debug menu and at least16 frames"); throw new ArgumentException("Debug SDL smoke requires fresh windowed LV1B, closed debug menu and at least16 frames");
if (diagnosticsSmoke && (headless || frames < 24 || director == null || level?.Code != "LV1B" || loadedSave != null if (diagnosticsSmoke && (headless || frames < 24 || director == null || level?.Code != "LV1B" || loadedSave != null
@@ -386,17 +447,15 @@ internal static class Program
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames."); throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null)) if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null))
throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames."); throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames.");
nint window = 0; var width = uint.Parse(Option(args, "--width") ?? "960");
if (!headless) var height = uint.Parse(Option(args, "--height") ?? "720");
if (width is < 64 or > 8192 || height is < 64 or > 8192) throw new ArgumentException("Viewport dimensions must be64..8192");
var renderer = presentation.LoadScene(mesh, texture, headless,
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
width, height, !args.Contains("--no-validation"));
var window = presentation.Window;
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
{ {
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
window = Sdl.SDL_CreateWindow(walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", 960, 720,
Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity);
if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); }
}
try
{
using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation"));
using var audio = Option(args, "--audio") is { } audioFile using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null; ? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null; using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
@@ -427,13 +486,15 @@ internal static class Program
&& Vector3.Distance(simulation.ActorRoot, returnRoot) < .001f && Vector3.Distance(simulation.ActorRoot, returnRoot) < .001f
&& Vector2.Distance(new(returnRoot.X, returnRoot.Z), new(originalStart!.Position.X, originalStart.Position.Z)) > 100; && Vector2.Distance(new(returnRoot.X, returnRoot.Z), new(originalStart!.Position.X, originalStart.Position.Z)) > 100;
var companionRestored = director.FindActor("C3DGODDARD")?.Position == returnRoot; var companionRestored = director.FindActor("C3DGODDARD")?.Position == returnRoot;
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}."); 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 (!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 (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (practiceReturnSmoke && level.Code == "VR04") if (practiceReturnSmoke && level.Code == "VR04")
{ {
if (interactions!.Inventory.State(0, 3) != 1)
throw new InvalidOperationException("VR04 PostLoad tail did not re-enable its owned practice jetpack");
director.Skip(); director.Skip();
interactions!.Update(level.Entities.First(e => e.Kind == "LOAD").Position); 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"); if (transitionRequest is not { Returning: true }) throw new InvalidOperationException("VR04 exit did not preserve RETURN identity");
@@ -492,14 +553,13 @@ internal static class Program
var keys = new HashSet<uint>(); var keys = new HashSet<uint>();
var debugCapturedKeys = new HashSet<uint>(); var debugCapturedKeys = new HashSet<uint>();
var running = true; var running = true;
var fullscreen = false;
var sawKey = false; var sawKey = false;
var didResize = false; var didResize = false;
var clock = Stopwatch.StartNew(); var clock = Stopwatch.StartNew();
var animationStarted = 0.0; var animationStarted = 0.0;
var animationSwitched = false; var animationSwitched = false;
var inspecting = !walking; var inspecting = !walking;
var active = true; var active = presentation.HasInputFocus;
var mouseJump = false; var mouseJump = false;
var stepClock = new FixedStepClock(); var stepClock = new FixedStepClock();
double poseTime = initialPoseTime; double poseTime = initialPoseTime;
@@ -533,6 +593,8 @@ internal static class Program
var diagnosticsInitialTravel = simulation?.Travel ?? 0; var diagnosticsInitialTravel = simulation?.Travel ?? 0;
var debugPausedRoot = simulation?.ActorRoot ?? Vector3.Zero; var debugPausedRoot = simulation?.ActorRoot ?? Vector3.Zero;
var debugPausedSteps = simulation?.Steps ?? 0; var debugPausedSteps = simulation?.Steps ?? 0;
var toolsPaused = false; var toolsMoved = false; var toolsStopped = false; var toolsSaved = false; var toolsSystems = false;
var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero;
void ResetScene() void ResetScene()
{ {
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; } if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
@@ -589,15 +651,91 @@ internal static class Program
case DebugAction.ToggleOverlay: case DebugAction.ToggleOverlay:
diagnostics.Enabled = !diagnostics.Enabled; diagnostics.Enabled = !diagnostics.Enabled;
debugMenu.Message = $"LIVE OVERLAY {diagnostics.Enabled}; F2 TOGGLE DURING PLAY"; break; debugMenu.Message = $"LIVE OVERLAY {diagnostics.Enabled}; F2 TOGGLE DURING PLAY"; break;
case DebugAction.Noclip when simulation != null:
if (inspecting) ToggleCamera();
var returnedToEntry = simulation.SetNoclip(!simulation.Noclip);
SyncDebugPlayer();
debugMenu.Message = returnedToEntry ? "NOCLIP OFF; INSIDE TERRAIN, RESTORED ENTRY POSITION"
: $"NOCLIP {simulation.Noclip}; F3 TOGGLE, CLOSE MENU TO MOVE";
break;
case DebugAction.NoclipSpeed when simulation != null:
simulation.NoclipSpeed = debugMenu.FlySpeed; debugMenu.Message = "FLY SPEED APPLIED"; break;
case DebugAction.StopMotion when simulation != null:
simulation.StopDebugMotion(); debugMenu.Message = "MOTION AND QUEUED JUMP CLEARED"; break;
case DebugAction.ReturnNoclipEntry when simulation != null:
debugMenu.Message = simulation.ReturnToNoclipEntry() ? "RESTORED NOCLIP ENTRY POSITION" : "ENABLE NOCLIP FIRST";
SyncDebugPlayer(); break;
case DebugAction.ShowObjective when objectivePanel != null:
objectivePanel.Show(); debugMenu.Message = "OBJECTIVE TIMER REOPENED"; break;
case DebugAction.LevelAvailability when interactions != null:
interactions.Inventory.ApplyLevelAvailability(level!.Code); debugMenu.Message = "SOURCE LEVEL AVAILABILITY APPLIED"; break;
case DebugAction.InputOrder when simulation != null:
simulation.InputAfterPlayerUpdate = !simulation.InputAfterPlayerUpdate;
debugMenu.Message = "DEBUG INPUT ORDER TOGGLED; NEW LEVEL RESTORES SOURCE POLICY"; break;
case DebugAction.ApplyJetpackState when interactions != null:
interactions.Inventory.SetState(0, 3, debugMenu.JetpackState); debugMenu.Message = "JET PACK AVAILABILITY APPLIED"; break;
case DebugAction.CameraObstruction when debugCameraRay != null:
debugCameraRay.Enabled = !debugCameraRay.Enabled; debugMenu.Message = "STATIC CAMERA QUERY TOGGLED"; break;
case DebugAction.MuteMusic or DebugAction.MuteSpeech or DebugAction.MuteEffects when sceneAudio != null:
sceneAudio.SetDebugMute(sceneAudio.MusicMuted ^ (action == DebugAction.MuteMusic),
sceneAudio.SpeechMuted ^ (action == DebugAction.MuteSpeech), sceneAudio.EffectsMuted ^ (action == DebugAction.MuteEffects));
debugMenu.Message = "AUDIO MUTE UPDATED; PLAYBACK CLOCK CONTINUES"; break;
case DebugAction.RestartMusic when sceneAudio != null:
sceneAudio.RestartMusic(); debugMenu.Message = "SELECTED MUSIC RESTARTED"; break;
case DebugAction.StopEffects when sceneAudio != null:
sceneAudio.StopEffects(); debugMenu.Message = "ALL EFFECTS AND LOOPS STOPPED"; break;
case DebugAction.Practice when interactions != null:
practice.Show(0); debugMenu.Close(); break;
case DebugAction.SaveCheckpoint when interactions != null:
try
{
var debugSnapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag!, StoredVector = returnRoot };
var temporaryCheckpoint = debugCheckpointFile + ".tmp";
Directory.CreateDirectory(Path.GetDirectoryName(debugCheckpointFile)!);
File.WriteAllBytes(temporaryCheckpoint, debugSnapshot.Encode()); File.Move(temporaryCheckpoint, debugCheckpointFile, true);
debugMenu.Message = "SAVED LEVEL/START/PROGRESSION; NOT LIVE POSITION";
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ debugMenu.Message = "CHECKPOINT WRITE FAILED: " + error.Message; }
break;
case DebugAction.LoadCheckpoint when interactions != null:
try
{
var debugSave = OriginalSave.Load(debugCheckpointFile);
var savedScene = debugMenu.FindScene(debugSave.LevelCode);
if (savedScene == null) { debugMenu.Message = "CHECKPOINT LEVEL GEOMETRY UNAVAILABLE"; break; }
var savedStart = GamLevel.Load(AssetPath.Resolve(root, "gam/" + savedScene.LevelFile))
.FindStart(debugSave.StartPoint.Equals("none", StringComparison.OrdinalIgnoreCase) ? null : debugSave.StartPoint);
if (savedStart == null) { debugMenu.Message = "CHECKPOINT START UNAVAILABLE"; break; }
var savedWorld = Mesh.LoadSceneJson(AssetPath.Resolve(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
Path.GetFileNameWithoutExtension(savedScene.LevelFile) + "/scene.json"));
if (new SceneCollision(savedWorld).GroundHeight(savedStart.Position, 2500) == null)
{ debugMenu.Message = "CHECKPOINT START HAS NO SUPPORTED FLOOR"; break; }
debugCheckpointToLoad = debugSave;
RequestTransition(new(savedScene.LevelFile, savedStart.Tag!, 0, -1)); debugMenu.Close();
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or InvalidDataException)
{ debugMenu.Message = "CHECKPOINT LOAD FAILED: " + error.Message; }
break;
case DebugAction.None: break; case DebugAction.None: break;
case DebugAction.CameraObstruction: debugMenu.Message = "SOURCE STATIC QUERY UNAVAILABLE IN THIS SCENE"; break;
case DebugAction.MuteMusic or DebugAction.MuteSpeech or DebugAction.MuteEffects or DebugAction.RestartMusic or DebugAction.StopEffects:
debugMenu.Message = "SCENE AUDIO UNAVAILABLE (--MUTE / HEADLESS)"; break;
default: debugMenu.Message = "ACTION REQUIRES PLAY MODE"; break; default: debugMenu.Message = "ACTION REQUIRES PLAY MODE"; break;
} }
} }
void SyncDebugPlayer()
{
if (simulation == null) return;
characterModel = simulation.Model;
if (level?.Player?.Tag is { } tag)
director?.SyncActor(tag, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
Vector2 Pointer() Vector2 Pointer()
{ {
Sdl.SDL_GetMouseState(out var x, out var y); Sdl.SDL_GetMouseState(out var x, out var y);
if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero; if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero;
return new(x * 640 / w, y * 480 / h); return new UiViewport(renderer.Width, renderer.Height).InverseModal(new(x, y), (uint)w, (uint)h);
} }
while (running) while (running)
{ {
@@ -634,6 +772,12 @@ internal static class Program
if (e.Repeat == 0) diagnostics.Enabled = !diagnostics.Enabled; if (e.Repeat == 0) diagnostics.Enabled = !diagnostics.Enabled;
continue; continue;
} }
if (e.Type == Sdl.KeyDown && e.Scancode == DebugMenu.NoclipKey)
{
debugCapturedKeys.Add(e.Scancode);
if (e.Repeat == 0) { DebugCommand(DebugAction.Noclip); DebugInputBoundary(); }
continue;
}
if (e.Type == Sdl.KeyDown && e.Scancode == DebugMenu.ToggleKey) if (e.Type == Sdl.KeyDown && e.Scancode == DebugMenu.ToggleKey)
{ {
debugCapturedKeys.Add(e.Scancode); debugCapturedKeys.Add(e.Scancode);
@@ -670,7 +814,8 @@ internal static class Program
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0; if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0;
if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0; if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0;
if (smoke && e.Scancode == 79) sawKey = true; if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false }) if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false }
&& (e.Scancode != 44 || simulation?.Noclip != true))
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; } { sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false; else if (e.Scancode == 41) running = false;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true) if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
@@ -689,8 +834,7 @@ internal static class Program
} }
if (e.Scancode == 68 && e.Repeat == 0) if (e.Scancode == 68 && e.Repeat == 0)
{ {
fullscreen = !fullscreen; presentation.ToggleFullscreen();
if (!Sdl.SDL_SetWindowFullscreen(window, fullscreen)) throw new InvalidOperationException(Sdl.Error);
} }
} }
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode); if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
@@ -700,17 +844,19 @@ internal static class Program
var dt = (float)Math.Min(elapsed, 0.1); var dt = (float)Math.Min(elapsed, 0.1);
last = now; last = now;
if (debugMenu.Open) animationStarted += elapsed; if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke)) if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{ {
var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke ? 1 : stepClock.Advance(elapsed); var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++) for (var step = 0; step < steps; step++)
{ {
var input = carlSmoke ? new PlayerInput(true, false, true, false, true) var input = carlSmoke ? new PlayerInput(true, false, true, false, true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps) : jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( : walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79), keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98)); mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98),
if (director?.Controlled != false) keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20),
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229));
if (director?.Controlled != false || simulation.Noclip)
{ {
var before = simulation.Position; var before = simulation.Position;
var powered = simulation.JetpackEffectVisible && !simulation.Grounded; var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
@@ -722,17 +868,20 @@ internal static class Program
} }
interactions?.UpdateEnergy(simulation.Energy); interactions?.UpdateEnergy(simulation.Energy);
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (!simulation.Noclip)
{
director?.Touch(level!.Player!.Tag!, simulation.ActorRoot); director?.Touch(level!.Player!.Tag!, simulation.ActorRoot);
interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius); interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius);
}
if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; } if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; }
mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius); if (!simulation.Noclip) mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius);
} }
mechanisms?.Step(FixedStepClock.Step); mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step); foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step); director?.Step(FixedStepClock.Step);
objectivePanel?.Key(keys.Contains(18) && director is { Controlled: true, InventoryEnabled: true }); objectivePanel?.Key(keys.Contains(18) && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(FixedStepClock.Step, director?.ControlledTag != null, practice.Active); objectivePanel?.Step(FixedStepClock.Step, director?.ControlledTag != null, practice.Active);
var switched = director is { Controlled: false } var switched = director is { Controlled: false } && !simulation.Noclip
? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation) ? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)
: animations!.SelectPose(simulation.Pose); : animations!.SelectPose(simulation.Pose);
if (switched) poseTime = 0; if (switched) poseTime = 0;
@@ -764,7 +913,7 @@ internal static class Program
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY); view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget; renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget;
} }
if (!inspecting && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget) if (!inspecting && simulation?.Noclip != true && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget)
{ {
view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY); view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY);
renderEye = storyEye; renderTarget = storyTarget; renderEye = storyEye; renderTarget = storyTarget;
@@ -776,9 +925,9 @@ internal static class Program
&& director is { Controlled: true, InventoryEnabled: true }); && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active); objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible, hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible,
practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible); practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height);
var gameplayProjection = originalCamera || simulation != null && !inspecting; var gameplayProjection = originalCamera || simulation != null && !inspecting;
var cameraMode = !inspecting && director?.CameraEye != null ? "CUTSCENE" var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE"
: simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT"; : simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT";
var debugStatus = new DebugStatus(level?.Code ?? "PREVIEW", originalStart?.Tag ?? "NONE", var debugStatus = new DebugStatus(level?.Code ?? "PREVIEW", originalStart?.Tag ?? "NONE",
simulation?.ActorRoot ?? Vector3.Zero, simulation?.Yaw ?? 0, simulation?.Speed ?? 0, simulation?.ActorRoot ?? Vector3.Zero, simulation?.Yaw ?? 0, simulation?.Speed ?? 0,
@@ -786,7 +935,21 @@ internal static class Program
storyTasks?.Get("SCENE") ?? 0, director?.CurrentTag ?? "NONE", director?.Controlled ?? false, storyTasks?.Get("SCENE") ?? 0, director?.CurrentTag ?? "NONE", director?.Controlled ?? false,
(director?.Issues.Count ?? 0) + (interactions?.Unsupported.Count ?? 0) + (mechanisms?.Unsupported.Count ?? 0), (director?.Issues.Count ?? 0) + (interactions?.Unsupported.Count ?? 0) + (mechanisms?.Unsupported.Count ?? 0),
gameplayProjection ? SceneProjection.FarPlane(level?.Code) : radius * 20, gameplayProjection ? SceneProjection.FarPlane(level?.Code) : radius * 20,
inspecting, director?.DebugForceControl ?? false, diagnostics.Enabled, cameraMode); inspecting, director?.DebugForceControl ?? false, diagnostics.Enabled, cameraMode, new DebugSystems
{
Noclip = simulation?.Noclip ?? false, NoclipSpeed = simulation?.NoclipSpeed ?? 600,
Velocity = simulation?.Velocity ?? Vector3.Zero, PendingImpulse = simulation?.PendingImpulse ?? Vector3.Zero,
MovementMode = simulation?.MovementMode ?? 0, InputAfterPlayer = simulation?.InputAfterPlayerUpdate ?? false,
JumpState = simulation?.JumpState ?? 0, JumpHold = simulation?.JumpHoldSeconds ?? 0,
BurnRemaining = simulation?.JetpackRemaining ?? 0, JetpackAvailability = interactions?.Inventory.State(0, 3) ?? 0,
Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0,
CameraObstruction = debugCameraRay?.Enabled, CameraPolygons = debugCameraRay?.PolygonCount ?? 0,
CameraWallPolygons = debugCameraRay?.WallPolygonCount ?? 0, CameraTests = debugCameraRay?.LastTriangleTests ?? 0,
AudioAvailable = sceneAudio != null, MusicMuted = sceneAudio?.MusicMuted ?? false,
SpeechMuted = sceneAudio?.SpeechMuted ?? false, EffectsMuted = sceneAudio?.EffectsMuted ?? false,
MusicBytes = sceneAudio?.QueuedMusicBytes ?? 0, SpeechBytes = sceneAudio?.QueuedSpeechBytes ?? 0,
EffectBytes = sceneAudio?.QueuedEffectBytes ?? 0
});
var debugView = debugMenu.View(debugStatus); var debugView = debugMenu.View(debugStatus);
var liveDebugLines = diagnostics.Lines(debugStatus, new(simulation?.Velocity ?? Vector3.Zero, var liveDebugLines = diagnostics.Lines(debugStatus, new(simulation?.Velocity ?? Vector3.Zero,
simulation?.TurnRate ?? 0, simulation?.Pose.ToString() ?? "NONE", simulation?.Steps ?? 0, simulation?.TurnRate ?? 0, simulation?.Pose.ToString() ?? "NONE", simulation?.Steps ?? 0,
@@ -795,7 +958,8 @@ internal static class Program
renderer.ValidationErrors, debugMenu.Open || practice.Active || inspecting || !active)); renderer.ValidationErrors, debugMenu.Open || practice.Active || inspecting || !active));
var liveDebugVisible = !debugMenu.Open && liveDebugLines.Length > 0; var liveDebugVisible = !debugMenu.Open && liveDebugLines.Length > 0;
debugOverlay.Update(mesh, debugMenu.Open ? debugView.Lines : liveDebugLines, debugOverlay.Update(mesh, debugMenu.Open ? debugView.Lines : liveDebugLines,
debugMenu.Open ? debugView.SelectedLine : -1, compact: !debugMenu.Open); debugMenu.Open ? debugView.SelectedLine : -1, compact: !debugMenu.Open,
viewportWidth: renderer.Width, viewportHeight: renderer.Height);
var projection = gameplayProjection var projection = gameplayProjection
? SceneProjection.CreateGameplay(level?.Code, (float)renderer.Width / renderer.Height) ? SceneProjection.CreateGameplay(level?.Code, (float)renderer.Width / renderer.Height)
: Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20); : Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20);
@@ -814,6 +978,51 @@ internal static class Program
count++; count++;
audio?.Pump(); audio?.Pump();
sceneAudio?.Pump(); sceneAudio?.Pump();
if (toolsSmoke)
{
void PushTool(uint key, bool down = true, bool repeat = false)
{
var e = new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = key,
Down = down ? (byte)1 : (byte)0, Repeat = repeat ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref e)) throw new InvalidOperationException(Sdl.Error);
}
void TapTool(uint key) { PushTool(key); PushTool(key, false); }
if (count == 1) { toolsEntry = simulation!.ActorRoot; TapTool(DebugMenu.ToggleKey); }
if (count == 2) { TapTool(43); TapTool(40); }
if (count == 3)
{
toolsPaused = debugMenu.Open && debugMenu.Page == 1 && simulation!.Noclip
&& simulation.ActorRoot == toolsEntry && sceneAudio?.Paused != false;
director!.Trigger("neutron1a"); // Flight must work without changing scripted control ownership.
TapTool(DebugMenu.ToggleKey); PushTool(26); PushTool(44);
}
if (count == 7)
{
toolsMoved = simulation!.Noclip && simulation.ActorRoot.Y > toolsEntry.Y + 20
&& Vector3.Distance(simulation.ActorRoot, toolsEntry) > 30 && simulation.Jumps == 0
&& director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" };
PushTool(DebugMenu.NoclipKey); PushTool(DebugMenu.NoclipKey, repeat: true); PushTool(DebugMenu.NoclipKey, false);
}
if (count == 8)
{
toolsStopped = !simulation!.Noclip && simulation.PendingImpulse == Vector3.Zero && simulation.Speed == 0 && simulation.Jumps == 0;
PushTool(26, false); PushTool(44, false); TapTool(DebugMenu.ToggleKey);
}
if (count == 9) TapTool(43);
if (count == 10)
{
TapTool(40); TapTool(81); TapTool(40); // Camera query and music mute.
for (var i = 0; i < 5; i++) TapTool(81);
TapTool(40); // Save progression.
}
if (count == 11)
{
toolsSystems = debugMenu.Page == 2 && debugCameraRay?.Enabled == false && sceneAudio?.MusicMuted == true;
toolsSaved = File.Exists(debugCheckpointFile) && OriginalSave.Load(debugCheckpointFile).Tasks.Any(t => t.Name == "SCENE" && t.State == 30);
storyTasks!.SetExisting("SCENE", 35);
TapTool(81); TapTool(40); // Load the saved progression and rebuild through normal continuation.
}
}
if (diagnosticsSmoke) if (diagnosticsSmoke)
{ {
void Push(uint key, bool down = true, bool repeat = false) void Push(uint key, bool down = true, bool repeat = false)
@@ -980,6 +1189,13 @@ internal static class Program
Console.WriteLine($"Debug SDL check: paused={debugPauseObserved}, actions={debugActionsObserved}, Escape/input capture={debugEscapeObserved}, resumed={debugResumeObserved}, forced movement during MCA={debugForceObserved}, resize800x600={didResize}."); Console.WriteLine($"Debug SDL check: paused={debugPauseObserved}, actions={debugActionsObserved}, Escape/input capture={debugEscapeObserved}, resumed={debugResumeObserved}, forced movement during MCA={debugForceObserved}, resize800x600={didResize}.");
if (!debugPauseObserved || !debugActionsObserved || !debugEscapeObserved || !debugResumeObserved || !debugForceObserved || !didResize) return 2; if (!debugPauseObserved || !debugActionsObserved || !debugEscapeObserved || !debugResumeObserved || !debugForceObserved || !didResize) return 2;
} }
if (toolsSmoke)
{
var loaded = debugCheckpointToLoad?.Tasks.Any(t => t.Name == "SCENE" && t.State == 30) == true
&& transitionRequest?.LevelFile.Equals("level1b.gam", StringComparison.OrdinalIgnoreCase) == true;
Console.WriteLine($"Debug tools SDL check: paused={toolsPaused}, flight={toolsMoved}, stop/input capture={toolsStopped}, systems={toolsSystems}, saved={toolsSaved}, loaded={loaded}.");
if (!toolsPaused || !toolsMoved || !toolsStopped || !toolsSystems || !toolsSaved || !loaded) return 2;
}
if (carlSmoke) if (carlSmoke)
{ {
var locked = director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" } && simulation!.Steps == 0; var locked = director is { Controlled: false, Playing: true, CurrentTag: "neutron1a" } && simulation!.Steps == 0;
@@ -1032,14 +1248,21 @@ internal static class Program
for (var i = 0; i < args.Length; i++) for (var i = 0; i < args.Length; i++)
{ {
if (args[i] is "--smoke-transition" or "--smoke-lab-route" or "--smoke-practice-prompt" or "--smoke-practice-transition" if (args[i] is "--smoke-transition" or "--smoke-lab-route" or "--smoke-practice-prompt" or "--smoke-practice-transition"
or "--debug-menu" or "--smoke-debug-menu" or "--smoke-debug-overlay") continue; or "--debug-menu" or "--smoke-debug-menu" or "--smoke-debug-overlay" or "--smoke-debug-tools" or "--noclip") continue;
if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time") { i++; continue; } if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time" or "--debug-page") { i++; continue; }
nextArgs.Add(args[i]); nextArgs.Add(args[i]);
} }
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile, nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]); "--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with { if (toolsSmoke) nextArgs.AddRange(["--frames", "2"]);
StartPoint = transitionRequest.StartPoint, StoredVector = returnRoot }, transitionRequest.Returning); // Deliberate test sentinels after the last departure tick: the
// destination assertion observes loader state, before grounding
// or controller/fire callbacks can legitimately change it.
if (practiceReturnSmoke && simulation != null)
simulation.ApplyRetainedLevelState(new(level!.Code, 3, 1, .625f, 6.125f));
continuation = new(nextArgs.ToArray(), (debugCheckpointToLoad ?? interactions!.Snapshot()) with {
StartPoint = transitionRequest.StartPoint, StoredVector = debugCheckpointToLoad?.StoredVector ?? returnRoot }, transitionRequest.Returning,
debugCheckpointToLoad == null ? simulation?.CaptureLevelState(interactions!.Inventory.SelectedGadget) : null);
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed."); Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
} }
if (walkSmoke && !simulation!.SmokePassed) return 2; if (walkSmoke && !simulation!.SmokePassed) return 2;
@@ -1066,10 +1289,6 @@ internal static class Program
} }
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0; return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
} }
finally
{
if (window != 0) { Sdl.SDL_DestroyWindow(window); Sdl.SDL_Quit(); }
}
} }
private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | F1 menu | F2 overlay | R reset | C inspect"; private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | F1 menu | F2 overlay | R reset | C inspect";
+163 -16
View File
@@ -36,7 +36,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
private Sampler sampler; private Sampler sampler;
private readonly List<Texture> textures=[]; private readonly List<Texture> textures=[];
private readonly Dictionary<int,DescriptorSet> descriptors=[]; private readonly Dictionary<int,DescriptorSet> descriptors=[];
private readonly Mesh mesh; private Mesh mesh;
private readonly nint window; private readonly nint window;
private SurfaceKHR surface; private SurfaceKHR surface;
private KhrSurface? surfaceApi; private KhrSurface? surfaceApi;
@@ -52,8 +52,14 @@ public sealed unsafe class VulkanRenderer : IDisposable
public int ValidationErrors { get; private set; } public int ValidationErrors { get; private set; }
public uint Width=>width; public uint Width=>width;
public uint Height=>height; public uint Height=>height;
public int SceneRevision { get; private set; }
public RendererIdentity Identity => new(unchecked((ulong)instance.Handle), unchecked((ulong)device.Handle),
surface.Handle, swapchain.Handle, pipeline.Handle, pipelineLayout.Handle, descriptorLayout.Handle);
private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View); private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View);
private sealed record SceneResources(Mesh Mesh, Buffer VertexBuffer, DeviceMemory VertexMemory,
Buffer IndexBuffer, DeviceMemory IndexMemory, DescriptorPool DescriptorPool, Sampler Sampler,
Texture[] Textures, KeyValuePair<int,DescriptorSet>[] Descriptors);
private static void Check(Result result,string operation) private static void Check(Result result,string operation)
{if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");} {if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");}
@@ -63,6 +69,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
debugCallback=OnValidation; debugCallback=OnValidation;
try try
{ {
ValidateScene(mesh,texture);
CreateInstance(validation); CreateInstance(validation);
if(window!=0) if(window!=0)
{ {
@@ -81,10 +88,97 @@ public sealed unsafe class VulkanRenderer : IDisposable
CreatePipeline(); CreatePipeline();
if(window!=0)CreateSwapchain(); if(window!=0)CreateSwapchain();
CreateTarget(); CreateTarget();
SceneRevision=1;
} }
catch{Dispose();throw;} catch{Dispose();throw;}
} }
/// <summary>
/// Replace only scene buffers/textures/descriptors. The renderer, SDL surface,
/// pipelines, swapchain and current render target remain alive. Staging keeps
/// the previous scene usable if allocation/upload of the replacement fails.
/// </summary>
public void ReplaceScene(Mesh replacement,PngImage fallback)
{
ObjectDisposedException.ThrowIf(device.Handle==0,this);
ValidateScene(replacement,fallback);
Check(vk.DeviceWaitIdle(device),"ReplaceSceneWaitIdle");
var previous=DetachScene();
mesh=replacement;
try
{
UploadBuffers();
CreateDescriptors(fallback);
}
catch
{
vk.DeviceWaitIdle(device);
DestroySceneResources();
RestoreScene(previous);
throw;
}
DestroySceneResources(previous);
SceneRevision++;
}
private static void ValidateScene(Mesh mesh,PngImage fallback)
{
ArgumentNullException.ThrowIfNull(mesh);
ArgumentNullException.ThrowIfNull(fallback);
if(mesh.Vertices.Length==0 || mesh.Indices.Length==0 || mesh.Indices.Length%3!=0
|| mesh.Indices.Any(i=>i>=mesh.Vertices.Length))
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
ValidateTexture(fallback);
foreach(var image in mesh.Textures.Values)ValidateTexture(image);
static void ValidateTexture(PngImage image)
{
ArgumentNullException.ThrowIfNull(image);
if(image.Width is 0 or >8192 || image.Height is 0 or >8192
|| (long)image.Width*image.Height*4!=image.Rgba.LongLength)
throw new ArgumentException("Scene texture has invalid dimensions or RGBA length.",nameof(image));
}
}
private SceneResources DetachScene()
{
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
descriptorPool,sampler,textures.ToArray(),descriptors.ToArray());
vertexBuffer=default;vertexMemory=default;indexBuffer=default;indexMemory=default;
descriptorPool=default;sampler=default;textures.Clear();descriptors.Clear();
return scene;
}
private void RestoreScene(SceneResources scene)
{
mesh=scene.Mesh;
vertexBuffer=scene.VertexBuffer;vertexMemory=scene.VertexMemory;
indexBuffer=scene.IndexBuffer;indexMemory=scene.IndexMemory;
descriptorPool=scene.DescriptorPool;sampler=scene.Sampler;
textures.AddRange(scene.Textures);
foreach(var entry in scene.Descriptors)descriptors.Add(entry.Key,entry.Value);
}
private void DestroySceneResources() => DestroySceneResources(DetachScene());
private void DestroySceneResources(SceneResources scene)
{
if(scene.DescriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,scene.DescriptorPool,null);
if(scene.Sampler.Handle!=0)vk.DestroySampler(device,scene.Sampler,null);
foreach(var texture in scene.Textures)
{
vk.DestroyImageView(device,texture.View,null);
vk.DestroyImage(device,texture.Image,null);
vk.FreeMemory(device,texture.Memory,null);
}
if(scene.VertexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.VertexBuffer,null);
if(scene.VertexMemory.Handle!=0)vk.FreeMemory(device,scene.VertexMemory,null);
if(scene.IndexBuffer.Handle!=0)vk.DestroyBuffer(device,scene.IndexBuffer,null);
if(scene.IndexMemory.Handle!=0)vk.FreeMemory(device,scene.IndexMemory,null);
}
private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user) private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user)
{ {
if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++; if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++;
@@ -177,6 +271,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
throw new NotSupportedException($"No memory type for {flags}."); throw new NotSupportedException($"No memory type for {flags}.");
} }
private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory) private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory)
{
buffer=default;memory=default;
try
{ {
var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive}; var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive};
Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer"); Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer");
@@ -185,6 +282,14 @@ public sealed unsafe class VulkanRenderer : IDisposable
Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory"); Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory");
Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory"); Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory");
} }
catch
{
if(buffer.Handle!=0)vk.DestroyBuffer(device,buffer,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
buffer=default;memory=default;
throw;
}
}
private void UploadBuffers() private void UploadBuffers()
{ {
var vertexBytes=MemoryMarshal.AsBytes(mesh.Vertices.AsSpan()); var vertexBytes=MemoryMarshal.AsBytes(mesh.Vertices.AsSpan());
@@ -203,9 +308,13 @@ public sealed unsafe class VulkanRenderer : IDisposable
private void CopyToMemory(DeviceMemory memory,ReadOnlySpan<byte> bytes) private void CopyToMemory(DeviceMemory memory,ReadOnlySpan<byte> bytes)
{ {
void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory"); void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory");
bytes.CopyTo(new Span<byte>(data,bytes.Length));vk.UnmapMemory(device,memory); try{bytes.CopyTo(new Span<byte>(data,bytes.Length));}
finally{vk.UnmapMemory(device,memory);}
} }
private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view) private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view)
{
image=default;memory=default;view=default;
try
{ {
var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined}; var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined};
Check(vk.CreateImage(device,&info,null,out image),"CreateImage"); Check(vk.CreateImage(device,&info,null,out image),"CreateImage");
@@ -215,6 +324,15 @@ public sealed unsafe class VulkanRenderer : IDisposable
var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)}; var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)};
Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView"); Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView");
} }
catch
{
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
if(image.Handle!=0)vk.DestroyImage(device,image,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
image=default;memory=default;view=default;
throw;
}
}
private void Begin() private void Begin()
{ {
Check(vk.ResetCommandBuffer(command,0),"ResetCommandBuffer"); Check(vk.ResetCommandBuffer(command,0),"ResetCommandBuffer");
@@ -234,21 +352,39 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
private Texture UploadTexture(PngImage image) private Texture UploadTexture(PngImage image)
{ {
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out var staging,out var memory); Buffer staging=default;DeviceMemory memory=default;
Image texture=default;DeviceMemory textureMemory=default;ImageView view=default;
try
{
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out staging,out memory);
CopyToMemory(memory,image.Rgba); CopyToMemory(memory,image.Rgba);
MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out var texture,out var textureMemory,out var view); MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out texture,out textureMemory,out view);
Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit); Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)}; var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)};
vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,&copy); vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,&copy);
Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit(); Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit();
vk.DestroyBuffer(device,staging,null);vk.FreeMemory(device,memory,null); var result=new Texture(texture,textureMemory,view);
var result=new Texture(texture,textureMemory,view);textures.Add(result);return result; textures.Add(result);
texture=default;textureMemory=default;view=default;
return result;
}
finally
{
if(staging.Handle!=0)vk.DestroyBuffer(device,staging,null);
if(memory.Handle!=0)vk.FreeMemory(device,memory,null);
if(view.Handle!=0)vk.DestroyImageView(device,view,null);
if(texture.Handle!=0)vk.DestroyImage(device,texture,null);
if(textureMemory.Handle!=0)vk.FreeMemory(device,textureMemory,null);
}
} }
private void CreateDescriptors(PngImage fallback) private void CreateDescriptors(PngImage fallback)
{
if(descriptorLayout.Handle==0)
{ {
var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit}; var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit};
var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding}; var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding};
Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout"); Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout");
}
var count=(uint)mesh.Textures.Count+1; var count=(uint)mesh.Textures.Count+1;
var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count); var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count);
var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size}; var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size};
@@ -328,9 +464,17 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
private void DestroyTarget() private void DestroyTarget()
{ {
vk.DestroyFramebuffer(device,framebuffer,null);vk.DestroyImageView(device,colorView,null);vk.DestroyImageView(device,depthView,null); if(framebuffer.Handle!=0)vk.DestroyFramebuffer(device,framebuffer,null);
vk.DestroyImage(device,color,null);vk.DestroyImage(device,depth,null);vk.FreeMemory(device,colorMemory,null);vk.FreeMemory(device,depthMemory,null); if(colorView.Handle!=0)vk.DestroyImageView(device,colorView,null);
vk.DestroyBuffer(device,readback,null);vk.FreeMemory(device,readbackMemory,null); if(depthView.Handle!=0)vk.DestroyImageView(device,depthView,null);
if(color.Handle!=0)vk.DestroyImage(device,color,null);
if(depth.Handle!=0)vk.DestroyImage(device,depth,null);
if(colorMemory.Handle!=0)vk.FreeMemory(device,colorMemory,null);
if(depthMemory.Handle!=0)vk.FreeMemory(device,depthMemory,null);
if(readback.Handle!=0)vk.DestroyBuffer(device,readback,null);
if(readbackMemory.Handle!=0)vk.FreeMemory(device,readbackMemory,null);
framebuffer=default;colorView=default;depthView=default;color=default;depth=default;
colorMemory=default;depthMemory=default;readback=default;readbackMemory=default;
} }
private void CreateSwapchain() private void CreateSwapchain()
{ {
@@ -352,7 +496,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
{ {
if(window==0)return; if(window==0)return;
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return; Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return;
Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();swapApi!.DestroySwapchain(device,swapchain,null);CreateSwapchain();CreateTarget(); Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();
swapApi!.DestroySwapchain(device,swapchain,null);swapchain=default;swapImages=[];
CreateSwapchain();CreateTarget();
} }
public void Render(Matrix4x4 mvp) public void Render(Matrix4x4 mvp)
{ {
@@ -416,17 +562,13 @@ public sealed unsafe class VulkanRenderer : IDisposable
if(device.Handle!=0) if(device.Handle!=0)
{ {
vk.DeviceWaitIdle(device); vk.DeviceWaitIdle(device);
if(framebuffer.Handle!=0)DestroyTarget(); DestroyTarget();
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null); if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null); if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null); if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null); if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null); DestroySceneResources();
if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null); if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null);
if(sampler.Handle!=0)vk.DestroySampler(device,sampler,null);
foreach(var t in textures){vk.DestroyImageView(device,t.View,null);vk.DestroyImage(device,t.Image,null);vk.FreeMemory(device,t.Memory,null);}
if(vertexBuffer.Handle!=0)vk.DestroyBuffer(device,vertexBuffer,null);if(vertexMemory.Handle!=0)vk.FreeMemory(device,vertexMemory,null);
if(indexBuffer.Handle!=0)vk.DestroyBuffer(device,indexBuffer,null);if(indexMemory.Handle!=0)vk.FreeMemory(device,indexMemory,null);
if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null); if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null);
if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null); if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null);
if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null); if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null);
@@ -438,3 +580,8 @@ public sealed unsafe class VulkanRenderer : IDisposable
vk.Dispose(); vk.Dispose();
} }
} }
/// <summary>Presentation/device identities for transition verification; swapchain
/// identity may legitimately change on resize, unlike device and surface.</summary>
public readonly record struct RendererIdentity(ulong Instance,ulong Device,ulong Surface,
ulong Swapchain,ulong Pipeline,ulong PipelineLayout,ulong DescriptorLayout);
+22
View File
@@ -78,6 +78,28 @@ using (var scene = new SceneAudio(new PreparedEntityResources(manifest)))
} }
Console.WriteLine("PASS mixer pauses all stream categories and preserves pause across replacement streams"); Console.WriteLine("PASS mixer pauses all stream categories and preserves pause across replacement streams");
using (var muted = new SdlAudio(wave, muted: true))
{
var queued = muted.QueuedBytes;
Require(muted.Muted && !muted.Paused, "Muted audio remains running");
Thread.Sleep(200);
Require(muted.QueuedBytes < queued, "Mute must advance transport rather than freeze obsolete speech");
muted.SetMuted(false); Require(!muted.Muted, "Mute toggle restores gain");
}
using (var scene = new SceneAudio(new PreparedEntityResources(manifest)))
{
scene.SetDebugMute(true, true, true); scene.SetPaused(true);
scene.Music("music.omt", 0); scene.Speech("voice.omt", 1); scene.Effect(58);
var queued = Queued(scene);
scene.SetPaused(false);
Require(scene.MusicMuted && scene.SpeechMuted && scene.EffectsMuted, "Menu resume preserves category mute preferences");
Thread.Sleep(200);
var after = Queued(scene);
Require(after.Music < queued.Music && after.Speech < queued.Speech && after.Effects < queued.Effects,
"Muted categories consume audio after menu resume");
}
Console.WriteLine("PASS muted transport advances and category settings survive menu pause/new streams");
var disposed = new SdlAudio(wave, paused: true); var disposed = new SdlAudio(wave, paused: true);
disposed.Dispose(); disposed.Dispose(); disposed.Dispose(); disposed.Dispose();
try { disposed.SetPaused(false); throw new InvalidOperationException("Expected disposed-state rejection"); } try { disposed.SetPaused(false); throw new InvalidOperationException("Expected disposed-state rejection"); }
@@ -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.
+6
View File
@@ -32,12 +32,18 @@ Require(newGame.LevelCode == "LV1B" && newGame.StartPoint == "STARTEXP", "Wrong
var tasks = new TaskStates(newGame.Tasks); var tasks = new TaskStates(newGame.Tasks);
Require(tasks.Get("scene") == 30 && tasks.Get("missing") == 0, "Original task query semantics differ"); Require(tasks.Get("scene") == 30 && tasks.Get("missing") == 0, "Original task query semantics differ");
var assignments = 0; var assignments = 0;
var assignmentPhases = new List<string>();
tasks.Assigning += (name, value) => assignmentPhases.Add($"before:{tasks.Get(name)}:{value}");
tasks.Assigned += (name, value) => assignmentPhases.Add($"after:{tasks.Get(name)}:{value}");
tasks.Assigned += (_, _) => assignments++; tasks.Assigned += (_, _) => assignments++;
tasks.SetExisting("ScEnE", 35); tasks.SetExisting("ScEnE", 35);
tasks.SetExisting("missing", 77); tasks.SetExisting("missing", 77);
tasks.SetExisting("SCENE", 35); tasks.SetExisting("SCENE", 35);
Require(tasks.Get("SCENE") == 35 && tasks.Get("missing") == 0 && tasks.Snapshot().Length == 12 && assignments == 3, Require(tasks.Get("SCENE") == 35 && tasks.Get("missing") == 0 && tasks.Snapshot().Length == 12 && assignments == 3,
"Task assignment must broadcast without creating missing entries"); "Task assignment must broadcast without creating missing entries");
Require(assignmentPhases.SequenceEqual(new[] { "before:30:35", "after:35:35", "before:0:77",
"after:0:77", "before:35:35", "after:35:35" }),
"Objective phase must see old records, entity phase new records, including repeated/missing assignments");
var changed = newGame with { Score = 15, Tasks = tasks.Snapshot() }; var changed = newGame with { Score = 15, Tasks = tasks.Snapshot() };
Require(OriginalSave.Parse(changed.Encode()).Score == 15 && OriginalSave.Parse(changed.Encode()).Tasks[3].State == 35, Require(OriginalSave.Parse(changed.Encode()).Score == 15 && OriginalSave.Parse(changed.Encode()).Tasks[3].State == 35,
"Modified original save did not persist recovered fields"); "Modified original save did not persist recovered fields");
@@ -50,13 +50,13 @@ try { lines = diagnostics.Lines(status, motion); }
finally { CultureInfo.CurrentCulture = originalCulture; } finally { CultureInfo.CurrentCulture = originalCulture; }
Require(lines.Length == 12 && lines.All(l => l.Length <= 58), "Live diagnostics fit the compact overlay bounds"); Require(lines.Length == 12 && lines.All(l => l.Length <= 58), "Live diagnostics fit the compact overlay bounds");
Require(lines[2].Contains("76.5") && lines[2].Contains("-3.5") && !lines.Any(l => l.Contains("NEG")), "Numeric output is invariant under user culture"); Require(lines[2].Contains("76.5") && lines[2].Contains("-3.5") && !lines.Any(l => l.Contains("NEG")), "Numeric output is invariant under user culture");
Require(lines[6] == "CTRL T FORCE F PAUSED F", "Control and pause diagnostics use live state"); Require(lines[6] == "CTRL T FORCE F PAUSED F NOCLIP F", "Control, pause and noclip diagnostics use live state");
Require(lines[7].Contains("SCENE 60 SCORE 150 JETPACK 1 7.5S"), "Task, score, ownership and burst countdown are visible together"); Require(lines[7].Contains("SCENE 60 SCORE 150 JETPACK 1 7.5S"), "Task, score, ownership and burst countdown are visible together");
var changedStatus = status with { Root = new(40, 50, 60), ForcedControl = true, Inspecting = true, Cutscene = "neutron1a" }; var changedStatus = status with { Root = new(40, 50, 60), ForcedControl = true, Inspecting = true, Cutscene = "neutron1a", Systems = new() { Noclip = true } };
var changedMotion = motion with { Velocity = new(0, 500, 0), Pose = "FLY", Shot = 2, Blocked = true, Paused = true, VulkanErrors = 3 }; var changedMotion = motion with { Velocity = new(0, 500, 0), Pose = "FLY", Shot = 2, Blocked = true, Paused = true, VulkanErrors = 3 };
var changed = diagnostics.Lines(changedStatus, changedMotion); var changed = diagnostics.Lines(changedStatus, changedMotion);
Require(changed[2] != lines[2] && changed[3] != lines[3] && changed[5].Contains("FLY"), "Motion and position text changes with every live snapshot"); Require(changed[2] != lines[2] && changed[3] != lines[3] && changed[5].Contains("FLY"), "Motion and position text changes with every live snapshot");
Require(changed[6] == "CTRL T FORCE T PAUSED T" && changed[8].Contains("ORBIT") && changed[9].Contains("neutron1a SHOT 2 BLOCK T") Require(changed[6] == "CTRL T FORCE T PAUSED T NOCLIP T" && changed[8].Contains("ORBIT") && changed[9].Contains("neutron1a SHOT 2 BLOCK T")
&& changed[11].Contains("VK ERR 3"), "Force/camera/cutscene/block/Vulkan diagnostics stay independent"); && changed[11].Contains("VK ERR 3"), "Force/camera/cutscene/block/Vulkan diagnostics stay independent");
var authoredView = diagnostics.Lines(changedStatus with { CameraMode = "STRT", FarPlane = 5000 }, changedMotion); var authoredView = diagnostics.Lines(changedStatus with { CameraMode = "STRT", FarPlane = 5000 }, changedMotion);
Require(authoredView[8] == "CAM STRT FAR 5000.0", "Actual rendered camera/projection can override inferred mode"); Require(authoredView[8] == "CAM STRT FAR 5000.0", "Actual rendered camera/projection can override inferred mode");
+25
View File
@@ -41,6 +41,31 @@ menu.Toggle(65);
Require(menu.SceneTask == 65, "Reopening refreshes live task state"); Require(menu.SceneTask == 65, "Reopening refreshes live task state");
Console.WriteLine("PASS debug navigation, input repeat, staged tasks, scene/start selection and view"); Console.WriteLine("PASS debug navigation, input repeat, staged tasks, scene/start selection and view");
menu.Key(43);
Require(menu.Page == 1 && menu.Selected == 0 && menu.Key(40) == DebugAction.Noclip, "Tab reaches player tools and noclip");
menu.Key(43, true); Require(menu.Page == 1, "Tab repeat cannot change pages");
menu.Key(81); menu.Key(79);
Require(menu.FlySpeed == 1200 && menu.Key(40) == DebugAction.NoclipSpeed, "Fly speed is bounded and staged");
for (var i = 0; i < 6; i++) menu.Key(81);
menu.Key(79); Require(menu.JetpackState == 4, "Jetpack ownership/availability editor includes disabled state");
menu.Key(81); Require(menu.Key(40) == DebugAction.ApplyJetpackState, "Availability requires explicit apply");
menu.Key(43);
Require(menu.Page == 2 && menu.Selected == 0 && menu.Key(40) == DebugAction.CameraObstruction, "Systems page exposes existing static ray");
for (var i = 0; i < 6; i++) menu.Key(81);
Require(menu.Key(40) == DebugAction.SaveCheckpoint, "Systems checkpoint save action");
menu.Key(81); Require(menu.Key(40) == DebugAction.LoadCheckpoint, "Systems checkpoint load action");
for (var page = 0; page < 3; page++)
{
var pageView = menu.View(new("LV1B", "STARTEXP", Vector3.Zero, 0, 0, true, 20, 0, 30, "NONE", true, 0, 10000, false));
Require(pageView.Lines.Length <= 32 && pageView.SelectedLine >= 0 && pageView.SelectedLine < pageView.Lines.Length,
"Every menu page fits the fixed widescreen-aware overlay");
menu.Key(43);
}
menu.Key(43); // Return from systems to general.
Require(menu.Page == 0, "Tab cycles all three pages");
Require(menu.FindScene("VR04")?.LevelFile == "VR04.gam" && menu.FindScene("MISSING") == null, "Checkpoint resolution only uses prepared catalog");
Console.WriteLine("PASS paged player/systems tools, noclip, staged settings and bounded overlay views");
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original"); var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var catalog = DebugMenu.AvailableScenes(original, Path.GetFullPath("artifacts/extracted")); var catalog = DebugMenu.AvailableScenes(original, Path.GetFullPath("artifacts/extracted"));
Require(catalog.Length == 33 && catalog.All(s => s.Starts.Length > 0), "Only33 supplied scenes with prepared geometry are offered"); Require(catalog.Length == 33 && catalog.All(s => s.Starts.Length > 0), "Only33 supplied scenes with prepared geometry are offered");
@@ -5,5 +5,6 @@
<Compile Include="../../src/GamePort/Assets/Mesh.cs"/> <Compile Include="../../src/GamePort/Assets/Mesh.cs"/>
<Compile Include="../../src/GamePort/Assets/PngImage.cs"/> <Compile Include="../../src/GamePort/Assets/PngImage.cs"/>
<Compile Include="../../src/GamePort/Application/DebugMenuOverlay.cs"/> <Compile Include="../../src/GamePort/Application/DebugMenuOverlay.cs"/>
<Compile Include="../../src/GamePort/Application/UiViewport.cs"/>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -26,6 +26,28 @@ Check(final.Draws.Skip(1).Count(d => d.Visible) == 3, "Live panel has no selecte
overlay.Update(final, ["Menu", "Resume", "Camera"], 1); overlay.Update(final, ["Menu", "Resume", "Camera"], 1);
Check(final.Vertices[2].Position.X == menuRight && final.Vertices[3].Position.Y == menuBottom, Check(final.Vertices[2].Position.X == menuRight && final.Vertices[3].Position.Y == menuBottom,
"Returning to menu restores its full layout using the same buffers"); "Returning to menu restores its full layout using the same buffers");
foreach (var (width, height) in new[] { (1920u, 1080u), (3440u, 1440u), (3840u, 1080u), (1080u, 1920u) })
{
Vector2 Pixel(int index)
{
var p = final.Vertices[index].Position;
return new((p.X + 1) * width / 2, (p.Y + 1) * height / 2);
}
var viewport = new UiViewport(width, height);
overlay.Update(final, ["Menu", "Resume", "Camera"], 1, viewportWidth: width, viewportHeight: height);
var backgroundLeft = Pixel(1).X; var backgroundRight = Pixel(2).X;
Check(MathF.Abs((backgroundLeft + backgroundRight) / 2 - width / 2f) < .003f,
"F1 panel centers in the wide physical viewport");
var character = Pixel(9);
Check(MathF.Abs((Pixel(10).X - character.X) / 7 - (Pixel(12).Y - character.Y) / 9.8f) < .0001f,
"F1 glyphs retain equal X/Y scale");
overlay.Update(final, ["F2 LIVE DEBUG", "ROOT X 10 Y 20 Z 30"], compact: true, viewportWidth: width, viewportHeight: height);
Check(Vector2.Distance(Pixel(1), new Vector2(8 * viewport.Scale)) < .003f,
"F2 remains at the uniform top-left safe inset");
character = Pixel(9);
Check(MathF.Abs((Pixel(10).X - character.X) / 5.6f - (Pixel(12).Y - character.Y) / 7.84f) < .0001f,
"F2 glyphs are never stretched across widescreen");
}
overlay.Update(final, [new string('X', 100)], -1); overlay.Update(final, [new string('X', 100)], -1);
Check(final.Draws.Skip(1).Count(d => d.Visible) == 2, "Long labels clip to bounded text range"); Check(final.Draws.Skip(1).Count(d => d.Visible) == 2, "Long labels clip to bounded text range");
overlay.Update(final, []); overlay.Update(final, []);
+39
View File
@@ -7,6 +7,45 @@ using GamePort.Application;
var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original"); var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var level = GamLevel.Load(AssetPath.Resolve(root,"gam/level1b.gam")); var level = GamLevel.Load(AssetPath.Resolve(root,"gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(root,"NewGame.tsk")); var save = OriginalSave.Load(AssetPath.Resolve(root,"NewGame.tsk"));
// Original Carl413F30 owns its complete base+derived task callback. Observers
// must never see a generic-only Carl state or wait for SceneInteractions to fix it.
var orderedTasks = new TaskStates(save.Tasks);
var orderedDirector = new SceneDirector(level, orderedTasks, (_, _) => 1);
var orderedCarl = orderedDirector.FindActor("C3DCARL")!;
var orderedMarker = orderedDirector.FindActor("CARLESC3")!;
var notifiedCarl = false;
var notifiedAfterCarl = false;
orderedDirector.ActorChanged += actor =>
{
if (ReferenceEquals(actor, orderedCarl))
{
Check(orderedTasks.Get("SCENE") == 50 && actor.Active && actor.Visible && actor.AIstate == 6
&& actor.Position == orderedMarker.Position, "Carl callback observer sees final derived state");
notifiedCarl = true;
}
else if (notifiedCarl)
{
Check(orderedCarl.Position == orderedMarker.Position && orderedCarl.AIstate == 6,
"Later actor callbacks observe completed Carl override");
notifiedAfterCarl = true;
}
};
orderedCarl.Position = Vector3.Zero; orderedCarl.AIstate = 0;
orderedTasks.SetExisting("SCENE", 50);
Check(notifiedCarl && notifiedAfterCarl, "Authored registry includes Carl followed by task actors");
foreach (var scene in new[] { -1, 0, 30, 31, 59, 60, 61 })
{
var boundaryTasks = new TaskStates(save.Tasks.Select(t => t.Name == "SCENE" ? t with { State = scene } : t));
var boundaryDirector = new SceneDirector(level, boundaryTasks, (_, _) => 1);
var actor = boundaryDirector.FindActor("C3DCARL")!;
var generic = TaskActivation.Animated(actor.SourceGam!, scene);
Check(actor.Active == (scene is >= 0 and < 60 || scene == 60 && generic != false),
"LV1B Carl derived activation boundaries and generic result at60");
if (scene is > 30 and <= 60)
Check(actor.AIstate == 6 && actor.Position == boundaryDirector.FindActor("CARLESC3")!.Position,
"Carl marker/state override follows base activation at construction");
}
Console.WriteLine("PASS per-actor Carl task callback order, derived observation and LV1B boundaries");
var tasks = new TaskStates(save.Tasks); var tasks = new TaskStates(save.Tasks);
var director = new SceneDirector(level,tasks,(_,_)=>.1); var director = new SceneDirector(level,tasks,(_,_)=>.1);
var cues = 0; var cues = 0;
@@ -5,6 +5,7 @@
<Compile Include="../../src/GamePort/Assets/Mesh.cs"/> <Compile Include="../../src/GamePort/Assets/Mesh.cs"/>
<Compile Include="../../src/GamePort/Assets/PngImage.cs"/> <Compile Include="../../src/GamePort/Assets/PngImage.cs"/>
<Compile Include="../../src/GamePort/Application/SceneHud.cs"/> <Compile Include="../../src/GamePort/Application/SceneHud.cs"/>
<Compile Include="../../src/GamePort/Application/UiViewport.cs"/>
<Compile Include="../../src/GamePort/Game/ObjectivePanel.cs"/> <Compile Include="../../src/GamePort/Game/ObjectivePanel.cs"/>
</ItemGroup> </ItemGroup>
</Project> </Project>
+21
View File
@@ -50,6 +50,27 @@ try
Check(final.Draws.Skip(1).All(d => !d.Visible), "Timed-out objective has no remaining overlay draw"); Check(final.Draws.Skip(1).All(d => !d.Visible), "Timed-out objective has no remaining overlay draw");
panel.Key(true); panel.Step(1); PresentPanel(); panel.Key(true); panel.Step(1); PresentPanel();
Check(final.Draws.Skip(1).Count(d => d.Visible) == 3, "O reopens timed-out panel through the timer"); Check(final.Draws.Skip(1).Count(d => d.Visible) == 3, "O reopens timed-out panel through the timer");
foreach (var (width, height) in new[] { (1920u, 1080u), (3440u, 1440u), (3840u, 1080u), (1080u, 1920u) })
{
hud.Update(final, 1, true, true, viewportWidth: width, viewportHeight: height);
var viewport = new UiViewport(width, height);
Vector2 Pixel(int index)
{
var p = final.Vertices[index].Position;
return new((p.X + 1) * width / 2, (p.Y + 1) * height / 2);
}
var pad = Pixel(1); var modal = Pixel(29);
Check(Vector2.Distance(pad, new(width - 256 * viewport.Scale, height - 169 * viewport.Scale)) < .003f,
"Objective pad remains bottom/right anchored");
var modalExpected = (new Vector2(210, 210) + viewport.CenterOffset) * viewport.Scale;
Check(Vector2.Distance(modal, modalExpected) < .003f, "Modal shifts with centered authored canvas");
Check(MathF.Abs((Pixel(30).X - modal.X) / 207 - (Pixel(32).Y - modal.Y) / 100) < .0001f,
"Original modal art has equal physical X/Y scale");
Check(MathF.Abs((Pixel(2).X - pad.X) / 320 - (Pixel(4).Y - pad.Y) / 173) < .0001f,
"Objective pad is never stretched in widescreen");
}
hud.Update(final, 2, true, true);
Near(final.Vertices[1].Position, new(.2f, 2*311f/480-1, 0), "Returning to4:3 restores source positions");
Reject(() => hud.Update(source, 1, true, false), "Missing final ranges"); Reject(() => hud.Update(source, 1, true, false), "Missing final ranges");
Reject(() => hud.Update(final, 1, true, false, float.NaN), "Nonfinite HUD offset"); Reject(() => hud.Update(final, 1, true, false, float.NaN), "Nonfinite HUD offset");
File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, width=e.id==120 ? 0 : e.width, e.height, e.path }))); File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, width=e.id==120 ? 0 : e.width, e.height, e.path })));
@@ -9,6 +9,7 @@
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/> <Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/> <Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/> <Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/> <Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/> <Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/> <Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
+52 -10
View File
@@ -10,7 +10,7 @@ var lab = GamLevel.Load(AssetPath.Resolve(root, "gam/level1b.gam"));
var counter = 1; var counter = 1;
var tasks = new TaskStates(original.Tasks); var tasks = new TaskStates(original.Tasks);
var director = new SceneDirector(lab, tasks, (_, _) => 5); var director = new SceneDirector(lab, tasks, (_, _) => 5);
var interactions = new SceneInteractions(director, tasks, original, lab.Code); var interactions = new SceneInteractions(director, tasks, original);
director.Begin(lab.FindStart()!); director.Begin(lab.FindStart()!);
interactions.Reset(); interactions.Reset();
director.Skip(); director.Skip();
@@ -25,7 +25,19 @@ var help = -1;
var selected = -1; var selected = -1;
var events = new List<string>(); var events = new List<string>();
interactions.CheckpointCaptured += p => { checkpoint = p; events.Add("checkpoint"); }; interactions.CheckpointCaptured += p => { checkpoint = p; events.Add("checkpoint"); };
tasks.Assigned += (name, state) => { if (name == "SCENE" && state == 50) events.Add("task50"); }; interactions.ObjectiveChanged += objective =>
{
if (objective != 2) return;
Check(tasks.Get("SCENE") == 35, "Objective callback observes old task records before assignment");
events.Add("objective2");
};
tasks.Assigned += (name, state) =>
{
if (name != "SCENE" || state != 50) return;
Check(interactions.CurrentObjective == 2 && tasks.Get(name) == 50,
"Entity assignment observers see the selected objective and new task records");
events.Add("task50");
};
interactions.PracticeRequested += page => { help = page; events.Add("help"); }; interactions.PracticeRequested += page => { help = page; events.Add("help"); };
interactions.Inventory.GadgetSelected += gadget => { selected = gadget; events.Add("gadget"); }; interactions.Inventory.GadgetSelected += gadget => { selected = gadget; events.Add("gadget"); };
interactions.Collected += (_, points) => events.Add("score" + points); interactions.Collected += (_, points) => events.Add("score" + points);
@@ -33,10 +45,10 @@ interactions.Update(shrinkray.Position);
Check(tasks.Get("SCENE") == 50 && interactions.Score == 50, "Shrinkray grants50 and original task35->50"); Check(tasks.Get("SCENE") == 50 && interactions.Score == 50, "Shrinkray grants50 and original task35->50");
Check(interactions.Inventory.State(0, 3) == 1 && selected == 3 && help == 0, "Shrinkray inventory/help/gadget side effects"); Check(interactions.Inventory.State(0, 3) == 1 && selected == 3 && help == 0, "Shrinkray inventory/help/gadget side effects");
Check(checkpoint == shrinkray.Position && !shrinkray.Visible && !shrinkray.Active, "Capture current root before hiding acquired shrinkray"); Check(checkpoint == shrinkray.Position && !shrinkray.Visible && !shrinkray.Active, "Capture current root before hiding acquired shrinkray");
Check(events.SequenceEqual(new[] { "checkpoint", "task50", "help", "gadget", "score50" }), "Recovered special hook ordering"); Check(events.SequenceEqual(new[] { "checkpoint", "objective2", "task50", "help", "gadget", "score50" }), "Recovered special hook ordering");
Check(interactions.Snapshot().ItemStates[301] == 1 && interactions.CurrentObjective == 2, "Acquired state and objective2 persist"); Check(interactions.Snapshot().ItemStates[301] == 1 && interactions.CurrentObjective == 2, "Acquired state and objective2 persist");
interactions.Update(shrinkray.Position); interactions.Update(shrinkray.Position);
Check(interactions.Score == 50 && events.Count == 5, "Repeated overlap cannot recollect"); Check(interactions.Score == 50 && events.Count == 6, "Repeated overlap cannot recollect");
Console.WriteLine("PASS source intro/explanation/shrinkray state, inventory and event ordering"); Console.WriteLine("PASS source intro/explanation/shrinkray state, inventory and event ordering");
var carl = director.FindActor("C3DCARL")!; var carl = director.FindActor("C3DCARL")!;
@@ -69,7 +81,7 @@ Check(decoded.InventoryStates[3] == 1 && decoded.ItemStates[301] == 1 && decoded
Check(decoded.StoredVector == original.StoredVector, "Pickup42AF00 does not overwrite the separate saved transition root"); Check(decoded.StoredVector == original.StoredVector, "Pickup42AF00 does not overwrite the separate saved transition root");
var restoredTasks = new TaskStates(decoded.Tasks); var restoredTasks = new TaskStates(decoded.Tasks);
var restoredDirector = new SceneDirector(lab, restoredTasks, (_, _) => 5); var restoredDirector = new SceneDirector(lab, restoredTasks, (_, _) => 5);
var restored = new SceneInteractions(restoredDirector, restoredTasks, decoded, lab.Code); var restored = new SceneInteractions(restoredDirector, restoredTasks, decoded);
restoredDirector.Begin(lab.FindStart()!); restored.Reset(); restoredDirector.Skip(); restoredDirector.Begin(lab.FindStart()!); restored.Reset(); restoredDirector.Skip();
Check(!restoredDirector.FindActor("shrinkray")!.Active && restored.Inventory.State(0, 3) == 1, "Resume retains collected shrinkray/inventory"); Check(!restoredDirector.FindActor("shrinkray")!.Active && restored.Inventory.State(0, 3) == 1, "Resume retains collected shrinkray/inventory");
restored.Update(restoredDirector.FindActor("shrinkray")!.Position); restored.Update(restoredDirector.FindActor("shrinkray")!.Position);
@@ -82,7 +94,7 @@ foreach (var state in new[] { 30, 36, 50 })
{ {
var boundaryTasks = new TaskStates(original.Tasks.Select(t => t.Name == "SCENE" ? t with { State = state } : t)); var boundaryTasks = new TaskStates(original.Tasks.Select(t => t.Name == "SCENE" ? t with { State = state } : t));
var boundaryDirector = new SceneDirector(lab, boundaryTasks, (_, _) => 1); var boundaryDirector = new SceneDirector(lab, boundaryTasks, (_, _) => 1);
var boundary = new SceneInteractions(boundaryDirector, boundaryTasks, original, lab.Code); var boundary = new SceneInteractions(boundaryDirector, boundaryTasks, original);
boundary.Update(boundaryDirector.FindActor("shrinkray")!.Position); boundary.Update(boundaryDirector.FindActor("shrinkray")!.Position);
Check(boundaryTasks.Get("SCENE") == state && boundary.Inventory.State(0, 3) == 0 && boundary.Score == 50, Check(boundaryTasks.Get("SCENE") == state && boundary.Inventory.State(0, 3) == 0 && boundary.Score == 50,
"Shrinkray special effect exact task35 gate, ordinary score remains"); "Shrinkray special effect exact task35 gate, ordinary score remains");
@@ -100,7 +112,7 @@ foreach (var talkState in new[] { -1, -2, 50, 49 })
("TalkState2", -2), ("TalkTrigger2", "fallback")); ("TalkState2", -2), ("TalkTrigger2", "fallback"));
var testTasks = new TaskStates([new("SCENE", 50)]); var testTasks = new TaskStates([new("SCENE", 50)]);
var testDirector = new SceneDirector(new("TEST", [body, friend, camera0, camera1]), testTasks, (_, _) => 5); var testDirector = new SceneDirector(new("TEST", [body, friend, camera0, camera1]), testTasks, (_, _) => 5);
var test = new SceneInteractions(testDirector, testTasks, original, "TEST"); var test = new SceneInteractions(testDirector, testTasks, original);
test.Update(Vector3.Zero); test.Update(Vector3.Zero);
Check(testDirector.CurrentTag == (talkState is -2 or 50 ? "first" : "fallback"), "First existing match/wildcard; -1 disabled, missing target skipped"); Check(testDirector.CurrentTag == (talkState is -2 or 50 ? "first" : "fallback"), "First existing match/wildcard; -1 disabled, missing target skipped");
Check(testTasks.Get("SCENE") == 60 && test.Score == 100, "Selected trigger alone invokes Carl callback"); Check(testTasks.Get("SCENE") == 60 && test.Score == 100, "Selected trigger alone invokes Carl callback");
@@ -109,7 +121,7 @@ var noneFriend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"),
("TalkState0", 49), ("TalkTrigger0", "first")); ("TalkState0", 49), ("TalkTrigger0", "first"));
var noTasks = new TaskStates([new("SCENE", 50)]); var noTasks = new TaskStates([new("SCENE", 50)]);
var noDirector = new SceneDirector(new("TEST", [body, noneFriend, camera0]), noTasks, (_, _) => 5); var noDirector = new SceneDirector(new("TEST", [body, noneFriend, camera0]), noTasks, (_, _) => 5);
var noTalk = new SceneInteractions(noDirector, noTasks, original, "TEST"); var noTalk = new SceneInteractions(noDirector, noTasks, original);
noTalk.Update(Vector3.Zero); noTalk.Update(Vector3.Zero);
Check(noTasks.Get("SCENE") == 50 && noTalk.Score == 0 && noDirector.FindActor("friend")!.AIstate == 0, Check(noTasks.Get("SCENE") == 50 && noTalk.Score == 0 && noDirector.FindActor("friend")!.AIstate == 0,
"No matching talk target leaves state0 without award/task mutation"); "No matching talk target leaves state0 without award/task mutation");
@@ -121,13 +133,13 @@ foreach (var distance in new[] { 160f, 159.5f })
("TalkState0", 50), ("TalkTrigger0", "first")); ("TalkState0", 50), ("TalkTrigger0", "first"));
var edgeTasks = new TaskStates([new("SCENE", 50)]); var edgeTasks = new TaskStates([new("SCENE", 50)]);
var edgeDirector = new SceneDirector(new("TEST", [body, friend, camera0]), edgeTasks, (_, _) => 5); var edgeDirector = new SceneDirector(new("TEST", [body, friend, camera0]), edgeTasks, (_, _) => 5);
var edge = new SceneInteractions(edgeDirector, edgeTasks, original, "TEST"); var edge = new SceneInteractions(edgeDirector, edgeTasks, original);
edge.Update(new(distance, 0, 0)); edge.Update(new(distance, 0, 0));
Check(edge.Score == (distance < 160 ? 100 : 0), "Strict original sum-radius Carl contact boundary"); Check(edge.Score == (distance < 160 ? 100 : 0), "Strict original sum-radius Carl contact boundary");
} }
var waiting = new SceneDirector(lab, new TaskStates(original.Tasks), (_, _) => 5); var waiting = new SceneDirector(lab, new TaskStates(original.Tasks), (_, _) => 5);
waiting.Begin(lab.FindStart()!); waiting.Begin(lab.FindStart()!);
var locked = new SceneInteractions(waiting, new TaskStates(original.Tasks), original, lab.Code); var locked = new SceneInteractions(waiting, new TaskStates(original.Tasks), original);
locked.Update(waiting.FindActor("shrinkray")!.Position); locked.Update(waiting.FindActor("shrinkray")!.Position);
Check(locked.Score == 0 && locked.Snapshot().ItemStates[301] == 0, "Noncontrolled intro cannot collect pickups"); Check(locked.Score == 0 && locked.Snapshot().ItemStates[301] == 0, "Noncontrolled intro cannot collect pickups");
Console.WriteLine("PASS strict recovered Carl radius boundary and active-player control gate"); Console.WriteLine("PASS strict recovered Carl radius boundary and active-player control gate");
@@ -143,6 +155,36 @@ inventory.SetState(0, 3, 0); Throws(() => inventory.SelectGadget(3));
inventory.SetState(0, 3, 1); inventory.SelectGadget(3); Check(inventory.SelectedGadget == 3, "Owned gadget selection"); 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"); 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;
var practiceItem = tutorial[3] - '1';
Check(Enumerable.Range(0, 8).All(i => availability.State(0, i)
== (i == practiceItem && state is 1 or 4 ? 1 : disabled)),
"Complete tutorial PostLoad re-enables its practice gadget after the common disable pass");
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 ? i is 1 or 7 ? 4 : 1 : state)),
"Serialized tutorial state returns to lab-specific owned gadget availability");
}
}
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 complete route/tutorial PostLoad availability tails, unknown states and lab RETURN round-trip");
// Independently recover the original SCENE setter's two dispatch tables rather // Independently recover the original SCENE setter's two dispatch tables rather
// than testing the port's switch against another manually copied switch. // than testing the port's switch against another manually copied switch.
var exe = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe")); var exe = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe"));
+1 -1
View File
@@ -14,7 +14,7 @@ var save = OriginalSave.Load(Path.Combine(original, "NewGame.tsk"));
var tasks = new TaskStates(save.Tasks); var tasks = new TaskStates(save.Tasks);
var resources = new PreparedEntityResources(Path.Combine(prepared, "level1b/entities/entities.json")); var resources = new PreparedEntityResources(Path.Combine(prepared, "level1b/entities/entities.json"));
var director = new SceneDirector(level, tasks, resources.Duration); var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save, level.Code); var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director); var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models")); var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")), var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
+163 -9
View File
@@ -8,6 +8,10 @@ var tests = new (string Name, Action Check)[]
{ {
("60 simulation calls across 60/120/144 Hz presentation", ClockRates), ("60 simulation calls across 60/120/144 Hz presentation", ClockRates),
("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries), ("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries),
("physics consumes prior motion; fresh versus retained input order", FrameOrdering),
("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState),
("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer),
("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip),
("turn-only speed, forward acceleration/cap and release", SpeedLimits), ("turn-only speed, forward acceleration/cap and release", SpeedLimits),
("backpedal cap and release", Backpedal), ("backpedal cap and release", Backpedal),
("yaw sign, forward half-turn and left precedence", Turning), ("yaw sign, forward half-turn and left precedence", Turning),
@@ -59,6 +63,150 @@ static void ClockBoundaries()
Throws<ArgumentOutOfRangeException>(() => clock.Advance(elapsed)); 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 RetainedLevelState()
{
var state = new PlayerLevelState("LV1B", 3, 1, .625f, 6.125f);
foreach (var destination in new[] { "VR04", "LV1B", "LEV1" })
{
var next = FlatSimulation(); next.LevelCode = destination; next.InputAfterPlayerUpdate = true;
Check(next.ApplyRetainedLevelState(state), "Proven route accepts supported retained scalars");
Check(next.MovementMode == 1 && next.JumpState == 0 && next.JumpHoldSeconds == .625f
&& next.JetpackRemaining == 6.125f, "Jump reset does not imply mode/hold/fire reset");
Check(next.Speed == 0 && next.TurnRate == 0 && next.Velocity == Vector3.Zero
&& next.PendingImpulse == Vector3.Zero && !next.JetpackEffectVisible, "Body and effect presentation remain independently initialized");
next.RestoreReturnRoot(next.ActorRoot + Vector3.UnitY * 500);
next.Step(default);
Check(!next.Grounded && next.MovementMode == 1 && next.JumpState == 0,
"Airborne first destination tick keeps retained input mode after jump state reset");
Near(next.JetpackRemaining, 6.125f - FixedStepClock.Step, .00001f, "Fire timer advances in its own next-tick phase");
var carried = next.CaptureLevelState(-1)!;
Check(carried.SourceLevel == destination && carried.HoldSeconds == .625f, "Ordinary boundary captures current scalars");
next.Reset();
Check(next.MovementMode == 0 && next.JumpHoldSeconds == 0 && next.JetpackRemaining == 0, "Explicit modern reset clears transient carry state");
}
var grounded = FlatSimulation(); grounded.ApplyRetainedLevelState(state); grounded.Step(default);
Check(grounded.MovementMode == 0 && grounded.JetpackRemaining < 0,
"First grounded released controller/fire ticks clear mode and timer independently of loader");
var unsupported = FlatSimulation();
Check(!unsupported.ApplyRetainedLevelState(state with { SourceLevel = "LEV6" })
&& !unsupported.ApplyRetainedLevelState(state with { SelectedGadget = 0 }), "Unproven class cleanup/level states do not acquire carry policy");
unsupported.SetNoclip(true); Check(unsupported.CaptureLevelState(-1) == null, "Modern noclip does not leak flight into retained gameplay state");
Throws<ArgumentOutOfRangeException>(() => grounded.ApplyRetainedLevelState(state with { HoldSeconds = float.NaN }));
Throws<ArgumentOutOfRangeException>(() => grounded.ApplyRetainedLevelState(state with { EffectRemaining = float.PositiveInfinity }));
}
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 Noclip()
{
var points = new[] {
new Vector3(-1000, 0, -1000), new(-1000, 0, 1000), new(1000, 0, 1000),
new Vector3(-1000, 0, -1000), new(1000, 0, 1000), new(1000, 0, -1000),
new Vector3(-1000, -1000, 50), new(1000, -1000, 50), new(1000, 1000, 50),
new Vector3(-1000, -1000, 50), new(1000, 1000, 50), new(-1000, 1000, 50) };
var mesh = new Mesh(points.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(),
Enumerable.Range(0, points.Length).Select(i => (uint)i).ToArray());
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
var collision = new SceneCollision(mesh);
var rayQueries = 0; var dynamicQueries = 0;
var simulation = new LabSimulation(collision, standing, new(0, 25, 0), 0,
(_, _) => { rayQueries++; return null; });
simulation.DynamicRootResolver = (a, b, r) => { dynamicQueries++; return b; };
var entry = simulation.Position;
simulation.Step(new(false, false, false, false, true));
Check(simulation.PendingImpulse.Y > 0, "Fixture has queued motion before noclip");
simulation.SetNoclip(true);
var rays = rayQueries; var bodies = dynamicQueries;
for (var i = 0; i < 10; i++) simulation.Step(new(true, false, false, false, true));
Check(simulation.Position.Z > 90 && !simulation.Grounded && simulation.Jumps == 1,
"Noclip crosses a solid wall without another gameplay jump");
Near(simulation.PendingImpulse.Length(), 0, 0, "Noclip discards queued impulse");
Check(rayQueries == rays && dynamicQueries == bodies && simulation.Energy == 20,
"Noclip bypasses camera/body queries and jetpack drain");
var height = simulation.Position.Y;
for (var i = 0; i < 10; i++) simulation.Step(new(false, false, false, false, false, Rise: true));
Check(simulation.Position.Y > height + 90, "Noclip ascends independently of jumping/gravity");
simulation.Step(new(false, false, false, false, false, Descend: true, Fast: true));
Near(simulation.Velocity.Y, -1800, .001f, "Fast descend uses bounded fly speed multiplier");
var saved = simulation.Position;
simulation.Step(default); NearVector(simulation.Position, saved, .0001f, "Released noclip has no momentum or gravity");
Check(!simulation.SetNoclip(false), "Clear exit retains exploration position");
NearVector(simulation.Position, saved, .0001f, "Disabling in clear space retains position");
Check(simulation.Velocity == Vector3.Zero && simulation.PendingImpulse == Vector3.Zero && simulation.JumpState == 0,
"Disabling clears fly velocity and queued gameplay work");
simulation.Step(default); Check(simulation.Position.Y < saved.Y, "Normal gravity resumes after disabling");
simulation.ReturnToNoclipEntry(); NearVector(simulation.Position, entry, .001f, "Explicit return restores entry");
simulation.Reset(); simulation.SetNoclip(true);
for (var i = 0; i < 5; i++) simulation.Step(new(true, false, false, false, false));
Check(!collision.CanOccupy(simulation.Position, LabSimulation.BodyRadius, simulation.BodyHeight), "Exit fixture intersects wall");
Check(simulation.SetNoclip(false), "Embedded exit restores known entry instead of leaving the capsule trapped");
NearVector(simulation.Position, entry, .001f, "Embedded exit restores cached position");
simulation.SetNoclip(true); simulation.Reset();
Check(!simulation.Noclip && !simulation.HasNoclipEntry, "Reset clears modern noclip state");
}
static void SpeedLimits() static void SpeedLimits()
{ {
var turn = FlatSimulation(); var turn = FlatSimulation();
@@ -102,7 +250,8 @@ static void Turning()
Near(left.Yaw, -right.Yaw, .00001f, "opposed keyboard yaw symmetry"); Near(left.Yaw, -right.Yaw, .00001f, "opposed keyboard yaw symmetry");
Near(forwardLeft.Yaw, left.Yaw / 2, .00001f, "Up halves target turn offset"); Near(forwardLeft.Yaw, left.Yaw / 2, .00001f, "Up halves target turn offset");
Near(forwardLeft.Speed, 60, 0, "Up plus turn performs both speed increments"); 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 both = FlatSimulation();
var leftOnly = FlatSimulation(); var leftOnly = FlatSimulation();
@@ -138,8 +287,8 @@ static void JumpLanding()
var simulation = FlatSimulation(); var simulation = FlatSimulation();
var floor = simulation.Position.Y; var floor = simulation.Position.Y;
simulation.Step(new(false, false, false, false, true)); simulation.Step(new(false, false, false, false, true));
Check(!simulation.Grounded && simulation.Velocity.Y > 500 && simulation.Jumps == 1 && simulation.Pose == PlayerPose.Jump, Check(simulation.Grounded && simulation.PendingImpulse.Y == 550 && simulation.Jumps == 1 && simulation.Pose == PlayerPose.Jump,
"jump takes off with one queued impulse"); "jump queues once after physics and requests its animation");
var sawFall = false; var sawFall = false;
var largestHeight = simulation.Position.Y; var largestHeight = simulation.Position.Y;
for (var i = 0; i < 120; i++) for (var i = 0; i < 120; i++)
@@ -164,7 +313,7 @@ static void HeldJump()
for (var i = 0; i < 150; i++) simulation.Step(default); for (var i = 0; i < 150; i++) simulation.Step(default);
Check(simulation.Jumps == jumpCount && simulation.Grounded, "release stops held repetition and lands"); Check(simulation.Jumps == jumpCount && simulation.Grounded, "release stops held repetition and lands");
simulation.Step(new(false, false, false, false, true)); 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() static void AirArithmetic()
@@ -196,6 +345,7 @@ static void AirControl()
{ {
var simulation = FlatSimulation(); var simulation = FlatSimulation();
simulation.Step(new(false, false, false, false, true)); simulation.Step(new(false, false, false, false, true));
simulation.Step(default); // Consume the queued takeoff before airborne input.
var origin = simulation.Position; var origin = simulation.Position;
for (var i = 0; i < 20; i++) for (var i = 0; i < 20; i++)
{ {
@@ -262,10 +412,14 @@ static void LandingTurn()
{ {
var simulation = FlatSimulation(); var simulation = FlatSimulation();
simulation.Step(new(true, false, false, false, true)); 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)); simulation.Step(new(true, false, initialLeft, !initialLeft, false));
Check(simulation.Grounded && MathF.Abs(simulation.TurnRate) > 20, largestAirTurn = MathF.Max(largestAirTurn, MathF.Abs(simulation.TurnRate));
"Landing fixture retains an opposing air turn before outer grounded reset"); }
Check(simulation.Grounded && largestAirTurn > 20 && simulation.TurnRate == 0,
"Physics landing precedes the same-frame player update clearing air turn");
var before = simulation.Yaw; var before = simulation.Yaw;
simulation.Step(new(true, false, !initialLeft, initialLeft, false)); simulation.Step(new(true, false, !initialLeft, initialLeft, false));
Near(simulation.TurnRate, 0, 0, "grounded released-jump reset clears shared air-turn field"); Near(simulation.TurnRate, 0, 0, "grounded released-jump reset clears shared air-turn field");
@@ -376,7 +530,7 @@ static void OriginalLab(string project, string originals)
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor"); 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[] var positions = new[]
{ {
@@ -386,7 +540,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 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), var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One),
new(new(20, 80, 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) static void SameState(LabSimulation actual, LabSimulation expected, string message)
@@ -13,6 +13,7 @@
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/> <Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/> <Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/> <Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/> <Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/> <Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/> <Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
@@ -0,0 +1,8 @@
<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/Application/UiViewport.cs" />
<Compile Include="../../src/GamePort/Game/PracticePrompt.cs" />
</ItemGroup>
</Project>
+84
View File
@@ -0,0 +1,84 @@
using System.Numerics;
using GamePort.Application;
using GamePort.Game;
var sizes = new (uint Width, uint Height)[] { (640, 480), (960, 720), (1920, 1080),
(2560, 1080), (3440, 1440), (3840, 1080), (1080, 1920), (1920, 1920), (3840, 2160) };
foreach (var (width, height) in sizes)
{
var viewport = new UiViewport(width, height);
var a = Pixels(viewport.ToNdc(new(100, 100)), width, height);
var b = Pixels(viewport.ToNdc(new(200, 140)), width, height);
Near((b.X - a.X) / 100, viewport.Scale, "Horizontal art scale");
Near((b.Y - a.Y) / 40, viewport.Scale, "Vertical art scale");
NearVector(Pixels(viewport.ToNdc(new Vector2(320, 240) + viewport.CenterOffset), width, height),
new(width / 2f, height / 2f), "Centered authored canvas");
NearVector(Pixels(viewport.ToNdc(new Vector2(640, 480) + viewport.BottomRightOffset), width, height),
new(width, height), "Bottom-right authored canvas");
Near(Pixels(viewport.ToNdc(new Vector2(704, 480) + viewport.BottomRightOffset), width, height).X,
width + 64 * viewport.Scale, "Original HUD overscan remains clipped rather than squeezed");
NearVector(Pixels(viewport.ToNdc(new(8, 8)), width, height), new(8 * viewport.Scale), "Corner safe inset scales uniformly");
var pointer = new Vector2(265, 270);
NearVector(viewport.InverseModal((pointer + viewport.CenterOffset) * viewport.Scale), pointer,
"Render/input mappings are inverses");
foreach (var (point, choice) in new[] { (new Vector2(265, 270), true), (new Vector2(355, 270), false) })
{
var prompt = new PracticePrompt();
bool? selected = null;
prompt.Chosen += (_, yes) => selected = yes;
prompt.Show(0);
prompt.Click(viewport.InverseModal(Pixels(viewport.ToNdc(point + viewport.CenterOffset), width, height)));
Check(!prompt.Active && selected == choice, "Centered practice hit regions match visible art");
}
foreach (var boundary in new[] { new Vector2(225, 270), new Vector2(305, 270),
new Vector2(265, 240), new Vector2(265, 300), new Vector2(315, 270), new Vector2(395, 270) })
{
var prompt = new PracticePrompt();
prompt.Show(0);
prompt.Click(viewport.InverseModal(Pixels(viewport.ToNdc(boundary + viewport.CenterOffset), width, height)));
Check(prompt.Active, $"Strict source boundary must remain unselected: {width}x{height} {boundary}");
}
}
Console.WriteLine("PASS uniform4:3/widescreen/ultrawide/portrait scale, anchors and strict modal input regions");
foreach (var (width, height) in new[] { (800u, 600u), (1280u, 720u), (1720u, 720u) })
{
var logical = new UiViewport(width, height);
var authored = new Vector2(265, 270);
var pointer = (authored + logical.CenterOffset) * logical.Scale;
foreach (var (numerator, denominator) in new[] { (2u, 1u), (3u, 2u) })
{
var pixelWidth = width * numerator / denominator;
var pixelHeight = height * numerator / denominator;
var drawable = new UiViewport(pixelWidth, pixelHeight);
var drawn = Pixels(drawable.ToNdc(authored + drawable.CenterOffset), pixelWidth, pixelHeight);
NearVector(pointer * numerator / denominator, drawn, "High-DPI drawable art corresponds to logical pointer pixels");
NearVector(logical.InverseModal(pointer), authored, "High-DPI pointer returns original modal coordinates");
}
}
var classic = new UiViewport(640, 480);
var fractional = new UiViewport(1922, 1082);
var authoredPoint = new Vector2(265, 270);
var drawnPoint = Pixels(fractional.ToNdc(authoredPoint + fractional.CenterOffset), 1922, 1082);
var logicalPoint = new Vector2(drawnPoint.X * 1281 / 1922, drawnPoint.Y * 721 / 1082);
NearVector(fractional.InverseModal(logicalPoint, 1281, 721), authoredPoint,
"Fractional DPI with independently rounded drawable dimensions maps to actual art");
Reject(() => fractional.InverseModal(Vector2.Zero, 0, 721));
var old = classic.ToNdc(new(384, 311));
Check(Vector3.Distance(old, new(.2f, 2 * 311f / 480 - 1, 0)) < .00001f, "Original4:3 NDC is unchanged");
Reject(() => new UiViewport(0, 480));
Reject(() => new UiViewport(640, 0));
Reject(() => classic.ToNdc(new(float.NaN, 0)));
Reject(() => classic.InverseModal(new(0, float.PositiveInfinity)));
Console.WriteLine("PASS high-DPI mapping, original4:3 compatibility and invalid viewport/input rejection");
static Vector2 Pixels(Vector3 ndc, uint width, uint height) => new((ndc.X + 1) * width / 2, (ndc.Y + 1) * height / 2);
static void Near(float actual, float expected, string message) => Check(MathF.Abs(actual - expected) < .002f, $"{message}: {actual} != {expected}");
static void NearVector(Vector2 actual, Vector2 expected, string message) => Check(Vector2.Distance(actual, expected) < .003f, $"{message}: {actual} != {expected}");
static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); }
static void Reject(Action action)
{
try { action(); } catch (ArgumentOutOfRangeException) { return; }
throw new InvalidOperationException("Expected invalid UI viewport/input rejection");
}
@@ -16,7 +16,7 @@ var tasks = new TaskStates(save.Tasks);
tasks.SetExisting("SCENE", 65); tasks.SetExisting("SCENE", 65);
var resources = new PreparedEntityResources(Path.Combine(prepared, "level1b/entities/entities.json")); var resources = new PreparedEntityResources(Path.Combine(prepared, "level1b/entities/entities.json"));
var director = new SceneDirector(level, tasks, resources.Duration); var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save, level.Code); var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director); var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models")); var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")), var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
@@ -136,14 +136,15 @@ void Tick(PlayerInput input)
director.Touch(level.Player.Tag!, simulation.ActorRoot); director.Touch(level.Player.Tag!, simulation.ActorRoot);
interactions.Update(simulation.ActorRoot, simulation.InteractionRadius); interactions.Update(simulation.ActorRoot, simulation.InteractionRadius);
mechanisms.Update(simulation.ActorRoot, simulation.InteractionRadius); mechanisms.Update(simulation.ActorRoot, simulation.InteractionRadius);
// Test actual aperture clearance when crossing the gate plane, before this // Test the recovered radius60 root body when crossing the gate plane,
// frame's mechanism movement. The resolver uses this same current transform. // 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) if ((previous.Z - bars.Position.Z) * (simulation.ActorRoot.Z - bars.Position.Z) < 0)
{ {
var box = visuals.DoorColliders().Single(); var box = visuals.DoorColliders().Single();
var minimumY = DynamicSceneCollision.Corners(box).Min(p => p.Y); var minimumY = DynamicSceneCollision.Corners(box).Min(p => p.Y);
Require(minimumY > simulation.Position.Y + simulation.BodyHeight, Require(minimumY > simulation.ActorRoot.Y + simulation.InteractionRadius,
"Replay crossed the bars before the moving doorway cleared the player"); "Replay crossed the bars before the moving doorway cleared the recovered body");
crossings++; crossings++;
} }
mechanisms.Step(FixedStepClock.Step); mechanisms.Step(FixedStepClock.Step);
+32
View File
@@ -0,0 +1,32 @@
"""Immutable PE contract and bounded recovered camera algebra checks."""
import importlib.util
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
spec = importlib.util.spec_from_file_location('checkpoint_camera_audio_ui',
ROOT / 'tools' / 'binary' / 'checkpoint_camera_audio_ui.py')
checkpoint = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checkpoint)
class CameraAudioUiCheckpointTests(unittest.TestCase):
def test_original_contract_and_offsets(self):
result = checkpoint.recover(ROOT.parent / 'Original')
self.assertEqual(len(checkpoint.ANCHORS), len(result['anchors']))
self.assertEqual(len(checkpoint.CONSTANTS), len(result['constants']))
for entry in result['anchors'] + result['constants']:
self.assertEqual(int(entry['va'], 16) - 0x400000, int(entry['file_offset'], 16))
self.assertTrue(all(g['file_offset'] is None for g in result['globals']))
def test_ray_adjustment_toward_look_point(self):
self.assertEqual((0, 25, 75), checkpoint.obstructed_eye((0, 100, 0), (0, 0, 100)))
self.assertEqual((5, -4, 3), checkpoint.obstructed_eye((5, -4, 3), (5, -4, 3)))
# Translation must not affect the weighting; this guards point vs direction confusion.
self.assertEqual((100, 125, 175), checkpoint.obstructed_eye((100, 200, 100), (100, 100, 200)))
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
"""Source camera predicate priorities/order, including deliberately non-nearest hits."""
import importlib.util
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
spec = importlib.util.spec_from_file_location('checkpoint_camera_ray',
ROOT / 'tools' / 'binary' / 'checkpoint_camera_ray.py')
ray = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ray)
class CameraRayCheckpointTests(unittest.TestCase):
def test_source_and_route_data(self):
data = ray.recover(ROOT.parent / 'Original')
self.assertEqual(len(ray.ANCHORS), len(data['anchors']))
expected = {'level1b.omt': (2851, 2483, 18), 'VR04.omt': (508, 420, 0),
'level1.omt': (5231, 3860, 24)}
for name, (polygons, walls, excluded) in expected.items():
entry = data['route_geometry'][name]
self.assertEqual({3: polygons}, entry['registered_polygon_corner_counts'])
self.assertEqual(walls, entry['wall_grid_polygons'])
self.assertEqual(excluded, entry['nc_polygons_excluded'])
self.assertEqual(0, entry['checkpoint_polygons_excluded'])
self.assertTrue(entry['shape_ids_ascending'])
def test_grid_rectangle_order_and_negative_truncation(self):
self.assertEqual(129, ray.cell_coordinate(-1))
self.assertEqual(130, ray.cell_coordinate(0))
expected = [(130, 130), (130, 131), (131, 130), (131, 131)]
self.assertEqual(expected, list(ray.cells_between((0, 0, 0), (501, 0, 501))))
self.assertEqual(expected, list(ray.cells_between((501, 100, 501), (0, -100, 0))))
self.assertEqual([], list(ray.cells_between((1e6, 0, 1e6), (1e6, 0, 1e6))))
def test_first_wall_hit_overrides_nearer_all_grid_hit(self):
wall = {(130, 130): ['far', 'near']}
all_grid = {(130, 130): ['nearest_floor']}
distances = {'far': 80, 'near': 20, 'nearest_floor': 10}
query = lambda p, a, b, sides: distances[p]
self.assertEqual(('far', 80), ray.first_hit((0, 0, 0), (100, 0, 0), wall, all_grid, query))
def test_cell_priority_duplicate_tests_fallback_and_gate(self):
seen = []
wall = {(130, 130): ['miss'], (130, 131): ['miss']}
all_grid = {(130, 130): ['hit']}
def accept(p, start, end, sides):
seen.append((p, sides))
return 1 if p == 'hit' else None
self.assertEqual(('hit', 1), ray.first_hit((0, 0, 0), (0, 0, 501), wall, all_grid, accept))
self.assertEqual([('miss', False), ('miss', False), ('hit', False)], seen)
seen.clear()
self.assertIsNone(ray.first_hit((0, 0, 0), (0, 0, 501), wall, all_grid, accept, enabled=False))
self.assertEqual([], seen)
if __name__ == '__main__':
unittest.main()
+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_common_availability_prefix_without_level_specific_tails(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()
+28
View File
@@ -0,0 +1,28 @@
"""Regress the actual binary bridge, not a guessed phase-order simulation."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
from checkpoint_input_frame import collect, SLOTS, CALLS
class InputFrameEvidenceTests(unittest.TestCase):
def test_original_dispatch_and_timer_evidence(self):
original = ROOT.parent / 'Original'
if not (original / 'Neutron.exe').exists():
self.skipTest('Original evidence is local-only and absent')
report = collect(original)
self.assertEqual(len(report['evidence']), 30)
self.assertEqual(len(SLOTS), 8)
self.assertEqual(len(CALLS), 6)
def test_physics_precedes_registry_in_same_viewport_override(self):
sites = {label: va for va, _, label in CALLS}
self.assertLess(sites['physics'], sites['all game objects'])
self.assertLess(sites['all game objects'], sites['all logical-to-visual transforms'])
if __name__ == '__main__':
unittest.main()
+26
View File
@@ -0,0 +1,26 @@
"""Original-source construction boundaries for the scheduler checkpoint."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
from checkpoint_lab_registry import collect, ANCHORS, CALLS, SLOTS
class LabRegistryEvidenceTests(unittest.TestCase):
def test_original_lab_construction_trace(self):
original = ROOT.parent / 'Original'
if not (original / 'Neutron.exe').exists():
self.skipTest('Local original files absent')
report = collect(original)
self.assertEqual(len(report['evidence']), len(ANCHORS) + len(CALLS) + len(SLOTS))
self.assertEqual(report['lab']['code'], 'LV1B')
self.assertEqual(report['lab']['entities'], 129)
self.assertEqual(report['lab']['first_record'], dict(kind='3JIM', offset='0x8', tag='JIM1'))
self.assertEqual(report['lab']['serialized_goddards'], 0)
self.assertIn('Retained/reused', report['boundary'])
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()
+25
View File
@@ -0,0 +1,25 @@
import importlib.util
from pathlib import Path
import sys
import unittest
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT / 'tools/binary'))
from checkpoint_loop_motion import recover
class CheckpointLoopEvidence(unittest.TestCase):
def test_original_frame_and_registry_anchors(self):
evidence = recover(PROJECT.parent / 'Original')
self.assertEqual([x['target'] for x in evidence['calls']],
['0x479bc0', '0x462a20', '0x4693a0', '0x47d8f0',
'0x473740', '0x473770', '0x477db0'])
self.assertEqual(evidence['viewport_slot_b8']['target'], '0x47e4f0')
self.assertEqual(len(evidence['anchors']), 11)
for item in evidence['calls'] + evidence['anchors']:
self.assertEqual(int(item['va'], 16) - 0x400000,
int(item['file_offset'], 16))
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
"""Static evidence guards; no original executable is launched."""
import importlib.util
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location(
"checkpoint_scene_loader", ROOT / "tools/binary/checkpoint_scene_loader.py")
loader = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(loader)
class SceneLoaderEvidenceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = loader.collect(ROOT.parent / "Original")
def test_exact_original_sites_and_receiver_vtables(self):
self.assertTrue(self.report["known_binary"])
for site in self.report["sites"] + self.report["vtables"]:
with self.subTest(site=site["name"]):
self.assertTrue(site["matches"], site)
def test_pending_game_load_and_tsk_load_are_different_owners(self):
tables = {t["name"]: t["target"] for t in self.report["vtables"]}
self.assertEqual(tables["editor request load"], "0x46df70")
self.assertEqual(tables["editor consume load"], "0x46dff0")
self.assertEqual(tables["editor load GAM"], "0x46e170")
self.assertEqual(tables["editor reset/postload"], "0x46e570")
self.assertEqual(tables["Jimmy placement PostLoad"], "0x423610")
def test_reset_is_R_input_not_serialized_loader_flag(self):
self.assertEqual(self.report["acquired_reset_virtual_key"], ord("R"))
sites = {s["name"]: s for s in self.report["sites"]}
self.assertEqual(sites["acquired_reset_count"]["actual"], "b968100000") #4200 dwords
self.assertEqual(sites["jimmy_constructor_flag"]["direct_call_target"], "0x470f40")
self.assertEqual(sites["goddard_constructor_flag"]["direct_call_target"], "0x470f40")
self.assertEqual(sites["jimmy_constructor_reusable"]["actual"], "c685c900000001")
self.assertEqual(sites["goddard_constructor_reusable"]["actual"], "c686c900000001")
def test_factory_destruction_and_timer_dependencies(self):
sites = {s["name"]: s for s in self.report["sites"]}
self.assertEqual(sites["object_factory"]["direct_call_target"], "0x459cb0")
self.assertEqual(sites["teardown_delete_sweep"]["direct_call_target"], "0x473710")
self.assertEqual(sites["registry_timer_reset"]["direct_call_target"], "0x47e470")
def test_game_constructor_and_prefix_do_not_identify_old_game_removal(self):
sites = {s["name"]: s for s in self.report["sites"]}
self.assertEqual(sites["load_prefix_caption_cleanup"]["direct_call_target"], "0x4766e0")
self.assertEqual(sites["load_prefix_physics_cleanup"]["direct_call_target"], "0x479000")
self.assertEqual(sites["lab_constructor_base"]["direct_call_target"], "0x44d2b0")
self.assertEqual(sites["game_constructor_base"]["direct_call_target"], "0x4745a0")
self.assertEqual(sites["game_constructor_clear_control"]["direct_call_target"], "0x475a40")
self.assertEqual(sites["lab_constructor_defaults_bridge"]["direct_call_target"], "0x4749a0")
self.assertEqual(sites["lab_defaults_base"]["direct_call_target"], "0x44d3d0")
if __name__ == "__main__":
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Original-data evidence for task ordering and separate transition state."""
import importlib.util
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location(
"checkpoint_script_state", ROOT / "tools/binary/checkpoint_script_state.py")
evidence = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(evidence)
class ScriptStateEvidenceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.original = ROOT.parent / "Original"
cls.report = evidence.collect(cls.original)
def test_binary_identity_sites_and_virtual_call_provenance(self):
self.assertTrue(self.report["known_binary"])
for site in self.report["sites"] + self.report["vtables"]:
with self.subTest(site=site["name"]):
self.assertTrue(site["matches"], site)
def test_objective_record_and_actor_call_order(self):
sites = {s["name"]: s for s in self.report["sites"]}
names = ["task_objective_before_records", "task_record_mutation", "task_entity_callback"]
self.assertEqual([int(sites[n]["va"], 16) for n in names], [0x45FB5B, 0x45FB7F, 0x45FBD9])
self.assertEqual(sites[names[0]]["direct_call_target"], "0x406f50")
self.assertEqual(sites["carl_query_scene"]["direct_call_target"], "0x45fea0")
self.assertEqual(sites["carl_generic_callback"]["direct_call_target"], "0x40e340")
def test_tsk_rebroadcast_and_deferred_load(self):
sites = {s["name"]: s for s in self.report["sites"]}
self.assertEqual(sites["tsk_setter_call"]["direct_call_target"], "0x45f990")
self.assertEqual(sites["load_update_reader"]["direct_call_target"], "0x4603f0")
# Slot420 is not Jimmy's placement PostLoad: its actual target matters.
slots = {s["name"]: s["target"] for s in self.report["vtables"]}
self.assertEqual(slots["Jimmy game post-task hook"], "0x472970")
def test_route_keeps_return_distinct_from_outside(self):
lab, tutorial = self.report["route"]
self.assertEqual((lab["code"], tutorial["code"]), ("LV1B", "VR04"))
exits = [e["fields"] for e in lab["entities"] if e["kind"] == "LOAD"]
self.assertTrue(any(e.get("LevelName", "").casefold() == "level1.gam"
and e.get("StartPoint", "").casefold() == "level1"
and e.get("RequiredLevel") == 60 for e in exits))
self.assertTrue(any(e["fields"].get("LevelName", "").casefold() == "return"
for e in tutorial["entities"]))
def test_non_call_and_negative_read_rejected(self):
pe = evidence.PE(evidence.find_case(self.original, "neutron.exe"))
with self.assertRaises(ValueError):
evidence.rel_call_target(pe, 0x45FB7F)
with self.assertRaises(ValueError):
evidence.read_va(pe, 0x45FB7F, -1)
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 checkpoint_voice_clock import collect
class VoiceClockEvidenceTests(unittest.TestCase):
def test_original_voice_uses_software_time_and_repeat(self):
report = collect(ROOT.parent / 'Original')
self.assertEqual(len(report['vtables']), 3)
self.assertEqual(len(report['anchors']), 12)
self.assertEqual([c['value'] for c in report['constants']], [.5, 1000.0])
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()
+54
View File
@@ -0,0 +1,54 @@
"""Retained companion local reset provenance; static evidence, not runtime fidelity."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from retained_companion import collect, level_policy, HIDDEN_CODES
class RetainedCompanionTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_hash_instruction_and_virtual_callback_provenance(self):
self.assertTrue(self.report['known_binary'])
for key in ('sites', 'vtables'):
for site in self.report[key]:
with self.subTest(key=key, site=site):
self.assertTrue(site['matches'])
if key == 'sites':
self.assertEqual(int(site['file_offset'], 16), int(site['va'], 16) - 0x400000)
def test_route_has_no_companion_property_reload(self):
self.assertEqual([r['code'] for r in self.report['route']], ['LV1B', 'VR04', 'LEV1'])
for route in self.report['route']:
self.assertEqual(route['dog_records'], [])
self.assertEqual(route['shadow_records'], [])
self.assertEqual(route['policy'], dict(hidden=False, range=1500, collision_enabled=True,
radius=130, submode=0, flag928=0))
def test_reused_companion_callback_resets_rotation_not_velocity(self):
targets = {s['name']: s['target'] for s in self.report['vtables']}
self.assertEqual(targets['Goddard authored Euler setter'], '0x4716d0')
self.assertEqual(targets['Goddard logical Euler xyz setter'], '0x472420')
self.assertEqual(targets['Goddard rotation sync'], '0x4624f0')
sites = {s['name']: s['actual'] for s in self.report['sites']}
self.assertEqual(sites['rotation_set_authored_x'], '8986fc000000')
self.assertEqual(sites['rotation_set_logical'], 'ff9030030000')
def test_level_policy_hidden_branches_leave_radius_submode_unassigned(self):
for code in HIDDEN_CODES:
self.assertEqual(level_policy(code), dict(hidden=True, range=1500, collision_enabled=False,
radius=None, submode=None, flag928=1))
for code in ('LEV5', 'LEV8', 'LV1B', 'LV1E', 'LV4B', 'LV6B', 'VR04'):
self.assertFalse(level_policy(code)['hidden'])
self.assertEqual(level_policy('VR06')['range'], 3500)
with self.assertRaises(ValueError):
level_policy('VR004')
if __name__ == '__main__':
unittest.main()
+31
View File
@@ -0,0 +1,31 @@
"""Guard body-vector owners and their initialization/physics consumers."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from retained_player_body import collect
class RetainedBodyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_authored_body_vectors_reapplied_in_init(self):
targets = {x['name']: x['target'] for x in self.report['tables']}
self.assertEqual(targets['live velocity'], '0x471f70')
self.assertEqual(targets['physics velocity'], '0x471f10')
self.assertEqual(targets['live impulse'], '0x471cc0')
self.assertEqual(targets['physics impulse'], '0x471c60')
def test_preparation_has_its_own_velocity_reset_boundary(self):
sites = {x['name']: x['bytes'] for x in self.report['sites']}
self.assertEqual(sites['prepare_velocity_xyz'], '6a006a006a008bceff90c4020000')
self.assertEqual(sites['prepare_speed_clear'], 'c7860806000000000000')
self.assertEqual(sites['postload_prepare'], 'ff9010040000')
if __name__ == '__main__':
unittest.main()
+69
View File
@@ -0,0 +1,69 @@
"""Guard RETURN/ordinary departure distinctions against the original EXE."""
from dataclasses import replace
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from retained_return_cleanup import collect, JetpackCleanupProjection, project_jetpack_cleanup
class RetainedReturnCleanupTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_identity_instruction_targets_and_dispatch(self):
self.assertTrue(self.report['known_binary'])
for key in ('sites', 'vtables', 'cleanup_table', 'select_table', 'tutorial_tail', 'tutorial_table'):
for site in self.report[key]:
with self.subTest(key=key, site=site):
self.assertTrue(site['matches'])
def test_jetpack_dispatch_is_common_epilogue_not_other_gadget_mode_reset(self):
targets = [s['target'] for s in self.report['cleanup_table']]
self.assertEqual(targets[3], '0x42882f')
self.assertNotEqual(targets[3], targets[0])
self.assertNotEqual(targets[3], targets[1])
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['cleanup_case0_mode_zero']['actual'], '66899ec4070000')
self.assertEqual(sites['cleanup_case1_mode_one']['actual'], '6689aec4070000')
def test_cleanup_prelude_is_menu_and_return_flags_precede_stage(self):
self.assertEqual(self.report['menu_identity'], 'C2DInGameMenu')
tables = {t['name']: t['target'] for t in self.report['vtables']}
self.assertEqual(tables['Menu select'], '0x405fb0')
self.assertEqual(tables['Menu close'], '0x406590')
sites = {s['name']: int(s['va'], 16) for s in self.report['sites']}
self.assertLess(sites['return_cleanup'], sites['return_flag'])
self.assertLess(sites['return_flag'], sites['return_preserve_departure'])
self.assertLess(sites['return_preserve_departure'], sites['return_stage'])
self.assertLess(sites['stage_request'], sites['stage_sound_callback'])
def test_postload_tail_is_part_of_the_route_contract(self):
sites = {s['name']: s for s in self.report['sites']}
# The earlier generic-enable/VR-disable prefix is not the final state.
self.assertEqual(sites['route_lab_disable1']['actual'][:12], '6a016a016a00')
self.assertEqual(sites['route_lab_disable7']['actual'][:12], '6a016a076a00')
self.assertEqual(sites['route_vr04_enable3']['actual'][:12], '6a006a036a00')
self.assertEqual([t['target'] for t in self.report['select_table']], ['0x428de0']*2)
self.assertEqual(self.report['final_action'], 'STOP')
self.assertEqual([x['item'] for x in self.report['tutorial_tail']], list(range(8)))
self.assertTrue(all(not x['disabled'] and x['target'] == '0x403870' for x in self.report['tutorial_tail']))
def test_bounded_jetpack_projection_does_not_invent_blanket_reset(self):
# Deliberately nondefault sentinels expose accidental conflation of
# selected gadget, movement mode, jump state, hold and owned effect timer.
state = JetpackCleanupProjection(3, 1, 3, .625, 6.5)
self.assertEqual(project_jetpack_cleanup(state), replace(state, selected=-1))
self.assertEqual(state.selected, 3)
no_selection = replace(state, selected=-1)
self.assertEqual(project_jetpack_cleanup(no_selection), no_selection)
for other in (0, 1, 2, 4, 5, 6, 7, 99):
with self.assertRaises(ValueError):
project_jetpack_cleanup(replace(state, selected=other))
if __name__ == '__main__':
unittest.main()
+52
View File
@@ -0,0 +1,52 @@
"""Immutable original streamer/descriptor evidence; no original code execution."""
import importlib.util
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('retained_streamer', ROOT / 'tools/binary/retained_streamer.py')
streamer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(streamer)
class RetainedStreamerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.evidence = streamer.collect(ROOT.parent / 'Original')
def test_import_export_and_receiver_dispatch(self):
r = self.evidence
self.assertTrue(r['known_binary'])
self.assertTrue(r['import_export_matches'])
self.assertEqual(r['extraction_export']['va'], '0x10073e00')
self.assertTrue(all(s['matches'] for s in r['sites']), r['sites'])
self.assertEqual(len(r['sites']), 20)
self.assertEqual(len(r['vtables']), 6)
self.assertTrue(all(t['matches'] for t in r['vtables']))
self.assertEqual({t['target'] for t in r['vtables'] if t['slot'] == '0x4'}, {'0x473b30'})
def test_entire_reader_lookup_bodies_and_direct_field_destinations(self):
r = self.evidence
self.assertEqual(len(r['functions']), 2)
self.assertTrue(all(f['matches'] for f in r['functions']))
self.assertEqual(len(r['descriptors']), 20)
self.assertTrue(all(d['matches'] for d in r['descriptors']), r['descriptors'])
fields = {d['name']: int(d['interface_offset'], 16) for d in r['descriptors']}
self.assertEqual([fields[n] for n in ('PositionX', 'PositionY', 'PositionZ')], [0xEC, 0xF0, 0xF4])
self.assertEqual([fields[n] for n in ('RotationX', 'RotationY', 'RotationZ')], [0xFC, 0x100, 0x104])
self.assertEqual(fields['StartPoint'], 0x664)
self.assertTrue(set(fields.values()).isdisjoint({0x704, 0x728, 0x1A4, 0x274, 0x288}),
'Mode/jump/live body vectors are not these GAM descriptor destinations')
def test_route_properties_are_exact_registered_subset_without_runtime_fields(self):
r = self.evidence
self.assertEqual([s['code'] for s in r['route']], ['LV1B', 'VR04', 'LEV1'])
self.assertTrue(all(s['exact_descriptor_set'] for s in r['route']))
names = sorted(d['name'] for d in r['descriptors'])
for scene in r['route']:
self.assertEqual(scene['player_properties'], names)
self.assertEqual(len(scene['player_properties']), 20)
if __name__ == '__main__':
unittest.main()
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Read-only camera/audio/UI checkpoint anchors, with PE-mapped offsets.
Run from GamePort: python3 tools/binary/checkpoint_camera_audio_ui.py ../Original
This checks immutable source instructions; it neither executes nor writes originals.
"""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from pe_inspect import PE
EXE_SHA256 = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
DLL_SHA256 = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
# Deliberately selected instruction sequences, rather than matching whole functions.
ANCHORS = (
('follow_default_eye_y200', 0x437742, 'c781cc07000000004843'),
('follow_virtual_ray_callback', 0x439714, 'ff966c010000'),
('follow_x_gain', 0x4397B1, 'd88d54080000d84c2414d88c2480000000'),
('follow_y_extra_gain', 0x4397C2, 'd98558080000dc05d02a4a00'),
('follow_viewport_position', 0x4397F8, 'a1509a5000'),
('follow_ray_call', 0x43B874, 'e897090400'),
('follow_hit_adjustment', 0x43B8AD, 'd826d80dacd54900'),
('follow_hit_gain', 0x43B8F7, 'd90538314a00'),
('jimmy_complete_vtable_ray_slot', 0x4A3D48, '20b84300'),
('cam_interface_update_slot', 0x497FC0, '905f4100'),
('cam_complete_activate_slot', 0x498138, 'a0654100'),
('mca_interface_update_slot', 0x4A9328, 'a00d4300'),
('mca_complete_activate_slot', 0x4A94A0, '80124300'),
('default_local_eye', 0x447E2F, '680000fac3680000fa43'),
('default_snap_threshold', 0x447E9D, 'd81dace54800dfe0f6c441'),
('default_snap_store', 0x447EAA, 'd95944'),
('cam_voice_poll', 0x415FC2, '8b8eb408000051e8c2780600'),
('cam_music_bank', 0x416776, 'a104606900'),
('cam_effect_bank_release_gate', 0x416813, '891d08606900881d34844f00'),
('mca_effect_bank_release_gate', 0x4315C2, '891d08606900881d34844f00'),
('default_effect_bank_restore_gate', 0x447F64, 'a30860690085c07406881d34844f00'),
('voice_duration_and_repeat_flag', 0x47D8CB, 'ff50148b44240c85c075078a463084c07405'),
('ui_dispatch_base_first', 0x404080, '83ec1453558b6c242056578bf155e8adf10600'),
('ui_controlled_clock_then_draw', 0x4043D9,
'391de49950000f8495000000d90588814f00d84424288bced91d88814f008b16ff92d0040000'),
('modal_pause_game', 0x407022, '8b0d48995000538b01ff9068010000'),
)
CONSTANTS = (
('default_snap_distance', 0x48E5AC, 'f', 1000.0),
('ray_hit_weight', 0x49D5AC, 'f', .75),
('ray_hit_follow_gain', 0x4A3138, 'f', 1.5),
('follow_y_gain_extra', 0x4A2AD0, 'd', .2),
('special_eye_state_threshold', 0x495338, 'd', 1.7),
('special_eye_back_multiplier', 0x4AFCF0, 'd', 3.7),
('look_target_height_multiplier', 0x4AFCE8, 'd', 1.9),
)
GLOBALS = (('viewport', 0x509A50), ('controlled', 0x5099E4),
('music_database', 0x696004), ('current_wave_database', 0x696008),
('sound_engine', 0x69600C), ('default_positional_sfx_gate', 0x4F8434),
('objective_timer', 0x4F8188), ('objective_selector', 0x4F8194),
('modal_active', 0x4F8198), ('modal_type', 0x4F8048))
def recover(original):
original = Path(original)
pe = PE(original / 'Neutron.exe')
exe_hash = hashlib.sha256(pe.data).hexdigest()
dll_hash = hashlib.sha256((original / 'OMT2.dll').read_bytes()).hexdigest()
if exe_hash != EXE_SHA256 or dll_hash != DLL_SHA256:
raise ValueError('Unrecognized original module hash; do not apply preferred-VA evidence')
result = {'module_hashes': {'Neutron.exe': exe_hash, 'OMT2.dll': dll_hash},
'anchors': [], 'constants': [], 'globals': []}
for name, va, expected in ANCHORS:
off = pe.offset(va - pe.base)
actual = pe.data[off:off + len(bytes.fromhex(expected))].hex()
if actual != expected:
raise ValueError(f'{name}: expected instruction bytes differ at {va:#x}')
result['anchors'].append({'name': name, 'va': hex(va),
'file_offset': hex(off), 'bytes': actual})
for name, va, fmt, expected in CONSTANTS:
off = pe.offset(va - pe.base)
actual = struct.unpack_from('<' + fmt, pe.data, off)[0]
if actual != expected:
raise ValueError(f'{name}: constant differs')
result['constants'].append({'name': name, 'va': hex(va),
'file_offset': hex(off), 'value': actual, 'format': fmt})
for name, va in GLOBALS:
try:
off = hex(pe.offset(va - pe.base))
except ValueError:
off = None # PE zero-fill; a VA is not automatically a physical file offset.
result['globals'].append({'name': name, 'va': hex(va), 'file_offset': off})
return result
def obstructed_eye(look, hit):
"""43B8AD..43B8F4 algebra, independent of unrecovered ray layer/filter rules."""
return tuple(a - (a - b) * .75 for a, b in zip(look, hit, strict=True))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
args = parser.parse_args()
print(json.dumps(recover(args.original), indent=2))
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""Read-only C5 ray evidence and bounded grid-order reference (not runtime code)."""
import argparse
from collections import Counter
import hashlib
import json
import math
from pathlib import Path
import struct
import sys
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'extractors'))
from omt import Database, read_shape
EXE_HASH = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
CELL_SCALE = struct.unpack('<f', bytes.fromhex('6f12033b'))[0]
CELL_ORIGIN = 130.0
GRID_SIZE = 260
ANCHORS = (
('enabled_gate', 0x47C210, 'a0e5694f005684c0745c'),
('wall_query_return_on_hit', 0x47C23D, 'e83e00000083c42484c07404b0015ec3'),
('all_query_fallback', 0x47C26C, 'e83f020000'),
('wall_cell_list', 0x47C3DF, '8b04ad249b5000'),
('wall_triangle_return_first', 0x47C442, 'e8c9d5feff83c42484c0753d'),
('wall_next_fifo_node', 0x47C44E, '8b368b04ad249b50003bf07591'),
('inclusive_z_then_x_loop', 0x47C463, '43663bda0f8e37ffffff8b5c241041663b4c2414894c24180f8e1affffff'),
('first_hit_identity', 0x47C48B, '8b4704a3585d69008b0f5f5e5d890d545d6900b0015b'),
('all_cell_list', 0x47C60F, '8b04ad7cfc5c00'),
('all_triangle_return_first', 0x47C672, 'e899d3feff83c42484c0753d'),
('fifo_append_tail', 0x4798A2, '8947048b4804890183c00885c0'),
('wall_normal_filter', 0x4798B3, 'd94424148b8680fc5c00d81d74d9480040898680fc5c00dfe0f6c401743d'),
('caller_actor_getter_first', 0x43B83F, 'ff9010030000'),
('caller_actor_getter_second', 0x43B84E, 'ff9210030000'),
('caller_end_and_false_sidedness', 0x43B854, '8b74242c6a0083ec108bcc56e8fbe6fcff'),
('caller_incoming_look_vector', 0x43B865, '83ec108d5424408bcc52e8ece6fcffe897090400'),
('getter_reads_interface_position', 0x472304, '8b91140200008910'),
('jimmy_getter_slot', 0x4A3A4C, '00234700'),
('default_camera_adjustment10', 0x438CC6, 'c7854c08000000002041'),
('mouse_relative_camera_adjustment', 0x438C78, 'd8854c080000d99d4c080000'),
('one_sided_triangle_gate', 0x469C7E, '8a84248000000084c00f8491010000'),
('negative_t_reject', 0x469DDD, '753f'),
('strict_endpoint_reject', 0x469DEE, '752e'),
('nc_shape_skip', 0x44DD64, '83f86374078b178bcfff522c'),
('terrain_register_call', 0x464B18, 'e823460100'),
('checkpoint_filter', 0x4791C7, '5355e8f202000083c40884'),
('game_filter', 0x4791D9, '5355e8c005000083c40884c0740c'),
('polygon_array_step48', 0x479473, '8b838c00000083c5303be889'),
('shape_id_increment', 0x44DEAF, '46'),
('lab_game_polygon_filter_slot', 0x4C3E04, 'd05c4700'),
('vr04_game_polygon_filter_slot', 0x4CEA44, 'd05c4700'),
('outside_game_polygon_filter_slot', 0x4C5BB4, 'd05c4700'),
('route_game_filter_false', 0x475CD0, '32c0c21800'),
)
def cell_coordinate(value):
"""Stored float scale, x87 truncation, then signed16 comparison domain.
Python double arithmetic is a bounded order oracle, not an x87 boundary oracle.
"""
if not math.isfinite(value):
raise ValueError('Finite grid coordinate required')
number = math.trunc(value * CELL_SCALE + CELL_ORIGIN)
return (number + 32768) % 65536 - 32768
def cells_between(a, b):
"""Inclusive endpoint XZ rectangle, increasing X then increasing Z."""
xmin, xmax = sorted((cell_coordinate(a[0]), cell_coordinate(b[0])))
zmin, zmax = sorted((cell_coordinate(a[2]), cell_coordinate(b[2])))
# Skipping out-of-grid indices is equivalent to the source's loop rejection.
for x in range(max(0, xmin), min(GRID_SIZE - 1, xmax) + 1):
for z in range(max(0, zmin), min(GRID_SIZE - 1, zmax) + 1):
yield x, z
def first_hit(start, end, walls, all_polygons, accept, enabled=True, two_sided=False):
"""Order contract only; accept owns the separately recovered triangle kernel.
Grid values are FIFO polygon identities. Repeated polygons in multiple cells
are intentionally not deduplicated. Return first hit, not nearest distance.
"""
if not enabled:
return None
cells = tuple(cells_between(start, end))
for grid in (walls, all_polygons):
for cell in cells:
for polygon in grid.get(cell, ()):
hit = accept(polygon, start, end, two_sided)
if hit is not None:
return polygon, hit
return None
def route_geometry(original):
result = {}
checkpoint_names = {'cstart', *(f'ccheck{i}' for i in range(1, 10))}
for name in ('level1b.omt', 'VR04.omt', 'level1.omt'):
path = Path(original) / 'omt' / name
database = Database(path)
materials = {e.id: e.name for e in database.entries if e.type == '3DMa'}
corners = Counter()
ids, walls, checkpoint, excluded = [], 0, 0, 0
for entry in database.entries:
if entry.type != '3DSh':
continue
shape = read_shape(database.payload(entry))
if (entry.name or '').lower().startswith('nc'):
excluded += len(shape['polygons'])
continue
ids.append(entry.id)
for polygon in shape['polygons']:
material = polygon['material']
if material and materials.get(material['id']) in checkpoint_names:
checkpoint += 1
continue
corners[len(polygon['corners'])] += 1
walls += polygon['normal'][1] < struct.unpack('<f', bytes.fromhex('3333333f'))[0]
result[name] = {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'registered_polygon_corner_counts': dict(corners),
'wall_grid_polygons': walls, 'nc_polygons_excluded': excluded,
'checkpoint_polygons_excluded': checkpoint,
'shape_ids_ascending': ids == sorted(ids)}
return result
def recover(original):
pe = PE(Path(original) / 'Neutron.exe')
if hashlib.sha256(pe.data).hexdigest() != EXE_HASH:
raise ValueError('Unrecognized executable hash')
anchors = []
for name, va, expected in ANCHORS:
offset = pe.offset(va - pe.base)
actual = pe.data[offset:offset + len(expected) // 2].hex()
if actual != expected:
raise ValueError(f'Instruction mismatch: {name} at {va:#x}')
anchors.append({'name': name, 'va': hex(va), 'file_offset': hex(offset), 'bytes': actual})
constants = []
for name, va, fmt in (('cell_scale', 0x4D6A04, 'f'), ('cell_origin', 0x49B1FC, 'f'),
('wall_normal_threshold', 0x48D974, 'f'),
('enabled_default', 0x4F69E5, 'B')):
offset = pe.offset(va - pe.base)
constants.append({'name': name, 'va': hex(va), 'file_offset': hex(offset),
'value': struct.unpack_from('<' + fmt, pe.data, offset)[0]})
return {'exe_sha256': EXE_HASH, 'anchors': anchors, 'constants': constants,
'route_geometry': route_geometry(original),
'limits': 'Static source/order evidence; no original execution, x87 boundary or GPU comparison'}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
args = parser.parse_args()
print(json.dumps(recover(args.original), indent=2))
+140
View File
@@ -0,0 +1,140 @@
#!/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):
"""Common PostLoad prefix only:403870 preserves values other than1/4.
Later level tails override this result; see retained_return_cleanup.py.
This function does not model final scene availability.
"""
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)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Read-only original input/frame bridge anchors; never executes legacy binaries."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from pe_inspect import PE
HASHES = {
'Neutron.exe': 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8',
'OMT2.dll': '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943',
}
# The byte assertions cover indirect dispatch that a direct-call search misses.
ANCHORS = {
'Neutron.exe': [
(0x473758, 'ff5010', 'registry calls interface slot10'),
(0x4702C5, 'ff92c4030000', 'normal wrapper calls slot3C4'),
(0x475AA9, 'ff92cc030000', 'controlled input calls slot3CC'),
(0x475A8A, '8b8674ffffff8d8e74ffffff', 'game interface converts complete by subtracting8C'),
(0x4747A5, 'ff1530d24800', 'game OMT update forwards to base element'),
(0x462265, 'ff1544d24800', 'Jimmy OMT update forwards to morph animation'),
(0x47E6DF, 'ff1504d34800', 'base viewport draw after game pass'),
],
'OMT2.dll': [
(0x100215D4, '68a4fdffff', 'logic message -604'),
(0x100215E8, '68a3fdffff', 'render message -605 follows logic'),
(0x100F989D, '897e58', 'world timer mode1 default'),
(0x100F98A0, 'c7465c28000000', 'world period40 default'),
(0x100F98A7, 'c74660f4010000', 'world maxperiod500 default'),
(0x100F98AE, '897e64', 'world minperiod1 default'),
(0x100F8D18, 'ff150c411110', 'engine clock GetTickCount import'),
(0x100F9B45, '7603', 'maxperiod clamps elapsed'),
(0x100F9B5B, '0f82c9000000', 'minperiod skips logic if elapsed below bound'),
],
}
SLOTS = [
(0x4C2C84, 0x10, 0x470280, 'CJimmyGame interface+8C wrapper'),
(0x4C2C84, 0x3C4, 0x44DF80, 'CJimmyGame normal update'),
(0x4C386C, 0x10, 0x470280, 'CLevel01BGame interface+8C wrapper'),
(0x4C386C, 0x3C4, 0x44DF80, 'CLevel01BGame normal update'),
(0x4C3CD0, 0x3C, 0x4747A0, 'CLevel01BGame OMT logic uses base element'),
(0x4A373C, 0x3C4, 0x424600, 'Jimmy interface+C0 ordinary update'),
(0x4A373C, 0x3CC, 0x426030, 'Jimmy interface+C0 input'),
(0x4A3BDC, 0x3C, 0x462260, 'Jimmy complete OMT update'),
]
CALLS = [
(0x47E554, 0x479BC0, 'physics'),
(0x47E582, 0x473740, 'all game objects'),
(0x47E587, 0x473770, 'all logical-to-visual transforms'),
(0x44DF89, 0x45F510, 'game timer/event records before input'),
(0x44DF94, 0x475A70, 'game input dispatcher'),
(0x426084, 0x438A60, 'Jimmy base movement input'),
]
def read_va(pe, va, size):
offset = pe.offset(va - pe.base)
data = pe.data[offset:offset + size]
if len(data) != size:
raise ValueError('Truncated evidence range')
return offset, data
def collect(original):
results = []
for module, expected_hash in HASHES.items():
pe = PE(Path(original) / module)
digest = hashlib.sha256(pe.data).hexdigest()
if digest != expected_hash:
raise ValueError(f'{module}: unsupported hash {digest}')
for va, hex_bytes, label in ANCHORS[module]:
expected = bytes.fromhex(hex_bytes)
off, actual = read_va(pe, va, len(expected))
if actual != expected:
raise ValueError(f'{module} {va:#x}: {actual.hex()} != {expected.hex()}')
results.append(dict(module=module, va=hex(va), file_offset=hex(off),
bytes=actual.hex(), evidence=label))
if module == 'Neutron.exe':
for table, slot, target, label in SLOTS:
va = table + slot
off, data = read_va(pe, va, 4)
actual, = struct.unpack('<I', data)
if actual != target:
raise ValueError(f'{label}: {actual:#x} != {target:#x}')
results.append(dict(module=module, va=hex(va), file_offset=hex(off),
target=hex(target), evidence=label))
for va, target, label in CALLS:
off, data = read_va(pe, va, 5)
if data[0] != 0xE8 or va + 5 + struct.unpack('<i', data[1:])[0] != target:
raise ValueError(f'{label}: call target mismatch at {va:#x}')
results.append(dict(module=module, va=hex(va), file_offset=hex(off),
target=hex(target), evidence=label))
return dict(hashes=HASHES, evidence=results,
boundary='Static source evidence; cadence and original runtime remain unverified.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', nargs='?', type=Path,
default=Path(__file__).resolve().parents[3] / 'Original')
print(json.dumps(collect(parser.parse_args().original), indent=2))
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Check the bounded fresh-lab registry construction proof against original bytes."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
import sys
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
from gam import parse
EXE_HASH = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
GAM_HASH = '316fff40db565c2add5b07cbccdef640ddb67c64d6625fea1429ce2a0542a234'
CALLS = [
(0x46E335, 0x459CB0, 'loader constructs header game before reading entities'),
(0x45D3FD, 0x44F300, 'LV1B factory constructor'),
(0x44F358, 0x44D2B0, 'lab constructor calls JimmyGame base'),
(0x44D306, 0x4745A0, 'JimmyGame calls game base'),
(0x47460A, 0x4586F0, 'game base constructs interface at complete+8C'),
(0x458712, 0x46FBE0, 'interface base owns registry insertion'),
(0x46E3B9, 0x459CB0, 'loader first fresh entity factory'),
(0x45B1E2, 0x422160, '3JIM factory constructor'),
(0x4221B1, 0x437280, 'Jimmy calls player base'),
(0x4372DA, 0x40D110, 'player calls animated base'),
(0x40D162, 0x462040, 'animated calls object base'),
(0x4620AA, 0x4586F0, 'object base constructs interface at complete+C0'),
(0x4374DF, 0x421D80, 'player constructs owned jetpack fire'),
(0x421DD2, 0x40D110, 'fire calls animated base and registers'),
(0x42250C, 0x43F640, 'Jimmy constructs owned shadow'),
(0x43F692, 0x4352F0, 'shadow calls picture base'),
(0x435341, 0x463F10, 'picture calls sprite base'),
(0x463F74, 0x4586F0, 'sprite base constructs interface at complete+C8'),
(0x46E49A, 0x459CB0, 'loader remaining fresh entities factory'),
(0x423C98, 0x41C810, 'Jimmy postload creates absent Goddard'),
(0x41C861, 0x407A40, 'Goddard calls AI base'),
(0x407A92, 0x40D110, 'AI calls animated base and registers'),
(0x41C95F, 0x43F640, 'Goddard constructs owned shadow'),
]
ANCHORS = [
(0x46FF4A, '8b359c9950006a0c8b7e04', 'registry sentinel,12-byte node,old tail'),
(0x46FF6D, '8978048946048b48048901', 'link node before sentinel after old tail'),
(0x46FF7F, '8928', 'node payload receives interface pointer'),
(0x46E36A, 'ffd6', 'read entity count after header construction'),
(0x46E37F, 'ffd6', 'read first entity code after count'),
(0x46E61A, 'ff920c040000', 'postload pass calls interface40C'),
(0x4374EF, '8985f8070000', 'Jimmy complete+7F8 owns fire complete pointer'),
(0x42251C, '89852c0a0000', 'Jimmy complete+A2C owns shadow complete pointer'),
(0x41C96F, '898694090000', 'Goddard complete+994 owns shadow complete pointer'),
(0x42275A, 'c685c900000001', 'Jimmy enables interface+09 reuse flag'),
(0x41C9C0, 'c686c900000001', 'Goddard enables interface+09 reuse flag'),
(0x46E6B9, '3bb00404000075078a580984db750d', 'reuse requires matching class code and interface+09'),
]
SLOTS = [
(0x4D5EA0, 0x128, 0x46E570, 'supervisor postload pass'),
(0x4D5EA0, 0x110, 0x46E6E0, 'supervisor existing class lookup'),
(0x4D5EA0, 0x11C, 0x46E6A0, 'supervisor class reuse predicate'),
(0x4A373C, 0x40C, 0x423610, 'Jimmy postload contains Goddard creation'),
]
def collect(original):
original = Path(original)
pe = PE(original / 'Neutron.exe')
gam_data = (original / 'gam' / 'level1b.gam').read_bytes()
if hashlib.sha256(pe.data).hexdigest() != EXE_HASH:
raise ValueError('Unsupported Neutron.exe hash')
if hashlib.sha256(gam_data).hexdigest() != GAM_HASH:
raise ValueError('Unsupported lab GAM hash')
evidence = []
for va, expected, label in ANCHORS:
off = pe.offset(va - pe.base)
actual = pe.data[off:off + len(expected)//2].hex()
if actual != expected:
raise ValueError(f'{label} {va:#x}: {actual} != {expected}')
evidence.append(dict(va=hex(va), file_offset=hex(off), bytes=actual, evidence=label))
for va, target, label in CALLS:
off = pe.offset(va - pe.base)
data = pe.data[off:off + 5]
if data[0] != 0xE8 or va + 5 + struct.unpack('<i', data[1:])[0] != target:
raise ValueError(f'{label}: invalid direct call at {va:#x}')
evidence.append(dict(va=hex(va), file_offset=hex(off), target=hex(target), evidence=label))
for table, slot, target, label in SLOTS:
va = table + slot
off = pe.offset(va - pe.base)
if pe.u32(off) != target:
raise ValueError(f'{label}: invalid vtable entry at {va:#x}')
evidence.append(dict(va=hex(va), file_offset=hex(off), target=hex(target), evidence=label))
lab = parse(gam_data)
return dict(hashes={'Neutron.exe': EXE_HASH, 'gam/level1b.gam': GAM_HASH},
evidence=evidence, lab=dict(code=lab.code, entities=len(lab.entities),
first_record=dict(kind=lab.entities[0].kind, offset=hex(lab.entities[0].offset),
tag=lab.entities[0].values().get('ObjectTag')),
serialized_goddards=sum(e.kind == '3GOD' for e in lab.entities)),
fresh_partial_order=['LV1B game', 'Jimmy', 'Jimmy fire', 'Jimmy shadow',
'remaining serialized entities', 'postload Goddard', 'Goddard shadow'],
boundary='Partial order, not absolute indices: other constructor helpers intervene. '
'Retained/reused transition ordering and original runtime remain unverified.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', nargs='?', type=Path,
default=Path(__file__).resolve().parents[3] / 'Original')
print(json.dumps(collect(parser.parse_args().original), indent=2))
@@ -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)
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Read-only, bounded anchors for the architecture checkpoint (not a disassembler)."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from pe_inspect import PE
EXE_SHA256 = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
FRAME_CALLS = [(0x47E554, 0x479BC0), (0x47E560, 0x462A20),
(0x47E56B, 0x4693A0), (0x47E57A, 0x47D8F0),
(0x47E582, 0x473740), (0x47E587, 0x473770),
(0x47E6B1, 0x477DB0)]
ANCHORS = {
'viewport_constructor': (0x47E374, 'c706c4744d00'),
'viewport_render_import': (0x47E6DF, 'ff1504d34800'),
'registry_update_slot10': (0x473758, 'ff5010'),
'registry_next_after_callback': (0x47375B, '8b36'),
'registry_sync_slot3dc': (0x473784, 'ff90dc030000'),
'registry_sync_slot3e0': (0x47378E, 'ff92e0030000'),
'tail_link': (0x46FF70, '894604'),
'registry_interface_payload': (0x46FF7F, '8928'),
'normal_update_slot3c4': (0x4702C5, 'ff92c4030000'),
'controlled_input_slot3cc': (0x475AA9, 'ff92cc030000'),
'morph_logic_import': (0x462265, 'ff1544d24800'),
}
def recover(original):
exe = PE(Path(original) / 'Neutron.exe')
digest = hashlib.sha256(exe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unsupported original EXE hash')
result = {'sha256': digest, 'calls': [], 'anchors': []}
for va, expected in FRAME_CALLS:
off = exe.offset(va - exe.base)
if exe.data[off] != 0xE8:
raise ValueError(f'Expected direct call at {va:#x}')
target = va + 5 + struct.unpack_from('<i', exe.data, off + 1)[0]
if target != expected:
raise ValueError(f'Changed call at {va:#x}')
result['calls'].append({'va': f'{va:#x}', 'file_offset': f'{off:#x}',
'target': f'{target:#x}'})
for name, (va, expected) in ANCHORS.items():
off = exe.offset(va - exe.base)
raw = bytes.fromhex(expected)
if exe.data[off:off + len(raw)] != raw:
raise ValueError(f'Changed anchor {name}')
result['anchors'].append({'name': name, 'va': f'{va:#x}',
'file_offset': f'{off:#x}', 'bytes': expected})
vtable = 0x4D74C4
off = exe.offset(vtable + 0xB8 - exe.base)
if exe.u32(off) != 0x47E4F0:
raise ValueError('Viewport vtable slot B8 changed')
result['viewport_slot_b8'] = {'va': hex(vtable + 0xB8), 'file_offset': hex(off),
'target': '0x47e4f0'}
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
print(json.dumps(recover(parser.parse_args().original), indent=2))
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Read-only ordinary scene-loader ownership and keyboard-reset byte 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
SITES = (
("editor_constructor_vtable", 0x46B200, "c74500a05e4d00"),
("editor_global_owner", 0x46B237, "892d80995000"),
("request_pending", 0x46DF76, "c6814c07000001"),
("request_filename", 0x46DF7D, "8d914d070000"),
("update_pending_dispatch", 0x46C05E, "ff9204010000"),
("teardown_first_filter", 0x46E032, "ff9200020000"),
("teardown_first_uninit", 0x46E054, "ff5220"),
("teardown_second_uninit", 0x46E091, "ff5234"),
("teardown_delete_mark", 0x46E0CA, "c6460601"),
("teardown_delete_sweep", 0x46E0D9, "e832560000"),
("teardown_database_close", 0x46E117, "e8e4ceffff"),
("ordinary_gam_load", 0x46E152, "ff90fc000000"),
("ordinary_pending_clear", 0x46E158, "c6854c07000000"),
("object_reuse_test", 0x46E45A, "ff921c010000"),
("object_reuse_lookup", 0x46E46E, "ff9010010000"),
("object_factory", 0x46E49A, "e811b8feff"),
("ordinary_postload_registry", 0x46E4FF, "ff9228010000"),
("registry_init_callback", 0x46E5C3, "ff5228"),
("registry_postload_callback", 0x46E61A, "ff920c040000"),
("registry_timer_reset", 0x46E694, "e8d7fd0000"),
("destruction_predicate", 0x4719B0, "8a8139010000c3"),
("destruction_predicate_set", 0x4719C4, "888139010000"),
("persistent_flag_setter", 0x470F47, "884111ff9204020000"),
("jimmy_constructor_flag", 0x4226BF, "e87ce80400"),
("goddard_constructor_flag", 0x41C99E, "e89d450500"),
("jimmy_constructor_reusable", 0x42275A, "c685c900000001"),
("goddard_constructor_reusable", 0x41C9C0, "c686c900000001"),
("load_prefix_caption_cleanup", 0x46E26C, "e86f840000"),
("load_prefix_physics_cleanup", 0x46E271, "e88aad0000"),
("lab_constructor_base", 0x44F358, "e853dfffff"),
("game_constructor_base", 0x44D306, "e895720200"),
("game_constructor_clear_control", 0x474683, "e8b8130000"),
("game_constructor_current_game", 0x474688, "893548995000"),
("lab_game_preserve_predicate", 0x44D472, "ff9004020000"),
("lab_constructor_defaults_bridge", 0x44F3B3, "e8e8550200"),
("game_defaults_virtual_dispatch", 0x4749CA, "ff92b4000000"),
("lab_defaults_base", 0x44F4D5, "e8f6deffff"),
("keyboard_down_array", 0x46A370, "c6803898500001"),
("keyboard_up_array", 0x46A390, "c6803898500000"),
("acquired_reset_key_test", 0x4235D8, "a08a98500084c07423"),
("acquired_reset_count", 0x4235E2, "b968100000"),
("acquired_reset_address", 0x4235E9, "bf38844f00f3ab"),
)
VTABLES = (
("editor update", 0x4D5EA0, 0xC4, 0x46BEC0),
("editor load GAM", 0x4D5EA0, 0xFC, 0x46E170),
("editor request load", 0x4D5EA0, 0x100, 0x46DF70),
("editor consume load", 0x4D5EA0, 0x104, 0x46DFF0),
("editor cleanup", 0x4D5EA0, 0x10C, 0x46E710),
("editor find reusable", 0x4D5EA0, 0x110, 0x46E6E0),
("editor test reusable", 0x4D5EA0, 0x11C, 0x46E6A0),
("editor reset/postload", 0x4D5EA0, 0x128, 0x46E570),
("Jimmy destruction predicate", 0x4A373C, 0x200, 0x4719B0),
("Jimmy initialization", 0x4A373C, 0x28, 0x437890),
("Jimmy placement PostLoad", 0x4A373C, 0x40C, 0x423610),
("Jimmy key-gated reset", 0x4A373C, 0x3C8, 0x4235B0),
("lab game destruction predicate", 0x4C386C, 0x200, 0x4719B0),
("lab game predicate setter", 0x4C386C, 0x204, 0x4719C0),
("lab game class-default initializer", 0x4C3CD0, 0xB4, 0x44F4B0),
)
def collect(root: Path) -> dict:
pe = PE(find_case(root, "Neutron.exe"))
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:
target = 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(target), matches=target == expected))
digest = hashlib.sha256(pe.data).hexdigest()
return dict(module="Neutron.exe", sha256=digest, known_binary=digest == EXE_SHA256,
sites=sites, vtables=tables, acquired_reset_virtual_key=0x50988A-0x509838,
scope="Static source instructions only, no original runtime execution.")
def main() -> None:
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)
if __name__ == "__main__":
main()
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more