Reconstruct lab story, interactions, patrol and jet pack practice flow

This commit is contained in:
UnixNight committed 2026-10-24 20:33:03 -04:00
1 parent 58424120bb
commit c929f942e1
84 files changed
+7951 -299

No files matched your search

+42 -15
View File
@@ -4,11 +4,12 @@ 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`. There are no Git remotes or runtime online services.
**Current milestone: controllable original lab with walking, jumping, collision, **Current milestone: original lab story, interactions and jet pack practice flow.**
chase camera and original animation clips.** Recovered controller arithmetic is The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
integrated; collision/pivot/cadence and animation timing remain provisional. patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and
Introductory cutscenes, interactions, progression and saves remain incomplete. checkpoint transitions. Collision response, timing and visual fidelity remain
See [progress](docs/progress.md) and [compatibility](docs/compatibility.md). provisional. The full game is incomplete; see [progress](docs/progress.md) and
[compatibility](docs/compatibility.md) for tested scope and remaining work.
## Build and run locally ## Build and run locally
@@ -21,12 +22,34 @@ python3 tools/extractors/prepare.py --audio sounds musicsecretlab
dotnet run dotnet run
``` ```
The default is the original secret lab (LV1B), starting at the GAM location after The default starts the original secret lab (LV1B), including the recovered intro
settling onto source floor geometry. **Arrows** walk/backpedal/turn; **Shift, camera/speech sequence. **Escape or Space** skips the current sequence and restores
Insert, numpad 0 or right mouse** jump. **R** resets, **C** pauses into inspection control. **Arrows** walk/backpedal/turn; **Shift, Insert, numpad 0 or right mouse**
and resumes the chase camera, **F11** toggles fullscreen, **Escape** quits. jump, and holding jump uses the jet pack after obtaining it. **O** raises/lowers
No-gadget held jump can repeat on landing; normal midair arrows do not steer. the objective panel. **R** resets the scene placement with current progression;
The original STARTEXP/LABEXP intro is skipped for this checkpoint. **C** pauses into inspection, **F11** toggles fullscreen, **Escape** quits during
ordinary play. Use `--skip-intro` to begin with control or `--mute` for silent play.
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
on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the
hovered Yes region, otherwise No. The original practice return uses the saved
lab start tag. Runtime checkpoint-position restoration is still unrecovered.
Normal midair arrows do not steer. Source patrol/door logic is integrated, while
sensing, full collision response, alpha/lighting and audio effects remain incomplete.
`--load-save PATH` reads original TSK task/items/score/checkpoint state;
`--write-save PATH` writes that state outside the asset directory. This resumes the
saved STRT checkpoint; arbitrary current-position/complete game-state saving is
not implemented. `--start TAG` selects an original checkpoint for investigation.
Prepare all available scenes for other save files with
`python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab`.
All35 GAM entity files are supplied;33 have matching OMT geometry archives.
Level3B.gam and Level3E.gam each contain the same four entities apart from their
level identifier. Their registered OMT archives are absent, but no incoming GAM
transition or supplied save selects them. Their use in normal gameplay remains
unverified; this is not an established blocker. The manifest records the absent
geometry without substitution. See [level resource evidence](docs/analysis/level-resource-mapping.md).
Use `--inspect` for the previous inspector: arrows/WASD orbit, plus/minus zoom; Use `--inspect` for the previous inspector: arrows/WASD orbit, plus/minus zoom;
1 idle, 2 run, 3 jump, 4 scratch preview. With no simulation, C toggles stored/orbit 1 idle, 2 run, 3 jump, 4 scratch preview. With no simulation, C toggles stored/orbit
@@ -39,6 +62,8 @@ Headless verification on a machine with Vulkan 1.3 (Mesa lavapipe works):
```bash ```bash
dotnet run -- --headless --with-player --time 0.05 --screenshot artifacts/lab.ppm dotnet run -- --headless --with-player --time 0.05 --screenshot artifacts/lab.ppm
dotnet run -- --headless --smoke-walk --screenshot artifacts/walk.ppm dotnet run -- --headless --smoke-walk --screenshot artifacts/walk.ppm
dotnet run -- --headless --story --story-time 12 --screenshot artifacts/story.ppm
dotnet run -- --headless --skip-intro --write-save artifacts/checkpoint.tsk
dotnet run -- --headless --model ASE/jimstop.ase --texture png/jimycarl.png dotnet run -- --headless --model ASE/jimstop.ase --texture png/jimycarl.png
dotnet run -- --audio artifacts/extracted/musicsecretlab/Wave_00000000_HuntingBuildupVar2_11k.wav --loop-audio dotnet run -- --audio artifacts/extracted/musicsecretlab/Wave_00000000_HuntingBuildupVar2_11k.wav --loop-audio
dotnet run -- --help dotnet run -- --help
@@ -77,14 +102,16 @@ dotnet publish -c Release -r win-x64 --self-contained true
Packages are local directories `dist/linux-x64` and `dist/win-x64`. Run Packages are local directories `dist/linux-x64` and `dist/win-x64`. Run
`launch-scene.sh` or `launch-scene.cmd`; append `--headless --frames 1` for a `launch-scene.sh` or `launch-scene.cmd`; append `--headless --frames 1` for a
render smoke test. They include the .NET runtime, SDL3 native library, SPIR-V, render smoke test. They include the .NET runtime, SDL3 native library, SPIR-V,
original asset copies, prepared lab/Jimmy resources, audio and limitations. original asset copies, all33 available prepared scenes, actor/UI resources, audio
and limitations.
Windows cross-publishing and preliminary headless Wine64 rendering are verified. Windows cross-publishing and preliminary headless Wine64 rendering are verified.
A user confirmed native Windows loading/rendering; this movement update still A user confirmed native Windows loading/rendering of the earlier checkpoint;
needs native Windows input/physics testing. Full native Windows functionality is unverified. this story/tutorial update still needs native Windows input/physics testing. Full native Windows functionality is unverified.
These are investigation packages, not a finished game release. These are investigation packages, not a finished game release.
`scripts/test.sh` runs Python regressions, native C# data/collision/movement checks, `scripts/test.sh` runs Python regressions, native C# data/collision/movement checks,
all PNG/ASE decoders, actual Vulkan GPU readback, dummy-device SDL3 audio, and all PNG/ASE decoders, source-backed interaction/AI/support/jetpack/UI checks,
actual Vulkan GPU readback, dummy-device SDL3 audio, and
original SHA-256 verification. Set `NEUTRON_WINDOW_TEST=1` with a working DISPLAY original SHA-256 verification. Set `NEUTRON_WINDOW_TEST=1` with a working DISPLAY
to include injected keyboard and swapchain-resize verification. Full OMT audit: to include injected keyboard and swapchain-resize verification. Full OMT audit:
+75
View File
@@ -0,0 +1,75 @@
# Player-contact buttons and vertical doors
Static recovery and managed integration, 2026-10-24. Original executable SHA-256:
f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8.
EXE text file offsets are VA minus0x400000. Originals were only read.
## Button contact
C3DButton interface+C0 vtable493B60, enter slot40=411BB0, update slot3C4=411DE0,
activation slot28=4118B0, PostLoad slot404=411EF0. InitObject411B82 sets radius300;
PostLoad411EF8/411F09 sets authored/current radius300 again. Activation4119A7
sets150; runtime resizing after subsequent task reactivation remains to be matched.
The current player contact subset uses normal PostLoad radius300 plus Jimmy60,
strict overlap and source offsets to distinguish duplicate C3DBUTTON tags.
Enter411BC1 accepts the active player or a C3DBASEBALL. The port currently handles
only player contact. Availability at interface608 must be nonzero, cooldown7B0
must be<=0. Current definition HIUP (literal4ED9C0) selects the press branch:
set cooldown4.0 at411C35, optionally play AvailSound at411C92..A2, select DOWN
at411CAE..B5 and set material RGB(.2,.2,.2) at411CBB..FC. Existing DOWN selects
UP and original authored RGB at411D59..B1. Material pulse/tint is not yet ported.
Resolve ActivateButton through first case-insensitive tag lookup474070. If found,
call its interface428 with source Toggle (411D18..23). A button target additionally
becomes available while the caller becomes unavailable (411D29..47). Complete
generic button-to-button toggle activation is still unresolved by this consumer;
the lab targets bars, a vertical door. NewTaskState/NASound are serialized but the
traced ordinary contact path does not consume them. No task award was invented.
The special LV4B branch411C3F..8F is outside this lab implementation.
Update411E24 subtracts dt only for positive cooldown and reactivates/resets at
<=0, then stores0. Continuous contact does not generate another enter callback.
SceneMechanisms retains contact membership across cooldown reset.
## Vertical door state
C3DDoorUpDown interface+C0 vtable4993AC: activation417760, contact4178C0,
update417930, toggle428=417AC0. Source fields are ItemClosed at5FC, current
closed flag600, Next604, remaining668, DoorSpeed66C, OpenTime670, elapsed674,
OpenAmount680. DoorSpeed is used as the movement **duration**, not units/second.
Initial open state adds OpenAmount to the stored source origin at41777B..AE.
Origin getter interface164=471600 returns the saved vector atEC..F8.
Toggle ignores requests equal to current closed state. During movement it replaces
remaining with duration-minus-remaining (417AE9..F5); from rest it copies duration
and starts loop sound59 when no movement sound is active (417B11..43). Next is
dispatched before assigning closed state (417B49..C01). The current consumer
handles Next targeting3AIT; other original subclasses remain explicit unsupported.
Requested0 opens,1 closes; other values toggle (417C01..34).
Update first consumes positive remaining by dt and clamps to0. Completion stops
the movement loop and emits sound58 (417974..AE). Set vertical root to:
```text
fraction = remaining / DoorSpeed
closed: sourceY + OpenAmount*fraction
open: sourceY + OpenAmount*(1-fraction), reset open elapsed0
```
There is no leftover-dt integration. Once stationary/open, add dt to elapsed and
close only when elapsed is **strictly greater** than OpenTime (417A77..AA).
Lab bars: originY-1076.0883, duration5sec, distance500, open hold3sec, touch-disabled.
Its two authored buttons use Toggle-1. TouchActivated doors' own contact and
baseball contact paths remain outside the player-button subset.
## Runtime verification and limits
Game/SceneMechanisms runs in the same fixed-step scene loop as the director.
Application/StaticSceneVisuals displays UP/DOWN variants and door root movement.
Two source-data regression groups cover strict360 contact, four-second reset,
duplicate tags, contact persistence, five-second opening, continuous reversal,
sound-loop lifetime, exact endpoints and strict three-second hold expiration.
These checks establish port behavior from static evidence. Moving-object physics,
material pulse, sound-bank resolution, full task/reactivation behavior and original
runtime comparison are not established by these tests.
+130
View File
@@ -0,0 +1,130 @@
# Moving vertical-door collision
Read-only static recovery and bounded managed component,2026-10-24. Original
Neutron.exe SHA-256 f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8.
EXE text file offsets below are VA minus0x400000. No original code was executed
for this investigation. Source geometry/defaults are recovered; full response is
still injected and must not be called the original collision solver.
## Door defaults and activation
C3DDoorUpDown complete constructor4174F0 installs interface+C0 vtable4993AC.
| Evidence | Result |
| --- | --- |
|4175B0 ->4710C0 ->iface224/471A40|Entity pair collision enabled; current byte+140=true|
|4175C6/4175CA ->471730|Collision mode178/field124=2|
|4175CF/4175D2 ->471030 ->iface214/471A00|Own physics integration disabled; byte13E=false|
|417CAB/417CB2 ->iface110|PostLoad radius40, overriding automatically copied shape radius|
|40E410/40E413|HasCollision-1 retains constructor flags|
|40E427/40E433|Explicit HasCollision nonzero enables pairs and own integration|
|40E44B/40E457|Explicit HasCollision0 disables pairs and own integration|
Do not interpret own integration=false as a noncolliding door. Its entity pairs
remain enabled. Render visibility, current pair permission, world geometry checks,
own integration and authored CanMove are different flags. On HasCollision-1,
task visibility changes do not themselves execute the explicit pair-disable path;
the caller must track source activation flags without equating visible and solid.
CanMove is read at base40E0F0. After physical update462520, zero restores the
serialized origin through position/Euler setters40E103..40E15C. Nonzero permits
the current position to remain, allowing the door state machine's vertical motion.
It does not replace collision mode2 with a static world mesh.
## What the box actually uses
Shape-change hook462270 reads the current OMT shape's find_cube method through
complete slot44 at4622D4. This is the min/max of its local source vertex positions,
not a world-aligned bound of an already transformed rendered model. It forwards
min to iface2E8 at4622FB (storage1D4..1E0), max to iface2E0 at462325
(storage1C4..1D0). OMT find_cube1000AA80 computes all six values from shape vectors.
This justifies original local shape bounds; unrelated editor icons or a guessed
full-model world AABB are not substitutes.
47A776/47A7A5 retrieve these bounds.47A7EC..47A99B transforms all eight corners
through iface384=472980, using current Euler angles and root position. The point
method quantizes angles through the original trigonometric table. The bounded
component accepts a supplied local-to-world matrix; correctness of that matrix
for every nonzero authored Euler rotation remains the caller's responsibility.
The actual lab bars have zero rotation, so translation is unambiguous.
Corner bits:4 selects maxX,2 maxY,1 maxZ. The switch at47B3AC then emits these
twelve triangles, with the original diagonal choice/order preserved:
```text
0,1,2 1,3,2 0,2,4 2,6,4
4,6,5 6,7,5 5,7,3 5,3,1
0,4,1 4,5,1 2,3,7 7,6,2
```
The pure component rebuilds these triangles from the current door transform.
There is no persistent collider left at its closed root and no invented relative
door-motion sweep. Original47A5E0 similarly constructs the box at its current
pose, then obtains the other body's previous/current roots47AAD4/47AB0D.
## Dispatch, gates and response boundary
Global entity-pair loop47A430 requires both slot220 flags and mutual slot3A0
class/permission gates. At47A4CF/47A4E7 it checks collision mode178. If either
actor has mode2, it calls47A5E0 with that actor first; otherwise it calls the
ordinary root-sphere path47B3E0. Exclusions/class gates are inputs to the bounded
component; their complete class-specific behavior is not silently invented.
47A5F5 additionally requires the **other** actor's world-geometry flag1D0.
Root broadphase then uses quick_magnitude and these inclusive comparisons:
- Other actor mode2: distance<=boxRadius+otherRadius, then return contact directly
at47A712..47A72C/47B39F without the twelve-triangle response.
- Other modes: distance<=2*boxRadius+otherRadius, at47A73F..47A75B. Only candidates
passing this gate construct/sweep the oriented cube.
The second rule is a source quirk. Normal Jimmy radius60 and door radius40 give
**140 units**, despite the bars' much larger shape bounds. Do not enlarge it to
the graphic cube's bounding sphere while calling the result recovered behavior.
For every cube triangle,47B277 invokes shared sphere/triangle kernel47BD80 and
can invoke the other actor's normal response callback374 at47B29B. After all
twelve, box iface1E0 inhibits ordinary position response when true47B2EF..47B2F7.
Otherwise the candidate displacement is clipped against static world through
47B4B0 at47B364 before assigning the sphere root via314 at47B399. Thus a generic
sphere-vs-AABB overlap/push is not an exact translation of the original response.
## Implemented interface and tests
Game/DynamicSceneCollision.cs is deliberately bounded: source defaults and
HasCollision sentinel handling; pair/world-geometry gates; exact broadphase;
current oriented corners; exact twelve-triangle order; injected narrowphase;
contact-preserving response inhibition and second-mode2 shortcut.
DynamicBoxCollider takes identity, source root, local min/max, local-to-world
matrix, current radius, pair flag and response-inhibition flag. DynamicSphereMotion
takes previous/current root, radius and the relevant flags/mode. Resolve invokes
a supplied Func<DynamicBoxSweep,DynamicCollisionResponse>, or returns unchanged
when a recovered gate rejects it. The sweep contains all twelve SupportTriangles.
The callback must provide the still-unrecovered47BD80/static clipping response.
Source lab fixture: bars GAM offsetA29C, root(3810.1970,-1076.0883,-1180.4956),
HasCollision-1,CanMove1,OpenAmount500,rotation0. Its42 ASE source points convert
to local min(-223.8069,-18.7273,-16.8051),max(228.7926,391.2706,16.8051).
All raw points, including any nonvisible faces, contribute to these shape bounds.
Run from GamePort:
```sh
python3 tools/binary/dynamic_collision_evidence.py
source scripts/env.sh
dotnet run --project tests/GamePort.DynamicCollisionTests
```
The script checks26 original instruction sequences, all12 jump targets and all36
corner indices extracted directly from the bounded switch-case machine bytes.
It verifies the source class table, lab entity flags and ASE bound facts.
JSON evidence is artifacts/binary/dynamic-collision-evidence.json.
All10 managed groups pass: defaults/sentinel; inclusive140 broadphase and its
large-cube quirk; permission/geometry gates; oriented corners; source cube topology;
injected response/inhibition; mode2 shortcut; moving geometry; invalid inputs;
actual lab bars closed/open passage using the existing provisional swept-sphere
SceneCollision adapter. The latter verifies port integration, not original47BD80
or original runtime behavior. Full edge/vertex sphere response, static reclipping,
door pushing/crushing and native original comparison remain unresolved.
+99
View File
@@ -0,0 +1,99 @@
# Laboratory jet pack and powered jump
Read-only static recovery plus managed implementation,2026-10-24. EXE text file
offsets are VA minus0x400000. Neutron.exe SHA-256 is
f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8.
Original DLL/frame and original game comparisons are separate evidence categories.
## Identity
The lab pickup's GAM tag SHRINKRAY/PickupIndex301 is a prototype/internal name.
Original screens.omt Canv120 says GET JET PACK; its effect grants inventory
group0/item3. That exact inventory slot gates the powered-jump code43848E/4385C9.
It must not be presented as a shrink-ray weapon. The original readme describes
Shift/Insert/right mouse as Jump - Jet Pack Burst. The actual C3DShrinkRay class
has separate ray.ase/ray0000..2.png bindings440035..A6, outside this implementation.
## Controller and state order
Game/JetpackBurst.cs translates the vertical state/action subset of437F90.
Grounded/released outer update437B9E resets jump state0 before air application.
States below3 set extra acceleration to gravity*1.33f-gravity at438148..18D.
With gravity-800 this yields-264 extra/-1064 net. The initial jump queues550
at4383B3 and clears the effect timer; the hold timer starts0.
State1 adds dt and starts a burst only after hold is strictly>.4f
(4383FD..418). State2 renewed hold attempts immediately (438559). Both enter
state3 even when disabled. Allowed start sets effect time8 (field884, ctor437640),
current radius100 when the effect exists (4384DE..F3), requests FLY and sets
vertical velocity10 (4384F9..546). Slot138(2) invokes a gadget/sound callback;
it is not a proven movement-mode assignment and the component does not invent one.
Start is disallowed in LEV6,LV4B,LV6A,LEV3,LV3A/B/C/D; gadget modes2/6/7;
nonpositive global4F83D4; or inventory item3 state0/4. VR04 bypasses those guards
(43841E..4384D4,438559..633). Other nonzero inventory states remain accepted.
Before state dispatch, states>=3 inspect the effect timer. An existing effect
with time<=0 resets states3/4 to0, requests FALL, stops the gadget and returns
before replacing acceleration (438192..20D). The previous extra acceleration
therefore survives that invocation. This is also why unavailable gadgets can
repeat ordinary jumps on landing while jump remains held.
With positive burn time, distance-controlled extra acceleration is:
| Condition | Extra Y | Net Y including gravity |
| --- | --- | --- |
| Shadow distance<500, velocityY>=-1 |880|80|
| Shadow distance<500, velocityY<-1 |1040|240|
| Shadow distance>=500 |720|-80|
Near-branch .1/.3 are stored doubles; far .1 is float (438210..30D).
Source distance86C comes from Jimmy to his shadow425450..47C. Shadow query
4252E0 uses a vertical segment2500 downward and places its root hitY+13 for
default height30. Current integration approximates this query with the port's
walkable floor query; failed queries retain prior distance.
Held state3 landing stops the effect, restores radius60 and enters4
(438693..6EF). Airborne release stops the timer, requests FALL and enters4
without a radius restore (438745..780). Jimmy's next ordinary grounded update
42469B restores60. Source released table state4 goes directly to reset43879A;
state5 checks grounding. The component's tests preserve these distinct branches.
## Effect, energy and visual assets
C3DJetpackFire update421FB0 obtains its owner. Grounded owner sets remaining0;
then it subtracts dt, including when inactive (421FDD..422009). A nonpositive
result hides it. A positive result shows it and adjusts global4F83D4 by-dt*.5
(42202B..3B). Timer values are not clamped to0. Empty owner/effect leaves fields
unchanged. Running burn is not cancelled merely because energy reaches0.
Energy helper42A920 skips adjustments for numeric FourCC VR01..VR08, otherwise
adds the requested amount and clamps0..100 (42A975..9C1). Low/empty-energy sounds
and other energy/damage consumers are not yet mapped. The original TSK float
PlayerValue retains this global. SceneInteractions now preserves live energy
when producing a checkpoint snapshot.
Effect bindings421F30..96 are DEFAULT fire.ase, HINONE fire2.ase and fire.png.
The active effect follows owner root/Euler directly at42204C..B6. Preparation
exports the original two-triangle morph; JetpackVisuals samples it into the final
combined GPU buffer and controls its draw from the effect phase. Exact effect
translucency and global morph cadence remain open. Jimmy HIFLY->jimfly.ase is
registered at422B1A..26; its426 point vectors reuse the original Jimmy base UVs.
## Integration and verification boundary
LabSimulation uses controller -> movement/static/dynamic collision -> effect
update at fixed60Hz. Original global object iteration/phase order is unresolved;
the pure APIs expose controller and effect phases separately rather than hiding
that choice. Normal logical actor-root clearance is now75.9 from recovered
PostLoad/support constants; player capsule radius24, full wall solver and sole
placement remain provisional. Burst100/landing60 radius changes currently affect
contacts and moving-door broadphase; they do not make the modern capsule exact.
Fourteen JetpackTests groups pass: takeoff/release/refire, strict .4 threshold,
disabled repeat, all source start gates/VR04 exception, acceleration thresholds,
transition acceleration/radius semantics, timer/energy order, negative inactive
timer, energy clamp/VR immunity, depletion, explicit phase differences, absent
effect and bounded malformed input. The existing13 movement groups still pass.
These are static/data/port algorithm checks. Original gameplay/native Windows
comparison remains required before a fidelity claim.
+216
View File
@@ -0,0 +1,216 @@
# Original lab trigger and camera sequence
Static executable/GAM investigation, 2026-10-24. VAs are preferred-base
Neutron.exe addresses (these text offsets are VA-0x400000). Port runtime
verification is separate; no original gameplay comparison has succeeded.
## Recovered sequence
LV1B STRT STARTEXP at GAM0x5B0E starts LABEXP. AITrigger labexp at0x18FAD
selects labexp1 when SCENE30; original NewGame starts with SCENE30. Chain:
LABEXP1 -> SITGODDARD -> LABEXP2a -> LABEXP2 -> labexp2b -> LABEXP3A ->
LABEXP3 -> labexp3b -> GOCARL -> GOGODDARD -> WATCHGODDARD -> TELGODDARD ->
GODDARDDIS -> TELFX1OFF -> TELGODDARD2 -> end -> jimend -> default.
CAM/MCA nodes supply16 speech cues in this sequence. Speech end, not a guessed
fixed cutscene duration, advances the nodes.
STRT deferred dispatch0x4426A7 validates a C3DTriggerType target, then clears
player control through game slot0x118 before dispatch0x4426B7..C1. CAM activation
0x4165E2 PlayerControlled='none' preserves control, 'NULL' clears it, named existing
objects receive control. DEFAULT0x447CF0 restores Jimmy, enables inventory, and
clears the global skip flag at0x447F89. SCENE30 calls Jimmy help/inventory callback
0x42AB60; it does not unlock the exit or simply advance the task to60.
AI trigger actions0x40C300 execute synchronously: actor animation/state/speed,
patrol, hide/show, named-marker teleport, yaw; then conditional child selection
0x40C230 exact-matches current TaskName state to ActivateStateN and selects first
existing ActivateObjectN. 0x40C9BF/0x40CA26/58 dispatch child or NextTrigger.
SITGODDARD does not wait for SIT animation. GOGODDARD sets actor state3/speed260/
patrolGODDARDPAT1 and starts WATCHGODDARD immediately. Patrol movement is concurrent
and is now consumed by ActorPatrol with recovered support and provisional wall response.
## Camera formulas and timing
CAM0x415FC2 checks sound handle through0x47D890; finished sound deactivates target
animation then dispatches NextTrigger0x4160A4..E2. MCA0x430DD2 waits similarly,
advances to next non-none target, then finisher0x4311F0 dispatches NextTrigger.
Port uses exact prepared PCM sample duration for deterministic stepping; actual
hardware playback latency/end state is not yet matched to the original handle.
CAM0x4161CD..585: CameraType2 eye=authored camera position, look=target root.
Otherwise D=clamp(InitialDist-ZoomSpeed*t,MinDist,MaxDist). ViewFromCamera0 uses
eye=targetLocalToWorld(TargOffsetX,TargOffsetY,D), look=root+(0,LookVoffset,0).
Nonzero ViewFromCamera (including1/3) uses A=targetLocalToWorld(TargOffsetXYZ),
eye=A+normalize(cameraPosition-A)*D, look=A; LookVoffset unused in that branch.
MCA0x431027..11C1 resets per-shot elapsed time0x43190F. Local eyes:
|Type|Local eye|
|---|---|
|0|(0,40,200)|
|1|(0,140,max(100,300-15t))|
|2|(0,240,max(100,500-35t))|
|3|(200,240,max(100,700-55t))|
|4|(-200,190,max(100,700-55t))|
Transform eye by target Euler/root; look=root+(0,LookatVOffsetN-60,0), constant60
at0x49D5B4/handler0x43116A. Both handlers write exact eye/look via0x431670.
Port uses quantized modern trigonometry; x87 table/rotation-bit identity unverified.
CAM skip0x4160F1 and MCA0x430EED accept Escape/Space/controller/global flag, set
0x4F83E4, stop speech, preserve deactivation/actions and fast-forward the remaining
chain until DEFAULT. Port suppresses newly queued speech while skipping.
## Progression after intro
Teleport explanation AI special0x40CB43..6B changes SCENE30/31->35. Pickup special
0x4365D0..639 changes SCENE35->50 for shrinkray, with additional inventory effects.
Carl callback0x413E50..9D changes50->60,65->70,270->280 after base0x41B810.
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,
weapon behavior and all special pickups remain incomplete.
LOAD LABTONEIGH GAM0xA43 goes tolevel1.gam/startlevel1, SCENE60/radius200.
Underground LOAD0x8360 requires scene65, start riverlab. Binary0x457F32..7F5F:
none requiredtask bypasses; taskvalue-1 bypasses; otherwise >=RequiredLevel and
ExactLevel!=-1 additionally requires equality to that numeric ExactLevel.
Original LOAD contact uses the independent RequiredTask gate. Its interface+C8
vtable0x4D025C has task callback+0x424=0x458880, which only stores the supplied
TaskState at interface+0x494; it does not apply animated-entity activation rules.
Applying generic Animated.RequiredLevel to LABTONEIGH incorrectly disables it
because its TaskName is none while its RequiredTask is SCENE. The director now
leaves LOAD activation alone and SceneInteractions checks its real task gate.
## Implementation and remaining limits
Game/SceneDirector is bounded synchronous dispatch plus stateful CAM/MCA timing.
It preserves original GAM values, task gates, skip actions and reports unknown
classes/cycles/missing targets. Source-authored actor states are mutable copies.
Jimmy creates Goddard at0x423C98->0x41C810 (tag at0x41C88C); initial port position
uses gstart as a placement inference, then the authored SITGODDARD action positions
him before his first shot. Source visibility/collision masks are not fully ported.
Carl/Goddard rendering, speech/music and camera integration run in default lab play;
--story-time N gives a headless comparison point, --skip-intro executes skip actions.
Sprite/OMT props, common patrol, lab interactions and the practice modal are integrated.
Fades, complete collision/sensing, animation timing and full inventory remain incomplete. Model pivot/grounding remains provisional. Tests exercise original
sequence/control restoration, all five MCA formulas, CAM modes, task gates,
bounded cycles and actual decoded sound durations; GPU story12s render is verified
under Linux llvmpipe with zero validation errors. This does not prove original fidelity.
## Lab jet pack (internal tag SHRINKRAY) and Carl interaction follow-up
Read-only static source investigation plus managed regression execution. Original
source EXE SHA-256 is f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8.
Source GAM level1b SHA remains recorded in original-manifest.json. No original
binary was executed for this follow-up.
### Lab jet pack: ordinary collection and the exact special gate
GAM0x1799 is3PIC tagshrinkray, PickupIndex301, PointValue50, Radius125,
SoundIndex116, noPIC_NUMBER/RequiredPicNum/PickedUpIndex. Its generic contact
0x435CE0 accepts the active player, rejects an already acquired index, runs the
prerequisite virtual complete+0xD8, marks ordinary acquired state1 at0x435E11,
hides and disables contact. It invokes special hook0x4365D0 at0x435FCB before
positive score0x435FED.
The special hook compares ObjectTag to SHRINKRAY at0x4365D7..E7 (literal0x4F050C)
and SCENE exactly35 at0x4365ED..FD. Only that gate performs:
1. Active Jimmy complete+0x1E8 at0x43662C, resolved through complete vtable
0x4A3BDC to0x42AF00: capture current level code and physics root at complete
+0x1E48/+0x1E38. The port emits CheckpointCaptured(root); it does not guess
that this is the unidentified TSK StoredVector or change a STRT checkpoint.
2. SCENE50 assignment0x436632..639.
3. Inventory setter0x4038C0(group0,item3,state1) at0x43663E..644.
4. Help/item-information page0 via0x406F90(0), call0x43664B.
5. Jimmy complete+0x174(3) at0x43667C..67E, resolved to0x428D50 gadget selection.
Collecting this tag outside SCENE35 still performs ordinary acquired/score behavior,
but does not receive these special side effects. The port preserves this boundary
rather than adding a minimum-level restriction. It emits HelpRequested(0) and
Inventory.GadgetSelected(3); presentation, modal pause and the jetpack motion/effect
consumer are separate integration work.
### Carl: entering talk precedes dialogue, rather than following its end
Carl interface is complete+0xC0, vtable0x495364; complete vtable0x495804.
InitObject0x413D60 sets radius100 through interface+0x110 at0x413E2F..36 and
support factor0.75 via+0x100 at0x413E3E..45. This supports a100-unit root
contact radius, not a model-sized capsule assumption.
Inherited contact-enter0x40A3C0 first handles base collision.0x40A44C..45C checks
that the contacted entity is the actor's resolved TargetName (complete+0x6C0,
interface+0x600; resolved at0x40948B..49A). If actor AIState6,
0x40A676..68D calls complete+0x124(0). C3DFriend update0x41B950 runs general
AI0x408000 first and, whenever resulting AIState0, calls complete+0x140 at
0x41B972..988. Carl's complete+0x140 is0x41B7B0.
That dispatcher obtains complete+0x17C=0x41BB20. This searches five TalkTriggerN
names in source order, requiring an existing target, TalkState!=-1 and either
exact actor TaskState or wildcard-2. It retains the selected object before any
task mutation. With a match, it invokes complete+0x180=0x413E50 FIRST, then
dispatches the chosen object's interface+0x5C with that object itself as caller
at0x41B7D3..D8. It increments the conversation counter, sets AIState9 at
0x41B7F0..F7, and invokes desired-facing hook+0x148=0x4093E0. Without a match,
it leaves state0 and retries on later updates without awarding points.
Carl0x413E50 calls base0x41B810 (+100 score, zero velocity through interface+0x410)
and then maps SCENE50->60,65->70 or270->280. Thus the normal lab route changes
to60 BEFORE starting neutron1a, and the exit may pass its gate while the dialogue
is running. The port does not award or advance on conversation end. General
state6 visibility/FOV sensing0x409CC0 and desired-facing smoothing are not yet
implemented by this contact subset; entering the recovered100+60 root-sphere
contact path is supported. Other friend classes do not reuse Carl's derived hook.
Carl TaskState override0x413F30 invokes generic activation, then LV1B branch
0x414068..118: SCENE outside0..60 deactivates;31..60 resolves CARLESC3 and sets
state6/position; states below60 activate;60 leaves generic activation unchanged.
This runs on every assignment, including repeated values. On scene initialization
or reset, call SceneInteractions.Reset AFTER SceneDirector.Begin to restore the
class callback and acquired-item visibility after actor reset.
### Inventory and objective persistence
SceneInventory preserves the19 signed TSK inventory values (9 group0,10 group1)
with owned arrays and bounded indices. Source0x4038C0 writes an item state at
group pointer0x4F8164[group]+40*item+0x24;0x403950 reads a signed short from
the same location. Unknown existing wire values remain unchanged unless the port
performs a recovered assignment. The separate29-item consumable group/counts are
not silently conflated with these two groups.
The TSK OtherCounter global0x4F8194 is now identified as the current objective
selector. SCENE setter0x45F990 uses byte/target jump tables0x45FC48/0x45FBF0 and
0x45FD98/0x45FD40 to call0x406F50(objective,1). That helper clears44 transient
flags at0x4F7D00, stores the selector0x4F8194 and sets flag[objective]=1. Relevant
lab milestones35/50/60 select1/2/3;65 does not replace the selector. The port
maps all44 supplied milestone states (including140/141 selecting8), exposes
CurrentObjective/ObjectiveChanged, and saves the selector in OtherCounter.
The lab stationary objective panel and practice modal are integrated; timed UI
slides/highlights and remaining objective consumers are separate work.
### Verification and boundaries
Run source scripts/env.sh, then dotnet run --project tests/GamePort.InteractionTests
-- ../Original. Managed checks cover the actual authored intro/skip/explanation,
task35->50 shrinkray with exact event order and+50, Carl task-position/contact/
talk with pre-dialogue60/+100, original LABTONEIGH destination, TSK write/reload,
no repeated acquisition or talk, outside35 behavior, first-existing/wildcard talk
selection, no-match/no-award, strict160 contact threshold, controlled-player gate,
inventory bounds/array ownership and every objective mapping against the original
EXE dispatch tables. Eleven exact instruction sequences support the decisive
call sites/constants. These are implementation/data checks, not original gameplay
comparison or native Windows validation.
Contacts now call OriginalBodySupport.QuickMagnitude, which translates the original
lookup algorithm with generated sine/acos tables; eight float-bit outputs now
match isolated original DLL probes. Full table bit identity, exclusion lists,
specialized contacts, body resolution and general AI sensing remain incomplete. Other special pickups remain reported unsupported.
## Corrected pickup identity and modal
The source tag SHRINKRAY is a prototype name. screens.omt Canv120 explicitly
says GET JET PACK; inventorygroup0/item3 also gates powered jumping. User-facing
notes must call this the lab jetpack.406F90(0) opens PracticeYesNo169 and pauses
the game; it is not a generic help page. Yes enters VR04/PHONEBOOTH with current
level/current STRT return context, while No resumes. See ui.md and jetpack.md.
+97
View File
@@ -0,0 +1,97 @@
# Level3B / Level3E resource evidence
Static investigation, 2026-10-24. Source: unmodified `Original/Neutron.exe`, SHA-256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Addresses are preferred-base EXE virtual addresses. File offsets for the addresses
below equal VA minus `0x400000` in this PE. No original code was executed.
## Findings and scope
The user is correct that **`gam/Level3B.gam` and `gam/Level3E.gam` exist**.
Both parse successfully as 1,777-byte entity files with four entities:
`3JIM`, `STRT`, `LOAD`, `3SBU`. Their bytes after the four-byte level header
are identical; headers are `LV3B` and `LV3E`. GAMs contain entity properties,
not replacement scene mesh/material/texture payloads.
The original executable also has explicit, separate archive-opening paths for
**`omt/level3B.omt` and `omt/level3E.omt`**. Those files are absent from the
supplied original tree. This is verified loader behavior, rather than an inferred
same-stem pairing or merely an unused string reference. No shared-map alias is
present on the traced initialization paths.
However, whether these scenes occur in normal shipped gameplay is **unverified**.
Small identical entity bodies suggest possible stubs/development leftovers; that
is an inference, not established intent. The primary's corpus check found no
serialized GAM string references to either scene name/code and no source TSK
starting in `LV3B`/`LV3E`. This does not exclude hardcoded transitions or other
entry routes. Do not describe the archives as confirmed required files for the
normal game, or tell the user their GAM files are missing.
## Class and archive dispatch
| Evidence | Level3B | Level3E |
|---|---|---|
| Complete class | `CLevel03BGame` | `CLevel03EGame` |
| Constructor | `0x451AF0` | `0x452690` |
| Constructor sets level code | `0x451BA8`: push `LV3B` | `0x452748`: push `LV3E` |
| Factory calls constructor for code | `0x45D635` | `0x45D78B` |
| Complete vtable | `0x4C7830` | `0x4C8A00` |
| Initialization slot `+0xB4` | `0x451C50` | `0x4527F0` |
| Literal archive string | `0x4F1F24`: `level3B.omt` | `0x4F1FFC`: `level3E.omt` |
| Archive string length/copy | `0x451C99` / `0x451CC5` | `0x452839` / `0x452865` |
| Dispatch archive loader slot `+0xE4` | `0x451CE8` | `0x452888` |
Both vtable `+0xE4` entries are `0x44E7B0`. This function copies the supplied
archive filename, invokes slot `+0x16C` with the directory string `omt` at
`0x4F1B1C` (`0x44E7FF..0x44E81E`), builds the string argument, calls the file
stream helper `0x476170` at `0x44E8B4`, then calls database helper `0x476000`
at `0x44E8CE`. It stores the file stream/database in globals
`0x5099D8` / `0x5099C0`. There is no fallback archive name in this routine.
File helper `0x476170` imports `OMediaFilePath` and `OMediaFileStream`
constructors (`0x48D188`, `0x48D184`). Database helper `0x476000` imports
`OMediaDataBase(OMediaStream*)` at `0x48D19C`. This confirms the archive string
goes to the real file/database path rather than to a debug label.
The level-code-to-GAM path is separate: the switch at `0x4607F1` selects
`level3b.gam` (`0x4F49C4`) at `0x46083E`; the `LV3E` branch selects
`level3e.gam` (`0x4F49A0`) at `0x46088E`. The level registry also contains
code/GAM records at `0x4F3BE0` and `0x4F3C4C`. Existence in the factory and
registries proves registration, not a normal-gameplay route.
## Missing-file handling
The traced archive-opening path does **not** directly abort, choose a shared map,
or produce procedural replacement geometry when the map archive cannot open:
- `0x476000` initializes its result to null, checks the stream pointer and its
open byte `+0x24` (`0x47602A..0x476033`), and returns null without constructing
a database when either condition fails.
- `0x44E7B0` retains the resulting null database and returns. It does not itself
throw or dispatch an explicit missing-map error in the examined path.
- Base geometry/entity-resource enumeration `0x44D4F0` checks `0x5099C0` at
`0x44D513`; null skips enumeration to `0x44D7F2`.
- The child initialization then continues and separately constructs `3SKY` through
the factory `0x459CB0`. Its sky resource is `omt\nightsky.omt` at `0x4F1DA4`,
passed at `0x451D35` / `0x4528D5`.
Thus these archives' absence means the port has no recovered scene geometry for
the registered entries. It does **not** prove an original startup crash, and this
static trace cannot establish whether the shipped game ever tries to enter them.
## Reproducible checks
Run from `GamePort`:
```sh
python3 tools/binary/level_resource_evidence.py
```
The read-only script passes **13 decisive instruction byte assertions**, resolves
both class vtables, verifies the archive directory/names, parses both GAMs, reports
their SHA-256 hashes, confirms their identical bodies and checks archive presence
case-insensitively. It reports normal-gameplay reachability as unverified.
Confidence: high for supplied-file presence, original loader mapping and null-map
enumeration handling; unverified for gameplay reachability, intended stub status,
and original runtime outcome.
+309
View File
@@ -0,0 +1,309 @@
# Follow-up original collision evidence
Static investigation and isolated copied-DLL probes,2026-10-24. The bounded
OriginalBodySupport module now translates the vertical support/segment path.
This does not supersede the complete provisional SceneCollision solver or prove
original gameplay fidelity; full body collision/pivot/cadence remain unresolved.
HasCollision is serialized type6 at EXE40D423 into interface+584. LV1B includes
-1defaults, explicit1Carl, explicit0plant/teleport/OMT props. Per-object collision
exclusions DisableCollisionID4730F0/EnableCollisionID473170 maintain separate lists;
visibility/material alone cannot choose collision masks.
Jimmy grounded update42469B..4246E3 sets physical-radius slot264 to60 when WORD
4F0588!=0, versus160 otherwise. Shape/animation reset42369A..4236AA sets authored
radius60 through interface slot110, forwarding the radius. Gate semantics/root and
vertical support differ from the preview feet capsule: do not blindly replace its
radius24 with60 and call that original collision. Static resolver47B4B0 ->47BBB0 ->
47BD80 reads interface+15C radius; recovered vertical support47B890 is below.
ASE mode2 conversion of standing Jimmy was executed against a copied DLL in the
isolated harness: its raw bounds remain unchanged and both frame offsets are zero.
No hidden scale/pivot correction was found. The remaining sole/root discrepancy
must not be replaced with a guessed scale or translation.
## Reproducible source evidence
All addresses below are preferred virtual addresses. Neutron `.text` addresses
map to file offsets VA minus `0x400000`; OMT2 addresses should be mapped through
their PE section table. Original files are only read, never executed or modified
by this investigation. Bounded `objdump -d -M intel --start-address=...
--stop-address=...` reads were used for instruction interpretation.
Run `python3 tools/binary/collision_evidence.py` from GamePort. This read-only
script checks27 decisive EXE/DLL instruction-byte sequences, resolves interface and
game vtable slots from original PE bytes, and derives source mesh/GAM facts. It
uses the existing bounded PE, OMT and GAM readers and adds no dependencies.
Neutron.exe SHA-256 is
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
The script does not execute original instructions; its calculated values are
static consequences, not observed original gameplay.
## Jimmy PostLoad: radius and vertical clearance
Jimmy's game interface is complete object plus `0xC0`, vtable `0x4A373C`.
The **interface** slots below must not be looked up in the complete-object OMT
vtable `0x4A3BDC`.
| Interface slot | Implementation | Field/behavior |
| --- | --- | --- |
| `0x100` | `0x4711E0` | Authored support factor at interface `+0x2C`; forwards to slot `0x254` |
| `0x110` | `0x471240` | Authored radius at `+0x34`; forwards to slot `0x264` |
| `0x250` | `0x471AF0` | Current support factor getter, `+0x154` |
| `0x254` | `0x471B00` | Current support factor setter, `+0x154` |
| `0x260` | `0x471B30` | Current radius getter, `+0x15C` |
| `0x264` | `0x471B40` | Current radius setter, `+0x15C` |
| `0x310` | `0x472300` | Current physics position, `+0x214..+0x220` |
| `0x318` | `0x472330` | Physics position setter and changed hook |
| `0x40C` | `0x423610` | Jimmy PostLoad |
`0x423631` passes the string `Calling PostLoad for C3DJimmy()` (VA `0x4EF3B4`).
After restoring the base shape through complete-object slot `0xAC`, PostLoad
pushes `0x42700000 = 60.0f` at `0x4236A3` and calls interface slot `0x110` at
`0x4236AA`. It then pushes `0x3FA1EB85 = 1.2649999856948853f` at `0x4236B3`
and calls interface slot `0x100` at `0x4236BA`.
The earlier player constructor factor `0.7` at `0x4373C2..0x4373C9` is therefore
superseded by Jimmy PostLoad. It is not friction: constructor friction `0.8`
goes through `0x4711B0` and interface slot `0x24C`. The factor's original source
name is not recovered; "support factor" describes its verified use below.
Grounded update `0x42469B..0x4246E9` sets the current radius again. It uses 160
when WORD current gadget selector `0x4F0588` equals zero and 60 otherwise. The
selector is initialized to `-1` by Jimmy constructor `0x42225F`, so no-gadget
grounded behavior takes the 60 branch. Grounded gadget-specific changes are
distinct from a uniform player body dimension and must remain state-dependent.
This establishes original radius 60 for the ordinary path; it does **not**
establish a vertical capsule of height 209.4361. The current provisional capsule
radius 24 cannot be described as recovered, and simply replacing that radius
without recovering root/solver conventions would mix two different models.
## Vertical support handler `0x47B890`
This handler queries source geometry separately from the horizontal/ceiling
triangle resolver. It exits immediately if geometry collision byte `0x4F69E5`
is zero. Its active path reads radius through slot `0x260` and support factor
through `0x250` at `0x47B8B0` / `0x47B8BE`. The multiplication at `0x47B8C8`
stores `radius * factor` (the subsequent `push` means the store at `0x47B8D5`
is local offset `+0x08`, not `+0x0C`; tracking that stack shift matters).
Recovered active-path outline, omitting callback bookkeeping:
```text
r = currentRadius
h = currentSupportFactor
clearance = (h == 1 or h < 0.1) ? r : r*h
P = currentPhysicsPosition
Q = previous/resolverPosition (slot 0x2F8)
top = max(P.y, Q.y)
if segmentQuery(Q, P, 0) hits H:
top += length(P-Q) - length(H-Q)
start = (P.x, top + clearance, P.z)
end = (P.x, P.y - 2*r, P.z)
if segmentQuery(start, end, 0) hits F:
resolvedY = F.y + r*h
if preventLowering(slot0x208) and P.y > resolvedY: return
setPosition(P.x, resolvedY, P.z)
zero acceleration.Y and velocity.Y, preserving X/Z
setGrounded(true)
preserve hit polygon and shape for callbacks
```
The ray span uses the conditional `clearance`; the final support height adds
the stored product `r*h`. The distinction matters for factors below0.1, although
ordinary Jimmy's1.265 branch uses the same product in both places. Ray assembly
is `0x47BA33..0x47BAD1`, hit Y plus product `0x47BAE1..0x47BAEF`, position write
`0x47BB23..0x47BB32`, grounded write `0x47BB7C..0x47BB80`. The handler invokes
an optional interface landing hook only when prior grounded byte `0x695D49`
was false (`0x47BB51..0x47BB5E`).
For radius60 and PostLoad factor1.265, float32 clearance is **75.9000015** world
units. At the actual lab spawn XZ, the only source polygon below GAM root26.6619
is Box06/shape71/polygon497/material17 at Y=0.5486332333; its stored normal is
approximately `(−0.00002292,1,−0.00002965)`. The next vertical hits are overhead
surfaces at473.6309 and491.0861. Thus the ordinary successful flat support branch
predicts physics root Y about **76.448635**, not a permanent root-to-floor offset
of26.1133 inferred from serialized GAM placement.
That is a conditional static prediction, not an original frame capture. Initial
GAM placement can be corrected by physics after loading. With raw standing
minimum local Y=-64.6165, the predicted root would put its lowest raw vertex
11.2835 units above that floor. This remaining discrepancy must not be turned
into an invented scale factor. The port's present sole-based render transform
and floor-derived actor offset remain separate approximations.
## Shape bounds and render transform
Complete-object shape-change hook `0x462270` reads current shape pointer `+0x8C`,
copies shape bounding-sphere radius `shape+0x4C` into interface slot `0x110`,
then asks shape virtual `0x44` for six cube bounds. It forwards two four-float
records through interface slots `0x2E8` / `0x2E0`, stored at `+0x1D4` /
`+0x1C4` by `0x472120` / `0x4720C0`. These are bound records, not a recovered
capsule radius/height constructor. Jimmy's explicit PostLoad radius60 follows
the base-shape restore and therefore overrides the automatically copied radius.
OMT shape `prepare` at DLL `0x100062A0` computes sphere center and maximum
vertex distance (`0x100062EE..0x10006389`) using the bounding-box center finder
`0x10005470`. This computes bounds and does not itself move the vertices.
Physics-to-render position hook `0x4624B0` reads interface slot `0x310` and copies
XYZ directly to complete-object offsets `+0x44,+0x48,+0x4C` (interface-relative
`-0x7C,-0x78,-0x74`) at `0x4624CA..0x4624E8`. No extra vertical translation
or scalar multiplier occurs in this hook.
Jimmy complete-object slot `0x7C` targets import thunk `0x47EDB4`, which jumps
through IAT `0x48D36C` to OMT `get_dynamic_offset@OMedia3DMorphAnim`, DLL
`0x100033F0`. It reads current animation frame `+0x98` and returns that frame's
XYZ offsets `+0x08,+0x0C,+0x10`; without a frame it returns zero. Base frame
constructor DLL `0x10021180` initializes those offsets to zero. Therefore this
hook has no hardcoded Jimmy floor/pivot adjustment. Full converter/frame writes
still need controlled probing before asserting every relevant offset stays zero.
## ASE object mode2 does not imply a scale correction
The DLL object-mode global `0x1013D6CC` has five absolute-address references in
the inspected binary (the script lists their operand addresses). ASE-specific
reads at `0x1001396E` and `0x10013CBF` control GROUP/GEOMOBJECT separation. ASE
constructor `0x10012DF1` sets its "first object" flag1 and `0x10012DF7` sets
group depth0. In object mode2, the first ungrouped GEOMOBJECT clears that flag
and does not request a new shape (`0x10013CD2..0x10013D15`).
`jimstop.ase` contains one GEOMOBJECT, no GROUP and no TM_ANIMATION. Its ordinary
vertex-list handler `0x10014EE0` parses each XYZ, swaps Y/Z and appends the
four-float vector to either base-shape vectors or the current morph frame
(`0x10014F59..0x10014FA8`). There is no multiplication by NODE_TM scale or a
constant0.4 in that handler. NODE_TM parsing `0x10014130` stores matrix rows
and an inverse matrix in converter state; this is not evidence that the baked
mesh vertices should be transformed a second time.
The earlier mode0 probe matched raw standing bounds (rendering.md). The follow-up
mode2 animated probe now also matches them; its two jimstop frames both have
offset(0,0,0). Do not apply an unproven0.4 scale or call the actor pivot solved.
## Static scene inclusion versus entity activation
Static grid registration is `0x479140`, called by scene-object InitPhysics
`0x464B00`. It visits every shape polygon and makes these exclusions:
1. `0x4794C0` handles checkpoint materials named exactly `cstart` or
`ccheck1`..`ccheck9`, marking their polygon word at `+0x1C` as4 and calling
the game checkpoint hook.
2. `0x4797A0` asks game virtual slot `0x134` whether to consume a polygon.
For CJimmyGame and CLevel01BGame this slot is `0x475CD0`, which returns false.
3. Otherwise it computes polygon centroid/radius and XZ bounds, then registers
it in a260×260 grid with cell index `trunc(world*0.002+130)`.
The checkpoint filter immediately returns false when polygon material is null
(`0x4794E8..0x4794ED`). **Null material is therefore retained for static collision**,
even though it is skipped by drawing. This directly supports retaining the lab's
325 unresolved-material triangles. The actual LV1B materials contain no
`cstart`/`ccheck*` names, so all2,869 source triangles reach this registration
path. No general "decorative" name filter was found in it.
Two grids are populated: all polygons at base `0x5CFC7C` and a wall/ceiling grid
at `0x509B24` when stored polygon normal.Y is strictly below0.7
(`0x47987D` captures normal.Y; `0x4798B3..0x4798CF` performs the comparison).
The vertical segment query `0x47C6E0` uses the all-polygon grid, retaining the
nearest hit along the input segment. The static sweep `0x47B4B0` uses the
wall/ceiling grid. Its radius comes from interface slot `0x260`; closest-hit
state feeds recursive sliding and callbacks. Its full narrow-phase behavior
`0x47BBB0 ->0x47BD80` remains incompletely translated, so the current port's
two-sided capsule and0.65 slope threshold are still provisional.
Entity collision is a different layer. HasCollision registration at `0x40D423`
binds a type6 property to interface `+0x584` (complete object `+0x644`). During
activation, `0x40E40A..0x40E45D` treats-1 as "retain default", zero as disable
(slot `0x3A4` plus slot `0x214=false`), and nonzero as enable (slot `0x3AC` plus
`0x214=true`). This is separate from visibility and the all-polygon static grid.
Actual LV1B values are nine default-1, one explicit1 and seven explicit0.
Carl is explicitly enabled; plant/teleport/OMT props provide explicit exclusions.
`DisableCollisionID` `0x4730F0` searches global entities by ObjectID at interface
`+0x404` and adds matches to the caller's exclusion list `+0x254` if absent;
`EnableCollisionID` `0x473170` removes matching entries. Parent/entity analysis
also recovered the ordinary pair test at `0x47B3E0`: strict actor-root Euclidean
distance less than the sum of current radii, followed by exclusions. Mode2 pair
geometry follows another path and must not be replaced with that metric blindly.
## Recovered guard, ray kernel and frame phase
Support slot208 is4719D0, reading interface+13A. Guard47BAFD..47BB0A rejects
currentRoot.Y strictly greater than hitY+r*h. It does not inspect velocity; it
prevents lowering a body above support even while that body is descending.
C3DAI constructor407B4D..51 enables the authored flag through470F70, which
forwards to current flag setter4719E0. The earlier label "upward guard" was
imprecise. Clearance comparison48D920 is float0.10000000149, not0.5.
Goddard inherits support factor0.30000001192 at407B2B/407B30; PostLoad41E64A/
41E651 overrides radius to130, so ordinary flat clearance is39.0. No corresponding
factor override was found in the traced Goddard constructor/PostLoad path.
EXE469B70 is a Moller-Trumbore-style segment test. It normalizes direction using
quick_magnitude, retains source winding, and accepts determinant<=-epsilon when
twoSided=false, or absolute determinant>=epsilon when true. Epsilon4D5E40/44 is
±1.1920928955078125e-7. Barycentric u/v boundaries are inclusive; t>=0 is accepted
but t>=segmentLength is rejected (469DDD/469DEE). Hit XYZ is correct: the pop edi
at469DF6 shifts subsequent stack operands, so apparently repeated offsets do not
mean repeated direction components.47C6E0 retains strictly nearer hits; equal ties
follow original grid traversal. No slope-normal cutoff is applied by this query.
Physics479D20 captures prior grounded via218 at479D2E, saves695D49, and clears
current grounded through21C at479D4E when geometry-support flag1C8 is set.
Impulse/acceleration/gravity integration precedes wall/ceiling resolution47B4B0;
support47B890 is called at47A235 after the resulting position is assigned, then
friction47A330 and small-velocity clearing follow. The new support module preserves
this phase boundary; it is not the entire479D20 implementation.
## quick_magnitude lookup recovery and actual DLL comparison
OMT1001FF70 keeps largest absolute component m and other components a,b, computes
index=trunc((a²+b²)*16384/(a²+b²+m²))&16383, then returns m/sine[halfAcos[index]].
Initializer100EDC00 uses these stored doubles:
- sine[i]=float(sin(i*0.0003834951969604492)), with exact quadrant overrides;
- halfAcos[i]=trunc(acos(i/8192.0-1)*2607.5945876921437*0.5).
This is a sine table, not the cosine table initially suspected. The isolated
copied-DLL probe observed FNV1a32 fingerprints431383b5 for all16384 sine floats
and4f800433 for all16384 half-acos words. Modern Python regeneration matches both
whole-table fingerprints. The C# function also matches eight actual original-DLL
float-bit outputs, including3/4/0 ->40a0001e,1/1/1 ->3fddb16e and500/100/300 ->
4413eb31. Zero is handled directly in the port; the observed DLL also returns0.
This verifies these math references on the tested environment; it is not a full
x87 arithmetic or native Windows gameplay equivalence claim.
## Implemented boundary and validation
src/GamePort/Game/OriginalBodySupport.cs provides QuickMagnitude, a source-winding
Trace over supplied SupportTriangle records, and Resolve for SupportBody input.
Resolve returns root/velocity/acceleration, supported/landing flags, source hit
identity and the support anchor written via2F4. The caller owns prior/current
grounded phase, geometry-registration masks, landing callback and hit bookkeeping.
Trace scans linearly instead of260x260 grid traversal; tie identities can differ.
Double/single arithmetic does not reproduce every x87 temporary rounding boundary.
This is a separate root-support component, not a replacement feet capsule.
Run source scripts/env.sh then dotnet run --project tests/GamePort.SupportTests.
All13 groups pass: original-DLL math bit references; source winding/two-sided
override; strict endpoint/start; nearest/tie identity; root/velocity/acceleration;
height guard independent of velocity;0.1 factor boundary; crossed-geometry query
lift; disabled geometry; invalid input; ten-second gravity stability/jump; actual
2869 lab triangles including invisible proxies and predicted root76.448635.
tools/binary/collision_mode2_probe.c builds with local i686-w64-mingw32-gcc and
runs only via tools/recon/reference_capture.py --asset-probe --probe-executable
artifacts/binary/collision_mode2_probe.exe in a copied installation. Original and
network paths are absent from that namespace. Artifacts/binary/mode2-jimstop.log
records successful conversion:426 points, matching raw bounds, one sequence/two
frames and zero offsets. An initial probe-reader error treated sequence pointers
as frames; the corrected bounded vector-of-sequences/list-of-frames traversal
was verified against100203C0/10020870. No original assets were written.
The follow-up jimjump animation-only conversion also succeeds after allowing its
legitimate empty base shape: one sequence, three frames of426 points, all offsets
zero. See artifacts/binary/mode2-jimjump.log. Empty base center/bounds are not
initialized geometry and must not be interpreted as a transform. The final probe
suppresses that center output when the base is empty.
Full horizontal/ceiling narrow-phase sliding, dynamic collider activation/boxes,
exact body/render pivot and original gameplay/native Windows comparison remain.
+252
View File
@@ -0,0 +1,252 @@
# Original patrol and Goddard lab route
Static evidence from the immutable `Original/Neutron.exe`, `OMT2.dll` and
`gam/level1b.gam`, investigated 2026-10-24. Addresses below are preferred-base VAs;
the executable text file offsets are VA minus `0x400000`. No successful original
runtime comparison verifies the resulting motion. The follow-up at the end records
the bounded runtime AI implementation and its separate test/physics limits.
## Relevant dispatch and fields
Goddard's interface pointer is complete object plus `0xC0`. His interface vtable
is `0x49F480`, complete-object vtable `0x49F920`. His update `0x41DEE0` reaches
the general AI update `0x408000` at `0x41E520` for the ordinary patrol state,
after clearing interface `+0x8A8` (complete `+0x968`, animation override).
|Complete offset|Interface offset|Meaning/evidence|
|---|---|---|
|`0x6C4`|`0x604`|Movement speed, float; AI trigger integer AISpeed converted to float|
|`0x6C8`|`0x608`|Current AI state; `3` is patrol, `1` is waiting, `7` is timed waypoint wait|
|`0x6CC`|`0x60C`|Previous AI state, assigned by setter `0x4089B0`|
|`0x6E4..6EC`|`0x624..62C`|Destination minus current root position|
|`0x6F4`|`0x634`|Within arrival distance flag|
|`0x6FC`|`0x63C`|Exact square-root 3D destination distance|
|`0x708`|`0x648`|Initial PatrolPoint tag|
|`0x820`|`0x760`|Patrol/run animation alias|
|`0x870`|`0x7B0`|Waiting animation alias|
|`0x8C0`|`0x800`|Current waypoint interface pointer, initially null|
|`0x8C8`|`0x808`|Previous waypoint pointer|
|`0x8D0/8D4/8D8`|`0x810/814/818`|Euler smoothing factors X/Y/Z|
|`0x8E8..8F0`|`0x828..830`|Current destination root position|
|`0x90C`|`0x84C`|Timed waypoint wait remaining seconds|
|`0x944`|`0x884`|Arrival threshold, default `110.0f` at `0x407D9A`|
|`0x948`|`0x888`|Alternate movement mode flag, default zero; nonzero uses facing vector and threshold440|
|`0x968`|`0x8A8`|Suppress automatic animation selection while nonzero|
The normal lab Goddard path uses default arrival threshold110 and mode flag0;
the inspected Goddard constructor does not replace those defaults. His Euler
smoothing factors are explicitly overridden to `(0.3,3.2,0.3)` at
`0x41C8DB..0x41C90C`.
## State3 movement, arrival and update order
The general AI state dispatch table at `0x408980` maps state3 to `0x408518`.
Before that dispatch, `0x408000` calls animated/base update `0x40E050(dt)`.
That calls shared physical integration `0x462520`, which reaches game physics
through slot `0x130`, and then `0x458930 -> 0x473240`. The latter calls the
AI interface slot `0x3D8 -> 0x4096E0` for orientation smoothing. Thus previous
velocity and previous desired Euler angles are consumed before this update
computes the next patrol velocity and angle target. A port that immediately
integrates the newly selected velocity differs by one simulation tick.
Patrol performs the following operations in source order:
1. Complete slot `0x12C -> 0x408C90`: when current waypoint pointer is null,
resolve PatrolPoint tag (`complete+0x708`) with first case-insensitive tag
lookup `0x474070`. If still missing, set state1 and clear horizontal velocity,
preserving its Y component. Otherwise call complete slot `0x130`.
2. Slot `0x130 -> 0x408D40`: normally copy waypoint root to destination and compute
`delta = waypoint.Position - actor.Position`. Store full 3D Euclidean distance
(`sqrt(dx*dx + dy*dy + dz*dz)`) at complete `+0x6FC`. A separate movement
special flag can retain a previous destination; its nonordinary behavior is
outside this lab route.
3. Ensure the patrol/run animation is active (`0x408549..0x40856A`), looping,
unless animation override is nonzero.
4. Unless an independent temporary-target timer is positive, complete slot
`0x134 -> 0x408E40` computes `velocity = delta / quick_magnitude(delta) * speed`.
State3 has multiplier1. Full XYZ velocity is assigned, rather than retaining
old vertical velocity. If already marked arrived, assign zero XYZ instead.
5. Complete slot `0x128 -> 0x408BC0` compares exact stored distance with threshold.
**Strictly less than110** sets arrived true and calls an arrival virtual
method. Distance greater than110 clears an existing arrival flag for state3;
exactly110 leaves it unchanged. The arrival method is `0x41E580 -> 0x409890`
for Goddard and does nothing in state3 (its special branch is state10).
6. If arrived and the current pointer is a PAT, process wait/next below.
7. At `0x408958..0x40896C`, complete slot `0x138 -> 0x409140(dt)` computes new
destination Euler angles from the final destination-minus-root vector.
The velocity assignment therefore precedes the arrival comparison: on the first
update entering the arrival radius, it may retain a nonzero newly selected
velocity for the next physical step while already selecting the next waypoint.
There is no normal exact-position snapping, remaining-distance speed clamp, or
multiple-waypoint traversal loop in this branch.
When a new waypoint is selected, arrival is not immediately cleared or distance
recomputed. On the next update the old arrived flag can therefore select zero
velocity/WAG before the newly computed distance clears that flag; subsequent
update selects RUN and movement again. Avoid replacing this order with a
smooth continuous multi-segment walker while describing it as recovered.
`quick_magnitude` is the OMT export at `OMT2.dll:0x1001FF70`, imported through
`0x48D104`. It uses absolute components, largest-component selection and lookup
tables rather than a direct sqrt. The follow-up `OriginalBodySupport.QuickMagnitude`
now reconstructs those tables from their recovered initializer constants; modern
trig versus original x87 table equality remains unverified. Arrival itself uses
sqrt, not this helper. Zero delta is handled defensively by the port instead of
depending on the original invalid float-to-integer conversion behavior.
## WaitTime and NextPatrolPoint
PAT property loader `0x434DE0` operates on the PAT interface (complete plus
`0xC8`):
|Property|PAT interface offset|PAT complete offset|
|---|---|---|
|CallObjectTag|`0x520`|`0x5E8`|
|ActivateAnim|`0x584`|`0x64C`|
|SoundDatabase|`0x64C`|`0x714`|
|SoundIndex|`0x714`|`0x7DC`|
|NextPatrolPoint|`0x5E8`|`0x6B0`|
|WaitAnim|`0x6B0`|`0x778`|
|WaitTime|`0x718`|`0x7E0`|
At `0x40861F..0x408698`, **WaitTime>0** enters state7, starts PAT.WaitAnim loop1
unless animation override is active, copies WaitTime to actor wait timer and
sets XYZ velocity zero. State7 `0x408370..0x408414` subtracts dt only while the
timer was positive at entry; if the result is **less than or equal to zero** it
restores the previous state, clears arrival and resolves this waypoint's
NextPatrolPoint. It does not consume leftover time to move through the next
segment in the same update. The exact-zero case corrects an earlier report
reading: `0x40838C` uses `test ah,0x41 / jne` to skip an initially nonpositive
timer, whereas `0x4083B0` uses `test ah,0x41 / je` to keep waiting only after a
positive result. On equality x87 C3 makes `ah&0x41=0x40`, so expiry occurs.
The comparison constant at `0x48D914` is float0. A timer already zero at entry
remains in state7. The timed-wait next-point lookup at `0x408406` does not
interpret missing `WAIT`/`SCAN` names specially; the immediate branch below does.
For WaitTime<=0, `0x40869D..0x408757` immediately saves the current pointer as
previous and resolves NextPatrolPoint. If the lookup fails, the literal `WAIT`
sets state1 and literal `SCAN` sets state6. A nonexistent ordinary name, including
`none`, compares unequal to both special literals and leaves state3 until the
next `0x408C90` lookup of initial PatrolPoint; this detail is easy to miss.
`none` is not equal to `WAIT`. Consequently this path can restart a route on the
next update instead of necessarily becoming idle. Any port choosing to stop at
`NextPatrolPoint=none` is making a terminal-route policy approximation, not an
exact translation of these instructions. For the lab cutscene, a later authored
GODDARDDIS action interrupts patrol and explicitly sets state1/SIT/phone2.
CallObjectTag/ActivateAnim/SoundIndex are serialized and loaded, but their generic
execution is **not** recovered from this normal Goddard branch. PAT touch handler
`0x434EA0` calls base touch then only logs when a C3DAI is in state2. All lab PATs
have CallObjectTag=`none`; no invented callback is necessary for Goddard's route.
## Goddard animation and authored route
Goddard constructor (`0x41C9A3..0x41CA79`) sets aliases:
complete `+0x7F8=WAG`, `+0x820=RUN`, `+0x848=FLY`, `+0x870=WAG`,
`+0x7D0=WAG`, `+0x898=RUN`. Literal RUN is at `0x4ECA64`; WAG at `0x4ECA68`.
State3 update therefore replaces the trigger's AIAnim=`walk` with RUN on the
next update, without requiring an invented WALK-to-RUN asset alias. State1
setter starts WAG unless animation override is nonzero; state1's steady update
does not itself force a new alias. A trigger can therefore preserve an explicit
SIT in state1 when its animation override suppresses the setter default.
|Tag / GAM offset|Position|Next / wait|
|---|---|---|
|gstart / `0x960A`|`(4801.444336,38.160038,669.824158)`|none, wait0, WaitAnim sit|
|GODDARDPAT1 / `0x3D5F`|`(5011.098633,16.988688,716.637146)`|GODDARDPAT2, wait0|
|GODDARDPAT2 / `0x3F69`|`(5244.313477,26.268572,-249.976944)`|none, wait-1, WaitAnim sit|
GOGODDARD AIT at GAM`0x3918` sets target C3DGODDARD, AIState3, AISpeed260,
AIPatrol GODDARDPAT1 and AIAnim walk, then immediately begins WATCHGODDARD.
SITGODDARD previously positions Goddard at gstart with yaw180. GODDARDDIS at
GAM`0x48D4` later interrupts by setting AIState1, AIAnim sit, AINewPos phone2,
AINewRotY10. None of these AI triggers waits for patrol completion.
## Heading smoothing and remaining limits
Desired orientation `0x409140` calls OMT vector.angles through `0x48D108`
(`OMT2.dll:0x1001FDA0`), scales the returned integer angular units by
`360/16384 = 0.02197265625f` (`0x48E5B4`) and writes destination Euler angles
through `0x472660`. In the ordinary flat yaw case, the equivalent heading is
`atan2(-delta.X, delta.Z)` in degrees. This mathematical atan2 equivalence is an
approximation to the original table quantization.
The following frame's `0x4096E0` wraps each destination-minus-current Euler delta
at180 degrees, then adds `wrappedDelta * axisFactor * dt`; Goddard Y factor3.2
is recovered above. Factor clamping is absent in this routine. The routine first
checks enabled/dirty flags; collision/arrival conditions can skip updating desired
heading. Full pitch/table equality and actor-floor contact matching remain open.
Shared world gravity/collision also applies during the base update; replacing
the full body solver by direct waypoint interpolation or floor clamping must be
recorded as a port approximation. General stuck recovery `0x40A250`, temporary
targets and AI states other than the normal state3/7 path are not covered here.
Read-only verification checked 17 executable dispatcher/vtable/string and GAM
route assertions: state3 dispatch, patrol virtual targets, WAIT/SCAN/RUN/WAG
literals, both route links, speed260, final WaitTime-1, and absence of actors
named none/WAIT/SCAN. This establishes consistency of the static evidence, not
runtime or visual fidelity. No original files or C# source were changed.
## Runtime follow-up
`Game/ActorPatrol.cs` implements ordinary states1/3/7 plus the common base phase
for state9. Carl state6 also receives that phase; its general FOV/visibility
sensor409CC0 remains unimplemented, while SceneInteractions handles source contact
dispatch. Other states are outside the supported subset. It exchanges root position/velocity
through the injected `PatrolBodyState -> PatrolBodyState` body step. Its own
algorithm does not invent a body radius, support factor, collision solver or
floor clamp. It consumes the prior velocity, smooths the prior yaw target by3.2,
selects RUN, computes the next fullXYZ velocity, compares exact distance and then
processes one waypoint/wait transition. The recovered table magnitude helper is
the default normalizer; a separate injected metric remains available for tests.
Follow-up disassembly also verifies ordinary state1 zeroes XYZ at`0x40835D`
**after** the base physics update. The missing-initial-point transition preserves
Y at`0x408D1E..26`; its enclosing state3 branch still passes through RUN selection
after the resolver returns. States1/6/7 skip new destination-angle selection at
`0x409186..19B`. The port keeps their authored animations rather than forcing
WAG every idle tick. The subsequent TELGODDARD2 camera explicitly requests TALK
after GODDARDDIS requests SIT;40DF18..22 proves this unregistered TALK request
leaves the selected SIT clip/name unchanged. SceneActorVisuals retains that no-op.
The runtime's authored teleport synchronization resets its velocity/route cache
and preserves the authored yaw/animation. This is an explicit port reset policy;
full original teleport bookkeeping is not recovered. Camera-only animation
events do not reset the route. Heading currently changes yaw only using atan2;
full pitch, original angle quantization, dirty flags, temporary targets and stuck
recovery are not implemented here. Physics and original runtime comparison remain
separate integration/validation work.
Verification from `GamePort`:
```sh
source scripts/env.sh
dotnet run --project tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj
```
All9 deterministic groups pass: prior velocity/yaw phase; velocity-before-arrival
and waypoint pause; strict110/equality behavior; wait expiry at exact zero and
discarded remainder; WAIT/SCAN/none and lookup precedence; missing initial Y
preservation and fullXYZ velocity; authored teleport/cache handling; injectable
normalization separate from sqrt arrival; and the actual GAM Goddard route plus
GODDARDDIS interruption. Free-body/held-body fixtures validate AI ordering, not
original body physics, rendering or original gameplay fidelity.
## Carl profile and live integration
Carl constructor413BCB sets speed200. It installs WALK at complete820/898 through
413BFC..1D (literal4ECA54), STOP at7F8/870 through413C22..43 (literal4ED040).
Its yaw smoothing factor remains inherited3.0 from407CF8; Goddard overrides3.2.
The shared state3/7 code is therefore reused with class-specific aliases/factors.
State9 dispatch table408980 jumps directly to408911, adding no new velocity or
animation command. State6 calls the still-unported sensor409CC0 before this
common finisher. No arbitrary proximity-to-dialogue-end task rule was added.
Live runtime bodies now use recovered Goddard130/.3 and Carl100/.75 root support,
source-winding floor queries and the exact source normal.Y<.7 wall-grid mask.
The wall response is still the port's swept sphere, not the original47BD80 solver.
Visuals use those actor roots without an additional sole-based correction.
The remaining raw-sole/root clearance difference is documented in collision notes.
Primary added a tenth test group for Carl's profile, speed, yaw factor and state9.
+104
View File
@@ -0,0 +1,104 @@
# Source entity resources and contact investigation
Read-only 2026-10-24. tools/extractors/entities.py prepares exact GAM typed fields,
sourceSHA/offsets/raw bytes, transforms, duplicate tags, object-link candidate
ordinals, and explicit database/type/id references. It does not decide gameplay
visibility or turn editor SpriteDatabase icons into game actors. --decode preserves
referenced PCM WAV, Canv RGBA/PNG and3DSh decoded JSON. Tests check preservation,
case lookup/ambiguity, path boundaries and actual lab/VR01 resources.
LV1B has129 entities:19 PIC,20AIT,13CAM,12MCA,16PAT,4OMT,2LOAD,2buttons and a bars
object, plus actors/effects. Its62 explicit resources resolve. VR01 has16 entities,
4star pickups IDs3001..3004 (sprites.omt Canv135 star, PointValue5,radius100),
2RETURN gates,2phone booths, trophy and a3-shot voicepractice intro24/23/22;
10 unique explicit resources resolve. Static level geometry omits dynamic actors.
## Verified visual mappings
- Carl STOP carlstop.ase0x4EDBC0 registered413DDC; texturecarl.png0x4EDBB4 at413DF2.
TALK/WALK/INHALE/CHEER/TELE registrations413D8C..413DE8; actual strings have HI
quality prefixes. Raw morph animation timing/quality dispatch remains incomplete.
- Goddard godsit.ASE0x4EEA0C registered41CDDE, goddard02.png0x4EE980 at41CE58.
HI-prefixed registrations41CDA0..41CE5F include FLY/EAT/RUN/SIT/SCOOT/WAG/GROWL/
ROCK/POINT. Godpoint has complete UVs; godsit/run/growl have none. Current actor
preparation retains godpoint UVs for the common222-point/411-face topology;
this base choice is an inference. Godwag has30 different expanded corner UVs.
Follow-up40DF18..22 proves unregistered STOP/TALK/WALK requests preserve the
current clip/name. The consumer retains that source no-op; it invents no aliases.
- Trophy trophy.ase0x4F16E4 at448E1F; trophy.png0x4F16D8 at448E3A. Update448EC0 spins
Y90deg/sec (constant0x4A7388). Contact448F20 accepts active player, hides, adds300
score, plays effect230, disables contact. No task/level completion in that callback.
- Phone class43579D opens phone.omt0x4F0314, shape3DSh0 via477BA0 at4357C9. Do not
substitute similarly named phone.ASE/phone.png without evidence.
- Buttons explicit down/up ASEbuttondown/buttonup and switch.png bind411695/
4116C3/411722. Bars explicit GAM ASEFilebars.ase/PNGFilechain.png.
- SpriteSize is actual world width/height: EXE4645F0 sets complete+AC/B0, C4 bit1;
OMTget_canv_wordsize10029930 reads them. Align values3/3 center offsets by half
size via10029890. Exact billboard flag248 handling remains under investigation.
## Contact and pickup rules
PIC interface+C8 vtable4AE548 contactslot40->435CE0. LOAD interface+C8 vtable4D025C
contactslot40->457EC0. Shared0x47A430 uses sphere path0x47B3E0 unless collisionmode
slot178 returns2, which uses specialized box path47A5E0. Sphere overlap obtains
roots via slot310, quick_magnitude, compares STRICT distance <radiusA+radiusB
(slot260), applies exclusion lists47CA90, invokes enter40 once, stay48 while
recorded, leave44 on separation. It is not a per-frame pickup callback.
quick_magnitude (OMT1001FF70..10020059, imported48D104) uses abs components, squared
ratio and original acos/cos lookup tables; Vector3.Distance is an approximation.
Jimmy normal interaction radius60 (different state160) is established in original
collision notes; this is not evidence to resize the provisional physical capsule.
PIC accepts only global active player5099E4. Acquired flag table4F8438 indexed by
PickupIndex prevents repeat. RequiredPicNum gate436830 requires group2 inventory
state nonzero and count>=ReqPicNumAmount, then consumes that amount and clears
inventory if depleted. This is a consuming prerequisite, not only a check.
PointValue>0 adds global score through42ADC0, lower-clamped0; repeat count gates it.
Normal collected flag1 hides/disables; PickedUpIndex!=-1 path uses flag2/effect.
Inventory/special pickup effects remain to be completed before broad collection.
These data/executable findings are not full runtime entity or interaction support.
Only Carl/Goddard and Jimmy morph consumers are currently integrated into --story;
source sprites/OMT props/phones/trophy/buttons/bars still require runtime consumers.
## Implemented sprite/contact subset (primary follow-up)
Source3ANI update40ED40 adds dt to a float timer and advances only when timer is
strictly greater than1/FPS; resets timer0, advances one frame per invocation,
discarding remainder. Loop0 stops on last visible frame,1 repeats,2 hides/stops
(40EF02..41). Toggle40F160 resets index/timer and shows/starts on1, hides/stops
on0, -1 toggles subject to its one-second debounce. Port implements explicit0/1
from the director; debounced-1 sprite toggles remain pending. Task activation is
separate from the AnimatedSprite Activated field: a visible apple can be idle.
SourceSprite1..9 resources are now exported, and source-sized centered quads
render3PIC/3ANI from their explicit Canv resources. Camera-facing orientation is
still an approximation. Color modulation is retained; translucent alpha/blending
and all billboard flags remain to be recovered. Editor icons are not rendered.
SceneInteractions currently accepts the ordinary3000..3999,PointValue5, no-inventory
star subset and trophy; broader pickup inventory/special effects report unsupported.
Normal acquired flag1 at435E11 hides/disables; score path435FC3..436002 adds positive
PointValue under repeat gating. Special tags4365D0..436829 are intentionally not
silently treated as plain score pickups. Original VR01 fixture tests collect4stars
for20, trophy for300, prevent repeat, serialize/reload acquired flags, and emit a
single stored RETURN request per contact entry. Original quick_magnitude and
exclusion/box contact rules remain unresolved; modern root-sphere distance is used.
The executable's RETURN branch457F92..4580BE reads Jimmy complete+88C (saved third
string) and+8F0 (fourth string), supporting stored ReturnLevel/ReturnStart semantics.
Headless VR01->LV1B renderer/window-lifetime integration passes. Fades are not yet
implemented. Acquisition is serialized in TSK; full game-state/UI saving remains
unfinished. Trophy disable is per scene; no invented permanent trophy flag is added.
All35 GAM files are present, including Level3B.gam and Level3E.gam. Their matching
OMT geometry archives are absent and named by the executable at4F1F24/4F1FFC.
Both1777-byte GAMs have identical bytes after the level identifier and four entities;
no serialized incoming GAM transition or supplied save selects them. Original
class registration/loading paths do not establish use in normal progression.
Their absence is not a proven required-content blocker.33 available pairs are
generated; scene-catalog.json records unavailable geometry without substitution.
See level-resource-mapping.md for loader and corpus evidence.
Additional unresolved explicit references: LEV1 icons.omt Canv45 (editor icon),
LV5A musicrocketmaze.omt Wave2, LV2A musicschool.omt Wave2. No substitutions.
+120
View File
@@ -0,0 +1,120 @@
# Source-backed static scene models
Implemented 2026-10-24 in `tools/extractors/models.py` and
`Application/StaticSceneVisuals.cs`. This adds the original model consumers for
OMT props, phone booths and explicit ASE/PNG entities. It does not establish
complete interaction, door collision, animation playback or visual fidelity.
## Evidence and prepared fixtures
LV1B has nine relevant model instances, sharing six source models:
| Source entities | Original model | Triangles per instance | Texture binding |
|---|---|---:|---|
| PHONE1 / PHONE2 | `phone.omt`, `3DSh:0` | 90 | Three original material/canvas links |
| bars | GAM `ASEFile=bars.ase` | 54 | GAM `PNGFile=chain.png` |
| Two `C3DBUTTON` records | GAM `Up.ase` / `Down.ase` | 16 each variant | GAM `UpDown.Png=switch.png` |
| dino | GAM `objects.omt`, `3DSh:27` | 256 | Original material27 -> canvas26 |
| plant1 / plant2 / plant3 | GAM `objects.omt`, `3DSh:28` | 168 | Original material28 -> canvas27 |
VR01 has two phone booths, using the same verified `phone.omt:3DSh:0` source
binding. Both booth instances remain separate even though their GAM tags match.
The phone class opens `phone.omt` at EXE `0x43579d` and selects shape0 at
`0x4357c9`. The similarly named `phone.ASE` and standalone `phone.png` are other
assets and are not substituted. Its three material links are `{0:Canv1,
1:Canv0,2:Canv2}`. The 90 triangles span **five** source material draw ranges,
with index counts `[120,6,12,6,126]`; retaining only a single final draw would omit
parts of the booth.
Button resource registrations are recovered at EXE `0x411695`, `0x4116c3`,
`0x411722`. InitObject at `0x411b93` selects literal `UP` (`0x4ed9bc`), so the
default static variant is source-backed. The consumer recognizes `UP` / `HIUP`
and `DOWN` / `HIDOWN`. It displays the first authored pose of the selected
variant; it does not imply that button morph transition timing is reconstructed.
Bars and other explicit ASEFile/PNGFile pairs retain the first authored sample
and the proven ASE-to-OMT axis/UV conversion. No additional node transform or
floor correction is introduced.
## Preparation interface
```python
prepare_models(original: Path, level_file: str, output: Path) -> dict
```
From `GamePort/`:
```sh
python3 tools/extractors/models.py --level level1b.gam --output artifacts/extracted/level1b/models
python3 tools/extractors/models.py --level VR01.gam --output artifacts/extracted/VR01/models
python3 -m unittest discover -s tests -p test_models.py -v
```
`models.json` schema1 contains:
- Source GAM path/hash and level code.
- `models`: unique keys, relative scene JSON paths, source hashes/resource
identities and geometry counts.
- `actors`: original ordinal/byte offset/tag/class, default variant, variant-to-
model-key references, and mapping evidence.
- `unresolved`: incomplete explicit mappings; no class default is invented.
Each OMT model exports only its selected `3DSh` and transitively referenced
`3DMa` / `Canv` resources. Source material/texture IDs remain local inside each
model scene file. No unrelated archive geometry is copied. Existing ASE and PNG
assets are decoded locally, without modifying originals.
The source corpus contains one Level3C button at GAM offset33909 whose explicit
`UpDown.Png` is `none`. It is recorded unresolved and omitted from model actors
until its actual constructor/fallback binding is recovered. LV1B/VR01 have no
unresolved entries in this subset. Other classes without explicit bindings are
outside this consumer and are not presumed invisible or complete.
## Runtime interface and invariants
```csharp
new StaticSceneVisuals(Mesh combined, SceneDirector director,
string assetsRoot, string preparedRoot);
Mesh Mesh { get; }
void Update(Mesh destination);
```
`preparedRoot` is the scene's `models` directory containing `models.json`.
All required geometry/texture bytes are prepared; no speculative runtime fallback
uses `assetsRoot`. Actor lookup uses original source GAM byte offsets rather than
tags, preserving duplicate tags. The integration can append later consumers and
pass the resulting combined mesh to `Update`.
All source model vertex/index/draw ranges are retained. Each instance/variant
gets distinct texture IDs starting at `int.MinValue+20000`; preexisting identity
collisions are rejected. The actual lab consumer adds19 original draw ranges
and15 texture identities. Every phone material draw follows actor visibility.
Button inactive variants keep allocated ranges but do not draw.
Director position/rotation updates transform original local vertices directly.
The current shared actor rotation convention is X, negative yaw Y, then Z,
followed by the director position. Exact general Euler composition still requires
original comparison; tests establish the implemented translation and yaw behavior.
No character grounding/floor correction is applied to these props. Bars movement
is visible only when a separate recovered gameplay consumer changes its actor
root; this visual consumer itself does not invent opening motion.
Null material handling matches the existing original DX rule: preserve geometry
but skip draws whose original material is null or unresolved. The original LV1B
invisible proxies reference absent material18; selective extraction preserves
those links and reports `nullMaterialIds` rather than fabricating a white material.
An explicit empty draw list stays empty on mesh integration.
## Verification
Eight Python test groups include a locally compiled .NET10 consumer harness.
They verify actual phone geometry and all five material ranges, explicit model
bindings, OMT subset export, duplicate tags, source hashes/output boundaries,
missing mapping reporting, distinct texture IDs, translation/yaw/no floor
correction, hide/show, independent button variants, retained combined buffers,
reserved-ID conflict rejection, and null-material geometry without invented draws.
The main C# project builds with zero warnings/errors after adding the consumer.
Prepared asset and managed harness checks are not GPU or original-runtime fidelity
verification. Primary integration must verify scene rendering, updating the final
combined buffers, source entity transitions, packaging, and native platform behavior.
+45
View File
@@ -0,0 +1,45 @@
# Original default effects bank
Read-only EXE/OMT recovery and port SDL stream checks,2026-10-24. Text offsets
are VA minus0x400000. This is not original-game audio comparison or speaker testing.
Jimmy PostLoad423642 pushes string4EE08C=`SoundEffects.omt`, calls46A910,
and stores its database pointer to current sound database696008 at423656.
The separate sounds.omt has only4 waves and is not the numeric gameplay SFX bank.
SoundEffects.omt supplies251 Wave identities, including58=`door closing`,
59=`Door opening loop`,230=`winning prize2`.
458980 forwards three arguments to47D390;4589C0 forwards four to47D640 after
checking global4F8434. Both set volume through47DC80 from4F6B38.47D390 checks
current database696008 and tests/loads FourCC Wave/id via interface slots20/14
at47D3B6..DA. Contextual voice/music paths may temporarily switch the current
bank; the consumer currently uses the proven default for pickup/mechanism events.
This does not recover the entire original bank-switching/channel system.
Vertical-door417B28..43 calls4589C0(actor,-1,59,1), retaining its returned handle
while moving.41797E..4179AE stops that handle through458A00(handle,0), clears it
to-1 and calls4589C0(actor,-1,58,0). Reversing while the handle exists does not
start a second loop. Button411Cxx uses serialized AvailSound. Pickup435Fxx uses
serialized SoundIndex; trophy's230 identity is retained by the interaction path.
`tools/extractors/sound_bank.py` preserves each bounded source RIFF byte sequence,
archive/id/name/offset/hash and PCM duration in effects/effects.json. One resource,
162 bird1, contains format55 (MPEG Layer3) in RIFF. Its explicit fact sample count
is25344 at11025Hz; the encoded payload is retained unchanged. SDL3.4.2 local
src/audio/SDL_wave.c1755..57 explicitly rejects MPEG formats. Playback of162
therefore requires a separate decoder/conversion and remains unsupported; it is
not silently substituted. The currently connected lab effects use PCM resources.
PreparedEntityResources merges the bank with per-scene explicit references;
duplicate identities require equal duration and identical payload bytes. SceneAudio
uses independent one-shot streams and owner-keyed loops, stops door loops on
completion/reset, and disposes all voices on scene rebuild. Music and speech remain
independent. Original attenuation/pan/volume/channel limits and full jetpack sound
callbacks are incomplete, so current SDL mixing is an implementation policy.
Verification:2 Python tests compare all251 emitted RIFFs to exact original slices,
check original bank/call/FourCC instruction bytes, preserve source hash and reject
output in Original. Managed merge tests reject conflicting identities. The SDL
dummy-device --effects-audio-smoke consumes original58/59 streams, retains a
one-shot while stopping the loop, adds230 independently and clears all streams.
No physical speaker, original timing/position or native Windows audio claim follows.
+133
View File
@@ -0,0 +1,133 @@
# Original laboratory objectives and practice modal
Evidence: read-only Neutron.exe disassembly (`artifacts/binary/neutron.asm`),
original `omt/screens.omt`, and `alpha.omt`. EXE VAs below equal file offsets
plus `0x400000` for these sections. Static evidence and decoded original art
are verified; original modal/HUD runtime comparison remains outstanding.
## Recovered screen resources and coordinates
`402687..4026E8` registers slot0=`screens:Canv156` objectivePad,
slot1=120 labobjective0A, slot2=121 labobjective0B, slot3=122 labobjective0C.
Their original pixels say **GET JET PACK.**, **TALK TO CARL.**, and
**FOLLOW CARL OUTSIDE.** respectively. GAM pickup tag `shrinkray` is the
prototype/internal name of the lab jetpack (inventory group0/item3); the art
does not describe it as a shrink-ray weapon.
| Element | Original identity | Native dimensions | Reference top-left |
| --- | --- | --- | --- |
| Objective pad | screens Canv156 | 320x173 | (384,380+offset) |
| Current objective | screens Canv120/121/122 | 256x29 | (384,448+offset) |
| Objective selector digit | alpha Canv83/84/85 | 8x8 | (393,450+offset) |
| PracticeYesNo | screens Canv169 | 207x100 | (210,210) |
`402C40` positions visible flagged objectives at x384,
y=`448 + self[4EC] + visibleRow*15`. `407070` renders the pad at x384,
y=`380+self[4EC]` during its stationary phase and prints selector `%d`
(`4EC794`) at (393,450+offset), font tag SMAL (`534D414C`). `401F9D`
initializes offset=-69; `406590` changes -69 to0, while `406650` changes0 to-69.
These source paths toggle vertical layout and other gadget UI, not a simple
objective visibility bit. The pad extends beyond the640x480 reference viewport;
retain clipping rather than repositioning it to fit.
`406F50(index,flag)` only accepts index>0: it clears44 dword flags at4F7D00,
sets selector4F8194, resets animation timer4F8188, then enables the selected
entry. It does not map selector0 to objective1. The source has sliding/timed
objective presentation; the consumer currently renders its stationary geometry
under caller-controlled visibility. Animation and exact source visibility timing
are not yet implemented.
`402D70/402CC0` convert positions using windowWidth/640 and windowHeight/480;
constants at file8D40C=1/640 and8D408=1/480. The port quads use NDC
`(2*x/640-1,2*y/480-1,0)` with an identity overlay transform. Original bitmap
UV orientation is top-down, retained as(0,0) at top-left.
Gameplay text uses individual `alpha.omt` canvases, not editor
`fontsmall.png`: `4683E0` loads `alpha.omt` (string4F51D8), copies6x64
Canv pointer sets from table4F4ED8, and `468B80` maps uppercase ASCII-32.
SMAL selects set1; table entries for '1'/'2'/'3' are83/84/85. The separate
fontsmall CanvasFont is created in editor initialization46B280..46B3C7 and
must not silently substitute for gameplay digits.
## Practice request, input and dispatch
`402243..402273` binds Canv169 at(210,210). `406F90(type)` guards against
an existing modal (4F8198), shows the matching canvas, enables cursor,
pauses the main game through virtual168, then stores type at4F8048. Type0
uses169, whose pixels explicitly ask **DO YOU WANT TO PRACTICE? YES / NO**.
`46A360/46A380` set/clear keyboard bytes at509838+virtualKey;
46A3A0/46A3B0 track left mouse at509834. Consequently modal code reads
Y=509891, N=509886, Enter=509845. Source404523..404586 defines strict
Yes hit bounds225<x<305,240<y<300; No404BD0..404C40 is315<x<395 with
the same y bounds. Y accepts regardless of pointer; N dismisses. Enter
accepts Yes while hovering its region and otherwise follows No. Mouse
click accepts the corresponding hovered region; no blanket click dismissal.
Controller state paths also exist but remain unmapped. Escape handling is
not established by this modal branch.
Type0 Yes dispatch is `40469E` jump table4=404DA8 ->4046AF. It hides the
modal/highlight, clears4F8198, disables cursor, invokes4063E0 for screen155,
and calls Jimmy virtual168 (`43B5A0`) with:
```
targetLevel = "VR04.gam" (4EC77C)
targetStart = "PHONEBOOTH" (4EC788)
returnLevel = Jimmy+955
returnStart = Jimmy+724
```
The latter field names follow how43B5A0 stages requested/current strings;
the argument addresses and literal targets are certain. Modal1/2/3 dispatch
VR03/VR02/VR01 respectively, so type0 must not be routed toVR01.
Runtime checkpoint42AF00 captures the current level code and a16-byte
actor root into Jimmy+1E48/+1E38 separately. This does not prove the
meaning of the saved TSK StoredVector or justify overwriting it.
No path404D1E hides practice elements, clears4F8198, disables cursor and
unpauses main game virtual168(0); yes continues into the level transition.
## Implementation and verification
- `tools/extractors/ui.py` exports only the8 proven canvases, retaining original
identity, database, offset, source size, whole-input hashes and decoded RGBA
hashes. It validates every requested identity/dimension before writing and
rejects destinations overlapping source directories.
- `Application/SceneHud.cs` bounds manifest/depth/count, exact canvas dimensions,
paths and decoded byte counts; appends screen-space indexed quads to the scene,
preserves world draws/textures, and updates the final merged vertex buffer.
Selector0 produces no invented objective image. Input/modal state belongs to
the caller.
- `python3 tests/GamePort.HudTests/test_ui.py` verifies exact original RGBA,
output roundtrip, missing-resource rejection and input hash preservation.
- `dotnet run --project tests/GamePort.HudTests -- artifacts/prepared/ui/ui.json`
verifies final-buffer writes, original coordinates, digit/objective/modal
visibility, retained implicit world draw, and malformed-resource rejection.
Both targeted commands passed24Oct2026. Integrated headless overlays/VR04 entry
and GTX1070/Xvfb modal pause/N/resume/resize pass with zero validation errors.
The packaged Windows Wine64 modal check also passes with validation disabled;
native Windows/original-game comparison remain outstanding.
## Return-context field confirmation
Follow-up field tracing confirms the meaning of the two staged return arguments:
- Literal4EF524 is `level1b.gam`. Jimmy constructor437656..437684 copies it
to complete-object+955, initializing the current/requested GAM filename.
- Constructor437589..4375B5 initializes+724 from4ECA6C=`none`, not PHONEBOOTH.
- PlayerLoadLevel43B5A0 copies its second argument (requested start tag) to+724
at43B6A7..43B6E0, first argument (requested GAM) to+955 at43B764..43B78C,
third argument (return GAM) to+88C, and fourth argument (return start) to+8F0.
- TSK load460A83..460AE5 reads the saved StartPoint string and copies it to
+724 and+774. The supplied NewGame StartPoint is STARTEXP, so a lab practice
transition after loading NewGame should carry ReturnStart=STARTEXP, rather
than copying NewGame's preexisting ReturnStart=`none`.
-40B70A..40B770 looks up+724 with actor lookup474070 and assigns that actor's
root transform to Jimmy, independently confirming that this buffer is a
start entity tag. Runtime checkpoint42AF00 does not alter it.
Therefore source modal0 Yes preserves current `level1b.gam`/`STARTEXP` as the
return pair for the normal NewGame route, while entering VR04/PHONEBOOTH.
Its separately captured checkpoint root and unknown TSK StoredVector remain
distinct evidence; a new PHONEBOOTH return marker must not be invented.
+56 -1
View File
@@ -40,7 +40,7 @@ and pause simulation, while C pauses for inspection and R resets the start area.
triangles, including invisible proxies, and clips the chase camera with a sphere triangles, including invisible proxies, and clips the chase camera with a sphere
sweep. Solver/masks/radius/pivot are explicit approximations. The physical position sweep. Solver/masks/radius/pivot are explicit approximations. The physical position
is feet; a separate original-root height feeds camera math and standing mesh minimum is feet; a separate original-root height feeds camera math and standing mesh minimum
Y feeds visual placement. GAM/ASE data is preserved. There is no task/trigger engine. Y feeds visual placement. GAM/ASE data is preserved. SceneDirector supplies the separate task/trigger interpreter.
Application/PreviewCharacterPlacement and PreviewAnimationLibrary keep inspection Application/PreviewCharacterPlacement and PreviewAnimationLibrary keep inspection
policies available alongside the walking checkpoint. Inspector ground contact is a model-only offset policies available alongside the walking checkpoint. Inspector ground contact is a model-only offset
@@ -53,3 +53,58 @@ floor-derived pivot still require original comparison and further recovery.
Subsystem implementation and validated ownership are documented in Subsystem implementation and validated ownership are documented in
`infrastructure.md`, `analysis/graphics.md` and `rendering.md` as they become `infrastructure.md`, `analysis/graphics.md` and `rendering.md` as they become
available. Persistent docs distinguish planned architecture from verified behavior. available. Persistent docs distinguish planned architecture from verified behavior.
SceneDirector interprets original synchronous AI actions and CAM/MCA speech/camera
sequences from mutable copies of GAM actors. PreparedEntityResources retains
archive/type/id identities and PCM durations; SceneAudio independently streams
music and speech. SceneActorVisuals and SceneSpriteVisuals append original morphs
and source-sized Canv quads to a combined mesh. Shared draw visibility changes
before synchronous rendering; vertex ranges remain independent after composition.
SpriteSequence implements recovered per-call timing/stop/hide modes. Billboard
orientation, some actor aliases, pivots and actual playback-end synchronization
remain provisional.
TaskStates and TaskActivation retain original case/sentinel/numeric gates.
OriginalSave accounts for every TSK byte and preserves unknown data. SceneInteractions
implements star/trophy/lab jetpack contacts, Carl dialogue dispatch and LOAD requests, tracking
contact entry by source offset (duplicate tags remain distinct). Main disposes
renderer/window/audio before rebuilding the next scene, carrying task/items/score.
Checkpoint CLI saves use atomic replacement outside asset directories; complete
runtime saves, menus and configuration are not yet implemented.
ActorPatrol implements the recovered common patrol phases and actor-specific
profiles. OriginalScenePhysics uses recovered support/trace/magnitude and source
wall-mask metadata, with a provisional modern wall solver. LabSimulation retains
its provisional feet capsule, recovered normal root clearance75.9 and visual sole
placement. DynamicSceneCollision builds source3DUD box triangles/broadphase;
DynamicBodyResponse supplies the modern narrowphase. Keep these evidence boundaries
explicit rather than presenting the complete original solver as recovered.
SceneMechanisms consumes button contacts and explicit door toggle requests, maintains
vertical-door movement/hold/reversal and emits sound/stop events. StaticSceneVisuals
transforms original model actors into the final combined buffer, preserving source
local bounds separately from visible material geometry. Collision uses source flags
and transforms rather than draw visibility.
JetpackBurst exposes controller/effect phases independently; LabSimulation currently
orders controller -> collision -> effect at60Hz. Inventory slot0/3, current energy,
level exceptions, effect radius and original FLY/fire morph consumers are connected.
The complete original global object update order is unverified. SceneInteractions
snapshots live energy, tasks, inventory, objective selector and RETURN strings.
PracticePrompt implements source strict Yes/No regions and keyboard dispatch;
Program pauses simulation while modal, clears held input and rebuilds VR04 on Yes.
SceneHud appends source640x480 screen quads; the Vulkan overlay pipeline disables
depth and draws after world geometry using identity transforms. Panel slide timing,
full HUD state and practice highlighting remain incomplete. Fixed-size authored art
is scaled with the viewport; input uses matching logical-window coordinates.
Prepared effects/effects.json preserves251 original SoundEffects.omt identities
and RIFF payloads, including one MPEG-in-RIFF resource whose playback is unverified.
PreparedEntityResources merges this explicit bank with per-scene named resources.
SceneAudio mixes independent SDL streams for music/speech/one-shots and owner-keyed
effect loops. Pickup and mechanism events are connected, including loop stop on
bar movement completion/reset. Original positional/channel/volume policies and
jetpack sound callbacks remain open; no online audio or services are used.
+21 -6
View File
@@ -11,10 +11,10 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| C# original loaders | Linux runtime | All128 PNG /254 ASE base meshes; morph/base UV tests | | C# original loaders | Linux runtime | All128 PNG /254 ASE base meshes; morph/base UV tests |
| .NET10 Linux build | Pass, zero warnings/errors | Local SDK10.0.402/runtime10.0.13 | | .NET10 Linux build | Pass, zero warnings/errors | Local SDK10.0.402/runtime10.0.13 |
| Windows x64 publish | Pass | Correct PE32+ app and SDL3.dll; initial native rendering user-reported | | Windows x64 publish | Pass | Correct PE32+ app and SDL3.dll; initial native rendering user-reported |
| Windows package under Wine64 | Preliminary headless pass | Two frames, exit0; fixed-time readback identical to Linux on lavapipe; validation disabled | | Windows story/practice package under Wine64 | Preliminary headless/window pass |12s story;12-frame practice pause/N/resume/resize and original streams; simulation matches Linux; validation disabled |
| Corrected Windows preview under Wine64 | Preliminary window pass | Six frames, key2 animation switch, resize800x600, exit0; validation disabled | | Corrected Windows preview under Wine64 | Preliminary window pass | Six frames, key2 animation switch, resize800x600, exit0; validation disabled |
| Windows walking package under Wine64 | Preliminary240-step window pass | SDL arrows/Shift, walking/jump/landing and800x600 resize; matches Linux movement statistics; validation disabled | | Windows walking package under Wine64 | Preliminary240-step window pass | SDL arrows/Shift, walking/jump/landing and800x600 resize; matches Linux movement statistics; validation disabled |
| Linux self-contained package | Native run verified | Two headless frames without SDK/source/originals mounted | | Linux self-contained package | Native headless/window verified |12s story without SDK/source/Original mounted; GTX1070 practice pause/N/resume/resize, zero validation errors |
| Vulkan1.3 lab | llvmpipe + GTX1070 | Real indexed/textured/depth frame/readback; validation enabled, zero errors | | Vulkan1.3 lab | llvmpipe + GTX1070 | Real indexed/textured/depth frame/readback; validation enabled, zero errors |
| Original camera/projection | Data/math integrated | GAM camera, recovered FOV/clips; startup/follow behavior not compared | | Original camera/projection | Data/math integrated | GAM camera, recovered FOV/clips; startup/follow behavior not compared |
| Jimmy normal texture / morph | Native preview verified | Correct atlas slot0, base topology/UV retained; state speed/loop unverified | | Jimmy normal texture / morph | Native preview verified | Correct atlas slot0, base topology/UV retained; state speed/loop unverified |
@@ -32,12 +32,27 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| Simulation cadence | 13 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved | | Simulation cadence | 13 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved |
| Walking camera and animation | Linux headless/window pass | Original five motion clips, recovered eye180/target99; pivot, timing and obstruction solver provisional | | Walking camera and animation | Linux headless/window pass | Original five motion clips, recovered eye180/target99; pivot, timing and obstruction solver provisional |
| Walk SDL input/resize | GTX1070/Xvfb240-step pass | Arrows/Shift injected through SDL; travel1250.12,jump/landing; resize800x600; zero validation errors | | Walk SDL input/resize | GTX1070/Xvfb240-step pass | Arrows/Shift injected through SDL; travel1250.12,jump/landing; resize800x600; zero validation errors |
| Intro/task/entity/gameplay loop | Incomplete | GAM data recovery is not task execution or gameplay | | TSK saves/task gates | All12 originals byte-round-trip | Bounded parse/write, task/items/score/checkpoint CLI resume; full game-state/menu save incomplete |
| Lab CAM/MCA/AI interpreter | Source sequence tests + Linux GPU pass |16 speech cues, recovered camera formulas, skip/actions/control restoration; no original comparison |
| 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 |Independent stream consumption and speech replacement; speakers/latency/Windows audio unverified |
| 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 | Linux headless pass |Original VR01 RETURN dispatch renders VR01 thenLV1B, zero validation errors; fades/window transition 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 |
| Lab task/contact route | Managed and headless GPU pass |Explanation/jetpack/Carl/exit reachesSCENE60, score150 andlevel1; direct contacts do not verify navigation |
| Patrol/support |10 patrol +13 support groups pass |Source phases/profiles and8 DLL magnitude refs; Carl sensing, Goddard follow and full wall response incomplete |
| Buttons/doors | Source state tests and GPU props pass |Cooldown, hold/reversal, original model transforms; source broadphase/box order with modern narrowphase |
| Dynamic collision |10 managed groups pass |Includes actual closed/open lab bars; full source solver/activation exclusions incomplete |
| Lab objectives/practice | Art/data/managed/headless + native Linux window pass |Exact source coordinates, modal pause, Y/N/pointer rules; N resumes and resize800x600 onGTX1070, zero errors; slide/highlight incomplete |
| Jetpack tutorial |14 state groups +300-step VR04 GPU pass |FLY/fire effect, radius/timer/energy/VR rules; maxrise418.98/landing, zero validation errors; phase/shadow/collision approximations |
| Default effects bank |251 exact RIFF exports, SDL dummy pass |Pickup/button/door sounds and owner-loop stop; positional/volume/channel policy incomplete; MPEG-in-RIFF bird1/id162 unsupported by SDL WAV |
| Complete scene/gameplay loop | Incomplete |Lab navigation, exact collision/pivot/cadence and original reference comparison still required |
| Menus/AI/combat/progression/saves | Incomplete | Required future work | | Menus/AI/combat/progression/saves | Incomplete | Required future work |
| Original execution | Attempted under isolated Wine11 | Window created, GL/Vulkan rendering unusable; no reference comparison | | Original execution | Attempted under isolated Wine11 | Window created, GL/Vulkan rendering unusable; no reference comparison |
| Native Windows functionality | Loading/rendering user-confirmed | This movement checkpoint/input/audio/resize still unverified natively | | Native Windows functionality | Loading/rendering user-confirmed | Current story/tutorial/input/audio/resize still unverified natively |
Generated evidence: artifacts/final-tests.log, test-level1b.ppm, test-player.ppm, Generated evidence: artifacts/full-integration-test.log, practice-window.log,
practice-transition.log, jetpack-runtime.log, final-tests.log, test-level1b.ppm, test-player.ppm,
resize-input.ppm, package-linux.ppm, extracted/audit.json and reference*/ logs. resize-input.ppm, package-linux.ppm, extracted/audit.json and reference*/ logs.
The lab/player images have been visually inspected; they do not establish original The lab/player images have been visually inspected; they do not establish original
visual equivalence. Windows cross-publishing must not be represented as Windows visual equivalence. Windows cross-publishing must not be represented as Windows
@@ -45,6 +60,6 @@ runtime validation. Package scope and prerequisites are in infrastructure.md.
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, absent intro/trigger/interaction execution, close-wall camera clipping near Jimmy, incomplete class-specific triggers/interactions,
and no original comparison captures. Walk evidence: artifacts/walk-tests.log, and no original comparison captures. Walk evidence: artifacts/walk-tests.log,
test-walk.ppm, walk-start.png and walk-window.ppm. Original fidelity is unverified. test-walk.ppm, walk-start.png and walk-window.ppm. Original fidelity is unverified.
+30
View File
@@ -33,3 +33,33 @@
masks. Document the skipped intro, missing interactions, transient jump-state masks. Document the skipped intro, missing interactions, transient jump-state
simplification, animation timing and close-wall camera limitation. Test against simplification, animation timing and close-wall camera limitation. Test against
source geometry and build both packages without calling this a faithful full scene. source geometry and build both packages without calling this a faithful full scene.
10. **Source-driven scene interpreter.** Preserve synchronous AI action dispatch,
original camera formulas and audio-duration advancement rather than adding a
fixed intro timer or completingSCENE on intro end. Separate task activation,
sprite playback, draw visibility and physical collision. Report unrecovered
behavior explicitly. Preserve unknown TSK fields and original checkpoint resume;
no claim of arbitrary-position/full-state save support.
11. **Separate supplied records from required content.** All35 GAM entity files
exist;33 have matching OMT geometry archives. Level3B/Level3E GAMs contain the
same four entities apart from their level code, with no incoming serialized
GAM transition or supplied save selecting them. Their original classes name
absent OMT archives, but registration alone does not prove normal gameplay use.
Record unavailable geometry without substitution; do not classify it as a
reconstruction blocker or request more files unless progression requires it.
12. **Preserve source physics boundaries.** Recovered quick magnitude, support trace,
radii/factors and3DUD broadphase/triangle ordering stay separate from provisional
wall/capsule response. Check isolated original DLL results without executing or
modifying originals in place. Keep visual soles distinct from logical root75.9.
13. **Correct prototype names from original evidence.** The pickup tagged SHRINKRAY
is the jet pack in original objective art and inventory slot0/3 code. Practice0
entersVR04/PHONEBOOTH with current GAM/STRT return context. Do not invent a
shrink-ray weapon, VR01 mapping or TSK StoredVector checkpoint meaning.
14. **Compose original UI and effect assets.** Draw source640x480 UI in a separate
depth-disabled overlay; retain clipped original coordinates. Use exact default
SoundEffects.omt identities for lab effects, preserve encoded RIFF resources
and document unsupported decoders. Do not substitute editor fonts/audio banks.
15. **Default recovered scene play.** Start the integrated lab story/interactions by
default; retain --inspect and deterministic smoke modes. Passing direct-contact
tests does not establish navigation, original fidelity or full-game completion.
+18 -14
View File
@@ -61,18 +61,22 @@ animation state/render sorting are incomplete. See rendering.md for evidence.
## Scope limits ## Scope limits
This is a controllable lab checkpoint, not complete reconstructed gameplay. The default now runs the lab story and recovered interactions, source props/patrol,
Collision solver/masks/dimensions, pivot,60Hz cadence, camera obstruction and objectives/practice modal and jet pack tutorial. --skip-intro restores control;
animation state timing remain provisional. Original task/trigger execution, --inspect retains the scene/clip inspector. Collision response, visual pivot,
introductory cutscene, inventory, combat, enemies, progression, save/load, mouse 60Hz cadence, global phase order and animation/render-state fidelity remain
steering and remaining scenes are incomplete. The default now walks/jumps from provisional. Full combat/AI/progression/menus/runtime saves are incomplete.
the original start area; `--inspect` retains clip selection with keys1/2/3/4.
Default idle samples remain identical. The floor-derived visual transform is
separate from original physics; details are in the movement/collision reports.
Packages include local copies of asset directories (ASE/png/gam/omt), original Packages include all33 available prepared scene pairs, original ASE/png/gam/omt
font PNGs/NewGame/readme, lab/Jimmy scene resources, recovered music, .NET runtime, copies, alpha.omt, entity speech/canvases, actor clips, original UI,251 preserved
SDL3, SPIR-V and these limitations. Legacy EXEs/DLLs, old user save slots, tool effect RIFF resources, .NET runtime, native SDL3 and SPIR-V. Legacy EXE/DLLs, tool
caches and analysis databases are not runtime dependencies. Vulkan drivers remain caches and original save slots are not runtime dependencies. Level3B/E GAMs are
platform prerequisites. Initial native Windows rendering is user-reported; the supplied; registered geometry archives are absent but gameplay use is unverified,
movement checkpoint and broader native Windows functionality remain unverified. so this is not an established missing-content blocker. No substitutes are used.
SceneAudio connects music/speech, pickup/button/door effects and owner loop stops.
Original positioning/volume/channel policy, jetpack callbacks and MPEG-in-RIFF
bird1/id162 decoding are unfinished. Linux dummy streams establish consumption,
not speaker output or historical fidelity. Native Windows story/input/audio and
original comparison remain unverified. See compatibility.md and progress.md for
current tests; these packages are investigation checkpoints, not a finished release.
+89 -120
View File
@@ -1,134 +1,103 @@
# Progress — current checkpoint # Progress — 2026-10-24
**Full reconstruction is incomplete.** The current milestone is an evidence-backed **The full reconstruction is incomplete.** The current implementation extends the
asset recovery toolchain and a controllable original lab with local Linux/Windows user-verified Windows rendering checkpoint into an interactive original lab and
packages. This is a movement checkpoint, not a completely reconstructed scene. jet pack tutorial flow. This is not a verified faithful complete scene or release.
## Controllable lab checkpoint ## Current integrated behavior
The user confirmed that the previous Windows build loads and renders and asked - Default play runs LV1B STARTEXP and its16-cue CAM/MCA/AI camera/speech sequence.
to advance. The default now runs walking/backpedaling/turning, ballistic no-gadget Escape/Space skips actions and restores control; `--inspect` retains inspection.
jumping, source-triangle collision, a chase camera, and original idle/run/backpedal/ - Original walking/backpedal/turn/jump arithmetic, source clips, chase camera and
jump/fall clips. Arrows move, Shift/Insert/numpad0/right mouse jump, R resets, C fixed60Hz port simulation. Powered jumping now translates the recovered state
pauses for inspection/resumes, F11 fullscreen, Escape quits. The intro is skipped. table,8-second effect timer,60/100 contact radii and energy/VR immunity rules.
- Original Carl/Goddard morphs, sprite quads and9 lab model actors, including the
OMT phones, source buttons and moving bars. Goddard's unregistered STOP/WALK/TALK
requests retain the current source clip rather than invented aliases.
- Shared patrol states1/3/7, state9 base motion and Carl's WALK/STOP profile.
Body support uses recovered radii, factors, quick magnitude and one-sided trace;
full wall response and Carl sensing remain incomplete.
- Lab explanation -> SCENE35 -> jet pack pickup -> SCENE50 -> Carl contact/talk
-> SCENE60 -> outside LOAD dispatch. Pickup adds50, Carl callback adds100 before
dialogue. Source task gates/objective selector and inventory slot0/3 persist.
- The pickup's internal tag `shrinkray` names the lab jet pack, proven by original
GET JET PACK art and powered-jump inventory checks. It is not a shrink-ray weapon.
- Original objective pad, three lab objective images, digits and PracticeYesNo
are rendered at source640x480 coordinates. O changes stationary panel offset.
Practice pauses the simulation; Y enters VR04/PHONEBOOTH and N resumes.
Return context is current GAM/latest STRT (LV1B/STARTEXP for NewGame), separate
from the still-unrecovered runtime checkpoint-root restoration.
- Button contact/cooldown/down/up/next-trigger and vertical-door duration,
reversal/hold/next-trigger logic. Source dynamic-box broadphase/triangle ordering
is translated; narrowphase/response still uses a modern approximation.
- Ordinary stars/trophy, score and acquired flags; all12 TSK files round-trip.
CLI checkpoint load/write preserves unknown fields, inventory, tasks, energy,
objective selector and RETURN context. Complete runtime/menu saving is unfinished.
- Music and speech use independent SDL streams. Positional effects/banks and
physical audio verification remain unfinished. Original default-bank pickup/button/
moving-door one-shots and owner loop stop are now connected; attenuation/volume
policy and jetpack sound callbacks remain unfinished.
Recovered arithmetic and addresses are in `analysis/movement-checkpoint.md`. ## Source availability and evidence
Notable corrections: Left precedence; current-yaw target offsets rather than
accumulating destination yaw; Up halves keyboard turn; turning alone decays speed;
no ordinary midair arrow steering; disabled-gadget long hold can repeat on landing;
normal camera eye `(0,180,-350)` and target `(0,99,0)`. Exact original frame order
is unresolved; the transient disabled-gadget state3 transition is collapsed.
Explicit port approximations: fixed60Hz cadence, capsule radius24 and standing All539 original hashes remain the baseline. All35 GAM files are supplied and33
height209.4361, floor-derived model/root separation, static sweep/slide solver and have matching OMT geometry. Level3B/E GAMs exist, each1777 bytes, and are identical
all-source-triangle mask, camera sphere obstruction, animation state/loop timing. after their four-byte level identifiers. Their classes name absent OMT archives,
Collision retains all2869 lab triangles including325 invisible proxy triangles. but no serialized incoming GAM transition or supplied save selects them; loader
Original solver/masks, actor pivot/scale, stairs/dynamic objects and state activation null handling does not establish a fatal failure. Normal gameplay use is unverified,
remain unresolved. At walls the clipped camera can move close to Jimmy. so these are not an established blocker and no extra files are currently requested.
The catalog preserves absent geometry without substitution.
Verification: 11 collision and13 movement groups pass, including real lab source Detailed recovery: analysis/lab-progression.md, scene-entities.md, scene-models.md,
geometry, long/high-speed sweeps, held/re-pressed jumping, ten-minute stability, patrol.md, original-collision.md, dynamic-collision.md, buttons-doors.md, ui.md,
deterministic replay and60/120/144Hz presentation yielding the same simulation. jetpack.md, level-resource-mapping.md, and save-format.md. Addresses, source offsets,
A240-step GPU walk/jump replay travels1250.12 units, jumps once, lands, and ends confidence and approximation boundaries are retained there.
grounded; maximum rise137.62. This is port behavior, not original fidelity proof.
The Linux SDL window run receives injected movement/jump keys, resizes800x600,
and reports zero Vulkan validation errors on GTX1070. Headless llvmpipe also
reports zero errors. User-confirmed native Windows loading/rendering applies to
the previous build; native Windows movement validation remains outstanding.
Both self-contained packages were rebuilt. The Linux package passes the same
GTX1070 window replay; the Windows package passes240 windowed frames under isolated
Wine64 with SDL keys/jump/resize and identical movement statistics (validation
disabled there). Wine is preliminary compatibility evidence, not native Windows.
One additional inspector-window regression was not executed because automatic
approval review was unavailable; the full headless inspector regressions passed.
## Latest user-reported preview fix ## Verification
The user ran the Windows build and observed a static Jimmy partially inside the Managed checks cover source data, director/actions/cameras, task/interactions,
lab floor. This verifies initial Windows startup/rendering by user report, with patrol, recovered support, moving-box collision, jetpack states and HUD composition.
OS/GPU/version/input/audio details unspecified. The user subsequently confirmed that the corrected build loads and renders. Python currently has35 top-level regression tests plus2 targeted UI extraction tests.
Existing11 collision and13 movement groups pass;14 jetpack groups pass. Eight
quick-magnitude float results are checked against an isolated original DLL probe.
Original mode2 standing/jump animation probes confirm zero dynamic-point offsets
for the tested clips. This is DLL evidence, not observed original game behavior.
Both issues were reproduced from actual assets: jimstop has two byte-identical Headless llvmpipe runs render the story, model actors, practice prompt, lab exit
vertex poses, and its minimum local Y=-64.6165 plus GAM Y=26.6619 places the soles and VR04 entry with zero Vulkan validation errors. The300-step VR04 powered replay
at -37.9546 while the original visible floor is near Y=0.5486. Calling the default jumps once, rises418.98 units and lands; VR immunity retains20 energy. The ordinary
an animated idle was inaccurate. The idle stays faithful to its still source pose; 240-step replay travels1250.12 and rises137.62; port landing-count telemetry changed
1/2/3/4 now explicitly select idle/run/jump/scratch previews and the window title with the explicit state table. These measurements verify port behavior only.
states the mode/controls. A source-data-based preview correction of +38.503 Y See artifacts/full-integration-test.log and practice/jetpack logs for current checks.
places the standing model on visible floor triangles, leaving GAM data unchanged.
This is an explicit preview policy, not the recovered game collision solver.
Tests verify real lab grounding, ceiling/invisible-proxy rejection, still idle and The full scripts/test.sh integration passed:35 Python regressions,2 targeted UI
moving clips, automatic animation advance in actual GPU readbacks, and SDL keyboard checks, all managed groups, GPU story/route/practice/VR04 replays, SDL dummy streams
switching to a run cycle. Khronos validation reports zero errors on llvmpipe and and539 unchanged original hashes. Both self-contained packages rebuilt successfully.
GTX1070. Source assets remain unchanged. See rendering.md for evidence/scope. Linux package runs the12s story without SDK/source/Original mounted, zero Vulkan
The rebuilt Windows package additionally passed an isolated Wine64 window test: validation errors. Its GTX1070/Xvfb practice window pauses, receives N, resumes11
six frames, animation key2 selected moving source samples, resize800x600, exit0. steps and resizes800x600 with zero validation errors and original pickup audio.
Validation was disabled in that Wine test; corrected native Windows retest is pending. The Windows package passes the same12-frame practice/input/resize/stream check
under isolated Wine64, matching simulation statistics (validation disabled).
It also renders the12s story under Wine. Generated package logs live under
artifacts/package-integration.log, linux-package-integration/, package-practice-window.log
and windows-practice-package/. Initial native Windows loading/rendering remains
user-confirmed for the earlier checkpoint; current native Windows story/input/audio
is still unverified. Wine is preliminary compatibility evidence only.
## Verified ## Next work and limits
- Full `../prompt.MD` specification read; originals preserved and local Git initialized. No usable original gameplay reference has been captured: isolated Wine GL/Vulkan
- All 539 original files (224,601,234 bytes) still match recorded SHA-256 hashes. attempts fail rendering. Continue static recovery and isolated DLL probes locally;
- Native PE32 x86 MSVC C++ game, Open Media Toolkit 2.0 DR4, Direct3D7/DirectDraw7, comparison on a working original installation remains required for fidelity.
DirectInput8 and DirectSound identified with addresses in analysis reports.
- 35 GAM files: 3,299 entities, 93 class codes, 84,044 properties, byte-for-byte
round-trip in Python and full corpus decoding in native C#.
- 100 OMT files / 7,027 indexed resources audited: 2,155 meshes, 2,183 materials,
1,614 textures, 875 bounded RIFF resources; zero decode failures.
- ASE/OMT coordinate and UV conversion proven with duplicate assets. Jimmy morph
sample vectors retain original base UV/topology; normal texture corrected to
jimycarl.png via actual InitObject code, with shock atlas kept separate.
- .NET SDK10.0.402/runtime10.0.13, Silk.NET2.23.0, SDL3.4.2 provisioned locally.
- C# builds without warnings/errors; 20 Python tests plus native C# corpus,
malformed-data, arithmetic, visibility, case lookup, morph and merge tests pass.
- Native Vulkan lab rendering: 2,869 triangles / 33 textures; combined Jimmy
preview: 3,683 triangles / 34 textures. Real GPU readback, zero validation errors
under llvmpipe; scene/player screenshots visually reviewed.
- Fixed original null-material skipping removes false white collision-proxy
surfaces. Original startpoint/camera and recovered projection are available.
- SDL3 hardware window/presentation on GTX1070 under Xvfb: six frames, injected
keyboard received, resize to800x600, zero validation errors.
- SDL3 recovered WAV stream consumes bytes on dummy device. Speaker output untested.
- Self-contained linux-x64/win-x64 packages built under dist/. Linux package also
renders inside a separate filesystem namespace with no SDK/project/original
directory mounted. Initial Windows rendering is now user-reported as noted above.
- Windows x64 package also renders two headless frames under isolated Wine64,
exit0, without source/SDK/originals mounted. Its fixed-time PPM is byte-identical
to the Linux package on the same lavapipe driver (checkpoint670adb4). Broader native Windows remains untested;
Wine test did not enable validation or exercise SDL window/audio/input.
- Official Wine11 original-copy runs attempted in isolated filesystem/network
namespaces. Both GL and Vulkan backends produce unusable frames; details below.
## Build and run Next priorities are lab navigation/door collision and checkpoint return-position
fidelity; original collision47BD80/479D20 and phase/cadence; audio-bank/SFX mapping;
UI slide/highlights/energy gauges; actor sensing/animation completion. Then expand
remaining gadgets, damage/combat/enemies, menus/configuration, full saves and all
level progression. Lighting/fog/blend/culling and sprite/pivot fidelity are open.
Do not claim complete gameplay based on direct-contact route or GPU smoke tests.
From GamePort: `source scripts/env.sh`, `dotnet build`, then `dotnet run -- --with-player`. All previous agent file ownership has returned to primary; investigators that
Asset preparation: `python3 tools/extractors/prepare.py --audio sounds musicsecretlab`. reached usage limits are not dependencies. Generated output stays separate from
Tests: `scripts/test.sh`; packages: `scripts/package.sh`. See README for exact options. Original and the nested local repository has no remotes. Read tasks.md and Git
Generated outputs and dependencies are ignored, and everything remains local. status before continuing; preserve source evidence and update these notes.
## Remaining and current constraints
No original gameplay reference has been captured. Wine GL cannot obtain a suitable
pixel format/3D surface; Wine Vulkan logs unsupported fixed-function state and a
swapchain image count mismatch. Native Windows/VM access has been requested for
reference/fidelity and native port validation. These failures do not establish
original behavior. Static reverse engineering can continue independently.
Original collision resolution, introductory LABEXP cutscene, entity activation/
task/trigger execution, interactions, combat, AI, progression, menus, mouse aiming
and saves remain incomplete. The no-gadget controller checkpoint requires original
runtime comparison. Animation looping/speed and collider/pivot remain approximations.
Rendering material/lighting/fog/blend state mapping also remains incomplete.
Two investigators contributed movement evidence/tests and collision implementation/
tests for this checkpoint. Primary integrated the runtime, input, animation, packages
and verification. Reports distinguish static recovery from runtime checks.
## Continuation
Read AGENTS, tasks, architecture, compatibility, reverse-engineering index, and
analysis reports. Check Git status before editing. Avoid repeating solved inventory,
GAM decoding or OMT extraction. LV1B/STARTEXP is initial scene evidence; its LABEXP
trigger still needs reconstruction. VR01 provides a smaller, 16-entity test scene.
Next actionable addresses/tasks are in tasks.md; original execution procedure and
errors are in reference-testing.md. Commit history preserves local milestones.
+16 -2
View File
@@ -2,8 +2,22 @@
Authoritative reference is supplied originals. Findings must be supported by file Authoritative reference is supplied originals. Findings must be supported by file
offsets, virtual addresses, API symbols or observed behavior. Decompiled output is offsets, virtual addresses, API symbols or observed behavior. Decompiled output is
evidence, not original source. Runtime behavior has not yet been observed. evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL
probes and modern runtime checks are recorded separately.
- `save-format.md`: full supplied TSK layout, task query/assignment and activation gates.
- `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas.
- `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence.
- `analysis/level-resource-mapping.md`: supplied Level3B/E GAMs, separate registered
OMT loader paths, null-database handling and unverified gameplay reachability.
- `analysis/original-collision.md`: radius/mask follow-up; unresolved original pivot/solver.
- `analysis/scene-models.md`: explicit OMT/ASE model bindings, source bounds and props.
- `analysis/patrol.md`: shared state/waypoint phases, Goddard/Carl profiles and limits.
- `analysis/dynamic-collision.md`: source3DUD broadphase/triangle order and modern response boundary.
- `analysis/buttons-doors.md`: button contact/cooldown and moving-bar state machine.
- `analysis/ui.md`: original objective/practice canvases, coordinates, input and return strings.
- `analysis/jetpack.md`: corrected lab pickup identity, powered-jump/effect/energy phases.
- `analysis/sound-effects.md`: default bank identity, preserved wave payloads and loop lifecycle.
- `original-manifest.json`: complete original SHA-256 baseline. - `original-manifest.json`: complete original SHA-256 baseline.
- `reconnaissance.md`: input/tool inventory, game identity and initial environment. - `reconnaissance.md`: input/tool inventory, game identity and initial environment.
- `analysis/binary.md`: PE/compiler, entry points, imports and function mappings. - `analysis/binary.md`: PE/compiler, entry points, imports and function mappings.
@@ -34,5 +48,5 @@ the older preliminary movement interpretations.
## Unresolved ## Unresolved
Original execution under isolated Wine/Windows; complete gameplay algorithms; Original execution under isolated Wine/Windows; complete gameplay algorithms;
archive animations and render states; save schema; exact historical timing and remaining actor animations and render states; full runtime save state; exact historical timing and
Windows runtime compatibility. Follow `tasks.md` for concrete next actions. Windows runtime compatibility. Follow `tasks.md` for concrete next actions.
+57
View File
@@ -0,0 +1,57 @@
# Original TSK save and task state
All12 supplied TSK files decode completely and byte-round-trip in C#.
Originals remain read-only; implementation is `Assets/OriginalSave.cs`.
This establishes the wire format, not complete runtime saving or resume behavior.
Original writer EXE`0x45FEE0` and loader`0x4603F0` use OMT stream operators
(big endian scalars; one-byte Latin1 string length). Writer calls at
`0x45FFD3–0x46003C`, `0x460057–0x4600AF`, `0x4600B2–0x46013F` independently
support these field sizes/order. Reader calls at`0x4605A8–0x460633`,
`0x460A83–0x460BCF`, `0x460BDD–0x460D60` mirror them.
| Offset / order | Wire type | Evidence / current interpretation |
| --- | --- | --- |
|0|4-byte FourCC|Current level code; NewGame LV1B|
|4|float32|Global0x4F83D4; NewGame20.0; energy consumed by jetpack, adjustment0x42A920 clamps0..100; other uses pending|
|8|int16|Global0x4F83CC; preserve signed/raw value|
|10|int32|Score0x4F83C0; pickup addition0x42ADC0|
|14|int32|Global0x4F8194; selected objective index, set by0x406F50|
|18|4200 int32|Global0x4F8438..0x4FC5D8; acquired-item slots referenced by pickup code|
|16818|29 int32|One int at each8-byte record from0x4F7DB8..0x4F7EA0; semantics pending|
|16934|4 Pascal strings|Startpoint, reserved name, return level, return start|
|after strings|3 float32|Stored vector; exact meaning unresolved, not assumed player position|
|after vector|19 int32|9 group0 and10 group1 inventory states; source getters sign-extend shorts|
|after inventory|int32 count|Task entry count|
|per task|Pascal string +int32|Task name and state, in original order|
No version tag/checksum was found in this supplied format. Unknown tables/fields
and unusual existing inventory values are preserved. Several old saves contain
large or negative inventory states; normalizing them to booleans would break
the forensic round-trip and is not justified by current evidence.
NewGame's12 tasks are MOM, LIBBY, BENNY, SCENE, DINO, CLONE, KITTY1/2/3,
HYDRANT1/2 and REACTOR. Only SCENE is nonzero, initially30.
`TaskStates.Get` implements EXE`0x45FEA0`: first matching name, missing returns0.
Comparison helper`0x487C20` folds ASCII A-Z (locale fallback exists in the original;
the supplied task names are ASCII). Setter`0x45F990` updates matching existing
entries and broadcasts assignment to objects sharing TaskName via slot0x424.
It does not insert a missing task, and repeated assignments still broadcast.
SCENE milestone dispatch now updates the selected objective through the recovered
44-entry mapping (`SceneInteractions.ObjectiveForScene`), including35/50/60 to1/2/3.
The original helper0x406F50 clears transient objective flags and selects the new
entry. The TSK field currently retains its generic C# name `OtherCounter` to avoid
changing the wire representation; its recovered meaning is the objective selector.
`TaskActivation` implements the corrected animated-entity, pickup and LOAD gates.
ExactLevel is a numeric state, not a boolean. Animated entities prioritize exact
match, otherwise RequiredLevel threshold and exclusive RemoveLevel; Required=-1
leaves state unchanged. Pickup override omits RemoveLevel. LOAD accepts no required
task, taskstate-1, or threshold plus optional exact equality. These are gate
formulas only; scene visibility/collision/state execution requires integration.
Tests cover all12 original saves, truncation/trailing bytes, mutations,
case-insensitive task query, missing tasks and assignment notification. Remaining:
map every remaining global field and task side effect, original checkpoint selection,
complete state serialization/resume, port configuration and native platform tests.
+59 -68
View File
@@ -1,78 +1,69 @@
# Tasks # Tasks
## Completed milestones Full-game completion remains the objective. Original files are authoritative;
compile, runtime and original-fidelity verification are separate.
- [x] Entire specification; original inventory/hashes; local-only Git and guidance. ## Integrated milestones
- [x] Binary/compiler/API identification and address-based reports.
- [x] All GAM entities decoded and byte-round-tripped; C# corpus reader tested.
- [x] All indexed OMT meshes/materials/textures/RIFF resources decoded and audited.
- [x] ASE transform/morph-base UV/topology recovery and regression tests.
- [x] .NET10 + SDL3 + Vulkan1.3 shared source; real scene/model/texture rendering.
- [x] Original LV1B lab plus original Jimmy morph preview at GAM startpoint.
- [x] Correct normal atlas and null-material visibility from binary evidence.
- [x] Recovered impulse/gravity/speed/RNG arithmetic fragments with tests.
- [x] Native Linux Vulkan offscreen and SDL3 window/input/resize verification.
- [x] SDL3 recovered WAV stream consumption test (dummy device).
- [x] Self-contained Linux and Windows local packages, matching SDL3 libraries.
- [x] Packaged Linux runtime isolated from SDK/source/originals; renders successfully.
- [x] Preliminary Wine64 Windows-package render; exact fixed-time readback matches Linux.
- [x] Isolated copied-original Wine attempts; actual failures documented.
- [x] Correct preview floor overlap, identify still idle, add explicit animation inspection controls/tests.
- [x] User confirmed corrected Windows build loads and renders.
- [x] Controllable lab: recovered walking/backpedal/turn/no-gadget jump formulas,
original animation clips, fixed60Hz simulation, collision and chase camera.
- [x] 11 collision and13 movement test groups; source lab and synthetic edge cases,
render-rate independence, held/re-pressed jumping and ten-minute stability.
- [x] Linux240-step SDL key/jump/resize replay and GPU readback, zero validation errors.
- [x] Rebuilt both packages; packaged Linux window and preliminary Windows Wine64
window240-step walking/key/jump/resize pass, matching movement statistics.
- [ ] Test this movement checkpoint natively on Windows (previous rendering confirmed).
## Next implementation priorities - [x] Inventory/hashes, binary/API identification, full GAM round-trip and OMT audit.
- [x] .NET10/SDL3/Vulkan1.3 shared native code and self-contained platform packages.
- [x] Original lab geometry, corrected Jimmy atlas, original morphs and inspection.
- [x] Walking/jumping/chase camera and source-triangle provisional collision.
- [x] Linux headless/window/input/resize/audio-stream checks; initial native Windows
rendering user-confirmed; preliminary Wine64 movement package checks.
- [x] Original TSK/task gates/checkpoint CLI and independent music/speech streams.
- [x]16-cue lab camera/speech/actions/control restoration and skip execution.
- [x] Source actor/sprite/model preparation,9 lab props and all33 available scenes.
- [x] B/E GAM correction: both supplied; missing registered OMT geometry is not an
established progression blocker. No substitution or extra-file request.
- [x] Lab jet pack/Carl/exit task route and objective/inventory/score effects.
- [x] Original objective/practice art, strict input regions, modal pause and VR04 entry.
- [x] Shared Goddard/Carl patrol subset and recovered body support with DLL checks.
- [x] Button/vertical-door behavior and source dynamic broadphase/box triangle rules.
- [x] Powered-jump state/effect/energy arithmetic, original FLY/fire morphs and GPU replay.
1. Replace provisional capsule collision/pivot with recovered original behavior. ## Immediate continuation
Trace `0x479D20` past displacement integration, shared collision call
via interface slot0x130 in `0x462520`, and object collision caches. Retain
invisible/null-material geometry; its exact collision masks remain unresolved.
Recover original actor/model pivot, scale and spawn settling: the preview now
uses a floor-derived model offset, which must be replaced with proven behavior.
Recover stair/step handling, dynamic collider activation, and camera obstruction.
2. Compare reconstructed no-gadget airborne behavior with the original. Walking,
jump state table and zero-fuel held/re-press repeat path are now recovered in
`analysis/movement-checkpoint.md`; transient state3 and takeoff phase remain
approximations. Recover powered gadget states and original animation routing.
3. Recover original frame cadence and phase order; current fixed60Hz preserves
per-call speed increments independent of rendering. Find reverse timer+0x830
writer before implementing its >1.5 turnaround branch. Recover mouse steering.
4. Execute LV1B STARTEXP/LABEXP intro. GAM parsing supplies records; implement task
prerequisites, object activation/visibility, camera triggers and progression
from code/observations. Then build a complete small scene (VR01 if useful).
5. Recover original morph state selection, playback speed, smooth normals and
transitions. Current interpolation is original; loop/speed are preview policy.
6. Continue material/fog/light/blend/culling and render sorting mapping, then
compare visuals to original; current unlit modulation is only a foundation.
## Required validation and expansion 1. Integration suite and both packages pass; commit this stable milestone locally.
Keep native Windows story/input/audio pending and preserve current evidence.
Re-run checks only when new changes or unresolved concerns justify them.
2. Exercise the lab route through actual walking/navigation, buttons and doors.
Current lab-route smoke directly invokes source contacts; it is not navigation
or original-fidelity evidence. Recover runtime42AF00 checkpoint restoration on
VR return separately from saved STRT/RETURN strings and unknown TSK StoredVector.
3. Recover47BD80 collision response/479D20 movement phase and source object exclusions.
Support trace/magnitude/radii/factors and dynamic broadphase are recovered;
wall response, Jimmy capsule/visual pivot, stairs and camera obstruction remain
modern approximations. Preserve source normals and invisible proxy geometry.
4. Complete contextual SFX bank switching, source volume/pan/attenuation/channel
policies, jetpack sound callbacks and MPEG-in-RIFF bird1/id162 decoding. Default
SoundEffects.omt identity and pickup/button/door stream lifecycle are integrated;
physical/native Windows output and original timing remain unverified.
5. Complete objective slide/timing, practice highlights/cursor/controller handling,
energy/gadget UI. Stationary geometry and keyboard/pointer choices are recovered.
6. Recover Carl sensing409CC0, Goddard follow-state4, actor class defaults and full
morph state/playback-end synchronization. Generic patrol states alone are not AI.
7. Recover original global cadence/object phase order, mouse steering/relative input,
exact clipping/fullscreen/focus/scaling behavior and material/fog/light/blend states.
- [ ] Usable original reference captures under local Windows/VM or working Wine. ## Full reconstruction and verification
- [ ] Original walking/jump/collision/camera/input comparisons and first complete scene
including intro/triggers/interactions (movement checkpoint implemented).
- [ ] Physical audio output and original SFX/music timing, mixing/panning/positional audio.
- [ ] Fullscreen, minimized-window, mouse/relative capture, display scaling and controller behavior.
- [ ] Pickups, score/health, gadgets/inventory, combat/AI, all levels and transitions.
- [ ] Original menus, cutscenes, dialogue/voice and state-dependent rendering.
- [ ] Save/load schema and configuration persistence; NewGame reference is not save support.
- [ ] Full native Windows input/audio/resize/driver testing (initial rendering is user-reported).
- [ ] Fidelity regression references, remaining discrepancies and actual release candidate.
## Repeatable commands - [ ] Working original gameplay captures and physics/input/render/audio comparisons.
- [ ] One complete, source-faithful playable scene including navigation and transitions.
- [ ] All inventory/gadgets, health/damage, enemies/combat, scoring and win/loss behavior.
- [ ] All levels, class-specific triggers/AI and full original progression.
- [ ] Menus, cutscenes, configuration and complete runtime save/load.
- [ ] Original render-state, animation, lighting/fog/alpha and camera fidelity.
- [ ] Speaker output, positional mixing, original timing and native Windows audio.
- [ ] Native Windows input/resize/story/driver validation of the current build.
- [ ] Verified Linux/Windows release packages and documented remaining discrepancies.
- `source scripts/env.sh; dotnet build` ## Commands
- `scripts/test.sh` (20 Python tests, C# checks, native offscreen/audio, original hashes)
- `python3 tools/extractors/audit.py ../Original --report artifacts/extracted/audit.json`
- `NEUTRON_WINDOW_TEST=1 scripts/test.sh` with DISPLAY for input/resize smoke
- `scripts/package.sh` for local investigation packages (not a finished game release)
Keep runtime, tests and docs coherent. No remotes/uploads/cloud CI. Do not modify From GamePort: `source scripts/env.sh`, `dotnet build`, `scripts/test.sh`.
originals or claim unobserved fidelity. All prior agent ownership has returned to `scripts/package.sh` rebuilds local packages. `NEUTRON_WINDOW_TEST=1 scripts/test.sh`
primary; use explicit file ownership if further parallel work is started. adds window checks with a working DISPLAY. `tools/recon/reference_capture.py`
executes copied originals/generated probes in an isolated local harness.
Verify preservation using `python3 tools/recon/inventory.py ../Original --verify
docs/original-manifest.json`. No remotes/uploads/cloud work. Check Git status and
exclusive file ownership before edits; all prior agent ownership returned to primary.
+27 -9
View File
@@ -3,14 +3,26 @@ set -euo pipefail
source "$(dirname "$0")/env.sh" source "$(dirname "$0")/env.sh"
scripts/build-linux.sh scripts/build-linux.sh
scripts/build-windows.sh scripts/build-windows.sh
python3 tools/extractors/prepare.py --audio sounds musicsecretlab python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab
for rid in linux-x64 win-x64; do for rid in linux-x64 win-x64; do
out="dist/$rid" out="dist/$rid"
mkdir -p "$out/assets" "$out/scenes/level1b" "$out/scenes/animations" "$out/audio/sounds" "$out/licenses" "$out/docs" mkdir -p "$out/assets" "$out/scenes/level1b" "$out/scenes/VR01" "$out/scenes/animations" "$out/scenes/actors" "$out/scenes/ui" "$out/audio/sounds" "$out/licenses" "$out/docs"
for directory in ASE png gam omt; do cp -a "../Original/$directory" "$out/assets/"; done for directory in ASE png gam omt; do cp -a "../Original/$directory" "$out/assets/"; done
cp ../Original/fontsmall.png ../Original/green_font.png ../Original/NewGame.tsk ../Original/readme.txt "$out/assets/" cp ../Original/fontsmall.png ../Original/green_font.png ../Original/alpha.omt ../Original/NewGame.tsk ../Original/readme.txt "$out/assets/"
cp -a artifacts/extracted/level1b/. "$out/scenes/level1b/" cp -a artifacts/extracted/level1b/. "$out/scenes/level1b/"
cp -a artifacts/extracted/animations/. "$out/scenes/animations/" cp -a artifacts/extracted/animations/. "$out/scenes/animations/"
cp -a artifacts/extracted/actors/. "$out/scenes/actors/"
cp -a artifacts/extracted/ui/. "$out/scenes/ui/"
mkdir -p "$out/scenes/effects"
cp -a artifacts/extracted/effects/. "$out/scenes/effects/"
cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json"
cp -a artifacts/extracted/VR01/. "$out/scenes/VR01/"
for manifest in artifacts/extracted/*/scene.json; do
scene_directory="$(dirname "$manifest")"
scene_name="$(basename "$scene_directory")"
mkdir -p "$out/scenes/$scene_name"
cp -a "$scene_directory/." "$out/scenes/$scene_name/"
done
cp -a artifacts/extracted/musicsecretlab/. "$out/audio/" cp -a artifacts/extracted/musicsecretlab/. "$out/audio/"
cp -a artifacts/extracted/sounds/. "$out/audio/sounds/" cp -a artifacts/extracted/sounds/. "$out/audio/sounds/"
cp .tools/sdl-win/LICENSE.txt "$out/licenses/SDL3.txt" cp .tools/sdl-win/LICENSE.txt "$out/licenses/SDL3.txt"
@@ -20,7 +32,7 @@ for rid in linux-x64 win-x64; do
cp -a docs/. "$out/docs/" cp -a docs/. "$out/docs/"
cp README.md "$out/SOURCE-README.md" cp README.md "$out/SOURCE-README.md"
cat > "$out/README.md" <<'NOTES' cat > "$out/README.md" <<'NOTES'
# Neutron controllable lab checkpoint # Neutron lab story and jet pack checkpoint
Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd. Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd.
Append --headless --frames 2 to render without a window, or --screenshot lab.ppm Append --headless --frames 2 to render without a window, or --screenshot lab.ppm
@@ -32,12 +44,18 @@ Shift, Insert, numpad 0 or right mouse jump. R resets to the original start area
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.
The default runs the recovered lab camera/speech sequence; Escape/Space skips
its actions and restores control. --skip-intro starts with control; --mute disables
scene audio. O raises/lowers objectives. The original jet pack pickup opens the
practice prompt: Y/Yes enters VR04; N/No resumes. Hold jump for a powered burst
after obtaining it. --headless --story-time 12 renders a deterministic story shot.
This checkpoint implements recovered walking/jump/camera arithmetic and original Original actor/model/sprite props, common patrol, buttons/moving bars, lab task
animation clips. Collision solver/masks, collider/pivot, 60Hz cadence and animation route, objectives, practice flow and checkpoint CLI are integrated. Collision,
state timing remain provisional. Intro, interactions, progression, AI and saves 60Hz cadence, pivots, rendering states and animation timing remain provisional.
remain incomplete. A user verified rendering on Windows; this new movement build Full combat, AI, progression, menus and runtime saves remain incomplete. Initial
still needs native Windows input/physics testing. Windows rendering is user-confirmed for an older build; this story/tutorial
checkpoint still needs native Windows input/physics/audio validation.
See BUILD-AND-LIMITATIONS.md, COMPATIBILITY.md and docs/ for evidence and remaining See BUILD-AND-LIMITATIONS.md, COMPATIBILITY.md and docs/ for evidence and remaining
work. SOURCE-README.md describes development from the separate source repository. work. SOURCE-README.md describes development from the separate source repository.
+20 -1
View File
@@ -2,16 +2,32 @@
set -euo pipefail set -euo pipefail
source "$(dirname "$0")/env.sh" source "$(dirname "$0")/env.sh"
python3 -m unittest discover -s tests -p 'test_*.py' -v python3 -m unittest discover -s tests -p 'test_*.py' -v
python3 tools/extractors/prepare.py --audio sounds musicsecretlab python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab
dotnet run --project tests/GamePort.DataTests -- ../Original dotnet run --project tests/GamePort.DataTests -- ../Original
dotnet run --project tests/GamePort.CollisionTests -- ../Original dotnet run --project tests/GamePort.CollisionTests -- ../Original
dotnet run --project tests/GamePort.MovementTests -- ../Original dotnet run --project tests/GamePort.MovementTests -- ../Original
dotnet run --project tests/GamePort.DirectorTests -- ../Original
dotnet run --project tests/GamePort.PatrolTests -- ../Original
dotnet run --project tests/GamePort.SupportTests -- ../Original
dotnet run --project tests/GamePort.InteractionTests -- ../Original
dotnet run --project tests/GamePort.DynamicCollisionTests -- ../Original
dotnet run --project tests/GamePort.JetpackTests
python3 tests/GamePort.HudTests/test_ui.py
dotnet run --project tests/GamePort.HudTests -- artifacts/extracted/ui/ui.json
dotnet build GamePort.csproj dotnet build GamePort.csproj
dotnet run --no-build -- --verify-assets --assets ../Original dotnet run --no-build -- --verify-assets --assets ../Original
python3 tools/extractors/omt.py ../Original/omt/level1b.omt --scene --output artifacts/extracted/level1b python3 tools/extractors/omt.py ../Original/omt/level1b.omt --scene --output artifacts/extracted/level1b
dotnet run --no-build -- --headless --assets ../Original --scene artifacts/extracted/level1b/scene.json --level gam/level1b.gam --original-camera --screenshot artifacts/test-level1b.ppm dotnet run --no-build -- --headless --assets ../Original --scene artifacts/extracted/level1b/scene.json --level gam/level1b.gam --original-camera --screenshot artifacts/test-level1b.ppm
dotnet run --no-build -- --inspect --headless --with-player --time 0.05 --screenshot artifacts/test-player.ppm dotnet run --no-build -- --inspect --headless --with-player --time 0.05 --screenshot artifacts/test-player.ppm
dotnet run --no-build -- --headless --smoke-walk --screenshot artifacts/test-walk.ppm dotnet run --no-build -- --headless --smoke-walk --screenshot artifacts/test-walk.ppm
dotnet run --no-build -- --headless --story --story-time 12 --screenshot artifacts/test-story.ppm
dotnet run --no-build -- --headless --story --smoke-practice-prompt --screenshot artifacts/test-practice.ppm
dotnet run --no-build -- --headless --story --smoke-practice-transition
dotnet run --no-build -- --headless --story --smoke-lab-route
dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.ppm
dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk
dotnet run --no-build -- --headless --load-save artifacts/test-checkpoint.tsk --skip-intro
dotnet run --no-build -- --headless --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro
dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --time 0 --screenshot artifacts/test-run-start.ppm dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --time 0 --screenshot artifacts/test-run-start.ppm
dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --frames 7 --screenshot artifacts/test-run-advanced.ppm dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --frames 7 --screenshot artifacts/test-run-advanced.ppm
python3 - <<'PY' python3 - <<'PY'
@@ -19,9 +35,12 @@ from pathlib import Path
assert Path('artifacts/test-run-start.ppm').read_bytes() != Path('artifacts/test-run-advanced.ppm').read_bytes(), 'Animation did not advance in GPU readback' assert Path('artifacts/test-run-start.ppm').read_bytes() != Path('artifacts/test-run-advanced.ppm').read_bytes(), 'Animation did not advance in GPU readback'
print('PASS: original run preview advances across rendered frames') print('PASS: original run preview advances across rendered frames')
PY PY
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --effects-audio-smoke artifacts/extracted/effects/effects.json
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --audio-smoke artifacts/extracted/sounds/Wave_00000001_save.wav SDL_AUDIODRIVER=dummy dotnet run --no-build -- --audio-smoke artifacts/extracted/sounds/Wave_00000001_save.wav
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-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-practice-window --frames 12 --screenshot artifacts/test-practice-window.ppm
dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm
dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm
fi fi
@@ -0,0 +1,31 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original C3DJetpackFire DEFAULT shape/texture, following the owner root/Euler.</summary>
public sealed class JetpackVisuals
{
private readonly MorphAnimation clip;
private readonly int offset;
private readonly MeshDraw draw;
public Mesh Mesh { get; }
public JetpackVisuals(Mesh combined, string preparedRoot)
{
clip = new MorphAnimation(Path.Combine(preparedRoot, "actors/jetpack/fire/animation.json"));
offset = combined.Vertices.Length;
Mesh = clip.AppendTo(combined, int.MinValue + 10_000);
draw = Mesh.Draws[^1]; draw.Visible = false;
}
public void Update(Mesh destination, LabSimulation owner)
{
draw.Visible = owner.JetpackEffectVisible;
if (!draw.Visible) return;
var model = Matrix4x4.CreateRotationY(-owner.Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(owner.ActorRoot);
clip.Sample(owner.Steps / 60d, destination.Vertices.AsSpan(offset, clip.Base.Vertices.Length), model);
}
}
+32
View File
@@ -0,0 +1,32 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>
/// Deterministic integration check using direct contacts at original actor roots.
/// This does not test navigation, player input, physics or original runtime fidelity.
/// </summary>
public static class LabRouteSmoke
{
public static void Run(GamLevel level, SceneDirector director, SceneInteractions interactions, Action? dismissPractice = null)
{
if (level.Code != "LV1B") throw new ArgumentException("Lab route check requires original LV1B");
director.Skip();
var player = level.Player!.Tag!;
director.Touch(player, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions.Update(director.FindActor("shrinkray")!.Position);
dismissPractice?.Invoke();
var carl = director.FindActor("C3DCARL")!;
director.SyncActor(player, carl.Position, Vector3.Zero);
interactions.Update(carl.Position);
director.Skip();
if (!director.Controlled || interactions.Score != 150 || interactions.Inventory.State(0, 3) != 1
|| interactions.CurrentObjective != 3)
throw new InvalidOperationException("Original lab contact route did not reach the recovered exit state");
interactions.Update(level.Entities.Single(e => e.Tag == "LABTONEIGH").Position);
Console.WriteLine("Lab direct-contact integration: explanation, shrinkray, Carl callback and exit; score150, gadget3, objective3. Navigation was not exercised.");
}
}
@@ -8,6 +8,7 @@ public sealed class PreviewAnimationLibrary
{ {
private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = []; private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = [];
private readonly Dictionary<PlayerPose, MorphAnimation> movement = []; private readonly Dictionary<PlayerPose, MorphAnimation> movement = [];
private readonly Dictionary<string, MorphAnimation> actions = new(StringComparer.OrdinalIgnoreCase);
public MorphAnimation Current { get; private set; } public MorphAnimation Current { get; private set; }
public string Name { get; private set; } public string Name { get; private set; }
public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera"; public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera";
@@ -46,12 +47,18 @@ public sealed class PreviewAnimationLibrary
if (ReferenceEquals(clip, Current)) Name = label; if (ReferenceEquals(clip, Current)) Name = label;
} }
foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"), foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"),
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall") }) (PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly") })
{ {
var path = Path.Combine(parent, folder, "animation.json"); var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue; if (!File.Exists(path)) continue;
movement[pose] = Load(path); movement[pose] = Load(path);
} }
foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"),
("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly") })
{
var path = Path.Combine(parent, folder, "animation.json");
if (File.Exists(path)) actions[action] = Load(path);
}
} }
public bool Select(uint scancode) public bool Select(uint scancode)
@@ -70,4 +77,10 @@ public sealed class PreviewAnimationLibrary
Name = pose.ToString(); Name = pose.ToString();
return true; return true;
} }
public bool SelectAction(string action)
{
if (!actions.TryGetValue(action, out var clip) || ReferenceEquals(Current, clip)) return false;
Current = clip; Name = action; return true;
}
} }
@@ -0,0 +1,98 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Prepared original Carl/Goddard morphs driven by recovered director state.</summary>
public sealed class SceneActorVisuals
{
private sealed class Visual(DirectorActor actor, Dictionary<string, MorphAnimation> clips,
MorphAnimation initial, string clipName, HashSet<string> ignored, int offset, MeshDraw draw, float correction)
{
public DirectorActor Actor = actor;
public Dictionary<string, MorphAnimation> Clips = clips;
public MorphAnimation Clip = initial;
public string ClipName = clipName;
public HashSet<string> Ignored = ignored;
public int Offset = offset;
public MeshDraw Draw = draw;
public float Correction = correction;
public double Time;
}
private readonly List<Visual> visuals = [];
private readonly HashSet<string> missing = [];
public Mesh Mesh { get; }
public IReadOnlyCollection<string> UnsupportedAnimations => missing;
public SceneActorVisuals(Mesh combined, Mesh world, SceneDirector director, string preparedRoot,
Func<DirectorActor, bool>? usesPhysicsRoot = null)
{
foreach (var actor in director.Actors)
{
var family = actor.Kind switch { "3CAR" => "carl", "3DOG" => "goddard", "3TRO" => "trophy", _ => null };
if (family == null) continue;
var manifest = Path.Combine(preparedRoot, "actors", family, "family.json");
if (!File.Exists(manifest)) throw new FileNotFoundException("Prepare original actor animation resources", manifest);
using var doc = JsonDocument.Parse(File.ReadAllText(manifest));
var clips = new Dictionary<string, MorphAnimation>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in doc.RootElement.GetProperty("actions").EnumerateObject())
clips.Add(entry.Name, new MorphAnimation(Path.Combine(Path.GetDirectoryName(manifest)!, entry.Value.GetString()!)));
var initialName = doc.RootElement.GetProperty("default").GetString()!;
var initial = clips[initialName];
var ignored = doc.RootElement.TryGetProperty("ignoredAnimations", out var ignoredNames)
? new HashSet<string>(ignoredNames.EnumerateArray().Select(n => n.GetString()!), StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var clip in clips.Values)
if (clip.Base.Vertices.Length != initial.Base.Vertices.Length || !clip.Base.Indices.SequenceEqual(initial.Base.Indices)
|| !clip.Base.Vertices.Select(v => v.Uv).SequenceEqual(initial.Base.Vertices.Select(v => v.Uv))
|| !clip.Texture.Rgba.SequenceEqual(initial.Texture.Rgba)) throw new InvalidDataException("Actor morph family mismatch");
var offset = combined.Vertices.Length;
var correction = actor.Kind == "3TRO" || usesPhysicsRoot?.Invoke(actor) == true ? 0
: PreviewCharacterPlacement.Create(world, initial.Base, actor.Position, actor.Rotation.Y).VerticalCorrection;
combined = initial.AppendTo(combined, int.MinValue + 1 + visuals.Count);
visuals.Add(new(actor, clips, initial, initialName, ignored, offset, combined.Draws[^1], correction));
}
Mesh = combined;
Update(0);
// Original animation selection is synchronous. Preserve intermediate
// SIT then ignored TALK requests even if both occur before a render.
director.ActorChanged += actor =>
{
var visual = visuals.Find(v => ReferenceEquals(v.Actor, actor));
if (visual != null) SelectAnimation(visual);
};
}
public void Update(double seconds, Mesh? destination = null)
{
foreach (var visual in visuals)
{
var actor = visual.Actor;
SelectAnimation(visual);
visual.Time += seconds;
var rotation = Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180)
* Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180);
var model = rotation * Matrix4x4.CreateTranslation(actor.Position + Vector3.UnitY * visual.Correction);
visual.Clip.Sample(visual.Time, (destination ?? Mesh).Vertices.AsSpan(visual.Offset, visual.Clip.Base.Vertices.Length), model);
visual.Draw.Visible = actor.Visible;
}
}
private void SelectAnimation(Visual visual)
{
var actor = visual.Actor;
if (visual.Clips.TryGetValue(actor.Animation, out var clip))
{
if (!ReferenceEquals(clip, visual.Clip)) { visual.Clip = clip; visual.Time = 0; }
visual.ClipName = actor.Animation;
}
// EXE40DF18..22: an unregistered definition returns without selecting
// or renaming the current animation. These aliases have no Goddard
// registrations; this is an ignored request, not a made-up asset alias.
else if (visual.Ignored.Contains(actor.Animation)) actor.Animation = visual.ClipName;
else if (actor.Animation != "none") missing.Add(actor.Tag + ":" + actor.Animation);
}
}
+97
View File
@@ -0,0 +1,97 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
namespace GamePort.Application;
/// <summary>Original screens.omt laboratory objectives and PracticeYesNo; positions from EXE 402C40/407070.</summary>
public sealed class SceneHud
{
private sealed record Quad(int Canvas, int VertexOffset, uint FirstIndex, uint Width, uint Height);
private readonly List<Quad> quads = [];
private static readonly Dictionary<int, (uint Width, uint Height)> Dimensions = new()
{
[120] = (256, 29), [121] = (256, 29), [122] = (256, 29),
[156] = (320, 173), [169] = (207, 100), [83] = (8, 8), [84] = (8, 8), [85] = (8, 8)
};
public Mesh Mesh { get; }
public SceneHud(Mesh combined, string manifest)
{
var full = Path.GetFullPath(manifest);
if (new FileInfo(full).Length > 64 * 1024) throw new InvalidDataException("UI manifest exceeds limit");
var directory = Path.GetDirectoryName(full)!;
using var doc = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 });
var root = doc.RootElement;
if (root.GetProperty("version").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640
|| root.GetProperty("referenceHeight").GetInt32() != 480)
throw new InvalidDataException("Unsupported prepared UI format");
var recovered = new Dictionary<int, PngImage>();
var entries = root.GetProperty("textures");
if (entries.GetArrayLength() != Dimensions.Count) throw new InvalidDataException("Unexpected UI texture count");
foreach (var entry in entries.EnumerateArray())
{
var id = entry.GetProperty("id").GetInt32();
var width = entry.GetProperty("width").GetUInt32();
var height = entry.GetProperty("height").GetUInt32();
if (!Dimensions.TryGetValue(id, out var expected) || expected != (width, height))
throw new InvalidDataException("Unexpected UI canvas identity/dimensions");
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("UI resource escapes prepared directory");
var bytes = checked((long)width * height * 4);
if (new FileInfo(path).Length != bytes) throw new InvalidDataException("Invalid prepared UI pixel count");
if (!recovered.TryAdd(id, new(width, height, File.ReadAllBytes(path))))
throw new InvalidDataException("Duplicate prepared UI canvas");
}
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.Draws.ToList();
if (!combined.HasExplicitDraws && draws.Count == 0 && indices.Count != 0)
draws.Add(new(0, (uint)indices.Count, -1));
var textures = new Dictionary<int, PngImage>(combined.Textures);
// Pad precedes writing; modal follows the HUD, exactly as layered screen elements.
foreach (var id in new[] { 156, 120, 121, 122, 83, 84, 85, 169 })
{
var image = recovered[id];
var texture = int.MinValue;
while (textures.ContainsKey(texture)) texture++;
textures.Add(texture, image);
var first = (uint)vertices.Count;
quads.Add(new(id, vertices.Count, (uint)indices.Count, image.Width, image.Height));
vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0, 0), Vector3.One),
new MeshVertex(Vector3.Zero, new(1, 0), Vector3.One),
new MeshVertex(Vector3.Zero, new(1, 1), Vector3.One),
new MeshVertex(Vector3.Zero, new(0, 1), Vector3.One) });
draws.Add(new((uint)indices.Count, 6, texture) { ScreenSpace = true, Visible = false });
indices.AddRange(new[] { first, first + 1, first + 2, first, first + 2, first + 3 });
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true,
Textures = textures, CollisionPolygons = combined.CollisionPolygons };
}
/// <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,
float objectiveYOffset = -69)
{
if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480)
throw new ArgumentOutOfRangeException(nameof(objectiveYOffset));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits HUD ranges", nameof(destination));
foreach (var quad in quads)
{
var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace
&& d.IndexCount == 6) ?? throw new ArgumentException("Destination omits HUD draws", nameof(destination));
draw.Visible = quad.Canvas == 169 ? practiceVisible : objectivesVisible && currentObjective is >= 1 and <= 3
&& (quad.Canvas == 156 || quad.Canvas == 119 + currentObjective || quad.Canvas == 82 + currentObjective);
var digit = quad.Canvas is >= 83 and <= 85;
var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f;
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);
destination.Vertices[quad.VertexOffset].Position = Position(x, 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 + 3].Position = Position(x, y + quad.Height);
}
}
}
@@ -0,0 +1,92 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Source-sized, center-aligned Canv quads. Camera-facing orientation is still a port approximation.</summary>
public sealed class SceneSpriteVisuals
{
private sealed class Visual(DirectorActor actor, int offset, MeshDraw[] draws, SpriteSequence sequence)
{
public DirectorActor Actor = actor;
public int Offset = offset;
public MeshDraw[] Draws = draws;
public SpriteSequence Sequence = sequence;
public int Revision = actor.SpriteRevision;
}
private readonly List<Visual> visuals = [];
public Mesh Mesh { get; }
public SceneSpriteVisuals(Mesh combined, SceneDirector director, PreparedEntityResources resources)
{
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.Draws.ToList();
var textures = new Dictionary<int, PngImage>(combined.Textures);
foreach (var actor in director.Actors)
{
if (actor.Kind is not ("3PIC" or "3ANI") || actor.SourceGam is not { } source) continue;
var database = source.Text("SpriteDatabase") ?? "none";
var identities = actor.Kind == "3ANI" ? Enumerable.Range(1, 9)
.Select(i => source.Integer("Sprite" + i, -1)).TakeWhile(i => i >= 0).ToArray()
: [source.Integer("SpriteIndex", -1)];
if (identities.Length == 0) continue;
var frameDraws = new List<MeshDraw>();
var offset = vertices.Count;
var color = new Vector3(source.Number("Red", 1), source.Number("Green", 1), source.Number("Blue", 1));
foreach (var identity in identities)
{
var canvas = resources.Canvas(database, identity) ?? throw new FileNotFoundException($"Missing original canvas {database}:{identity}");
var texture = int.MinValue + 1000 + textures.Count;
textures.Add(texture, canvas);
var first = (uint)vertices.Count;
vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0,1),color), new MeshVertex(Vector3.Zero,new(1,1),color),
new MeshVertex(Vector3.Zero,new(1,0),color),new MeshVertex(Vector3.Zero,new(0,0),color) });
var draw = new MeshDraw((uint)indices.Count, 6, texture);
indices.AddRange(new[] { first, first+1, first+2, first, first+2, first+3 });
draws.Add(draw); frameDraws.Add(draw);
}
var sequence = new SpriteSequence(identities.Length, source.Number("FPS", 1), source.Integer("Loop", 1));
if (actor.Kind == "3ANI" && actor.SpritePlaying) sequence.Start();
visuals.Add(new(actor, offset, frameDraws.ToArray(), sequence));
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures };
}
public void Step(float dt)
{
foreach (var visual in visuals)
{
if (visual.Revision != visual.Actor.SpriteRevision)
{
visual.Revision = visual.Actor.SpriteRevision;
if (visual.Actor.SpritePlaying) visual.Sequence.Start();
}
if (visual.Actor.SpritePlaying) visual.Sequence.Step(dt);
}
}
public void FaceCamera(Vector3 eye, Vector3 target, Mesh? destination = null)
{
var output = destination ?? Mesh;
if (output.Vertices.Length < Mesh.Vertices.Length)
throw new ArgumentException("Destination omits sprite vertex ranges", nameof(destination));
var direction = target - eye;
if (direction.LengthSquared() < .000001f) direction = Vector3.UnitZ;
var right = Vector3.Cross(Vector3.UnitY, direction);
right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right);
var up = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(direction), right));
foreach (var visual in visuals)
{
var half = visual.Actor.SourceGam!.Integer("SpriteSize", 50) * .5f;
var center = visual.Actor.Position;
var corners = new[] { center-right*half-up*half, center+right*half-up*half,
center+right*half+up*half, center-right*half+up*half };
for (var frame = 0; frame < visual.Draws.Length; frame++)
{
visual.Draws[frame].Visible = visual.Actor.Visible && !visual.Sequence.Hidden && frame == visual.Sequence.Frame;
for (var corner = 0; corner < 4; corner++) output.Vertices[visual.Offset + frame * 4 + corner].Position = corners[corner];
}
}
}
}
@@ -0,0 +1,160 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>
/// Prepared original OMT props, phone booths and explicitly authored ASE models.
/// Keeps source-local positions, every non-null material draw, and director visibility.
/// </summary>
public sealed class StaticSceneVisuals
{
private sealed record Variant(string Name, MeshVertex[] LocalVertices, int Offset, MeshDraw[] Draws);
private sealed record Visual(DirectorActor Actor, string DefaultVariant, Variant[] Variants,
(Vector3 Min, Vector3 Max)? LocalBounds);
private readonly List<Visual> visuals = [];
public Mesh Mesh { get; }
public int ActorCount => visuals.Count;
public StaticSceneVisuals(Mesh combined, SceneDirector director, string assetsRoot, string preparedRoot)
{
// All authored ASE/PNG data is prepared locally too; runtime does not
// invent model defaults or silently fall back to an unrelated file.
_ = assetsRoot;
var root = Path.GetFullPath(preparedRoot);
using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "models.json")));
if (document.RootElement.GetProperty("schema").GetInt32() != 1)
throw new InvalidDataException("Unsupported prepared static model manifest");
string Resolve(string relative)
{
if (Path.IsPathRooted(relative)) throw new InvalidDataException("Static model path must be relative");
var path = Path.GetFullPath(Path.Combine(root, relative));
if (!path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Prepared static model escapes its directory");
return path;
}
var models = new Dictionary<string, Mesh>(StringComparer.Ordinal);
var bounds = new Dictionary<string, (Vector3 Min, Vector3 Max)>(StringComparer.Ordinal);
foreach (var model in document.RootElement.GetProperty("models").EnumerateArray())
{
models.Add(model.GetProperty("key").GetString()!, Mesh.LoadSceneJson(Resolve(model.GetProperty("path").GetString()!)));
if (model.TryGetProperty("source", out var source) && source.TryGetProperty("localBounds", out var box))
{
Vector3 Read(string key) => new(box.GetProperty(key)[0].GetSingle(), box.GetProperty(key)[1].GetSingle(), box.GetProperty(key)[2].GetSingle());
bounds.Add(model.GetProperty("key").GetString()!, (Read("min"), Read("max")));
}
}
var sourceActors = director.Actors.Where(a => a.SourceGam is not null)
.ToDictionary(a => a.SourceGam!.Offset);
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.HasExplicitDraws ? combined.Draws.ToList()
: [new MeshDraw(0, (uint)combined.Indices.Length, -1)];
var textures = new Dictionary<int, PngImage>(combined.Textures);
var nextTexture = int.MinValue + 20_000;
var added = new HashSet<int>();
foreach (var entry in document.RootElement.GetProperty("actors").EnumerateArray())
{
var sourceOffset = entry.GetProperty("offset").GetInt32();
if (!added.Add(sourceOffset) || !sourceActors.TryGetValue(sourceOffset, out var actor)
|| actor.Kind != entry.GetProperty("kind").GetString())
throw new InvalidDataException("Prepared static model actor does not match its source GAM offset");
var variants = new List<Variant>();
var tint = new Vector3(actor.SourceGam!.Number("Red", 1), actor.SourceGam.Number("Green", 1),
actor.SourceGam.Number("Blue", 1));
foreach (var variant in entry.GetProperty("variants").EnumerateObject())
{
var model = models[variant.Value.GetString()!];
var local = model.Vertices.Select(v => new MeshVertex(v.Position, v.Uv, v.Color * tint)).ToArray();
var vertexOffset = vertices.Count;
var indexOffset = indices.Count;
var identities = new Dictionary<int, int>();
foreach (var texture in model.Textures)
{
if (textures.ContainsKey(nextTexture))
throw new InvalidDataException("Reserved static model texture identity is already in use");
identities.Add(texture.Key, nextTexture);
textures.Add(nextTexture++, texture.Value);
}
vertices.AddRange(local);
indices.AddRange(model.Indices.Select(i => checked(i + (uint)vertexOffset)));
var retained = new List<MeshDraw>();
// LoadSceneJson intentionally omits null-material draws. Never
// replace an empty explicit list with a white whole-model draw.
var modelDraws = model.HasExplicitDraws ? model.Draws
: [new MeshDraw(0, (uint)model.Indices.Length, -1)];
foreach (var draw in modelDraws)
{
var textureId = draw.TextureId == -1 ? -1
: identities.TryGetValue(draw.TextureId, out var mapped) ? mapped
: throw new InvalidDataException("Static model draw references a missing texture");
var retainedDraw = new MeshDraw(checked(draw.FirstIndex + (uint)indexOffset), draw.IndexCount, textureId);
retained.Add(retainedDraw);
draws.Add(retainedDraw);
}
variants.Add(new(variant.Name, local, vertexOffset, retained.ToArray()));
}
var defaultVariant = entry.GetProperty("defaultVariant").GetString()!;
if (!variants.Any(v => Equal(v.Name, defaultVariant)))
throw new InvalidDataException("Missing default static model variant");
var defaultKey = entry.GetProperty("variants").GetProperty(defaultVariant).GetString()!;
visuals.Add(new(actor, defaultVariant, variants.ToArray(), bounds.TryGetValue(defaultKey, out var box) ? box : null));
}
Mesh = new(vertices.ToArray(), indices.ToArray())
{
Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures
};
Update(Mesh);
}
/// <summary>Apply the director's current root transform/visibility to retained model ranges.</summary>
public void Update(Mesh destination)
{
if (destination.Vertices.Length < Mesh.Vertices.Length)
throw new ArgumentException("Destination omits static model vertex ranges", nameof(destination));
foreach (var visual in visuals)
{
var actor = visual.Actor;
var selected = visual.DefaultVariant;
if (actor.Kind == "3BUT")
{
if (Equal(actor.Animation, "DOWN") || Equal(actor.Animation, "HIDOWN")) selected = "DOWN";
else if (Equal(actor.Animation, "UP") || Equal(actor.Animation, "HIUP")) selected = "UP";
}
var transform = Transform(actor);
foreach (var variant in visual.Variants)
{
for (var i = 0; i < variant.LocalVertices.Length; i++)
{
var vertex = variant.LocalVertices[i];
vertex.Position = Vector3.Transform(vertex.Position, transform);
destination.Vertices[variant.Offset + i] = vertex;
}
foreach (var draw in variant.Draws)
draw.Visible = actor.Visible && Equal(variant.Name, selected);
}
}
}
public IEnumerable<DynamicBoxCollider> DoorColliders()
{
foreach (var visual in visuals)
{
if (visual.Actor.Kind != "3DUD") continue;
var box = visual.LocalBounds ?? throw new InvalidDataException("Prepare original local door bounds before dynamic collision");
var flags = DynamicSceneCollision.DoorCollisionFlags(visual.Actor.SourceGam!.Integer("HasCollision", -1));
yield return new(visual.Actor.SourceGam.Offset, visual.Actor.Position, box.Min, box.Max,
Transform(visual.Actor), CollisionEnabled: flags.EntityCollision);
}
}
private static Matrix4x4 Transform(DirectorActor actor) =>
Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180)
* Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180)
* Matrix4x4.CreateTranslation(actor.Position);
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
+17 -2
View File
@@ -14,6 +14,7 @@ public struct MeshVertex(Vector3 position, Vector2 uv, Vector3 color)
public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices) public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
{ {
public MeshPolygonSource[] CollisionPolygons { get; init; } = [];
public MeshDraw[] Draws { get; init; } = []; public MeshDraw[] Draws { get; init; } = [];
public bool HasExplicitDraws { get; init; } public bool HasExplicitDraws { get; init; }
public Dictionary<int,PngImage> Textures { get; init; } = []; public Dictionary<int,PngImage> Textures { get; init; } = [];
@@ -38,6 +39,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray(); var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray();
if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices."); if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices.");
if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh."); if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh.");
var collisionPolygons = root.TryGetProperty("collisionPolygons", out var polygonList)
? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(),
p.GetProperty("polygonIndex").GetInt32(),
new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()),
p.GetProperty("materialName").GetString())).ToArray() : [];
if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3
|| collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z))))
throw new InvalidDataException("Invalid source collision polygon metadata");
var textures = new Dictionary<int,PngImage>(); var textures = new Dictionary<int,PngImage>();
if(root.TryGetProperty("textures",out var textureList)) foreach(var t in textureList.EnumerateArray()) if(root.TryGetProperty("textures",out var textureList)) foreach(var t in textureList.EnumerateArray())
{ {
@@ -71,8 +80,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2; for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2;
draws.Add(new MeshDraw(first,count,material.Item1)); draws.Add(new MeshDraw(first,count,material.Item1));
} }
return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures}; return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures,CollisionPolygons=collisionPolygons};
} }
} }
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId); public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName);
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{
public bool Visible { get; set; } = true;
public bool ScreenSpace { get; init; }
}
+4 -3
View File
@@ -72,18 +72,19 @@ public sealed class MorphAnimation
} }
} }
public Mesh AppendTo(Mesh scene) public Mesh AppendTo(Mesh scene, int textureId = int.MinValue)
{ {
var vertices = new MeshVertex[scene.Vertices.Length + Base.Vertices.Length]; var vertices = new MeshVertex[scene.Vertices.Length + Base.Vertices.Length];
scene.Vertices.CopyTo(vertices, 0); scene.Vertices.CopyTo(vertices, 0);
Base.Vertices.CopyTo(vertices, scene.Vertices.Length); Base.Vertices.CopyTo(vertices, scene.Vertices.Length);
var indices = scene.Indices.Concat(Base.Indices.Select(i => checked(i + (uint)scene.Vertices.Length))).ToArray(); var indices = scene.Indices.Concat(Base.Indices.Select(i => checked(i + (uint)scene.Vertices.Length))).ToArray();
var draws = scene.HasExplicitDraws ? scene.Draws : [new MeshDraw(0, (uint)scene.Indices.Length, -1)]; var draws = scene.HasExplicitDraws ? scene.Draws : [new MeshDraw(0, (uint)scene.Indices.Length, -1)];
var textures = new Dictionary<int, PngImage>(scene.Textures) { [int.MinValue] = Texture }; if (scene.Textures.ContainsKey(textureId)) throw new InvalidDataException("Actor texture identity already in use");
var textures = new Dictionary<int, PngImage>(scene.Textures) { [textureId] = Texture };
return new Mesh(vertices, indices) return new Mesh(vertices, indices)
{ {
HasExplicitDraws = true, HasExplicitDraws = true,
Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, int.MinValue)], Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, textureId)],
Textures = textures Textures = textures
}; };
} }
+114
View File
@@ -0,0 +1,114 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
namespace GamePort.Assets;
public sealed record SavedTask(string Name, int State);
/// <summary>Original TSK wire layout recovered at EXE0x45FEE0/0x4603F0; unknown fields retained.</summary>
public sealed record OriginalSave(string LevelCode, float PlayerValue, short Counter,
int Score, int OtherCounter, int[] ItemStates, int[] LevelCounters,
string StartPoint, string ReservedName, string ReturnLevel, string ReturnStart,
Vector3 StoredVector, int[] InventoryStates, SavedTask[] Tasks)
{
public const int ItemCount = 4200, LevelCounterCount = 29, InventoryCount = 19;
public static OriginalSave Load(string path) => Parse(File.ReadAllBytes(path));
public static OriginalSave Parse(ReadOnlySpan<byte> bytes)
{
var reader = new Reader(bytes);
var code = reader.Text(4);
if (code.Any(c => !char.IsAsciiLetterOrDigit(c))) throw new InvalidDataException("Invalid TSK level code");
var playerValue = reader.Float();
var counter = reader.Short();
var score = reader.Integer();
var otherCounter = reader.Integer();
var items = reader.Integers(ItemCount);
var levels = reader.Integers(LevelCounterCount);
var start = reader.Pascal();
var reserved = reader.Pascal();
var returnLevel = reader.Pascal();
var returnStart = reader.Pascal();
var vector = new Vector3(reader.Float(), reader.Float(), reader.Float());
var inventory = reader.Integers(InventoryCount);
var count = reader.Integer();
if (count < 0 || count > reader.Remaining / 5) throw new InvalidDataException("Invalid TSK task count");
var tasks = new SavedTask[count];
for (var i = 0; i < count; i++) tasks[i] = new(reader.Pascal(), reader.Integer());
if (reader.Remaining != 0) throw new InvalidDataException("Unexpected TSK trailing bytes");
return new(code, playerValue, counter, score, otherCounter, items, levels, start, reserved,
returnLevel, returnStart, vector, inventory, tasks);
}
public byte[] Encode()
{
using var output = new MemoryStream();
void Integer(int value)
{
Span<byte> raw = stackalloc byte[4];
BinaryPrimitives.WriteInt32BigEndian(raw, value);
output.Write(raw);
}
void Float(float value)
{
if (!float.IsFinite(value)) throw new InvalidDataException("Nonfinite TSK float");
Integer(BitConverter.SingleToInt32Bits(value));
}
void Text(string value, bool pascal)
{
if (value.Any(c => c > 255) || pascal && value.Length > 255)
throw new InvalidDataException("TSK text must fit original Latin1 Pascal string");
if (pascal) output.WriteByte((byte)value.Length);
output.Write(Encoding.Latin1.GetBytes(value));
}
void Table(int[] values, int length)
{
if (values.Length != length) throw new InvalidDataException("Invalid fixed TSK table length");
foreach (var value in values) Integer(value);
}
if (LevelCode.Length != 4 || LevelCode.Any(c => !char.IsAsciiLetterOrDigit(c)))
throw new InvalidDataException("Invalid TSK level code");
Text(LevelCode, false);
Float(PlayerValue);
Span<byte> shortBytes = stackalloc byte[2];
BinaryPrimitives.WriteInt16BigEndian(shortBytes, Counter);
output.Write(shortBytes);
Integer(Score); Integer(OtherCounter);
Table(ItemStates, ItemCount); Table(LevelCounters, LevelCounterCount);
Text(StartPoint, true); Text(ReservedName, true); Text(ReturnLevel, true); Text(ReturnStart, true);
Float(StoredVector.X); Float(StoredVector.Y); Float(StoredVector.Z);
Table(InventoryStates, InventoryCount);
Integer(Tasks.Length);
foreach (var task in Tasks) { Text(task.Name, true); Integer(task.State); }
return output.ToArray();
}
private ref struct Reader(ReadOnlySpan<byte> data)
{
private readonly ReadOnlySpan<byte> bytes = data;
private int offset;
public int Remaining => bytes.Length - offset;
private ReadOnlySpan<byte> Take(int count)
{
if (count < 0 || count > Remaining) throw new InvalidDataException($"Truncated TSK at0x{offset:X}");
var value = bytes.Slice(offset, count); offset += count; return value;
}
public string Text(int count) => Encoding.Latin1.GetString(Take(count));
public string Pascal() => Text(Take(1)[0]);
public short Short() => BinaryPrimitives.ReadInt16BigEndian(Take(2));
public int Integer() => BinaryPrimitives.ReadInt32BigEndian(Take(4));
public float Float()
{
var value = BitConverter.Int32BitsToSingle(Integer());
return float.IsFinite(value) ? value : throw new InvalidDataException("Nonfinite TSK float");
}
public int[] Integers(int count)
{
if (count > Remaining / 4) throw new InvalidDataException("Truncated fixed TSK table");
var values = new int[count];
for (var i = 0; i < count; i++) values[i] = Integer();
return values;
}
}
}
@@ -0,0 +1,60 @@
using System.Text.Json;
namespace GamePort.Assets;
public sealed record PreparedWave(string Path, double Seconds);
/// <summary>Original database/type/id resource identities retained by entities.py.</summary>
public sealed class PreparedEntityResources
{
private readonly Dictionary<(string Database, int Id), PreparedWave> waves = [];
private readonly Dictionary<(string Database, int Id), PngImage> canvases = [];
public PreparedEntityResources(params string[] manifests)
{
foreach (var manifest in manifests) Load(manifest);
}
private void Load(string manifest)
{
var directory = Path.GetDirectoryName(Path.GetFullPath(manifest))!;
string Resolve(string relative)
{
var full = Path.GetFullPath(Path.Combine(directory, relative));
if (!full.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Prepared resource escapes its directory");
return full;
}
using var doc = JsonDocument.Parse(File.ReadAllText(manifest));
foreach (var resource in doc.RootElement.GetProperty("resources").EnumerateArray())
{
if (!resource.TryGetProperty("path", out var path)) continue;
var key = (Normalize(resource.GetProperty("database").GetString()!), resource.GetProperty("id").GetInt32());
switch (resource.GetProperty("type").GetString())
{
case "Wave":
var seconds = resource.GetProperty("audio").GetProperty("seconds").GetDouble();
if (!double.IsFinite(seconds) || seconds < 0) throw new InvalidDataException("Invalid prepared audio duration");
var resolved = Resolve(path.GetString()!);
if (waves.TryGetValue(key, out var previous))
{
if (previous.Seconds != seconds || !File.ReadAllBytes(previous.Path).AsSpan().SequenceEqual(File.ReadAllBytes(resolved)))
throw new InvalidDataException("Conflicting prepared wave identity");
}
else waves.Add(key, new(resolved, seconds));
break;
case "Canv":
var width = resource.GetProperty("width").GetUInt32();
var height = resource.GetProperty("height").GetUInt32();
var rgba = File.ReadAllBytes(Resolve(path.GetString()!));
if (width == 0 || height == 0 || width > 8192 || height > 8192 || rgba.Length != checked((int)(width * height * 4)))
throw new InvalidDataException("Invalid prepared canvas");
canvases.Add(key, new(width, height, rgba));
break;
}
}
}
private static string Normalize(string name) => Path.GetFileName(name.Replace('\\', '/')).ToUpperInvariant();
public PreparedWave? Wave(string database, int id) => waves.GetValueOrDefault((Normalize(database), id));
public PngImage? Canvas(string database, int id) => canvases.GetValueOrDefault((Normalize(database), id));
public double Duration(string database, int id) => Wave(database, id)?.Seconds
?? throw new FileNotFoundException($"Prepare original speech resource {database}:Wave:{id}");
}
+61
View File
@@ -0,0 +1,61 @@
using GamePort.Assets;
namespace GamePort.Audio;
/// <summary>Independent original music and sequential speech streams.</summary>
public sealed class SceneAudio : IDisposable
{
private readonly PreparedEntityResources resources;
private SdlAudio? music, speech;
private readonly List<SdlAudio> effects = [];
private readonly Dictionary<string, SdlAudio> loops = new(StringComparer.OrdinalIgnoreCase);
public int EffectCount => effects.Count;
public int LoopCount => loops.Count;
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
public int QueuedMusicBytes => music?.QueuedBytes ?? 0;
public int QueuedSpeechBytes => speech?.QueuedBytes ?? 0;
public SceneAudio(PreparedEntityResources resources) => this.resources = resources;
public void Music(string database, int id)
{
music?.Dispose(); music = null;
if (resources.Wave(database, id) is { } wave) music = new(wave.Path, true);
}
public void Speech(string database, int id)
{
StopSpeech();
var wave = resources.Wave(database, id) ?? throw new FileNotFoundException($"Missing prepared speech: {database}:{id}");
speech = new(wave.Path);
}
public void StopSpeech() { speech?.Dispose(); speech = null; }
// Default current bank set by Jimmy PostLoad423642..656; positional attenuation
// and original channel/volume policy are separate unrecovered consumers.
public void Effect(int id, string? loopOwner = null)
{
var wave = resources.Wave("SoundEffects.omt", id)
?? throw new FileNotFoundException($"Missing original default sound effect {id}");
if (loopOwner == null) effects.Add(new(wave.Path));
else
{
StopLoop(loopOwner);
loops.Add(loopOwner, new(wave.Path, true));
}
}
public void StopLoop(string owner)
{
if (loops.Remove(owner, out var stream)) stream.Dispose();
}
public void StopEffects()
{
foreach (var effect in effects) effect.Dispose();
foreach (var effect in loops.Values) effect.Dispose();
effects.Clear(); loops.Clear();
}
public void Pump()
{
music?.Pump(); speech?.Pump();
foreach (var effect in loops.Values) effect.Pump();
for (var i = effects.Count - 1; i >= 0; i--)
if (effects[i].QueuedBytes == 0) { effects[i].Dispose(); effects.RemoveAt(i); }
}
public void Dispose() { StopEffects(); StopSpeech(); music?.Dispose(); music = null; }
}
+214
View File
@@ -0,0 +1,214 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>Root state exchanged with the separately implemented body solver.</summary>
public readonly record struct PatrolBodyState(Vector3 Position, Vector3 Velocity);
/// <summary>
/// Goddard/Carl's ordinary state3 patrol and state7 waypoint wait. The original base
/// update consumes the preceding velocity/heading before choosing the next ones.
/// Physical collision/gravity are supplied by the caller. Magnitude uses the
/// recovered OMT table algorithm; flat atan2 heading and modern table-generation
/// trig still require comparison against original angle/x87 results.
/// See docs/analysis/patrol.md for recovered order, addresses and limitations.
/// </summary>
public sealed class ActorPatrol
{
public const float ArrivalDistance = 110;
public const float YawFactor = 3.2f;
private readonly DirectorActor actor;
private readonly Func<string, DirectorActor?> findActor;
private readonly Func<PatrolBodyState, float, PatrolBodyState> integrateBody;
private readonly Func<Vector3, float> magnitude;
private readonly float yawFactor;
private readonly string movingAnimation, waitingAnimation;
private DirectorActor? waypoint;
private DirectorActor? previousWaypoint;
private Vector3 publishedPosition, publishedRotation;
private string? publishedPatrol;
private int publishedState, previousState;
private float desiredYaw;
public Vector3 Velocity { get; private set; }
public Vector3 DestinationDelta { get; private set; }
public float DestinationDistance { get; private set; }
public bool Arrived { get; private set; }
public float WaitRemaining { get; private set; }
public string? CurrentWaypoint => waypoint?.Tag;
public string? PreviousWaypoint => previousWaypoint?.Tag;
public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6;
public ActorPatrol(DirectorActor actor, Func<string, DirectorActor?> findActor,
Func<PatrolBodyState, float, PatrolBodyState> integrateBody,
Func<Vector3, float>? magnitude = null)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(findActor);
ArgumentNullException.ThrowIfNull(integrateBody);
if (actor.Kind is not ("3DOG" or "3CAR")) throw new ArgumentException("Recovered patrol requires Goddard or Carl", nameof(actor));
this.actor = actor;
this.findActor = findActor;
this.integrateBody = integrateBody;
this.magnitude = magnitude ?? OriginalBodySupport.QuickMagnitude;
// Carl413BFC..43 installs WALK/STOP; his Y factor remains3 (407CF8).
yawFactor = actor.Kind == "3DOG" ? YawFactor : 3;
movingAnimation = actor.Kind == "3DOG" ? "RUN" : "WALK";
waitingAnimation = actor.Kind == "3DOG" ? "WAG" : "STOP";
desiredYaw = actor.Rotation.Y;
Publish();
}
/// <summary>
/// Observe authored AI/teleport actions without changing their animation.
/// Teleports reset the port body's motion/route cache; their full original
/// physics bookkeeping is not yet recovered. Camera-only animation changes
/// leave the body and waypoint intact. Internal patrol changes emit no event.
/// </summary>
public void SynchronizeAuthoredState()
{
if (actor.Position != publishedPosition)
{
Velocity = Vector3.Zero;
ResetRoute();
desiredYaw = actor.Rotation.Y;
}
if (actor.Rotation != publishedRotation) desiredYaw = actor.Rotation.Y;
if (!Equal(actor.Patrol, publishedPatrol)
|| actor.AIstate != publishedState && actor.AIstate == 3)
ResetRoute();
Publish();
}
/// <returns>False when the current AI state lies outside this recovered subset.</returns>
public bool Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
SynchronizeAuthoredState();
if (!SupportedState) return false;
if (!actor.Active) return true;
if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed");
// EXE408023->40E050: the body consumes the *previous* velocity first.
var body = integrateBody(new(actor.Position, Velocity), dt);
if (!Finite(body.Position) || !Finite(body.Velocity))
throw new InvalidOperationException("Goddard body solver produced nonfinite state");
actor.Position = body.Position;
Velocity = body.Velocity;
var yawError = (desiredYaw - actor.Rotation.Y) % 360;
if (yawError > 180) yawError -= 360;
if (yawError < -180) yawError += 360;
actor.Rotation = actor.Rotation with { Y = actor.Rotation.Y + yawError * yawFactor * dt };
switch (actor.AIstate)
{
case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration.
case 3: StepPatrol(); break;
case 7: StepWait(dt); break;
// State9 jumps directly to the common finisher408911. State6 calls
// sensing409CC0 first; source player-contact dispatch is implemented
// by SceneInteractions, while general FOV/visibility sensing is open.
case 6: case 9: break;
}
// States1/6/7 return before selecting a destination angle (409186..19B).
// Retain the old destination on a waypoint change, as the source does.
if (actor.AIstate == 3 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0)
desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI);
Publish();
return true;
}
private void StepPatrol()
{
waypoint ??= findActor(actor.Patrol ?? "none");
if (waypoint == null)
{
SetState(1);
Velocity = new(0, Velocity.Y, 0); // Missing initial waypoint preserves Y.
}
else
{
DestinationDelta = waypoint.Position - actor.Position;
DestinationDistance = DestinationDelta.Length();
if (!float.IsFinite(DestinationDistance)) throw new InvalidOperationException("Patrol destination exceeds finite arithmetic range");
}
// This remains after the waypoint resolver even if it changed state1.
actor.Animation = movingAnimation;
if (waypoint == null) return;
if (Arrived)
{
Velocity = Vector3.Zero;
actor.Animation = waitingAnimation;
}
else if (DestinationDelta == Vector3.Zero) Velocity = Vector3.Zero;
else
{
var length = magnitude(DestinationDelta);
if (!float.IsFinite(length) || length <= 0) throw new InvalidOperationException("Invalid patrol magnitude");
Velocity = DestinationDelta / length * actor.Speed;
}
// EXE408BC0 compares distance only after selecting the next velocity.
if (DestinationDistance < ArrivalDistance) Arrived = true;
else if (DestinationDistance > ArrivalDistance) Arrived = false;
if (!Arrived || waypoint.Kind != "3PAT" || waypoint.SourceGam is not { } point) return;
var wait = point.Number("WaitTime");
if (wait > 0)
{
SetState(7);
actor.Animation = point.Text("WaitAnim") ?? "none";
WaitRemaining = wait;
Velocity = Vector3.Zero;
return;
}
previousWaypoint = waypoint;
var next = point.Text("NextPatrolPoint") ?? "none";
waypoint = findActor(next);
if (waypoint != null) return;
if (Equal(next, "WAIT")) SetState(1);
else if (Equal(next, "SCAN")) SetState(6);
// Ordinary unresolved names, including "none", retain state3. Next tick
// resolves the initial PatrolPoint; there is no terminal-route snap.
}
private void StepWait(float dt)
{
Velocity = Vector3.Zero;
if (WaitRemaining <= 0) return; // Source checks positivity before subtract.
WaitRemaining -= dt;
if (WaitRemaining > 0) return; // Equality expires: EXE4083B0 testah41/je.
SetState(previousState);
Arrived = false;
// The timed-wait branch does not interpret WAIT/SCAN specially.
waypoint = waypoint?.SourceGam is { } point && waypoint.Kind == "3PAT"
? findActor(point.Text("NextPatrolPoint") ?? "none") : null;
}
private void SetState(int state)
{
previousState = actor.AIstate;
actor.AIstate = state;
if (state == 1) actor.Animation = waitingAnimation;
else if (state == 3) actor.Animation = movingAnimation;
}
private void ResetRoute()
{
waypoint = previousWaypoint = null;
Arrived = false;
WaitRemaining = 0;
DestinationDelta = Vector3.Zero;
DestinationDistance = 0;
}
private void Publish()
{
publishedPosition = actor.Position;
publishedRotation = actor.Rotation;
publishedPatrol = actor.Patrol;
publishedState = actor.AIstate;
}
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
}
+34
View File
@@ -0,0 +1,34 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Explicit provisional narrowphase adapter. Source mode2 gates/corners/order
/// come from DynamicSceneCollision; sweep/slide uses the modern sphere kernel.
/// This is not a translation of original47BD80.
/// </summary>
public static class DynamicBodyResponse
{
public static Vector3 Resolve(IEnumerable<DynamicBoxCollider> boxes, Vector3 previous, Vector3 position, float radius)
{
foreach (var box in boxes)
{
var response = DynamicSceneCollision.Resolve(box, new(previous, position, radius), Sweep);
if (response.Contact) position = response.Position;
}
return position;
}
private static DynamicCollisionResponse Sweep(DynamicBoxSweep sweep)
{
var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C })
.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray();
var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray());
var radius = sweep.Sphere.Radius;
var moved = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius,
sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2);
var position = moved.Position + Vector3.UnitY * radius;
return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position);
}
}
+128
View File
@@ -0,0 +1,128 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>
/// A mode2 entity's original local shape cube and current transform. Drawing
/// visibility and own physics integration are independent of CollisionEnabled.
/// </summary>
public readonly record struct DynamicBoxCollider(
int Identity, Vector3 Root, Vector3 LocalMin, Vector3 LocalMax, Matrix4x4 LocalToWorld,
float Radius = 40, bool CollisionEnabled = true, bool InhibitResponse = false);
public readonly record struct DynamicSphereMotion(
Vector3 PreviousPosition, Vector3 Position, float Radius,
bool CollisionEnabled = true, bool GeometryCollisionEnabled = true, int Mode = 1);
public sealed record DynamicBoxSweep(
DynamicBoxCollider Box, DynamicSphereMotion Sphere, IReadOnlyList<SupportTriangle> Triangles);
public readonly record struct DynamicCollisionResponse(bool Contact, Vector3 Position);
/// <summary>
/// Recovered mode2 dispatch, broadphase and oriented local-cube triangulation
/// from EXE47A430/47A5E0. The narrowphase is injected because47BD80 and its
/// static-world response have not been fully translated. See dynamic-collision.md.
/// </summary>
public static class DynamicSceneCollision
{
// C3DDoorUpDown constructor/PostLoad: pair tests on, own integration off,
// mode2 and current radius40. HasCollision=-1 preserves those defaults.
public const float DoorRadius = 40;
public const int DoorMode = 2;
public const bool DoorEntityCollisionDefault = true;
public const bool DoorIntegrationDefault = false;
// Corner bits X=4,Y=2,Z=1. Source jump table47B3AC selects these12 triples.
private static readonly int[] triangleCorners = [
0, 1, 2, 1, 3, 2, 0, 2, 4, 2, 6, 4,
4, 6, 5, 6, 7, 5, 5, 7, 3, 5, 3, 1,
0, 4, 1, 4, 5, 1, 2, 3, 7, 7, 6, 2
];
public static (bool EntityCollision, bool Integrate) DoorCollisionFlags(int hasCollision) =>
hasCollision == -1 ? (DoorEntityCollisionDefault, DoorIntegrationDefault)
: (hasCollision != 0, hasCollision != 0);
/// <summary>
/// Preserve the original inclusive root-distance gate. Normal sphere-mode
/// bodies use 2*boxRadius+sphereRadius, even for a large shape-local cube.
/// Mode2-vs-mode2 instead uses the radius sum and skips the triangle sweep.
/// </summary>
public static bool BroadPhase(DynamicBoxCollider box, DynamicSphereMotion sphere)
{
Validate(box, sphere);
if (!box.CollisionEnabled || !sphere.CollisionEnabled || !sphere.GeometryCollisionEnabled) return false;
var limit = sphere.Mode == 2 ? box.Radius + sphere.Radius : 2 * box.Radius + sphere.Radius;
return OriginalBodySupport.QuickMagnitude(sphere.Position - box.Root) <= limit;
}
public static Vector3[] Corners(DynamicBoxCollider box)
{
ValidateBox(box);
var corners = new Vector3[8];
for (var i = 0; i < corners.Length; i++)
{
var local = new Vector3((i & 4) == 0 ? box.LocalMin.X : box.LocalMax.X,
(i & 2) == 0 ? box.LocalMin.Y : box.LocalMax.Y,
(i & 1) == 0 ? box.LocalMin.Z : box.LocalMax.Z);
corners[i] = Vector3.Transform(local, box.LocalToWorld);
RequireFinite(corners[i]);
}
return corners;
}
public static SupportTriangle[] Triangles(DynamicBoxCollider box)
{
var corners = Corners(box);
return Enumerable.Range(0, 12).Select(i => new SupportTriangle(
corners[triangleCorners[3 * i]], corners[triangleCorners[3 * i + 1]],
corners[triangleCorners[3 * i + 2]], box.Identity, i)).ToArray();
}
/// <summary>
/// Caller supplies mutual exclusion/class gates via pairAllowed and the current
/// source cube/transform. Triangle geometry follows the moving box's current
/// root; no invented relative-door sweep or permanent closed-position mesh.
/// </summary>
public static DynamicCollisionResponse Resolve(DynamicBoxCollider box, DynamicSphereMotion sphere,
Func<DynamicBoxSweep, DynamicCollisionResponse> narrowPhase, bool pairAllowed = true)
{
ArgumentNullException.ThrowIfNull(narrowPhase);
var unchanged = new DynamicCollisionResponse(false, sphere.Position);
if (!pairAllowed || !BroadPhase(box, sphere)) return unchanged;
// EXE47A712..47A72C returns contact directly for a second mode2 entity.
if (sphere.Mode == 2) return new(true, sphere.Position);
var response = narrowPhase(new(box, sphere, Triangles(box)));
if (!response.Contact) return unchanged;
RequireFinite(response.Position);
// EXE47B2EF checks the box's iface1E0 flag after narrowphase; touch events
// can still occur even when its ordinary root response is inhibited.
return new(true, box.InhibitResponse ? sphere.Position : response.Position);
}
private static void Validate(DynamicBoxCollider box, DynamicSphereMotion sphere)
{
ValidateBox(box);
RequireFinite(sphere.Position); RequireFinite(sphere.PreviousPosition);
if (!float.IsFinite(sphere.Radius) || sphere.Radius < 0)
throw new ArgumentOutOfRangeException(nameof(sphere), "Finite nonnegative sphere radius required");
}
private static void ValidateBox(DynamicBoxCollider box)
{
RequireFinite(box.Root); RequireFinite(box.LocalMin); RequireFinite(box.LocalMax);
if (box.LocalMin.X > box.LocalMax.X || box.LocalMin.Y > box.LocalMax.Y || box.LocalMin.Z > box.LocalMax.Z
|| !float.IsFinite(box.Radius) || box.Radius < 0)
throw new ArgumentOutOfRangeException(nameof(box), "Ordered source cube and finite nonnegative radius required");
var m = box.LocalToWorld;
if (new[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24,
m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44 }.Any(v => !float.IsFinite(v))
|| m.M14 != 0 || m.M24 != 0 || m.M34 != 0 || m.M44 != 1)
throw new ArgumentOutOfRangeException(nameof(box), "Finite affine source transform required");
}
private static void RequireFinite(Vector3 v)
{
if (!float.IsFinite(v.X) || !float.IsFinite(v.Y) || !float.IsFinite(v.Z))
throw new ArgumentOutOfRangeException(nameof(v), "Finite source coordinates required");
}
}
+202
View File
@@ -0,0 +1,202 @@
namespace GamePort.Game;
public readonly record struct JetpackBurstState(
int JumpState = 0, float HoldSeconds = 0, float EffectRemaining = 0);
public readonly record struct JetpackBurstInput(
bool Grounded, bool JumpHeld, float VelocityY, float ShadowDistance,
int InventoryState, float Energy, string LevelCode, int GadgetMode,
float DeltaSeconds, float CurrentExtraAccelerationY,
bool EffectAvailable = true, float GravityY = -800);
public enum JetpackPose { None, Jump, Fall, Fly }
public readonly record struct JetpackBurstResult(
JetpackBurstState State, float ImpulseY, float? VelocityYOverride,
float ExtraAccelerationY, JetpackPose Pose, float? RadiusOverride,
bool StartGadget, bool StopGadget, int? MovementModeOverride);
public readonly record struct JetpackEffectResult(
JetpackBurstState State, float Energy, bool Visible);
/// <summary>
/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0.
/// Controller and effect phases are separate: their full-scene order has not
/// been recovered. The caller must explicitly choose an order. Horizontal
/// movement, shadow queries, visuals and sound callbacks belong to the caller.
/// </summary>
public static class JetpackBurst
{
public const float Duration = 8;
public const float HoldThreshold = .4f;
public const float JumpImpulse = 550;
public const float BurstInitialVelocityY = 10;
public const float BurstRadius = 100;
public const float LandingRadius = 60;
public const float EnergyPerSecond = .5f;
/// <summary>
/// Includes the outer update's ordinary grounded/released reset (437B9E).
/// CurrentExtraAccelerationY is required because the expired-effect branch
/// returns before writing acceleration. Results describe this invocation;
/// a newly started/stopped burst changes acceleration on the next call.
/// </summary>
public static JetpackBurstResult Step(JetpackBurstState state, JetpackBurstInput input)
{
ValidateState(state);
ValidateSeconds(input.DeltaSeconds);
RequireFinite(input.VelocityY);
RequireFinite(input.ShadowDistance);
RequireFinite(input.Energy);
RequireFinite(input.CurrentExtraAccelerationY);
RequireFinite(input.GravityY);
ArgumentNullException.ThrowIfNull(input.LevelCode);
var extra = input.CurrentExtraAccelerationY;
JetpackBurstResult Result(float impulse = 0, float? velocity = null,
JetpackPose pose = JetpackPose.None, float? radius = null,
bool start = false, bool stop = false, int? mode = null) =>
new(state, impulse, velocity, extra, pose, radius, start, stop, mode);
if (input.Grounded && !input.JumpHeld)
{
// This path runs ground apply instead of air apply; it does not
// itself clear the effect timer or restore the radius.
state = state with { JumpState = 0 };
return Result(mode: 0);
}
if (state.JumpState < 3)
extra = input.GravityY * 1.33f - input.GravityY;
else
{
if (input.EffectAvailable && state.EffectRemaining <= 0 && state.JumpState is 3 or 4)
{
state = state with { JumpState = 0, EffectRemaining = 0 };
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
}
// The near-floor constants are doubles in the original; the far
// branch uses float .1. Preserve those distinct constant widths.
extra = input.ShadowDistance < 500
? (float)(-input.GravityY - (input.VelocityY < -1 ? .3 : .1) * input.GravityY)
: .1f * input.GravityY - input.GravityY;
}
if (!input.JumpHeld)
{
switch (state.JumpState)
{
case 1:
state = state with { JumpState = 2 };
break;
case 3:
state = state with { JumpState = 4,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
case 4:
// Table4387C4 entry3 jumps directly43879A. Only state5's
// entry checks grounded at43878C (outer reset above too).
state = state with { JumpState = 0 };
break;
}
return Result();
}
switch (state.JumpState)
{
case 0:
if (!input.Grounded) return Result(pose: JetpackPose.Fall, stop: true);
state = state with { JumpState = 1, HoldSeconds = 0,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(impulse: JumpImpulse, pose: JetpackPose.Jump);
case 1:
state = state with { HoldSeconds = state.HoldSeconds + input.DeltaSeconds };
if (state.HoldSeconds <= HoldThreshold) return Result();
break;
case 2:
break;
case 3:
if (!input.Grounded) return Result();
state = state with { JumpState = 4,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(pose: JetpackPose.Fall, radius: LandingRadius, stop: true, mode: 1);
case 5:
if (input.Grounded) state = state with { JumpState = 0 };
return Result();
default:
return Result();
}
// Both the >.4-second and released-then-held branches enter state3
// even when no gadget is available. The next expired-effect guard
// then returns to state0, preserving the ballistic acceleration.
state = state with { JumpState = 3 };
if (!CanStart(input.LevelCode, input.GadgetMode, input.InventoryState, input.Energy)) return Result();
if (input.EffectAvailable) state = state with { EffectRemaining = Duration };
return Result(velocity: BurstInitialVelocityY, pose: JetpackPose.Fly,
radius: input.EffectAvailable ? BurstRadius : null, start: true);
}
public static bool CanStart(string levelCode, int gadgetMode, int inventoryState, float energy)
{
ArgumentNullException.ThrowIfNull(levelCode);
RequireFinite(energy);
if (levelCode == "VR04") return true;
return levelCode is not ("LEV6" or "LV4B" or "LV6A" or "LEV3" or "LV3A" or "LV3B" or "LV3C" or "LV3D")
&& gadgetMode is not (2 or 6 or 7) && energy > 0 && inventoryState is not (0 or 4);
}
/// <summary>
/// Effect421FB0 resets grounded remaining time to0, subtracts dt (including
/// when inactive), then drains only if the stored result is positive.
/// Owner/effect absence leaves timer and energy unchanged. Energy reaching
/// zero does not cancel an already running burst. Visibility is this phase's
/// request; the controller phase does not itself show/hide the effect.
/// </summary>
public static JetpackEffectResult StepEffect(JetpackBurstState state, bool grounded,
float deltaSeconds, float energy, string levelCode,
bool ownerAvailable = true, bool effectAvailable = true)
{
ValidateState(state);
ValidateSeconds(deltaSeconds);
RequireFinite(energy);
ArgumentNullException.ThrowIfNull(levelCode);
if (!ownerAvailable || !effectAvailable) return new(state, energy, false);
var remaining = (grounded ? 0 : state.EffectRemaining) - deltaSeconds;
state = state with { EffectRemaining = remaining };
if (remaining <= 0) return new(state, energy, false);
return new(state, AdjustEnergy(energy, -deltaSeconds * EnergyPerSecond, levelCode), true);
}
/// <summary>EXE42A920 numeric VR01..VR08 immunity and [0,100] clamp. SFX are external.</summary>
public static float AdjustEnergy(float energy, float delta, string levelCode)
{
RequireFinite(energy);
RequireFinite(delta);
ArgumentNullException.ThrowIfNull(levelCode);
// The source compares a big-endian FourCC numerically, not by prefix.
if (levelCode.Length == 4)
{
var code = ((uint)levelCode[0] << 24) | ((uint)levelCode[1] << 16)
| ((uint)levelCode[2] << 8) | levelCode[3];
if (code is >= 0x56523031 and <= 0x56523038) return energy;
}
return Math.Clamp(energy + delta, 0, 100);
}
private static void ValidateState(JetpackBurstState state)
{
if (state.JumpState is < 0 or > 5) throw new ArgumentOutOfRangeException(nameof(state));
RequireFinite(state.HoldSeconds);
RequireFinite(state.EffectRemaining);
}
private static void ValidateSeconds(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
}
private static void RequireFinite(float value)
{
if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value));
}
}
+57 -27
View File
@@ -4,7 +4,7 @@ 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);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall } public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly }
/// <summary> /// <summary>
/// No-gadget walking checkpoint. Recovered input/arithmetic is described in /// No-gadget walking checkpoint. Recovered input/arithmetic is described in
@@ -16,9 +16,18 @@ 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 Vector3 sourceStart; private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight; private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, jumpHeldTime; private float targetYaw, extraAirAcceleration, shadowDistance;
private int jumpState; private JetpackBurstState jumpState;
private bool forceFall;
public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B";
public int GadgetMode { get; set; } = -1;
public float Energy { get; set; } = 20;
public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining;
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; }
@@ -26,13 +35,15 @@ public sealed class LabSimulation
public float Speed { get; private set; } public float Speed { 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 => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; } public int Steps { get; private set; }
public int Jumps { get; private set; } public int Jumps { get; private set; }
public int Landings { get; private set; } public int Landings { get; private set; }
public int WallHits { get; private set; } public int WallHits { get; private set; }
public float Travel { get; private set; } public float Travel { get; private set; }
public float MaximumRise { get; private set; } public float MaximumRise { get; private set; }
public Func<Vector3, Vector3, float, Vector3>? DynamicRootResolver { get; set; }
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight; public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; } public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0); public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
@@ -49,7 +60,11 @@ public sealed class LabSimulation
BodyHeight = bounds.Max.Y - bounds.Min.Y; BodyHeight = bounds.Max.Y - bounds.Min.Y;
var floor = collision.GroundHeight(start, 2500) var floor = collision.GroundHeight(start, 2500)
?? throw new InvalidDataException("No support below GAM startpoint"); ?? throw new InvalidDataException("No support below GAM startpoint");
rootHeight = start.Y - floor; startFloor = floor;
// Normal Jimmy PostLoad4236A3..BA and support47BAE1 place the actor
// root at floor+60*1.265. Serialized spawnY is settled by physics.
// Feet collision and sole-based visual placement remain provisional.
rootHeight = OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
Reset(); Reset();
} }
@@ -59,8 +74,10 @@ public sealed class LabSimulation
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z); Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z);
Velocity = Vector3.Zero; Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw; Yaw = targetYaw = startYaw;
Speed = jumpHeldTime = 0; Speed = extraAirAcceleration = shadowDistance = 0;
jumpState = 0; jumpState = default;
forceFall = JetpackEffectVisible = false;
InteractionRadius = 60; Bursts = 0;
Grounded = true; Grounded = true;
Steps = Jumps = Landings = WallHits = 0; Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0; Travel = MaximumRise = 0;
@@ -83,7 +100,7 @@ public sealed class LabSimulation
float lateral = 0; float lateral = 0;
if (Grounded) if (Grounded)
{ {
if (!input.Jump) jumpState = 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; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); } else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
@@ -97,34 +114,47 @@ public sealed class LabSimulation
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);
if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt); if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt);
var impulse = Vector3.Zero; if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
if (Grounded && input.Jump && jumpState == 0) shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13);
{ var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
impulse.Y = RecoveredMotion.JumpImpulse; JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
jumpState = 1; jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
jumpHeldTime = 0; var impulse = new Vector3(0, air.ImpulseY, 0);
Grounded = false; if (air.ImpulseY != 0) { Grounded = false; Jumps++; }
Jumps++; if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
} if (air.RadiusOverride is { } radius) InteractionRadius = radius;
if (!Grounded && jumpState == 1) if (air.Pose == JetpackPose.Fall) forceFall = true;
{ else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (!input.Jump) jumpState = 2; if (air.StartGadget) Bursts++;
else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL.
}
else if (!Grounded && jumpState == 2 && input.Jump)
jumpState = 0; // Renewed hold enters the same disabled-gadget reset path.
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse, var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
RecoveredMotion.Gravity * 0.33f, 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);
Position = result.Position; Position = result.Position;
if (DynamicRootResolver != null)
{
var root = ActorRoot;
var resolved = DynamicRootResolver(before + Vector3.UnitY * rootHeight, root, InteractionRadius);
if (resolved != root)
{
// Original47A5E0 re-clips against static geometry before storing
// the new root. Here both kernels remain explicitly provisional.
result = collision.Move(Position, resolved - root, BodyRadius, BodyHeight);
Position = result.Position;
}
}
Grounded = result.Grounded && velocity.Y <= 0; Grounded = result.Grounded && velocity.Y <= 0;
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; }
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 - sourceStart.Y + rootHeight); MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
Steps++; Steps++;
var desired = DesiredEye(); var desired = DesiredEye();
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt; var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
+167
View File
@@ -0,0 +1,167 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct SupportTriangle(Vector3 A, Vector3 B, Vector3 C, int ShapeId = 0, int PolygonId = 0);
public readonly record struct SupportHit(Vector3 Position, int ShapeId, int PolygonId, float Distance);
public delegate SupportHit? SupportSegmentQuery(Vector3 start, Vector3 end, bool twoSided);
public readonly record struct SupportBody(
Vector3 Position, Vector3 PreviousPosition, Vector3 Velocity, Vector3 Acceleration,
float Radius, float Factor, bool PreventLowering = true);
public readonly record struct SupportResult(
SupportBody Body, bool Supported, bool Landed, SupportHit? Hit, Vector3 SupportAnchor);
/// <summary>
/// Bounded translation of EXE47B890 and its source triangle query. This handles
/// root support, not the wall/ceiling sphere solver or entity collisions. Lookup
/// tables use the recovered initializer constants with modern trig; exact x87
/// table values and full original frame ordering still require comparison.
/// </summary>
public static class OriginalBodySupport
{
public const float JimmyRadius = 60;
public const float JimmyFactor = 1.265f;
public const float GoddardRadius = 130;
public const float GoddardFactor = 0.3f;
private const float TriangleEpsilon = 1.1920928955078125e-7f;
private static readonly float[] sine = BuildSine();
private static readonly ushort[] halfAcos = BuildHalfAcos();
/// <summary>OMT1001FF70: largest component divided by a quantized sine lookup.</summary>
public static float QuickMagnitude(Vector3 vector)
{
RequireFinite(vector);
var x = (double)MathF.Abs(vector.X);
var y = (double)MathF.Abs(vector.Y);
var z = (double)MathF.Abs(vector.Z);
if (x > y) { if (x > z) (x, z) = (z, x); }
else if (y > z) (y, z) = (z, y);
// The original passes 0/0 through _ftol. The port handles zero directly
// instead of depending on an invalid x87 conversion/control-word mode.
if (z == 0) return 0;
var otherSquared = x * x + y * y;
var index = (int)(otherSquared * 16384 / (otherSquared + z * z)) & 0x3fff;
return (float)(z / sine[halfAcos[index] & 0x3fff]);
}
/// <summary>
/// Apply support after motion/wall resolution. The caller captures previous
/// grounded state and clears its current grounded flag before this phase.
/// A successful support preserves horizontal velocity/acceleration, sets their
/// Y components to zero and emits a landing only on an ungrounded-to-grounded step.
/// </summary>
public static SupportResult Resolve(SupportBody body, bool wasGrounded,
SupportSegmentQuery query, bool geometryEnabled = true)
{
ArgumentNullException.ThrowIfNull(query);
RequireFinite(body.Position); RequireFinite(body.PreviousPosition);
RequireFinite(body.Velocity); RequireFinite(body.Acceleration);
if (!float.IsFinite(body.Radius) || body.Radius <= 0 || !float.IsFinite(body.Factor))
throw new ArgumentOutOfRangeException(nameof(body), "Finite support factor and positive finite radius required");
var unchanged = new SupportResult(body, false, false, null, Vector3.Zero);
if (!geometryEnabled) return unchanged;
var product = body.Radius * body.Factor;
var top = MathF.Max(body.Position.Y, body.PreviousPosition.Y);
var motionHit = query(body.PreviousPosition, body.Position, false);
if (motionHit is { } crossed)
top += QuickMagnitude(body.Position - body.PreviousPosition)
- QuickMagnitude(crossed.Position - body.PreviousPosition);
// EXE48D920 is .1f, not .5f. Final root offset always uses r*factor.
var clearance = body.Factor == 1 || body.Factor < 0.1f ? body.Radius : product;
var start = new Vector3(body.Position.X, top + clearance, body.Position.Z);
var end = new Vector3(body.Position.X, body.Position.Y - 2 * body.Radius, body.Position.Z);
var hit = query(start, end, false);
if (hit is not { } floor) return unchanged;
var supportedY = floor.Position.Y + product;
// EXE47BAF3 queries iface208. It rejects a downward root correction,
// independently of vertical velocity, when this flag is enabled.
if (body.PreventLowering && body.Position.Y > supportedY) return unchanged;
var grounded = body with {
Position = new(body.Position.X, supportedY, body.Position.Z),
Velocity = new(body.Velocity.X, 0, body.Velocity.Z),
Acceleration = new(body.Acceleration.X, 0, body.Acceleration.Z)
};
return new SupportResult(grounded, true, !wasGrounded, floor, new Vector3(0, supportedY, 0));
}
/// <summary>
/// EXE469B70/47C6E0 source-winding segment query. Null-material polygons must
/// be included. The caller supplies the statically registered polygons;
/// checkpoint/material and game-specific registration filters are separate.
/// A linear scan replaces the original 260x260 broad phase. Equal-distance
/// selection follows input order, which can differ from original grid order.
/// </summary>
public static SupportHit? Trace(IEnumerable<SupportTriangle> triangles,
Vector3 start, Vector3 end, bool twoSided = false)
{
ArgumentNullException.ThrowIfNull(triangles);
RequireFinite(start); RequireFinite(end);
var direction = end - start;
var length = QuickMagnitude(direction);
if (length == 0) return null;
direction /= length;
SupportHit? nearest = null;
var nearestDistance = length;
foreach (var triangle in triangles)
{
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
var edge1 = triangle.B - triangle.A;
var edge2 = triangle.C - triangle.A;
var p = Cross(direction, edge2);
var determinant = Dot(edge1, p);
// Source indices use the opposite sign from a conventional right-
// handed visible-front-face test. Preserve the actual serialized order.
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
continue;
var inverse = 1 / determinant;
var relative = start - triangle.A;
var u = Dot(relative, p) * inverse;
if (u < 0 || u > 1) continue;
var q = Cross(relative, edge1);
var v = Dot(q, direction) * inverse;
if (v < 0 || u + v > 1) continue;
var distance = Dot(q, edge2) * inverse;
// Source accepts the beginning, but rejects its endpoint and equal
// distance candidates. No invented extra ray distance or skin is used.
if (distance < 0 || distance >= length) continue;
var position = start + direction * distance;
var fromStart = QuickMagnitude(position - start);
if (fromStart >= nearestDistance) continue;
nearestDistance = fromStart;
nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart);
}
return nearest;
}
private static float Dot(Vector3 a, Vector3 b) =>
(float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z);
private static Vector3 Cross(Vector3 a, Vector3 b) => new(
(float)((double)a.Y * b.Z - (double)a.Z * b.Y),
(float)((double)a.Z * b.X - (double)a.X * b.Z),
(float)((double)a.X * b.Y - (double)a.Y * b.X));
private static float[] BuildSine()
{
var table = new float[16384];
// DLL100EDC21 uses this stored double, rather than Math.Tau/16384.
for (var i = 0; i < table.Length; i++) table[i] = (float)Math.Sin(i * 0.0003834951969604492);
table[0] = table[8192] = 0; table[4096] = 1; table[12288] = -1;
return table;
}
private static ushort[] BuildHalfAcos()
{
var table = new ushort[16384];
// DLL100EDC8C..100EDCB4 truncates half of the acos angular-unit result.
for (var i = 0; i < table.Length; i++)
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1) * 2607.5945876921437 * 0.5);
return table;
}
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");
}
}
+45
View File
@@ -0,0 +1,45 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Recovered source wall-grid selection and root-support phase, with the port's
/// provisional swept-sphere wall response. This is not the full original solver.
/// The caller supplies body radius/factor from the actual actor class.
/// </summary>
public sealed class OriginalScenePhysics
{
private readonly SceneCollision walls;
private readonly SupportTriangle[] support;
public OriginalScenePhysics(Mesh world)
{
if (world.CollisionPolygons.Length != world.Indices.Length / 3)
throw new InvalidDataException("Prepare source collision polygon metadata before original root support");
walls = new SceneCollision(world, wallsAndCeilingsOnly: true);
support = Enumerable.Range(0, world.Indices.Length / 3)
.Where(i => !Checkpoint(world.CollisionPolygons[i].MaterialName))
.Select(i => new SupportTriangle(world.Vertices[world.Indices[i * 3]].Position,
world.Vertices[world.Indices[i * 3 + 1]].Position, world.Vertices[world.Indices[i * 3 + 2]].Position,
world.CollisionPolygons[i].ShapeId, world.CollisionPolygons[i].PolygonIndex)).ToArray();
}
public SupportResult Step(Vector3 position, Vector3 velocity, float radius, float factor, bool wasGrounded, float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
var previous = position;
velocity += RecoveredMotion.Gravity * dt;
// A capsule with height=diameter is a sphere. Floor polygons are handled
// by the separate original support query, not by this wall response.
var moved = walls.Move(position - Vector3.UnitY * radius, velocity * dt, radius, radius * 2);
position = moved.Position + Vector3.UnitY * radius;
if (moved.HitCeiling && velocity.Y > 0) velocity.Y = 0;
return OriginalBodySupport.Resolve(new(position, previous, velocity, Vector3.Zero, radius, factor),
wasGrounded, (start, end, twoSided) => OriginalBodySupport.Trace(support, start, end, twoSided));
}
private static bool Checkpoint(string? name) => name != null
&& (name.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| name.Length == 7 && name.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && name[6] is >= '1' and <= '9');
}
+46
View File
@@ -0,0 +1,46 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>EXE404523..404D1E keyboard and pointer selection for PracticeYesNo.</summary>
public sealed class PracticePrompt
{
public bool Active { get; private set; }
public int Mode { get; private set; }
public event Action<int, bool>? Chosen;
public void Show(int mode)
{
if (mode is < 0 or > 3) throw new NotSupportedException("Practice mode is outside recovered VR04..VR01 mapping");
if (Active) return;
Mode = mode; Active = true;
}
public void Key(uint scancode, Vector2 pointer)
{
if (!Active) return;
if (scancode == 28) Choose(true); // Y.
else if (scancode == 17) Choose(false); // N.
else if (scancode is 40 or 88) Choose(Yes(pointer)); // Enter / keypad Enter.
}
public void Click(Vector2 pointer)
{
if (!Active) return;
if (Yes(pointer)) Choose(true);
else if (pointer.X > 315 && pointer.X < 395 && pointer.Y > 240 && pointer.Y < 300) Choose(false);
}
public static string Destination(int mode) => mode switch
{
0 => "VR04.gam", 1 => "VR03.gam", 2 => "VR02.gam", 3 => "VR01.gam",
_ => throw new NotSupportedException("Unrecovered practice destination")
};
private void Choose(bool accepted)
{
Active = false;
Chosen?.Invoke(Mode, accepted);
}
private static bool Yes(Vector2 p) => p.X > 225 && p.X < 305 && p.Y > 240 && p.Y < 300;
}
+9 -1
View File
@@ -25,14 +25,22 @@ public sealed class SceneCollision
public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface); public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface);
} }
public SceneCollision(Mesh mesh) public SceneCollision(Mesh mesh, bool wallsAndCeilingsOnly = false)
{ {
if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh)); if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh));
if (wallsAndCeilingsOnly && mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original wall grid requires prepared source polygon normals");
var result = new List<Triangle>(); var result = new List<Triangle>();
// Render visibility is not a proven collision mask. Original null-material // Render visibility is not a proven collision mask. Original null-material
// proxies remain present and block movement in this provisional policy. // proxies remain present and block movement in this provisional policy.
for (var i = 0; i < mesh.Indices.Length; i += 3) for (var i = 0; i < mesh.Indices.Length; i += 3)
{ {
// EXE4798B3 registers only stored normal.Y<.7 in the wall/ceiling
// grid. Render normals and a recomputed cross product differ.
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].Normal.Y >= .7f) continue;
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].MaterialName is { } material
&& (material.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && material[6] is >= '1' and <= '9')) continue;
if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length
|| mesh.Indices[i + 2] >= mesh.Vertices.Length) || mesh.Indices[i + 2] >= mesh.Vertices.Length)
throw new ArgumentException("Collision index outside vertex table", nameof(mesh)); throw new ArgumentException("Collision index outside vertex table", nameof(mesh));
+527
View File
@@ -0,0 +1,527 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Mutable source-entity state for the reconstructed trigger/camera interpreter.</summary>
public sealed class DirectorActor
{
public GamEntity? SourceGam { get; }
public string Tag { get; }
public string Kind { get; }
public bool ConstructorCreated => SourceGam is null;
public Vector3 Position { get; internal set; }
public Vector3 Rotation { get; internal set; }
public bool Visible { get; internal set; }
public bool Active { get; internal set; }
public string Animation { get; internal set; } = "STOP";
public int AIstate { get; internal set; }
public float Speed { get; internal set; }
public string? Patrol { get; internal set; }
public int SpriteRevision { get; internal set; }
public bool SpritePlaying { get; internal set; }
internal DirectorActor(GamEntity? source, string tag, string kind, Vector3 position)
{
SourceGam = source; Tag = tag; Kind = kind; Position = position;
Rotation = source?.Rotation ?? Vector3.Zero;
Visible = source?.Integer("InitiallyVisible", -1) != 0;
Active = source?.Integer("InitallyActive", source?.Integer("Activated", 1) ?? 1) != 0;
if (kind == "3PIC") Visible = Active;
AIstate = source?.Integer("AIState", kind == "3DOG" ? 4 : 0) ?? (kind == "3DOG" ? 4 : 0);
Speed = kind switch { "3CAR" => 200, "3DOG" => 1, _ => 0 }; // EXE413BCB /41C8FA.
if (kind == "3DOG") Animation = "none"; // Initial pose selection is not recovered; no fabricated STOP alias.
Patrol = source?.Text("PatrolPoint");
SpritePlaying = (source?.Integer("Activated") ?? 0) != 0;
}
}
public sealed record DirectorIssue(string Tag, string Kind, string Detail);
/// <summary>
/// Recovered synchronous AI-trigger dispatch and audio-duration-driven CAM/MCA
/// sequence. See lab-progression.md. Actor physics/AI, sprites, inventory effects
/// and fades remain separate consumers; unsupported execution is reported.
/// </summary>
public sealed class SceneDirector
{
private readonly GamLevel level;
private readonly TaskStates tasks;
private readonly Func<string, int, double> soundDuration;
private readonly Dictionary<string, GamEntity> entities = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DirectorActor> actors = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<int, int> activations = [];
private readonly Queue<(string Tag, string? Caller)> pending = [];
private readonly List<DirectorIssue> issues = [];
private readonly HashSet<string> reported = new(StringComparer.Ordinal);
private readonly HashSet<string> patrolConsumers = new(StringComparer.OrdinalIgnoreCase);
private Shot? shot;
private bool draining, skipping;
private string? blockedNext, blockedCaller;
private sealed class Shot(GamEntity source, int index, DirectorActor target, double duration)
{
public GamEntity Source { get; } = source;
public int Index { get; } = index; // -1 for a single CAM.
public DirectorActor Target { get; } = target;
public double Duration { get; } = duration;
public double Elapsed { get; set; }
}
public List<DirectorActor> Actors { get; } = [];
public IReadOnlyList<DirectorIssue> Issues => issues;
public bool Controlled => Equal(ControlledTag, level.Player?.Tag);
public string? ControlledTag { get; private set; }
public bool InventoryEnabled { get; private set; } = true;
public bool Blocked { get; private set; }
public bool Playing => shot is not null;
public string? CurrentTag => shot?.Source.Tag;
public int CurrentShot => shot?.Index ?? -1;
public Vector3? CameraEye { get; private set; }
public Vector3? CameraTarget { get; private set; }
public event Action<string, int>? Speech;
public event Action<DirectorActor>? ActorChanged;
public event Action<string, string>? Unsupported;
public SceneDirector(GamLevel level, TaskStates tasks, Func<string, int, double> soundDuration)
{
this.level = level;
this.tasks = tasks;
this.soundDuration = soundDuration;
foreach (var entity in level.Entities)
{
if (entity.Tag is not { Length: > 0 } tag) continue;
// Original tag lookup scans in object-list order and returns the first.
entities.TryAdd(tag, entity);
var actor = new DirectorActor(entity, tag, entity.Kind, entity.Position);
Actors.Add(actor);
actors.TryAdd(tag, actor);
}
// Jimmy creates Goddard in EXE423C98->41C810, independently of GAM.
// LV1B's explicit SITGODDARD command positions him at gstart before his
// first shot. This initial binding is a documented placement inference.
if (!actors.ContainsKey("C3DGODDARD") && entities.TryGetValue("gstart", out var goddardStart))
{
var goddard = new DirectorActor(null, "C3DGODDARD", "3DOG", goddardStart.Position);
Actors.Add(goddard);
actors.Add(goddard.Tag, goddard);
}
ControlledTag = level.Player?.Tag;
foreach (var actor in Actors) ApplyTask(actor, tasks.Get(actor.SourceGam?.Text("TaskName")));
tasks.Assigned += OnTaskAssigned;
}
public void Begin(GamEntity start)
{
if (start.Kind != "STRT") throw new ArgumentException("Expected original STRT entity", nameof(start));
shot = null; pending.Clear(); activations.Clear();
Blocked = skipping = false; blockedNext = blockedCaller = null;
CameraEye = CameraTarget = null;
InventoryEnabled = true;
foreach (var actor in Actors)
{
if (actor.SourceGam is not { } source) continue;
var initial = new DirectorActor(source, actor.Tag, actor.Kind, source.Position);
actor.Position = initial.Position; actor.Rotation = initial.Rotation;
actor.Visible = initial.Visible; actor.Active = initial.Active;
actor.Animation = initial.Animation; actor.AIstate = initial.AIstate;
actor.Speed = initial.Speed; actor.Patrol = initial.Patrol;
actor.SpritePlaying = initial.SpritePlaying; actor.SpriteRevision++;
ApplyTask(actor, tasks.Get(source.Text("TaskName")));
}
var trigger = start.Text("StartTrigger");
ControlledTag = IsNone(trigger) ? level.Player?.Tag : null; // EXE4426B7.
if (!IsNone(trigger)) Trigger(trigger!, start.Tag);
}
public void Trigger(string tag, string? callerTag = null)
{
if (tag.Length > 100) throw new ArgumentException("Trigger tag exceeds original field size", nameof(tag));
pending.Enqueue((tag, callerTag));
Drain();
}
/// <summary>
/// Port contact query: point against the source trigger radius. Original
/// collision callback selection/radius combination is not yet reproduced.
/// The actual AI trigger's actor, animation and task-child checks are retained.
/// </summary>
public void Touch(string activatorTag, Vector3 position)
{
if (!Finite(position)) throw new ArgumentOutOfRangeException(nameof(position));
foreach (var entity in level.Entities)
{
if (entity.Kind != "3AIT" || entity.Integer("TouchActivated") == 0) continue;
var radius = entity.Number("Radius");
if (radius < 0 || Vector3.DistanceSquared(position, entity.Position) > radius * radius) continue;
if (entity.Tag is { } tag) pending.Enqueue((tag, activatorTag));
}
Drain();
}
public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag);
public void RegisterPatrolConsumer(string tag) => patrolConsumers.Add(tag);
public void SyncActor(string tag, Vector3 position, Vector3 rotation)
{
if (!Finite(position) || !Finite(rotation)) throw new ArgumentOutOfRangeException(nameof(position));
if (!actors.TryGetValue(tag, out var actor)) return;
actor.Position = position; actor.Rotation = rotation;
if (shot is not null) UpdateCamera(shot);
}
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
foreach (var actor in Actors)
if (actor.Kind == "3TRO") actor.Rotation = actor.Rotation with { Y = (actor.Rotation.Y + dt * 90) % 360 };
var remaining = (double)dt;
for (var count = 0; count < 256 && shot is not null; count++)
{
var current = shot;
var untilEnd = Math.Max(0, current.Duration - current.Elapsed);
var consumed = Math.Min(remaining, untilEnd);
current.Elapsed += consumed;
remaining -= consumed;
UpdateCamera(current);
if (current.Elapsed + 1e-8 < current.Duration) return;
FinishShot(current);
if (remaining <= 0 && (shot is null || shot.Duration > 0)) return;
}
if (shot is not null && shot.Duration <= 0)
Block(shot.Source, "Zero-duration scene sequence exceeded bounded dispatch", shot.Source.Text("NextTrigger"));
}
/// <summary>Escape/Space original chain skip: preserve AI/toggle actions and skip remaining speech/shots.</summary>
public void Skip()
{
skipping = true;
if (Blocked)
{
Blocked = false;
if (blockedNext is { } next) pending.Enqueue((next, blockedCaller));
blockedNext = blockedCaller = null;
}
if (shot is { } current)
{
shot = null;
DeactivateAnimation(current);
if (current.Index >= 0) FinishMulti(current.Source);
else EnqueueNext(current.Source);
}
Drain();
}
private void Drain()
{
if (draining || Blocked) return;
draining = true;
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
for (var count = 0; pending.Count > 0 && !Blocked; count++)
{
var (tag, caller) = pending.Dequeue();
if (IsNone(tag)) continue;
if (Equal(tag, "default")) { RestoreControl(); continue; }
if (count >= 256 || !visited.Add(tag))
{
Report(tag, "cycle", "Synchronous trigger cycle or dispatch limit");
pending.Clear(); Blocked = true; return;
}
if (!entities.TryGetValue(tag, out var entity))
{
Report(tag, "missing", "Trigger target absent from original GAM");
Blocked = true; return;
}
switch (entity.Kind)
{
case "3AIT": ExecuteAi(entity, caller); break;
case "3CAM": StartCamera(entity, -1); break;
case "3MCA": StartMulti(entity); break;
default: Block(entity, "Trigger class execution not recovered", entity.Text("NextTrigger")); break;
}
}
}
finally { draining = false; }
}
private void ExecuteAi(GamEntity entity, string? caller)
{
var by = entity.Text("ActivateBy");
var isA = entity.Text("IsA");
var matchesActor = !IsNone(by) && Equal(by, caller);
if (!IsNone(isA))
{
Report(entity.Tag!, entity.Kind, "IsA predicate requires original class hierarchy; trigger not executed");
return;
}
if (!IsNone(by) && !matchesActor) return;
var byAnimation = entity.Text("ActivateByAnim");
if (!IsNone(byAnimation) && (!actors.TryGetValue(caller ?? "", out var callerActor)
|| !Equal(byAnimation, callerActor.Animation))) return;
var times = entity.Integer("TimesToTrigger", -1);
var number = activations.GetValueOrDefault(entity.Offset) + 1;
activations[entity.Offset] = number;
if (times != -1 && number > times) return;
SetControl(entity);
var targetTag = entity.Text("AITarget");
if (!IsNone(targetTag))
{
if (!actors.TryGetValue(targetTag!, out var target))
Report(entity.Tag!, entity.Kind, $"AI target {targetTag} absent");
else
{
var hide = entity.Integer("AIHideObj", -1);
if (hide != -1) target.Visible = hide == 0;
var positionTag = entity.Text("AINewPos");
if (!IsNone(positionTag))
{
if (actors.TryGetValue(positionTag!, out var marker)) target.Position = marker.Position;
else Report(entity.Tag!, entity.Kind, $"AINewPos {positionTag} absent");
}
var animation = entity.Text("AIAnim");
if (!IsNone(animation)) target.Animation = animation!;
target.AIstate = entity.Integer("AIState", target.AIstate);
var speed = entity.Integer("AISpeed", -1);
if (speed != -1) target.Speed = speed;
var patrol = entity.Text("AIPatrol");
if (!IsNone(patrol)) target.Patrol = patrol;
var yaw = entity.Number("AINewRotY", -1);
if (yaw != -1) target.Rotation = target.Rotation with { Y = yaw };
ActorChanged?.Invoke(target);
if (target.AIstate == 3 && (target.Kind is "3DOG" or "3CAR") && !patrolConsumers.Contains(target.Tag))
Report(target.Tag, target.Kind, "Patrol motion/arrival is not yet reconstructed; actor-state callback emitted");
}
}
Toggle(entity);
var conditional = ConditionalChild(entity);
// EXE40CB43: the nearby teleport explanation advances the task before its camera chain.
if (Equal(entity.Tag, "teleportexplanation") && tasks.Get("SCENE") is 30 or 31)
tasks.SetExisting("SCENE", 35);
pending.Enqueue((conditional ?? entity.Text("NextTrigger") ?? "none", entity.Tag));
}
private string? ConditionalChild(GamEntity entity)
{
var state = tasks.Get(entity.Text("TaskName"));
for (var i = 0; i < 5; i++)
{
var desired = entity.Integer($"ActivateState{i}", -1);
var target = entity.Text($"ActivateObject{i}");
if (desired != -1 && desired == state && !IsNone(target) && entities.ContainsKey(target!)) return target;
}
return null;
}
private void StartMulti(GamEntity entity)
{
SetControl(entity);
Toggle(entity);
if (skipping) { FinishMulti(entity); return; }
StartCamera(entity, 0, applyCommon: false);
}
private void StartCamera(GamEntity entity, int index, bool applyCommon = true)
{
if (applyCommon) { SetControl(entity); Toggle(entity); }
if (entity.Integer("DeactivateInv") != 0) InventoryEnabled = false;
if (skipping)
{
if (index >= 0) FinishMulti(entity);
else EnqueueNext(entity);
return;
}
var suffix = index < 0 ? "" : index.ToString(System.Globalization.CultureInfo.InvariantCulture);
var targetTag = entity.Text("CameraTarget" + suffix);
var sound = entity.Integer("SoundIndex" + suffix, -1);
if (index >= 8 || IsNone(targetTag) || sound == -1)
{
if (index >= 0) FinishMulti(entity);
else Block(entity, "CAM target/sound unavailable", entity.Text("NextTrigger"));
return;
}
if (!actors.TryGetValue(targetTag!, out var target))
{
Block(entity, $"Camera target {targetTag} absent", entity.Text("NextTrigger"));
return;
}
var database = entity.Text("SoundDatabase") ?? "none";
var duration = soundDuration(database, sound);
if (!double.IsFinite(duration) || duration < 0)
{
Block(entity, $"Missing original sound duration {database}:{sound}", entity.Text("NextTrigger"));
return;
}
var animation = entity.Text(index < 0 ? "TargetActAnim" : "TargetAnim" + suffix);
if (!IsNone(animation)) { target.Animation = animation!; ActorChanged?.Invoke(target); }
shot = new Shot(entity, index, target, duration);
UpdateCamera(shot);
Speech?.Invoke(database, sound);
}
private void FinishShot(Shot current)
{
if (shot != current) return;
shot = null;
DeactivateAnimation(current);
if (current.Index < 0) EnqueueNext(current.Source);
else StartCamera(current.Source, current.Index + 1, applyCommon: false);
Drain();
}
private void DeactivateAnimation(Shot current)
{
var animation = current.Source.Text("TargetDeactAnim");
if (!IsNone(animation))
{
current.Target.Animation = animation!;
ActorChanged?.Invoke(current.Target);
}
}
private void FinishMulti(GamEntity entity)
{
// MCA finisher4311F0 preserves 'none'/NULL semantics for PlayerControlled.
SetControl(entity);
EnqueueNext(entity);
}
private void EnqueueNext(GamEntity entity)
{
pending.Enqueue((entity.Text("NextTrigger") ?? "none", entity.Tag));
}
private void UpdateCamera(Shot current)
{
var source = current.Source;
var target = current.Target;
var t = (float)current.Elapsed;
if (current.Index >= 0)
{
var suffix = current.Index.ToString(System.Globalization.CultureInfo.InvariantCulture);
var type = source.Integer("CameraType" + suffix);
var local = type switch
{
1 => new Vector3(0, 140, MathF.Max(100, 300 - 15 * t)),
2 => new Vector3(0, 240, MathF.Max(100, 500 - 35 * t)),
3 => new Vector3(200, 240, MathF.Max(100, 700 - 55 * t)),
4 => new Vector3(-200, 190, MathF.Max(100, 700 - 55 * t)),
_ => new Vector3(0, 40, 200),
};
CameraEye = TransformLocal(target, local);
CameraTarget = target.Position + Vector3.UnitY * (source.Number("LookatVOffset" + suffix, 100) - 60);
return;
}
if (source.Integer("CameraType") == 2)
{
CameraEye = source.Position;
CameraTarget = target.Position;
return;
}
var minimum = source.Number("MinDist", 100);
var maximum = source.Number("MaxDist", 1000);
var distance = Math.Clamp(source.Number("InitialDist", 200) - source.Number("ZoomSpeed") * t,
MathF.Min(minimum, maximum), MathF.Max(minimum, maximum));
var offset = new Vector3(source.Number("TargOffsetX"), source.Number("TargOffsetY"), source.Number("TargOffsetZ"));
if (source.Integer("ViewFromCamera") == 0)
{
CameraEye = TransformLocal(target, offset with { Z = distance });
CameraTarget = target.Position + Vector3.UnitY * source.Number("LookVoffset");
}
else
{
var point = TransformLocal(target, offset);
var direction = source.Position - point;
if (direction.LengthSquared() < .000001f)
{
Report(source.Tag!, source.Kind, "CAM eye coincides with target offset; original normalization undefined");
CameraEye = source.Position;
}
else CameraEye = point + Vector3.Normalize(direction) * distance;
CameraTarget = point;
}
}
private static Vector3 TransformLocal(DirectorActor target, Vector3 point)
{
// Original OMT Euler local-to-world routine472980; quantized modern
// sin/cos here retains the source angular grid, not x87 bit identity.
var (sx, cx) = LabSimulation.Trig(target.Rotation.X);
var (sy, cy) = LabSimulation.Trig(target.Rotation.Y);
var (sz, cz) = LabSimulation.Trig(target.Rotation.Z);
var x = point.X * cz - point.Y * sz;
var y = point.X * sz + point.Y * cz;
var z = point.Z;
var pitchedY = y * cx - z * sx;
var pitchedZ = y * sx + z * cx;
return target.Position + new Vector3(x * cy - pitchedZ * sy, pitchedY, x * sy + pitchedZ * cy);
}
private void SetControl(GamEntity entity)
{
var control = entity.Text("PlayerControlled");
if (IsNone(control)) return;
if (Equal(control, "NULL")) ControlledTag = null;
else if (actors.ContainsKey(control!)) ControlledTag = control;
else Report(entity.Tag!, entity.Kind, $"PlayerControlled target {control} absent");
}
private void Toggle(GamEntity entity)
{
var tag = entity.Text("ToggleObject");
var toggle = entity.Integer("Toggle", -1);
if (toggle is not (0 or 1) || IsNone(tag)) return;
if (!actors.TryGetValue(tag!, out var actor)) { Report(entity.Tag!, entity.Kind, $"ToggleObject {tag} absent"); return; }
actor.Visible = actor.Active = toggle == 1;
if (actor.Kind == "3ANI") { actor.SpritePlaying = toggle == 1; actor.SpriteRevision++; }
ActorChanged?.Invoke(actor);
}
private void RestoreControl()
{
shot = null;
ControlledTag = level.Player?.Tag;
InventoryEnabled = true;
CameraEye = CameraTarget = null;
skipping = false;
// Original DEFAULT invokes a Jimmy help/inventory callback at SCENE30;
// it does not assign a new task value or complete the lab.
}
private void OnTaskAssigned(string name, int state)
{
foreach (var actor in Actors)
if (Equal(actor.SourceGam?.Text("TaskName"), name)) ApplyTask(actor, state);
}
private void ApplyTask(DirectorActor actor, int state)
{
if (actor.SourceGam is not { } source) return;
// LOAD.RequiredLevel belongs to its RequiredTask contact gate, not the
// animated actor's TaskName activation contract. Applying the latter
// here disables the lab exit even when SCENE reaches60.
if (source.Kind == "LOAD") return;
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); }
}
private void Block(GamEntity source, string detail, string? next)
{
shot = null; Blocked = true;
blockedNext = next; blockedCaller = source.Tag;
Report(source.Tag ?? "?", source.Kind, detail);
}
private void Report(string tag, string kind, string detail)
{
if (!reported.Add(tag + "\0" + kind + "\0" + detail)) return;
issues.Add(new DirectorIssue(tag, kind, detail));
Unsupported?.Invoke(tag, kind);
}
private static bool Equal(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool IsNone(string? value) => string.IsNullOrEmpty(value) || Equal(value, "none");
private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
}
+240
View File
@@ -0,0 +1,240 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType);
/// <summary>
/// Recovered star/trophy/lab jetpack contacts, Carl talk dispatch and LOAD gates. Uses source root spheres
/// with recovered lookup magnitude (x87 table identity/exclusions/box contacts pending).
/// Other pickup effects and general AI sensing remain explicit unsupported cases.
/// </summary>
public sealed class SceneInteractions
{
private readonly SceneDirector director;
private readonly TaskStates tasks;
private readonly OriginalSave initial;
private readonly string levelCode;
private readonly int[] itemStates;
private readonly HashSet<int> contacts = [];
private readonly HashSet<string> unsupported = [];
public int Score { get; private set; }
public float Energy { get; private set; }
public int CurrentObjective { get; private set; }
public string ReturnLevel { get; private set; }
public string ReturnStart { get; private set; }
public SceneInventory Inventory { get; }
public IReadOnlyCollection<string> Unsupported => unsupported;
public event Action<GamEntity, int>? Collected;
public event Action<LevelTransition>? Transition;
public event Action<int>? SoundEffect;
public event Action<int>? PracticeRequested;
public event Action<Vector3>? CheckpointCaptured;
public event Action<DirectorActor, string>? ConversationStarted;
public event Action<int>? ObjectiveChanged;
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save, string? levelCode = null)
{
this.director = director; this.tasks = tasks; initial = save;
this.levelCode = levelCode ?? save.LevelCode;
Inventory = new SceneInventory(save.InventoryStates);
itemStates = save.ItemStates.ToArray(); Score = save.Score;
Energy = save.PlayerValue;
CurrentObjective = save.OtherCounter;
ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart;
tasks.Assigned += OnTaskAssigned;
Reset();
}
public void UpdateEnergy(float energy)
{
if (!float.IsFinite(energy)) throw new ArgumentOutOfRangeException(nameof(energy));
Energy = energy;
}
public OriginalSave Snapshot() => initial with { Score = Score, PlayerValue = Energy, ItemStates = itemStates.ToArray(),
InventoryStates = Inventory.Snapshot(), Tasks = tasks.Snapshot(), OtherCounter = CurrentObjective,
ReturnLevel = ReturnLevel, ReturnStart = ReturnStart };
public void SetReturnContext(string levelFile, string start)
{
if (levelFile.Length > 100 || start.Length > 100 || !levelFile.EndsWith(".gam", StringComparison.OrdinalIgnoreCase)
|| levelFile.Contains('/') || levelFile.Contains('\\')) throw new ArgumentException("Invalid original return level/start");
ReturnLevel = levelFile; ReturnStart = start;
}
/// <summary>Call after SceneDirector.Begin, including a scene reset.</summary>
public void Reset()
{
contacts.Clear();
HideCollected();
ApplyCarlTask();
}
public void HideCollected()
{
foreach (var actor in director.Actors)
if (actor.SourceGam is { Kind: "3PIC" } source && source.Integer("PickupIndex", -1) is var id
&& id > 0 && id < itemStates.Length && itemStates[id] != 0) actor.Active = actor.Visible = false;
}
public void Update(Vector3 activePlayerRoot, float playerRadius = 60)
{
if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z)
|| !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot));
if (!director.Controlled) return;
HideCollected();
foreach (var actor in director.Actors)
{
if (!director.Controlled) break;
if (actor.SourceGam is not { } source || source.Kind is not ("3PIC" or "3TRO" or "LOAD" or "3CAR")) continue;
// C3DFriend update41B972..988 calls the talk dispatcher every update
// in state0, even when a prior contact found no matching TalkTrigger.
if (source.Kind == "3CAR" && actor.Active && actor.AIstate == 0)
{
TryBeginCarlTalk(actor, source);
if (!director.Controlled) break;
}
// Carl InitObject413E2F..45 sets radius100 and support factor0.75.
var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius"));
var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
if (!overlaps) { contacts.Remove(source.Offset); continue; }
if (!contacts.Add(source.Offset)) continue;
switch (source.Kind)
{
case "3PIC": CollectPickup(actor, source, activePlayerRoot); break;
case "3CAR":
//40A44C..45C/40A676..68D: target contact in state6 sets0.
var player = director.Actors.FirstOrDefault(a => a.Kind == "3JIM");
if (actor.AIstate == 6 && Equal(source.Text("TargetName"), player?.Tag))
{
actor.AIstate = 0;
TryBeginCarlTalk(actor, source);
}
break;
case "3TRO":
Score = Math.Max(0, unchecked(Score + 300));
actor.Active = actor.Visible = false;
SoundEffect?.Invoke(230);
Collected?.Invoke(source, 300);
break;
case "LOAD":
if (!TaskActivation.Load(source, tasks)) break;
var destination = source.Text("LevelName") ?? "none";
var start = source.Text("StartPoint") ?? "none";
if (string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase))
{ destination = ReturnLevel; start = ReturnStart; }
if (string.Equals(destination, "none", StringComparison.OrdinalIgnoreCase))
{ unsupported.Add("RETURN has no stored destination"); break; }
Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType")));
break;
}
}
}
private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot)
{
var id = source.Integer("PickupIndex", -1);
// The source tag is SHRINKRAY; original objective art120 calls this
// pickup the jet pack, matching group0/item3 and powered-jump ownership.
var jetpack = Equal(source.Tag, "SHRINKRAY");
var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5;
if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50)
|| source.Integer("PIC_NUMBER", -1) != -1
|| source.Integer("PickedUpIndex", -1) != -1 || source.Integer("RequiredPicNum", -1) != -1)
{ unsupported.Add($"Pickup {source.Tag}@0x{source.Offset:X}: inventory/special effect not reconstructed"); return; }
if (itemStates[id] != 0) return;
itemStates[id] = 1; // EXE435E11..31: ordinary acquired state, hide and disable.
actor.Active = actor.Visible = false;
//435FCB invokes the special hook before the positive PointValue award.
if (jetpack && tasks.Get("SCENE") == 35)
{
//436603..67E: Jimmy checkpoint capture42AF00, task35->50, group0
//item3 state1, practice prompt0, then gadget selection3. The checkpoint
//event does not assign the still-unidentified TSK StoredVector.
CheckpointCaptured?.Invoke(playerRoot);
tasks.SetExisting("SCENE", 50);
Inventory.SetState(0, 3, 1);
PracticeRequested?.Invoke(0);
Inventory.SelectGadget(3);
}
var points = source.Integer("PointValue");
Score = Math.Max(0, unchecked(Score + points));
var sound = source.Integer("SoundIndex", -1);
if (sound >= 0) SoundEffect?.Invoke(sound);
Collected?.Invoke(source, points);
var next = source.Text("NextTrigger");
if (!string.IsNullOrEmpty(next) && !string.Equals(next, "none", StringComparison.OrdinalIgnoreCase))
director.Trigger(next, source.Tag);
}
private void TryBeginCarlTalk(DirectorActor actor, GamEntity source)
{
var state = tasks.Get(source.Text("TaskName"));
for (var i = 0; i < 5; i++)
{
var tag = source.Text("TalkTrigger" + i);
var required = source.Integer("TalkState" + i, -1);
if (required == -1 || required != state && required != -2 || string.IsNullOrEmpty(tag)
|| Equal(tag, "none") || director.FindActor(tag) is null) continue;
//41B7B0 calls derived slot180 BEFORE dispatching the selected object.
//Carl413E50 calls base41B810 (+100) then changes SCENE milestones.
Score = Math.Max(0, unchecked(Score + 100));
var scene = tasks.Get("SCENE");
var next = scene switch { 50 => 60, 65 => 70, 270 => 280, _ => scene };
if (next != scene) tasks.SetExisting("SCENE", next);
director.Trigger(tag, tag); //Original target receives itself as caller.
actor.AIstate = 9;
ConversationStarted?.Invoke(actor, tag);
return;
}
}
private void OnTaskAssigned(string name, int value)
{
HideCollected();
if (Equal(name, "SCENE"))
{
//45F990 jump tables ->406F50: clear the transient objective flags,
//select this objective and set its flag1; TSK writes selector4F8194.
var objective = ObjectiveForScene(value);
if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); }
ApplyCarlTask();
}
}
private void ApplyCarlTask()
{
//Carl's override413F30 follows generic activation; LV1B branch414068.
//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
&& string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
public static int ObjectiveForScene(int scene) => scene switch
{
35 => 1, 50 => 2, 60 => 3, 70 => 4, 90 => 5, 100 => 6, 108 => 7,
140 or 141 => 8, 160 => 9, 162 => 10, 168 => 11, 178 => 12,
200 => 13, 205 => 14, 210 => 15, 220 => 16, 230 => 17,
250 => 18, 260 => 19, 270 => 20, 280 => 21, 290 => 22,
300 => 23, 310 => 24, 320 => 25, 330 => 26, 340 => 27,
350 => 28, 360 => 29, 380 => 30, 390 => 31, 400 => 32,
410 => 33, 420 => 34, 430 => 35, 460 => 36, 470 => 37,
480 => 38, 500 => 39, 510 => 40, 520 => 41, 540 => 42, 550 => 43,
_ => 0,
};
}
+43
View File
@@ -0,0 +1,43 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// The two inventory-state groups serialized by the original TSK writer.
/// Preserves unknown existing values; this is not a complete inventory UI or
/// implementation of the separate 29-item consumable-count group.
/// </summary>
public sealed class SceneInventory
{
private readonly int[] states;
public int SelectedGadget { get; private set; } = -1;
public event Action<int>? GadgetSelected;
public SceneInventory(IEnumerable<int> savedStates)
{
states = savedStates.ToArray();
if (states.Length != OriginalSave.InventoryCount)
throw new ArgumentException("Expected the original 19 inventory states", nameof(savedStates));
}
public int State(int group, int item) => states[Offset(group, item)];
public void SetState(int group, int item, int state) => states[Offset(group, item)] = state;
public void SelectGadget(int item)
{
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
throw new ArgumentOutOfRangeException(nameof(item), "Gadget is outside the recovered group or unavailable");
SelectedGadget = item;
GadgetSelected?.Invoke(item);
}
public int[] Snapshot() => states.ToArray();
private static int Offset(int group, int item) => group switch
{
0 when item is >= 0 and < 9 => item,
1 when item is >= 0 and < 10 => 9 + item,
_ => throw new ArgumentOutOfRangeException(nameof(item), "Only the two serialized inventory groups are recovered here"),
};
}
+176
View File
@@ -0,0 +1,176 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>
/// Recovered player-contact button and vertical-door state machines. Contact
/// broadphase uses the recovered lookup magnitude; moving-object collision and material pulses
/// are separate, still incomplete consumers. See analysis/buttons-doors.md.
/// </summary>
public sealed class SceneMechanisms
{
private sealed class Button(DirectorActor actor)
{
public DirectorActor Actor = actor;
public bool Available;
public bool Down;
public float Cooldown;
}
private sealed class Door(DirectorActor actor)
{
public DirectorActor Actor = actor;
public Vector3 Origin = actor.SourceGam!.Position;
public bool Closed;
public float Remaining;
public float OpenElapsed;
public bool Looping;
public float Duration = actor.SourceGam!.Number("DoorSpeed", 1);
public float OpenTime = actor.SourceGam!.Number("OpenTime", 3);
public float Amount = actor.SourceGam!.Number("OpenAmount", 500);
}
private readonly SceneDirector director;
private readonly List<Button> buttons;
private readonly List<Door> doors;
private readonly HashSet<int> contacts = [];
private readonly HashSet<string> unsupported = [];
public IReadOnlyCollection<string> Unsupported => unsupported;
public event Action<DirectorActor, int, bool>? Sound; // Source bank index and loop flag.
public event Action<DirectorActor>? StopSound;
public SceneMechanisms(SceneDirector director)
{
this.director = director;
buttons = director.Actors.Where(a => a.Kind == "3BUT" && a.SourceGam != null).Select(a => new Button(a)).ToList();
doors = director.Actors.Where(a => a.Kind == "3DUD" && a.SourceGam != null).Select(a => new Door(a)).ToList();
foreach (var door in doors)
if (!float.IsFinite(door.Duration) || door.Duration <= 0 || !float.IsFinite(door.Amount)
|| !float.IsFinite(door.OpenTime)) throw new InvalidDataException("Invalid source door timing or displacement");
Reset();
}
public void Reset()
{
contacts.Clear();
foreach (var button in buttons) ResetButton(button);
foreach (var door in doors)
{
if (door.Looping) StopSound?.Invoke(door.Actor);
door.Closed = door.Actor.SourceGam!.Integer("ItemClosed", 1) != 0;
door.Remaining = door.OpenElapsed = 0;
door.Looping = false;
door.Actor.Position = door.Origin + (door.Closed ? Vector3.Zero : Vector3.UnitY * door.Amount);
}
}
/// <summary>Player contact-enter only; holding overlap never presses repeatedly.</summary>
public void Update(Vector3 root, float radius = 60)
{
if (!Finite(root) || !float.IsFinite(radius) || radius < 0) throw new ArgumentOutOfRangeException(nameof(root));
foreach (var button in buttons)
{
var source = button.Actor.SourceGam!;
// EXE411EF0 PostLoad sets current radius300 after InitObject.
var overlap = button.Actor.Active && OriginalBodySupport.QuickMagnitude(root - button.Actor.Position) < radius + 300;
if (!overlap) { contacts.Remove(source.Offset); continue; }
if (contacts.Add(source.Offset)) Press(button);
}
}
public bool Toggle(DirectorActor actor, int requested)
{
var door = doors.Find(d => ReferenceEquals(d.Actor, actor));
if (door == null) return false;
var current = door.Closed ? 1 : 0;
if (current == requested) return true;
door.Remaining = door.Remaining > 0 ? door.Duration - door.Remaining : door.Duration;
if (!door.Looping)
{
door.Looping = true;
Sound?.Invoke(actor, 59, true);
}
var next = actor.SourceGam!.Text("Next");
if (!string.IsNullOrEmpty(next) && !Equal(next, "none"))
{
var target = director.FindActor(next);
if (target?.Kind == "3AIT") director.Trigger(next, actor.Tag);
else unsupported.Add($"Door {actor.Tag}: chained target {next} class execution is unrecovered");
}
door.Closed = requested switch { 0 => false, 1 => true, _ => !door.Closed };
return true;
}
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
foreach (var button in buttons)
{
if (!button.Actor.Active || button.Cooldown <= 0) continue;
button.Cooldown -= dt;
if (button.Cooldown <= 0) ResetButton(button);
}
foreach (var door in doors)
{
if (!door.Actor.Active) continue;
if (door.Remaining > 0)
{
door.Remaining -= dt;
if (door.Remaining <= 0)
{
door.Remaining = 0;
door.Looping = false;
StopSound?.Invoke(door.Actor);
Sound?.Invoke(door.Actor, 58, false);
}
var fraction = door.Remaining / door.Duration;
if (!door.Closed) door.OpenElapsed = 0;
door.Actor.Position = door.Origin + Vector3.UnitY * door.Amount * (door.Closed ? fraction : 1 - fraction);
}
else if (!door.Closed)
{
door.OpenElapsed += dt;
if (door.OpenElapsed > door.OpenTime)
{
door.OpenElapsed = 0;
Toggle(door.Actor, 1);
}
}
}
}
private void Press(Button button)
{
if (!button.Available || button.Cooldown > 0) return;
if (!button.Down)
{
button.Cooldown = 4; // EXE411C35.
var sound = button.Actor.SourceGam!.Integer("AvailSound", -1);
if (sound != -1) Sound?.Invoke(button.Actor, sound, false);
}
button.Down = !button.Down;
button.Actor.Animation = button.Down ? "DOWN" : "UP";
var targetName = button.Actor.SourceGam!.Text("ActivateButton");
if (string.IsNullOrEmpty(targetName) || Equal(targetName, "none")) return;
var target = director.FindActor(targetName);
if (target == null) return; // Original missing-tag lookup quietly returns.
var toggle = button.Actor.SourceGam.Integer("Toggle", -1);
if (!Toggle(target, toggle) && target.Kind != "3BUT")
unsupported.Add($"Button {button.Actor.Tag}: target {targetName} toggle is unrecovered");
if (button.Down && target.Kind == "3BUT")
{
var linked = buttons.Find(b => ReferenceEquals(b.Actor, target))!;
linked.Available = true;
button.Available = false;
}
}
private static void ResetButton(Button button)
{
button.Available = button.Actor.SourceGam!.Integer("ButtonAvailable", 1) != 0;
button.Down = !button.Available;
button.Cooldown = 0;
button.Actor.Animation = button.Down ? "DOWN" : "UP";
}
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
}
+25
View File
@@ -0,0 +1,25 @@
namespace GamePort.Game;
/// <summary>Animated sprite timing EXE0x40ED40: strict interval, one frame/call, discard remainder.</summary>
public sealed class SpriteSequence(int frames, float fps, int loop)
{
private float elapsed;
private int next;
public int Frame { get; private set; }
public bool Running { get; private set; }
public bool Hidden { get; private set; }
public void Start() { elapsed = 0; next = Frame = 0; Running = true; Hidden = false; }
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0) throw new ArgumentOutOfRangeException(nameof(dt));
if (!Running || frames <= 0 || fps <= 0) return;
elapsed += dt;
if (elapsed <= 1 / fps) return;
elapsed = 0;
Frame = next++;
if (next < frames) return;
next = 0;
if (loop is 0 or 2) Running = false;
if (loop == 2) Hidden = true;
}
}
+37
View File
@@ -0,0 +1,37 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Recovered task gates; -1 sentinels and numeric ExactLevel must retain their original meaning.</summary>
public static class TaskActivation
{
// Animated entity EXE0x40E340. null means keep the prior activation state.
public static bool? Animated(GamEntity entity, int state)
{
var exact = entity.Integer("ExactLevel", -1);
if (exact != -1) return state == exact;
var required = entity.Integer("RequiredLevel", -1);
if (required == -1) return null;
var remove = entity.Integer("RemoveLevel", -1);
return state >= required && (remove == -1 || state < remove);
}
// Pickup EXE0x45F2B0: no RemoveLevel check in this override.
public static bool? Pickup(GamEntity entity, int state)
{
var exact = entity.Integer("ExactLevel", -1);
if (exact != -1) return state == exact;
var required = entity.Integer("RequiredLevel", -1);
return required == -1 ? null : state >= required;
}
// LOAD EXE0x457F32. A stored task state -1 bypasses the requirements.
public static bool Load(GamEntity entity, TaskStates tasks)
{
var name = entity.Text("RequiredTask");
if (string.Equals(name, "none", StringComparison.OrdinalIgnoreCase)) return true;
var state = tasks.Get(name);
var exact = entity.Integer("ExactLevel", -1);
return state == -1 || state >= entity.Integer("RequiredLevel") && (exact == -1 || state == exact);
}
}
+25
View File
@@ -0,0 +1,25 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>EXE0x45FEA0 query/0x45F990 assignment; ASCII case folding, missing returns0.</summary>
public sealed class TaskStates
{
private readonly List<SavedTask> tasks;
public event Action<string, int>? Assigned;
public TaskStates(IEnumerable<SavedTask> initial) => tasks = initial.ToList();
private static bool Equal(string a, string b) => Fold(a) == Fold(b);
private static string Fold(string text) => string.Create(text.Length, text, (span, source) =>
{
for (var i = 0; i < span.Length; i++) span[i] = source[i] is >= 'A' and <= 'Z' ? (char)(source[i] + 32) : source[i];
});
public int Get(string? name) => name == null ? 0 : tasks.FirstOrDefault(t => Equal(t.Name, name))?.State ?? 0;
public void SetExisting(string name, int value)
{
for (var i = 0; i < tasks.Count; i++)
if (Equal(tasks[i].Name, name)) tasks[i] = tasks[i] with { State = value };
// Original broadcasts even repeated assignments and unknown task names.
Assigned?.Invoke(name, value);
}
public SavedTask[] Snapshot() => tasks.ToArray();
}
+2
View File
@@ -43,6 +43,8 @@ internal static unsafe class Sdl
[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);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_Vulkan_CreateSurface(nint window,nint instance,void* allocator,out ulong surface); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_Vulkan_CreateSurface(nint window,nint instance,void* allocator,out ulong surface);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSizeInPixels(nint window,out int w,out int h); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSizeInPixels(nint window,out int w,out int h);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSize(nint window,out int w,out int h);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern uint SDL_GetMouseState(out float x,out float y);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowFullscreen(nint window,[MarshalAs(UnmanagedType.I1)]bool fullscreen); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowFullscreen(nint window,[MarshalAs(UnmanagedType.I1)]bool fullscreen);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowRelativeMouseMode(nint window,[MarshalAs(UnmanagedType.I1)]bool enabled); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowRelativeMouseMode(nint window,[MarshalAs(UnmanagedType.I1)]bool enabled);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowSize(nint window,int width,int height); [DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowSize(nint window,int width,int height);
+357 -18
View File
@@ -13,7 +13,16 @@ internal static class Program
{ {
public static int Main(string[] args) public static int Main(string[] args)
{ {
try { return Run(args); } try
{
OriginalSave? carriedSave = null;
while (true)
{
var result = Run(args, carriedSave, out var continuation);
if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save;
}
}
catch (Exception error) { Console.Error.WriteLine(error); return 1; } catch (Exception error) { Console.Error.WriteLine(error); return 1; }
} }
@@ -26,8 +35,11 @@ internal static class Program
return args[i + 1]; return args[i + 1];
} }
private static int Run(string[] args) private sealed record SceneContinuation(string[] Args, OriginalSave Save);
private static int Run(string[] args, OriginalSave? carriedSave, out SceneContinuation? continuation)
{ {
continuation = null;
if (args.Contains("--help")) if (args.Contains("--help"))
{ {
Console.WriteLine(""" Console.WriteLine("""
@@ -40,15 +52,30 @@ internal static class Program
--original-camera Stored GAM start camera and recovered projection --original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint --animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--with-player Use prepared jimstop animation in scene --with-player Use prepared jimstop animation in scene
--walk Controllable lab (default with prepared lab) --walk Play prepared scene with recovered story/interactions
--inspect Pause simulation and inspect scene/animation --inspect Pause simulation and inspect scene/animation
--smoke-walk Deterministic 240-step movement/jump check --smoke-walk Deterministic 240-step movement/jump check
--story Execute recovered original CAM/MCA/AI trigger sequence
--story-time N Headless scene-sequence time for GPU comparisons
--skip-intro Fast-forward original intro actions and restore control
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons --time SECONDS Fixed animation time for comparisons
--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)
--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
--effects-audio-smoke PATH Verify default effect bank and loop lifetime
--smoke-transition Headless VR01 RETURN / renderer-recreation check
--smoke-lab-route Headless source lab contact route / next-scene rebuild
--smoke-practice-prompt Headless original jet pack practice prompt
--smoke-practice-transition Headless lab-to-VR04 practice transition
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack Headless 300-step powered-jump/release check in VR04
--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
@@ -56,12 +83,53 @@ internal static class Program
C pauses into inspection / resumes chase camera. F11 fullscreen, Escape quit. C pauses into inspection / resumes chase camera. F11 fullscreen, Escape quit.
Inspector: arrows/WASD orbit, +/- zoom, Inspector: arrows/WASD orbit, +/- zoom,
F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch. F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch.
Collision/pivot/cadence and animation timing are provisional. Intro/interactions remain incomplete. Collision/pivot/cadence and animation timing are provisional. Full gameplay remains incomplete.
"""); """);
return 0; return 0;
} }
var root = AssetPath.FindOriginal(Option(args, "--assets")); var root = AssetPath.FindOriginal(Option(args, "--assets"));
var saveOutput = Option(args, "--write-save");
if (saveOutput != null)
{
saveOutput = Path.GetFullPath(saveOutput);
if (saveOutput.StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Save output must be outside original asset directory");
for (var parent = new DirectoryInfo(Path.GetDirectoryName(saveOutput)!); parent != null; parent = parent.Parent)
if (parent.Exists && parent.LinkTarget != null) throw new ArgumentException("Save output directory must not redirect through a symbolic link");
}
if (args.Contains("--verify-assets")) return VerifyAssets(root); if (args.Contains("--verify-assets")) return VerifyAssets(root);
if (Option(args, "--effects-audio-smoke") is { } effectsManifest)
{
using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest));
mixer.Effect(59, "bars"); mixer.Effect(58);
var before = mixer.QueuedEffectBytes;
Thread.Sleep(200);
var consumed = mixer.QueuedEffectBytes < before;
mixer.Pump();
mixer.StopLoop("bars");
var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1;
mixer.Effect(230);
var mixed = mixer.EffectCount == 2;
mixer.StopEffects();
Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}.");
return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2;
}
if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest)
{
var bank = new PreparedEntityResources(sceneAudioManifest);
using var mixer = new SceneAudio(bank);
mixer.Music("musicsecretlab.omt", 0);
mixer.Speech("voiceneighborhood.omt", 36);
var beforeMusic = mixer.QueuedMusicBytes;
var beforeSpeech = mixer.QueuedSpeechBytes;
Thread.Sleep(500);
var consumed = mixer.QueuedMusicBytes < beforeMusic && mixer.QueuedSpeechBytes < beforeSpeech;
mixer.StopSpeech();
mixer.Speech("voiceneighborhood.omt", 46);
var restarted = mixer.QueuedMusicBytes > 0 && mixer.QueuedSpeechBytes > 0;
Console.WriteLine($"Scene music and speech consumed independently: {consumed}; speech replacement retained music: {restarted}.");
return consumed && restarted ? 0 : 2;
}
if (Option(args, "--audio-smoke") is { } audioSmoke) if (Option(args, "--audio-smoke") is { } audioSmoke)
{ {
using var sound = new SdlAudio(audioSmoke); using var sound = new SdlAudio(audioSmoke);
@@ -73,6 +141,19 @@ internal static class Program
} }
var scene = Option(args, "--scene"); var scene = Option(args, "--scene");
var loadedSave = carriedSave ?? (Option(args, "--load-save") is { } savePath ? OriginalSave.Load(savePath) : null);
string? savedLevelPath = null;
if (loadedSave != null && carriedSave == null)
{
savedLevelPath = Directory.EnumerateFiles(AssetPath.Resolve(root, "gam"))
.Where(p => p.EndsWith(".gam", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(p => GamLevel.Load(p).Code == loadedSave.LevelCode)
?? throw new FileNotFoundException($"No GAM matches saved level {loadedSave.LevelCode}");
var prepared = new[] { "artifacts/extracted", Path.Combine(AppContext.BaseDirectory, "scenes") }
.FirstOrDefault(p => Directory.Exists(Path.Combine(p, "animations")))
?? throw new DirectoryNotFoundException("Prepare original scenes before loading saves");
scene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(savedLevelPath) + "/scene.json");
}
var defaultScene = false; var defaultScene = false;
if (scene == null && Option(args, "--model") == null) if (scene == null && Option(args, "--model") == null)
{ {
@@ -80,9 +161,12 @@ internal static class Program
Path.Combine(AppContext.BaseDirectory, "scenes/level1b/scene.json") }.FirstOrDefault(File.Exists); Path.Combine(AppContext.BaseDirectory, "scenes/level1b/scene.json") }.FirstOrDefault(File.Exists);
defaultScene = scene != null; defaultScene = scene != null;
} }
var levelPath = Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null); var levelPath = savedLevelPath == null ? Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null)
: "gam/" + Path.GetFileName(savedLevelPath);
GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath)); GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath));
var originalStart = level?.FindStart(); var startTag = Option(args, "--start") ?? loadedSave?.StartPoint;
if (string.Equals(startTag, "none", StringComparison.OrdinalIgnoreCase)) startTag = null;
var originalStart = level?.FindStart(startTag);
if (level != null) Console.WriteLine($"Decoded GAM {level.Code}: {level.Entities.Count} entities."); if (level != null) Console.WriteLine($"Decoded GAM {level.Code}: {level.Entities.Count} entities.");
var originalCamera = args.Contains("--original-camera") || defaultScene; var originalCamera = args.Contains("--original-camera") || defaultScene;
if (originalCamera && originalStart == null) if (originalCamera && originalStart == null)
@@ -90,6 +174,7 @@ internal static class Program
var mesh = scene != null ? Mesh.LoadSceneJson(scene) var mesh = scene != null ? Mesh.LoadSceneJson(scene)
: AseMesh.Load(AssetPath.Resolve(root, Option(args, "--model") ?? "ASE/jimstop.ase")); : AseMesh.Load(AssetPath.Resolve(root, Option(args, "--model") ?? "ASE/jimstop.ase"));
var world = mesh;
var texture = scene != null ? PngImage.White var texture = scene != null ? PngImage.White
: PngImage.Load(AssetPath.Resolve(root, Option(args, "--texture") ?? "png/jimycarl.png")); : PngImage.Load(AssetPath.Resolve(root, Option(args, "--texture") ?? "png/jimycarl.png"));
var bounds = mesh.Bounds(); var bounds = mesh.Bounds();
@@ -97,9 +182,18 @@ internal static class Program
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1); var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
var animationPath = Option(args, "--animation"); var animationPath = Option(args, "--animation");
var walkSmoke = args.Contains("--smoke-walk"); var walkSmoke = args.Contains("--smoke-walk");
var jetpackSmoke = args.Contains("--smoke-jetpack");
var practiceWindowSmoke = args.Contains("--smoke-practice-window");
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")
&& animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode."); if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode."); if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode.");
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (args.Contains("--walk") || walkSmoke var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (story || args.Contains("--walk") || walkSmoke
|| defaultScene && animationPath == null && !args.Contains("--time")); || defaultScene && animationPath == null && !args.Contains("--time"));
if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null) if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null)
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json"); animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
@@ -107,6 +201,19 @@ internal static class Program
throw new ArgumentException("Walking requires a scene and matching GAM startpoint."); throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null; PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null; LabSimulation? simulation = null;
SceneDirector? director = null;
SceneActorVisuals? actorVisuals = null;
SceneSpriteVisuals? spriteVisuals = null;
StaticSceneVisuals? staticVisuals = null;
PreparedEntityResources? resources = null;
SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null;
SceneHud? hud = null;
JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt();
var objectiveOffset = -69f;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null;
var characterOffset = mesh.Vertices.Length; var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity; var characterModel = Matrix4x4.Identity;
if (animationPath != null) if (animationPath != null)
@@ -115,7 +222,8 @@ 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) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y)
{ LevelCode = level!.Code };
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;
mesh = animations.Current.AppendTo(mesh); mesh = animations.Current.AppendTo(mesh);
@@ -124,15 +232,79 @@ internal static class Program
else else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch."); Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
} }
if (story)
{
resources = new PreparedEntityResources(Path.Combine(Path.GetDirectoryName(scene!)!, "entities/entities.json"),
Path.Combine(Path.GetDirectoryName(scene!)!, "../effects/effects.json"));
var save = loadedSave ?? OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var tasks = new TaskStates(save.Tasks);
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save, level!.Code);
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
mechanisms = new SceneMechanisms(director);
interactions.Transition += request => transitionRequest ??= request;
interactions.PracticeRequested += practice.Show;
practice.Chosen += (mode, accepted) =>
{
if (!accepted) return;
// Player43B5A0 receives current/requested GAM and latest STRT tag
// as return context;42AF00's runtime checkpoint is separate.
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
transitionRequest ??= new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1);
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}.");
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{
var physics = new OriginalScenePhysics(world);
var grounded = false;
var patrol = new ActorPatrol(actor, director.FindActor, (body, dt) =>
{
var resolved = physics.Step(body.Position, body.Velocity,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardRadius : 100,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardFactor : .75f, grounded, dt);
grounded = resolved.Supported;
return new(resolved.Body.Position, resolved.Body.Velocity);
});
patrols.Add(actor.Tag, patrol);
director.RegisterPatrolConsumer(actor.Tag);
director.ActorChanged += changed => { if (ReferenceEquals(changed, actor)) patrol.SynchronizeAuthoredState(); };
}
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh;
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
mesh = staticVisuals.Mesh;
simulation!.DynamicRootResolver = (previous, position, radius) =>
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
}
Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures."); Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
var fixedTimeText = Option(args, "--time"); var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture); double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless"); var headless = args.Contains("--headless");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : headless ? "1" : "0")); if (args.Contains("--smoke-transition") && (!headless || level?.Code is not ("VR01" or "VR04") || interactions == null))
throw new ArgumentException("Transition smoke requires headless story playback of VR01 or VR04.");
if (args.Contains("--smoke-lab-route") && (!headless || level?.Code != "LV1B" || interactions == null || loadedSave != null))
throw new ArgumentException("Lab route smoke requires fresh headless story playback of LV1B.");
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : headless ? "1" : "0"));
if (jetpackSmoke && (!headless || level?.Code != "VR04" || frames < 300))
throw new ArgumentException("Jetpack smoke requires headless VR04 and at least300 frames");
if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames."); if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames.");
var smoke = args.Contains("--smoke-window"); var smoke = args.Contains("--smoke-window");
if (frames < 0 || (smoke && (headless || frames < 6))) if (frames < 0 || (smoke && (headless || frames < 6)))
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))
throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames.");
nint window = 0; nint window = 0;
if (!headless) if (!headless)
{ {
@@ -146,6 +318,56 @@ internal static class Program
using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation")); 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")) : null; ? new SdlAudio(audioFile, args.Contains("--loop-audio")) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
double initialPoseTime = 0;
if (director != null)
{
if (sceneAudio != null)
{
director.Speech += sceneAudio.Speech;
interactions!.SoundEffect += id => sceneAudio.Effect(id);
mechanisms!.Sound += (actor, id, loop) => sceneAudio.Effect(id, loop ? actor.Tag : null);
mechanisms.StopSound += actor => sceneAudio.StopLoop(actor.Tag);
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!);
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (args.Contains("--skip-intro") || jetpackSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--smoke-transition"))
{
director.Skip();
interactions!.Update(level!.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest == null) throw new InvalidOperationException("Original VR01 RETURN contact did not request a transition");
}
if (args.Contains("--smoke-lab-route"))
{
LabRouteSmoke.Run(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (transitionRequest?.LevelFile != "level1.gam")
throw new InvalidOperationException("Original lab exit did not request level1.gam");
}
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions!.Update(director.FindActor("shrinkray")!.Position);
if (!practice.Active) throw new InvalidOperationException("Original lab pickup did not open practice modal");
if (args.Contains("--smoke-practice-transition")) practice.Key(28, Vector2.Zero);
}
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active; tick++)
{
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh);
spriteVisuals!.Step(FixedStepClock.Step);
}
}
var keys = new HashSet<uint>(); var keys = new HashSet<uint>();
var running = true; var running = true;
var fullscreen = false; var fullscreen = false;
@@ -158,12 +380,20 @@ internal static class Program
var active = true; var active = true;
var mouseJump = false; var mouseJump = false;
var stepClock = new FixedStepClock(); var stepClock = new FixedStepClock();
double poseTime = 0; double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput); var injectedInput = default(PlayerInput);
var sawWalkKeys = 0; var sawWalkKeys = 0;
var sawPracticeDismiss = false;
var sawPracticePause = false;
double last = clock.Elapsed.TotalSeconds; double last = clock.Elapsed.TotalSeconds;
float angle = 0.6f, elevation = 0.32f; float angle = 0.6f, elevation = 0.32f;
var count = 0; var count = 0;
Vector2 Pointer()
{
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;
return new(x * 640 / w, y * 480 / h);
}
while (running) while (running)
{ {
if (walkSmoke && !headless) if (walkSmoke && !headless)
@@ -187,6 +417,14 @@ internal static class Program
{ keys.Clear(); mouseJump = false; active = false; stepClock.Reset(); } { keys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored) if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; } { active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown)
{
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) mouseJump = true; if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) mouseJump = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false; if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown) if (e.Type == Sdl.KeyDown)
@@ -194,7 +432,11 @@ internal static class Program
keys.Add(e.Scancode); keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0; if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0;
if (smoke && e.Scancode == 79) sawKey = true; if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode == 41) running = false; if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false })
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false;
if (e.Scancode == 18 && e.Repeat == 0 && director is { Controlled: true, InventoryEnabled: true })
objectiveOffset = objectiveOffset == -69 ? 0 : -69;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true) if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{ {
animationStarted = clock.Elapsed.TotalSeconds; animationStarted = clock.Elapsed.TotalSeconds;
@@ -214,7 +456,12 @@ internal static class Program
} }
else originalCamera = !originalCamera; else originalCamera = !originalCamera;
} }
if (!inspecting && e.Scancode == 21 && e.Repeat == 0) { simulation!.Reset(); poseTime = 0; } if (!inspecting && e.Scancode == 21 && e.Repeat == 0)
{
simulation!.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset();
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
if (e.Scancode == 68 && e.Repeat == 0) if (e.Scancode == 68 && e.Repeat == 0)
{ {
fullscreen = !fullscreen; fullscreen = !fullscreen;
@@ -227,17 +474,35 @@ internal static class Program
var elapsed = now - last; var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1); var dt = (float)Math.Min(elapsed, 0.1);
last = now; last = now;
if (simulation != null && !inspecting && (active || headless || walkSmoke)) if (simulation != null && !inspecting && !practice.Active && (active || headless || walkSmoke))
{ {
var steps = headless || walkSmoke ? 1 : stepClock.Advance(elapsed); var steps = headless || walkSmoke || practiceWindowSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++) for (var step = 0; step < steps; step++)
{ {
var input = walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( var input = jetpackSmoke ? new PlayerInput(false, false, false, false, simulation.Steps < 180)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79), keys.Contains(82), keys.Contains(81), 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)
{
simulation.Step(input); simulation.Step(input);
if (animations!.SelectPose(simulation.Pose)) poseTime = 0; interactions?.UpdateEnergy(simulation.Energy);
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
director?.Touch(level!.Player!.Tag!, simulation.ActorRoot);
interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius);
if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; }
mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius);
}
mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step);
var switched = director is { Controlled: false }
? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)
: animations!.SelectPose(simulation.Pose);
if (switched) poseTime = 0;
poseTime += FixedStepClock.Step; poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh);
spriteVisuals?.Step(FixedStepClock.Step);
} }
characterModel = simulation.Model; characterModel = simulation.Model;
} }
@@ -256,8 +521,22 @@ internal static class Program
var view = originalCamera var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY) ? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY)
: Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY); : Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY);
var renderEye = originalCamera ? originalStart!.CameraPosition : eye;
var renderTarget = originalCamera ? originalStart!.Position + new Vector3(0,80,0) : target;
if (simulation != null && !inspecting) if (simulation != null && !inspecting)
{
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY); view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget;
}
if (!inspecting && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget)
{
view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY);
renderEye = storyEye; renderTarget = storyTarget;
}
staticVisuals?.Update(mesh);
jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && director!.Controlled, practice.Active, objectiveOffset);
var far = level?.Code == "LV1B" ? 10000 : 3200; var far = level?.Code == "LV1B" ? 10000 : 3200;
var projection = originalCamera || simulation != null && !inspecting var projection = originalCamera || simulation != null && !inspecting
? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far) ? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far)
@@ -266,12 +545,21 @@ internal static class Program
if (animations != null) if (animations != null)
{ {
animations.Current.Sample(simulation != null && !inspecting ? poseTime animations.Current.Sample(simulation != null && !inspecting ? poseTime
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted), mesh.Vertices.AsSpan(characterOffset), characterModel); : fixedTime ?? (headless ? count / 60.0 : now - animationStarted),
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
renderer.UpdateVertices(mesh.Vertices); renderer.UpdateVertices(mesh.Vertices);
} }
renderer.Render(view * projection); renderer.Render(view * projection);
count++; count++;
audio?.Pump(); audio?.Pump();
sceneAudio?.Pump();
if (practiceWindowSmoke && count == 1)
{
sawPracticePause = practice.Active && simulation!.Steps == 0;
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 17, Down = 1 };
if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
}
if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600)) if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error); throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 1) if (smoke && count == 1)
@@ -285,8 +573,9 @@ internal static class Program
if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error); if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error);
} }
} }
if ((smoke || walkSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true; if ((smoke || walkSmoke || practiceWindowSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if (frames > 0 && count >= frames) break; if (frames > 0 && count >= frames) break;
if (transitionRequest != null) break;
} }
if (Option(args, "--screenshot") is { } screenshot) if (Option(args, "--screenshot") is { } screenshot)
{ {
@@ -299,6 +588,50 @@ internal static class Program
if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++; if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++;
Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s)."); Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s).");
if (simulation != null) Console.WriteLine(simulation.Report); if (simulation != null) Console.WriteLine(simulation.Report);
if (jetpackSmoke)
{
Console.WriteLine($"Powered jump: bursts={simulation!.Bursts}, remaining={simulation.JetpackRemaining:F3}, energy={simulation.Energy:F3}, grounded={simulation.Grounded}.");
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded) return 2;
}
if (director != null)
{
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
foreach (var issue in director.Issues) Console.WriteLine($"Unrecovered scene behavior {issue.Tag}: {issue.Detail}");
foreach (var missing in actorVisuals!.UnsupportedAnimations) Console.WriteLine($"Unrecovered animation alias {missing}");
foreach (var missing in interactions!.Unsupported) Console.WriteLine(missing);
foreach (var missing in mechanisms!.Unsupported) Console.WriteLine(missing);
foreach (var (tag, patrol) in patrols)
Console.WriteLine($"Patrol {tag}: root={director.FindActor(tag)!.Position}, waypoint={patrol.CurrentWaypoint ?? "none"}, velocity={patrol.Velocity}; recovered support, provisional wall response.");
}
if (interactions != null && saveOutput is { } output)
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag! };
var temporary = output + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) stream.Write(snapshot.Encode());
File.Move(temporary, output, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
Console.WriteLine($"Wrote original-format checkpoint state: {output}");
}
if (transitionRequest != null && renderer.ValidationErrors == 0)
{
var prepared = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."));
var nextScene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(transitionRequest.LevelFile) + "/scene.json");
var nextArgs = new List<string>();
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") continue;
if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time") { i++; continue; }
nextArgs.Add(args[i]);
}
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with { StartPoint = transitionRequest.StartPoint });
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;
if (walkSmoke && !headless) if (walkSmoke && !headless)
{ {
@@ -315,6 +648,12 @@ internal static class Program
if (!animationSwitched || !animations.Current.HasVertexMotion) return 2; if (!animationSwitched || !animations.Current.HasVertexMotion) return 2;
} }
} }
if (practiceWindowSmoke)
{
var resumed = !practice.Active && simulation!.Steps > 0;
Console.WriteLine($"Practice SDL check: paused={sawPracticePause}, N dismiss={sawPracticeDismiss}, resumed={resumed}, resize800x600={didResize}.");
if (!sawPracticePause || !sawPracticeDismiss || !resumed || !didResize) return 2;
}
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0; return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
} }
finally finally
@@ -29,7 +29,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
private ImageView colorView,depthView; private ImageView colorView,depthView;
private RenderPass renderPass; private RenderPass renderPass;
private Framebuffer framebuffer; private Framebuffer framebuffer;
private Pipeline pipeline; private Pipeline pipeline,overlayPipeline;
private PipelineLayout pipelineLayout; private PipelineLayout pipelineLayout;
private DescriptorSetLayout descriptorLayout; private DescriptorSetLayout descriptorLayout;
private DescriptorPool descriptorPool; private DescriptorPool descriptorPool;
@@ -312,6 +312,8 @@ public sealed unsafe class VulkanRenderer : IDisposable
var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates}; var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates};
var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0}; var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0};
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline"); Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
ds.DepthTestEnable=false;ds.DepthWriteEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline");
} }
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);} finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
} }
@@ -368,14 +370,20 @@ public sealed unsafe class VulkanRenderer : IDisposable
var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height)); var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height));
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor); vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32); var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&mvp);
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)]; var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
foreach(var screenSpace in new[]{false,true})
{
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,screenSpace?overlayPipeline:pipeline);
var transform=screenSpace?Matrix4x4.Identity:mvp;
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&transform);
foreach(var draw in draws) foreach(var draw in draws)
{ {
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]); var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null); vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0); vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
} }
}
vk.CmdEndRenderPass(command); vk.CmdEndRenderPass(command);
if(window==0){Submit();return;} if(window==0){Submit();return;}
var target=swapImages[imageIndex];Barrier(target,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit); var target=swapImages[imageIndex];Barrier(target,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
@@ -410,6 +418,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
vk.DeviceWaitIdle(device); vk.DeviceWaitIdle(device);
if(framebuffer.Handle!=0)DestroyTarget(); if(framebuffer.Handle!=0)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(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); if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null);
@@ -9,6 +9,8 @@
<ItemGroup> <ItemGroup>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/GamLevel.cs" Link="GamLevel.cs" /> <Compile Include="../../src/GamePort/Assets/GamLevel.cs" Link="GamLevel.cs" />
<Compile Include="../../src/GamePort/Assets/OriginalSave.cs" Link="OriginalSave.cs" />
<Compile Include="../../src/GamePort/Assets/PreparedEntityResources.cs" Link="PreparedEntityResources.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" /> <Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" /> <Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" />
<Compile Include="../../src/GamePort/Assets/AseMesh.cs" Link="AseMesh.cs" /> <Compile Include="../../src/GamePort/Assets/AseMesh.cs" Link="AseMesh.cs" />
+55
View File
@@ -17,6 +17,31 @@ foreach (var file in files)
} }
Require(entities == 3299, "Original entity total differs"); Require(entities == 3299, "Original entity total differs");
var initial = GamLevel.Load(Path.Combine(root, "gam/level1b.gam")); var initial = GamLevel.Load(Path.Combine(root, "gam/level1b.gam"));
var saves = Directory.GetFiles(root, "*.tsk");
Require(saves.Length == 12, "Expected original save corpus");
foreach (var file in saves)
{
var raw = File.ReadAllBytes(file);
var save = OriginalSave.Parse(raw);
Require(save.Encode().SequenceEqual(raw), $"TSK byte round-trip differs: {file}");
foreach (var length in new[] { 0, 4, 18, 16000, raw.Length - 1 }) RejectSave(raw[..length]);
RejectSave([.. raw, 0]);
}
var newGame = OriginalSave.Load(Path.Combine(root, "NewGame.tsk"));
Require(newGame.LevelCode == "LV1B" && newGame.StartPoint == "STARTEXP", "Wrong new-game resume data");
var tasks = new TaskStates(newGame.Tasks);
Require(tasks.Get("scene") == 30 && tasks.Get("missing") == 0, "Original task query semantics differ");
var assignments = 0;
tasks.Assigned += (_, _) => assignments++;
tasks.SetExisting("ScEnE", 35);
tasks.SetExisting("missing", 77);
tasks.SetExisting("SCENE", 35);
Require(tasks.Get("SCENE") == 35 && tasks.Get("missing") == 0 && tasks.Snapshot().Length == 12 && assignments == 3,
"Task assignment must broadcast without creating missing entries");
var changed = newGame with { Score = 15, Tasks = tasks.Snapshot() };
Require(OriginalSave.Parse(changed.Encode()).Score == 15 && OriginalSave.Parse(changed.Encode()).Tasks[3].State == 35,
"Modified original save did not persist recovered fields");
Console.WriteLine("PASS: all12 original TSK files byte-round-trip, malformed saves reject, task query/assignment and mutations persist.");
Require(initial.Code == "LV1B" && initial.Entities.Count == 129, "Wrong initial scene"); Require(initial.Code == "LV1B" && initial.Entities.Count == 129, "Wrong initial scene");
Require(initial.Player!.Position.X == 5071.93310546875f, "Original player X changed"); Require(initial.Player!.Position.X == 5071.93310546875f, "Original player X changed");
Require(initial.FindStart()!.CameraPosition.Y == 235.64761352539062f, "Original camera Y changed"); Require(initial.FindStart()!.CameraPosition.Y == 235.64761352539062f, "Original camera Y changed");
@@ -113,6 +138,29 @@ foreach (var key in new[] { 31u, 32u, 33u })
Require(clips.Select(30) && !clips.Current.HasVertexMotion, "Idle selection did not restore original still pose"); Require(clips.Select(30) && !clips.Current.HasVertexMotion, "Idle selection did not restore original still pose");
Console.WriteLine($"PASS: original lab grounding (+{placement.VerticalCorrection:F3} Y), ceiling/proxy rejection, and explicit idle/run/jump/scratch selection."); Console.WriteLine($"PASS: original lab grounding (+{placement.VerticalCorrection:F3} Y), ceiling/proxy rejection, and explicit idle/run/jump/scratch selection.");
var preparedFixture = Path.Combine(Path.GetTempPath(), "neutron-bank-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(preparedFixture);
try
{
string WaveManifest(string name, string database, string payload)
{
File.WriteAllText(Path.Combine(preparedFixture, name + ".wav"), payload);
var path = Path.Combine(preparedFixture, name + ".json");
File.WriteAllText(path, System.Text.Json.JsonSerializer.Serialize(new { resources = new[] {
new { database, type = "Wave", id = 59, path = name + ".wav", audio = new { seconds = 1.0 } } } }));
return path;
}
var first = WaveManifest("scene", "omt/soundeffects.omt", "same-source-riff");
var second = WaveManifest("bank", "SoundEffects.omt", "same-source-riff");
var merged = new PreparedEntityResources(first, second);
Require(merged.Wave("SOUNDEFFECTS.OMT", 59)?.Seconds == 1, "Explicit bank/scene identity did not merge");
File.WriteAllText(Path.Combine(preparedFixture, "bank.wav"), "different-source-riff");
try { _ = new PreparedEntityResources(first, second); throw new Exception("Conflicting audio identities accepted"); }
catch (InvalidDataException) { }
Console.WriteLine("PASS: explicit bank/scene resource merge accepts identical waves and rejects conflicting identities.");
}
finally { Directory.Delete(preparedFixture, true); }
static void Require(bool condition, string message) static void Require(bool condition, string message)
{ {
if (!condition) throw new Exception(message); if (!condition) throw new Exception(message);
@@ -124,3 +172,10 @@ static void Reject(byte[] data)
catch (InvalidDataException) { return; } catch (InvalidDataException) { return; }
throw new Exception("Malformed GAM was accepted"); throw new Exception("Malformed GAM was accepted");
} }
static void RejectSave(byte[] data)
{
try { OriginalSave.Parse(data); }
catch (InvalidDataException) { return; }
throw new Exception("Malformed TSK was accepted");
}
@@ -0,0 +1,4 @@
<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/Assets/*.cs"/><Compile Include="../../src/GamePort/Game/*.cs"/><Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs"/><Compile Include="../../src/GamePort/Application/SceneActorVisuals.cs"/><Compile Include="../../src/GamePort/Application/SceneSpriteVisuals.cs"/><Compile Include="../../src/GamePort/Application/StaticSceneVisuals.cs"/></ItemGroup>
</Project>
+175
View File
@@ -0,0 +1,175 @@
using System.Buffers.Binary;
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var level = GamLevel.Load(AssetPath.Resolve(root,"gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(root,"NewGame.tsk"));
var tasks = new TaskStates(save.Tasks);
var director = new SceneDirector(level,tasks,(_,_)=>.1);
var cues = 0;
director.Speech += (_,_)=>cues++;
director.Begin(level.FindStart()!);
Check(!director.Controlled && director.CurrentTag == "LABEXP1", "STRT must freeze into original first camera");
for(var i=0;i<200 && !director.Controlled;i++) director.Step(.1f);
Check(director.Controlled && !director.Blocked && cues>10, "Complete original intro trigger/camera chain");
Check(tasks.Get("SCENE")==30, "Intro must not invent a progression/task advance");
var endGoddard = director.FindActor("C3DGODDARD")!.Position;
Check(endGoddard==director.FindActor("phone2")!.Position,"AI teleport position actions must execute");
Check(director.Issues.Any(x=>x.Detail.Contains("Patrol")),"Unsupported patrol must remain explicit");
Console.WriteLine($"PASS original lab sequence: {cues} original speech cues, correct task30, control restored");
var skip = new SceneDirector(level,new TaskStates(save.Tasks),(_,_)=>10);
var skipCues=0;
skip.Speech += (_,_)=>skipCues++;
skip.Begin(level.FindStart()!);
skip.Skip();
Check(skip.Controlled && !skip.Blocked && skipCues==1,"Skip must fast-forward voices and return control");
Check(skip.FindActor("C3DGODDARD")!.Position==endGoddard,"Skip must preserve AI/toggle actions");
Console.WriteLine("PASS original intro skip preserves action sequence");
foreach(var type in new[]{0,1,2,3,4})
{
var camera=Entity("3MCA","camera",("CameraTarget0","actor"),("SoundDatabase","voice"),("SoundIndex0",1),("CameraType0",type),("LookatVOffset0",100f),("NextTrigger","default"));
var actor=Entity("3CAR","actor",("PositionX",50f),("PositionY",20f),("PositionZ",70f));
var test=new SceneDirector(new("TEST",[camera,actor]),new TaskStates([]),(_,_)=>20);
test.Trigger("camera");test.Step(1);
var expected=type switch {1=>new Vector3(0,140,285),2=>new(0,240,465),3=>new(200,240,645),4=>new(-200,190,645),_=>new(0,40,200)};
Near(test.CameraEye!.Value,actor.Position+expected,"Recovered MCA eye");
Near(test.CameraTarget!.Value,actor.Position+new Vector3(0,40,0),"Recovered MCA target offset minus60");
}
Console.WriteLine("PASS all five recovered MCA framing/zoom formulas");
var target=Entity("3CAR","actor",("PositionX",20f),("PositionY",30f),("PositionZ",40f));
var cam=Entity("3CAM","camera",("CameraTarget","actor"),("SoundDatabase","voice"),("SoundIndex",1),("CameraType",2),("PositionX",200f),("PositionY",300f),("PositionZ",400f));
var fixedCam=new SceneDirector(new("TEST",[target,cam]),new TaskStates([]),(_,_)=>10);
fixedCam.Trigger("camera");Near(fixedCam.CameraEye!.Value,cam.Position,"CAM type2 authored eye");Near(fixedCam.CameraTarget!.Value,target.Position,"CAM type2 no offset");
var zoom=Entity("3CAM","camera",("CameraTarget","actor"),("SoundDatabase","voice"),("SoundIndex",1),("CameraType",0),("ViewFromCamera",0),("InitialDist",300f),("MinDist",100f),("MaxDist",500f),("ZoomSpeed",20f),("TargOffsetX",12f),("TargOffsetY",40f),("LookVoffset",90f));
var zoomCam=new SceneDirector(new("TEST",[target,zoom]),new TaskStates([]),(_,_)=>10);zoomCam.Trigger("camera");zoomCam.Step(1);
Near(zoomCam.CameraEye!.Value,target.Position+new Vector3(12,40,280),"CAM local zoom");Near(zoomCam.CameraTarget!.Value,target.Position+new Vector3(0,90,0),"CAM look offset");
Console.WriteLine("PASS CAM authored/local camera and zoom");
var gated=Entity("3CAR","gate",("RequiredLevel",30),("ExactLevel",-1),("RemoveLevel",60));
Check(TaskActivation.Animated(gated,29)==false && TaskActivation.Animated(gated,30)==true && TaskActivation.Animated(gated,59)==true && TaskActivation.Animated(gated,60)==false,"Threshold and exclusive removal");
var exact=Entity("3CAR","exact",("RequiredLevel",100),("ExactLevel",35),("RemoveLevel",20));
Check(TaskActivation.Animated(exact,35)==true && TaskActivation.Animated(exact,36)==false,"Exact numeric level takes precedence");
Check(TaskActivation.Animated(Entity("3CAR","unchanged",("RequiredLevel",-1)),999)==null,"-1 leaves activation unchanged");
var load=Entity("LOAD","load",("RequiredTask","SCENE"),("RequiredLevel",30),("ExactLevel",60));
Check(!TaskActivation.Load(load,tasks),"LOAD exact numeric60 must reject30");tasks.SetExisting("SCENE",60);Check(TaskActivation.Load(load,tasks),"LOAD gate60");tasks.SetExisting("SCENE",-1);Check(TaskActivation.Load(load,tasks),"LOAD task-1 bypass");
Console.WriteLine("PASS recovered task activation and LOAD gates");
var cycle=Entity("3AIT","cycle",("NextTrigger","cycle"),("TimesToTrigger",-1));
var cyclic=new SceneDirector(new("TEST",[cycle]),new TaskStates([]),(_,_)=>1);cyclic.Trigger("cycle");Check(cyclic.Blocked && cyclic.Issues.Count==1,"Malformed cycle must stop bounded");
Console.WriteLine("PASS bounded trigger-cycle handling");
var manifest="artifacts/extracted/level1b/entities/entities.json";
var resources=new PreparedEntityResources(manifest);
Check(resources.Duration("voiceneighborhood.omt",36)>0,"Original voice duration");
var real=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);real.Begin(level.FindStart()!);
for(var i=0;i<180 && !real.Controlled;i++)real.Step(1);
Check(real.Controlled && !real.Blocked,"Actual WAV-duration intro reaches original DEFAULT");
Console.WriteLine("PASS original decoded speech durations drive lab intro completion");
var once = new SpriteSequence(3,10,0);once.Start();once.Step(.1f);Check(once.Frame==0 && once.Running,"Strict frame interval");
once.Step(.01f);once.Step(.11f);Check(once.Frame==1,"Advance one frame per source call");once.Step(.11f);Check(once.Frame==2 && !once.Running && !once.Hidden,"Loop0 stops on final visible frame");
var hidden = new SpriteSequence(2,10,2);hidden.Start();hidden.Step(.11f);hidden.Step(.11f);Check(hidden.Hidden && !hidden.Running,"Loop2 hides at sequence end");
var repeat = new SpriteSequence(2,10,1);repeat.Start();for(var i=0;i<10;i++)repeat.Step(.5f);Check(repeat.Running && !repeat.Hidden && repeat.Frame==1,"Loop1 repeats, at most one frame/call");
Console.WriteLine("PASS recovered sprite strict timing, repeat and stop/hide modes");
var world=Mesh.LoadSceneJson("artifacts/extracted/level1b/scene.json");
var visualDirector=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);
var actorVisuals=new SceneActorVisuals(world,world,visualDirector,"artifacts/extracted");
var spriteVisuals=new SceneSpriteVisuals(actorVisuals.Mesh,visualDirector,resources);
var staticVisuals=new StaticSceneVisuals(spriteVisuals.Mesh,visualDirector,root,"artifacts/extracted/level1b/models");
var combined=staticVisuals.Mesh;
Check(staticVisuals.ActorCount==9,"Actual lab adds nine explicitly bound model actors");
visualDirector.FindActor("C3DCARL")!.Animation="TALK";
actorVisuals.Update(0,combined);
var before=combined.Vertices.Select(v=>v.Position).ToArray();
actorVisuals.Update(.05,combined);
Check(combined.Vertices.Where((v,i)=>v.Position!=before[i]).Any(),"Appending props must retain live actor animation updates in final buffer");
var spriteOffset=actorVisuals.Mesh.Vertices.Length;
spriteVisuals.FaceCamera(new(4873,235,373),new(5071,126,824),combined);
Check(combined.Vertices[spriteOffset].Position!=Vector3.Zero,"Appending props must retain live sprite updates in final buffer");
var firstSprite=combined.Vertices[spriteOffset].Position;
spriteVisuals.FaceCamera(new(5373,335,373),new(5071,126,824),combined);
Check(combined.Vertices[spriteOffset].Position!=firstSprite,"Sprite quad orientation responds to the rendered camera in final buffer");
Check(combined.Vertices.All(v=>float.IsFinite(v.Position.X+v.Position.Y+v.Position.Z)),"Combined model/sprite geometry must remain finite");
Check(combined.Draws.Count(d=>d.Visible)>world.Draws.Length,"Original actor/sprite/model consumers add visible source geometry");
Console.WriteLine("PASS combined source actor/sprite/model geometry and live animation/billboard buffer updates");
var mechanismDirector=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);
var mechanisms=new SceneMechanisms(mechanismDirector);
var bar=mechanismDirector.FindActor("bars")!;
var closed=bar.Position;
var buttons=mechanismDirector.Actors.Where(a=>a.Kind=="3BUT").ToArray();
var moveSounds=0;mechanisms.Sound+=(_,index,loop)=>{if(index==59&&loop)moveSounds++;};
mechanisms.Update(buttons[0].Position+new Vector3(360,0,0));
mechanisms.Step(1);Near(bar.Position,closed,"Strict button contact boundary");
mechanisms.Update(buttons[0].Position);mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*100,"DoorSpeed5 gives a five-second opening of500");
Check(buttons[0].Animation=="DOWN","Player contact presses original DOWN model");
mechanisms.Toggle(bar,1);mechanisms.Step(0);
Near(bar.Position,closed+Vector3.UnitY*100,"Reversal preserves current vertical position");
mechanisms.Step(.5f);Near(bar.Position,closed+Vector3.UnitY*50,"Reversed door closes with remaining fraction");
mechanisms.Step(.5f);Near(bar.Position,closed,"Reversed door finishes at source root");
Check(moveSounds==1,"Reversing an active door retains one looping movement sound");
Console.WriteLine("PASS original lab button strict contact, source door duration, reversal continuity and sound lifetime");
mechanisms.Reset();mechanisms.Update(buttons[0].Position);
for(var i=0;i<4;i++)mechanisms.Step(1);
Check(buttons[0].Animation=="UP","Button returns UP exactly when four-second cooldown expires");
mechanisms.Update(buttons[0].Position);
Check(buttons[0].Animation=="UP","Continuous contact must not press again after cooldown");
mechanisms.Step(1);Near(bar.Position,closed+Vector3.UnitY*500,"Door reaches full source OpenAmount");
for(var i=0;i<3;i++)mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*500,"OpenTime equality does not auto-close");
mechanisms.Step(.1f);mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*400,"OpenTime strict expiry starts next closing phase");
mechanisms.Update(buttons[1].Position);
Check(buttons[1].Animation=="DOWN","Duplicate button tags preserve distinct contact states by source offset");
Console.WriteLine("PASS source button cooldown, contact-enter persistence, duplicate tags and strict timed door close");
var prompt=new PracticePrompt();
var selections=new List<(int Mode,bool Accepted)>();prompt.Chosen+=(mode,accepted)=>selections.Add((mode,accepted));
prompt.Show(0);prompt.Click(new(225,260));Check(prompt.Active,"Practice hitbox excludes its boundary");
prompt.Click(new(260,260));Check(!prompt.Active && selections[^1]==(0,true),"Practice Yes mouse region");
prompt.Show(0);prompt.Key(40,Vector2.Zero);Check(!prompt.Active && !selections[^1].Accepted,"Enter outside Yes follows original No branch");
prompt.Show(0);prompt.Key(40,new(260,260));Check(!prompt.Active && selections[^1].Accepted,"Enter hovering Yes accepts");
prompt.Show(0);prompt.Key(28,Vector2.Zero);Check(!prompt.Active && selections[^1].Accepted,"Y accepts regardless of pointer");
prompt.Show(0);prompt.Key(17,new(260,260));Check(!prompt.Active && !selections[^1].Accepted,"N declines regardless of pointer");
Check(PracticePrompt.Destination(0)=="VR04.gam" && PracticePrompt.Destination(3)=="VR01.gam","Original practice mode mapping");
Console.WriteLine("PASS original practice keyboard/pointer boundaries and VR04 jet pack mapping");
var vr=GamLevel.Load(AssetPath.Resolve(root,"gam/VR01.gam"));
var vrTasks=new TaskStates(save.Tasks);var vrDirector=new SceneDirector(vr,vrTasks,(_,_)=>1);
var interactions=new SceneInteractions(vrDirector,vrTasks,save);
var stars=vr.Entities.Where(e=>e.Kind=="3PIC").ToArray();
Check(stars.Length==4,"Original VR01 star count");
interactions.Update(stars[0].Position+Vector3.UnitX*160);
Check(interactions.Score==0,"Source sphere boundary is strict");
foreach(var star in stars){interactions.Update(star.Position);interactions.Update(star.Position);}
Check(interactions.Score==20 && stars.All(e=>interactions.Snapshot().ItemStates[e.Integer("PickupIndex")]==1),"Source stars score once and persist acquired flags");
var trophy=vr.Entities.Single(e=>e.Kind=="3TRO");interactions.Update(trophy.Position);interactions.Update(trophy.Position);
Check(interactions.Score==320,"Trophy awards300 once and disables itself");
var restoredDirector=new SceneDirector(vr,new TaskStates(save.Tasks),(_,_)=>1);var restored=new SceneInteractions(restoredDirector,new TaskStates(save.Tasks),OriginalSave.Parse(interactions.Snapshot().Encode()));
Check(restoredDirector.Actors.Where(a=>a.Kind=="3PIC").All(a=>!a.Visible && !a.Active),"Loaded acquired stars must hide before contact");
var transitions=0;LevelTransition? returned=null;interactions.Transition += request=>{transitions++;returned=request;};
var returnGate=vr.Entities.First(e=>e.Kind=="LOAD");interactions.Update(returnGate.Position);interactions.Update(returnGate.Position);
Check(transitions==1 && returned!.LevelFile==save.ReturnLevel && returned.StartPoint==save.ReturnStart,"RETURN uses stored destination and contact-enter gating");
Console.WriteLine("PASS original VR01 star/trophy score, strict contact entry, acquired-state save/reload and RETURN request");
static GamEntity Entity(string kind,string tag,params (string Name,object Value)[] values)
{
var properties=new Dictionary<string,GamProperty>();
foreach(var (name,value) in values.Prepend(("ObjectTag",(object)tag)))
{
uint type;byte[] raw;
if(value is string text){type=1;raw=System.Text.Encoding.Latin1.GetBytes(text);}
else {raw=new byte[4];type=value is float?3u:6u;BinaryPrimitives.WriteInt32BigEndian(raw,value is float number?BitConverter.SingleToInt32Bits(number):(int)value);}
properties[name]=new(name,type,raw);
}
return new(kind,0,properties,new byte[4]);
}
static void Check(bool condition,string message){if(!condition)throw new Exception(message);}
static void Near(Vector3 actual,Vector3 expected,string message)=>Check(Vector3.Distance(actual,expected)<.01f,$"{message}: {actual} != {expected}");
@@ -0,0 +1,16 @@
<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/DynamicSceneCollision.cs" Link="DynamicSceneCollision.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" Link="OriginalBodySupport.cs" />
<Compile Include="../../src/GamePort/Game/SceneCollision.cs" Link="SceneCollision.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" />
<Compile Include="../../src/GamePort/Assets/GamLevel.cs" Link="GamLevel.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,140 @@
using System.Globalization;
using System.Numerics;
using System.Text.RegularExpressions;
using GamePort.Assets;
using GamePort.Game;
var groups = 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(); groups++; Console.WriteLine($"PASS {name}"); }
DynamicBoxCollider Box() => new(4, Vector3.Zero, new(-5), new(5), Matrix4x4.Identity);
DynamicSphereMotion Sphere(float x = 0) => new(new(x, 0, -1), new(x, 0, 0), 60);
Test("door constructor defaults and HasCollision sentinel", () => {
Check(DynamicSceneCollision.DoorRadius == 40 && DynamicSceneCollision.DoorMode == 2, "door dimensions/mode");
Check(DynamicSceneCollision.DoorCollisionFlags(-1) == (true, false), "-1 must preserve pair on/integration off");
Check(DynamicSceneCollision.DoorCollisionFlags(0) == (false, false), "explicit collision off");
Check(DynamicSceneCollision.DoorCollisionFlags(1) == (true, true), "explicit collision on");
});
Test("inclusive quantized-root broadphase and large-cube quirk", () => {
Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(140)), "140 boundary rejected");
Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(140.01f)), "outside 140 accepted");
var large = Box() with { LocalMin = new(-1000), LocalMax = new(1000) };
Check(!DynamicSceneCollision.BroadPhase(large, Sphere(200)), "cube extents silently enlarged root broadphase");
Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(100) with { Mode = 2 }), "box/box boundary");
Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(100.01f) with { Mode = 2 }), "box/box sum radius exceeded");
});
Test("pair, entity and sphere-geometry gates avoid narrowphase", () => {
DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("disabled narrowphase invoked");
Check(!DynamicSceneCollision.Resolve(Box() with { CollisionEnabled = false }, Sphere(), Fail).Contact, "box gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { CollisionEnabled = false }, Fail).Contact, "sphere gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { GeometryCollisionEnabled = false }, Fail).Contact, "geometry gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere(), Fail, false).Contact, "mutual exclusion gate");
});
Test("oriented source-local corners and current translation", () => {
var local = Box() with { LocalMin = new(-1, -2, -3), LocalMax = new(4, 5, 6) };
var corners = DynamicSceneCollision.Corners(local);
Check(corners[0] == local.LocalMin && corners[7] == local.LocalMax, "min/max corners");
Check(corners[1] == new Vector3(-1, -2, 6) && corners[6] == new Vector3(4, 5, -3), "corner bit order");
var transform = Matrix4x4.CreateRotationY(MathF.PI / 2) * Matrix4x4.CreateTranslation(100, 500, -80);
var moved = DynamicSceneCollision.Corners(local with { Root = new(100, 500, -80), LocalToWorld = transform });
for (var i = 0; i < 8; i++) Check(moved[i] == Vector3.Transform(corners[i], transform), "oriented transform");
});
Test("twelve source triangle order, normals and closed surface", () => {
var box = Box(); var corners = DynamicSceneCollision.Corners(box); var triangles = DynamicSceneCollision.Triangles(box);
Check(triangles.Length == 12, "cube triangle count");
Check(triangles[0] == new SupportTriangle(corners[0], corners[1], corners[2], 4, 0), "first original face");
Check(triangles[11] == new SupportTriangle(corners[7], corners[6], corners[2], 4, 11), "last original face");
var edges = new Dictionary<(int, int), int>();
foreach (var triangle in triangles) {
var normal = Vector3.Cross(triangle.B - triangle.A, triangle.C - triangle.A);
Check(Vector3.Dot(normal, (triangle.A + triangle.B + triangle.C) / 3) > 0, "face winding is not outward");
var ids = new[] { Array.IndexOf(corners, triangle.A), Array.IndexOf(corners, triangle.B), Array.IndexOf(corners, triangle.C) };
for (var i = 0; i < 3; i++) {
var a = ids[i]; var b = ids[(i + 1) % 3]; var key = (Math.Min(a, b), Math.Max(a, b));
edges[key] = edges.GetValueOrDefault(key) + 1;
}
}
Check(edges.Count == 18 && edges.Values.All(n => n == 2), "cube surface has a gap/duplicate");
});
Test("injected narrowphase and response-inhibition semantics", () => {
var calls = 0;
DynamicCollisionResponse Query(DynamicBoxSweep sweep) {
calls++; Check(sweep.Triangles.Count == 12 && sweep.Box.Identity == 4 && sweep.Sphere == Sphere(), "sweep contract");
return new(true, new(1, 2, 3));
}
Check(DynamicSceneCollision.Resolve(Box(), Sphere(), Query) == new DynamicCollisionResponse(true, new(1, 2, 3)), "response lost");
Check(DynamicSceneCollision.Resolve(Box() with { InhibitResponse = true }, Sphere(), Query)
== new DynamicCollisionResponse(true, Sphere().Position), "inhibited response moved body");
Check(calls == 2, "response inhibition incorrectly suppressed contact query");
var noContact = DynamicSceneCollision.Resolve(Box(), Sphere(), _ => new(false, new(10)));
Check(!noContact.Contact && noContact.Position == Sphere().Position, "failed query moved body");
});
Test("mode2 second actor bypasses triangle response", () => {
DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("box/box shortcut swept triangles");
var body = Sphere(80) with { Mode = 2 };
Check(DynamicSceneCollision.Resolve(Box(), body, Fail) == new DynamicCollisionResponse(true, body.Position), "box/box shortcut");
});
Test("source motion changes geometry without a closed-position residue", () => {
var box = Box(); var closed = DynamicSceneCollision.Corners(box);
var open = DynamicSceneCollision.Corners(box with { Root = new(0, 500, 0), LocalToWorld = Matrix4x4.CreateTranslation(0, 500, 0) });
for (var i = 0; i < closed.Length; i++) Check(open[i] - closed[i] == new Vector3(0, 500, 0), "door corner did not move");
});
Test("invalid source cube and transform rejected", () => {
foreach (var box in new[] { Box() with { LocalMin = new(10) }, Box() with { Radius = float.NaN },
Box() with { LocalToWorld = new Matrix4x4() }, Box() with { Root = new(float.PositiveInfinity) } }) {
var threw = false;
try { DynamicSceneCollision.BroadPhase(box, Sphere()); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "malformed collider accepted");
}
});
Test("actual lab bars bounds, closed/open passage with provisional sphere adapter", () => {
var original = Path.GetFullPath("../Original");
var level = GamLevel.Load(Path.Combine(original, "gam/level1b.gam"));
var bars = level.Entities.Single(e => e.Kind == "3DUD" && e.Tag == "bars");
Check(bars.Integer("HasCollision") == -1 && bars.Integer("CanMove") == 1 && bars.Rotation == Vector3.Zero, "lab authored flags");
var asePath = Directory.EnumerateFiles(Path.Combine(original, "ASE")).Single(p => Path.GetFileName(p).Equals("bars.ase", StringComparison.OrdinalIgnoreCase));
var text = File.ReadAllText(asePath);
var count = int.Parse(Regex.Match(text, @"\*MESH_NUMVERTEX\s+(\d+)").Groups[1].Value, CultureInfo.InvariantCulture);
var points = Regex.Matches(text, @"\*MESH_VERTEX\s+\d+\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)")
.Take(count).Select(m => new Vector3(float.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture),
float.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture), float.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture))).ToArray();
Check(points.Length == 42, "source bars vertex count");
var min = points.Aggregate(Vector3.Min); var max = points.Aggregate(Vector3.Max);
Near(min.X, -223.8069f, .0001f, "source xmin"); Near(min.Y, -18.7273f, .0001f, "source ymin");
Near(max.Y, 391.2706f, .0001f, "source ymax"); Near(max.Z, 16.8051f, .0001f, "source zmax");
var box = new DynamicBoxCollider(bars.Offset, bars.Position, min, max, Matrix4x4.CreateTranslation(bars.Position));
var body = new DynamicSphereMotion(bars.Position + new Vector3(0, 76, -100), bars.Position + new Vector3(0, 76, -20), 60);
// This adapter verifies integration/blocked passage only. SceneCollision's
// sweep/slide remains the explicitly provisional consumer, not original47BD80.
var calls = 0;
DynamicCollisionResponse Provisional(DynamicBoxSweep sweep) {
calls++;
var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C })
.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray();
var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray());
var radius = sweep.Sphere.Radius;
var result = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius,
sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2);
var position = result.Position + Vector3.UnitY * radius;
return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position);
}
var closed = DynamicSceneCollision.Resolve(box, body, Provisional);
Check(closed.Contact && closed.Position.Z < bars.Position.Z - 76, "closed bars did not block source-sized sphere");
var raised = bars.Position + Vector3.UnitY * bars.Number("OpenAmount");
var open = DynamicSceneCollision.Resolve(box with { Root = raised, LocalToWorld = Matrix4x4.CreateTranslation(raised) }, body, Provisional);
Check(!open.Contact && open.Position == body.Position && calls == 1, "raised bars still block closed location");
});
Console.WriteLine($"{groups} dynamic collision groups passed; injected narrowphase/runtime fidelity remain unverified.");
@@ -0,0 +1,9 @@
<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/Assets/Mesh.cs"/>
<Compile Include="../../src/GamePort/Assets/PngImage.cs"/>
<Compile Include="../../src/GamePort/Application/SceneHud.cs"/>
</ItemGroup>
</Project>
+63
View File
@@ -0,0 +1,63 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Application;
var temp = Path.Combine(Path.GetTempPath(), "neutron-hud-" + Guid.NewGuid());
Directory.CreateDirectory(temp);
try
{
var entries = new[] { (120,256,29),(121,256,29),(122,256,29),(156,320,173),(169,207,100),(83,8,8),(84,8,8),(85,8,8) }
.Select(t => new { id=t.Item1, width=t.Item2, height=t.Item3, path=$"{t.Item1}.rgba" }).ToArray();
foreach (var entry in entries) File.WriteAllBytes(Path.Combine(temp, entry.path), new byte[entry.width * entry.height * 4]);
string Manifest(object textures) => JsonSerializer.Serialize(new { version=1, referenceWidth=640, referenceHeight=480, textures });
var path = Path.Combine(temp, "ui.json");
File.WriteAllText(path, Manifest(entries));
var source = new Mesh([new(new(5,6,7), Vector2.Zero, Vector3.One)], [0,0,0]);
var hud = new SceneHud(source, path);
Check(hud.Mesh.Vertices.Length == 33 && hud.Mesh.Indices.Length == 51, "Exact bounded HUD ranges");
Check(hud.Mesh.Draws.Length == 9 && !hud.Mesh.Draws[0].ScreenSpace && hud.Mesh.Draws.Skip(1).All(d => d.ScreenSpace),
"Preserve implicit world draw; explicit HUD overlays");
Check(hud.Mesh.Textures.Count == 8, "Original canvas count");
var final = hud.Mesh with { Vertices = hud.Mesh.Vertices.ToArray(), Draws = hud.Mesh.Draws.Select(d => d with {}).ToArray() };
hud.Update(final, 2, true, true);
Check(final.Vertices[0].Position == new Vector3(5,6,7), "HUD leaves world data unchanged");
Check(hud.Mesh.Vertices[1].Position == Vector3.Zero && final.Vertices[1].Position != Vector3.Zero,
"Update writes final merged buffer after copies");
Near(final.Vertices[1].Position, new(.2f, 2*311f/480-1, 0), "Pad default source offset");
Near(final.Vertices[9].Position, new(.2f, 2*379f/480-1, 0), "Selected objective row position");
Near(final.Vertices[21].Position, new(2*393f/640-1, 2*381f/480-1, 0), "Selected original digit position");
Near(final.Vertices[29].Position, new(2*210f/640-1, 2*210f/480-1, 0), "Practice source position");
Check(final.Draws.Select(d => d.Visible).SequenceEqual(new[] { true,true,false,true,false,false,true,false,true }),
"Only pad, active objective2 and practice visible");
hud.Update(final, 3, true, false, 0);
Check(final.Draws.Select(d => d.Visible).SequenceEqual(new[] { true,true,false,false,true,false,false,true,false }), "Objective3 and dismissed modal");
Near(final.Vertices[1].Position, new(.2f, 2*380f/480-1, 0), "Expanded source HUD offset");
hud.Update(final, 0, true, false);
Check(final.Draws.Skip(1).All(d => !d.Visible), "No invented objective0 image");
Reject(() => hud.Update(source, 1, true, false), "Missing final ranges");
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 })));
Reject(() => new SceneHud(source,path), "Bad canvas dimensions");
File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, e.width, e.height, path=e.id==120 ? "../outside.rgba" : e.path })));
Reject(() => new SceneHud(source,path), "Escaping texture path");
File.WriteAllText(path, Manifest(entries.Concat(entries.Take(1))));
Reject(() => new SceneHud(source,path), "Unbounded texture count");
if (args.Length == 1)
{
var originalHud = new SceneHud(source, args[0]);
originalHud.Update(originalHud.Mesh,1,true,true);
Check(originalHud.Mesh.Textures.Values.Any(p=>p.Rgba.Any(v=>v!=0)), "Actual original RGBA loaded");
}
Console.WriteLine("PASS original UI geometry/visibility/final buffer and bounded prepared manifest checks");
}
finally { Directory.Delete(temp,true); }
static void Check(bool value,string message) { if(!value)throw new Exception(message); }
static void Near(Vector3 a,Vector3 b,string message) => Check(Vector3.Distance(a,b)<.00001f,message);
static void Reject(Action action,string message)
{
try { action(); }
catch (Exception e) when (e is InvalidDataException or ArgumentException) { return; }
throw new Exception("Accepted invalid input: " + message);
}
+50
View File
@@ -0,0 +1,50 @@
"""Original UI extraction regressions; stdlib only, no original writes."""
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from omt import Database, FormatError, read_canvas
from ui import export_ui
class UiTests(unittest.TestCase):
def test_original_canvases_and_hashes(self):
original = ROOT.parent / 'Original'
screens = Database(original / 'omt' / 'screens.omt')
alpha = Database(original / 'alpha.omt')
before = [hashlib.sha256(db.path.read_bytes()).hexdigest() for db in (screens, alpha)]
with tempfile.TemporaryDirectory() as target:
output = Path(target) / 'ui'
result = export_ui(screens, output, alpha)
self.assertEqual(8, len(result['textures']))
self.assertEqual([120,121,122,156,169,83,84,85], [t['id'] for t in result['textures']])
for entry in result['textures']:
database = alpha if entry['source'] == 'alpha.omt' else screens
raw = next(e for e in database.entries if e.type == 'Canv' and e.id == entry['id'])
rgba = read_canvas(database.payload(raw))['rgba']
self.assertEqual(rgba, (output / entry['path']).read_bytes())
self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256'])
self.assertEqual(result, json.loads((output / 'ui.json').read_text()))
self.assertEqual(before, [hashlib.sha256(db.path.read_bytes()).hexdigest() for db in (screens, alpha)])
def test_missing_canvas_and_original_output_rejected(self):
original = ROOT.parent / 'Original'
screens = Database(original / 'omt' / 'screens.omt')
alpha = Database(original / 'alpha.omt')
with self.assertRaises(ValueError):
export_ui(screens, screens.path.parent / 'generated', alpha)
screens.entries = [e for e in screens.entries if e.id != 120]
with tempfile.TemporaryDirectory() as target:
output = Path(target) / 'ui'
with self.assertRaises(FormatError):
export_ui(screens, output, alpha)
self.assertFalse(output.exists(), 'Validate identities before creating output')
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,18 @@
<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/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/SceneInteractions.cs"/>
<Compile Include="../../src/GamePort/Game/SceneInventory.cs"/>
<Compile Include="../../src/GamePort/Game/SceneDirector.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs"/>
</ItemGroup>
</Project>
+201
View File
@@ -0,0 +1,201 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var original = OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var lab = GamLevel.Load(AssetPath.Resolve(root, "gam/level1b.gam"));
var counter = 1;
var tasks = new TaskStates(original.Tasks);
var director = new SceneDirector(lab, tasks, (_, _) => 5);
var interactions = new SceneInteractions(director, tasks, original, lab.Code);
director.Begin(lab.FindStart()!);
interactions.Reset();
director.Skip();
Check(tasks.Get("SCENE") == 30 && director.Controlled, "Intro cannot invent lab completion");
var explanation = lab.Entities.Single(e => e.Tag == "teleportexplanation");
director.Touch("JIM1", explanation.Position);
Check(tasks.Get("SCENE") == 35 && interactions.CurrentObjective == 1, "Original explanation enables objective1/task35");
director.Skip();
var shrinkray = director.FindActor("shrinkray")!;
var checkpoint = Vector3.Zero;
var help = -1;
var selected = -1;
var events = new List<string>();
interactions.CheckpointCaptured += p => { checkpoint = p; events.Add("checkpoint"); };
tasks.Assigned += (name, state) => { if (name == "SCENE" && state == 50) events.Add("task50"); };
interactions.PracticeRequested += page => { help = page; events.Add("help"); };
interactions.Inventory.GadgetSelected += gadget => { selected = gadget; events.Add("gadget"); };
interactions.Collected += (_, points) => events.Add("score" + points);
interactions.Update(shrinkray.Position);
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(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(interactions.Snapshot().ItemStates[301] == 1 && interactions.CurrentObjective == 2, "Acquired state and objective2 persist");
interactions.Update(shrinkray.Position);
Check(interactions.Score == 50 && events.Count == 5, "Repeated overlap cannot recollect");
Console.WriteLine("PASS source intro/explanation/shrinkray state, inventory and event ordering");
var carl = director.FindActor("C3DCARL")!;
Check(carl.Position == director.FindActor("CARLESC3")!.Position && carl.AIstate == 6, "Carl task callback positions state6 at authored marker");
var talkStarted = 0;
var taskAtSpeech = -1;
var scoreAtSpeech = -1;
director.Speech += (_, _) => { taskAtSpeech = tasks.Get("SCENE"); scoreAtSpeech = interactions.Score; };
interactions.ConversationStarted += (_, tag) => { talkStarted++; Check(tag == "neutron1a", "Authored TalkTrigger0"); };
director.SyncActor("JIM1", carl.Position, Vector3.Zero);
interactions.Update(carl.Position);
Check(taskAtSpeech == 60 && scoreAtSpeech == 150, "Carl callback runs before dialogue starts");
Check(tasks.Get("SCENE") == 60 && carl.AIstate == 9 && talkStarted == 1, "Carl ends dispatcher in state9 with scene60");
for (var i = 0; i < 10; i++) interactions.Update(carl.Position);
Check(interactions.Score == 150 && talkStarted == 1, "Talk does not repeat on contact stay");
Check(interactions.CurrentObjective == 3, "Carl transition selects objective3");
director.Skip();
LevelTransition? transition = null;
interactions.Transition += request => transition = request;
var exit = lab.Entities.Single(e => e.Tag == "LABTONEIGH");
interactions.Update(exit.Position);
Check(transition?.LevelFile == "level1.gam" && transition.StartPoint == "level1",
$"Original lab exit task60 gate opens: request={transition}; controlled={director.Controlled}; blocked={director.Blocked}; tag={director.CurrentTag}");
Console.WriteLine("PASS source Carl contact/callback/dialogue/task60 and original lab exit gate");
var snapshot = interactions.Snapshot();
var decoded = OriginalSave.Parse(snapshot.Encode());
Check(decoded.InventoryStates[3] == 1 && decoded.ItemStates[301] == 1 && decoded.Score == 150 && decoded.OtherCounter == 3,
"Original TSK serializes acquired gadget, score and objective selector");
Check(decoded.StoredVector == original.StoredVector, "Unknown saved vector is not overwritten by inferred checkpoint data");
var restoredTasks = new TaskStates(decoded.Tasks);
var restoredDirector = new SceneDirector(lab, restoredTasks, (_, _) => 5);
var restored = new SceneInteractions(restoredDirector, restoredTasks, decoded, lab.Code);
restoredDirector.Begin(lab.FindStart()!); restored.Reset(); restoredDirector.Skip();
Check(!restoredDirector.FindActor("shrinkray")!.Active && restored.Inventory.State(0, 3) == 1, "Resume retains collected shrinkray/inventory");
restored.Update(restoredDirector.FindActor("shrinkray")!.Position);
Check(restored.Score == 150, "Resume cannot award shrinkray twice");
Console.WriteLine("PASS original-format save/resume retains gadget and objective state");
// The source permits collection at other task values, but its special shrinkray
// hook only grants the gadget when SCENE==35. Preserve that awkward boundary.
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 boundaryDirector = new SceneDirector(lab, boundaryTasks, (_, _) => 1);
var boundary = new SceneInteractions(boundaryDirector, boundaryTasks, original, lab.Code);
boundary.Update(boundaryDirector.FindActor("shrinkray")!.Position);
Check(boundaryTasks.Get("SCENE") == state && boundary.Inventory.State(0, 3) == 0 && boundary.Score == 50,
"Shrinkray special effect exact task35 gate, ordinary score remains");
}
Console.WriteLine("PASS exact shrinkray task gate without invented progression");
var body = Entity("3JIM", "jim");
var camera0 = Entity("3CAM", "first", ("CameraTarget", "jim"), ("SoundDatabase", "voice"), ("SoundIndex", 1));
var camera1 = Entity("3CAM", "fallback", ("CameraTarget", "jim"), ("SoundDatabase", "voice"), ("SoundIndex", 2));
foreach (var talkState in new[] { -1, -2, 50, 49 })
{
var friend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", talkState), ("TalkTrigger0", "missing"),
("TalkState1", talkState), ("TalkTrigger1", "first"),
("TalkState2", -2), ("TalkTrigger2", "fallback"));
var testTasks = new TaskStates([new("SCENE", 50)]);
var testDirector = new SceneDirector(new("TEST", [body, friend, camera0, camera1]), testTasks, (_, _) => 5);
var test = new SceneInteractions(testDirector, testTasks, original, "TEST");
test.Update(Vector3.Zero);
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");
}
var noneFriend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", 49), ("TalkTrigger0", "first"));
var noTasks = new TaskStates([new("SCENE", 50)]);
var noDirector = new SceneDirector(new("TEST", [body, noneFriend, camera0]), noTasks, (_, _) => 5);
var noTalk = new SceneInteractions(noDirector, noTasks, original, "TEST");
noTalk.Update(Vector3.Zero);
Check(noTasks.Get("SCENE") == 50 && noTalk.Score == 0 && noDirector.FindActor("friend")!.AIstate == 0,
"No matching talk target leaves state0 without award/task mutation");
Console.WriteLine("PASS talk lookup order, missing/disabled/wildcard states and no-match behavior");
foreach (var distance in new[] { 160f, 159.5f })
{
var friend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", 50), ("TalkTrigger0", "first"));
var edgeTasks = new TaskStates([new("SCENE", 50)]);
var edgeDirector = new SceneDirector(new("TEST", [body, friend, camera0]), edgeTasks, (_, _) => 5);
var edge = new SceneInteractions(edgeDirector, edgeTasks, original, "TEST");
edge.Update(new(distance, 0, 0));
Check(edge.Score == (distance < 160 ? 100 : 0), "Strict original sum-radius Carl contact boundary");
}
var waiting = new SceneDirector(lab, new TaskStates(original.Tasks), (_, _) => 5);
waiting.Begin(lab.FindStart()!);
var locked = new SceneInteractions(waiting, new TaskStates(original.Tasks), original, lab.Code);
locked.Update(waiting.FindActor("shrinkray")!.Position);
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");
var inventoryRaw = Enumerable.Range(0, 19).Select(i => i == 18 ? int.MinValue : i * 10).ToArray();
var inventory = new SceneInventory(inventoryRaw);
inventoryRaw[3] = 999;
Check(inventory.State(0, 3) == 30 && inventory.State(1, 9) == int.MinValue, "Owned inventory copy preserves unknown signed wire values");
var inventoryCopy = inventory.Snapshot(); inventoryCopy[3] = 888;
Check(inventory.State(0, 3) == 30, "Snapshot owns its storage");
Throws(() => inventory.State(2, 0)); Throws(() => inventory.State(0, 9));
inventory.SetState(0, 3, 0); Throws(() => inventory.SelectGadget(3));
inventory.SetState(0, 3, 1); inventory.SelectGadget(3); Check(inventory.SelectedGadget == 3, "Owned gadget selection");
Console.WriteLine("PASS inventory bounds, ownership, unknown-state preservation and gadget availability");
// Independently recover the original SCENE setter's two dispatch tables rather
// than testing the port's switch against another manually copied switch.
var exe = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe"));
foreach (var (address, expected) in new (int, string)[] {
(0x435fcb, "e800060000"), //Contact invokes special hook before score.
(0x4365fa, "83f823"), //Exact task35.
(0x43663e, "6a016a036a00"), //Inventory group0,item3,state1.
(0x436649, "6a00e84009fdff"), //Help page0.
(0x43667c, "6a03ff9274010000"), //Jimmy gadget3.
(0x413e2f, "680000c842"), //Carl radius100.
(0x40a676, "83be0806000006"), //Carl inherited contact requires state6.
(0x41b7cd, "ff9280010000"), //Derived award before selected trigger.
(0x41b813, "6a64e8a6f50000"), //Base friend awards100.
(0x41b7f0, "c786c806000009000000"), //Talk dispatcher ends in state9.
(0x458880, "8b442404898194040000c20400"), //LOAD task hook only stores value.
})
Check(exe.AsSpan(address - 0x400000, expected.Length / 2).SequenceEqual(Convert.FromHexString(expected)),
"Original interaction instruction evidence at" + address.ToString("X"));
int U32(int address) => BinaryPrimitives.ReadInt32LittleEndian(exe.AsSpan(address - 0x400000, 4));
int ExpectedObjective(int state)
{
int target;
if (state is >= 35 and <= 280) target = U32(0x45fbf0 + 4 * exe[0x45fc48 + state - 35 - 0x400000]);
else if (state == 290) target = 0x45fab6;
else if (state is >= 300 and <= 550) target = U32(0x45fd40 + 4 * exe[0x45fd98 + state - 300 - 0x400000]);
else return 0;
var offset = target - 0x400000;
return exe[offset] == 0x6a && exe[offset + 1] == 1 && exe[offset + 2] == 0x6a ? exe[offset + 3] : 0;
}
for (var state = -1; state <= 600; state++)
Check(SceneInteractions.ObjectiveForScene(state) == ExpectedObjective(state), "Objective map agrees with original jump tables at state" + state);
Console.WriteLine("PASS all SCENE objective milestones against original executable dispatch tables");
void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
void Throws(Action action)
{
try { action(); } catch (ArgumentOutOfRangeException) { return; }
throw new Exception("Expected bounded inventory rejection");
}
GamEntity Entity(string kind, string tag, params (string Name, object Value)[] properties)
{
var values = new Dictionary<string, GamProperty> { ["ObjectTag"] = new("ObjectTag", 1, Encoding.Latin1.GetBytes(tag)) };
foreach (var (name, value) in properties)
{
if (value is string text) values[name] = new(name, 1, Encoding.Latin1.GetBytes(text));
else
{
var bytes = new byte[4];
BinaryPrimitives.WriteInt32BigEndian(bytes, value is float number ? BitConverter.SingleToInt32Bits(number) : (int)value);
values[name] = new(name, value is float ? 3u : 6u, bytes);
}
}
// Distinct source offsets retain duplicate-tag contacts independently.
return new(kind, counter++ * 100, values, []);
}
@@ -0,0 +1,11 @@
<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/JetpackBurst.cs" Link="JetpackBurst.cs" />
</ItemGroup>
</Project>
+189
View File
@@ -0,0 +1,189 @@
using GamePort.Game;
var count = 0;
void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
}
void Near(float actual, float expected, string message) =>
Check(MathF.Abs(actual - expected) < .0002f, $"{message}: {actual} != {expected}");
void Test(string name, Action action)
{
action();
count++;
Console.WriteLine($"PASS {name}");
}
JetpackBurstInput Input(bool ground = false, bool held = true, float vy = 20,
float distance = 100, int inventory = 1, float energy = 100, string level = "LV1B",
int mode = -1, float dt = .1f, float extra = -264) =>
new(ground, held, vy, distance, inventory, energy, level, mode, dt, extra);
Test("ordinary jump, release and renewed hold", () =>
{
var first = JetpackBurst.Step(new(), Input(ground: true));
Check(first.State.JumpState == 1 && first.State.HoldSeconds == 0, "ordinary takeoff state");
Check(first.Pose == JetpackPose.Jump && first.ImpulseY == 550 && first.VelocityYOverride is null,
"550 queued impulse selects JUMP");
Near(first.ExtraAccelerationY - 800, -1064, "ballistic net acceleration");
var released = JetpackBurst.Step(first.State, Input(held: false));
Check(released.State.JumpState == 2 && released.ImpulseY == 0, "release arms refire");
var refired = JetpackBurst.Step(released.State, Input(dt: 0));
Check(refired.State.JumpState == 3 && refired.State.EffectRemaining == 8, "refire needs no new .4 delay");
Check(refired.Pose == JetpackPose.Fly && refired.VelocityYOverride == 10
&& refired.RadiusOverride == 100 && refired.StartGadget, "powered start commands");
Near(refired.ExtraAccelerationY, first.ExtraAccelerationY, "start invocation remains ballistic");
});
Test("hold is strictly greater than .4 seconds", () =>
{
var state = new JetpackBurstState(1);
state = JetpackBurst.Step(state, Input(dt: .2f)).State;
state = JetpackBurst.Step(state, Input(dt: .2f)).State;
Check(state.JumpState == 1 && state.EffectRemaining == 0, "exactly .4 does not start");
var started = JetpackBurst.Step(state, Input(dt: .001f));
Check(started.StartGadget && started.State.EffectRemaining == 8, "more than .4 starts");
});
Test("disabled long hold stays ballistic and can jump on landing", () =>
{
var denied = JetpackBurst.Step(new(1, .4f), Input(inventory: 0));
Check(denied.State.JumpState == 3 && denied.Pose == JetpackPose.None
&& denied.VelocityYOverride is null && denied.State.EffectRemaining == 0, "disabled transition only enters3");
var expired = JetpackBurst.Step(denied.State, Input(extra: -271));
Check(expired.State.JumpState == 0 && expired.Pose == JetpackPose.Fall
&& expired.ExtraAccelerationY == -271 && expired.StopGadget, "expired guard preserves external acceleration");
var landed = JetpackBurst.Step(expired.State, Input(ground: true, inventory: 0));
Check(landed.ImpulseY == 550 && landed.State.JumpState == 1, "held unavailable gadget repeats ordinary jump");
});
Test("all blocked levels and gadget modes plus VR04 override", () =>
{
foreach (var level in new[] { "LEV6", "LV4B", "LV6A", "LEV3", "LV3A", "LV3B", "LV3C", "LV3D" })
Check(!JetpackBurst.CanStart(level, -1, 1, 100), $"level {level}");
foreach (var mode in new[] { 2, 6, 7 }) Check(!JetpackBurst.CanStart("LV1B", mode, 1, 100), $"mode {mode}");
Check(!JetpackBurst.CanStart("LV1B", -1, 1, 0), "zero energy");
Check(!JetpackBurst.CanStart("LV1B", -1, 4, 100), "inventory state4");
Check(JetpackBurst.CanStart("VR04", 7, 0, -1), "VR04 bypasses every availability gate");
Check(JetpackBurst.CanStart("LV1B", -1, 2, 100), "inventory state2 is accepted");
});
Test("powered distance and vertical-speed thresholds", () =>
{
var state = new JetpackBurstState(3, .5f, 8);
Near(JetpackBurst.Step(state, Input(vy: -1)).ExtraAccelerationY - 800, 80, "exact -1 uses near hover");
Near(JetpackBurst.Step(state, Input(vy: -1.001f)).ExtraAccelerationY - 800, 240, "descending boost");
Near(JetpackBurst.Step(state, Input(distance: 499.999f)).ExtraAccelerationY - 800, 80, "below500");
Near(JetpackBurst.Step(state, Input(distance: 500)).ExtraAccelerationY - 800, -80, "exact500");
Near(JetpackBurst.Step(state, Input(distance: 800, vy: -40)).ExtraAccelerationY - 800, -80, "far distance wins");
});
Test("airborne release stops without radius reset and preserves transition acceleration", () =>
{
var stopped = JetpackBurst.Step(new(3, .5f, 7), Input(held: false));
Check(stopped.State.JumpState == 4 && stopped.State.EffectRemaining == 0
&& stopped.Pose == JetpackPose.Fall && stopped.RadiusOverride is null && stopped.StopGadget,
"air release stop commands");
Near(stopped.ExtraAccelerationY, 880, "release invocation still powered");
var reset = JetpackBurst.Step(stopped.State, Input(held: false, extra: stopped.ExtraAccelerationY));
Check(reset.State.JumpState == 0, "expired state4 resets");
Near(reset.ExtraAccelerationY, 880, "expired guard preserves last powered acceleration");
var ordinary = JetpackBurst.Step(reset.State, Input(held: false, extra: reset.ExtraAccelerationY));
Near(ordinary.ExtraAccelerationY, -264, "next state0 invocation becomes ballistic");
});
Test("held landing stops effect and restores radius60", () =>
{
var stopped = JetpackBurst.Step(new(3, .5f, 7), Input(ground: true));
Check(stopped.State.JumpState == 4 && stopped.State.EffectRemaining == 0
&& stopped.RadiusOverride == 60 && stopped.MovementModeOverride == 1, "held landing commands");
var releasedGround = JetpackBurst.Step(new(3, .5f, 7), Input(ground: true, held: false, extra: 800));
Check(releasedGround.State.JumpState == 0 && releasedGround.State.EffectRemaining == 7
&& releasedGround.RadiusOverride is null && releasedGround.MovementModeOverride == 0,
"outer grounded release precedes air handler");
Near(releasedGround.ExtraAccelerationY, 800, "ground apply owns acceleration");
});
Test("effect subtracts before visibility and energy drain", () =>
{
var effect = JetpackBurst.StepEffect(new(3, 0, .1f), false, .1f, 90, "LV1B");
Check(effect.State.EffectRemaining == 0 && !effect.Visible && effect.Energy == 90,
"exact expiry does not drain");
effect = JetpackBurst.StepEffect(new(3, 0, .1f), false, .2f, 90, "LV1B");
Near(effect.State.EffectRemaining, -.1f, "negative timer is retained");
Check(!effect.Visible && effect.Energy == 90, "overshoot does not drain partial interval");
effect = JetpackBurst.StepEffect(new(3, 0, 8), false, .2f, 90, "LV1B");
Check(effect.Visible, "positive post-subtraction timer shows effect");
Near(effect.State.EffectRemaining, 7.8f, "active remaining");
Near(effect.Energy, 89.9f, ".5 energy per second");
});
Test("grounded effect resets then stores negative dt", () =>
{
var effect = JetpackBurst.StepEffect(new(3, 0, 8), true, .2f, 90, "LV1B");
Near(effect.State.EffectRemaining, -.2f, "grounded timer");
Check(!effect.Visible && effect.Energy == 90, "grounded effect no drain");
effect = JetpackBurst.StepEffect(effect.State, true, .3f, effect.Energy, "LV1B");
Near(effect.State.EffectRemaining, -.3f, "grounded reset happens each invocation");
});
Test("energy clamps and VR01 through VR08 preserve energy", () =>
{
Near(JetpackBurst.AdjustEnergy(.1f, -1, "LV1B"), 0, "lower clamp");
Near(JetpackBurst.AdjustEnergy(99, 5, "LV1B"), 100, "upper clamp");
for (var i = 1; i <= 8; i++)
{
var effect = JetpackBurst.StepEffect(new(3, 0, 8), false, .2f, 90, $"VR0{i}");
Check(effect.Visible && effect.Energy == 90, $"VR0{i} timer runs but energy is immune");
}
Near(JetpackBurst.AdjustEnergy(50, -2, "VR09"), 48, "VR09 outside numeric range");
Near(JetpackBurst.AdjustEnergy(50, -2, "VR00"), 48, "VR00 outside numeric range");
});
Test("energy depletion does not cancel active burn", () =>
{
var effect = JetpackBurst.StepEffect(new(3, .5f, 8), false, 1, .1f, "LV1B");
Check(effect.Energy == 0 && effect.Visible && effect.State.EffectRemaining == 7, "depletion leaves timer active");
var control = JetpackBurst.Step(effect.State, Input(energy: effect.Energy));
Check(control.State.JumpState == 3 && !control.StopGadget, "availability is checked only on start");
Near(control.ExtraAccelerationY, 880, "burn continues at zero energy");
});
Test("explicit phase ordering exposes first-tick timer difference", () =>
{
var initial = new JetpackBurstState(2);
var before = JetpackBurst.StepEffect(initial, false, .1f, 100, "LV1B");
var effectFirst = JetpackBurst.Step(before.State, Input(energy: before.Energy));
var controlFirst = JetpackBurst.Step(initial, Input());
var after = JetpackBurst.StepEffect(controlFirst.State, false, .1f, 100, "LV1B");
Check(effectFirst.State.EffectRemaining == 8 && before.Energy == 100, "effect-first start");
Near(after.State.EffectRemaining, 7.9f, "controller-first start");
Near(after.Energy, 99.95f, "controller-first drain");
});
Test("null effect bypasses expiry and does not assign radius or timer", () =>
{
var start = JetpackBurst.Step(new(2), Input() with { EffectAvailable = false });
Check(start.StartGadget && start.Pose == JetpackPose.Fly && start.VelocityYOverride == 10
&& start.RadiusOverride is null && start.State.EffectRemaining == 0, "null-effect start boundary");
var flying = JetpackBurst.Step(start.State, Input() with { EffectAvailable = false });
Check(flying.State.JumpState == 3, "no expiry guard for null pointer");
Near(flying.ExtraAccelerationY, 880, "null-effect powered branch");
var absentOwner = JetpackBurst.StepEffect(new(3, 0, 8), false, .1f, 50, "LV1B", ownerAvailable: false);
Check(absentOwner.State.EffectRemaining == 8 && absentOwner.Energy == 50, "absent owner leaves fields");
});
Test("bounded inputs reject invalid state, time and nonfinite values", () =>
{
void Throws(Action action)
{
try { action(); }
catch (ArgumentException) { return; }
throw new Exception("invalid input was accepted");
}
Throws(() => JetpackBurst.Step(new(6), Input()));
Throws(() => JetpackBurst.Step(new(), Input(dt: -1)));
Throws(() => JetpackBurst.Step(new(), Input(vy: float.NaN)));
Throws(() => JetpackBurst.StepEffect(new(), false, float.PositiveInfinity, 100, "LV1B"));
});
Console.WriteLine($"Jetpack checks passed: {count}");
@@ -0,0 +1,22 @@
<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/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/ActorPatrol.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs"/>
<Compile Include="../../src/GamePort/Game/SceneDirector.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
<Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs"/>
</ItemGroup>
</Project>
+255
View File
@@ -0,0 +1,255 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
{
var inputs = new List<Vector3>();
var rig = Rig([Point("A", new(500, 0, 0), "none")], body: (state, dt) =>
{
inputs.Add(state.Velocity);
return FreeBody(state, dt);
});
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, Vector3.Zero, "First step must consume initial zero velocity");
Near(rig.Patrol.Velocity, new(100, 0, 0), "Next velocity selected after body step");
NearFloat(rig.Actor.Rotation.Y, 0, "First step consumes prior heading");
Check(rig.Actor.Animation == "RUN", "State3 replaces authored walk with Goddard RUN");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "Second step consumes preceding velocity");
NearFloat(rig.Actor.Rotation.Y, -28.8f, "Prior target yaw smoothed by3.2*dt");
Check(inputs.Count == 2 && inputs[0] == Vector3.Zero && inputs[1] == new Vector3(100, 0, 0), "Body integration phase order");
Pass("prior velocity and prior desired-yaw phase, recovered RUN selection");
}
{
var rig = Rig([Point("A", new(50, 0, 0), "B"), Point("B", new(1000, 0, 0), "none")]);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived && rig.Patrol.CurrentWaypoint == "B", "Arrival selects next waypoint once");
Near(rig.Actor.Position, Vector3.Zero, "Arrival must not snap to waypoint");
Near(rig.Patrol.Velocity, new(100, 0, 0), "First arrival retains velocity selected before flag");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "Prior arrival velocity remains for next physical step");
Check(!rig.Patrol.Arrived && rig.Patrol.Velocity == Vector3.Zero && rig.Actor.Animation == "WAG", "Old arrival selects zero/WAG before new distance clears it");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "One-tick pause must remain");
Near(rig.Patrol.Velocity, new(100, 0, 0), "Subsequent update resumes next segment");
Pass("velocity-before-arrival, no snap and the original waypoint-change pause");
}
{
var rig = Rig([Point("A", new(110, 0, 0), "A")], body: HoldBody);
rig.Patrol.Step(.1f);
Check(!rig.Patrol.Arrived, "Initial distance exactly110 must not arrive");
rig.Director.FindActor("A")!.Position = new(109, 0, 0);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived, "Strictly below110 arrives");
rig.Director.FindActor("A")!.Position = new(110, 0, 0);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived, "Exactly110 retains an already-set arrival flag");
rig.Director.FindActor("A")!.Position = new(111, 0, 0);
rig.Patrol.Step(.1f);
Check(!rig.Patrol.Arrived, "Strictly above110 clears arrival");
Pass("strict arrival threshold and equality hysteresis");
}
{
var rig = Rig([Point("A", Vector3.Zero, "B", .25f, "SIT"), Point("B", new(1000, 0, 0), "none")]);
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == 7 && rig.Patrol.WaitRemaining == .25f && rig.Actor.Animation == "SIT", "Wait starts with full authored time after arrival");
rig.Patrol.Step(.125f);
Check(rig.Actor.AIstate == 7 && rig.Patrol.WaitRemaining == .125f, "Positive wait remains active");
rig.Patrol.Step(.125f);
Check(rig.Actor.AIstate == 3 && rig.Patrol.WaitRemaining == 0 && rig.Patrol.CurrentWaypoint == "B" && !rig.Patrol.Arrived,
"Timer reaching exactly zero expires and restores state3");
Near(rig.Actor.Position, Vector3.Zero, "Wait expiry must not consume extra movement");
Near(rig.Patrol.Velocity, Vector3.Zero, "Wait expiry selects waypoint without selecting its velocity yet");
rig.Patrol.Step(.1f);
Check(rig.Patrol.Velocity.Length() > 0 && rig.Actor.Position == Vector3.Zero, "First resumed update still consumes preceding zero velocity");
var overshoot = Rig([Point("A", Vector3.Zero, "B", .125f, "SIT"), Point("B", new(1000, 0, 0), "none")]);
overshoot.Patrol.Step(.5f);
overshoot.Patrol.Step(.5f);
Check(overshoot.Actor.AIstate == 3 && overshoot.Patrol.WaitRemaining == -.375f && overshoot.Actor.Position == Vector3.Zero,
"Wait expiry discards elapsed remainder rather than advancing next segment");
var zeroAtEntry = Rig([Point("A", Vector3.Zero, "none")], state: 7);
zeroAtEntry.Patrol.Step(.1f);
Check(zeroAtEntry.Actor.AIstate == 7, "Original state7 positivity guard retains zero-at-entry timer");
Pass("timed wait, exact-zero expiry, zero-entry guard and discarded remainder");
}
{
foreach (var (next, expectedState) in new[] { ("wAiT", 1), ("sCaN", 6), ("none", 3), ("missing", 3) })
{
var rig = Rig([Point("A", Vector3.Zero, next)], body: HoldBody);
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == expectedState && rig.Patrol.CurrentWaypoint == null, "Unresolved next-name semantics: " + next);
if (expectedState == 3)
{
rig.Patrol.Step(.1f);
Check(rig.Patrol.PreviousWaypoint == "A" && rig.Patrol.Arrived, "Ordinary missing next names restart initial route");
}
}
var realWaitTag = Rig([Point("A", Vector3.Zero, "WAIT"), Point("WAIT", new(1000, 0, 0), "none")]);
realWaitTag.Patrol.Step(.1f);
Check(realWaitTag.Actor.AIstate == 3 && realWaitTag.Patrol.CurrentWaypoint == "WAIT", "Existing actor tag takes precedence over WAIT specialcase");
var timedWaitName = Rig([Point("A", Vector3.Zero, "WAIT", .25f, "SIT")]);
timedWaitName.Patrol.Step(.1f);
timedWaitName.Patrol.Step(.25f);
Check(timedWaitName.Actor.AIstate == 3 && timedWaitName.Patrol.CurrentWaypoint == null, "Timed wait resolution does not interpret WAIT specially");
Pass("WAIT/SCAN lookup precedence, unresolved-none route restart and timed-wait distinction");
}
{
var rig = Rig([Point("A", new(0, 500, 0), "none")], body: (body, _) => body with { Velocity = new(5, -7, 9) }, initial: "missing");
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == 1, "Missing initial waypoint enters waiting state1");
Near(rig.Patrol.Velocity, new(0, -7, 0), "Missing initial waypoint preserves Y and clears XZ");
rig.Patrol.Step(.1f);
Near(rig.Patrol.Velocity, Vector3.Zero, "Ordinary state1 clears XYZ after body callback");
var vertical = Rig([Point("A", new(0, 500, 0), "none")]);
vertical.Patrol.Step(.1f);
Near(vertical.Patrol.Velocity, new(0, 100, 0), "Patrol selects fullXYZ velocity rather than retaining body Y");
Pass("missing initial waypoint preserves Y for its transition; ordinary waiting and fullXYZ patrol");
}
{
var rig = Rig([Point("A", new(500, 0, 0), "none")]);
rig.Patrol.Step(.1f);
rig.Patrol.Step(.1f);
var before = rig.Patrol.Velocity;
rig.Actor.Animation = "SIT";
rig.Patrol.SynchronizeAuthoredState();
Check(rig.Patrol.Velocity == before && rig.Patrol.CurrentWaypoint == "A", "Camera-only animation cannot reset body/route");
rig.Actor.Position = new(400, 50, -20);
rig.Actor.Rotation = new(0, 10, 0);
rig.Actor.AIstate = 1;
rig.Actor.Animation = "SIT";
rig.Patrol.SynchronizeAuthoredState();
Check(rig.Patrol.Velocity == Vector3.Zero && rig.Patrol.CurrentWaypoint == null && !rig.Patrol.Arrived,
"Authored teleport resets port motion and route cache");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(400, 50, -20), "Teleport cannot inherit preceding patrol velocity");
NearFloat(rig.Actor.Rotation.Y, 10, "Teleport authored heading retained");
Check(rig.Actor.Animation == "SIT", "Authored state1 SIT retained");
Pass("authored teleport reset and camera-only animation preservation");
}
{
var rig = Rig([Point("A", new(300, 400, 0), "none")], body: HoldBody, magnitude: _ => 1000);
rig.Patrol.Step(.1f);
Near(rig.Patrol.Velocity, new(30, 40, 0), "Injected original magnitude controls normalization");
NearFloat(rig.Patrol.DestinationDistance, 500, "Arrival still uses exact sqrt rather than injected magnitude");
foreach (var dt in new[] { -1f, float.NaN, float.PositiveInfinity, 1.01f })
{
var threw = false;
try { rig.Patrol.Step(dt); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "Invalid dt rejected");
}
rig.Actor.Active = false;
var inactive = rig.Actor.Position;
rig.Patrol.Step(.5f);
Check(rig.Actor.Position == inactive, "Inactive actor must not update");
rig.Actor.Active = true;
rig.Actor.AIstate = 6;
Check(!rig.Patrol.Step(.1f), "Unrecovered scan state reported unsupported");
Pass("injected magnitude remains separate from arrival metric; bounded inactive/unsupported state handling");
}
{
var level = GamLevel.Load(AssetPath.Resolve(original, "gam/level1b.gam"));
var director = new SceneDirector(level, new TaskStates([]), (_, _) => 10);
var actor = director.FindActor("C3DGODDARD")!;
director.Trigger("SITGODDARD", "LABEXP1");
var patrol = new ActorPatrol(actor, director.FindActor, FreeBody);
var sawAuthoredSit = false;
director.ActorChanged += changed =>
{
if (!ReferenceEquals(actor, changed)) return;
sawAuthoredSit |= actor.AIstate == 1 && actor.Animation.Equals("sit", StringComparison.OrdinalIgnoreCase);
patrol.SynchronizeAuthoredState();
};
director.Trigger("GOGODDARD", "GOCARL");
Check(actor.AIstate == 3 && actor.Speed == 260 && actor.Patrol == "GODDARDPAT1", "Original authored patrol input");
var start = actor.Position;
patrol.Step(1 / 60f);
Check(actor.Position == start && actor.Animation == "RUN", "Real route begins after velocity selection; source RUN alias");
var sawSecond = false;
var sawUnresolvedNone = false;
for (var i = 0; i < 800; i++)
{
patrol.Step(1 / 60f);
sawSecond |= patrol.CurrentWaypoint == "GODDARDPAT2";
sawUnresolvedNone |= sawSecond && patrol.CurrentWaypoint == null && actor.AIstate == 3;
Check(float.IsFinite(actor.Position.X + actor.Position.Y + actor.Position.Z), "Finite real route state");
}
Check(sawSecond && sawUnresolvedNone, "Real lab route traverses both points and reaches unresolved-none restart");
director.Trigger("GODDARDDIS", "TELGODDARD");
var destination = director.FindActor("phone2")!.Position;
Check(actor.Position == destination && actor.AIstate == 1 && sawAuthoredSit,
"Original authored patrol interruption must precede the following camera's TALK action");
patrol.Step(1 / 60f);
Check(actor.Position == destination && patrol.Velocity == Vector3.Zero, "Authored phone teleport stops port patrol motion");
Pass("actual lab patrol route and source GODDARDDIS interruption (free-body algorithm test)");
}
{
var carl = Entity("3CAR", "carl", ("AIState", 3), ("PatrolPoint", "A"));
var point = Point("A", new(1000, 0, 0), "WAIT");
var director = new SceneDirector(new("TEST", [carl, point]), new TaskStates([]), (_, _) => 1);
var actor = director.FindActor("carl")!;
Check(actor.Speed == 200, "Carl constructor speed200 is independent of Goddard defaults");
var patrol = new ActorPatrol(actor, director.FindActor, FreeBody);
patrol.Step(.1f);
Check(actor.Animation == "WALK" && actor.Position == Vector3.Zero, "Carl uses WALK with the same prior-velocity phase");
patrol.Step(.1f);
Near(actor.Position, new(20,0,0), "Carl source speed and body phase");
NearFloat(actor.Rotation.Y, -27, "Carl inherited yaw factor3 differs from Goddard3.2");
actor.AIstate = 9;
Check(patrol.Step(.1f), "State9 retains the common base phase without an invented patrol command");
Pass("Carl source WALK/STOP profile, speed200, inherited yaw factor and common state9 phase");
}
Console.WriteLine("All10 actor patrol test groups passed. Free/held body fixtures validate AI order, not original collision fidelity.");
static (SceneDirector Director, DirectorActor Actor, ActorPatrol Patrol) Rig(GamEntity[] points,
Func<PatrolBodyState, float, PatrolBodyState>? body = null, int state = 3, string initial = "A",
Func<Vector3, float>? magnitude = null)
{
var god = Entity("3DOG", "god", ("AIState", state), ("PatrolPoint", initial));
var director = new SceneDirector(new("TEST", new[] { god }.Concat(points).ToArray()), new TaskStates([]), (_, _) => 1);
var actor = director.FindActor("god")!;
actor.Speed = 100;
actor.Animation = "walk";
return (director, actor, new(actor, director.FindActor, body ?? FreeBody, magnitude));
}
static PatrolBodyState FreeBody(PatrolBodyState state, float dt) => state with { Position = state.Position + state.Velocity * dt };
static PatrolBodyState HoldBody(PatrolBodyState state, float dt) => state;
static GamEntity Point(string tag, Vector3 position, string next, float wait = 0, string waitAnimation = "none") => Entity("3PAT", tag,
("PositionX", position.X), ("PositionY", position.Y), ("PositionZ", position.Z), ("NextPatrolPoint", next), ("WaitTime", wait), ("WaitAnim", waitAnimation));
static GamEntity Entity(string kind, string tag, params (string Name, object Value)[] values)
{
var properties = new Dictionary<string, GamProperty>(StringComparer.Ordinal);
foreach (var (name, value) in new[] { ("ObjectTag", (object)tag) }.Concat(values))
{
uint type;
byte[] raw;
switch (value)
{
case string s: type = 1; raw = Encoding.Latin1.GetBytes(s); break;
case int i: type = 6; raw = new byte[4]; BinaryPrimitives.WriteInt32BigEndian(raw, i); break;
case float f: type = 3; raw = new byte[4]; BinaryPrimitives.WriteInt32BigEndian(raw, BitConverter.SingleToInt32Bits(f)); break;
default: throw new ArgumentException("Unsupported test property");
}
properties.Add(name, new(name, type, raw));
}
return new(kind, 0, properties, new byte[4]);
}
static void Near(Vector3 actual, Vector3 expected, string message) => Check(Vector3.Distance(actual, expected) < .001f, message + $": {actual} != {expected}");
static void NearFloat(float actual, float expected, string message) => Check(MathF.Abs(actual - expected) < .001f, message + $": {actual} != {expected}");
static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); }
static void Pass(string message) => Console.WriteLine("PASS " + message);
@@ -0,0 +1,11 @@
<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/OriginalBodySupport.cs" Link="OriginalBodySupport.cs" />
</ItemGroup>
</Project>
+168
View File
@@ -0,0 +1,168 @@
using System.Numerics;
using System.Text.Json;
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}"); }
SupportTriangle Ground(float height = 0, int id = 1) =>
new(new(-10000, height, -10000), new(10000, height, -10000), new(0, height, 10000), 1, id);
SupportHit? Query(Vector3 start, Vector3 end, bool sides) => OriginalBodySupport.Trace([Ground()], start, end, sides);
SupportBody Body(float y = 20) => new(new(0, y, 0), new(0, y, 0),
new(80, -16, 20), new(2, -800, 3), OriginalBodySupport.JimmyRadius, OriginalBodySupport.JimmyFactor);
Test("quantized magnitude axes, signs, permutation and scale", () => {
Near(OriginalBodySupport.QuickMagnitude(new(10, 0, 0)), 10, 0, "axis");
Near(OriginalBodySupport.QuickMagnitude(Vector3.Zero), 0, 0, "zero");
var magnitude = OriginalBodySupport.QuickMagnitude(new(3, 4, 0));
Near(magnitude, 5, .002f, "3-4-5 quantization");
Near(OriginalBodySupport.QuickMagnitude(new(-4, 0, -3)), magnitude, 0, "sign/permutation");
Near(OriginalBodySupport.QuickMagnitude(new(30, 40, 0)), magnitude * 10, .00001f, "scale");
var random = new Random(8414);
for (var i = 0; i < 1000; i++) {
var v = new Vector3(random.Next(-1000, 1001), random.Next(-1000, 1001), random.Next(-1000, 1001));
Near(OriginalBodySupport.QuickMagnitude(v) / v.Length(), 1, .001f, "lookup bound");
}
});
Test("isolated original DLL magnitude float-bit references", () => {
// Copied OMT2.dll under isolated Wine32, collision_mode2_probe.c,2026-10-24.
foreach (var (vector, expected) in new (Vector3, uint)[] {
(Vector3.Zero, 0x00000000), (new(10, 0, 0), 0x41200000),
(new(3, 4, 0), 0x40a0001e), (new(-4, 0, -3), 0x40a0001e),
(new(1, 1, 1), 0x3fddb16e), (new(500, 100, 300), 0x4413eb31),
(new(.25f, .125f, .75f), 0x3f4cec46), (new(1.2345f, 678.125f, -90.75f), 0x442b0b21)
}) {
var bits = BitConverter.SingleToUInt32Bits(OriginalBodySupport.QuickMagnitude(vector));
Check(bits == expected, $"original magnitude bits for{vector}: {bits:x8} != {expected:x8}");
}
});
Test("source winding and two-sided override", () => {
var hit = Query(new(0, 20, 0), new(0, -20, 0), false);
Check(hit.HasValue, "source floor winding rejected");
Near(hit!.Value.Position.Y, 0, .00001f, "floor intersection");
Check(Query(new(0, -20, 0), new(0, 20, 0), false) == null, "backface accepted");
Check(Query(new(0, -20, 0), new(0, 20, 0), true).HasValue, "two-sided ray rejected");
});
Test("strict segment endpoint and zero-length ray", () => {
Check(Query(new(0, 20, 0), Vector3.Zero, false) == null, "endpoint must be excluded");
Check(Query(Vector3.Zero, new(0, -20, 0), false).HasValue, "beginning must be included");
Check(Query(Vector3.Zero, Vector3.Zero, false) == null, "zero ray hit");
Check(Query(new(50000, 20, 0), new(50000, -20, 0), false) == null, "outside triangle hit");
});
Test("nearest support retains first equal-distance source identity", () => {
var hit = OriginalBodySupport.Trace([Ground(0, 1), Ground(10, 2), Ground(10, 3)],
new(0, 20, 0), new(0, -20, 0));
Check(hit?.PolygonId == 2, "nearest/tie source identity changed");
});
Test("support root correction and horizontal state preservation", () => {
var result = OriginalBodySupport.Resolve(Body(), false, Query);
Check(result.Supported && result.Landed, "support/landing missing");
Near(result.Body.Position.Y, 75.9f, .00001f, "recovered root clearance");
Check(result.Body.Velocity == new Vector3(80, 0, 20), "horizontal velocity changed");
Check(result.Body.Acceleration == new Vector3(2, 0, 3), "horizontal acceleration changed");
Check(result.SupportAnchor == new Vector3(0, result.Body.Position.Y, 0), "support anchor");
Check(!OriginalBodySupport.Resolve(Body(), true, Query).Landed, "repeated grounded landing");
});
Test("prevent-lowering flag compares root height independently of velocity", () => {
var body = Body(80);
var guarded = OriginalBodySupport.Resolve(body, false, Query);
Check(!guarded.Supported && guarded.Body == body, "falling high root snapped down");
body = body with { Velocity = new(0, 550, 0) };
Check(!OriginalBodySupport.Resolve(body, false, Query).Supported, "ascending root grounded");
var unguarded = OriginalBodySupport.Resolve(body with { PreventLowering = false }, false, Query);
Check(unguarded.Supported, "disabled guard did not lower root");
Near(unguarded.Body.Position.Y, 75.9f, .00001f, "unguarded offset");
});
Test("factor .1 boundary and distinct query/final offsets", () => {
foreach (var (factor, clearance) in new[] { (.099f, 100f), (.1f, 10f), (.3f, 30f), (1f, 100f) }) {
var calls = 0;
Vector3 secondStart = default, secondEnd = default;
SupportHit? Capture(Vector3 start, Vector3 end, bool sides) {
Check(!sides, "support requested two-sided");
if (++calls == 1) return null;
secondStart = start; secondEnd = end;
return new(Vector3.Zero, 4, 8, start.Y);
}
var result = OriginalBodySupport.Resolve(Body(0) with { Radius = 100, Factor = factor }, false, Capture);
Check(calls == 2 && result.Supported, "support query count");
Near(secondStart.Y, clearance, .00001f, "query clearance");
Near(secondEnd.Y, -200, 0, "query lower endpoint");
Near(result.Body.Position.Y, 100 * factor, .00001f, "final offset always product");
}
});
Test("crossed geometry raises support query by remaining motion", () => {
var body = Body(40) with { Position = new(20, 40, 0), PreviousPosition = new(0, 50, 0) };
var calls = 0;
var crossing = new Vector3(10, 45, 0);
var expectedTop = 50 + OriginalBodySupport.QuickMagnitude(body.Position - body.PreviousPosition)
- OriginalBodySupport.QuickMagnitude(crossing - body.PreviousPosition) + body.Radius * body.Factor;
SupportHit? Capture(Vector3 start, Vector3 end, bool sides) {
if (++calls == 1) {
Check(start == body.PreviousPosition && end == body.Position, "motion segment ordering");
return new(crossing, 1, 1, 0);
}
Near(start.Y, expectedTop, .0001f, "obstruction lift");
return null;
}
Check(!OriginalBodySupport.Resolve(body, false, Capture).Supported && calls == 2, "missing floor fabricated support");
});
Test("disabled geometry does not query or mutate state", () => {
var body = Body();
SupportHit? Fail(Vector3 start, Vector3 end, bool sides) => throw new Exception("disabled query invoked");
var result = OriginalBodySupport.Resolve(body, true, Fail, false);
Check(!result.Supported && !result.Landed && result.Body == body, "disabled body mutation");
});
Test("invalid input rejected", () => {
foreach (var body in new[] { Body() with { Radius = 0 }, Body() with { Factor = float.NaN },
Body() with { Position = new(float.PositiveInfinity, 0, 0) } }) {
var threw = false;
try { OriginalBodySupport.Resolve(body, false, Query); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "invalid body accepted");
}
});
Test("flat-floor repeated gravity and airborne jump", () => {
var body = Body(75.9f) with { Velocity = Vector3.Zero, Acceleration = Vector3.Zero };
var wasGrounded = true;
for (var i = 0; i < 600; i++) {
var velocity = body.Velocity + new Vector3(0, -800f / 60, 0);
body = body with { PreviousPosition = body.Position, Position = body.Position + velocity / 60, Velocity = velocity };
var result = OriginalBodySupport.Resolve(body, wasGrounded, Query);
Check(result.Supported && !result.Landed, "gravity support/landing stability");
body = result.Body; wasGrounded = result.Supported;
Near(body.Position.Y, 75.9f, .00001f, "root drift");
}
body = body with { PreviousPosition = body.Position, Position = body.Position + new Vector3(0, 550f / 60, 0), Velocity = new(0, 550, 0) };
Check(!OriginalBodySupport.Resolve(body, true, Query).Supported, "jump was grounded");
});
Test("original lab triangles retain invisible geometry and recover spawn support", () => {
var path = Path.GetFullPath("artifacts/extracted/level1b/scene.json");
using var document = JsonDocument.Parse(File.ReadAllText(path));
var root = document.RootElement;
var vertices = root.GetProperty("vertices").EnumerateArray().Select(v => new Vector3(v[0].GetSingle(), v[1].GetSingle(), v[2].GetSingle())).ToArray();
var indices = root.GetProperty("indices").EnumerateArray().Select(v => v.GetInt32()).ToArray();
var triangles = Enumerable.Range(0, indices.Length / 3).Select(i => new SupportTriangle(
vertices[indices[3 * i]], vertices[indices[3 * i + 1]], vertices[indices[3 * i + 2]], 0, i)).ToArray();
Check(triangles.Length == 2869, "source geometry count");
var position = new Vector3(5071.93310546875f, 26.661895751953125f, 824.1039428710938f);
SupportHit? Lab(Vector3 start, Vector3 end, bool sides) => OriginalBodySupport.Trace(triangles, start, end, sides);
var result = OriginalBodySupport.Resolve(Body() with { Position = position, PreviousPosition = position }, false, Lab);
Check(result.Supported, "actual lab spawn has no support");
Near(result.Hit!.Value.Position.Y, .5486332f, .001f, "actual floor hit");
Near(result.Body.Position.Y, 76.448635f, .001f, "PostLoad root support prediction");
});
Console.WriteLine($"{count} original support groups passed; full original body collision/runtime fidelity remain unverified.");
+84
View File
@@ -0,0 +1,84 @@
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent / 'Original'
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from entities import prepare_entities, resolve_asset, resource_pairs
from omt import FormatError
class EntityPreparation(unittest.TestCase):
def test_explicit_resource_pairs_preserve_numbered_audio_and_ignore_defaults(self):
pairs = list(resource_pairs({'SpriteDatabase': 'sprites.omt', 'SpriteIndex': 135,
'SoundDatabase': 'voicepractice.omt', 'SoundIndex0': 24,
'SoundIndex1': -1, 'SoundIndex2': 22, 'MusicDatabase': 'none', 'MusicIndex': 0}))
self.assertEqual(pairs, [('SpriteIndex', 'sprites.omt', 'Canv', 135),
('SoundIndex0', 'voicepractice.omt', 'Wave', 24),
('SoundIndex2', 'voicepractice.omt', 'Wave', 22)])
self.assertEqual(list(resource_pairs({'SoundIndex': 3})), [])
def test_case_lookup_and_traversal_rejection(self):
self.assertEqual(resolve_asset(ORIGINAL, 'GaM/vr01.GAM').name, 'VR01.gam')
for name in ('../readme.txt', '/gam/VR01.gam', 'gam//VR01.gam', 'gam/./VR01.gam'):
with self.assertRaises(FormatError): resolve_asset(ORIGINAL, name)
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
(root / 'File').touch()
(root / 'FILE').touch()
with self.assertRaises(FormatError): resolve_asset(root, 'file')
def test_vr01_data_and_decoded_source_references(self):
source = ORIGINAL / 'gam/VR01.gam'
before = source.read_bytes()
with tempfile.TemporaryDirectory() as temporary:
output = Path(temporary) / 'prepared'
report = prepare_entities(ORIGINAL, 'vr01.GAM', output, decode=True)
self.assertEqual(report['level'], 'VR01')
self.assertEqual(len(report['entities']), 16)
self.assertEqual(report['counts']['3PIC'], 4)
self.assertEqual(report['sha256'], hashlib.sha256(before).hexdigest())
pickups = [e for e in report['entities'] if e['kind'] == '3PIC']
self.assertEqual([e['properties']['PickupIndex'] for e in pickups], [3001, 3002, 3003, 3004])
self.assertEqual([e['properties']['PointValue'] for e in pickups], [5] * 4)
self.assertEqual(pickups[0]['offset'], 0x1ba7)
self.assertIn('Radius', pickups[0]['propertyEvidence'])
self.assertEqual(report['duplicateTags']['c3dloadlevel'], [4, 9])
intro = next(e for e in report['entities'] if e['tag'] == 'bu')
target = next(r for r in intro['objectReferences'] if r['property'] == 'CameraTarget0')
self.assertEqual(target['candidateOrdinals'], [6])
star = next(r for r in report['resources'] if r['database'] == 'omt/sprites.omt' and r['id'] == 135)
self.assertEqual(star['name'], 'star')
self.assertEqual((output / star['path']).stat().st_size, star['width'] * star['height'] * 4)
self.assertTrue((output / star['png']).read_bytes().startswith(b'\x89PNG'))
voice = next(r for r in report['resources'] if r['database'] == 'omt/voicepractice.omt' and r['id'] == 24)
self.assertGreater(voice['audio']['seconds'], 0)
self.assertEqual((output / voice['path']).read_bytes()[:4], b'RIFF')
self.assertEqual(json.loads((output / 'entities.json').read_text()), report)
self.assertEqual(source.read_bytes(), before)
def test_lab_duplicates_authored_files_and_casefold_links(self):
with tempfile.TemporaryDirectory() as temporary:
report = prepare_entities(ORIGINAL, 'level1b.gam', Path(temporary) / 'prepared')
self.assertEqual(len(report['entities']), 129)
self.assertEqual(report['counts']['3OMT'], 4)
door = next(e for e in report['entities'] if e['tag'] == 'bars')
self.assertEqual({r['source'].lower() for r in door['fileReferences']}, {'ase/bars.ase', 'png/chain.png'})
self.assertTrue(report['duplicateTags']['c3dpickupitem'])
startup = next(e for e in report['entities'] if e['tag'] == 'STARTEXP')
link = next(r for r in startup['objectReferences'] if r['property'] == 'StartTrigger')
labexp = next(e for e in report['entities'] if e['tag'] == 'labexp')
self.assertEqual(link['candidateOrdinals'], [labexp['ordinal']])
self.assertTrue(all('unresolved' not in r for r in report['resources']))
def test_output_cannot_overlap_original_directory(self):
for path in (ORIGINAL, ORIGINAL / 'generated', ORIGINAL.parent):
with self.assertRaises(FormatError): prepare_entities(ORIGINAL, 'VR01.gam', path)
if __name__ == '__main__':
unittest.main()
+194
View File
@@ -0,0 +1,194 @@
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent / 'Original'
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from models import prepare_models, export_omt_model
from omt import Database, FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Local original assets required')
class StaticModelPreparation(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix='neutron-model-tests-')
cls.output = Path(cls.temporary.name)
cls.lab = prepare_models(ORIGINAL, 'level1b.gam', cls.output / 'lab')
cls.vr = prepare_models(ORIGINAL, 'VR01.gam', cls.output / 'vr')
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def test_exact_instance_bindings_preserve_duplicate_tags(self):
self.assertEqual((self.lab['level'], len(self.lab['actors']), len(self.lab['models'])), ('LV1B', 9, 6))
buttons = [a for a in self.lab['actors'] if a['kind'] == '3BUT']
self.assertEqual([a['offset'] for a in buttons], [42261, 42998])
self.assertEqual([a['tag'] for a in buttons], ['C3DBUTTON', 'C3DBUTTON'])
self.assertEqual(buttons[0]['variants'], buttons[1]['variants'])
self.assertTrue(all(a['defaultVariant'] == 'UP' for a in buttons))
self.assertEqual(len([a for a in self.lab['actors'] if a['kind'] == '3OMT']), 4)
self.assertEqual(len([a for a in self.vr['actors'] if a['kind'] == '3PHO']), 2)
self.assertEqual(len(self.vr['models']), 1)
self.assertEqual(self.lab['unresolved'], [])
self.assertEqual(self.vr['unresolved'], [])
def test_phone_is_original_omt_and_keeps_every_material_range(self):
model = next(m for m in self.lab['models'] if m['source'].get('database') == 'phone.omt')
self.assertEqual(model['source']['shapeId'], 0)
self.assertEqual((model['source']['triangles'], model['source']['textures']), (90, 3))
scene = json.loads((self.output / 'lab' / model['path']).read_text())
self.assertEqual({m['id']: m['texture']['id'] for m in scene['materials']}, {0: 1, 1: 0, 2: 2})
self.assertEqual([m['indexCount'] for m in scene['meshes']], [120, 6, 12, 6, 126])
self.assertEqual(sum(m['indexCount'] for m in scene['meshes']), len(scene['indices']))
self.assertEqual(len(model['source']['resources']), 7) # 1 shape + 3 materials + 3 Canv.
self.assertFalse(any(r['type'] in ('0HDR', 'mCTy') for r in model['source']['resources']))
for texture in scene['textures']:
path = self.output / 'lab' / Path(model['path']).parent / texture['path']
self.assertEqual(path.stat().st_size, texture['width'] * texture['height'] * 4)
def test_explicit_ase_and_png_pairings_are_used(self):
models = {m['key']: m for m in self.lab['models']}
bars = next(a for a in self.lab['actors'] if a['tag'] == 'bars')
source = models[bars['variants']['STATIC']]['source']
self.assertEqual((source['ase'].casefold(), source['png'].casefold(), source['triangles']), ('bars.ase', 'chain.png', 54))
button = next(a for a in self.lab['actors'] if a['kind'] == '3BUT')
for variant, filename in (('UP', 'buttonup.ase'), ('DOWN', 'buttondown.ase')):
source = models[button['variants'][variant]]['source']
self.assertEqual((source['ase'].casefold(), source['png'], source['triangles']), (filename, 'switch.png', 16))
def test_prop_models_do_not_include_other_archive_geometry(self):
for model in self.lab['models']:
if model['source'].get('database') != 'objects.omt':
continue
resources = model['source']['resources']
shapes = [r for r in resources if r['type'] == '3DSh']
self.assertEqual(len(shapes), 1)
self.assertIn(shapes[0]['id'], (27, 28))
self.assertEqual(len(resources), 3)
self.assertEqual(len([m for m in self.lab['models'] if m['source'].get('shapeId') == 28]), 1)
def test_original_hashes_and_output_boundary(self):
paths = [ORIGINAL / 'omt' / name for name in ('objects.omt', 'phone.omt')]
before = {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
prepare_models(ORIGINAL, 'Vr01.GAM', self.output / 'again')
self.assertEqual(before, {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths})
for output in (ORIGINAL, ORIGINAL / 'models', ORIGINAL.parent):
with self.assertRaises(FormatError):
prepare_models(ORIGINAL, 'VR01.gam', output)
def test_missing_explicit_mapping_is_reported_without_substitution(self):
report = prepare_models(ORIGINAL, 'Level3C.gam', self.output / 'level3c')
missing = next(e for e in report['unresolved'] if e['offset'] == 33909)
self.assertEqual(missing['kind'], '3BUT')
self.assertNotIn(33909, {e['offset'] for e in report['actors']})
def test_selective_export_retains_null_material_geometry(self):
db = Database(ORIGINAL / 'omt' / 'level1b.omt')
# Missing original material18 resolves to a null runtime pointer.
from omt import read_shape
material_ids = {e.id for e in db.entries if e.type == '3DMa'}
entry = next(e for e in db.entries if e.type == '3DSh'
and any(p['material'] is None or p['material']['id'] not in material_ids
for p in read_shape(db.payload(e))['polygons']))
destination = self.output / 'null-original'
report = export_omt_model(db, entry.id, destination)
scene = json.loads((destination / 'scene.json').read_text())
self.assertIn(18, report['nullMaterialIds'])
self.assertTrue(any(m['material'] == 18 for m in scene['meshes']))
self.assertNotIn(18, {m['id'] for m in scene['materials']})
self.assertGreater(len(scene['indices']), 0)
def test_managed_consumer_transform_draw_visibility_and_texture_identity(self):
dotnet = shutil.which('dotnet') or str(ROOT / '.tools' / 'dotnet' / 'dotnet')
if not Path(dotnet).is_file():
self.skipTest('Local .NET10 SDK not provisioned')
harness = self.output / 'managed'
harness.mkdir(exist_ok=True)
source = ROOT / 'src' / 'GamePort'
includes = [*sorted((source / 'Assets').glob('*.cs')), *sorted((source / 'Game').glob('*.cs')),
source / 'Application' / 'StaticSceneVisuals.cs']
project = '<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"/>'
project += ''.join('<Compile Include="' + str(p) + '"/>' for p in includes)
project += '</ItemGroup></Project>'
(harness / 'Harness.csproj').write_text(project)
(harness / 'NuGet.Config').write_text('<configuration><packageSources><clear/></packageSources></configuration>')
(harness / 'Program.cs').write_text(MANAGED_CHECKS)
environment = os.environ.copy()
environment.update(DOTNET_CLI_TELEMETRY_OPTOUT='1', DOTNET_CLI_HOME=str(ROOT / '.dotnet-home'),
NUGET_PACKAGES=str(ROOT / '.nuget' / 'packages'))
result = subprocess.run([dotnet, 'run', '--project', str(harness / 'Harness.csproj'), '--',
str(ORIGINAL), str(self.output / 'lab')],
cwd=ROOT, env=environment, text=True, capture_output=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout + '\n' + result.stderr)
self.assertIn('PASS static model runtime', result.stdout)
MANAGED_CHECKS = r'''
using System.Numerics;
using System.Text.Json;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
static void Check(bool condition, string name) { if (!condition) throw new Exception(name); }
static void Near(Vector3 actual, Vector3 expected, string name) => Check(Vector3.Distance(actual, expected) < .002f, name);
var original = args[0]; var prepared = args[1];
var level = GamLevel.Load(AssetPath.Resolve(original, "gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(original, "NewGame.tsk"));
var director = new SceneDirector(level, new TaskStates(save.Tasks), (_,_) => 1);
var seed = new Mesh(new[] { new MeshVertex(new(1,2,3),Vector2.Zero,Vector3.One),
new MeshVertex(new(4,5,6),Vector2.Zero,Vector3.One), new MeshVertex(new(7,8,9),Vector2.Zero,Vector3.One) }, [0,1,2])
{ HasExplicitDraws = true, Draws = [new MeshDraw(0,3,5)], Textures = new() { [5] = PngImage.White } };
var visuals = new StaticSceneVisuals(seed, director, original, prepared);
Check(visuals.ActorCount == 9, "actual lab has nine model actor instances");
Check(visuals.Mesh.Draws.Length == 20, "all nineteen original model draw ranges retained");
Check(visuals.Mesh.Textures.Count == 16, "each model instance/variant has distinct texture identities");
Check(visuals.Mesh.Textures.Keys.Where(i => i != 5).All(i => i >= int.MinValue+20000 && i < int.MinValue+20015), "reserved texture identity range");
Check(visuals.Mesh.Draws.All(d => d.TextureId == -1 || visuals.Mesh.Textures.ContainsKey(d.TextureId)), "all draw textures resolve globally");
Check(visuals.Mesh.Vertices.Take(3).Select(v => v.Position).SequenceEqual(seed.Vertices.Select(v => v.Position)), "existing scene vertices retained");
var phone = director.Actors.Single(a => a.SourceGam?.Offset == 1729);
phone.Position = new(100,200,300); phone.Rotation = Vector3.Zero; phone.Visible = true;
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(prepared,"models.json")));
var firstModel = manifest.RootElement.GetProperty("models")[0].GetProperty("path").GetString()!;
var local = Mesh.LoadSceneJson(Path.Combine(prepared,firstModel)).Vertices[0].Position;
var final = visuals.Mesh with { Vertices = visuals.Mesh.Vertices.Concat(new MeshVertex[3]).ToArray() };
visuals.Update(final);
Near(final.Vertices[3].Position, local + phone.Position, "exact actor root translation, no floor correction");
phone.Rotation = new(0,90,0); visuals.Update(final);
Near(final.Vertices[3].Position, new Vector3(-local.Z,local.Y,local.X) + phone.Position, "recovered yaw convention");
phone.Visible = false; visuals.Update(final);
Check(final.Draws.Skip(1).Take(5).All(d => !d.Visible), "all five phone material draws hide together");
Check(final.Draws[6].Visible, "duplicate phone instance remains visible");
var firstButton = director.Actors.Single(a => a.SourceGam?.Offset == 42261);
var secondButton = director.Actors.Single(a => a.SourceGam?.Offset == 42998);
firstButton.Visible = secondButton.Visible = true; firstButton.Animation = "HIDOWN"; secondButton.Animation = "UP";
visuals.Update(final);
Check(!final.Draws[12].Visible && final.Draws[13].Visible && final.Draws[14].Visible && !final.Draws[15].Visible,
"duplicate button tags choose independent up/down variants by source offset");
var conflict = seed with { Textures = new() { [int.MinValue+20000] = PngImage.White } };
try { _ = new StaticSceneVisuals(conflict,director,original,prepared); throw new Exception("texture conflict accepted"); }
catch (InvalidDataException) { }
// An explicit empty material table must retain geometry without inventing any draw.
var nullRoot = Path.Combine(prepared,"null-runtime"); Directory.CreateDirectory(nullRoot);
File.WriteAllText(Path.Combine(nullRoot,"scene.json"), """
{"vertices":[[0,0,0],[1,0,0],[0,1,0]],"uvs":[[0,0],[0,0],[0,0]],"indices":[0,1,2],"materials":[],"textures":[],"meshes":[{"firstIndex":0,"indexCount":3,"material":-1}]}
""");
File.WriteAllText(Path.Combine(nullRoot,"models.json"), """
{"schema":1,"models":[{"key":"null","path":"scene.json"}],"actors":[{"offset":1729,"kind":"3PHO","defaultVariant":"STATIC","variants":{"STATIC":"null"}}]}
""");
var invisible = new StaticSceneVisuals(seed,director,original,nullRoot);
Check(invisible.Mesh.Indices.Length == 6 && invisible.Mesh.Draws.Length == 1, "null material keeps geometry and skips draw");
Console.WriteLine("PASS static model runtime: transforms, visibility, nineteen ranges, texture IDs, duplicate tags, variants, null materials");
'''
if __name__ == '__main__': unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Original bank identity/RIFF regression checks, including the bars sounds."""
import hashlib
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'tools/extractors'))
from omt import Database, FormatError
from sound_bank import export_sound_bank
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
class SoundBankTests(unittest.TestCase):
def test_exact_original_identities_and_riff_bytes(self):
source = ORIGINAL/'omt/soundeffects.omt'
before = hashlib.sha256(source.read_bytes()).hexdigest()
database = Database(source)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)
manifest = export_sound_bank(ORIGINAL, output)
self.assertEqual(len(manifest['resources']), 251)
entries = {e.id: e for e in database.entries if e.type == 'Wave'}
for item in manifest['resources']:
payload = database.payload(entries[item['id']])
start = payload.index(b'RIFF')
size = struct.unpack_from('<I', payload, start+4)[0]+8
decoded = (output/item['path']).read_bytes()
self.assertEqual(decoded, payload[start:start+size])
self.assertEqual(hashlib.sha256(decoded).hexdigest(), item['sha256'])
by_id = {r['id']: r for r in manifest['resources']}
self.assertEqual(by_id[58]['name'], 'door closing')
self.assertEqual(by_id[59]['name'], 'Door opening loop')
self.assertEqual(by_id[230]['name'], 'winning prize2')
self.assertEqual(json.loads((output/'effects.json').read_text()), manifest)
self.assertEqual(hashlib.sha256(source.read_bytes()).hexdigest(), before)
def test_original_output_boundary_and_executable_bank_reference(self):
with self.assertRaises(FormatError):
export_sound_bank(ORIGINAL, ORIGINAL/'not-created')
exe = (ORIGINAL/'Neutron.exe').read_bytes()
self.assertEqual(exe[0x23642:0x23647], bytes.fromhex('68 8c e0 4e 00'))
self.assertEqual(exe[0xee08c:0xee09d], b'SoundEffects.omt\0')
self.assertEqual(exe[0x589de:0x589e3], bytes.fromhex('e8 5d 4c 02 00'))
self.assertEqual(exe[0x7d3bc:0x7d3c2], bytes.fromhex('56 68 65 76 61 57'))
if __name__ == '__main__':
unittest.main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Read-only original collision/pivot evidence checks; executes no original code.
Run from GamePort: python3 tools/binary/collision_evidence.py
Outputs bounded JSON facts from the original PE, GAM, OMT and standing ASE bytes.
"""
from pathlib import Path
import collections
import hashlib
import json
import math
import re
import struct
import sys
HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent.parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(PROJECT / 'tools/levels'))
sys.path.insert(0, str(PROJECT / 'tools/extractors'))
from pe_inspect import PE
from rtti_map import rtti_map
from gam import parse
from omt import Database, read_shape
def f32(value):
return struct.unpack('<f', struct.pack('<f', value))[0]
def fingerprint(data):
value = 2166136261
for byte in data:
value = ((value ^ byte) * 16777619) & 0xffffffff
return f'{value:08x}'
def main():
originals = PROJECT.parent / 'Original'
pe = PE(originals / 'Neutron.exe')
omt_pe = PE(originals / 'OMT2.dll')
# These assertions guard the decisive instructions against source mismatch.
sequences = {
'jimmy_postload_radius60_push': (0x4236a3, '6800007042'),
'jimmy_postload_support_factor_push': (0x4236b3, '6885eba13f'),
'grounded_gadget0_radius160_push': (0x4246b4, '6800002043'),
'grounded_other_radius60_push': (0x4246dc, '6800007042'),
'support_radius_getter': (0x47b8b0, 'ff9060020000'),
'support_factor_getter': (0x47b8be, 'ff9250020000'),
'support_radius_factor_multiply': (0x47b8c8, 'd84c2420'),
'support_hit_height_plus_clearance': (0x47bae1, 'd90564fc5c00d8442408'),
'support_set_grounded': (0x47bb7c, '6a018bceff921c020000'),
'null_polygon_material_returns_false': (0x4794e8, '8b460485c00f8495020000'),
'ai_support_factor_point3_push': (0x407b2b, '689a99993e'),
'goddard_postload_radius130_push': (0x41e64a, '6800000243'),
'support_clearance_threshold_reference': (0x47ba48, 'd81d20d94800'),
'support_prevent_lowering_root_compare': (0x47bafd, 'd9442410d85c2408'),
'support_prevent_lowering_reject_above': (0x47bb0a, '0f8497000000'),
'ray_one_sided_flag': (0x469c7e, '8a842480000000'),
'ray_one_sided_reject': (0x469c85, '84c00f8491010000'),
'ray_negative_distance_reject': (0x469ddd, '753f'),
'ray_strict_endpoint_reject': (0x469dee, '752e'),
'physics_capture_previous_grounded': (0x479d2e, 'ff9018020000'),
'physics_clear_current_grounded': (0x479d4e, 'ff901c020000'),
'physics_support_after_motion_call': (0x47a235, 'e856160000'),
}
for label, (va, expected) in sequences.items():
offset = pe.offset(va - pe.base)
actual = pe.data[offset:offset + len(expected) // 2].hex()
if actual != expected:
raise ValueError(f'{label} instruction mismatch at {va:#x}: {actual}')
dll_sequences = {
'quick_magnitude_ratio_scale': (0x10020027, 'd80d54481110'),
'quick_magnitude_angle_lookup': (0x10020041, '668b1445381e1610'),
'quick_magnitude_sine_lookup': (0x1002004f, 'd83495301e1410'),
'sine_initializer_step': (0x100edc21, 'dc0dc0661110'),
'angle_initializer_step': (0x100edc90, 'dc0d88451110'),
}
for label, (va, expected) in dll_sequences.items():
offset = omt_pe.offset(va - omt_pe.base)
actual = omt_pe.data[offset:offset + len(expected) // 2].hex()
if actual != expected:
raise ValueError(f'{label} instruction mismatch at {va:#x}: {actual}')
threshold = struct.unpack_from('<f', pe.data, pe.offset(0x48d920 - pe.base))[0]
assert threshold == f32(0.1)
sine = [struct.pack('<f', math.sin(i * 0.0003834951969604492)) for i in range(16384)]
for index, value in [(0, 0), (8192, 0), (4096, 1), (12288, -1)]:
sine[index] = struct.pack('<f', value)
angles = [struct.pack('<H', int(math.acos(i * 0.0001220703125 - 1) * 2607.5945876921437 * 0.5))
for i in range(16384)]
sine_hash, angle_hash = fingerprint(b''.join(sine)), fingerprint(b''.join(angles))
# Actual original-DLL tables observed in copied-install mode2 probe2026-10-24.
assert (sine_hash, angle_hash) == ('431383b5', '4f800433')
slot_offsets = [0x100, 0x110, 0x208, 0x210, 0x250, 0x254, 0x260, 0x264,
0x2e0, 0x2e8, 0x310, 0x318, 0x40c]
interface_vtable = 0x4a373c
slots = {hex(slot): hex(pe.u32(pe.offset(interface_vtable + slot - pe.base)))
for slot in slot_offsets}
game_acceptance = {}
for cls in ['CJimmyGame', 'CLevel01BGame']:
tables = rtti_map(pe, cls)['vtables']
complete = next(t for t in tables if t['object_displacement'] == '0x0')
game_acceptance[cls] = next(m['va'] for m in complete['methods'] if m['slot'] == '0x134')
# Object conversion mode references are only collected, not executed.
mode_va = 0x1013d6cc
mode_refs = [hex(omt_pe.va(m.start())) for m in re.finditer(
re.escape(struct.pack('<I', mode_va)), omt_pe.data)]
source = (originals / 'ASE/jimstop.ase').read_text(encoding='latin-1')
count = int(re.search(r'\*MESH_NUMVERTEX\s+(\d+)', source)[1])
points = [(float(x), float(z), float(y)) for x, y, z in re.findall(
r'\*MESH_VERTEX\s+\d+\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)', source)[:count]]
low = [min(p[i] for p in points) for i in range(3)]
high = [max(p[i] for p in points) for i in range(3)]
level = parse((originals / 'gam/level1b.gam').read_bytes())
start = next(e.values() for e in level.entities if e.kind == '3JIM')
x, z = start['PositionX'], start['PositionZ']
scene = Database(originals / 'omt/level1b.omt')
materials = {e.id: e.name for e in scene.entries if e.type == '3DMa'}
triangles = unresolved = excluded = 0
hits = []
checkpoint_names = {'cstart', *(f'ccheck{i}' for i in range(1, 10))}
for entry in scene.entries:
if entry.type != '3DSh':
continue
shape = read_shape(scene.payload(entry))
for index, polygon in enumerate(shape['polygons']):
triangles += len(polygon['corners']) - 2
material_id = polygon['material']['id'] if polygon['material'] else None
unresolved += int(material_id not in materials) * (len(polygon['corners']) - 2)
excluded += int(materials.get(material_id) in checkpoint_names) * (len(polygon['corners']) - 2)
a, b, c = (shape['vertices'][p['vertex']] for p in polygon['corners'][:3])
denominator = (b[2]-c[2])*(a[0]-c[0]) + (c[0]-b[0])*(a[2]-c[2])
if abs(denominator) < 1e-8:
continue
u = ((b[2]-c[2])*(x-c[0]) + (c[0]-b[0])*(z-c[2])) / denominator
v = ((c[2]-a[2])*(x-c[0]) + (a[0]-c[0])*(z-c[2])) / denominator
if min(u, v, 1-u-v) < -1e-5:
continue
hits.append(dict(y=u*a[1]+v*b[1]+(1-u-v)*c[1], shape=entry.name,
shape_id=entry.id, polygon=index, normal=polygon['normal'],
material=material_id))
factor = struct.unpack('<f', bytes.fromhex('85eba13f'))[0]
clearance = f32(60 * factor)
floor = max(h['y'] for h in hits if h['y'] <= start['PositionY'])
result = dict(
source_sha256=hashlib.sha256(pe.data).hexdigest(),
verified_instruction_sequences=len(sequences) + len(dll_sequences),
jimmy_interface_vtable=hex(interface_vtable), interface_slots=slots,
scene_acceptance_slot134=game_acceptance,
jimmy_postload=dict(radius=60, support_factor=factor,
flat_floor_clearance=clearance,
predicted_flat_root_y=floor+clearance,
raw_sole_above_flat_floor=clearance+low[1]),
goddard_postload=dict(radius=130, inherited_ai_support_factor=f32(0.3), flat_floor_clearance=f32(130 * f32(0.3))),
support_ray_factor_threshold=threshold,
regenerated_math_table_fingerprints=dict(sine=sine_hash, half_acos=angle_hash,
reference='Recorded isolated copied-DLL execution2026-10-24; no original code executed by this script'),
standing_ase=dict(vertex_count=count, min=low, max=high,
geomobjects=len(re.findall(r'\*GEOMOBJECT\s*\{', source)),
groups=len(re.findall(r'\*GROUP\s', source)),
tm_animation='*TM_ANIMATION' in source),
object_conversion_mode_address=hex(mode_va), object_mode_references=mode_refs,
lab=dict(triangles=triangles, unresolved_material_triangles=unresolved,
checkpoint_material_triangles=excluded,
has_collision_counts=dict(collections.Counter(
str(e.values()['HasCollision']) for e in level.entities if 'HasCollision' in e.values())),
spawn_vertical_hits=sorted(hits, key=lambda h: h['y'])),
limitation='Static arithmetic/data evidence; no original code executed; model pivot and full solver fidelity remain unverified.')
print(json.dumps(result, indent=2))
if __name__ == '__main__':
main()
+134
View File
@@ -0,0 +1,134 @@
/* Original-DLL conversion probe. Run only against an isolated COPIED install.
* API: collision_mode2_probe.exe [ASE\jimstop.ase] [object_mode=2] [animation_mode=2]
* Reads source bytes, converts into in-memory OMT objects/database, prints bounded
* geometry/frame-offset summaries. Never writes original asset files. */
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#define OMT_THISCALL __attribute__((thiscall))
typedef void *(OMT_THISCALL *ctor0)(void *);
typedef void *(OMT_THISCALL *dbctor)(void *, void *);
typedef void (OMT_THISCALL *writefn)(void *, void *, unsigned);
typedef void (OMT_THISCALL *seekfn)(void *, unsigned, short);
typedef void *(OMT_THISCALL *converterctor)(void *, void *, void *);
typedef void (OMT_THISCALL *convertfn)(void *);
typedef void *(__cdecl *builderfn)(void);
typedef void (__cdecl *registerfn)(unsigned, builderfn, long);
typedef void *(OMT_THISCALL *getfn)(void *, unsigned, long);
typedef float (OMT_THISCALL *magnitudefn)(const void *);
static FARPROC required(HMODULE h, const char *name) {
FARPROC p=GetProcAddress(h,name);
if(!p){fprintf(stderr,"Missing export: %s\n",name);exit(2);} return p;
}
static void dump_vectors(const char *label, float *begin, float *end) {
intptr_t bytes=(intptr_t)end-(intptr_t)begin;
if(bytes==0){printf("%s VERTICES 0 (animation-only base may be empty)\n",label);return;}
if(!begin || bytes<=0 || bytes%16 || bytes>16000000){
fprintf(stderr,"Unexpected %s vectors: %p..%p (%ld bytes)\n",label,begin,end,(long)bytes);exit(3);
}
float lo[3]={FLT_MAX,FLT_MAX,FLT_MAX},hi[3]={-FLT_MAX,-FLT_MAX,-FLT_MAX};
for(float *p=begin;p<end;p+=4)for(int i=0;i<3;i++){
if(!isfinite(p[i])){fprintf(stderr,"Nonfinite %s coordinate\n",label);exit(3);}
if(p[i]<lo[i])lo[i]=p[i];
if(p[i]>hi[i])hi[i]=p[i];
}
printf("%s VERTICES %ld\n",label,(long)bytes/16);
printf("%s MIN %.9g %.9g %.9g MAX %.9g %.9g %.9g\n",label,lo[0],lo[1],lo[2],hi[0],hi[1],hi[2]);
for(int i=0;i<3 && begin+i*4<end;i++)printf("%s V%d %.9g %.9g %.9g\n",label,i,begin[i*4],begin[i*4+1],begin[i*4+2]);
}
static uint32_t fingerprint(const unsigned char *p, unsigned count) {
uint32_t result=2166136261u;
for(unsigned i=0;i<count;i++)result=(result^p[i])*16777619u;
return result;
}
int main(int argc,char **argv) {
setbuf(stdout,NULL);
const char *input=argc>1?argv[1]:"ASE\\jimstop.ase";
int object_mode=argc>2?atoi(argv[2]):2,animation_mode=argc>3?atoi(argv[3]):2;
if(object_mode<0 || object_mode>2 || animation_mode<0 || animation_mode>3)return 2;
FILE *f=fopen(input,"rb");if(!f){perror(input);return 2;}
fseek(f,0,SEEK_END);long length=ftell(f);rewind(f);
if(length<=0 || length>64000000){fclose(f);return 2;}
char *data=malloc(length);if(!data || fread(data,1,length,f)!=(size_t)length){fclose(f);return 2;}fclose(f);
HMODULE h=LoadLibraryA("Z:\\work\\game\\OMT2.dll");
if(!h){fprintf(stderr,"LoadLibrary OMT error %lu\n",GetLastError());return 2;}
printf("PROBE MODES object=%d animation=%d input=%s\n",object_mode,animation_mode,input);
magnitudefn magnitude=(magnitudefn)required(h,"?quick_magnitude@OMedia3DVector@@QBEMXZ");
float vectors[][4]={{0,0,0,0},{10,0,0,0},{3,4,0,0},{-4,0,-3,0},{1,1,1,0},
{500,100,300,0},{.25f,.125f,.75f,0},{1.2345f,678.125f,-90.75f,0}};
for(unsigned i=0;i<sizeof(vectors)/sizeof(vectors[0]);i++){
union {float f;uint32_t u;} value;value.f=magnitude(vectors[i]);
printf("QUICK_MAG %.9g %.9g %.9g = %.9g BITS %08lx\n",vectors[i][0],vectors[i][1],vectors[i][2],value.f,(unsigned long)value.u);
}
/* Preferred OMT2 VAs10141E30 and10161E38; module-relative offsets allow ASLR. */
printf("SINE_TABLE_FNV32 %08lx HALF_ACOS_TABLE_FNV32 %08lx\n",
(unsigned long)fingerprint((const unsigned char*)h+0x141e30,16384*4),
(unsigned long)fingerprint((const unsigned char*)h+0x161e38,16384*2));
registerfn register_object=(registerfn)required(h,"?register_object@OMediaDataBase@@SAXKP6APAVOMediaDBObject@@XZJ@Z");
register_object(0x33445368,(builderfn)required(h,"?db_builder@OMedia3DShape@@SAPAVOMediaDBObject@@XZ"),0);
register_object(0x4133646d,(builderfn)required(h,"?db_builder@OMedia3DMorphAnimDef@@SAPAVOMediaDBObject@@XZ"),0);
register_object(0x33444d61,(builderfn)required(h,"?db_builder@OMedia3DMaterial@@SAPAVOMediaDBObject@@XZ"),0);
register_object(0x43616e76,(builderfn)required(h,"?db_builder@OMediaCanvas@@SAPAVOMediaDBObject@@XZ"),0);
unsigned char *stream=calloc(1,8192),*database_stream=calloc(1,8192),*database=calloc(1,8192),*converter=calloc(1,8192);
ctor0 memctor=(ctor0)required(h,"??0OMediaMemStream@@QAE@XZ");
memctor(stream);memctor(database_stream);
((writefn)required(h,"?write@OMediaStream@@UAEXPAXK@Z"))(stream,data,length);
((seekfn)required(h,"?setposition@OMediaStream@@UAEXKF@Z"))(stream,0,0);
puts("DATABASE_BEGIN");
((dbctor)required(h,"??0OMediaDataBase@@QAE@PAVOMediaStream@@@Z"))(database,database_stream);
getfn get=(getfn)required(h,"?get_object@OMediaDataBase@@UAEPAVOMediaDBObject@@KJ@Z");
unsigned char *shape=get(database,0x33445368,0);
if(!shape){fputs("No database shape\n",stderr);return 3;}
printf("DATABASE_SHAPE %p DATABASE_LINK %p\n",shape,*(void**)(shape+0x1c));
if(*(void**)(shape+0x1c)!=database){fputs("Shape not attached to in-memory database\n",stderr);return 3;}
*(int*)required(h,"?obj_conv_mode@OMedia3DShapeConverter@@1W4omt_3DObjectConvertMode@@A")=object_mode;
*(int*)required(h,"?anim_conv_mode@OMedia3DShapeConverter@@1W4omt_3DAnimConvertMode@@A")=animation_mode;
((converterctor)required(h,"??0OMediaASEConverter@@QAE@PAVOMediaStreamOperators@@PAVOMedia3DShape@@@Z"))(converter,stream,shape);
puts("CONVERT_BEGIN");
((convertfn)required(h,"?convert@OMediaASEConverter@@UAEXXZ"))(converter);
puts("CONVERT_END");
dump_vectors("SHAPE",*(float**)(shape+0x68),*(float**)(shape+0x6c));
if(*(float**)(shape+0x68)!=*(float**)(shape+0x6c))
printf("SHAPE CENTER %.9g %.9g %.9g RADIUS %.9g\n",*(float*)(shape+0x3c),*(float*)(shape+0x40),*(float*)(shape+0x44),*(float*)(shape+0x4c));
unsigned char *related=(unsigned char*)required(h,"?related_morphdefs@OMedia3DShapeConverter@@2V?$vector@JV?$allocator@J@std@@@std@@A");
long *ids=*(long**)(related+4),*ids_end=*(long**)(related+8);
intptr_t id_bytes=(intptr_t)ids_end-(intptr_t)ids;
if(id_bytes<0 || id_bytes%4 || id_bytes>4096){fputs("Invalid related morph IDs\n",stderr);return 3;}
printf("MORPH_DEFINITIONS %ld\n",(long)id_bytes/4);
for(long *id=ids;id<ids_end;id++){
unsigned char *db_object=get(database,0x4133646d,*id);
if(!db_object){fputs("Missing morph definition\n",stderr);return 3;}
/* get_object returns the builder's complete pointer in this DLL. Some
* paths expose its virtual-base table; accept only the proven layouts. */
uintptr_t table=*(uintptr_t*)db_object;
unsigned displacement=table==(uintptr_t)h+0x114304?0:table==(uintptr_t)h+0x1142f8?0x38:0xffffffffu;
if(displacement==0xffffffffu){fprintf(stderr,"Unexpected morph vtable %p\n",(void*)table);return 3;}
printf("DATABASE_OBJECT_DISPLACEMENT %u\n",displacement);
unsigned char *definition=db_object-displacement;
unsigned char **sequences=*(unsigned char***)(definition+0x28),**sequences_end=*(unsigned char***)(definition+0x2c);
intptr_t sequence_bytes=(intptr_t)sequences_end-(intptr_t)sequences;
if(sequence_bytes<0 || sequence_bytes%4 || sequence_bytes>16384){fputs("Invalid sequence table\n",stderr);return 3;}
printf("MORPH_ID %ld SEQUENCES %ld\n",*id,(long)sequence_bytes/4);
for(unsigned char **sequence=sequences;sequence<sequences_end;sequence++){
unsigned char *sentinel=*(unsigned char**)(*sequence+4),*node=*(unsigned char**)sentinel;
unsigned frame_count=*(unsigned*)(*sequence+8),frame_index=0;
if(frame_count>4096){fputs("Invalid frame count\n",stderr);return 3;}
printf("SEQUENCE_%ld FRAMES %u\n",(long)(sequence-sequences),frame_count);
while(node!=sentinel && frame_index<frame_count){
unsigned char *p=*(unsigned char**)(node+8);
char label[64];snprintf(label,sizeof(label),"SEQUENCE_%ld_FRAME_%u",(long)(sequence-sequences),frame_index);
printf("%s OFFSET %.9g %.9g %.9g\n",label,*(float*)(p+8),*(float*)(p+0xc),*(float*)(p+0x10));
dump_vectors(label,*(float**)(p+0x2c),*(float**)(p+0x30));
node=*(unsigned char**)node;frame_index++;
}
if(node!=sentinel || frame_index!=frame_count){fputs("Frame list count mismatch\n",stderr);return 3;}
}
}
printf("POSTLOAD_STATIC radius=60 factor=%.9g clearance=%.9g\n",1.265f,60.0f*1.265f);
puts("PROBE_COMPLETE");
/* Process exit releases probe-only objects; no source/database is flushed. */
return 0;
}
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Read-only 3DUD/defaults/oriented-cube collision evidence; executes no originals."""
from pathlib import Path
import hashlib
import json
import re
import struct
import sys
HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent.parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(PROJECT / 'tools/levels'))
from pe_inspect import PE
from rtti_map import rtti_map
from gam import parse
def main():
original = PROJECT.parent / 'Original'
pe = PE(original / 'Neutron.exe')
checks = {
'door_pair_collision_enable': (0x4175b0, '56e80a9b0500'),
'door_mode2_push': (0x4175c6, '6a02'),
'door_mode2_setter': (0x4175ca, 'e861a10500'),
'door_integration_disable': (0x4175cf, '578bcde8599a0500'),
'door_postload_radius40': (0x417cab, '6800002042'),
'door_postload_radius_setter': (0x417cb2, 'ff9210010000'),
'activation_has_collision_sentinel': (0x40e410, '83f8ff747c'),
'activation_enable_pairs': (0x40e427, 'ff90ac030000'),
'activation_disable_pairs': (0x40e44b, 'ff90a4030000'),
'pair_dispatch_box_mode': (0x47a4cf, 'ff9078010000'),
'pair_dispatch_box_first': (0x47a4dc, 'e8ff000000'),
'pair_dispatch_box_second': (0x47a4f4, 'e8e7000000'),
'box_query_other_geometry_gate': (0x47a5f5, 'ff90d0010000'),
'box_query_other_mode': (0x47a707, 'ff9278010000'),
'box_sphere_double_box_radius': (0x47a73f, 'd9842498000000dcc0d8842494000000'),
'box_min_bound_getter': (0x47a776, 'ff90e4020000'),
'box_max_bound_getter': (0x47a7a5, 'ff90dc020000'),
'box_corner_transform': (0x47a7ec, 'ff9084030000'),
'box_triangle_count12': (0x47ab67, 'c784240c0100000c000000'),
'box_triangle_narrowphase': (0x47b277, 'e8040b0000'),
'box_response_inhibition_gate': (0x47b2ef, 'ff90e0010000'),
'box_response_world_clip': (0x47b364, 'e847010000'),
'box_response_position_setter': (0x47b399, 'ff9014030000'),
'shape_change_cube_query': (0x4622d4, 'ff5044'),
'shape_change_min_bound_setter': (0x4622fb, 'ff90e8020000'),
'shape_change_max_bound_setter': (0x462325, 'ff90e0020000'),
}
for label, (va, expected) in checks.items():
offset = pe.offset(va - pe.base)
actual = pe.data[offset:offset + len(expected) // 2].hex()
if actual != expected:
raise ValueError(f'{label} at{va:#x}: {actual} != {expected}')
table = struct.unpack_from('<12I', pe.data, pe.offset(0x47b3ac - pe.base))
assert table == (0x47ab82, 0x47abf3, 0x47ac64, 0x47acd5, 0x47ad46, 0x47adb7,
0x47ae34, 0x47aeb1, 0x47af22, 0x47af93, 0x47aff8, 0x47b075)
# These bounded switch cases copy three source corners into the triangle
# scratch vectors. Decode their mov EAX/ECX/EDX,[ESP+disp] loads directly.
locals_to_corners = {0xdc: 0, 0x70: 1, 0x40: 2, 0xac: 3,
0x50: 4, 0x60: 5, 0xbc: 6, 0x9c: 7}
triangles = []
for start, end in zip(table, (*table[1:], 0x47b0ef)):
code = pe.data[pe.offset(start - pe.base):pe.offset(end - pe.base)]
offsets = [m[1][0] if m[1] else struct.unpack('<I', m[2])[0] for m in re.finditer(
rb'\x8b[\x44\x4c\x54]\x24(.)|\x8b[\x84\x8c\x94]\x24(.{4})', code)]
assert len(offsets) == 12
triangles.extend(locals_to_corners[offsets[i]] for i in (0, 4, 8))
assert triangles == [0,1,2,1,3,2,0,2,4,2,6,4,4,6,5,6,7,5,5,7,3,5,3,1,0,4,1,4,5,1,2,3,7,7,6,2]
interface = next(t for t in rtti_map(pe, 'C3DDoorUpDown')['vtables']
if t['object_displacement'] == '0xc0')
assert interface['va'] == '0x4993ac'
methods = {m['slot']: m['va'] for m in interface['methods']}
for slot, target in {'0x178': '0x471720', '0x384': '0x472980', '0x40c': '0x417c50'}.items():
assert methods[slot] == target
level_path = original / 'gam/level1b.gam'
level = parse(level_path.read_bytes())
bars_entity = next(e for e in level.entities if e.kind == '3DUD' and e.values().get('ObjectTag') == 'bars')
bars = bars_entity.values()
assert bars['HasCollision'] == -1 and bars['CanMove'] == 1
source = next(p for p in (original / 'ASE').iterdir() if p.name.casefold() == bars['ASEFile'].casefold())
text = source.read_text(encoding='latin-1')
count = int(re.search(r'\*MESH_NUMVERTEX\s+(\d+)', text)[1])
points = [(float(x), float(z), float(y)) for x, y, z in re.findall(
r'\*MESH_VERTEX\s+\d+\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)', text)[:count]]
assert count == len(points) == 42
low = [min(v[i] for v in points) for i in range(3)]
high = [max(v[i] for v in points) for i in range(3)]
print(json.dumps(dict(
executable_sha256=hashlib.sha256(pe.data).hexdigest(),
verified_instruction_sequences=len(checks), verified_jump_table_entries=len(table),
door_interface=interface['va'], mode=2, postload_radius=40,
constructor_defaults=dict(entity_pair_collision=True, integrate_own_physics=False,
has_collision_minus1='preserves both defaults'),
normal_sphere_broadphase='quick_magnitude(otherRoot-boxRoot) <=2*boxRadius+otherRadius',
second_mode2_broadphase='quick_magnitude(otherRoot-boxRoot) <=boxRadius+otherRadius; returns directly',
bounds_origin='OMT shape find_cube ->EXE462270 ->iface2E8(min),2E0(max)',
corners='bit4 selects maxX,bit2 maxY,bit1 maxZ; transform by current root/rotation viaiface384',
triangle_corners=triangles,
lab_bars=dict(gam_offset=hex(bars_entity.offset), gam_sha256=hashlib.sha256(level_path.read_bytes()).hexdigest(),
ase_source=source.relative_to(original).as_posix(), ase_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
source_vertices=count, local_min=low, local_max=high,
position=[bars['Position'+a] for a in 'XYZ'], rotation=[bars['Rotation'+a] for a in 'XYZ'],
has_collision=bars['HasCollision'], can_move=bars['CanMove'], open_amount=bars['OpenAmount']),
limitation='Static geometry/dispatch/default evidence.47BD80 narrowphase and original runtime door blocking remain unverified.'
), indent=2))
if __name__ == '__main__':
main()
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Read-only checks for the original Level3B/E entity/archive loader paths.
No original code is executed. Run from GamePort with Python 3.
This proves what the loader requests, not normal-gameplay reachability.
"""
from pathlib import Path
import hashlib
import json
import struct
import sys
HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent.parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(PROJECT / 'tools/levels'))
from pe_inspect import PE
from rtti_map import rtti_map
from gam import parse
def main():
original = PROJECT.parent / 'Original'
pe = PE(original / 'Neutron.exe')
checks = {
'b_ctor_level_code': (0x451ba8, '684233564c'),
'b_archive_string_length': (0x451c99, 'bf241f4f00'),
'b_archive_string_copy': (0x451cc5, 'be241f4f00'),
'b_archive_loader_dispatch': (0x451ce8, 'ff92e4000000'),
'e_ctor_level_code': (0x452748, '684533564c'),
'e_archive_string_length': (0x452839, 'bffc1f4f00'),
'e_archive_string_copy': (0x452865, 'befc1f4f00'),
'e_archive_loader_dispatch': (0x452888, 'ff92e4000000'),
'loader_omt_directory': (0x44e7ff, '681c1b4f00'),
'loader_file_open': (0x44e8b4, 'e8b7780200'),
'loader_database_open': (0x44e8ce, 'e82d770200'),
'b_factory_ctor': (0x45d635, 'e8b644ffff'),
'e_factory_ctor': (0x45d78b, 'e8004fffff'),
}
for name, (va, expected) in checks.items():
off = pe.offset(va - pe.base)
actual = pe.data[off:off + len(expected)//2].hex()
if actual != expected:
raise ValueError(f'{name} at {va:#x}: {actual} != {expected}')
directory = pe.cstr(pe.offset(0x4f1b1c - pe.base))
assert directory == 'omt'
scenes = []
for suffix, string_va in [('B', 0x4f1f24), ('E', 0x4f1ffc)]:
level_path = original / 'gam' / f'Level3{suffix}.gam'
level = parse(level_path.read_bytes())
archive_name = pe.cstr(pe.offset(string_va - pe.base))
table = next(v for v in rtti_map(pe, f'CLevel03{suffix}Game')['vtables']
if v['object_displacement'] == '0x0')
methods = {m['slot']: m['va'] for m in table['methods']}
assert methods['0xe4'] == '0x44e7b0'
matches = [p for p in (original / directory).iterdir()
if p.name.casefold() == archive_name.casefold()]
scenes.append(dict(
gam=str(level_path.relative_to(original)),
gam_sha256=hashlib.sha256(level_path.read_bytes()).hexdigest(),
gam_bytes=level.size, gam_code=level.code,
entity_count=len(level.entities),
entity_kinds=[e.kind for e in level.entities],
complete_vtable=table['va'], initialize_slot_b4=methods['0xb4'],
archive_loader_slot_e4=methods['0xe4'],
archive_string_va=hex(string_va), archive=archive_name,
matching_files=[str(p.relative_to(original)) for p in matches]))
print(json.dumps(dict(
executable_sha256=hashlib.sha256(pe.data).hexdigest(),
verified_instruction_sequences=len(checks), archive_directory=directory,
scenes=scenes,
same_gam_bytes_after_header=(
(original/'gam/Level3B.gam').read_bytes()[4:] ==
(original/'gam/Level3E.gam').read_bytes()[4:]),
limitation='Static loader evidence only. Normal-gameplay reachability, unused/stub status and original runtime failure/success remain unverified.'), indent=2))
if __name__ == '__main__':
main()
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Prepare source-backed GAM entity references without assigning gameplay rules.
Keeps source order/offsets, duplicate tags and exact typed property values. Optional
resource decoding exports only resources named by explicit database/index pairs.
It does not turn editor icons into rendered actors or infer class asset defaults.
"""
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from dataclasses import asdict
import hashlib
import io
import json
from pathlib import Path
import re
import struct
import sys
import wave
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
from gam import parse
from omt import Database, FormatError, read_canvas, read_shape, safe_name, write_png
SENTINELS = {'none', 'null', 'default', 'end', ''}
OBJECT_LINKS = {
'StartTrigger', 'NextTrigger', 'ToggleObject', 'ActivateObject', 'CameraTarget',
'PlayerControlled', 'FaceObject', 'AITarget', 'AIPatrol', 'AINewPos', 'PatrolPoint',
'NextPatrolPoint', 'CallObjectTag', 'ActivateBy', 'PickupLink', 'ActivateButton',
}
def resolve_asset(root: Path, relative: str) -> Path:
"""Portable case-insensitive lookup, rejecting traversal and ambiguities."""
root = root.resolve()
current = root
parts = relative.replace('\\', '/').split('/')
if not relative or any(p in ('', '.', '..') for p in parts):
raise FormatError(f'Invalid asset path: {relative!r}')
for part in parts:
matches = [p for p in current.iterdir() if p.name.casefold() == part.casefold()]
if len(matches) != 1:
raise FormatError(f'Missing or ambiguous asset: {relative}')
current = matches[0]
if not current.resolve().is_relative_to(root):
raise FormatError(f'Asset escapes original root: {relative}')
return current
def _object_link(name: str) -> bool:
return name in OBJECT_LINKS or bool(re.fullmatch(r'(CameraTarget|ActivateObject)\d+', name))
def resource_pairs(values: dict):
"""Explicit serialized pairings only; no implicit global sound bank assumption."""
for prefix, resource_type in (('Sprite', 'Canv'), ('Music', 'Wave'), ('Omt', '3DSh')):
database, index = values.get(prefix + 'Database'), values.get(prefix + 'Index')
if isinstance(database, str) and isinstance(index, int) and index >= 0 and database.casefold() not in SENTINELS:
yield prefix + 'Index', database, resource_type, index
database = values.get('SpriteDatabase')
if isinstance(database, str) and database.casefold() not in SENTINELS:
for name, index in values.items():
if re.fullmatch(r'Sprite[1-9]', name) and isinstance(index, int) and index >= 0:
yield name, database, 'Canv', index
database = values.get('SoundDatabase')
if isinstance(database, str) and database.casefold() not in SENTINELS:
for name, index in values.items():
if re.fullmatch(r'SoundIndex\d*', name) and isinstance(index, int) and index >= 0:
yield name, database, 'Wave', index
def prepare_entities(original: Path, level_file: str, output: Path, decode: bool = False) -> dict:
original = original.resolve()
output = output.resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise FormatError('Output must be separate from the original directory')
source = resolve_asset(original, 'gam/' + level_file)
data = source.read_bytes()
level = parse(data)
output.mkdir(parents=True, exist_ok=True)
tags = defaultdict(list)
for ordinal, entity in enumerate(level.entities):
tag = entity.values().get('ObjectTag', '')
tags[str(tag).casefold()].append(ordinal)
databases, resources = {}, {}
entities = []
for ordinal, entity in enumerate(level.entities):
values = entity.values()
record = {
'ordinal': ordinal, 'kind': entity.kind, 'offset': entity.offset,
'tag': values.get('ObjectTag'),
'position': [values.get('Position' + axis, 0) for axis in 'XYZ'],
'rotation': [values.get('Rotation' + axis, 0) for axis in 'XYZ'],
'properties': values,
'propertyEvidence': {p.name: {'offset': p.offset, 'type': p.type, 'length': p.length, 'raw': p.raw}
for p in entity.properties},
'objectReferences': [], 'resourceReferences': [], 'fileReferences': [],
}
for name, value in values.items():
if _object_link(name) and isinstance(value, str) and value.casefold() not in SENTINELS:
candidates = tags.get(value.casefold(), [])
record['objectReferences'].append({'property': name, 'tag': value,
'candidateOrdinals': candidates})
if isinstance(value, str) and value.lower().endswith(('.ase', '.png')):
folder = 'ASE' if value.lower().endswith('.ase') else 'png'
try:
path = resolve_asset(original, folder + '/' + value)
record['fileReferences'].append({'property': name, 'source': path.relative_to(original).as_posix(),
'sha256': hashlib.sha256(path.read_bytes()).hexdigest()})
except FormatError as error:
record['fileReferences'].append({'property': name, 'source': value, 'unresolved': str(error)})
for property_name, database_name, resource_type, identity in resource_pairs(values):
database_path = resolve_asset(original, 'omt/' + database_name)
canonical = database_path.relative_to(original).as_posix()
if canonical not in databases:
databases[canonical] = Database(database_path)
database = databases[canonical]
key = (canonical, resource_type, identity)
if key not in resources:
matches = [e for e in database.entries if e.type == resource_type and e.id == identity]
resource = {'database': canonical, 'type': resource_type, 'id': identity,
'databaseSha256': hashlib.sha256(database.data).hexdigest()}
if len(matches) != 1:
resource['unresolved'] = 'No matching resource in explicitly named database'
else:
entry = matches[0]
resource.update(name=entry.name, offset=entry.offset, size=entry.size)
if decode:
_decode(database, entry, resource, output)
resources[key] = resource
record['resourceReferences'].append({'property': property_name, 'database': canonical,
'type': resource_type, 'id': identity})
entities.append(record)
report = {
'schema': 1, 'source': source.relative_to(original).as_posix(),
'sha256': hashlib.sha256(data).hexdigest(), 'level': level.code,
'policy': 'Exact source entity data and explicit references only; gameplay/visibility rules are not inferred.',
'counts': dict(sorted(Counter(e.kind for e in level.entities).items())),
'duplicateTags': {tag: ids for tag, ids in sorted(tags.items()) if len(ids) > 1},
'entities': entities, 'resources': [resources[key] for key in sorted(resources)],
}
(output / 'entities.json').write_text(json.dumps(report, indent=2, allow_nan=False) + '\n', encoding='utf8')
return report
def _decode(database, entry, resource: dict, output: Path):
folder = output / 'resources' / safe_name(database.path.stem)
folder.mkdir(parents=True, exist_ok=True)
stem = f'{entry.type}_{entry.id:08x}_{safe_name(entry.name)}'
payload = database.payload(entry)
if entry.type == 'Canv':
image = read_canvas(payload)
rgba = image.pop('rgba')
raw, png = folder / (stem + '.rgba'), folder / (stem + '.png')
raw.write_bytes(rgba)
write_png(png, image['width'], image['height'], rgba)
resource.update(image, path=raw.relative_to(output).as_posix(), png=png.relative_to(output).as_posix())
elif entry.type == '3DSh':
path = folder / (stem + '.json')
path.write_text(json.dumps(read_shape(payload), allow_nan=False) + '\n', encoding='utf8')
resource['path'] = path.relative_to(output).as_posix()
elif entry.type == 'Wave':
start = payload.find(b'RIFF')
if start < 0 or payload[start + 8:start + 12] != b'WAVE' or start + 12 > len(payload):
raise FormatError(f'Wave resource is missing bounded RIFF: {entry.id}')
size = struct.unpack_from('<I', payload, start + 4)[0] + 8
if size < 12 or start + size > len(payload):
raise FormatError(f'RIFF outside resource: {entry.id}')
audio = payload[start:start + size]
path = folder / (stem + '.wav')
path.write_bytes(audio)
resource['path'] = path.relative_to(output).as_posix()
try:
with wave.open(io.BytesIO(audio)) as wav:
resource['audio'] = {'rate': wav.getframerate(), 'channels': wav.getnchannels(),
'sampleWidth': wav.getsampwidth(), 'frames': wav.getnframes(),
'seconds': wav.getnframes() / wav.getframerate()}
except wave.Error:
resource['audio'] = {'encoding': 'non-PCM RIFF retained unchanged'}
def main():
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('--original', type=Path, default=Path('../Original'))
cli.add_argument('--level', default='level1b.gam')
cli.add_argument('--output', type=Path, required=True)
cli.add_argument('--decode', action='store_true')
args = cli.parse_args()
report = prepare_entities(args.original, args.level, args.output, args.decode)
print(f"{report['level']}: {len(report['entities'])} source entities, {len(report['resources'])} explicit resource references")
if __name__ == '__main__':
main()
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Prepare only explicitly bound original static entity models and their materials."""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
from pathlib import Path
from ase import expand_mesh, read_ase
from entities import resolve_asset
from gam import parse
from omt import Database, FormatError, export_scene, read_material, read_shape
from png import read_png
def _digest(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def _bounds(points: list) -> dict:
if not points:
raise FormatError('Original model has no source points for local bounds')
return {'min': [min(p[i] for p in points) for i in range(3)],
'max': [max(p[i] for p in points) for i in range(3)]}
def _one(database: Database, kind: str, identity: int):
matches = [e for e in database.entries if e.type == kind and e.id == identity]
if len(matches) != 1:
raise FormatError(f'Missing or ambiguous {database.path.name}:{kind}:{identity}')
return matches[0]
def export_omt_model(database: Database, identity: int, output: Path) -> dict:
"""Index only the selected mesh and transitively referenced material/canvas."""
shape_entry = _one(database, '3DSh', identity)
shape = read_shape(database.payload(shape_entry))
keys = {('3DSh', identity)}
missing_materials = set()
for polygon in shape['polygons']:
link = polygon['material']
if link is None:
continue # Null materials remain null, retaining invisible geometry.
if link['type'] != '3DMa':
raise FormatError(f'Unexpected shape material type {link["type"]}')
matches = [e for e in database.entries if e.type == '3DMa' and e.id == link['id']]
if not matches:
# An unresolved original material stream link becomes a null pointer.
# LV1B's invisible proxies name absent material18; preserve those
# original polygons without inventing a visible replacement surface.
missing_materials.add(link['id'])
continue
material_entry = _one(database, '3DMa', link['id'])
keys.add(('3DMa', link['id']))
texture = read_material(database.payload(material_entry))['texture']
if texture is not None:
if texture['type'] != 'Canv':
raise FormatError(f'Unexpected material texture type {texture["type"]}')
_one(database, 'Canv', texture['id'])
keys.add(('Canv', texture['id']))
selected = copy.copy(database)
selected.entries = [e for e in database.entries if (e.type, e.id) in keys]
scene = export_scene(selected, output)
return {
'kind': 'OMT', 'database': database.path.name, 'databaseSha256': _digest(database.path),
'shapeId': identity, 'shapeName': shape_entry.name,
'resources': [{'type': e.type, 'id': e.id, 'offset': e.offset, 'size': e.size, 'name': e.name}
for e in selected.entries],
'vertices': len(scene['vertices']), 'triangles': len(scene['indices']) // 3,
'materials': len(scene['materials']), 'textures': len(scene['textures']),
'nullMaterialIds': sorted(missing_materials),
'localBounds': _bounds(shape['vertices']),
}
def export_ase_model(source: Path, texture_source: Path, output: Path) -> dict:
"""Keep first authored sample of each node, with the explicit game PNG override."""
animation = read_ase(source)
scene = {'source': source.name, 'sha256': animation['sha256'],
'vertices': [], 'uvs': [], 'normals': [], 'indices': [], 'meshes': [],
'materials': [{'id': 0, 'texture': {'type': 'Canv', 'id': 0},
'colours': {'diffuse': [1, 1, 1]}}], 'textures': []}
for node in animation['objects']:
sample = node['samples'][0]
if not sample['textureFaces']:
raise FormatError(f'Explicit static model lacks texture coordinates: {source.name}')
mesh = expand_mesh(sample)
first_vertex, first_index = len(scene['vertices']), len(scene['indices'])
for field in ('vertices', 'uvs', 'normals'):
scene[field].extend(mesh[field])
scene['indices'].extend(i + first_vertex for i in mesh['indices'])
scene['meshes'].append({'name': node['name'], 'shapeId': len(scene['meshes']),
'firstIndex': first_index, 'indexCount': len(mesh['indices']), 'material': 0})
texture = read_png(texture_source)
rgba = texture.pop('rgba')
output.mkdir(parents=True, exist_ok=True)
(output / 'texture.rgba').write_bytes(rgba)
scene['textures'].append({'id': 0, 'path': 'texture.rgba', **texture})
(output / 'scene.json').write_text(json.dumps(scene, separators=(',', ':'), allow_nan=False) + '\n', encoding='utf8')
return {'kind': 'ASE', 'ase': source.name, 'aseSha256': animation['sha256'],
'png': texture_source.name, 'pngSha256': _digest(texture_source),
'mode': 'First original authored sample; no morph playback implied',
'localBounds': _bounds([p for node in animation['objects'] for p in node['samples'][0]['vertices']]),
'vertices': len(scene['vertices']), 'triangles': len(scene['indices']) // 3,
'materials': 1, 'textures': 1}
def prepare_models(original: Path, level_file: str, output: Path) -> dict:
original, output = original.resolve(), output.resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise FormatError('Output must be separate from the original installation')
source = resolve_asset(original, 'gam/' + level_file)
level = parse(source.read_bytes())
output.mkdir(parents=True, exist_ok=True)
models, actors, unresolved, cache, databases = [], [], [], {}, {}
def omt_model(name: str, identity: int) -> str:
archive = resolve_asset(original, 'omt/' + name)
key = ('OMT', str(archive), identity)
if key not in cache:
if archive not in databases:
databases[archive] = Database(archive)
database = databases[archive]
model_key = f'model_{len(models):04d}'
details = export_omt_model(database, identity, output / model_key)
models.append({'key': model_key, 'path': model_key + '/scene.json', 'source': details})
cache[key] = model_key
return cache[key]
def ase_model(ase_name: str, png_name: str) -> str:
ase = resolve_asset(original, 'ASE/' + ase_name)
png = resolve_asset(original, 'png/' + png_name)
key = ('ASE', str(ase), str(png))
if key not in cache:
model_key = f'model_{len(models):04d}'
details = export_ase_model(ase, png, output / model_key)
models.append({'key': model_key, 'path': model_key + '/scene.json', 'source': details})
cache[key] = model_key
return cache[key]
for ordinal, entity in enumerate(level.entities):
values, variants, evidence = entity.values(), {}, ''
if entity.kind == '3OMT':
database, identity = values.get('OmtDatabase'), values.get('OmtIndex')
if not isinstance(database, str) or not isinstance(identity, int) or identity < 0:
raise FormatError(f'3OMT has no explicit model at 0x{entity.offset:x}')
variants['STATIC'] = omt_model(database, identity)
evidence = 'Explicit GAM OmtDatabase/OmtIndex'
elif entity.kind == '3PHO':
# Verified original class binding, not the unrelated phone.ASE prop.
variants['STATIC'] = omt_model('phone.omt', 0)
evidence = 'EXE43579D opens phone.omt;4357C9 selects3DSh0'
elif entity.kind == '3BUT':
names = [values.get(key) for key in ('Up.ase', 'Down.ase', 'UpDown.Png')]
if not all(isinstance(name, str) and name.casefold() not in ('none', '') for name in names):
unresolved.append({'ordinal': ordinal, 'offset': entity.offset, 'kind': entity.kind,
'tag': values.get('ObjectTag'), 'reason': 'Button lacks a complete explicit ASE/PNG mapping; constructor fallback not inferred'})
continue
variants['UP'] = ase_model(names[0], names[2])
variants['DOWN'] = ase_model(names[1], names[2])
evidence = 'Explicit GAM Up.ase/Down.ase/UpDown.Png; EXE411B93 initialUP'
elif isinstance(values.get('ASEFile'), str) and isinstance(values.get('PNGFile'), str):
if any(values[name].casefold() in ('none', '') for name in ('ASEFile', 'PNGFile')):
unresolved.append({'ordinal': ordinal, 'offset': entity.offset, 'kind': entity.kind,
'tag': values.get('ObjectTag'), 'reason': 'Incomplete explicit ASEFile/PNGFile mapping; no default inferred'})
continue
variants['STATIC'] = ase_model(values['ASEFile'], values['PNGFile'])
evidence = 'Explicit GAM ASEFile/PNGFile (no class default inferred)'
if variants:
actors.append({'ordinal': ordinal, 'offset': entity.offset,
'tag': values.get('ObjectTag'), 'kind': entity.kind,
'defaultVariant': 'UP' if entity.kind == '3BUT' else 'STATIC',
'variants': variants, 'evidence': evidence})
report = {'schema': 1, 'source': source.relative_to(original).as_posix(),
'sha256': _digest(source), 'level': level.code, 'models': models, 'actors': actors, 'unresolved': unresolved,
'policy': 'Original local coordinates and source actor transforms; static samples only; no floor correction.'}
(output / 'models.json').write_text(json.dumps(report, indent=2, allow_nan=False) + '\n', encoding='utf8')
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--original', type=Path, default=Path('../Original'))
parser.add_argument('--level', default='level1b.gam')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
report = prepare_models(args.original, args.level, args.output)
print(f"{report['level']}: {len(report['actors'])} authored model instances; {len(report['models'])} unique models")
if __name__ == '__main__':
main()
+5 -2
View File
@@ -265,12 +265,13 @@ def export_scene(database: Database, output: Path):
scene = {'source': database.path.name, 'sha256': hashlib.sha256(database.data).hexdigest(), scene = {'source': database.path.name, 'sha256': hashlib.sha256(database.data).hexdigest(),
'coordinates': 'Original OMT world coordinates, unchanged', 'coordinates': 'Original OMT world coordinates, unchanged',
'vertices': [], 'uvs': [], 'normals': [], 'indices': [], 'meshes': [], 'vertices': [], 'uvs': [], 'normals': [], 'indices': [], 'meshes': [],
'materials': [], 'textures': [], 'warnings': []} 'materials': [], 'textures': [], 'warnings': [], 'collisionPolygons': []}
material_names = {entry.id: entry.name for entry in database.entries if entry.type == '3DMa'}
for entry in database.entries: for entry in database.entries:
payload = database.payload(entry) payload = database.payload(entry)
if entry.type == '3DSh': if entry.type == '3DSh':
shape = read_shape(payload) shape = read_shape(payload)
for poly in shape['polygons']: for polygon_index, poly in enumerate(shape['polygons']):
first_index = len(scene['indices']) first_index = len(scene['indices'])
first_vertex = len(scene['vertices']) first_vertex = len(scene['vertices'])
for corner in poly['corners']: for corner in poly['corners']:
@@ -280,6 +281,8 @@ def export_scene(database: Database, output: Path):
scene['normals'].append(shape['normals'][ni] if ni < len(shape['normals']) else poly['normal']) scene['normals'].append(shape['normals'][ni] if ni < len(shape['normals']) else poly['normal'])
for i in range(1, len(poly['corners'])-1): for i in range(1, len(poly['corners'])-1):
scene['indices'].extend((first_vertex, first_vertex+i, first_vertex+i+1)) scene['indices'].extend((first_vertex, first_vertex+i, first_vertex+i+1))
scene['collisionPolygons'].append({'shapeId': entry.id, 'polygonIndex': polygon_index,
'normal': poly['normal'], 'materialName': material_names.get(poly['material']['id']) if poly['material'] else None})
if len(poly['corners']) > 3: if len(poly['corners']) > 3:
scene['warnings'].append(f'{entry.id}: polygon with {len(poly["corners"])} corners fan triangulated; concavity not validated') scene['warnings'].append(f'{entry.id}: polygon with {len(poly["corners"])} corners fan triangulated; concavity not validated')
material = poly['material']['id'] if poly['material'] else -1 material = poly['material']['id'] if poly['material'] else -1
+60 -1
View File
@@ -7,6 +7,10 @@ from pathlib import Path
from omt import Database, export_scene, extract from omt import Database, export_scene, extract
from ase import export_ase from ase import export_ase
from png import read_png from png import read_png
from entities import prepare_entities
from models import prepare_models
from ui import export_ui
from sound_bank import export_sound_bank
def find_archive(original: Path, name: str) -> Path: def find_archive(original: Path, name: str) -> Path:
@@ -17,20 +21,65 @@ def find_archive(original: Path, name: str) -> Path:
return matches[0] return matches[0]
def prepare_actor(original: Path, output: Path, name: str, texture_name: str, actions: dict, base_name: str | None = None,
ignored_animations: tuple[str, ...] = ()):
"""Explicit EXE registration mappings; no texture guessed from ASE adjacency."""
target = output / 'actors' / name
target.mkdir(parents=True, exist_ok=True)
texture_source = next(p for p in (original/'png').iterdir() if p.name.casefold() == texture_name.casefold())
texture = read_png(texture_source)
(target/'texture.rgba').write_bytes(texture.pop('rgba'))
base_name = base_name or next(iter(actions.values()))
base = next(p for p in (original/'ASE').iterdir() if p.stem.casefold() == base_name.casefold())
for stem in dict.fromkeys(actions.values()):
source = next(p for p in (original/'ASE').iterdir() if p.stem.casefold() == stem.casefold())
manifest = export_ase(source, target/stem, base)
manifest['texture'] = {'path': '../texture.rgba', **texture}
(target/stem/'animation.json').write_text(json.dumps(manifest, indent=2)+'\n')
(target/'family.json').write_text(json.dumps({'default': next(iter(actions)),
'actions': {key: value+'/animation.json' for key, value in actions.items()},
'ignoredAnimations': list(ignored_animations)}, indent=2)+'\n')
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--original', type=Path, default=Path('../Original')) parser.add_argument('--original', type=Path, default=Path('../Original'))
parser.add_argument('--output', type=Path, default=Path('artifacts/extracted')) parser.add_argument('--output', type=Path, default=Path('artifacts/extracted'))
parser.add_argument('--scenes', nargs='+', default=['level1b', 'VR01']) parser.add_argument('--scenes', nargs='+', default=['level1b', 'VR01'])
parser.add_argument('--all-scenes', action='store_true', help='Prepare every supplied GAM/OMT scene pair')
parser.add_argument('--audio', nargs='*', default=['sounds', 'musicjimmyshouse', 'musicneighborhood']) parser.add_argument('--audio', nargs='*', default=['sounds', 'musicjimmyshouse', 'musicneighborhood'])
parser.add_argument('--animations', nargs='*', default=['jimstop', 'jimrun', 'jimjump', 'jimscratch', 'jimbackpedal', 'jimfall']) parser.add_argument('--animations', nargs='*', default=['jimstop', 'jimrun', 'jimjump', 'jimscratch', 'jimbackpedal', 'jimfall', 'jimtalk', 'jimfly'])
args = parser.parse_args() args = parser.parse_args()
if args.output.resolve().is_relative_to(args.original.resolve()): if args.output.resolve().is_relative_to(args.original.resolve()):
parser.error('Output must be outside the original installation') parser.error('Output must be outside the original installation')
if args.all_scenes:
args.scenes = sorted((p.stem for p in (args.original/'gam').iterdir() if p.suffix.casefold()=='.gam'), key=str.casefold)
catalog = {'prepared': [], 'unavailable': []}
for name in args.scenes: for name in args.scenes:
try:
source = find_archive(args.original, name) source = find_archive(args.original, name)
except ValueError:
if not args.all_scenes:
raise
# GAM entities and OMT geometry are distinct. The executable registers
# level3b/3e, but their use in normal progression is not established.
# Report the absent geometry without calling it required game content.
catalog['unavailable'].append({'level': name+'.gam', 'archive': name+'.omt',
'reason': 'GAM supplied; matching geometry archive absent; gameplay use unverified'})
print(f'{name}.gam is supplied; no matching {name}.omt geometry archive '
'(gameplay use unverified; no substitution)')
continue
scene = export_scene(Database(source), args.output / source.stem) scene = export_scene(Database(source), args.output / source.stem)
print(f"{source.name}: {len(scene['indices'])//3} triangles, {len(scene['textures'])} textures") print(f"{source.name}: {len(scene['indices'])//3} triangles, {len(scene['textures'])} textures")
report = prepare_entities(args.original, source.stem + '.gam', args.output / source.stem / 'entities', True)
print(f"{report['level']}: {len(report['resources'])} explicit entity resources")
models = prepare_models(args.original, source.stem + '.gam', args.output / source.stem / 'models')
print(f"{models['level']}: {len(models['actors'])} model actors; {len(models['unresolved'])} unresolved bindings")
catalog['prepared'].append({'level': name+'.gam', 'archive': source.name, 'scene': source.stem+'/scene.json'})
(args.output/'scene-catalog.json').write_text(json.dumps(catalog, indent=2)+'\n')
export_ui(Database(find_archive(args.original, 'screens')), args.output / 'ui', Database(args.original / 'alpha.omt'))
effects = export_sound_bank(args.original, args.output / 'effects')
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
for name in args.audio: for name in args.audio:
source = find_archive(args.original, name) source = find_archive(args.original, name)
report = extract(Database(source), args.output / source.stem) report = extract(Database(source), args.output / source.stem)
@@ -50,6 +99,16 @@ def main():
manifest['texture'] = {'path':'../jimycarl.rgba', **texture} manifest['texture'] = {'path':'../jimycarl.rgba', **texture}
(target/name/'animation.json').write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8') (target/name/'animation.json').write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8')
print(f"{matches[0].name}: {len(manifest['frames'])} animation samples") print(f"{matches[0].name}: {len(manifest['frames'])} animation samples")
# EXE413D8C..413DF9 (Carl);41CDA0..41CE5F (Goddard high-detail clips).
prepare_actor(args.original, args.output, 'carl', 'carl.png', {
'STOP': 'carlstop', 'WALK': 'carlwalk', 'TALK': 'carltalk', 'INHALE': 'carlinhale',
'CHEER': 'carlcheer', 'TELE': 'carlteleport'})
prepare_actor(args.original, args.output, 'goddard', 'goddard02.png', {
'SIT': 'godsit', 'RUN': 'godrun', 'GROWL': 'godgrowl', 'WAG': 'godwag',
'EAT': 'godeat', 'FLY': 'godfly', 'POINT': 'godpoint'}, 'godpoint', ('STOP', 'WALK', 'TALK'))
prepare_actor(args.original, args.output, 'trophy', 'trophy.png', {'STOP': 'trophy'})
# C3DJetpackFire421F30..96: DEFAULT fire.ase, HINONE fire2.ase, fire.png.
prepare_actor(args.original, args.output, 'jetpack', 'fire.png', {'DEFAULT': 'fire', 'NONE': 'fire2'}, 'fire')
if __name__ == '__main__': main() if __name__ == '__main__': main()
+58
View File
@@ -0,0 +1,58 @@
"""Prepare the original default SoundEffects.omt bank (EXE423642..656).
Numeric effect IDs are archive identities, not offsets into the four-entry
sounds.omt archive. Preserve the original PCM/RIFF bytes and explicit metadata.
"""
import hashlib
import json
from pathlib import Path
import struct
from entities import _decode, resolve_asset
from omt import Database, FormatError
def export_sound_bank(original: Path, output: Path) -> dict:
original, output = original.resolve(), output.resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise FormatError('Sound output must be separate from original files')
source = resolve_asset(original, 'omt/SoundEffects.omt')
database = Database(source)
source_hash = hashlib.sha256(database.data).hexdigest()
resources = []
for entry in database.entries:
if entry.type != 'Wave':
continue
resource = {'database': source.relative_to(original).as_posix(), 'type': 'Wave',
'id': entry.id, 'name': entry.name, 'offset': entry.offset,
'size': entry.size, 'databaseSha256': source_hash}
_decode(database, entry, resource, output)
if 'seconds' not in resource['audio']:
# Some original resources contain MPEG Layer3 in RIFF. Preserve the
# encoded bytes; duration comes from the explicit fact sample count.
raw = (output/resource['path']).read_bytes()
position, rate, frames, encoding = 12, None, None, None
while position + 8 <= len(raw):
tag = raw[position:position+4]
size = struct.unpack_from('<I', raw, position+4)[0]
begin, end = position+8, position+8+size
if end > len(raw):
raise FormatError('Sound RIFF chunk escapes resource')
if tag == b'fmt ' and size >= 16:
encoding, channels, rate = struct.unpack_from('<HHI', raw, begin)
elif tag == b'fact' and size >= 4:
frames = struct.unpack_from('<I', raw, begin)[0]
position = end+(size & 1)
if not rate or frames is None:
raise FormatError(f'No explicit sound duration for encoding: {entry.id}')
resource['audio'] = {'formatTag': encoding, 'channels': channels, 'rate': rate,
'frames': frames, 'seconds': frames/rate,
'encoding': 'encoded RIFF preserved; decoder support is separate'}
resource['sha256'] = hashlib.sha256((output/resource['path']).read_bytes()).hexdigest()
resources.append(resource)
if not resources or len({r['id'] for r in resources}) != len(resources):
raise FormatError('Missing or duplicate original sound identities')
report = {'schema': 1, 'evidence': 'Neutron.exe423642..423656; default current sound database',
'resources': resources}
(output/'effects.json').write_text(json.dumps(report, indent=2)+'\n', encoding='utf8')
return report
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Export proven laboratory HUD/PracticeYesNo Canv resources, without changing originals."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from omt import Database, FormatError, read_canvas, validate_output, write_png
# Neutron.exe 402687..4026E8 registers pad and laboratory objective IDs;
# 40224F registers PracticeYesNo. These are original identities, not guessed art.
CANVASES = {120: (256, 29), 121: (256, 29), 122: (256, 29),
156: (320, 173), 169: (207, 100)}
ALPHA_CANVASES = {83: (8, 8), 84: (8, 8), 85: (8, 8)}
def export_ui(database: Database, output: Path, alpha: Database | None = None) -> dict:
validate_output(database, output)
if alpha is None:
# The original font database is beside omt/, not within screens.omt.
alpha = Database(database.path.parent.parent / 'alpha.omt')
validate_output(alpha, output)
recovered = []
for source, identities in ((database, CANVASES), (alpha, ALPHA_CANVASES)):
for identity, expected in identities.items():
entry = next((e for e in source.entries if e.type == 'Canv' and e.id == identity), None)
if entry is None:
raise FormatError(f'Missing original UI canvas {source.path.name}:{identity}')
canvas = read_canvas(source.payload(entry))
if (canvas['width'], canvas['height']) != expected:
raise FormatError(f'Unexpected original UI canvas dimensions {identity}')
recovered.append((source, entry, canvas))
output.mkdir(parents=True, exist_ok=True)
textures = []
for source, entry, canvas in recovered:
name = f'canvas_{entry.id}'
rgba = canvas['rgba']
(output / (name + '.rgba')).write_bytes(rgba)
write_png(output / (name + '.png'), canvas['width'], canvas['height'], rgba)
textures.append({'id': entry.id, 'name': entry.name, 'width': canvas['width'],
'height': canvas['height'], 'path': name + '.rgba',
'source': source.path.name, 'sourceOffset': entry.offset, 'sourceBytes': entry.size,
'rgbaSha256': hashlib.sha256(rgba).hexdigest()})
manifest = {'version': 1, 'source': database.path.name,
'sourceSha256': hashlib.sha256(database.data).hexdigest(),
'alphaSha256': hashlib.sha256(alpha.data).hexdigest(),
'referenceWidth': 640, 'referenceHeight': 480, 'textures': textures}
(output / 'ui.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
return manifest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('database', type=Path)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--alpha', type=Path, help='Original alpha.omt (default: beside the omt directory)')
args = parser.parse_args()
result = export_ui(Database(args.database), args.output, Database(args.alpha) if args.alpha else None)
print(f"{len(result['textures'])} original UI canvases exported to {args.output}")
if __name__ == '__main__':
main()
+16 -6
View File
@@ -53,11 +53,11 @@ def inside(args):
application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe', application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe',
'--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json', '--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json',
'--level', 'gam/level1b.gam', '--original-camera', '--with-player', '--level', 'gam/level1b.gam', '--original-camera', '--with-player',
'--frames', '240' if args.port_walk else '6' if args.port_window else '2', '--no-validation', '--frames', '240' if args.port_walk else '12' if args.port_practice else '6' if args.port_window else '2', '--no-validation',
'--screenshot', r'Z:\work\port-frame.ppm'] '--screenshot', r'Z:\work\port-frame.ppm']
application += ['--smoke-walk'] if args.port_walk else ['--inspect', '--time', '0.05'] application += ['--smoke-walk'] if args.port_walk else ['--smoke-practice-window'] if args.port_practice else ['--story', '--story-time', '12'] if args.port_story else ['--inspect', '--time', '0.05']
application += ['--smoke-window'] if args.port_window and not args.port_walk else [] application += ['--smoke-window'] if args.port_window and not (args.port_walk or args.port_practice) else []
application += [] if args.port_window or args.port_walk else ['--headless'] application += [] if args.port_window or args.port_walk or args.port_practice else ['--headless']
if args.asset_probe: if args.asset_probe:
application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model] application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model]
wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env) wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env)
@@ -97,12 +97,18 @@ def main():
p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation') p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation')
p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64') p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64')
p.add_argument('--port-walk', action='store_true', help='Windows port walking/jump/keyboard/resize checkpoint under Wine64') p.add_argument('--port-walk', action='store_true', help='Windows port walking/jump/keyboard/resize checkpoint under Wine64')
p.add_argument('--port-story', action='store_true', help='Windows port original-resource story/camera render under Wine64')
p.add_argument('--port-practice', action='store_true', help='Windows port practice modal/input/resize under Wine64')
p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy') p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy')
p.add_argument('--probe-model', default=r'ASE\jimstop.ase') p.add_argument('--probe-model', default=r'ASE\jimstop.ase')
p.add_argument('--probe-executable', type=Path, help='Local probe executable to mount read-only for --asset-probe')
p.add_argument('--output', type=Path) p.add_argument('--output', type=Path)
args = p.parse_args() args = p.parse_args()
args.port_smoke = args.port_smoke or args.port_window or args.port_walk args.port_smoke = args.port_smoke or args.port_window or args.port_walk or args.port_story or args.port_practice
if args.port_smoke and args.asset_probe: p.error('Select either port smoke or asset probe') if args.port_smoke and args.asset_probe: p.error('Select either port smoke or asset probe')
if args.port_story and (args.port_window or args.port_walk or args.port_practice): p.error('Story comparison uses headless fixed time; select one port check')
if args.port_practice and (args.port_walk or args.port_window): p.error('Select one windowed port check')
if args.probe_executable and not args.asset_probe: p.error('--probe-executable requires --asset-probe')
if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120') if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120')
if args.inside: return inside(args) if args.inside: return inside(args)
project = Path(__file__).resolve().parents[2] project = Path(__file__).resolve().parents[2]
@@ -128,7 +134,9 @@ def main():
if args.port_smoke: if args.port_smoke:
cmd += ['--ro-bind', str(project/'dist/win-x64'), '/port'] cmd += ['--ro-bind', str(project/'dist/win-x64'), '/port']
if args.asset_probe: if args.asset_probe:
cmd += ['--ro-bind', str(project/'artifacts/binary/omt_shape_probe.exe'), '/probe.exe'] probe = (args.probe_executable or project/'artifacts/binary/omt_shape_probe.exe').resolve(strict=True)
if probe.is_relative_to(source.resolve()): p.error('Probe must be a generated executable outside originals')
cmd += ['--ro-bind', str(probe), '/probe.exe']
for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win64' if args.port_smoke else 'win32', for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win64' if args.port_smoke else 'win32',
'DISPLAY':':89', 'PATH':'/opt/wine-stable/bin:/usr/bin:/bin', 'LANG':'C.UTF-8', 'DISPLAY':':89', 'PATH':'/opt/wine-stable/bin:/usr/bin:/bin', 'LANG':'C.UTF-8',
'WINEDEBUG':'-all,err+all,warn+ddraw,warn+d3d,+seh' if args.debug else '-all', 'WINEDEBUG':'-all,err+all,warn+ddraw,warn+d3d,+seh' if args.debug else '-all',
@@ -148,6 +156,8 @@ def main():
if args.port_smoke: cmd += ['--port-smoke'] if args.port_smoke: cmd += ['--port-smoke']
if args.port_window: cmd += ['--port-window'] if args.port_window: cmd += ['--port-window']
if args.port_walk: cmd += ['--port-walk'] if args.port_walk: cmd += ['--port-walk']
if args.port_story: cmd += ['--port-story']
if args.port_practice: cmd += ['--port-practice']
if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model] if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model]
print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True) print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True)
subprocess.run(cmd, check=True, timeout=args.seconds + 40) subprocess.run(cmd, check=True, timeout=args.seconds + 40)