Implement original gadget panel and playable shrink ray

This commit is contained in:
UnixNight committed 2026-10-27 12:18:45 -04:00
1 parent 0272f7bef7
commit 7b5230ceb8
57 files changed
+3545 -48

No files matched your search

+9 -4
View File
@@ -35,12 +35,17 @@ other agents' active changes. Keep updates concise, save detailed evidence to di
Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests, Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests,
and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`, and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`,
`docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions. `docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions.
Current mode is evidence-led architecture continuation. The initial checkpoint is Current mode is user-requested gameplay/gadget implementation. On2026-10-27 the
documented in docs/checkpoint/review.md. Pause feature expansion; use the playable user parked collision recovery and requested gadgets. This overrides the earlier
feature-expansion pause; retain evidence before gameplay assumptions. Preserve
the35a2a66 body milestone/0272f7b release notes and remaining C4/C5 gates for return.
The initial architecture checkpoint is documented in docs/checkpoint/review.md; use the playable
69d0187 baseline as a comparison tool. Read 69d0187 baseline as a comparison tool. Read
docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay
changes. Only evidence probes or directly evidenced corrections belong in this changes. Current gadget controls/resources/primary-fire findings belong in
checkpoint; distinguish static recovery, port tests and original runtime evidence. docs/gameplay/. Distinguish static recovery, implementation, port tests and original
runtime evidence. Main owns integration/runtime; gadget investigators have
exclusive named files, not shared directories.
Use REA for original-binary investigations from now on, including delegated Use REA for original-binary investigations from now on, including delegated
investigations. Preserve its Evidence and cross-check relevant addresses/bytes; investigations. Preserve its Evidence and cross-check relevant addresses/bytes;
+27 -4
View File
@@ -5,7 +5,7 @@ using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain
untouched in `../Original`. Work is local; no remote operations or runtime online untouched in `../Original`. Work is local; no remote operations or runtime online
services are used. services are used.
**Current direction: architecture recovery; feature expansion paused.** The **Current direction: gameplay gadgets; collision recovery is parked.** The
[checkpoint review](docs/checkpoint/review.md), [coverage map](docs/checkpoint/coverage.md) [checkpoint review](docs/checkpoint/review.md), [coverage map](docs/checkpoint/coverage.md)
and [implementation plan](docs/checkpoint/implementation-plan.md) compare source and [implementation plan](docs/checkpoint/implementation-plan.md) compare source
owners, update order and lifecycles with the port. Clean69d0187 and its packages owners, update order and lifecycles with the port. Clean69d0187 and its packages
@@ -13,11 +13,20 @@ are preserved locally as the playable baseline. Corrections now include task/Car
callbacks, controlled player phase ordering, source static camera queries for the callbacks, controlled player phase ordering, source static camera queries for the
first route and gadget availability through tutorial/return. Full scene scheduling, first route and gadget availability through tutorial/return. Full scene scheduling,
collision and shared camera state remain incomplete. collision and shared camera state remain incomplete.
The user requested this change after milestone35a2a66/0272f7b. Gadget work uses
original controls, state and assets; the collision checkpoint remains available
to resume after this gameplay work.
VR04 now uses recovered static body response/support/friction with original-code VR04 now uses recovered static body response/support/friction with original-code
numeric references. Lab/outside retain the capsule until special contacts and numeric references. Lab/outside retain the capsule until special contacts and
dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md). dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md).
**Current milestone: original lab story, interactions and jet pack practice flow.** **Current milestone: original gadget screen and playable shrink ray.**
Tab/Space selects owned gadgets and their practice levels; the default device
fires on Enter/Ctrl/left mouse and supports actual VR04 soldier shrink/restore
with original morphs and score effects. Other gadget effects remain incomplete.
See [gadget implementation](docs/gameplay/gadgets-implementation.md) for recovered
rules, modern policies and the verification boundary.
The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and
checkpoint transitions. Collision response, timing and visual fidelity remain checkpoint transitions. Collision response, timing and visual fidelity remain
@@ -69,8 +78,22 @@ centered, objectives stay bottom-right and F2 stays top-left. Use
`--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11 `--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11
update UI placement and clicks. update UI placement and clicks.
The original lab pickup is internally tagged `shrinkray`; the original objective The lab pickup is the combined **shrink ray and jetpack** (inventory item3).
art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click Hold **Enter, Ctrl or left mouse** to fire the continuous ray; release to stop.
Grounded firing stops forward motion. Eligible original Yokian soldiers can be
shrunk for30 seconds, awarding10 points. Their authored shrink animation holds
its small endpoint; complete enemy AI/combat remains unimplemented.
**Tab or Space** opens the original gadget screen; with another special gadget
equipped, the first press unequips it. Use the mouse or arrows to point, then
Enter/Ctrl or a mouse button to select. Escape or Return closes the screen.
Practice Mode followed by an owned gadget enters its original tutorial directly.
The screen scales uniformly on widescreen and pauses port gameplay while music
continues. Other gadget selection art is present; their special behaviors remain
future work. F1's jetpack availability control also controls shrink-ray ownership.
The pickup's original objective calls its jump action the **jet pack**. Its
practice prompt accepts **Y** or a click
on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the
hovered Yes region, otherwise No. Practice RETURN restores Jimmy and Goddard to hovered Yes region, otherwise No. Practice RETURN restores Jimmy and Goddard to
the saved departure position, retains the lab start's yaw and suppresses its intro. the saved departure position, retains the lab start's yaw and suppresses its intro.
+5 -2
View File
@@ -7,10 +7,13 @@ Original DLL/frame and original game comparisons are separate evidence categorie
## Identity ## Identity
The lab pickup's GAM tag SHRINKRAY/PickupIndex301 is a prototype/internal name. The lab pickup's GAM tag SHRINKRAY/PickupIndex301 belongs to the combined device.
Original screens.omt Canv120 says GET JET PACK; its effect grants inventory Original screens.omt Canv120 says GET JET PACK; its effect grants inventory
group0/item3. That exact inventory slot gates the powered-jump code43848E/4385C9. 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 The later gadget recovery corrects the old prototype-name interpretation:
tile14 names SHRINK RAY, controls113 lists both SHRINK and JUMP/JETPACK, and
426E40 fires the default owned-item3 ray. See docs/gameplay/shrink-ray.md.
The original readme describes
Shift/Insert/right mouse as Jump - Jet Pack Burst. The actual C3DShrinkRay class 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. has separate ray.ase/ray0000..2.png bindings440035..A6, outside this implementation.
+19
View File
@@ -5,6 +5,25 @@ SDL3 for platform windowing, input and audio. Linux x64 and Windows x64 are
equally required. Source is `src/GamePort/`; root executable csproj allows equally required. Source is `src/GamePort/`; root executable csproj allows
`dotnet build` and `dotnet run` from GamePort. No runtime network dependencies. `dotnet build` and `dotnet run` from GamePort. No runtime network dependencies.
The first gadget slice separates UI display selection from the equipped raw mode.
`GadgetScreen` owns group0 panel state/hit regions; `GadgetMenuOverlay` loads54
original canvases and applies shared uniform640×480 viewport/pointer transforms.
Closing precedes the inventory selection event. Practice captures the existing
departure context and requests the selected VR01..08 without a pickup prompt.
The panel gates new gameplay SFX; full simulation pause is a declared port policy.
`SceneGadgets` subscribes to the player's existing input phase and owns ray sound,
energy, actual3SOL targets and score callbacks to `SceneInteractions`/TSK.
`ShrinkRay` isolates strict source heading/height/distance/wall gates and texture
clock; `OriginalHeading` implements the copied-DLL numeric references.
`ShrinkSoldier` separates authored/reset AI mode from prior dynamic mode, shrink
timer/marker and provisional NPC body support. `ShrinkSoldierVisuals` samples
original WALK/SHRINK morphs with nonloop hold rather than scaling the mesh.
`ShrinkRayVisuals` captures the effect root/yaw and three source textures.
Generic draw opacity and opaque/alpha/additive variants support the recovered
half-opacity ray. Blended-world depth writes disabled is an explicit renderer
policy. See gameplay/gadgets-implementation.md for evidence and remaining gates.
Original assets stay in `../Original`. Python tools parse undocumented original Original assets stay in `../Original`. Python tools parse undocumented original
formats into generated scene resources under `artifacts/`. The modern application formats into generated scene resources under `artifacts/`. The modern application
loads these original-derived resources and big endian GAM entity data. Portable loads these original-derived resources and big endian GAM entity data. Portable
+6 -1
View File
@@ -1,6 +1,6 @@
# Architecture checkpoint # Architecture checkpoint
Feature expansion is paused. The existing port is a preserved baseline and a tool This records the completed architecture checkpoint. The existing port is a preserved baseline and a tool
for testing interpretations. This checkpoint connects original state ownership, for testing interpretations. This checkpoint connects original state ownership,
update order and lifecycle to the lab → VR04 → lab → outside route; it does not update order and lifecycle to the lab → VR04 → lab → outside route; it does not
require recovering every level or certify complete gameplay fidelity. require recovering every level or certify complete gameplay fidelity.
@@ -45,6 +45,11 @@ ten numeric references and enables the static subset in VR04. Its
[implementation review](collision-body-implementation-review.md) preserves remaining [implementation review](collision-body-implementation-review.md) preserves remaining
dynamic, special-contact, initialization and modern noclip/render boundaries. dynamic, special-contact, initialization and modern noclip/render boundaries.
User-directed gadget continuation is in ../gameplay/gadgets-implementation.md.
It supersedes older inferred gadget names: raw mode0 is Bubble, menu item3 is the
combined shrink-ray/jetpack and its normal equipped mode remains−1. Numeric
collision findings remain valid independently of those old labels.
Evidence labels used throughout: Evidence labels used throughout:
- **Recovered:** static instructions, serialized original data, or a specifically - **Recovered:** static instructions, serialized original data, or a specifically
@@ -148,7 +148,9 @@ Thus radius100 changes both sphere response and radius×factor support clearance
and root offset, to126.5 with the ordinary factor. Grounded Jimmy's ordinary and root offset, to126.5 with the ordinary factor. Grounded Jimmy's ordinary
wrapper restores60 in its later object phase; physics/support must not perform wrapper restores60 in its later object phase; physics/support must not perform
that restoration early or clear it merely because control is absent. Other that restoration early or clear it merely because control is absent. Other
gadget radii (for example scooter160) remain outside the ordinary−1/3 subset. gadget radii (for example Bubble/mode0 radius160) remain outside the ordinary
default-device subset. Gadget continuation corrects the earlier Scooter label;
see ../gameplay/gadget-controls.md for display index versus raw mode.
## Verification and remaining integration questions ## Verification and remaining integration questions
@@ -73,7 +73,7 @@ the authority for that callback. Partial batches preserve successful Evidence.
Remaining: full424600 wrapper timers/UI/sound cleanup, base40E050/462520 Remaining: full424600 wrapper timers/UI/sound cleanup, base40E050/462520
resource/transform/morph policies, collision-triggered ceiling cancellation, resource/transform/morph policies, collision-triggered ceiling cancellation,
scooter radius160 and other gadget/class cases, original body registration and Bubble/mode0 radius160 and other gadget/class cases, original body registration and
response, complete registry and engine cadence, shared viewport handoff and response, complete registry and engine cadence, shared viewport handoff and
original whole-game comparison. Calling the entire controller with empty input original whole-game comparison. Calling the entire controller with empty input
would not implement these missing phases. Existing capsule/yaw/camera adapters would not implement these missing phases. Existing capsule/yaw/camera adapters
+15
View File
@@ -3,6 +3,21 @@
Compilation, native runtime, original behavior and full feature completion are Compilation, native runtime, original behavior and full feature completion are
separate evidence categories. **The game is not fully reconstructed/playable yet.** separate evidence categories. **The game is not fully reconstructed/playable yet.**
Gadgets (2026-10-27 UTC): original gadget screen and combined shrink-ray/jetpack
are implemented; actual VR04 soldiers use original shrink morphs, source timer,
authored AI reset and ordinary10-point score/save effect. First complete run:
157 Python+2 HUD, all managed suites including15 gadget groups,29 main GPU
completions and17 isolated blend/readback checks, zero enabled validation errors.
Heading matches15 original-DLL references and65,540 sweep cases. Final ordering/
authored-mode fixes pass the complete rerun in integration-final.log.
Native Linux GTX1070/private Xvfb verifies1920×1080 menu input/pause/capture and
1280×720 held ray against an actual authored VR04 target, with zero validation
errors. The fixture moves only the player near a settled soldier; it does not
establish gameplay navigation to the platform or original visual parity.
Other effects, full enemy AI/combat, energy warnings and lifecycle gaps remain;
see gameplay/gadgets-implementation.md. New packages are pending clean release
checks; native Windows gadget testing is not claimed.
C4 ordinary body (2026-10-27 UTC): all ten original-code body references match C4 ordinary body (2026-10-27 UTC): all ten original-code body references match
managed composition. VR04 uses source static response/support/friction and live managed composition. VR04 uses source static response/support/friction and live
radius60/100; lab/outside retain the capsule. Twenty body groups plus full suite radius60/100; lab/outside retain the capsule. Twenty body groups plus full suite
+10
View File
@@ -190,3 +190,13 @@
preparation separately from controller608. No dynamic-door geometry does not preparation separately from controller608. No dynamic-door geometry does not
establish absence of other source dynamic actor classes. Modern feet/sole and establish absence of other source dynamic actor classes. Modern feet/sole and
noclip admission remain explicit policies; this is not whole-tutorial fidelity. noclip admission remain explicit policies; this is not whole-tutorial fidelity.
36. **Keep gadget display, equipped mode and owned effects distinct.** The user
parked collision work and requested gameplay gadgets. Integrate original
group0 resources/state and default item3 first: its display index is3 but raw
mode remains−1. Do not treat the default shrink-ray/jetpack as special mode3
or call Bubble mode0 Scooter. Reuse original heading, strict multi-target
gates and nonloop soldier morph; ordinary hits award10 through the score/save
owner. Expiry restores authored/reset AIState, not pre-hit dynamic mode.
Keep modern full-panel pause, upright effect transform, additive branch and
blended-depth policy explicit. Other gadgets, full AI and warning-audio
lifecycle remain independent evidence gates, not guessed feature completion.
+134
View File
@@ -0,0 +1,134 @@
# Gadget resource inventory
2026-10-27. Read-only asset investigation; no original file was modified or
executed. This report describes serialized resources and inspected pixels.
It does not infer gadget timing, collision, selection policy or model attachment
from filenames. Binary/input contracts belong in [gadget-controls.md](gadget-controls.md).
## Selection screen and original labels
All following Canv IDs are from Original/omt/screens.omt, SHA256
`e8e95231f5d302b41f4fbf33df1c5a08ce4645370f9f519527ff1727b73b7a5e`.
Canvas20 (`menu`) is640×480 and already contains the dim gadget tiles and Return/
Practice labels. Unsuffixed, suffix-b and suffix-c tile art are141×141. Their inspected
appearances are green, white and blue respectively; which state selects a variant
must come from the dispatcher, not the colour. The independent controls investigation
reports constructor404E97..404F8B's inventory0..7-to-tile association; the displayed
labels below are independently visible in the original pixels.
| Group0 item | Original tile label | Unsuffixed / b / c Canv | HUD Canv/name | Control strip |
|---:|---|---|---|---|
|0|BUBBLE|11 /52 /178|94 `1bubble`|109 `BmenuLBubble`|
|1|ROCKETSHIP|12 /46 /171|87 `2rocket`|115 `BmenuLRocketship`|
|2|INVISIBLE|13 /47 /172|88 `3invisible`|111 `BmenuLInvisible`|
|3|SHRINK RAY|14 /48 /173|89 `4raygun`|113 `BmenuLRayGun`|
|4|SCOOTER|15 /49 /174|90 `5scooter`|116 `BmenuLScooter`|
|5|REMOTE|16 /50 /175|91 `6remote`|114 `BmenuLRemote`|
|6|BASEBALL|17 /51 /176|92 `7baseball`|118 `BmenuLBaseball`|
|7|GRAPPLER|18 /45 /177|93 `8grappler`|110 `BmenuLGrappler`|
Do not rename tile3 to Jetpack. The separate jetpack HUD canvas119 is named
`9jetpack`, and control strip112 is `BmenuLJetPack`; strip113 visibly describes
both SHRINK firing and JUMP/JETPACK. This agrees with the port's recovered
item3-powered-jump association, but the art itself does not establish firing logic.
The rendered selection background places bubble/rocket/scooter/remote across its
first row and invisible/shrink/baseball/grappler across its second. Exact hit
rectangles and hover/selected state are source-controller evidence, separate
from this visual layout observation.
The controls investigator specifically recovers white suffix-b as owned idle and
green unsuffixed as mouseover; group0 state0/4 hide both to expose the dim background.
The blue suffix-c resources are available assets but are not part of those current
group0 bindings. Their existence does not justify inventing an unavailable overlay.
Other useful screens.omt resources:
| IDs / names | Dimensions | Asset role |
|---|---|---|
|109..116 plus118 `BmenuL*`|393×69|Nine left-side gadget control strips.|
|108 `BmenuR2`,117 `BmenuR1`|247×69|Right-side instructions with SELECT/DESELECT INVENTIONS text.|
|24/181/182 `return`/`return2`/`return3`|141×78|Return button variants.|
|170/179/180 `practice`/`practice2`/`practice3`|141×78|Practice button variants.|
|87..94 plus119|80×70|Eight gadget HUD icons and separate jetpack icon.|
|84/85 `backpack`/`backpack2`|141×141|Backpack variants.|
|253 `CrossHairs`|15×210|Vertical strip;14 square15×15 frames arithmetically fit. Frame meaning/timing is not inferred.|
## Export and integration
tools/extractors/gadget_resources.py exports54 exact decoded canvases into a
separate directory. It checks original IDs/names/dimensions before writing, uses
the existing bounded OMT/RGB555/colour-key decoder, preserves alpha and records
archive/payload/RGBA SHA256 plus source offsets/sizes. It protects the entire
source asset root, including sibling ASE/png/gam directories when the archive is
under omt/. No image generation or replacement art is used.
```
python3 tools/extractors/gadget_resources.py ../Original/omt/screens.omt --output artifacts/extracted/gadgets
```
The generated gadgets.json uses schema1, referenceWidth640/referenceHeight480 and
textures with id/name/role/width/height/path/png/sourceOffset/sourceBytes/
sourceSha256/rgbaSha256. File paths are local `canvas_ID.rgba` and `.png`.
`tiles` records artItem1..8, literal labels and normal/b/c IDs; suffix roles remain
neutral so the source controller owns availability/highlight interpretation.
This separate manifest leaves the existing eight HUD/practice resources unchanged.
Primary owns prepare.py/package/runtime integration; this investigator did not
edit those files. Runtime should reuse UiViewport scaling and pointer conversion.
Generated inspection images are in artifacts/gadget-assets/: selection-sheet.png
and canvas_20.png. ase-inventory.json records exact hashes/counts for the model
files below. The fixture exporter wrote artifacts/extracted/gadgets/gadgets.json.
Three regression groups pass in artifacts/gadget-assets/tests.log: exact original
resource/pixel/dimension round-trip, rejection of all original asset subtrees, and
rejecting changed dimensions before producing partial output.
## Shipped model and animation candidates
These are file/content observations, not proof that a given runtime action uses
every candidate. The ASE parser maps original coordinates using the existing
verified `(x,z,y)` conversion. Jimmy clips share426 vertices/814 faces with the
prepared standing mesh, so existing morph preparation can preserve its topology.
| Source ASE | Samples / fps | Geometry and bounded use |
|---|---|---|
|jimshoot.ASE|2 /10|426 vertices/814 faces; original shooting pose candidate. Not in current default prepared animation list.|
|jimfly.ASE|2 /10|426/814; already prepared for powered jumping.|
|jimswing.ASE|2 /10|426/814; swing pose candidate.|
|jimscooter.ASE, jimscooterstop.ASE|2 each /10|426/814; scooter poses.|
|jimdrive.ASE|2 /10|426/814; driving pose.|
|jimheadshrink.ASE|7 /5|426/814; distinct authored morph sequence, not an inferred uniform scale.|
|godscooter.ASE, godscooter2.ASE|2 each /30|195 vertices/370 faces; reference `goddard02.png`.|
|godrocket.ASE|3 /5|222 vertices/411 faces; rocket-form candidate.|
|ray.ASE|2 /10|5 vertices/3 faces. Material text references `ray0002.ifl`; supplied PNGs ray0000..ray0003 exist. Sequence binding/cadence remains source work.|
|hook.ASE|1 /10|40 vertices/68 faces; material references hook.bmp, supplied hook.png exists.|
|rope01.ASE,rope02.ASE|1 each /30|6 vertices/6 faces and4 vertices/2 faces.|
|laser02.ASE,missile.ASE|1 each /30|8 vertices/8 faces and7 vertices/10 faces; missile's goo.bmp reference is not a verified gadget attachment.|
scooter.omt contains shape0 `goddard01`, shape1 `wheel`, matching material/canvas
resources0 `goddard128` and1 `scooterwheel2`; archive SHA256
`8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81`.
inventory.omt is an older-looking icon set with BUBBLE/GODJEEP/SCOOTER/jetpack etc;
its names alone do not justify replacing screens.omt menu art or IDs.
No explicit bubble-named ASE exists in the supplied directory; that bounded
filename search does not prove the original bubble geometry was absent/generated.
## Already prepared sounds
artifacts/extracted/effects/effects.json already preserves original SoundEffects.omt
waves, paths and source byte ranges. Bank SHA256 is
`c71e06d93b8a5ef4f4522a5c40220bc8aeaecb889b5de69445db44817fb9acb1`.
Useful identities are0 `shrinkray`,1 `jetpack`,2 `gravitybubble`,3 `gravitybubbleoff`,
10 `goddard baseballs`,18 `pickupbaseball`,45 `rocketship`,46 `Scooter`,106
`bubble boing` and117 `click shrink ray`. These are archive identity/name facts;
actual activation, repeat, ownership, volume and cancellation still need callers.
The existing resource export is sufficient; no duplicate sound extraction is needed.
## Practical next addition and limits
Original selection art and control labels are complete enough to implement a
source-driven gadget screen without invented icons. For a usable gadget beyond
the current powered jump, shrink firing has original pose, beam geometry/PNG frames
and both successful-fire/click sounds available; it still needs recovered target,
range, timing, energy and interruption policy. The selection3 naming overlap is
an explicit reason to implement the combined shrink/jetpack controls coherently.
Other gadget assets are candidates for later behavior recovery, not evidence that
all eight gadget behaviors are currently implemented.
+83
View File
@@ -0,0 +1,83 @@
# Gadget material opacity and blending
Implemented 2026-10-27. Scope: Vulkan support needed by the recovered shrink-ray
effect. This is a renderer capability, not a claim of complete original material
or fixed-function rendering fidelity.
## Recovered facts
[Shrink-ray investigation](shrink-ray.md) records the underlying REA evidence.
Original EXE SHA256:
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Original engine DLL SHA256:
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
| Original location | Fact and dependency |
| --- | --- |
| EXE VA40E4A0 / raw0E4A0, complete-object virtual offset114 | Positive opacity walks shape polygons and nonnull materials; writes material RGB1, alpha=parameter at +4C..58, source blend enum6 at +30, destination enum7 or1 at +34, and sets flag38 bit0. It does not multiply a previous alpha or scale geometry. |
| EXE VA440000 / raw40000, Init; VA440180 / raw40180, update | Effect initialization and texture changes invoke that setter with0.5. The material opacity applies to all three animated ray textures. |
| EXE global509A13; store VA476BBE / raw76BBE | False selects destination enum1; true selects enum7. Store comes from graphics setup. Complete hardware/settings fallback semantics remain unresolved. |
| DLL VA10036AB0 / raw36AB0; table VA1013667C / raw13667C | Adapter maps blend enums to Direct3D states19/20. Enum6→SRC_ALPHA, enum1→ONE, enum7→INV_SRC_ALPHA. False global therefore means additive SrcAlpha/One; true means conventional SrcAlpha/OneMinusSrcAlpha. |
The DLL REA evidence is
`ev_f5a914ee9eae593b02a04149b6651b2d783151df046bbb417624bf94f23bb96c`,
closed/exported in `artifacts/shrink-ray/rea-blend/00.json`. The parent report
links retained EXE evidence and byte-guard utility. No originals were modified
or executed for this implementation.
## Implementation and explicit policies
`MeshDraw.Opacity` defaults to1; `MeshDraw.Blend` defaults to `MeshBlend.Opaque`.
The other modes are `Alpha` and `Additive`, using exactly the source/destination
factors above for both RGB and alpha. The caller chooses the mode; opacity alone
does not enable blending. The source effect should use opacity0.5 with its chosen
graphics branch. Texture alpha is not pre-halved.
The fragment shader retains the existing texture-alpha cutout test (<0.5) and
then multiplies texture alpha by material opacity. Keeping this test and threshold
is existing port behavior; source alpha-test interaction is still unverified.
The push constant is float opacity at byte64 after the existing64-byte transform;
the68-byte range covers vertex and fragment stages. The vertex shader is
unchanged. Opaque world and opaque UI blend/depth pipeline states are unchanged.
Blended world draws test opaque depth without writing depth. This is an explicit
modern implementation policy: original shrink-ray depth-write state has not been
recovered in this bounded investigation. Rendering order is opaque world,
blended world, then UI; each pass preserves mesh draw order. There is no distance
sorting. UI modes use the same blend factors with depth testing/writing disabled
and the existing identity transform. This supports opacity without disturbing
ordinary HUD composition; it is not a recovered universal original UI contract.
All explicit draw opacities must be finite within0..1 and blend modes must be
valid, including invisible draws. Scene creation/replacement and every render
validate these properties. Per-frame validation runs before swapchain acquisition
or command-buffer recording so a rejected mutable material leaves rendering
usable after correction. All six pipelines are destroyed before their layout.
## Verification
`scripts/compile-shaders.sh` compiled both shaders for Vulkan1.3 and validated
both SPIR-V modules. Vertex SPIR-V remained unchanged. The isolated source-linked
test project builds without compiling the main runtime:
```sh
source scripts/env.sh
dotnet restore tests/GamePort.BlendTests/GamePort.BlendTests.csproj --ignore-failed-sources --source .nuget/packages
dotnet build tests/GamePort.BlendTests/GamePort.BlendTests.csproj --no-restore
dotnet tests/GamePort.BlendTests/bin/Debug/net10.0/GamePort.BlendTests.dll artifacts/gadget-blending/final-frame.ppm
```
Build: zero warnings/errors. Linux headless Vulkan runtime: llvmpipe
(LLVM20.1.2,256bits), Khronos validation enabled, **17 checks passed, zero
validation errors**. GPU RGBA readback checks exercise default opaque color,
half-opacity alpha/additive RGB equations, opaque occlusion, disabled blended
depth writes, UI ordering and depth bypass for both blend modes, zero opacity,
unchanged texture cutout, invalid opacity/enum rejection, and successful rendering
after correction. Numeric color tolerance is2/255 for attachment quantization.
Logs and a final opaque reference frame remain in `artifacts/gadget-blending/`.
These are real port GPU checks, not original-game comparisons. Windows runtime,
the selected graphics-option branch, original depth-write behavior, mixed
transparent scene ordering, and original alpha-test policy remain unverified.
Main-runtime integration and gameplay visual comparison belong to the primary
agent's integration checks.
+143
View File
@@ -0,0 +1,143 @@
# Gadget selection and control contracts
2026-10-27. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below have PE-mapped offsets in
artifacts/gadget-controls/source-contract.json. Tools guard the whole identity,
nine bounded source spans,40 instruction slices and10 virtual targets. Text
offsets equal VA−400000 for the supplied EXE. This is static recovery, not an
original gameplay capture or proof that every gadget is implemented in the port.
## REA evidence and limitations
Own generated-copy REA/Ghidra sessions are exported and closed in
artifacts/gadget-controls/rea-core/, rea-panel/ and rea-hit/.
| Procedure | Evidence |
|---|---|
|405FB0 display selection|ev_b740d70cfab21827d697151221a5cbcc0294c5d4b5742a2d3b94b10e62a08e1c|
|406590 selected HUD collapse|ev_c792af0532d5a11ecb3a602d31e3179a95b0c4b9e5242fbfe8390558b3a5c55a|
|406650 selected HUD expand|ev_dc23fb856bd21025fbfb4fb2389fae63431659f914d37475014d00dcc461fb6d|
|425870 menu-key dispatcher|ev_c2c664c7632af150fb70ecb3aaa13d8fb46c5493210a0c9af0b54a274f656ec2|
|403A20 menu group setter|ev_823efd8fa897c27a672c43a5e1859b0a4dbc8ba866593b6ab4e5db7d03b58944|
|404DE0 group/resource initialization|ev_bfded79da490ec9bc615e403ba00f4a006fe37d0f88b69fbf3a92ce433df17dc|
Queries404080,428D50,425B20,425EF0,403C50,403700,427370,403A30 and402F60
did not return pseudocode. Complete provider errors are retained; several say the
numeric input was interpreted as an unmapped file offset after no procedure
match. No successful pseudocode is attributed to those queries. Their contracts
below use reviewed instructions and fixed identity/span/virtual guards. No
unchanged failed calls were repeated. No original code was executed by this task.
## Owners and open/close transitions
Jimmy complete-object table4A3BDC maps184→425870 menu-key input,
1AC→427370 panel interaction,1F8→425EF0 open,1FC→425B20 close,
174→428D50 gadget selection.188 is429D00, **not** panel interaction.
Menu object is Jimmy complete+A18; global4F8181 is panel-open. Menu4D4 is group,
4C8 accepted item,4D8 selected HUD/display item. Global signed WORD4F0588 is a
different equipped movement/gadget mode. Menu display4D8 initializes3 at401F93;
Jimmy equipped mode initializes−1 at42225F.
425870 reads Tab at509841 and Space509858 (keyboard array509838+virtual-key),
plus controller509AC6. Shared edge latch Jimmy+1E00 suppresses repeats. With an
open panel,425AA6 calls close1FC. With panel closed and equipped mode!=-1,
425ABC calls cleanup178, writes mode−1, resets menu selection state and **returns**.
Only no-selection invokes open1F8(0) at425ADB..AF1. Thus equipped special gadget
requires one Tab to unequip and another to open; Tab is not a universal toggle.
The dispatcher also gates menu pointer, an elapsed/action field1E6C and competing
keys. Raw ownership/caller scheduling must remain distinct from this leaf branch.
Open425EF0 requires gameplay-enable4EC494 and closed panel. It collapses HUD,
sets group through menu4AC, invokes game168(1), marks panel-open, shows cursor
for groups except2 and disables Jimmy integration through interface214(false).
It also calls47D850 and clears sound-default gate4F8434. Close425B20 reverses
panel/game pause, cursor, integration and sound gate; root group0/previous-menu−1
Return simply closes. Source214 is body-enable, not raw controlled-pointer118.
Global control remains available to drive panel input while physics is disabled.
Full actor/fire/morph/music/software-clock pause ownership is not closed here;
pausing all port simulation is a broader declared policy, not this leaf proof.
Escape uses VK_ESCAPE509853 in425870 then complete1F0→42AB60. When panel is
open,42AB76 invokes close1FC and returns; it does not quit the application.
When closed it opens the separate main-menu group3, outside this gadget subset.
## Original group0 layout and rendering
404E97..404F8B constructs the eight gadget buttons in inventory-index order.
Their141×141 rectangles use strict interior comparisons in403A30:
| Item / original tile text | Top-left | Idle / hover canvases |
|---|---|---|
|0 BUBBLE|(12,182)|52 /11|
|1 ROCKET SHIP|(158,182)|46 /12|
|2 INVISIBLE|(12,327)|47 /13|
|3 SHRINK RAY|(157,327)|48 /14|
|4 SCOOTER|(342,182)|49 /15|
|5 REMOTE|(487,182)|50 /16|
|6 BASEBALL|(342,327)|51 /17|
|7 GRAPPLER|(487,327)|45 /18|
Canv20 is the640×480 base and already contains grey/unowned tiles. For current
route state1,402F60 creates both b/white and normal/green sprites.403A30 hides
green outside hover and shows it inside, leaving white idle. State0 and4 hide
both, exposing the base grey tile. Blue c assets are not bound by this group0
constructor; do not use them as an invented unavailable-state overlay.
Hit filtering skips state0/4 and missing green sprite, not every state!=1.
State3 can hit but forcibly hides green; state2/3 initial render visibility is
inherited (the initializer has no explicit show/hide branch for them). Do not
claim complete raw-state2/3 rendering from state1 behavior. Unknown states should
remain raw values, not be normalized into owned/available booleans.
403A30 scans29 entries in40-byte steps and returns the last overlapping eligible
hit. The state is menu-base+item*40+24; source sprite positions/dimensions determine
the hit rectangle. Boundaries x==left/right and y==top/bottom do not hit.
Return slot10 uses canvases182/181 at(12,95),141×78. Practice slot9 uses180/179
at(487,95),141×78. Jimmy construction4223BE..CD initializes both raw states1;
these runtime-only slots are outside the nine group0 entries serialized by TSK.
Slot8 is the separate backpack/inventory function, not a ninth ordinary gadget.
## Activation, practice and the combined default device
427370 samples the pointer and calls menu4A4→403A30. Primary activation includes
42A7A0 (left mouse, Enter, Ctrl, controller; a separate global suppressor can veto),
42A730 jump-input helper, and Enter polling46A3E0(13). It stores the accepted item
through menu478. Jimmy+1E25 is an action latch; releasing all accepted controls
clears it. This is source pointer selection; arrows/analog steer the OS pointer
in404080 using accumulated offsets±80*dt, not direct tile focus cycling.
For group0 gadget activation,4278D7 closes the panel, calls cleanup178, passes
menu4C8 to gadget174 and then re-enables body integration. Requested item3 and−1
share428DE0. That branch does **not** set global4F0588 to3: UI highlight becomes3,
while the normal equipped mode after cleanup remains−1. Ownership(0,3), HUD
highlight3, source mode−1 and the primary/jetpack action state are independent.
This agrees with the primary-fire investigation's default device path. The tile
name SHRINK RAY is authoritative art; its description113 includes both SHRINK
and JUMP/JETPACK actions. The old lab tag/internal-name explanation was too broad
if interpreted to mean no shrink-ray weapon exists.
Practice click427773..427802 toggles runtime group0/item9 between2(armed) and3,
rejecting SCENE>=500 and all VR01..08 levels. Item9 initially1 is also unarmed.
Choosing a gadget while armed invokes its direct tutorial LOAD, not Yes/No modal.
Bounded pushes/string offsets in the helper verify item0..7→vr01..08.gam. Item3
loads vr04.gam/PHONEBOOTH with authored return strings. The174 branch changes
item9 from2 to1 before loading; menu caller427903 subsequently writes3 when it
continues. The helper's default_device_selection models that174 branch, not the
entire caller's final state. Returning via slot10 also disarms practice to3.
Description records4F7EF0 stride24 map item0..7 to canvases
109,115,111,113,116,114,118,110.405FB0 and406590/6650 connect them to selected-gadget
HUD layout. No panel-hover description caller is proven; displaying BmenuL as
full-panel hover text would be a new policy. Viewport scaling/cursor placement in
the modern port remains separate from the original stretched640×480 coordinates.
## Verification and remaining scope
Seven Python groups pass in artifacts/gadget-controls/tests.log: original identity,
span/site/virtual guards; Tab states/latch; exact tile interiors and boundaries;
raw state filtering; highlight/equipped distinction; practice toggle gates; all
eight guarded tutorial destinations and initial runtime button states. The
functions are explicit source projections, not original execution or port UI
runtime verification. Primary owns integration, tests, widescreen policy and
unsupported gadget effects; this investigator changed only the three owned files.
+134
View File
@@ -0,0 +1,134 @@
# First playable gadget implementation
2026-10-27. User-directed gameplay continuation; collision checkpoint35a2a66/
0272f7b remains parked. This implements the original gadget screen and the combined
shrink-ray/jetpack device, with a bounded3SOL target consumer. It does not complete
the other seven special gadget modes, enemy combat/AI or original runtime comparison.
## Evidence and state ownership
The independent reports retain hashes, preferred VAs, mapped file offsets,
structures, callers, resource identities, REA Evidence and provider limitations:
- [Controls](gadget-controls.md):425870 keys/latch,425EF0/425B20 panel ownership,
427370 selection, exact rectangles/availability and eight practice destinations.
- [Assets](gadget-assets.md):54 exact screens.omt canvases; original tile labels,
models, morphs and sound resources. Blue c tiles are unused by recovered group0.
- [Primary fire](shrink-ray.md):426030/426E40 continuous scan, owned item3/raw
mode−1, energy−dt, strict target/obstruction gates,42AC10 callback and owned beam.
- [Heading](shrink-heading.md): original quantized heading;15 copied-DLL numeric
references and65,540 bin/quadrant cases match managed code, fingerprint24e64f91.
- [Targets](shrink-targets.md): actual3SOL constructor/load, radius90/factor1,
WALK/SHRINK clips, nonloop endpoint, authored/reset versus previous dynamic mode.
- [Blending](gadget-blending.md): source half opacity and blend enum conversion;
opaque/alpha/additive rendering implementation and explicit depth-write policy.
- [Review](gadgets-review.md): independent code/evidence review; missing ordinary
+10 callback corrected, eligibility defaults and remaining limits recorded.
Menu display item3 and equipped-mode word are separate. Selecting SHRINK RAY
closes the panel, cleans old special mode and leaves normal raw mode−1; item3
ownership also gates jetpack. SceneInventory.SelectedGadget remains the port's
display/request index; PlayerSceneBinding normalizes3 to raw mode−1. Existing
retained route state remains bounded to default device display−1/3.
## Implemented behavior
GadgetScreen/GadgetMenuOverlay use the original640×480 background, owned idle/
hover tiles and buttons, with uniform centered widescreen scale and inverse
pointer mapping. Tab/Space shares a held-key latch. First Tab unequips a special
mode, next opens. Escape/Return closes; mouse or Enter/Ctrl/jump buttons activates.
Arrows steer the pointer through the recovered accumulated80×dt offsets. Raw0/4
cannot hit; raw3 suppresses green hover. Current route0/1/4 rendering is recovered;
inherited raw2/3 idle visibility uses a declared owned-white port fallback.
Practice arm/choose loads the selected original tutorial directly, independently
of the pickup's Yes/No prompt. It rejects VR01..08 and SCENE>=500; runtime practice/
Return slots are not serialized in TSK. Selection observers see the panel closed.
Input capture clears held movement/jump/fire and preserves Space cutscene skip
when the panel cannot open. New SFX requests use the source panel gate; music
continues. Pausing all port gameplay/morph timers during the panel is broader than
the recovered body-enable/game168 leaves, and remains an explicit modern policy.
LabSimulation invokes gadget input in its existing fresh/retained input phase.
Grounded fire clears controller speed before movement apply and selects original
SHOOT. The ordinary FALL branch hides/stops the ray. Ray ownership requires
inventory(0,3)==1/raw mode−1; invalid ownership clicks117 once until release.
Held ordinary ray uses looping SFX0, spendsdt energy even without a hit and is
energy-exempt in VR01..08. Existing powered jump/fire remains independent.
ShrinkRay implements the continuous registry-order multi-target scan: body and
shrink-enable flags, not already shrunk, strict1500 distance, strict Y−150/+60,
strict quantized heading within yaw±5 with no added seam wrapping, and no accepted
source47C210 static-wall hit. The caller currently supplies only original3SOL
soldiers in LV1B/VR04/LEV1; only VR04 actually contains those actors.
Each ordinary hit requests SHRINK, sets mode5, timer30 and shrunk flag, awards10
through SceneInteractions and then writes the reaction marker. Score persists in
original-format snapshots. Already-shrunk targets do not receive repeated awards.
LIBBYPLANT/C3DDINO quest branches remain outside this3SOL consumer. Timer updates
preserve the source >0 decrement/<0 expiry edge, including exact-zero retention.
Expiry restores authored/reset AIState (VR04=2), not the pre-hit dynamic mode,
clears the marker and selects looping WALK/speed200.
Original soldier WALK/SHRINK geometry uses soldatak's matching original UV topology;
walk/shrink ASE files contain no UVs. Source SHRINK holds its last authored frame
(55.1186 high), without invented uniform scaling. The transition preserves frame
ordinal; exact within-frame clock preservation remains open. Source roots and
units are retained. Soldier body settling uses the existing provisional NPC
support/wall adapter with recovered90/1, not a claim of complete enemy physics.
The owned RAY mesh follows the captured player root/upright Euler without invented
muzzle offsets, lifetime or cooldown. Three source textures switch at the recovered
float-accumulator >double0.1 boundary, discarding overshoot. Source alpha0.5 is
applied once, not as geometric scale. Additive SrcAlpha/One is the chosen recovered
graphics branch; the source graphics-option predicate is still open. Generic alpha
SrcAlpha/OneMinusSrcAlpha is also implemented. Blended world depth-write disabled
and inherited cutout behavior are explicit rendering policies, not full legacy
material-state recovery. Opaque defaults and UI ordering are regression checked.
## Verification
Full scripts/test.sh passes157 Python checks,2 HUD tests, all managed suites,
29 game GPU completions and17 isolated Vulkan blend/readback checks with zero
enabled validation errors. Fifteen gadget groups cover menu/state/viewport,
source target gates, phase clock, held/release/energy/sound, authored morph hold,
score callback order and TSK persistence. Heading covers the65,540 original-DLL
references separately.539 original files remain unchanged.
Final source close-before-selection and authored-mode corrections pass the
complete final suite in integration-final.log; the latter distinguishes pre-hit
dynamic7 from restored authored2. No old numeric body/controller result changed.
Native Linux GTX1070/private Xvfb passes gadget-menu input at1920×1080 and ray
input at1280×720, with zero validation errors. Menu24 frames verify shared
Tab/Space edge, pause, Escape, select without leaking fire, Practice, Return and
stable root. Ray90 frames hits an actual VR04 yoke1 once, holds its authored small
pose, cycles all three textures and retains VR energy20.
Final source replay logs are native/menu-final.log and native/shrink-final.log.
The ray smoke explicitly moves the player near an actual authored soldier after
body settling. It does not invent/relocate targets or claim input navigation to
their high platforms, patrol/combat AI, or original visual parity. Saved mesh
height is a port animation observation; GPU readbacks verify rendered output and
material behavior. Logs/readbacks are in artifacts/gadget-implementation/ and
artifacts/gadget-blending/. Windows cross-publish/native runtime remain distinct.
## Remaining work
| System | Recovered contract | Current port / remaining boundary |
| --- | --- | --- |
| Selection | Group0, eight cards, display3 versus raw−1, close before select | Implemented; inherited raw2/3 art visibility is a declared fallback |
| Practice | Selected item→VR01..08, disabled in tutorials/SCENE>=500 | Implemented through existing departure/RETURN state |
| Primary ray | Owned item3==1, continuous held scan, FALL interruption | Implemented in first-route scenes; full Euler/retained owned-effect lifecycle open |
| Energy/audio | Energy−dt, VR exemption, loop0, invalid117, warning80/182 | Scalar/loop/invalid implemented; warning latch and broader sound lifecycle open |
| Soldier hit | Strict target gates, SHRINK/mode5/timer30, +10 then marker | Actual VR04 3SOL implemented; later eligibility setters/AI and special quest classes open |
| Restore/animation | Strict-negative expiry, authored AI mode, WALK200, nonloop SHRINK | Implemented; exact fractional morph clock and full NPC physics remain provisional |
| Rendering | Original mesh/textures, opacity.5, two blend branches | Tested additive choice; graphics-option predicate/full material state open |
| Timing/ownership | Body enable and SFX gate on menu, original input phase | Existing phase bridge used; full-panel pause is modern policy, complete scheduler open |
Other gadget effects/equip cleanup, full soldier AI/reaction consumers and
dynamic collision; score popup and other quest targets; low/empty energy audio
latches; owned-ray retention across loads; exact full-Euler/render root and morph
phase; complete menu/music/software-clock lifecycle; original whole-game and
native Windows verification. These are bounded follow-ups, not reasons to replace
recovered source rules with invented cooldowns, damage, colliders or uniform shrink.
+117
View File
@@ -0,0 +1,117 @@
# First gadget integration review
Review of `SceneGadgets`, `ShrinkRay`, `LabSimulation`, `ShrinkRayVisuals`,
`ShrinkSoldierVisuals` and their `Program` wiring against
[shrink-ray.md](shrink-ray.md), [shrink-heading.md](shrink-heading.md) and
[shrink-targets.md](shrink-targets.md). This is a read-only source/evidence review,
not new gameplay runtime verification. It records the snapshot before the
primary's review fixes; subsequent implementation/tests must mark fixes verified.
Update during review: the primary added `ScoreAwarded`→`ChangeScore` wiring and
the source hit marker. Reading the updated code confirms ordinary +10 reaches
the score/save owner and the marker is set after the event; build/runtime checks
belong to the primary. The initial finding remains below as the reason for that fix.
## Directly evidenced callback omission
**Resolved: the initial implementation omitted the original +10 score callback.**
The initial `SceneGadgets.Input` applied `ShrinkSoldier.Shrink()` and incremented a diagnostic
hit counter without awarding persistent `SceneInteractions.Score`. Primary now
awards/persists10 and sets the reaction marker after the score event; its managed
test verifies ordering and the original-format save round-trip. Original
`42AC10..42ADB5` (raw `2AC10..2ADB5`, same guarded source identity as the ray
report) performs action/mode/timer/flag writes, then branches on the target's
ObjectTag at interface+3A0:
| Tag comparison / address | Recovered effect |
| --- | --- |
| `LIBBYPLANT`, 42AC84–42AC9B | Find `C3DLIBBY`; if found, award 100, mode 0, write 160 to complete6C4, set two action strings to WALK, and change SCENE 250→255 if currently 250. |
| `C3DDINO`, 42AD3F–42AD7E | If task DINO <10, set DINO=10 and award 300; otherwise return without those effects. |
| Every other tag, 42AD81–42ADA1 | Award 10 through42ADC0; write target complete94C/interface88C=1.0. |
`42ADC0..42ADF9` (raw `2ADC0..2ADF9`) adds with signed 32 arithmetic, clamps
negative total to 0, and for positive awards records the amount at 4F83C4 with
1.2s at 4F83C8. Existing score/save ownership belongs to `SceneInteractions`;
the shrink hit diagnostic is not a substitute. Preserve the reaction field as
an explicitly identified dependency of the still-unported enemy base/AI update;
its complete consumer semantics have not been recovered by this review.
Read-only GAM parsing confirms first-route scope:
- `level1b.gam` (lab): zero 3SOL actors.
- `VR04.gam`: three 3SOL, tags `yoke1`, `C3DYOKIANSOLDIER`, `yoke2`.
- `Level1.gam` (outside): zero 3SOL actors.
Thus all currently supported real target hits use the ordinary +10 branch,
including VR04. The callback has **no VR score exemption**. Do not apply the
energy exemption to score, invent a generic quest/objective update, or award
the special branches for every enemy of a matching class. Earlier vague
Humphrey descriptions do not identify this branch: the exact shipped string is
`C3DLIBBY` at4EF710. The apparent SE9 call at 42AC17 reaches `472970`, whose body
is `C3`/return; it is not evidence for another hit sound.
The primary's regression now checks the +10 save effect once per accepted
unshrunk target, simultaneous targets and later re-shrink after restoration,
while VR energy stays unchanged. The reaction-field consumers and unsupported
quest classes remain named limits rather than inferred combat behavior.
## Confirmed source alignment
- Owned item 3 must equal 1; equipped mode is −1 even when UI display item 3 is
highlighted. There is no positive-energy gate or projectile cadence in the scan.
- The scan is continuous while held. Current strict root height, distance<1500,
quantized original heading, no added heading seam wrap, geometry-query rejection
and multiple-hit behavior agree with the bounded source contract.
- The corrected FALL logic is sound: at 42692A an absent loop branches to426937;
`strcmp(FALL)==0` at 426948 skips the scan. With a loop present, equality at
42695F falls through stopping its handle, setting−1 and hiding the beam at
426963..426989. Other airborne actions can start/retain the loop and scan.
The port correctly blocks FALL, not all airborne poses, and reserves SHOOT for
grounded fire. Source speed608 is zeroed before this branch, including air.
- Beam position/yaw are captured when firing and rendered from that snapshot;
they should not be replaced with the player's later render-frame root. Source
copies root and full Euler at 426EF1/426F47, with no caller muzzle offset.
- Texture phases 0/1/2 use a float timer compared strictly with double0.1, advance
at most once and discard overshoot. Opacity .5 and additive drawing implement the
known global509A13=false branch. Conventional alpha is the other recovered
branch; the original settings/hardware choice is unresolved, so additive is
an explicit port policy, not a universally recovered default.
- Soldier geometry uses original WALK/SHRINK topology, actual GAM roots and an
authored nonlooping shrink morph. False selector preserves a clamped frame
ordinal; modern within-frame clock is explicitly approximate. There is no
invented uniform scale. Strict-negative expiry, WALK restart and restored
speed 200 follow the source. Radius 90/factor 1 are source defaults; reuse of the
existing scene-physics adapter remains provisional collision behavior.
## Material bounded differences and next checks
1. **Energy audio:** direct subtraction/clamp in `SceneGadgets.Input` matches the
scalar part of42A920, but omits its empty-crossing SFX80 and low-energy SFX182
latch/hysteresis (<19 to set, >20 to clear). VR04 masks this omission through
its energy exemption. Share the energy-adjust lifecycle before claiming source
fidelity outside VR04; do not add an unsupported energy>0 firing restriction.
2. **Full Euler:** the effect and wall endpoint use only yaw. Source copies all
Euler components. This is bounded by the present upright controlled-player
model; source pitch/roll behavior and generic Euler normalization remain a
dependency. Preserve full snapshots when that orientation model is implemented.
3. **Eligibility:** both source defaults are now confirmed. Generic constructor
46FDDF (raw 6FDDF) pushes 1, then46FDE3 calls471030. That setter writes authored
+16 at471037 and dispatches slot 214 at47103A; soldier game vtable4C19C4+214
contains471A00, whose471A04 writes live interface13E. Yokian constructor44A94F
(raw 4A94F) writes complete958/interface898=true;44A905 clears shrunk. Actual
soldier constructor44BF32 calls shared44A730; loader44C0B0 does not override
these flags. This agrees with the prior guarded body-composition finding
integration210/live13E=true. The current default-true candidates cover these
initialized actors under the no-AI boundary, but do not mirror later setters.
Actual VR04 GAM CanMove1 is the separate animated-object58C field; do not
equate it, generic `Actor.Active`, or visibility to the source body/shrink gates.
4. **Scope/ordering:** soldier AI, shared enemy reaction-field consumers, full
registry scheduling and hidden-owned-effect initialization remain outside this
first interaction. The modern step order is an implementation partial order;
standalone or rendered smoke success does not verify the original game's
complete update order. A native Windows walkthrough still needs hold/release,
jumping/FALL interruption, a wall-blocked target and 30s restoration checks.
No additional runtime changes were made by this review. Existing complete REA
Evidence/source guards are reused; unavailable source42AC10 decompilation was
not retried. Exact callback branches above were cross-checked against the guarded
original instruction range and source string bytes.
+148
View File
@@ -0,0 +1,148 @@
# Shrink-ray heading recovery
This closes the heading dependency of the held shrink-ray scan in
[shrink-ray.md](shrink-ray.md). Facts below come from immutable original bytes,
REA/Ghidra 12.1.4, and an isolated component call to a generated DLL copy.
The managed implementation is `src/GamePort/Game/OriginalHeading.cs`;
`OriginalHeading.Degrees(targetRoot - jimmyRoot)` returns the quantized source
heading. The caller must retain the original strict EulerY±5 comparison without
adding seam wrapping. Whole-game target selection remains a separate integration
and runtime check.
## Source identity and ownership
Original EXE SHA256:
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
OMT2.dll SHA256:
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
Generated targets were `artifacts/uncontrolled-phases/rea/Neutron.exe` and
`artifacts/asset-probe/game/OMT2.dll`. No original was modified or executed in
place. The focused helper checks both complete hashes, the import/export mapping,
13 instruction sites, six constants, and the regenerated lookup fingerprint.
| Owner/location | File offset | Recovered role |
| --- | --- | --- |
| EXE IAT0048D108 | `8D108` | OMT2 import `?angles@OMedia3DVector@@QAEXAAF0@Z` |
| EXE 00426FE4–00427011 | `26FE4` | Stores float32 target-root minus Jimmy-root vector |
| EXE 004270B1–004270C5 | `270B1` | Calls vector::angles with two signed-short references |
| EXE 004270D7–0042713B | `270D7` | Reads second output; strict heading-window comparisons |
| DLL 1001FDA0–1001FF6E | `1FDA0` | Export 278, `OMedia3DVector::angles(short&,short&)` |
| DLL 1001FDCB–1001FE3D | `1FDCB` | Computes horizontal lookup/quadrants; stores second output |
| DLL 100EDC00–100EDD2A | `EDC00` | `OMediaCosSinTable::init_table`; table generation |
| DLL 10104E04–10104E2B | `104E04` | Integer conversion explicitly switches x87 to truncation |
| DLL 10161E38 | runtime-initialized table | Half-acos unsigned-short table, global object+20008 |
Ranges above end exclusively. EXE addresses use base00400000, DLL addresses
base10000000; these source ranges have raw offset=RVA. Full range hashes and
checks are in generated `artifacts/shrink-ray/heading-source.json`.
## Recovered algorithm
Only vectorX and vectorZ affect the second output. It is always in 0..16383,
although the caller reads it with sign extension. One unit is exactly
`360/16384 = 0.02197265625` degrees (EXE float0048E5B4).
For finite float32 components, with extended intermediates in the original:
```text
if x == 0 and z == 0: return 0
i = trunc(16384 * z*z / (x*x + z*z))
a = halfAcos[i]
if z < 0:
a = (x < 0) ? 8192+a : 8192-a
else if x < 0:
a = 16384-a
return (-a) & 16383
```
The original actually truncates the negative ratio multiplied by−16384 and
subtracts that integer from the combined-table base index10004. The positive
index formulation above is equivalent on finite inputs. There is no atan2 call.
The table contains truncated integers:
```text
halfAcos[i] = trunc(acos(i * .0001220703125 - 1)
* 2607.5945876921437 * .5) # i=0..16383
halfAcos[16384] = 0 # explicit final endpoint
```
The stored constants and truncation are significant. The first 16384 words match
the previously observed copied-DLL FNV32 `4f800433`. The 16385-word little-endian
table SHA256 is `292eaae8707bcbc0e760280eca51ecb760914dbac81e943428219713e9065744`.
| Direction | Heading units | Degrees |
| --- | ---: | ---: |
| +Z | 0 | 0 |
| −X | 4096 | 90 |
| −Z | 8192 | 180 |
| +X | 12288 | 270 |
| X=−1,Z=+1 | 2048 | 45 |
| X=+1,Z=+1 | 14336 | 315 |
| X=+1,Z=1000 | 16364 | 359.560546875 |
| X=−1,Z=1000 | 20 | .439453125 |
| X=1000,Z=1 | 12288 | 270 |
This orientation matches the port's forward vector `(−sin(yaw),0,cos(yaw))`.
The coarse ratio table near cardinal axes is part of recovered behavior;
replacing it with rounded atan2 would change target acceptance near the 5° edge.
The scan calls this after its root-height and distance filters. The first
reference receives pitch and is unused here. For the zero vector the copied DLL
returns pitch 4096/yaw 0; this utility intentionally implements only yaw.
## Window and state interaction
At004270D7 the scan reads the second output from stack +16. It multiplies by the
stored degrees factor, compares strictly greater than JimmyEulerY−5, then at
00427112 compares strictly less than JimmyEulerY+5. The 5 is stored at0048D950.
Rejected targets branch to00427310, the next registry entry. These instructions
perform no modulo normalization, shortest-angle difference, nearest-target
selection, cooldown, or heading hysteresis.
Consequently a tiny positiveX target can yield359.56° and fail when JimmyY=0,
while its mirrored negativeX target yields .44° and passes. Do not repair this
asymmetry speculatively. Original Euler normalization outside this caller is a
separate system dependency.
## Evidence and verification
REA Evidence
`ev_944c7a8e63e2c332ecaabe01ddb6587f0c4b25ee087124e15394d617a94b2633`
is retained completely in `artifacts/shrink-ray/rea-heading/evidence.json` and
`analysis.snapshot.json`; extracted pseudocode is `heading.pseudo.c`.
The Ghidra call completed in 254.6s, beyond the existing batch client's 180s wait.
The client then closed its owned session successfully. The complete result was
recovered from that closed snapshot; no unchanged request was repeated. Ghidra's
x87 pseudocode omits portions of the ratio expression and misnames some stack
values; the instruction stream, not those temporary names, establishes the
formula above. `heading-source.json` records source offsets and range hashes.
`tools/binary/shrink_heading.py --emit-probe <generated.c>` emits a bounded probe
using only LoadLibrary/GetProcAddress on the generated OMT2 copy. It calls the
export with synthetic vectors; no game entry point is run. The existing
`tools/recon/reference_capture.py` harness isolates its filesystem/network and
does not mount Original/. Retained output is
`artifacts/shrink-ray/heading-probe/wine.log` and `capture.json` (exit 0). The first
six-second attempt ended during cold Wine initialization; its capture/log were
retained separately. The changed thirty-second run completed normally.
Observed: 15 explicit vector results and 65,540 generated bin/quadrant cases.
The sweep's word-wise FNV32 is `24e64f91`; both Python and managed implementations
match. This verifies the component under Wine, not full gameplay or native
Windows behavior. The source uses x87 extended intermediates; the managed/Python
projection uses double. Arbitrary float32 inputs exactly at ratio-bin boundaries
remain a precision risk beyond the observed sweep. Nonfinite vectors are rejected
explicitly by the modern utility; original invalid-input behavior is not claimed.
Reproduce from GamePort/:
```sh
python3 tools/binary/shrink_heading.py
python3 -m unittest discover -s tests -p test_shrink_heading.py -v
source scripts/env.sh
dotnet run --project tests/GamePort.HeadingTests
```
Remaining: integrate the utility with the scan's eligibility/raycast/callback
contract and compare actual target acceptance in gameplay. No unresolved heading
quadrant or table dependency blocks that integration.
+147
View File
@@ -0,0 +1,147 @@
# Shrink ray primary fire and owned effect
2026-10-27. Read-only static recovery from supplied EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below map to raw file offset VA−400000 for this image's text;
shrink_ray.py independently PE-maps all locations and guards eight bounded
function ranges plus44 source sites. No original code was executed by this task.
## Important identity correction
The inventory/menu highlight is not the raw equipped-mode word4F0588. The
[gadget control investigation](gadget-controls.md) proves selecting group0/item3
cleans current mode to−1, then calls equip174(3); cases3 and−1 leave that mode
unchanged.426E40's shrink scan requires owned item3==1 **and mode−1**. The same
item owns the recovered jetpack ability. Earlier jetpack-only descriptions that
treat SHRINKRAY as an unrelated internal label are superseded by this combined
source path and the original item's SHRINK/JUMP art. Do not implement selected
mode3 as a separate shrink-ray state merely because the menu highlights item3.
## Primary input and animation ownership
| VA / raw | Recovered contract |
|---|---|
|426030 /26030|Input callback first requires407060 false,475CA0 true, controlled5099E4 nonnull, global4F8430 false and interface1D2D false. Movement438A60 and gadget subhandlers run before the ordinary fire tail.|
|42A7A0 /2A7A0|Primary helper is false while4F83E0 is set; otherwise OR of509834,509845,509849,509AC4. Readme maps Enter/Ctrl/left mouse; pad input remains separate.|
|426566..42657F /26566|Held primary helper OR keyboard13 invokes the held-fire branch. Release stops the owned sound loop and hides the ray.|
|42668F..4266BD /2668F|Busy1D65 or modal4F8182 rejects; raw mode0 rejects; otherwise controller speed608 is set0.|
|4266C8..4266F1 /266C8|Grappler/energy subhandlers run; mode4 exits; ordinary mode−1 continues.|
|4266F7..42672B /266F7|Supported body requests SHOOT, then animation148. The caller's grounded shooting pose, not the collision support routine, owns this action.|
|4268BE..4268F7 /268BE|Owned item3 must equal1. If sound handle interface974==−1, start SFX0 looping and retain its handle. Invalid availability emits SFX117 and latches busy1D65 until release.|
|426902..42698C /26902|Airborne branch permits the ordinary fire path around the FALL action and owns its own loop interruption; do not force all airborne frames to grounded SHOOT.|
|4269BD /269BD|Complete virtual1B8 invokes426E40 after these gates. No one-shot cooldown or projectile spawn is present in426E40. It is a held, per-input-invocation scan.|
Raw primary callback physics/control predicates are separate from the modern F1,
inspection, focus and practice modal policies. New primary input must be cleared
at modern capture boundaries and must not leak into cutscene skip/menu selection.
## Target scan and hit order
426E40..427334:
1. Require403950(group0,item3)==1 and signed4F0588==−1.
2. Show Jimmy-owned complete object+A10 (interface+950) if present. Copy Jimmy's
current root exactly via318 and current Euler exactly via330. There is no
muzzle offset in this caller; the original ASE supplies the effect geometry.
3. Call42A920(−dt) once **before target traversal**, even if there is no hit.
There is no positive-energy test in this ordinary scan.42A920 exempts original
VR01..VR08, otherwise clamps energy0..100 and owns low/empty sounds/latches.
4. Traverse object registry50999C in linked order. Payload is the game interface.
Require interface13E nonzero, class-name check18(`C3DENEMY`), interface898
nonzero and interface8B0 false (already-shrunk flag).
5. Require enemy rootY strictly greater than JimmyY−150 and strictly less than
JimmyY+60. Full root-to-root Euclidean distance must be strictly below1500.
6. Call imported vector calculate_angles48D108; convert its signed-short heading
to degrees with stored float0.02197265625. Require heading strictly inside
JimmyEulerY−5 .. JimmyEulerY+5. These instructions add no seam wrapping; exact
angle production/convention and generic Euler normalization remain a separate
numeric contract. The helper projection accepts the recovered heading as input.
7. Build a source ray from Jimmy root+(0,150,0) to offset384(0,150,distance).
Call47C210 and reject on **any accepted wall-query hit**. This is the original
static grid/winding query, not nearest sphere sweep or a pixel/crosshair test.
8. For each accepted enemy invoke Jimmy complete1DC→42AC10(target interface).
There is no break/nearest-target reduction: multiple eligible enemies may be
hit in a single invocation. Registry order and source wall query are dependencies.
42AC10 requests exact action string `SHRINK` at4EF71C with argument0 through
enemy completeE0, sets enemy complete124(5), then complete974=30.0 and
complete970=true. Those fields are interface8B4 timer and8B0 flag. It also owns
class/tag-specific objective, score and Humphrey policy, so generic shrinking
must not invent a universal score or destruction event.
The independent [target investigation](shrink-targets.md) owns actual3SOL class,
SHRINK morph, timer expiry and restored action. Its source check corrects an
initial label:44AEC6 requests `WALK` (4ECA54), not STOP. Visual shrink is driven
by the original morph/action; do not substitute an invented uniform scale.
## Beam effect is an owned object, not a ballistic projectile
Jimmy constructor4222AB allocates6D0 bytes;4222C9 calls43FE20 and4222D9 stores
the resulting complete object at Jimmy+A10.43FE20 establishes C3DShrinkRay
interface table4B4350, invokes440000 Init and disables its physical collision
through220 setter4710C0. Phase complete6BC starts0 (interface5FC).
440000 Init binds `HIRAY`→`ray.ase` at440037, then texture slots0/1/2 to
ray0000.png/ray0001.png/ray0002.png. It sets action `RAY`, radius40 and source
factor0.3; these physical values do not imply a moving projectile. The caller
keeps the owned effect at Jimmy's root/Euler while held and hides it on release.
**Opacity, not scale:** C3DShrinkRay complete114 resolves40E4A0. Positive param
walks shape polygons and each nonnull material, writes RGB1 and alpha=param to
material+4C..58, source blend field+30=6, destination+34=7 when global509A13 is
true or1 otherwise, and ORs material flag38 with1. Init and every texture switch
call114(0.5). The earlier per-texture RGBA writes also set0.5; this setter
replaces the alpha rather than multiplying it again. No geometric half-scale is
justified.
The engine adapter10036AB0 (raw36AB0) uses table1013667C (raw13667C) to map both
material enums into D3D render states19/20. Selected entries are6→D3D5 SRC_ALPHA,
1→D3D2 ONE,7→D3D6 INV_SRC_ALPHA. Thus global509A13=false selects alpha-weighted
**additive** blending (SrcAlpha,One), while true selects conventional alpha
(SrcAlpha,OneMinusSrcAlpha). The flag is loaded from a graphics-setup option and
stored476BBE; its complete settings/hardware fallback semantics remain open.
Do not silently treat both branches as conventional alpha. The DLL SHA256 is
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
440180 interface3C4 update first invokes base40E050. On its first pass a flag
interface604 causes Init through1C; then float timer600 adds dt. When strictly
greater than **stored double0.1**, phase5FC increments, wraps after2 back0,
swaps the bound texture, reasserts opacity0.5, and resets timer0. It advances at
most once per invocation and discards overshoot. Since float0.1 is slightly above
double0.1, passing an exact float0.1 triggers the switch. No independent finite
beam lifetime is present; hold/release and object visibility own it.
## REA evidence, gaps and checks
The three owned EXE REA sessions used the generated hashed
artifacts/uncontrolled-phases/rea/Neutron.exe and closed/exported normally.
A fourth session used the generated artifacts/asset-probe/game/OMT2.dll copy for
the blend adapter, also closed/exported under artifacts/shrink-ray/rea-blend/.
| Retained path | Successful Evidence |
|---|---|
|artifacts/shrink-ray/rea-primary-followup/03.json|42A7A0 ev_3ff9cde0cab7a1e7ed456591becfcc4c4f4db3796aa6ab5e76a1dd124f9dac47|
|rea-primary-followup/04.json|42A920 ev_71897af12f4bfa1de946c6f17f3bbed34764fdc84258ce64516c8f1f904b465d|
|rea-effect/00.json|440000 ev_875816ebeb0d690c83518f14f36a13d646009d3530c0ad1f27efbd3a2342aeff|
|rea-effect/03.json|43FE20 ev_3ae9cf6456693b674f937b0e4c86392b88f0d80f8eb416e5b7585f08f790e7f9|
|rea-blend/00.json|10036AB0 ev_f5a914ee9eae593b02a04149b6651b2d783151df046bbb417624bf94f23bb96c|
426030/426E40/429D00 VA queries were unrecognized; corrected raw-offset selectors
were tried once and also failed.440180 and42AC10 likewise have no recognized
procedure in this profile. Errors/complete diagnostics remain beside successful
Evidence; their conclusions use fixed source instruction/body guards and the
matching class/vtable/asset chain, not invented successful decompilation.
`python3 -m unittest discover -s tests -p test_shrink_ray.py -v` passes seven groups:
source bodies/constants/assets/opacity anchors; owned3/mode−1; independent target
gates; strict range/height; strict quantized-heading/no-added-wrap; texture float/
double threshold, wrap and discarded overshoot; DLL body/table identity and
additive/conventional-alpha factor distinction. These are source projections,
not original execution or managed/native gameplay verification. Complete source
report can be generated with shrink_ray.py ../Original; originals remain read-only.
Remaining: exact imported heading production/Euler normalization, full airborne
SHOOT interruption, graphics-option/depth order, full enemy class/
script/score policies and original whole-game runtime comparison. The source
device's held geometry, textures, ownership gates and target callbacks support a
bounded first implementation; a synthetic projectile cadence is not supported.
+198
View File
@@ -0,0 +1,198 @@
# Original 3SOL shrink targets
Status: recovered static binary/asset contract for a bounded first shrink interaction.
Original runtime verification, full soldier AI, and exact collision integration remain open.
Originals were read only; REA inspected generated hashed copies, never executed originals.
Run `python3 tools/binary/shrink_targets.py ../Original` to produce the guarded contract,
including PE-mapped **file offsets** for every address below. Saved output:
`artifacts/shrink-targets/source-contract.json`. Addresses in this note are preferred-base VAs.
## Evidence ledger
REA results, complete evidence, snapshots, and closed-session records are retained under
`artifacts/shrink-targets/`. REA observations are static analysis, not runtime traces.
| Question | REA Evidence ID | Saved directory |
|---|---|---|
| Shared Yokian construction | `ev_19d3441021faa1f39087a8e65e3b04df57315de2ee53f75b2e70fce2dc8a432d` | `rea-soldier/` |
| Shared Yokian update | `ev_c7d9d0bd6ea80f021689545e79baca422ca5b526d69c89d7ccf54c4ea2142a18` | `rea-soldier/` |
| Actual soldier construction | `ev_64b0152bae4f3a51a80c70f6470212b5c5cb9036e449d5eefe6129b35ace70c2` | `rea-soldier-bindings/` |
| Soldier model/texture loading | `ev_4e46100718fc9d13d99409941d2494de216d281317a04fd9e56ad33e1aa3e6ec` | `rea-soldier-bindings/` |
| Generic load caller | `ev_efdc2d429180a0cd692326a261bc274ac5cb0daf45ab167c0627a858acabf041` | `rea-soldier-bindings/` |
| Engine sequence selection | `ev_67aff8ee9529fa39014ae438e22e3dc52ecd2ce71d0886974d0682d6eea58f8b` | `rea-sequence/` |
| Engine endpoint/loop handling | `ev_e0d4f2ee9131d62ea289ea1aeb0f24b7de4a2bd696149309e9dfb2e3d14614df` | `rea-loop/` |
| Dynamic mode setter | `ev_8286c3d9b13f47f1e6fbf211d85636b54fb5ccb7cc7e55dd1e0f0366a7170b84` | `rea-mode-local-ipc/` |
| AIState property registration | `ev_aa47a422ce39fc5bf5bbca319fe3c37e27526299abeb9f6cdb9d065d46de9f50` | `rea-mode-local-ipc/` |
| Generic load/reset state | `ev_c448bb4062e760eb4bf3b09d39e630b130a8eafd377a27625a25b69ab7679a27` | `rea-mode-local-ipc/` |
The first mode-closure attempt (`rea-mode/00.json`) failed because the sandbox
blocked Ghidra's local Unix-socket bind. The successful invocation above used
local IPC permission; no provider/client configuration was changed. Its complete
Evidence and close/snapshot records are retained. The failed call is not used
as evidence for source behavior.
`Neutron.exe` SHA-256: `f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
`OMT2.dll` SHA-256: `3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
The helper guards eight bounded code ranges, decisive byte sites, vtable targets,
resource strings, and all three ASE hashes; it fails on an unexpected identity.
## Class ownership and initialization — recovered
`44A730` constructs shared **C3DYokian**, not the final soldier. Actual soldier
constructor `44BEE0..44C028` calls it at `44BF32`, then registers FourCC `3SOL`
at `44BFF5`. Soldier complete-object vtable is `4C1E64`, game-interface vtable
`4C19C4` at complete object `+C0`, and embedded morph vtable `4C1E14` at `+90`.
The generic model loader `40E270` dispatches complete slot `10C` at `40E331`,
reaching soldier loader `44C0B0..44C1BB`. Derived update `44C1C0` calls shared
Yokian update `44AA00` at `44C1C9`.
| Complete slot / callsite | Recovered binding |
|---|---|
| `D8` / `40D4A0` | Register model animation definition |
| `E0` / `40DD90` | Select named action; chooses HI/LO family |
| `E4` / `40DA30` | Select underlying sequence and copy loop flag |
| `10C` / `44C0B0` | Soldier model load |
At `44C19D` the soldier pushes float **90** into game-interface slot `110`
(`471240`, authored radius setter; live setter slot `264`). At `44C1AC` it
pushes float **1** into game-interface slot `100` (`4711E0`, authored factor;
live setter slot `254`). Live read slots `260`/`250` reach `471B30`/`471AF0`.
These are soldier body defaults; they do not establish the full collision solver.
## Model, texture, and authored shrink geometry — recovered
| Registration site | Action | Original ASE |
|---|---|---|
| `44C0C3/44C0C8` | `HIWALK` | `ASE/soldwalk.ASE` |
| `44C0DC/44C0E1` | `HISHRINK` | `ASE/soldshrink.ASE` |
| `44C0F0/44C0F5` | `HITALK` | `ASE/soldatak.ASE` |
| `44C104/44C109` | `HISTOP` | `ASE/soldatak.ASE` |
The loader compares scene FourCC against `VR01..VR08` at `44C121/44C128`.
For those scenes both texture indices 0 and 1 use `vryoksoldier.png`
(`44C133/44C144`, string `4F1950`). Supplied filename is
`png/VRyoksoldier.png`; portable lookup must ignore case. Other scenes bind
index 0 to `png/yoksold.png` (`44C14F`) and index 1 to `png/yoksoldtalk.png`
(`44C160`). Loader selects `WALK` with second argument 1 at `44C184`.
All three ASE clips have 190 vertices and 377 faces. `soldwalk` and
`soldshrink` have five samples at ticks `0,960,1920,2880,3840` (5 fps,
960 ticks/frame); `soldatak` has two samples (10 fps, 480 ticks/frame).
In existing ASE→OMT coordinates, shrinking sample Y bounds are:
| Tick | Minimum Y | Maximum Y | Height |
|---|---:|---:|---:|
| 0 | -55.6508 | 260.1789 | 315.8297 |
| 960 | -19.5291 | 208.5813 | 228.1104 |
| 1920 | -28.4904 | 156.9837 | 185.4741 |
| 2880 | -4.0918 | 105.3861 | 109.4779 |
| 3840 | -1.3301 | 53.7885 | 55.1186 |
This is actual morph deformation. A uniform quarter-scale soldier would be an
unsupported replacement. No extra uniform render scale was established in the
inspected source. The visual can retain original vertex units and authored root.
## Shrink, animation ownership, and expiry — recovered
Jimmy callback `42AC10` (investigated separately in `shrink-ray.md`) receives an
enemy game interface and subtracts `C0` to obtain the complete object. It selects
`SHRINK` with argument 0 at `42AC33`, selects mode 5 at `42AC50`, writes timer
complete `974 = 30` at `42AC68`, and writes flag complete `970 = true` at
`42AC8A`. The shared constructor initializes that flag false at `44A905` and
timer zero at `44A7EA`. Game-interface-relative offsets are timer `8B4` and flag
`8B0`; authored/reset mode is interface `87C`, complete `93C`.
### Mode setter and restoration ownership — closure
Soldier complete vtable `4C1E64` slot `124` points to generic enemy setter
`4089B0`. At `4089E5..4089FE` it copies **current complete `6C8` into previous
`6CC`**, then stores the requested mode in `6C8`. Requested mode 5 takes jump
table entry `408BA8` directly to the return at `408B8E`; there is no further
mode-5 callback or copy into `93C`. Thus SHRINK selection does **not** snapshot
the dynamic prior mode into the expiry field.
Interface `87C` is registered as the GAM **AIState** property at
`407F67..407F77` (name string `4ECA90`). Shared Yokian construction initializes
both complete `6C8` and `93C` to 2 at `44A7D3/44A7F7/44A7FD`. Generic load/reset
`409480`, at `409503..40951E`, copies interface `608` back to `87C` and passes
it to complete slot `124`; the separate initialization path `409460` copies
`87C` into `608`. The expiry body reads `87C`, not previous dynamic mode `6CC`.
For the three authored VR04 soldiers this restores GAM AIState **2**. A port
which snapshots its dynamic current AI state when shrinking would diverge once
AI begins changing modes; preserve a separate authored/reset AIState field.
Its value is 2 by constructor default, rather than an uninitialized zero.
Named selector `40DD90` forwards the caller's second argument through slot `E4`
at `40DF4C..40DF5E`. Wrapper `40DA30` calls embedded engine sequence selection
at `40DA61`, then explicitly writes the argument byte to complete `AD` at
`40DA64`. Since the embedded animation starts at `90`, this is engine animation
offset `1D`. Engine `find_next_frame` (`OMT2.dll:10021000`) reads `+1D` at
`10021079`: false holds the current endpoint (`100210B4`), true wraps to first
frame (`10021080`). Therefore source `SHRINK(...,0)` **does not loop**; source
`WALK(...,1)` does loop.
The engine sequence-selection boolean also controls restart: `100209F0`,
especially `10020A3A..10020A78`, restarts at first frame when true; when false
and an old frame exists it walks old/new lists to preserve the frame ordinal.
Thus changing WALK→SHRINK need not begin at shrink frame 0. Both have five
samples. Exact within-frame clock preservation remains open; any time-zero
transition in the port is an explicit approximation until closed.
Shared update `44AA00` decrements timer only when it is **strictly positive**
(`44AE5E..44AE6F`), subtracting delta at `44AE75..44AE7F`. It expires only when
the resulting value is **strictly negative** (`44AE85..44AE90`). Exact zero does
not expire in this body and is skipped next tick: preserve/document this source
edge case instead of silently substituting `<= 0`.
Expiry zeros timer (`44AE96`), clears flag (`44AE9C`), clears interface `88C`,
reads authored/reset mode `87C` (`44AEA8`), invokes complete mode slot `124` (`44AEBD`),
and requests **WALK** with argument 1 (`44AEC6`). String `4ECA54` is `WALK`,
not STOP. It restores interface `604` speed 200 (`44AED3`). While shrunk the
inspected branch can move current mode 0 to mode 5, set interface-related value
1500, and speed 400 (`44AE42..44AE54`). Full AI meaning of those transitions is
not closed here.
Calls `43F870(40,15)` while shrunk and `(140,50)` on expiry operate on owned
effect interface `8EC`. They are **effect sizes**, not soldier body radius.
No body-radius setter was found in this bounded shrink/expiry branch; that
negative observation does not prove no other mode/base update changes physics.
## First real targets: VR04 — original level data
`gam/VR04.gam` contains three `3SOL` actors; all set `AIState=2`, `CanMove=1`,
and `HasCollision=1`. Values below come directly from the bounded GAM parser.
| GAM offset | ObjectTag | Position X,Y,Z | PatrolPoint | VisibleRange / FOV |
|---|---|---|---|---|
| `4431` | `yoke1` | `-2463.1035,6327.9810,-7001.6870` | `dyok1` | 1000 / 259 |
| `582C` | `C3DYOKIANSOLDIER` | `1677.5118,6422.5869,-4131.2129` | `eyok1` | 2500 / 259 |
| `67C5` | `yoke2` | `-529.4881,6378.4834,1319.0276` | `fyok1` | 1000 / 359 |
These are authored actors high in the scene, not entrance test dummies. A bounded
interaction test can move the player near one as an explicit test fixture; it
must not relocate original actors or claim their AI has been reconstructed.
## Implementation boundary and unresolved work
At investigation start the runtime's `SceneActorVisuals` supported Carl,
Goddard, and trophy families; it did not render `3SOL`. `MorphAnimation.Sample`
looped all clips. The supported next chunk is to export these real soldier
clips/textures, render authored actors, support a nonlooping last-frame hold,
and apply the recovered SHRINK/timer/WALK transition. Parent owns runtime work;
this report does not assert those changes have shipped or run.
Existing `OriginalScenePhysics` can provide provisional radius-90/factor-1
settling for that bounded interaction. Reusing it is an implementation choice,
not proof of original soldier physics. The following remain explicitly open:
- Full soldier patrol, targeting, attack, damage, death, shadow/effect and sound updates.
- Exact collision/support/root defaults and all dynamic radius changes through base/AI modes.
- Other script/load/reset callers that can modify authored AIState independently of dynamic mode.
- Exact sequence-switch subframe timing and special empty/mismatched sequence cases.
- Non-VR texture-index animation switching and low-detail action availability.
- Original runtime comparison of shrink geometry, 30-second restoration, targeting,
and actor placement; native Windows gameplay verification remains required.
Regression checks validate original identities/dispatch, clip topology and shrink
geometry, authored VR04 actors, and a bounded timer control-flow projection.
They do not execute original code or establish original runtime equivalence.
+38 -1
View File
@@ -1,4 +1,41 @@
# Progress — 2026-10-26 # Progress — 2026-10-27
## Gameplay gadgets — user-directed continuation
2026-10-27 UTC: user explicitly parked further collision recovery and chose
gameplay gadgets. Preserve35a2a66/0272f7b as the collision resume point; original
special/dynamic/shared-context and camera gates remain documented. The previous
feature-expansion pause is superseded for this work. Independent investigators
own gadget controls, resources and shrink-ray source reports/helpers/tests under
exclusive names; primary owns gameplay/UI/runtime integration and root docs.
The original gadget panel and combined shrink-ray/jetpack are now implemented.
Tab/Space opens the original art with owned/hover tiles, Return and direct
Practice selection, uniformly scaled for widescreen. Display item3 selects normal
raw mode−1; raw mode0 is Bubble, correcting older inferred Scooter labels.
Enter/Ctrl/left mouse fires the owned ray; jump remains the powered-jump control.
Actual VR04 soldiers use original WALK/SHRINK geometry, hold the small endpoint,
award10 once per hit and restore authored mode/WALK after the source timer expiry.
No uniform-scale substitute, invented targets or projectile cooldown is used.
Independent local REA reports retain exact source addresses/offsets, guards and
Evidence for controls, resources, targeting, heading, blend and target state.
Managed heading matches15 copied-original DLL references and65,540 sweep cases.
The first broad suite passes157 Python+2 HUD, all managed groups,29 game GPU
completions and17 isolated blend/readback checks, with zero enabled validation
errors and539 unchanged originals. The complete final rerun also passes after
the close-before-selection/authored-mode corrections, including15 gadget groups.
Native Linux/private Xvfb passes24-frame1920×1080 menu input/capture/pause and
90-frame1280×720 ray input against actual VR04 yoke1, all three texture phases,
authored55.119 mesh height, unchanged tutorial energy20 and zero validation errors.
These observations verify port behavior, not full original-game or native Windows
parity. Logs: artifacts/gadget-implementation/ and artifacts/gadget-blending/.
Final logs: integration-final.log, native/menu-final.log and native/shrink-final.log.
Scope, state owners, modern policies and remaining gates are in
[gadget implementation](gameplay/gadgets-implementation.md). Full enemy AI/combat,
other gadget effects, energy-warning audio and original lifecycle/visual comparison
remain open. Package results will be recorded after the clean source milestone.
## C4 ordinary body implementation — 2026-10-27 UTC ## C4 ordinary body implementation — 2026-10-27 UTC
+9
View File
@@ -5,6 +5,15 @@ offsets, virtual addresses, API symbols or observed behavior. Decompiled output
evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL
probes and modern runtime checks are recorded separately. probes and modern runtime checks are recorded separately.
- `gameplay/gadgets-implementation.md`: first playable gadget scope and evidence
map. `gadget-controls.md`/`gadget-assets.md` retain original group0 state, menu
rectangles and54 canvases. `shrink-ray.md` traces input/ownership/energy/target
scan and callback; `shrink-heading.md` records15 copied-DLL references plus
65,540 comparison cases. `shrink-targets.md` traces actual3SOL bodies, authored
morphs and authored/reset versus prior dynamic AI modes. `gadget-blending.md`
distinguishes recovered opacity/blend branches from Vulkan depth policy;
`gadgets-review.md` records independent review and resolved scoring omission.
- `checkpoint/control-phase-implementation.md`, `uncontrolled-player.md`, - `checkpoint/control-phase-implementation.md`, `uncontrolled-player.md`,
`uncontrolled-physics.md`, `cutscene-preparation.md`: frame/body versus identity `uncontrolled-physics.md`, `cutscene-preparation.md`: frame/body versus identity
gates, ordered CAM/MCA/AI preparation and bounded implementation. `rea.md` records gates, ordered CAM/MCA/AI preparation and bounded implementation. `rea.md` records
+26 -1
View File
@@ -46,7 +46,32 @@ compile, runtime and original-fidelity verification are separate.
## Immediate continuation ## Immediate continuation
**Direction changed: pause feature expansion for the architecture checkpoint.** **Current direction: user-requested gameplay gadgets; collision work parked.**
Preserve35a2a66 body implementation,0272f7b release notes and baseline69d0187.
Recover/implement original gadget selection/use with local REA and original art;
extend the existing shrink-ray/jetpack device first where source contracts permit.
Current investigations own named files in docs/gameplay/, with runtime integration
owned by primary. Remaining special/dynamic collision and camera gates below are
the resume backlog, not prerequisites imposed on this user-directed gadget work.
- [x] Recover original gadget group0 selection, mode/display separation, ownership,
practice destinations and exact UI resources with local REA evidence.
- [x] Implement widescreen gadget screen, strict pointer regions, Tab/Space latch,
selection/input capture and direct Practice entry.
- [x] Implement owned default ray, original quantized target heading/obstruction,
texture phases, half opacity and tested alpha/additive Vulkan materials.
- [x] Render actual VR04 soldiers with original WALK/SHRINK morph, source timer,
authored-mode restoration and persistent ordinary10-point score callback.
- [x] Managed/source/GPU checks and native Linux menu/ray input fixtures.
- [ ] Rebuild clean Linux/Windows gadget packages and verify standalone resources.
- [ ] Other special gadget effects and equip cleanup, energy-warning audio,
enemy AI/reaction consumers and original/native Windows comparison.
Details: [first gadget slice](gameplay/gadgets-implementation.md). Investigators
have returned all file ownership to primary; the bounded implementation is ready
for final regression/release checks.
**Prior direction: architecture checkpoint and evidence-led implementation.**
Read `checkpoint/README.md`, `coverage.md` and `implementation-plan.md`. Preserved Read `checkpoint/README.md`, `coverage.md` and `implementation-plan.md`. Preserved
baseline69d0187 remains the testing tool. The loop/motion, script/state and baseline69d0187 remains the testing tool. The loop/motion, script/state and
camera/audio/UI investigations document the original lab→VR04→lab→outside route. camera/audio/UI investigations document the original lab→VR04→lab→outside route.
+9 -1
View File
@@ -13,6 +13,8 @@ for rid in linux-x64 win-x64; do
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/actors/. "$out/scenes/actors/"
cp -a artifacts/extracted/ui/. "$out/scenes/ui/" cp -a artifacts/extracted/ui/. "$out/scenes/ui/"
mkdir -p "$out/scenes/gadgets"
cp -a artifacts/extracted/gadgets/. "$out/scenes/gadgets/"
mkdir -p "$out/scenes/effects" mkdir -p "$out/scenes/effects"
cp -a artifacts/extracted/effects/. "$out/scenes/effects/" cp -a artifacts/extracted/effects/. "$out/scenes/effects/"
cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json" cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json"
@@ -37,7 +39,7 @@ for rid in linux-x64 win-x64; do
printf 'packaged_utc=%s\n' "$(date -u +%FT%TZ)" printf 'packaged_utc=%s\n' "$(date -u +%FT%TZ)"
} > "$out/BUILD-INFO.txt" } > "$out/BUILD-INFO.txt"
cat > "$out/README.md" <<'NOTES' cat > "$out/README.md" <<'NOTES'
# Neutron lab story and jet pack checkpoint # Neutron lab story, gadgets 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
@@ -62,6 +64,12 @@ Level changes retain the window, fullscreen and size. HUD/debug UI scales unifor
on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions. on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions.
C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit. C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit.
Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview.
Tab/Space opens the original gadget screen (first unequips a special gadget).
Point with mouse/arrows; Enter/Ctrl or a mouse button selects; Escape/Return closes.
Practice Mode plus an owned gadget opens its tutorial. The combined shrink-ray/
jetpack pickup fires on Enter/Ctrl/left mouse and bursts on jump. Original Yokian
soldiers support the shrink morph,30-second restoration and10-point reward.
Other gadget effects and full enemy AI/combat remain incomplete.
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 The default runs the recovered lab camera/speech sequence; Escape/Space skips
its actions and restores control. --skip-intro starts with control; --mute disables its actions and restores control. --skip-intro starts with control; --mute disables
+7
View File
@@ -12,6 +12,9 @@ dotnet run --project tests/GamePort.SupportTests -- ../Original
dotnet run --project tests/GamePort.SphereResponseTests dotnet run --project tests/GamePort.SphereResponseTests
dotnet run --project tests/GamePort.StaticCollisionTests dotnet run --project tests/GamePort.StaticCollisionTests
dotnet run --project tests/GamePort.BodyPhysicsTests dotnet run --project tests/GamePort.BodyPhysicsTests
dotnet run --project tests/GamePort.GadgetTests
dotnet run --project tests/GamePort.HeadingTests
dotnet run --project tests/GamePort.BlendTests
dotnet run --project tests/GamePort.CameraRayTests dotnet run --project tests/GamePort.CameraRayTests
dotnet run --project tests/GamePort.InteractionTests -- ../Original dotnet run --project tests/GamePort.InteractionTests -- ../Original
dotnet run --project tests/GamePort.CheckpointTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original
@@ -39,6 +42,7 @@ dotnet run --no-build -- --headless --story --smoke-practice-prompt --screenshot
dotnet run --no-build -- --headless --story --smoke-practice-transition dotnet run --no-build -- --headless --story --smoke-practice-transition
dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm
dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm
dotnet run --no-build -- --headless --skip-intro --gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu.ppm
dotnet run --no-build -- --headless --debug-page player --noclip --width 1920 --height 1080 --screenshot artifacts/test-debug-player.ppm dotnet run --no-build -- --headless --debug-page player --noclip --width 1920 --height 1080 --screenshot artifacts/test-debug-player.ppm
dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1080 --screenshot artifacts/test-debug-systems.ppm dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1080 --screenshot artifacts/test-debug-systems.ppm
dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm
@@ -48,6 +52,7 @@ dotnet run --no-build -- --headless --smoke-control-phases
dotnet run --no-build -- --headless --smoke-objective-panel --story-time 1 --screenshot artifacts/test-objective-visible.ppm dotnet run --no-build -- --headless --smoke-objective-panel --story-time 1 --screenshot artifacts/test-objective-visible.ppm
dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --screenshot artifacts/test-objective-hidden.ppm dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --screenshot artifacts/test-objective-hidden.ppm
dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.ppm 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 --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray.ppm
dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk 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 --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 --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro
@@ -64,6 +69,8 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --smoke-gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu-window.ppm
dotnet run --no-build -- --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray-window.ppm
dotnet run --no-build -- --smoke-debug-tools dotnet run --no-build -- --smoke-debug-tools
dotnet run --no-build -- --smoke-window-transitions dotnet run --no-build -- --smoke-window-transitions
dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm
@@ -0,0 +1,84 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original screens.omt gadget art in the existing uniformly scaled UI viewport.</summary>
public sealed class GadgetMenuOverlay
{
private sealed record Quad(int Vertex, uint FirstIndex, uint Width, uint Height);
private readonly Dictionary<int, Quad> quads = [];
public Mesh Mesh { get; }
public GadgetMenuOverlay(Mesh combined, string manifest)
{
var full = Path.GetFullPath(manifest);
if (new FileInfo(full).Length > 128 * 1024) throw new InvalidDataException("Gadget manifest exceeds limit");
var directory = Path.GetDirectoryName(full)!;
using var document = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 });
var root = document.RootElement;
if (root.GetProperty("schema").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640
|| root.GetProperty("referenceHeight").GetInt32() != 480)
throw new InvalidDataException("Unsupported gadget resource format");
var entries = root.GetProperty("textures");
if (entries.GetArrayLength() != 54) throw new InvalidDataException("Expected54 original gadget canvases");
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);
long total = 0;
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 (width is 0 or > 640 || height is 0 or > 480) throw new InvalidDataException("Invalid gadget canvas dimensions");
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Gadget canvas escapes prepared directory");
var bytes = checked((long)width * height * 4);
total += bytes;
if (total > 16 * 1024 * 1024 || new FileInfo(path).Length != bytes)
throw new InvalidDataException("Invalid gadget canvas pixel count");
var texture = int.MinValue;
while (textures.ContainsKey(texture)) texture++;
textures.Add(texture, new(width, height, File.ReadAllBytes(path)));
if (!quads.TryAdd(id, new(vertices.Count, (uint)indices.Count, width, height)))
throw new InvalidDataException("Duplicate gadget canvas");
var first = (uint)vertices.Count;
vertices.AddRange([new(Vector3.Zero, new(0,0), Vector3.One), new(Vector3.Zero, new(1,0), Vector3.One),
new(Vector3.Zero, new(1,1), Vector3.One), new(Vector3.Zero, new(0,1), Vector3.One)]);
indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]);
draws.Add(new((uint)indices.Count - 6, 6, texture) { ScreenSpace = true, Visible = false });
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true,
Textures = textures, CollisionPolygons = combined.CollisionPolygons,
HasCollisionMaterialIds = combined.HasCollisionMaterialIds };
}
public void Update(Mesh destination, IReadOnlyList<GadgetCanvas> visible, uint width, uint height)
{
if (destination.Vertices.Length < Mesh.Vertices.Length || visible.Count > quads.Count)
throw new ArgumentException("Destination omits gadget overlay ranges");
foreach (var quad in quads.Values) Draw(quad).Visible = false;
var viewport = new UiViewport(width, height);
foreach (var canvas in visible)
{
if (!quads.TryGetValue(canvas.Id, out var quad)) throw new InvalidDataException("Unprepared gadget canvas");
var draw = Draw(quad);
if (draw.Visible) throw new ArgumentException("Gadget canvas occurs more than once");
draw.Visible = true;
var point = canvas.Position + viewport.CenterOffset;
destination.Vertices[quad.Vertex].Position = viewport.ToNdc(point);
destination.Vertices[quad.Vertex + 1].Position = viewport.ToNdc(point + new Vector2(quad.Width, 0));
destination.Vertices[quad.Vertex + 2].Position = viewport.ToNdc(point + new Vector2(quad.Width, quad.Height));
destination.Vertices[quad.Vertex + 3].Position = viewport.ToNdc(point + new Vector2(0, quad.Height));
}
MeshDraw Draw(Quad quad) => destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex
&& d.IndexCount == 6 && d.ScreenSpace) ?? throw new ArgumentException("Destination omits gadget draws");
}
}
@@ -47,14 +47,14 @@ 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.Fly, "jimfly") }) (PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly"), (PlayerPose.Shoot, "jimshoot") })
{ {
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"), foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"),
("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly") }) ("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly"), ("SHOOT", "jimshoot") })
{ {
var path = Path.Combine(parent, folder, "animation.json"); var path = Path.Combine(parent, folder, "animation.json");
if (File.Exists(path)) actions[action] = Load(path); if (File.Exists(path)) actions[action] = Load(path);
@@ -0,0 +1,40 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Owned original RAY mesh and three texture phases; material alpha0.5, additive default.</summary>
public sealed class ShrinkRayVisuals
{
private readonly MorphAnimation clip;
private readonly int offset;
private readonly MeshDraw[] phases;
public Mesh Mesh { get; }
public ShrinkRayVisuals(Mesh combined, string preparedRoot, string originalRoot)
{
clip = new(Path.Combine(preparedRoot,"actors/shrink-ray/ray/animation.json"));
offset = combined.Vertices.Length;
var id = int.MinValue + 12000;
while (combined.Textures.ContainsKey(id)) id++;
var mesh = clip.AppendTo(combined,id);
phases = new MeshDraw[3]; phases[0] = mesh.Draws[^1];
for (var phase = 1; phase < phases.Length; phase++)
{
do id++; while (mesh.Textures.ContainsKey(id));
mesh.Textures.Add(id,PngImage.Load(AssetPath.Resolve(originalRoot,$"png/ray000{phase}.png")));
phases[phase] = new(phases[0].FirstIndex,phases[0].IndexCount,id);
}
foreach (var draw in phases) { draw.Visible = false; draw.Opacity = .5f; draw.Blend = MeshBlend.Additive; }
Mesh = mesh with {Draws=[.. mesh.Draws,phases[1],phases[2]]};
}
public void Update(Mesh destination, ShrinkRay ray, double seconds)
{
for (var phase = 0; phase < phases.Length; phase++) phases[phase].Visible = ray.Visible && ray.TexturePhase == phase;
if (!ray.Visible) return;
var model = Matrix4x4.CreateRotationY(-ray.Yaw * MathF.PI / 180) * Matrix4x4.CreateTranslation(ray.Position);
clip.Sample(seconds,destination.Vertices.AsSpan(offset,clip.Base.Vertices.Length),model);
}
}
@@ -0,0 +1,73 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original3SOL WALK/SHRINK morphs. No combat or patrol AI is inferred.</summary>
public sealed class ShrinkSoldierVisuals
{
private sealed class Visual(ShrinkSoldier soldier, int offset, MeshDraw draw)
{
public ShrinkSoldier Soldier = soldier;
public int Offset = offset;
public MeshDraw Draw = draw;
public bool Shrunk;
public double Time;
}
private readonly List<Visual> visuals = [];
private readonly MorphAnimation walk, shrink;
public Mesh Mesh { get; }
public ShrinkSoldierVisuals(Mesh combined, IReadOnlyList<ShrinkSoldier> soldiers, string preparedRoot, string level)
{
var vr = level.Length == 4 && level.StartsWith("VR0",StringComparison.Ordinal) && level[3] is >= '1' and <= '8';
var family = Path.Combine(preparedRoot,"actors",vr ? "soldier-vr" : "soldier");
walk = new(Path.Combine(family,"soldwalk/animation.json"));
shrink = new(Path.Combine(family,"soldshrink/animation.json"));
if (walk.Base.Vertices.Length != shrink.Base.Vertices.Length || !walk.Base.Indices.SequenceEqual(shrink.Base.Indices))
throw new InvalidDataException("Original soldier morph topology differs");
foreach (var soldier in soldiers)
{
var offset = combined.Vertices.Length;
var id = int.MinValue + 13000 + visuals.Count;
while (combined.Textures.ContainsKey(id)) id++;
combined = walk.AppendTo(combined,id);
visuals.Add(new(soldier,offset,combined.Draws[^1]));
}
Mesh = combined; Update(0,Mesh);
}
public void Update(double seconds, Mesh destination)
{
foreach (var visual in visuals)
{
if (visual.Shrunk != visual.Soldier.Shrunk)
{
//False selector preserves frame ordinal; within-frame clock is
//an explicit port approximation. WALK(true) restarts at frame0.
var ordinal = (int)Math.Floor(visual.Time / walk.SampleInterval) % walk.FrameCount;
visual.Time = visual.Soldier.Shrunk ? Math.Min(ordinal,shrink.FrameCount - 1) * shrink.SampleInterval : 0;
visual.Shrunk = visual.Soldier.Shrunk;
}
visual.Time += seconds;
var actor = visual.Soldier.Actor;
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 clip = visual.Shrunk ? shrink : walk;
clip.Sample(visual.Time,destination.Vertices.AsSpan(visual.Offset,clip.Base.Vertices.Length),
rotation * Matrix4x4.CreateTranslation(actor.Position),!visual.Shrunk);
visual.Draw.Visible = actor.Visible;
}
}
public float RenderedHeight(string tag, Mesh destination)
{
var visual = visuals.Single(v => v.Soldier.Actor.Tag == tag);
var vertices = destination.Vertices.AsSpan(visual.Offset,walk.Base.Vertices.Length);
var low = float.PositiveInfinity; var high = float.NegativeInfinity;
foreach (var vertex in vertices) { low = MathF.Min(low,vertex.Position.Y); high = MathF.Max(high,vertex.Position.Y); }
return high - low;
}
}
+4
View File
@@ -108,8 +108,12 @@ public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, V
public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true; public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true;
} }
public enum MeshBlend { Opaque, Alpha, Additive }
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId) public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{ {
public bool Visible { get; set; } = true; public bool Visible { get; set; } = true;
public bool ScreenSpace { get; init; } public bool ScreenSpace { get; init; }
public float Opacity { get; set; } = 1;
public MeshBlend Blend { get; set; } = MeshBlend.Opaque;
} }
+4 -3
View File
@@ -10,6 +10,7 @@ public sealed class MorphAnimation
public PngImage Texture { get; } public PngImage Texture { get; }
public double SampleInterval { get; } public double SampleInterval { get; }
public bool HasVertexMotion { get; } public bool HasVertexMotion { get; }
public int FrameCount => frames.Length;
private readonly Mesh[] frames; private readonly Mesh[] frames;
public MorphAnimation(string manifestPath) public MorphAnimation(string manifestPath)
@@ -54,15 +55,15 @@ public sealed class MorphAnimation
Texture = new PngImage(width, height, rgba); Texture = new PngImage(width, height, rgba);
} }
public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model) public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model, bool loop = true)
{ {
if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs"); if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs");
// Linear interpolation is recovered from DLL 0x10002F9A. Loop closure // Linear interpolation is recovered from DLL 0x10002F9A. Loop closure
// and gameplay-specific speed remain preview policies until recovered. // and gameplay-specific speed remain preview policies until recovered.
var frame = seconds / SampleInterval; var frame = seconds / SampleInterval;
var first = (int)(Math.Floor(frame) % frames.Length); var first = loop ? (int)(Math.Floor(frame) % frames.Length) : (int)Math.Min(Math.Floor(frame), frames.Length - 1);
var next = (first + 1) % frames.Length; var next = loop ? (first + 1) % frames.Length : Math.Min(first + 1, frames.Length - 1);
var t = (float)(frame - Math.Floor(frame)); var t = (float)(frame - Math.Floor(frame));
for (var i = 0; i < destination.Length; i++) for (var i = 0; i < destination.Length; i++)
{ {
+2
View File
@@ -14,6 +14,7 @@ public sealed class SceneAudio : IDisposable
public bool MusicMuted { get; private set; } public bool MusicMuted { get; private set; }
public bool SpeechMuted { get; private set; } public bool SpeechMuted { get; private set; }
public bool EffectsMuted { get; private set; } public bool EffectsMuted { get; private set; }
public bool GameplayEffectsEnabled { get; set; } = true;
public int EffectCount => effects.Count; public int EffectCount => effects.Count;
public int LoopCount => loops.Count; public int LoopCount => loops.Count;
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes); public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
@@ -43,6 +44,7 @@ public sealed class SceneAudio : IDisposable
// and original channel/volume policy are separate unrecovered consumers. // and original channel/volume policy are separate unrecovered consumers.
public void Effect(int id, string? loopOwner = null) public void Effect(int id, string? loopOwner = null)
{ {
if (!GameplayEffectsEnabled) return;
var wave = resources.Wave("SoundEffects.omt", id) var wave = resources.Wave("SoundEffects.omt", id)
?? throw new FileNotFoundException($"Missing original default sound effect {id}"); ?? throw new FileNotFoundException($"Missing original default sound effect {id}");
if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted)); if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted));
+99
View File
@@ -0,0 +1,99 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct GadgetCanvas(int Id, Vector2 Position);
/// <summary>Bounded group0 gadget panel; source425870/425EF0/425B20/427370.</summary>
public sealed class GadgetScreen(SceneInventory inventory)
{
public static IReadOnlyList<Vector2> Positions { get; } = Array.AsReadOnly<Vector2>([new(12,182), new(158,182), new(12,327), new(157,327),
new(342,182), new(487,182), new(342,327), new(487,327)]);
private static readonly int[] idle = [52,46,47,48,49,50,51,45];
private Vector2 pointerOffset;
public bool Open { get; private set; }
public bool PracticeArmed { get; private set; }
public int Hovered { get; private set; } = -1;
public event Action<int>? PracticeRequested;
public event Action? Changed;
//UI display3 is the default shrink-ray/jetpack; source equipped word is-1.
public static int EquippedMode(int displaySelection) => displaySelection == 3 ? -1 : displaySelection;
public bool Toggle(bool permitted)
{
if (Open) { Close(); return true; }
if (!permitted) return false;
if (EquippedMode(inventory.SelectedGadget) != -1)
{
inventory.SelectGadget(-1); Changed?.Invoke(); return true;
}
Open = true; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke(); return true;
}
public void Close()
{
if (!Open) return;
Open = false; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke();
}
public Vector2 MovePointer(Vector2 point, Vector2 axis, float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
if (!Open) return point;
//404080: accumulated source80*dt offsets; neutral clears each axis.
pointerOffset.X = axis.X > .5f ? pointerOffset.X + 80 * seconds
: axis.X < -.5f ? pointerOffset.X - 80 * seconds : 0;
pointerOffset.Y = axis.Y > .5f ? pointerOffset.Y + 80 * seconds
: axis.Y < -.5f ? pointerOffset.Y - 80 * seconds : 0;
return point + pointerOffset;
}
public bool PracticeAvailable(string level, int task) => task < 500
&& !(level.Length == 4 && level.StartsWith("VR0", StringComparison.Ordinal) && level[3] is >= '1' and <= '8');
public void Point(Vector2 point, string level, int task)
{
Hovered = -1;
if (!Open) return;
for (var i = 0; i < Positions.Count; i++)
if (inventory.State(0,i) is not (0 or 4) && Inside(point,Positions[i],141,141)) Hovered = i;
if (PracticeAvailable(level,task) && Inside(point,new(487,95),141,78)) Hovered = 9;
if (Inside(point,new(12,95),141,78)) Hovered = 10;
}
public bool Activate(string level, int task)
{
if (!Open) return false;
if (Hovered == 10) { Close(); return true; }
if (Hovered == 9 && PracticeAvailable(level,task))
{ PracticeArmed = !PracticeArmed; Changed?.Invoke(); return true; }
if (Hovered is < 0 or > 7 || inventory.State(0,Hovered) is 0 or 4) return false;
var item = Hovered;
var practice = PracticeArmed;
Close();
inventory.SelectGadget(item);
if (practice) PracticeRequested?.Invoke(item);
return true;
}
public GadgetCanvas[] Canvases(string level, int task)
{
if (!Open) return [];
List<GadgetCanvas> result = [new(20,Vector2.Zero)];
for (var i = 0; i < Positions.Count; i++)
{
//Known route states0/1/4. Other nonzero states retain an owned tile;
//their complete inherited visibility is not claimed recovered here.
if (inventory.State(0,i) is 0 or 4) continue;
result.Add(new(Hovered == i && inventory.State(0,i) != 3 ? 11+i : idle[i],Positions[i]));
}
result.Add(new(Hovered == 10 ? 181 : 182,new(12,95)));
if (PracticeAvailable(level,task))
result.Add(new(Hovered == 9 || PracticeArmed ? 179 : 180,new(487,95)));
return result.ToArray();
}
private static bool Inside(Vector2 point, Vector2 start, float width, float height) =>
point.X > start.X && point.X < start.X + width && point.Y > start.Y && point.Y < start.Y + height;
}
+12 -4
View File
@@ -4,8 +4,8 @@ using GamePort.Assets;
namespace GamePort.Game; namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump, public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump,
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false); bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false, bool Fire = false);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly, Shoot }
/// <summary> /// <summary>
/// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in /// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in
@@ -39,6 +39,8 @@ public sealed class LabSimulation
//predates source-body integration; burst100 is not an interaction-only size. //predates source-body integration; burst100 is not an interaction-only size.
public float InteractionRadius { get; private set; } = 60; public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; } public bool JetpackEffectVisible { get; private set; }
public Action<PlayerInput>? InputActions { get; set; }
public bool Shooting { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining; public float JetpackRemaining => jumpState.EffectRemaining;
public int JumpState => jumpState.JumpState; public int JumpState => jumpState.JumpState;
public float JumpHoldSeconds => jumpState.HoldSeconds; public float JumpHoldSeconds => jumpState.HoldSeconds;
@@ -59,7 +61,7 @@ public sealed class LabSimulation
public bool Grounded { get; private set; } public bool Grounded { get; private set; }
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: pendingImpulse.Y > 0 ? PlayerPose.Jump : pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle : Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; : !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; } public int Steps { get; private set; }
@@ -113,6 +115,7 @@ public sealed class LabSimulation
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0; lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
jumpState = default; jumpState = default;
forceFall = JetpackEffectVisible = false; forceFall = JetpackEffectVisible = false;
Shooting = false;
InteractionRadius = 60; Bursts = 0; InteractionRadius = 60; Bursts = 0;
Grounded = true; Grounded = true;
Noclip = HasNoclipEntry = false; Noclip = HasNoclipEntry = false;
@@ -168,7 +171,7 @@ public sealed class LabSimulation
StepPhysics(); StepPhysics();
if (controlled && !InputAfterPlayerUpdate) StepInput(input); if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC reasserts ordinary grounded radius before ownership //42469F..4246DC reasserts ordinary grounded radius before ownership
//checks. The scooter's separate radius160 policy remains unimplemented. //checks. Bubble mode0's separate radius160 policy remains unimplemented.
if (Grounded) InteractionRadius = 60; if (Grounded) InteractionRadius = 60;
//424BE0..424C34 runs this wrapper before437940's ownership gate. //424BE0..424C34 runs this wrapper before437940's ownership gate.
StepCeiling(); StepCeiling();
@@ -187,6 +190,9 @@ public sealed class LabSimulation
Speed = 0; Velocity = Vector3.Zero; Speed = 0; Velocity = Vector3.Zero;
} }
public void StopForPrimaryFire() => Speed = 0;
public void SetShooting(bool shooting) => Shooting = shooting;
private void StepCeiling() private void StepCeiling()
{ {
if (Velocity.Y <= 0 || ceilingRay == null if (Velocity.Y <= 0 || ceilingRay == null
@@ -228,6 +234,7 @@ public sealed class LabSimulation
public void StopDebugMotion() public void StopDebugMotion()
{ {
Shooting = false;
Velocity = pendingImpulse = Vector3.Zero; Velocity = pendingImpulse = Vector3.Zero;
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0; Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false; jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false;
@@ -285,6 +292,7 @@ public sealed class LabSimulation
targetYaw = Yaw; targetYaw = Yaw;
} }
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state. StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
InputActions?.Invoke(input);
} }
private void StepPlayer(PlayerInput input) private void StepPlayer(PlayerInput input)
+39
View File
@@ -0,0 +1,39 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>OMT2 vector::angles second output used by the original shrink ray.</summary>
public static class OriginalHeading
{
private static readonly ushort[] halfAcos = BuildHalfAcos();
public static float Degrees(Vector3 vector)
{
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
throw new ArgumentOutOfRangeException(nameof(vector), "A finite direction is required.");
double x = vector.X, z = vector.Z;
if (x == 0 && z == 0) return 0;
// DLL1001FDCB..1001FE3D: truncate the squared ratio, table lookup,
// quadrant correction, negate and mask to the original 14-bit circle.
// Double intermediates approximate x87 extended precision; see findings.
int index = (int)(16384.0 * z * z / (x * x + z * z));
int angle = halfAcos[index];
if (z < 0)
angle = x < 0 ? 8192 + angle : 8192 - angle;
else if (x < 0)
angle = 16384 - angle;
return ((-angle) & 0x3fff) * 0.02197265625f;
}
private static ushort[] BuildHalfAcos()
{
var table = new ushort[16385];
// Stored DLL constants; final endpoint is explicitly zero at100EDD0D.
for (int i = 0; i < 16384; i++)
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1)
* 2607.5945876921437 * 0.5);
return table;
}
}
+5
View File
@@ -17,6 +17,8 @@ public sealed class PlayerSceneBinding : IDisposable
this.director = director; this.player = player; this.inventory = inventory; this.tag = tag; this.director = director; this.player = player; this.inventory = inventory; this.tag = tag;
director.ActorPreparing += Prepare; director.ActorPreparing += Prepare;
director.AuthoredTransformChanged += Transform; director.AuthoredTransformChanged += Transform;
inventory.GadgetSelected += Selected;
Selected(inventory.SelectedGadget);
} }
public bool Step(PlayerInput input) public bool Step(PlayerInput input)
@@ -42,6 +44,8 @@ public sealed class PlayerSceneBinding : IDisposable
} }
} }
private void Selected(int item) => player.GadgetMode = GadgetScreen.EquippedMode(item);
private void Transform(DirectorActor actor) private void Transform(DirectorActor actor)
{ {
if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase))
@@ -52,5 +56,6 @@ public sealed class PlayerSceneBinding : IDisposable
{ {
director.ActorPreparing -= Prepare; director.ActorPreparing -= Prepare;
director.AuthoredTransformChanged -= Transform; director.AuthoredTransformChanged -= Transform;
inventory.GadgetSelected -= Selected;
} }
} }
+88
View File
@@ -0,0 +1,88 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>First usable default shrink/jetpack device; special gadgets stay separate.</summary>
public sealed class SceneGadgets : IDisposable
{
private readonly LabSimulation player;
private readonly SceneInventory inventory;
private readonly OriginalScenePhysics physics;
private readonly OriginalCameraRay geometry;
private bool loop, busy;
public ShrinkRay Ray { get; } = new();
public IReadOnlyList<ShrinkSoldier> Soldiers { get; }
public int ShrinkHits { get; private set; }
public event Action<int, bool>? Sound;
public event Action? StopSound;
public event Action<int>? ScoreAwarded;
public SceneGadgets(SceneDirector director, SceneInventory inventory, LabSimulation player, Mesh world)
{
this.inventory = inventory; this.player = player;
//Static source registration game-filter is only recovered for the route.
geometry = OriginalCameraRay.FromRouteScene(world, player.LevelCode);
physics = new OriginalScenePhysics(world);
Soldiers = director.Actors.Where(a => a.Kind == "3SOL").Select(a => new ShrinkSoldier(a)).ToArray();
foreach (var soldier in Soldiers) soldier.Actor.Animation = "WALK";
player.InputActions += Input;
}
public void StepBodies(float seconds)
{
Ray.StepTexture(seconds);
foreach (var soldier in Soldiers) soldier.StepBody(physics, seconds);
}
public void StepTimers(float seconds)
{
foreach (var soldier in Soldiers) soldier.StepTimer(seconds);
}
private void Input(PlayerInput input)
{
if (!input.Fire) { busy = false; Stop(); return; }
if (busy || player.GadgetMode != -1) { Stop(); return; }
player.StopForPrimaryFire();
if (inventory.State(0,3) != 1)
{ Sound?.Invoke(117,false); busy = true; Stop(); return; }
//426937..426989: ordinary airborne FALL stops/hides the owned beam.
if (!player.Grounded && player.Pose == PlayerPose.Fall) { Stop(); return; }
player.SetShooting(player.Grounded);
if (!loop) { Sound?.Invoke(0,true); loop = true; }
const float dt = FixedStepClock.Step;
if (!(player.LevelCode.Length == 4 && player.LevelCode.StartsWith("VR0",StringComparison.Ordinal)
&& player.LevelCode[3] is >= '1' and <= '8')) player.Energy = Math.Clamp(player.Energy - dt,0,100);
//Bridge modern signed float yaw to the source's nonnegative Euler domain.
var yaw = (player.Yaw % 360 + 360) % 360;
var hits = Ray.Fire(player.ActorRoot,yaw,dt,
Soldiers.Select(s => new ShrinkCandidate(s.Actor.Tag,s.Actor.Position,Shrunk:s.Shrunk)),
(start,end) => geometry.TraceGeometry(start,end));
foreach (var tag in hits)
{
var soldier = Soldiers.First(s => s.Actor.Tag == tag);
soldier.Shrink(); ShrinkHits++;
//Ordinary3SOL callback42AD81 awards10, then publishes marker94C.
//Other enemy classes/special LIBBYPLANT/C3DDINO callbacks are separate.
if (!tag.Equals("LIBBYPLANT",StringComparison.OrdinalIgnoreCase)
&& !tag.Equals("C3DDINO",StringComparison.OrdinalIgnoreCase))
{ ScoreAwarded?.Invoke(10); soldier.MarkScoredHit(); }
}
}
public void Stop()
{
Ray.Hide(); player.SetShooting(false);
if (loop) StopSound?.Invoke();
loop = false;
}
public void Reset()
{
Stop(); busy = false; Ray.Reset(); ShrinkHits = 0;
foreach (var soldier in Soldiers) soldier.Reset();
}
public void Dispose() { player.InputActions -= Input; Stop(); }
}
+3 -2
View File
@@ -32,6 +32,7 @@ public sealed class SceneInteractions
public event Action<Vector3>? CheckpointCaptured; public event Action<Vector3>? CheckpointCaptured;
public event Action<DirectorActor, string>? ConversationStarted; public event Action<DirectorActor, string>? ConversationStarted;
public event Action<int>? ObjectiveChanged; public event Action<int>? ObjectiveChanged;
public void ChangeScore(int delta) => Score = Math.Max(0,unchecked(Score + delta));
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save) public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save)
{ {
@@ -134,8 +135,8 @@ public sealed class SceneInteractions
private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot) private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot)
{ {
var id = source.Integer("PickupIndex", -1); var id = source.Integer("PickupIndex", -1);
// The source tag is SHRINKRAY; original objective art120 calls this //Group0/item3 is the combined shrink ray/jetpack. Objective120 names its
// pickup the jet pack, matching group0/item3 and powered-jump ownership. //jetpack action; original gadget tile14 and controls113 also name SHRINK.
var jetpack = Equal(source.Tag, "SHRINKRAY"); var jetpack = Equal(source.Tag, "SHRINKRAY");
var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5; var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5;
if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50) if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50)
+106
View File
@@ -0,0 +1,106 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct ShrinkCandidate(string Tag, Vector3 Position, bool BodyEnabled = true,
bool ShrinkEnabled = true, bool Shrunk = false);
/// <summary>Ordinary owned-item3/mode-1 continuous426E40 scan, not a projectile.</summary>
public sealed class ShrinkRay
{
private float textureTime;
public int TexturePhase { get; private set; }
public bool Visible { get; private set; }
public Vector3 Position { get; private set; }
public float Yaw { get; private set; }
public void StepTexture(float seconds)
{
Seconds(seconds);
textureTime += seconds;
//Float accumulation compared with the source stored double0.1.
if ((double)textureTime <= .1) return;
TexturePhase = (TexturePhase + 1) % 3;
textureTime = 0;
}
public void Hide() => Visible = false;
public void Reset() { Visible = false; TexturePhase = 0; textureTime = 0; }
public IReadOnlyList<string> Fire(Vector3 root, float yaw, float seconds,
IEnumerable<ShrinkCandidate> candidates, Func<Vector3, Vector3, SupportHit?> wallQuery)
{
Seconds(seconds);
if (!float.IsFinite(yaw)) throw new ArgumentOutOfRangeException(nameof(yaw));
Visible = true; Position = root; Yaw = yaw;
List<string> hits = [];
foreach (var target in candidates)
{
if (!target.BodyEnabled || !target.ShrinkEnabled || target.Shrunk
|| target.Position.Y <= root.Y - 150 || target.Position.Y >= root.Y + 60) continue;
var difference = target.Position - root;
var distance = difference.Length();
if (distance >= 1500) continue;
var heading = OriginalHeading.Degrees(difference);
//No added angle-seam wrapping in the recovered comparison.
if (heading <= yaw - 5 || heading >= yaw + 5) continue;
var (sin, cos) = LabSimulation.Trig(yaw);
var start = root + Vector3.UnitY * 150;
var end = start + new Vector3(-sin * distance, 0, cos * distance);
if (wallQuery(start, end) != null) continue;
hits.Add(target.Tag);
}
return hits;
}
private static void Seconds(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
}
}
/// <summary>Bounded original3SOL body settling and shrink state; combat/path AI remain open.</summary>
public sealed class ShrinkSoldier(DirectorActor actor)
{
public DirectorActor Actor { get; } = actor;
public Vector3 Velocity { get; private set; }
public bool Grounded { get; private set; }
public bool Shrunk { get; private set; }
public float Remaining { get; private set; }
public int AuthoredMode { get; } = actor.SourceGam?.Integer("AIState",2) ?? 2;
public int PreviousMode { get; private set; }
public int ShrinkRevision { get; private set; }
public float HitMarker { get; private set; }
public void MarkScoredHit() => HitMarker = 1;
public void Reset()
{
Velocity = Vector3.Zero; Grounded = Shrunk = false; Remaining = 0;
ShrinkRevision = 0; HitMarker = 0; Actor.Animation = "WALK";
}
public void StepBody(OriginalScenePhysics physics, float seconds)
{
var result = physics.Step(Actor.Position, Velocity, 90, 1, Grounded, seconds);
Actor.Position = result.Body.Position; Velocity = result.Body.Velocity; Grounded = result.Supported;
}
public void Shrink()
{
if (Shrunk) return;
PreviousMode = Actor.AIstate; Actor.AIstate = 5;
Actor.Animation = "SHRINK"; Remaining = 30; Shrunk = true; ShrinkRevision++;
}
public void StepTimer(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
if (!Shrunk || Remaining <= 0) return;
Remaining -= seconds;
//Source44AE85: exact zero does not expire and is skipped next tick.
if (Remaining >= 0) return;
Remaining = 0; Shrunk = false; HitMarker = 0;
PreviousMode = Actor.AIstate;
Actor.AIstate = AuthoredMode; Actor.Animation = "WALK"; Actor.Speed = 200;
}
}
+209 -14
View File
@@ -85,6 +85,9 @@ internal static class Program
--smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check --smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames) --smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack 300-step powered steering/jump check in VR04 --smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture
--gadget-menu Render original gadget panel (--skip-intro); fixture owns item3
--smoke-gadget-menu SDL menu input/pause/selection/practice/Return check (24 frames)
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse --smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
--smoke-carl-cutscene Verify input stays locked during the lab conversation --smoke-carl-cutscene Verify input stays locked during the lab conversation
--smoke-control-phases Airborne cutscene body/fire and restoration fixture --smoke-control-phases Airborne cutscene body/fire and restoration fixture
@@ -251,6 +254,7 @@ internal static class Program
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 jetpackSmoke = args.Contains("--smoke-jetpack");
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
var carlSmoke = args.Contains("--smoke-carl-cutscene"); var carlSmoke = args.Contains("--smoke-carl-cutscene");
var controlPhaseSmoke = args.Contains("--smoke-control-phases"); var controlPhaseSmoke = args.Contains("--smoke-control-phases");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window"); var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
@@ -266,11 +270,12 @@ internal static class Program
var debugSmoke = args.Contains("--smoke-debug-menu"); var debugSmoke = args.Contains("--smoke-debug-menu");
var toolsSmoke = args.Contains("--smoke-debug-tools"); var toolsSmoke = args.Contains("--smoke-debug-tools");
var diagnosticsSmoke = args.Contains("--smoke-debug-overlay"); var diagnosticsSmoke = args.Contains("--smoke-debug-overlay");
var gadgetWindowSmoke = args.Contains("--smoke-gadget-menu");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check"); if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time"); && animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time") var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window"))) if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode."); 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.");
@@ -292,6 +297,11 @@ internal static class Program
SceneInteractions? interactions = null; SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null; SceneMechanisms? mechanisms = null;
SceneHud? hud = null; SceneHud? hud = null;
GadgetScreen? gadgetScreen = null;
GadgetMenuOverlay? gadgetOverlay = null;
SceneGadgets? gadgets = null;
ShrinkRayVisuals? rayVisuals = null;
ShrinkSoldierVisuals? soldierVisuals = null;
JetpackVisuals? jetpackVisuals = null; JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt(); var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null; ObjectivePanel? objectivePanel = null;
@@ -344,7 +354,7 @@ internal static class Program
characterModel = placement.Model; characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh); mesh = animations.Current.AppendTo(mesh);
if (walking) if (walking)
Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; R reset; C pause/inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional."); Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; Enter/Ctrl/left mouse fire; Tab/Space gadgets; R reset; C inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
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.");
} }
@@ -358,11 +368,17 @@ internal static class Program
storyTasks = tasks; storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration); director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save); interactions = new SceneInteractions(director, tasks, save);
gadgetScreen = new GadgetScreen(interactions.Inventory);
interactions.Inventory.ApplyLevelAvailability(level!.Code); interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective); objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select; interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy; simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3); simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
if (level.Code is "LV1B" or "VR04" or "LEV1")
{
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
gadgets.ScoreAwarded += interactions.ChangeScore;
}
mechanisms = new SceneMechanisms(director); mechanisms = new SceneMechanisms(director);
interactions.Transition += RequestTransition; interactions.Transition += RequestTransition;
interactions.PracticeRequested += practice.Show; interactions.PracticeRequested += practice.Show;
@@ -373,6 +389,11 @@ internal static class Program
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!); interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1)); RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1));
}; };
gadgetScreen.PracticeRequested += item =>
{
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
RequestTransition(new($"VR0{item + 1}.gam", "PHONEBOOTH", 0, -1));
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}."); 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")) foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{ {
@@ -393,6 +414,12 @@ internal static class Program
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")), actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag)); actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh; mesh = actorVisuals.Mesh;
if (gadgets != null)
{
soldierVisuals = new ShrinkSoldierVisuals(mesh,gadgets.Soldiers,
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),level!.Code);
mesh = soldierVisuals.Mesh;
}
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources); spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh; mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models")); staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
@@ -406,10 +433,18 @@ internal static class Program
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius); DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."))); jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh; mesh = jetpackVisuals.Mesh;
if (gadgets != null)
{
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
mesh = rayVisuals.Mesh;
}
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json")); hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh; mesh = hud.Mesh;
gadgetOverlay = new GadgetMenuOverlay(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../gadgets/gadgets.json"));
mesh = gadgetOverlay.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}."); Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
} }
using var gadgetLifetime = gadgets;
var debugMenu = new DebugMenu(scene != null && level != null var debugMenu = new DebugMenu(scene != null && level != null
? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [], ? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [],
Path.GetFileName(levelPath), originalStart?.Tag); Path.GetFileName(levelPath), originalStart?.Tag);
@@ -437,7 +472,11 @@ internal static class Program
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24))
throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames");
if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60))
throw new ArgumentException("Shrink-ray smoke requires actual VR04 and at least60 frames");
if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null)) if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null))
throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames"); throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames");
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
@@ -467,12 +506,25 @@ internal static class Program
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
width, height, !args.Contains("--no-validation")); width, height, !args.Contains("--no-validation"));
var window = presentation.Window; var window = presentation.Window;
ShrinkSoldier? shrinkVictim = null;
var shrinkPhaseMask = 0;
var sawShrinkKey = false;
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}."); Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
{ {
using var audio = Option(args, "--audio") is { } audioFile using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null; ? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null; using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
sceneAudio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
if (gadgets != null)
{
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
gadgets.StopSound += () => sceneAudio?.StopLoop("shrink-ray");
}
if (gadgetScreen != null) gadgetScreen.Changed += () =>
{
gadgets?.Stop();
if (sceneAudio != null) sceneAudio.GameplayEffectsEnabled = !gadgetScreen.Open;
};
double initialPoseTime = 0; double initialPoseTime = 0;
if (director != null) if (director != null)
{ {
@@ -488,6 +540,7 @@ internal static class Program
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1)); sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
} }
director.Begin(originalStart!, activateStartTrigger: !returning); director.Begin(originalStart!, activateStartTrigger: !returning);
gadgets?.Reset();
interactions!.Reset(); interactions!.Reset();
mechanisms!.Reset(); mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
@@ -503,7 +556,8 @@ internal static class Program
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}."); Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions"); if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
} }
if (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke) if (controlPhaseSmoke)
{ {
interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3); interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3);
@@ -561,7 +615,9 @@ internal static class Program
} }
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++) for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++)
{ {
gadgets?.StepBodies(FixedStepClock.Step);
playerBinding!.Step(default); playerBinding!.Step(default);
gadgets?.StepTimers(FixedStepClock.Step);
interactions!.UpdateEnergy(simulation!.Energy); interactions!.UpdateEnergy(simulation!.Energy);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step); foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step); mechanisms!.Step(FixedStepClock.Step);
@@ -570,10 +626,51 @@ internal static class Program
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0; if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step; initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh); actorVisuals!.Update(FixedStepClock.Step, mesh);
soldierVisuals?.Update(FixedStepClock.Step,mesh);
spriteVisuals!.Step(FixedStepClock.Step); spriteVisuals!.Step(FixedStepClock.Step);
} }
if (args.Contains("--gadget-menu"))
{
interactions!.Inventory.SetState(0,3,1);
if (!gadgetScreen!.Toggle(director.Controlled && director.InventoryEnabled))
throw new InvalidOperationException("Gadget screen requires player control (--skip-intro)");
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
}
if (shrinkSmoke)
{
//Explicit test placement near an ACTUAL authored soldier.
//No invented targets or relocation of the soldier to entry.
for (var tick = 0; tick < 600; tick++) gadgets!.StepBodies(FixedStepClock.Step);
var floorQuery = new SceneCollision(world);
var sourceQuery = OriginalCameraRay.FromRouteScene(world,"VR04");
foreach (var soldier in gadgets!.Soldiers)
{
foreach (var direction in new[] {Vector3.UnitZ,-Vector3.UnitZ,Vector3.UnitX,-Vector3.UnitX})
{
var candidate = soldier.Actor.Position - direction * 500;
var floor = floorQuery.GroundHeight(candidate + Vector3.UnitY * 500,2500);
if (floor == null) continue;
candidate.Y = floor.Value + OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
if (soldier.Actor.Position.Y <= candidate.Y - 150 || soldier.Actor.Position.Y >= candidate.Y + 60
|| sourceQuery.TraceGeometry(candidate + Vector3.UnitY * 150,soldier.Actor.Position + Vector3.UnitY * 150) != null) continue;
var fixtureYaw = OriginalHeading.Degrees(soldier.Actor.Position - candidate);
var (viewSin,viewCos) = LabSimulation.Trig(fixtureYaw);
var fixtureEye = candidate + new Vector3(viewSin*350,180,-viewCos*350);
if (sourceQuery.TraceGeometry(fixtureEye,soldier.Actor.Position + Vector3.UnitY*25) != null) continue;
simulation!.ApplyAuthoredTransform(candidate,fixtureYaw);
simulation.RestoreReturnRoot(candidate); //Fixture camera snap at the explicitly moved player.
shrinkVictim = soldier; break;
}
if (shrinkVictim != null) break;
}
if (shrinkVictim == null) throw new InvalidOperationException("No supported source ray fixture near actual VR04 soldier");
interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3);
Console.WriteLine($"Shrink fixture: actual target={shrinkVictim.Actor.Tag}, target root={shrinkVictim.Actor.Position}, player root={simulation!.ActorRoot}.");
}
} }
var keys = new HashSet<uint>(); var keys = new HashSet<uint>();
var gadgetHeldKeys = new HashSet<uint>();
var gadgetArrows = new HashSet<uint>();
var debugCapturedKeys = new HashSet<uint>(); var debugCapturedKeys = new HashSet<uint>();
var running = true; var running = true;
var sawKey = false; var sawKey = false;
@@ -584,6 +681,7 @@ internal static class Program
var inspecting = !walking; var inspecting = !walking;
var active = presentation.HasInputFocus; var active = presentation.HasInputFocus;
var mouseJump = false; var mouseJump = false;
var mouseFire = false;
var stepClock = new FixedStepClock(); var stepClock = new FixedStepClock();
double poseTime = initialPoseTime; double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput); var injectedInput = default(PlayerInput);
@@ -620,12 +718,16 @@ internal static class Program
var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero; var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero;
var controlEntry = simulation?.ActorRoot ?? Vector3.Zero; var controlEntry = simulation?.ActorRoot ?? Vector3.Zero;
var phasesLocked = false; var phasesResumed = false; var phasesLocked = false; var phasesResumed = false;
var gadgetChecks = new bool[7];
var gadgetEntry = simulation?.ActorRoot ?? Vector3.Zero;
var gadgetPausedSteps = 0;
void ResetScene() void ResetScene()
{ {
gadgetScreen?.Close();
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; } if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
if (practice.Active) practice.Key(17, Vector2.Zero); if (practice.Active) practice.Key(17, Vector2.Zero);
simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!); simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset(); interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); mouseFire = false;
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
} }
void ToggleCamera() void ToggleCamera()
@@ -639,6 +741,8 @@ internal static class Program
} }
void DebugInputBoundary() void DebugInputBoundary()
{ {
gadgetArrows.Clear();
gadgets?.Stop(); mouseFire = false;
debugCapturedKeys.UnionWith(keys); debugCapturedKeys.UnionWith(keys);
keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds;
audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open); audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
@@ -764,6 +868,33 @@ internal static class Program
} }
while (running) while (running)
{ {
if (gadgetWindowSmoke)
{
void Key(uint key,bool down) { var e=new Sdl.Event {Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
void Click(bool down) { var e=new Sdl.Event {Type=down?Sdl.MouseButtonDown:Sdl.MouseButtonUp,MouseButton=1};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
void Aim(Vector2 point) { Sdl.SDL_GetWindowSize(window,out var w,out var h);var v=new UiViewport(renderer.Width,renderer.Height);
var p=v.ToNdc(point+v.CenterOffset);Sdl.SDL_WarpMouseInWindow(window,(p.X+1)*w/2,(p.Y+1)*h/2); }
if(count==0)Key(43,true);
if(count==1){gadgetPausedSteps=simulation!.Steps;Key(44,true);}
if(count==2){gadgetChecks[0]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(43,false);}
if(count==3){gadgetChecks[1]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(41,true);}
if(count==4){gadgetChecks[2]=!gadgetScreen!.Open&&running;Key(41,false);Key(44,false);Key(43,true);}
if(count==5){Aim(new(200,380));Key(40,true);}
if(count==6){gadgetChecks[3]=!gadgetScreen!.Open&&interactions!.Inventory.SelectedGadget==3
&&simulation!.GadgetMode==-1&&gadgets?.Ray.Visible!=true;Key(40,false);Key(43,false);Key(43,true);}
if(count==7){Aim(new(520,120));Click(true);}
if(count==8){gadgetChecks[4]=gadgetScreen!.PracticeArmed;Click(false);Aim(new(50,120));Click(true);}
if(count==9){gadgetChecks[5]=!gadgetScreen!.Open&&!gadgetScreen.PracticeArmed&&transitionRequest==null;Key(43,false);Click(false);}
if(count==11){gadgetChecks[6]=simulation!.Jumps==0&&gadgets?.Ray.Visible!=true
&&Vector3.Distance(simulation.ActorRoot,gadgetEntry)<.1f;Key(43,true);Aim(new(200,380));}
}
if (shrinkSmoke && !headless && count == 0)
{
var fire = new Sdl.Event {Type=Sdl.KeyDown,Scancode=224,Down=1};
if (!Sdl.SDL_PushEvent(ref fire)) throw new InvalidOperationException(Sdl.Error);
}
if ((walkSmoke || jetpackSmoke) && !headless) if ((walkSmoke || jetpackSmoke) && !headless)
{ {
var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps) var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps)
@@ -786,9 +917,10 @@ internal static class Program
if (e.Type is Sdl.Quit or 0x210) running = false; if (e.Type is Sdl.Quit or 0x210) running = false;
if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize(); if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized) if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
{ keys.Clear(); debugCapturedKeys.Clear(); mouseJump = false; active = false; stepClock.Reset(); } { keys.Clear(); debugCapturedKeys.Clear(); gadgetHeldKeys.Clear(); gadgetArrows.Clear(); mouseJump = mouseFire = false; gadgets?.Stop(); 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 (e.Type == Sdl.KeyUp) { gadgetHeldKeys.Remove(e.Scancode); gadgetArrows.Remove(e.Scancode); }
if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue; if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue; if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey) if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey)
@@ -820,13 +952,36 @@ internal static class Program
continue; continue;
} }
if (practice.Active && e.Type == Sdl.MouseButtonDown) if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; } { if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown) if (practice.Active && e.Type == Sdl.KeyDown)
{ {
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer()); if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true; if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue; keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
} }
if (e.Type == Sdl.KeyDown && e.Scancode is 43 or 44
&& !inspecting && simulation?.Noclip != true && !practice.Active && gadgetScreen != null
&& (gadgetScreen.Open || director is { Controlled: true, InventoryEnabled: true }))
{
var first = gadgetHeldKeys.Count == 0;
gadgetHeldKeys.Add(e.Scancode);
if (first && e.Repeat == 0) gadgetScreen.Toggle(director is { Controlled: true, InventoryEnabled: true });
debugCapturedKeys.UnionWith(keys);
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
}
if (gadgetScreen?.Open == true)
{
if (e.Type == Sdl.KeyDown && e.Scancode is >= 79 and <= 82) gadgetArrows.Add(e.Scancode);
gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
if (e.Type == Sdl.KeyDown) debugCapturedKeys.Add(e.Scancode);
if (e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode == 41) gadgetScreen.Close();
else if (e.Type == Sdl.MouseButtonDown && e.MouseButton is 1 or 3
|| e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode is 40 or 88 or 224 or 228 or 225 or 229 or 73 or 98)
gadgetScreen.Activate(level.Code,storyTasks.Get("SCENE"));
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 1) mouseFire = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 1) mouseFire = false;
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3)
{ {
mouseJump = true; mouseJump = true;
@@ -835,6 +990,7 @@ internal static class Program
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)
{ {
if (shrinkSmoke && e.Scancode == 224) sawShrinkKey = true;
keys.Add(e.Scancode); keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0; if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0;
if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0; if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0;
@@ -868,24 +1024,41 @@ 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 (debugMenu.Open) animationStarted += elapsed; if (gadgetScreen?.Open == true && !headless && !debugMenu.Open)
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{ {
var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); var axis = new Vector2((gadgetArrows.Contains(79) ? 1 : 0) - (gadgetArrows.Contains(80) ? 1 : 0),
(gadgetArrows.Contains(81) ? 1 : 0) - (gadgetArrows.Contains(82) ? 1 : 0));
var point = Pointer();
var moved = gadgetScreen.MovePointer(point,axis,dt);
if (moved != point && Sdl.SDL_GetWindowSize(window,out var menuWidth,out var menuHeight))
{
var viewport = new UiViewport(renderer.Width,renderer.Height);
var ndc = viewport.ToNdc(moved + viewport.CenterOffset);
Sdl.SDL_WarpMouseInWindow(window,(ndc.X + 1) * menuWidth / 2,(ndc.Y + 1) * menuHeight / 2);
}
}
if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++) for (var step = 0; step < steps; step++)
{ {
var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true) var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true)
: shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps) : jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( : walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79), keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98), mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98),
keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20), keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20),
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229)); keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229),
mouseFire || keys.Contains(40) || keys.Contains(88) || keys.Contains(224) || keys.Contains(228));
gadgets?.StepBodies(FixedStepClock.Step);
var before = simulation.Position; var before = simulation.Position;
var powered = simulation.JetpackEffectVisible && !simulation.Grounded; var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
bool acceptsInput; bool acceptsInput;
if (playerBinding != null) acceptsInput = playerBinding.Step(input); if (playerBinding != null) acceptsInput = playerBinding.Step(input);
else { simulation.Step(input); acceptsInput = true; } else { simulation.Step(input); acceptsInput = true; }
gadgets?.StepTimers(FixedStepClock.Step);
if (jetpackSmoke && powered) if (jetpackSmoke && powered)
{ {
poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z));
@@ -913,6 +1086,7 @@ internal static class Program
if (switched) poseTime = 0; if (switched) poseTime = 0;
poseTime += FixedStepClock.Step; poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh); actorVisuals?.Update(FixedStepClock.Step, mesh);
soldierVisuals?.Update(FixedStepClock.Step,mesh);
spriteVisuals?.Step(FixedStepClock.Step); spriteVisuals?.Step(FixedStepClock.Step);
} }
characterModel = simulation.Model; characterModel = simulation.Model;
@@ -945,13 +1119,22 @@ internal static class Program
renderEye = storyEye; renderTarget = storyTarget; renderEye = storyEye; renderTarget = storyTarget;
} }
staticVisuals?.Update(mesh); staticVisuals?.Update(mesh);
if (debugMenu.Open || inspecting || practice.Active || director?.Controlled == false) gadgets?.Stop();
soldierVisuals?.Update(0,mesh);
if (gadgets != null) rayVisuals!.Update(mesh,gadgets.Ray,simulation!.Steps / 60d);
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
jetpackVisuals?.Update(mesh, simulation!); jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh); spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
&& director is { Controlled: true, InventoryEnabled: true }); && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active); objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible, hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible && gadgetScreen?.Open != true,
practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height); practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height);
if (gadgetScreen != null)
{
if (!headless) gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
gadgetOverlay!.Update(mesh,gadgetScreen.Canvases(level!.Code,storyTasks!.Get("SCENE")),renderer.Width,renderer.Height);
}
var gameplayProjection = originalCamera || simulation != null && !inspecting; var gameplayProjection = originalCamera || simulation != null && !inspecting;
var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE" var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE"
: simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT"; : simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT";
@@ -1260,6 +1443,18 @@ internal static class Program
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded
|| poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2; || poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2;
} }
if (shrinkSmoke)
{
var renderedHeight = soldierVisuals!.RenderedHeight(shrinkVictim!.Actor.Tag,mesh);
Console.WriteLine($"Shrink ray: target={shrinkVictim.Actor.Tag}, hits={gadgets!.ShrinkHits}, shrunk={shrinkVictim.Shrunk}, height={renderedHeight:F3}, remaining={shrinkVictim.Remaining:F3}, beam={gadgets.Ray.Visible}, phases={shrinkPhaseMask}, energy={simulation!.Energy:F3}, SDL fire={sawShrinkKey}.");
if (!shrinkVictim.Shrunk || gadgets.ShrinkHits < 1 || renderedHeight > 60 || !gadgets.Ray.Visible || shrinkPhaseMask != 7
|| simulation.Energy != 20 || !headless && !sawShrinkKey) return 2;
}
if (gadgetWindowSmoke)
{
Console.WriteLine($"Gadget menu SDL: shared-edge={gadgetChecks[0]}, pause={gadgetChecks[1]}, Escape={gadgetChecks[2]}, selection/fire-capture={gadgetChecks[3]}, practice={gadgetChecks[4]}, Return={gadgetChecks[5]}, stable-root={gadgetChecks[6]}.");
if (!gadgetChecks.All(c=>c)) return 2;
}
if (director != null) if (director != null)
{ {
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}."); Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
+4 -1
View File
@@ -2,9 +2,12 @@
layout(location=0) in vec2 texCoord; layout(location=0) in vec2 texCoord;
layout(location=1) in vec3 vertexColor; layout(location=1) in vec3 vertexColor;
layout(binding=0) uniform sampler2D diffuseMap; layout(binding=0) uniform sampler2D diffuseMap;
layout(push_constant) uniform Material {
layout(offset=64) float opacity;
} material;
layout(location=0) out vec4 outColor; layout(location=0) out vec4 outColor;
void main() { void main() {
vec4 diffuse = texture(diffuseMap, texCoord); vec4 diffuse = texture(diffuseMap, texCoord);
if (diffuse.a < 0.5) discard; if (diffuse.a < 0.5) discard;
outColor = vec4(diffuse.rgb * vertexColor, diffuse.a); outColor = vec4(diffuse.rgb * vertexColor, diffuse.a * material.opacity);
} }
Binary file not shown.
@@ -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,overlayPipeline; private Pipeline pipeline,overlayPipeline,alphaPipeline,additivePipeline,overlayAlphaPipeline,overlayAdditivePipeline;
private PipelineLayout pipelineLayout; private PipelineLayout pipelineLayout;
private DescriptorSetLayout descriptorLayout; private DescriptorSetLayout descriptorLayout;
private DescriptorPool descriptorPool; private DescriptorPool descriptorPool;
@@ -130,6 +130,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh)); throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length)) if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh)); throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
ValidateDrawMaterials(mesh.Draws);
ValidateTexture(fallback); ValidateTexture(fallback);
foreach(var image in mesh.Textures.Values)ValidateTexture(image); foreach(var image in mesh.Textures.Values)ValidateTexture(image);
@@ -142,6 +143,17 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
} }
private static void ValidateDrawMaterials(MeshDraw[] draws)
{
foreach(var draw in draws)
{
if(!float.IsFinite(draw.Opacity) || draw.Opacity<0 || draw.Opacity>1)
throw new ArgumentException("Draw opacity must be finite and between zero and one.",nameof(draws));
if(draw.Blend is not (MeshBlend.Opaque or MeshBlend.Alpha or MeshBlend.Additive))
throw new ArgumentException("Draw blend mode is invalid.",nameof(draws));
}
}
private SceneResources DetachScene() private SceneResources DetachScene()
{ {
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory, var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
@@ -425,7 +437,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main"); var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
try try
{ {
var push=new PushConstantRange(ShaderStageFlags.VertexBit,0,64);var dl=descriptorLayout; var push=new PushConstantRange(ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit,0,68);var dl=descriptorLayout;
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push}; var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout"); Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
var stages=stackalloc PipelineShaderStageCreateInfo[2]; var stages=stackalloc PipelineShaderStageCreateInfo[2];
@@ -450,6 +462,23 @@ public sealed unsafe class VulkanRenderer : IDisposable
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; ds.DepthTestEnable=false;ds.DepthWriteEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline"); Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline");
// Blended world geometry tests opaque depth but does not write it.
// Preserve draw order; general transparent-surface sorting is separate work.
blendAttachment.BlendEnable=true;
blendAttachment.SrcColorBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstColorBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.ColorBlendOp=BlendOp.Add;
blendAttachment.SrcAlphaBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstAlphaBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.AlphaBlendOp=BlendOp.Add;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAlphaPipeline),"CreateOverlayAlphaPipeline");
ds.DepthTestEnable=true;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out alphaPipeline),"CreateAlphaPipeline");
blendAttachment.DstColorBlendFactor=BlendFactor.One;
blendAttachment.DstAlphaBlendFactor=BlendFactor.One;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out additivePipeline),"CreateAdditivePipeline");
ds.DepthTestEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAdditivePipeline),"CreateOverlayAdditivePipeline");
} }
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);}
} }
@@ -502,6 +531,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
public void Render(Matrix4x4 mvp) public void Render(Matrix4x4 mvp)
{ {
// Draw materials are mutable between frames. Reject invalid state before
// acquiring an image or beginning a command buffer, even on hidden draws.
ValidateDrawMaterials(mesh.Draws);
uint imageIndex=0; uint imageIndex=0;
if(window!=0) if(window!=0)
{ {
@@ -517,14 +549,30 @@ public sealed unsafe class VulkanRenderer : IDisposable
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);
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}) // Opaque world first, blended world second, UI last. Within each pass,
// retain source order so existing UI composition remains unchanged.
for(var pass=0;pass<3;pass++)
{ {
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,screenSpace?overlayPipeline:pipeline); var screenSpace=pass==2;
var transform=screenSpace?Matrix4x4.Identity:mvp; var transform=screenSpace?Matrix4x4.Identity:mvp;
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&transform); var stages=ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit;
vk.CmdPushConstants(command,pipelineLayout,stages,0,64,&transform);
foreach(var draw in draws) foreach(var draw in draws)
{ {
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue; if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
if(!screenSpace && (draw.Blend==MeshBlend.Opaque)!=(pass==0))continue;
var selectedPipeline=(screenSpace,draw.Blend) switch
{
(false,MeshBlend.Alpha)=>alphaPipeline,
(false,MeshBlend.Additive)=>additivePipeline,
(true,MeshBlend.Alpha)=>overlayAlphaPipeline,
(true,MeshBlend.Additive)=>overlayAdditivePipeline,
(true,_)=>overlayPipeline,
_=>pipeline
};
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,selectedPipeline);
var opacity=draw.Opacity;
vk.CmdPushConstants(command,pipelineLayout,stages,64,4,&opacity);
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);
@@ -565,6 +613,10 @@ public sealed unsafe class VulkanRenderer : IDisposable
DestroyTarget(); DestroyTarget();
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null); if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null); if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
if(alphaPipeline.Handle!=0)vk.DestroyPipeline(device,alphaPipeline,null);
if(additivePipeline.Handle!=0)vk.DestroyPipeline(device,additivePipeline,null);
if(overlayAlphaPipeline.Handle!=0)vk.DestroyPipeline(device,overlayAlphaPipeline,null);
if(overlayAdditivePipeline.Handle!=0)vk.DestroyPipeline(device,overlayAdditivePipeline,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);
DestroySceneResources(); DestroySceneResources();
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks><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/Platform/Sdl.cs" />
<Compile Include="../../src/GamePort/Rendering/Vulkan/VulkanRenderer.cs" />
<PackageReference Include="Silk.NET.Vulkan" Version="2.23.0" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.23.0" />
<Content Include="../../src/GamePort/Rendering/Shaders/*.spv" CopyToOutputDirectory="PreserveNewest" Link="Shaders/%(Filename)%(Extension)" />
</ItemGroup>
</Project>
+85
View File
@@ -0,0 +1,85 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Rendering.Vulkan;
// These tests read back actual Vulkan color attachments. No window or original
// executable is needed. The source-linked project avoids rebuilding GamePort.
var white=PngImage.White;
var count=0;
using var renderer=new VulkanRenderer(Scene(new Layer(Vector3.UnitZ,.8f)),white,64,64,validation:true);
Console.WriteLine($"Blend test GPU: {renderer.DeviceName}");
Check("opaque default",Scene(new Layer(Vector3.UnitX,.4f)),255,0,0);
Check("alpha half opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f)),128,0,128);
Check("additive half opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Additive,.5f),new(Vector3.UnitZ,.8f)),128,0,255);
Check("opaque depth occludes blend",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.2f)),0,0,255);
Check("blend does not write depth",Scene(new(Vector3.UnitX,.2f,MeshBlend.Alpha,.5f),new(Vector3.UnitY,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f)),64,128,64);
Check("UI follows blended world",Scene(new(Vector3.UnitY,.9f,Screen:true),new(Vector3.UnitX,.4f,MeshBlend.Additive,.5f),new(Vector3.UnitZ,.8f)),0,255,0);
Check("UI alpha ignores depth",Scene(new(Vector3.UnitX,.9f,MeshBlend.Alpha,.5f,true),new(Vector3.UnitZ,.2f)),128,0,128);
Check("UI additive ignores depth",Scene(new(Vector3.UnitX,.9f,MeshBlend.Additive,.5f,true),new(Vector3.UnitZ,.2f)),128,0,255);
Check("zero opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,0),new(Vector3.UnitZ,.8f)),0,0,255);
// Texture coverage is tested before material opacity: a solid texture at .5
// opacity must draw, while a cutout remains absent even at full opacity.
var cutout=Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f));
cutout.Draws[0]=cutout.Draws[0] with {TextureId=7};
cutout.Textures[7]=new PngImage(1,1,[255,255,255,0]);
Check("texture cutout unchanged",cutout,0,0,255);
var invalid=Scene(new Layer(Vector3.UnitX,.4f));
renderer.ReplaceScene(invalid,white);
foreach(var opacity in new[]{float.NaN,float.PositiveInfinity,-.01f,1.01f})
{
invalid.Draws[0].Opacity=opacity;
Throws("invalid mutable opacity",()=>renderer.Render(Matrix4x4.Identity));
}
invalid.Draws[0].Opacity=1;
invalid.Draws[0].Blend=(MeshBlend)99;
invalid.Draws[0].Visible=false;
Throws("invalid hidden blend",()=>renderer.Render(Matrix4x4.Identity));
Throws("replacement rejects invalid blend",()=>renderer.ReplaceScene(invalid,white));
invalid.Draws[0].Blend=MeshBlend.Opaque;
invalid.Draws[0].Visible=true;
renderer.Render(Matrix4x4.Identity);
AssertPixel("renderer usable after rejected state",255,0,0);
if(renderer.ValidationErrors!=0)throw new Exception($"Vulkan reported {renderer.ValidationErrors} validation errors.");
if(args.Length>0)renderer.SavePpm(args[0]);
Console.WriteLine($"PASS: {count} Vulkan material/readback checks; validation errors: {renderer.ValidationErrors}.");
void Check(string name,Mesh scene,int r,int g,int b)
{
renderer.ReplaceScene(scene,white);
renderer.Render(Matrix4x4.Identity);
AssertPixel(name,r,g,b);
}
void AssertPixel(string name,int r,int g,int b)
{
var pixels=renderer.ReadPixels();
var offset=(32*64+32)*4;
var expected=new[]{r,g,b};
for(var channel=0;channel<3;channel++)
if(Math.Abs(pixels[offset+channel]-expected[channel])>2)
throw new Exception($"{name}: expected ({r},{g},{b}), got ({pixels[offset]},{pixels[offset+1]},{pixels[offset+2]}).");
count++;
Console.WriteLine($"PASS: {name}");
}
void Throws(string name,Action action)
{
try {action();}
catch(ArgumentException){count++;Console.WriteLine($"PASS: {name}");return;}
throw new Exception($"{name}: expected ArgumentException.");
}
static Mesh Scene(params Layer[] layers)
{
var vertices=new List<MeshVertex>();var indices=new List<uint>();var draws=new List<MeshDraw>();
foreach(var layer in layers)
{
uint start=(uint)vertices.Count,first=(uint)indices.Count;
foreach(var xy in new[]{new Vector2(-1,-1),new Vector2(1,-1),new Vector2(1,1),new Vector2(-1,1)})
vertices.Add(new MeshVertex(new Vector3(xy,layer.Z),new Vector2(.5f),layer.Color));
indices.AddRange(new[]{start,start+1,start+2,start+2,start+3,start});
draws.Add(new MeshDraw(first,6,-1){Blend=layer.Blend,Opacity=layer.Opacity,ScreenSpace=layer.Screen});
}
return new Mesh(vertices.ToArray(),indices.ToArray()){HasExplicitDraws=true,Draws=draws.ToArray()};
}
readonly record struct Layer(Vector3 Color,float Z,MeshBlend Blend=MeshBlend.Opaque,float Opacity=1,bool Screen=false);
@@ -0,0 +1,12 @@
<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/UiViewport.cs" />
<Compile Include="../../src/GamePort/Application/GadgetMenuOverlay.cs" />
<Compile Include="../../src/GamePort/Application/ShrinkRayVisuals.cs" />
<Compile Include="../../src/GamePort/Application/ShrinkSoldierVisuals.cs" />
</ItemGroup>
</Project>
+179
View File
@@ -0,0 +1,179 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
void Check(bool value,string message) { if(!value)throw new Exception(message); }
var count=0;
void Test(string name,Action action) {action();count++;Console.WriteLine($"PASS {name}");}
SceneInventory Inventory() {var values=new int[19];values[3]=1;return new(values);}
Test("source control gate and combined default device",()=>{
var inventory=Inventory();inventory.SelectGadget(3);
var screen=new GadgetScreen(inventory);
Check(GadgetScreen.EquippedMode(3)==-1,"display3 must not become equipped mode3");
Check(!screen.Toggle(false)&&!screen.Open,"script ownership prohibits opening");
Check(screen.Toggle(true)&&screen.Open,"owned default device opens on first Tab");
screen.Toggle(true);Check(!screen.Open,"open panel closes on Tab");
});
Test("strict original card bounds and raw ownership",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);screen.Toggle(true);
foreach(var p in new[]{new Vector2(157,380),new(298,380),new(200,327),new(200,468)})
{screen.Point(p,"LV1B",60);Check(screen.Hovered==-1,"exact tile boundary must miss");}
screen.Point(new(200,380),"LV1B",60);Check(screen.Hovered==3,"owned shrink/jetpack tile hits");
inventory.SetState(0,3,4);screen.Point(new(200,380),"LV1B",60);
Check(screen.Hovered==-1,"unavailable ownership must not select");
inventory.SetState(0,3,3);screen.Point(new(200,380),"LV1B",60);
Check(screen.Hovered==3&&!screen.Canvases("LV1B",60).Any(c=>c.Id==14),"raw3 hits without green hover");
});
Test("original background and white/green owned art",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);
Check(screen.Canvases("LV1B",60).Select(c=>c.Id).SequenceEqual(new[]{20,48,182,180}),"unowned art remains base grey");
screen.Point(new(200,380),"LV1B",60);
Check(screen.Canvases("LV1B",60).Any(c=>c.Id==14)&&!screen.Canvases("LV1B",60).Any(c=>c.Id==48),"green selected by hover");
});
Test("Return closes without selecting or leaving practice armed",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);screen.Toggle(true);
screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
Check(screen.PracticeArmed,"Practice arms on click");
screen.Point(new(50,120),"LV1B",60);screen.Activate("LV1B",60);
Check(!screen.Open&&!screen.PracticeArmed&&inventory.SelectedGadget==-1,"Return closes/disarms only");
});
Test("armed gadget choice requests direct original tutorial",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);var chosen=-1;
var selectedAfterClose=false;inventory.GadgetSelected+=_=>selectedAfterClose=!screen.Open;
screen.PracticeRequested+=i=>chosen=i;screen.Toggle(true);
screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
screen.Point(new(200,380),"LV1B",60);screen.Activate("LV1B",60);
Check(chosen==3&&!screen.Open&&inventory.SelectedGadget==3&&selectedAfterClose,"source close-before-selection/direct item3→VR04");
screen.Toggle(true);screen.Point(new(520,120),"VR04",60);
Check(screen.Hovered==-1,"tutorial cannot recursively arm practice");
screen.Point(new(520,120),"LV1B",500);Check(screen.Hovered==-1,"scene500 blocks practice toggle");
});
Test("special equipped mode unequips before next Tab opens",()=>{
var inventory=Inventory();inventory.SetState(0,0,1);inventory.SelectGadget(0);
var screen=new GadgetScreen(inventory);screen.Toggle(true);
Check(!screen.Open&&inventory.SelectedGadget==-1,"first Tab unequips");
screen.Toggle(true);Check(screen.Open,"second Tab opens");
});
Test("real54-canvas overlay scales uniformly and preserves world",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);screen.Point(new(200,380),"LV1B",60);
var world=new Mesh([new(new(1,2,3),Vector2.Zero,Vector3.One)],[0,0,0])
{Textures=new(){[int.MinValue]=PngImage.White},HasCollisionMaterialIds=true};
var overlay=new GadgetMenuOverlay(world,"artifacts/extracted/gadgets/gadgets.json");
Check(overlay.Mesh.Vertices.Length==217&&overlay.Mesh.Textures.Count==55,"bounded original resources and unique texture IDs");
var final=overlay.Mesh with {Vertices=overlay.Mesh.Vertices.ToArray(),Draws=overlay.Mesh.Draws.Select(d=>d with{}).ToArray()};
foreach(var (width,height) in new[]{(1920u,1080u),(3440u,1440u),(1280u,1024u)})
{
overlay.Update(final,screen.Canvases("LV1B",60),width,height);
Check(final.Vertices[0].Position==new Vector3(1,2,3),"world vertices unchanged");
var a=final.Vertices[1].Position;var b=final.Vertices[3].Position;
var pixelsX=(b.X-a.X)*width/2;var pixelsY=(b.Y-a.Y)*height/2;
Check(MathF.Abs(pixelsX/pixelsY-640f/480)<.00001f,"original panel aspect ratio");
Check(final.Draws.Count(d=>d.ScreenSpace&&d.Visible)==4,"only source menu ranges visible");
var view=new UiViewport(width,height);var reference=new Vector2(200,380);
var ndc=view.ToNdc(reference+view.CenterOffset);
var point=view.InverseModal(new((ndc.X+1)*width/2,(ndc.Y+1)*height/2));
screen.Point(point,"LV1B",60);Check(screen.Hovered==3,"render and hit mapping agree");
}
overlay.Update(final,[],1920,1080);Check(final.Draws.Skip(1).All(d=>!d.Visible),"closing hides all gadget art");
});
Test("original menu pointer accumulation and neutral reset",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);
var p=screen.MovePointer(new(200,200),Vector2.UnitX,.25f);
Check(p==new Vector2(220,200),"source80*dt pointer offset");
p=screen.MovePointer(p,Vector2.UnitX,.25f);Check(p==new Vector2(260,200),"held axis accumulates offset");
Check(screen.MovePointer(p,Vector2.Zero,.25f)==p,"neutral discards accumulated axis");
});
Test("ray texture phase float/double boundary and discarded overshoot",()=>{
var ray=new ShrinkRay();ray.StepTexture(.1f);Check(ray.TexturePhase==1,"float.1 exceeds source double.1");
ray.StepTexture(.35f);Check(ray.TexturePhase==2,"one phase per invocation, no catchup");
ray.StepTexture(.1f);Check(ray.TexturePhase==0,"three source texture slots wrap");
ray.Reset();ray.StepTexture(.099f);Check(ray.TexturePhase==0,"below source boundary");
});
Test("continuous source target gates and no angle seam wrap",()=>{
var ray=new ShrinkRay();SupportHit? Clear(Vector3 a,Vector3 b)=>null;
var targets=new[]{new ShrinkCandidate("valid",new(0,0,1000)),new("body-off",new(0,0,800),false),
new("immune",new(0,0,800),ShrinkEnabled:false),new("already",new(0,0,800),Shrunk:true),
new("range",new(0,0,1500)),new("high",new(0,60,800)),new("low",new(0,-150,800)),
new("seam",new(1,0,1000)),new("near-zero",new(-1,0,1000)),new("last",new(0,0,900))};
Check(ray.Fire(Vector3.Zero,0,1f/60,targets,Clear).SequenceEqual(new[]{"valid","near-zero","last"}),
"source eligibility, strict range/height and input-order multi-hit");
Check(ray.Fire(Vector3.Zero,0,1f/60,targets,(a,b)=>new(Vector3.Zero,0,0,0)).Count==0,"any accepted static hit blocks");
var angle=OriginalHeading.Degrees(new(-1,0,1000));
Check(ray.Fire(Vector3.Zero,angle-5,1f/60,[new("edge",new(-1,0,1000))],Clear).Count==0,"exact yaw+5 is excluded");
});
var original=Path.GetFullPath("../Original");
var level=GamLevel.Load(AssetPath.Resolve(original,"gam/VR04.gam"));
var save=OriginalSave.Load(AssetPath.Resolve(original,"NewGame.tsk"));
Test("actual soldier shrink mode and strict timer expiry",()=>{
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var actor=director.Actors.First(a=>a.Kind=="3SOL");var old=actor.AIstate;
var soldier=new ShrinkSoldier(actor);soldier.Shrink();
Check(actor.Animation=="SHRINK"&&actor.AIstate==5&&soldier.Remaining==30,"source target callback state");
for(var i=0;i<40;i++)soldier.StepTimer(.75f);
Check(soldier.Remaining==0&&soldier.Shrunk,"exact source timer0 does not expire");
soldier.StepTimer(.1f);Check(soldier.Shrunk,"timer0 skips future positive-only countdown");
soldier.Reset();actor.AIstate=7;soldier.Shrink();
Check(soldier.PreviousMode==7&&soldier.AuthoredMode==old,"authored AIState is distinct from previous dynamic mode");
for(var i=0;i<34;i++)soldier.StepTimer(.9f);
Check(!soldier.Shrunk&&actor.Animation=="WALK"&&actor.AIstate==old&&actor.Speed==200,"negative crossing restores authored mode/WALK");
});
Test("source shrink morph reaches and holds authored endpoint",()=>{
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var soldier=new ShrinkSoldier(director.Actors.First(a=>a.Kind=="3SOL"));
var scene=new Mesh([],[]);var visuals=new ShrinkSoldierVisuals(scene,[soldier],"artifacts/extracted","VR04");
soldier.Shrink();visuals.Update(1,visuals.Mesh);
var height=visuals.RenderedHeight(soldier.Actor.Tag,visuals.Mesh);
Check(MathF.Abs(height-55.1186f)<.002f,"authored last shrink frame, no invented uniformscale");
visuals.Update(5,visuals.Mesh);Check(visuals.RenderedHeight(soldier.Actor.Tag,visuals.Mesh)==height,"nonloop endpoint stays small");
});
Test("ordinary primary fire, energy, sound transitions and release",()=>{
var lab=GamLevel.Load(AssetPath.Resolve(original,"gam/level1b.gam"));var start=lab.FindStart()!;
var world=Mesh.LoadSceneJson("artifacts/extracted/level1b/scene.json");
var player=new LabSimulation(new(world),AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase")),start.Position,start.Rotation.Y);
var director=new SceneDirector(lab,new(save.Tasks),(_,_)=>0);
var inventory=Inventory();using var gadgets=new SceneGadgets(director,inventory,player,world);
var loops=0;var stops=0;var clicks=0;
gadgets.Sound+=(id,loop)=>{if(id==0&&loop)loops++;if(id==117)clicks++;};gadgets.StopSound+=()=>stops++;
player.Step(new(true,false,false,false,false,Fire:true));
Check(gadgets.Ray.Visible&&player.Shooting&&player.Speed==0&&player.Velocity.X==0&&player.Velocity.Z==0,"grounded fire stops controller movement before apply");
Check(MathF.Abs(player.Energy-(20-1f/60))<.0001f&&loops==1,"held beam charges once even without target");
player.Step(new(false,false,false,false,false,Fire:true));Check(loops==1,"owned loop is not restarted every tick");
player.Step(default);Check(!gadgets.Ray.Visible&&!player.Shooting&&stops==1,"release hides/stops effect");
inventory.SetState(0,3,0);player.Step(new(false,false,false,false,false,Fire:true));
player.Step(new(false,false,false,false,false,Fire:true));Check(clicks==1,"dry click latches until release");
});
Test("ray visual uses original geometry and single half-opacity additive material",()=>{
var visuals=new ShrinkRayVisuals(new Mesh([],[]),"artifacts/extracted",original);var ray=new ShrinkRay();
ray.Fire(Vector3.Zero,0,1f/60,[],(a,b)=>null);visuals.Update(visuals.Mesh,ray,0);
Check(visuals.Mesh.Vertices.Length==9&&visuals.Mesh.Indices.Length==9
&& visuals.Mesh.Vertices.Select(v=>v.Position).Distinct().Count()==5,"original five source vertices expanded by UV corners");
var beamDraws=visuals.Mesh.Draws.Where(d=>d.IndexCount!=0).ToArray();
Check(beamDraws.Count(d=>d.Visible)==1&&beamDraws.All(d=>d.Opacity==.5f&&d.Blend==MeshBlend.Additive),"source alpha replaces once and one texture phase renders");
ray.Hide();visuals.Update(visuals.Mesh,ray,0);Check(beamDraws.All(d=>!d.Visible),"release hides all phases");
});
Test("ordinary hit score order, repeated-hit guard and original save persistence",()=>{
//Explicit synthetic floor for deterministic actor settling; actual original
//VR04 soldier records are used, never substituted into the playable level.
var floor=new Mesh([new(new(-10000,0,-10000),Vector2.Zero,Vector3.One),
new(new(10000,0,-10000),Vector2.Zero,Vector3.One),new(new(0,0,10000),Vector2.Zero,Vector3.One)],[0,1,2])
{CollisionPolygons=[new(0,0,Vector3.UnitY,null)],HasCollisionMaterialIds=true};
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var interactions=new SceneInteractions(director,new(save.Tasks),save);
interactions.Inventory.SetState(0,3,1);
var player=new LabSimulation(new(floor),AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase")),Vector3.Zero,0,
originalCollision:OriginalStaticCollision.FromRouteScene(floor,"VR04")){LevelCode="VR04"};
using var gadgets=new SceneGadgets(director,interactions.Inventory,player,floor);
for(var i=0;i<600;i++)gadgets.StepBodies(1f/60);
var target=gadgets.Soldiers[0];
player.ApplyAuthoredTransform(new(target.Actor.Position.X,75.9f,target.Actor.Position.Z-500),0);
var observed=false;
gadgets.ScoreAwarded+=points=>{observed=points==10&&target.Shrunk&&target.Actor.AIstate==5&&target.HitMarker==0;interactions.ChangeScore(points);};
player.Step(new(false,false,false,false,false,Fire:true));
Check(observed&&target.HitMarker==1&&interactions.Score==save.Score+10,"source score callback follows shrink and precedes94C marker");
for(var i=0;i<10;i++)player.Step(new(false,false,false,false,false,Fire:true));
Check(interactions.Score==save.Score+10&&gadgets.ShrinkHits==1,"already-shrunk flag prevents repeated awards");
Check(OriginalSave.Parse(interactions.Snapshot().Encode()).Score==save.Score+10,"source-format save preserves gadget reward");
Check(player.Energy==20,"original VR energy exemption also applies to primary fire");
});
Console.WriteLine($"Gadgets:{count} groups passed; other gadget effects and complete enemy AI remain separate.");
@@ -0,0 +1,13 @@
<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/OriginalHeading.cs" Link="OriginalHeading.cs" />
</ItemGroup>
</Project>
+47
View File
@@ -0,0 +1,47 @@
using System.Numerics;
using GamePort.Game;
// Source vector::angles cardinal/quadrant results, plus copied-DLL references.
var samples = new (Vector3 Direction, int Units)[]
{
(Vector3.Zero, 0), (Vector3.UnitZ, 0), (-Vector3.UnitX, 4096),
(-Vector3.UnitZ, 8192), (Vector3.UnitX, 12288),
(new(-1, 0, 1), 2048), (new(-1, 0, -1), 6144),
(new(1, 0, -1), 10240), (new(1, 0, 1), 14336),
(new(1, 100, 1000), 16364), (new(-1, -100, 1000), 20),
(new(1000, 0, 1), 12288), (new(-1000, 0, 1), 4096),
(new(.1234567f, 88, .7654321f), 15967), (new(-99.1f, -20, 15.7f), 3686),
};
foreach (var (direction, units) in samples)
{
float actual = OriginalHeading.Degrees(direction);
if (actual != units * 0.02197265625f)
throw new Exception($"Heading {direction}: expected {units} units, got {actual} degrees");
}
foreach (var bad in new[] { new Vector3(float.NaN, 0, 1), new Vector3(0, float.PositiveInfinity, 1) })
{
try { OriginalHeading.Degrees(bad); throw new Exception("Nonfinite vector accepted"); }
catch (ArgumentOutOfRangeException) { }
}
// A seam-crossing near-forward direction remains near360; the caller performs
// the original strict comparisons against Jimmy's EulerY without wrapping.
float seam = OriginalHeading.Degrees(new Vector3(1, 0, 1000));
if (seam is not (> 355 and < 360)) throw new Exception("Heading seam normalized away");
if (-5 < seam && seam < 5) throw new Exception("Source seam comparison changed");
uint hash = 2166136261;
int cases = 0;
for (int i = 0; i <= 16384; i++)
{
float a = (float)Math.Sqrt((i + .25) / 16384.5);
float b = (float)Math.Sqrt(1 - (i + .25) / 16384.5);
for (int quadrant = 0; quadrant < 4; quadrant++)
{
var direction = new Vector3((quadrant & 1) != 0 ? -b : b, 0, (quadrant & 2) != 0 ? -a : a);
ushort units = (ushort)(OriginalHeading.Degrees(direction) / .02197265625f);
hash = unchecked((hash ^ units) * 16777619);
cases++;
}
}
// Observed through the copied OMT2.dll export, heading-probe/wine.log.
if (hash != 0x24e64f91) throw new Exception($"Original-DLL sweep mismatch: {hash:x8}");
Console.WriteLine($"Heading: {samples.Length} copied-DLL references, {cases} sweep cases, finite guards and unwrapped seam passed.");
+69
View File
@@ -0,0 +1,69 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from gadget_controls import (collect, tab_action, hit_gadgets, practice_toggle,
default_device_selection, TILES)
class GadgetControlTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_source_identity_spans_and_virtual_targets(self):
self.assertEqual(len(self.report['bodies']), 9)
self.assertEqual(len(self.report['sites']), 40)
self.assertEqual(len(self.report['vtables']), 10)
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['tab_byte']['bytes'], 'a041985000')
self.assertEqual(sites['space_byte']['bytes'], 'a058985000')
self.assertEqual(sites['unequip_global']['file_offset'], '0x25ac2')
def test_tab_distinguishes_close_unequip_and_open_and_held_edge(self):
self.assertEqual(tab_action(True, -1), 'close')
self.assertEqual(tab_action(False, 5), 'unequip')
self.assertEqual(tab_action(False, -1), 'open_gadgets')
for opened in (True, False):
self.assertEqual(tab_action(opened, -1, latched=True), 'none')
def test_exact_tile_layout_and_strict_boundaries(self):
self.assertEqual(TILES[3], (157, 327))
for item, (x, y) in enumerate(TILES):
self.assertEqual(hit_gadgets([1]*8, x+70, y+70), item)
for a, b in ((x, y+70), (x+141, y+70), (x+70, y), (x+70, y+141)):
self.assertIsNone(hit_gadgets([1]*8, a, b))
def test_hit_filter_is_raw_state_not_owned_boolean(self):
x, y = TILES[3]
for state in (0, 4):
self.assertIsNone(hit_gadgets([state]*8, x+70, y+70))
for state in (1, 2, 3, -1):
self.assertEqual(hit_gadgets([state]*8, x+70, y+70), 3)
def test_display_highlight_three_is_not_equipped_mode_three(self):
table = self.report['selection_table']
self.assertEqual(table[0], table[4]) # Requested−1 and3 share branch428DE0.
state = default_device_selection(3)
self.assertEqual((state['highlight'], state['equipped_mode']), (3, -1))
self.assertIsNone(state['practice_level'])
def test_practice_toggles_only_outside_tutorial_and_before_scene500(self):
self.assertEqual(practice_toggle(3, 'LV1B', 60), 2)
self.assertEqual(practice_toggle(2, 'LV1B', 60), 3)
self.assertEqual(practice_toggle(3, 'LV1B', 500), 3)
for i in range(1, 9):
self.assertEqual(practice_toggle(3, f'VR0{i}', 60), 3)
state = default_device_selection(2)
self.assertEqual((state['practice_level'], state['practice_state']), ('VR04', 1))
def test_practice_destination_calls_match_all_eight_item_indices(self):
self.assertEqual([p['level'] for p in self.report['practice']], [f'vr0{i}.gam' for i in range(1,9)])
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['initial_practice_return_state1']['bytes'], '6a016a0953e8f814feff6a016a0a53e8ee14feff')
if __name__ == '__main__':
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from gadget_resources import CANVASES, export_gadget_resources
from omt import Database, FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class GadgetResourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.database = Database(ORIGINAL/'omt/screens.omt')
def test_exact_original_pixels_identities_and_dimensions_are_preserved(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'gadgets'
manifest = export_gadget_resources(self.database, output)
self.assertEqual(manifest['sourceSha256'], 'e8e95231f5d302b41f4fbf33df1c5a08ce4645370f9f519527ff1727b73b7a5e')
self.assertEqual((manifest['referenceWidth'], manifest['referenceHeight']), (640, 480))
self.assertEqual(len(manifest['textures']), 54)
self.assertEqual(len({texture['id'] for texture in manifest['textures']}), 54)
self.assertEqual(manifest, json.loads((output/'gadgets.json').read_text()))
by_id = {texture['id']: texture for texture in manifest['textures']}
self.assertEqual(by_id[14]['name'], 'item04')
self.assertEqual(manifest['tiles'][3]['label'], 'SHRINK RAY')
self.assertEqual(by_id[119]['name'], '9jetpack')
self.assertEqual((by_id[253]['width'], by_id[253]['height']), (15, 210))
for texture in manifest['textures']:
rgba = (output/texture['path']).read_bytes()
self.assertEqual(len(rgba), texture['width']*texture['height']*4)
self.assertEqual(hashlib.sha256(rgba).hexdigest(), texture['rgbaSha256'])
self.assertTrue((output/texture['png']).is_file())
def test_exports_cannot_overwrite_any_original_asset_subtree(self):
for output in (ORIGINAL, ORIGINAL/'omt/generated', ORIGINAL/'ASE/generated', ORIGINAL/'png/generated'):
with self.subTest(output=output), self.assertRaises(ValueError):
export_gadget_resources(self.database, output)
def test_changed_resource_contract_rejects_before_writing(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'gadgets'
with patch('gadget_resources.read_canvas', return_value=dict(width=1, height=1, rgba=b'\0'*4)):
with self.assertRaises(FormatError):
export_gadget_resources(self.database, output)
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
import math
from pathlib import Path
import sys
import unittest
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT / 'tools/binary'))
import shrink_heading as heading
class ShrinkHeadingTests(unittest.TestCase):
def test_quadrants(self):
for x, z, units in [(0, 0, 0), (0, 1, 0), (-1, 0, 4096),
(0, -1, 8192), (1, 0, 12288),
(-1, 1, 2048), (-1, -1, 6144),
(1, -1, 10240), (1, 1, 14336)]:
self.assertEqual(heading.heading_units(x, z), units)
def test_strict_window_and_no_seam_wrap(self):
self.assertTrue(heading.within_heading_window(0, 1, 0))
self.assertFalse(heading.within_heading_window(0, 1, 5))
self.assertFalse(heading.within_heading_window(0, 1, -5))
self.assertFalse(heading.within_heading_window(1, 1000, 0))
self.assertTrue(heading.within_heading_window(-1, 1000, 0))
def test_nonfinite(self):
for value in [math.nan, math.inf, -math.inf]:
with self.assertRaises(ValueError):
heading.heading_units(value, 1)
def test_copied_dll_samples(self):
for x, z, expected in [(1, 1000, 16364), (-1, 1000, 20),
(1000, 1, 12288), (-1000, 1, 4096),
(.1234567, .7654321, 15967), (-99.1, 15.7, 3686)]:
self.assertEqual(heading.heading_units(x, z), expected)
def test_copied_dll_full_bin_quadrant_sweep(self):
fingerprint = 2166136261
for i in range(16385):
a = heading.f32(math.sqrt((i + .25) / 16384.5))
b = heading.f32(math.sqrt(1 - (i + .25) / 16384.5))
for quadrant in range(4):
value = heading.heading_units(-b if quadrant & 1 else b,
-a if quadrant & 2 else a)
fingerprint = ((fingerprint ^ value) * 16777619) & 0xffffffff
self.assertEqual(fingerprint, 0x24e64f91)
def test_full_source_identity(self):
exe = PROJECT / 'artifacts/uncontrolled-phases/rea/Neutron.exe'
dll = PROJECT / 'artifacts/asset-probe/game/OMT2.dll'
if not exe.exists() or not dll.exists():
self.skipTest('generated original copies unavailable')
report = heading.evidence(exe, dll)
self.assertEqual(report['table_fnv32'], '4f800433')
self.assertEqual(report['exported']['ordinal'], 278)
if __name__ == '__main__':
unittest.main()
+67
View File
@@ -0,0 +1,67 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from shrink_ray import collect, target_eligible, texture_step, f32
class ShrinkRaySourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_source_bodies_constants_assets_and_opacity(self):
self.assertEqual(len(self.report['bodies']), 8)
self.assertEqual(self.report['constants'], dict(lower_y=150, upper_y=60, range=1500,
yaw_half_angle=5, angle_unit_degrees=.02197265625, texture_period=.1))
self.assertEqual(self.report['strings']['0x4ef71c'], 'SHRINK')
self.assertEqual(self.report['strings']['0x4f0b78'], 'ray.ase')
names = {site['name'] for site in self.report['sites']}
self.assertTrue({'alpha_not_scale', 'blend_src6', 'ray_rotation_copy', 'target_callback'}.issubset(names))
def test_default_owned3_uses_mode_minus1_not_menu_highlight3(self):
p, t = (0, 0, 0), (0, 0, 100)
self.assertTrue(target_eligible(p, t, 0, 0))
for state in (0, 2, 3, 4):
self.assertFalse(target_eligible(p, t, 0, 0, owned_state=state))
for mode in range(8):
self.assertFalse(target_eligible(p, t, 0, 0, equipped_mode=mode))
def test_target_class_enabled_and_already_shrunk_gates_are_independent(self):
p, t = (0, 0, 0), (0, 0, 100)
for kw in (dict(integrates=False), dict(enemy=False), dict(enabled=False), dict(shrunk=True), dict(wall_hit=True)):
self.assertFalse(target_eligible(p, t, 0, 0, **kw))
def test_strict_range_and_height(self):
p = (0, 0, 0)
self.assertTrue(target_eligible(p, (0, 0, 1499.99), 0, 0))
self.assertFalse(target_eligible(p, (0, 0, 1500), 0, 0))
for y in (-150, 60):
self.assertFalse(target_eligible(p, (0, y, 100), 0, 0))
for y in (-149.999, 59.999):
self.assertTrue(target_eligible(p, (0, y, 100), 0, 0))
def test_strict_quantized_yaw_window_does_not_add_seam_wrapping(self):
p, t = (0, 0, 0), (0, 0, 100)
for angle in (-5, 5, 359):
self.assertFalse(target_eligible(p, t, 0, angle))
for angle in (-4.999, 0, 4.999):
self.assertTrue(target_eligible(p, t, 0, angle))
def test_texture_float_accumulator_double_threshold_and_single_advance(self):
self.assertEqual(texture_step(0, 0, .099999994), (0, f32(.099999994)))
self.assertEqual(texture_step(0, 0, f32(.1)), (1, 0))
self.assertEqual(texture_step(2, 0, .5), (0, 0))
self.assertEqual(texture_step(1, .09, .02), (2, 0))
def test_original_engine_blend_table_distinguishes_additive_and_alpha(self):
blend = self.report['blend']
self.assertEqual((blend['source_alpha'], blend['additive_destination'], blend['alpha_destination']), (5, 2, 6))
self.assertEqual(blend['body_file_offset'], '0x36ab0')
self.assertEqual(blend['table_file_offset'], '0x13667c')
if __name__ == '__main__':
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
from shrink_targets import collect, timer_step
class ShrinkTargetSourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_byte_body_and_dispatch_identity(self):
self.assertTrue(self.report['known_binary'])
for group in ('bodies', 'sites', 'vtables', 'strings', 'clips'):
with self.subTest(group=group):
self.assertTrue(all(x['matches'] for x in self.report[group]))
self.assertEqual(len(self.report['bodies']), 8)
self.assertEqual((self.report['radius'], self.report['factor']), (90, 1))
modes = self.report['modes']
self.assertFalse(modes['shrink_snapshots_authored'])
self.assertEqual((modes['current_complete'], modes['previous_complete'], modes['authored_complete']),
('0x6c8', '0x6cc', '0x93c'))
self.assertEqual((modes['authored_property'], modes['initial_authored'], modes['expiry_restores']),
('AIState', 2, 'authored'))
def test_shrink_is_authored_geometry_with_compatible_topology(self):
clips = {c['name'].casefold(): c for c in self.report['clips']}
shrink = clips['soldshrink.ase']
self.assertEqual(shrink['times'], [0, 960, 1920, 2880, 3840])
self.assertEqual((shrink['frames_per_second'], shrink['ticks_per_frame']), (5, 960))
heights = [high-low for low, high in shrink['y_bounds']]
self.assertTrue(all(a > b for a, b in zip(heights, heights[1:])))
self.assertAlmostEqual(heights[0], 315.8297)
self.assertAlmostEqual(heights[-1], 55.1186)
for clip in clips.values():
self.assertEqual(set(clip['vertex_counts']), {190})
self.assertEqual(set(clip['face_counts']), {377})
self.assertEqual({t['name'].casefold() for t in self.report['textures']},
{'vryoksoldier.png', 'yoksold.png', 'yoksoldtalk.png'})
def test_timer_preserves_strict_original_expiry_boundary(self):
self.assertEqual(timer_step(30, 1), (29, True, False))
self.assertEqual(timer_step(.25, .5), (0, False, True))
self.assertEqual(timer_step(.25, .25), (0, True, False))
self.assertEqual(timer_step(0, 1), (0, True, False))
self.assertEqual(timer_step(0, 1, False), (0, False, False))
def test_original_vr04_has_three_authored_soldiers(self):
targets = self.report['vr04']['targets']
self.assertEqual([t['file_offset'] for t in targets], ['0x4431', '0x582c', '0x67c5'])
self.assertEqual([t['fields']['ObjectTag'] for t in targets],
['yoke1', 'C3DYOKIANSOLDIER', 'yoke2'])
for target in targets:
fields = target['fields']
self.assertEqual((fields['HasCollision'], fields['CanMove'], fields['AIState']), (1, 1, 2))
self.assertGreater(fields['PositionY'], 6300)
self.assertAlmostEqual(targets[0]['fields']['PositionX'], -2463.103515625)
self.assertAlmostEqual(targets[2]['fields']['PositionZ'], 1319.027587890625)
if __name__ == '__main__':
unittest.main()
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Read-only gadget panel contracts from retained REA and guarded EXE spans."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODIES = (
('menu_keys', 0x425870, 0x425B20, 'd06e437c3b858d187a094306891333ce735445c412e35ef8ccb33c37d8ce7735'),
('menu_close', 0x425B20, 0x425C32, '8e80202c37b31235630e097297395c3c196959dfa11fdc5582cf6acc7b7a74c4'),
('menu_open', 0x425EF0, 0x426027, '472c5356cc85c9d3e79f053e63114fb03d7b81d79b51a653fc56c7ae1fee1008'),
('menu_tick', 0x427370, 0x427F6F, 'c0a95b31c9d2c0563c132fd2a8b04fd1710c2b77a17e0746722b407909f10b45'),
('hit', 0x403A30, 0x403BCE, 'fd20747d496832e9582deea8daa1c41c1400e9de35d07656ca622a61614ed2ce'),
('initialize', 0x404DE0, 0x405F70, 'd3505b89b02f229976a47566c1e1a5897489fc52bc21b55ee234b1c552c2057c'),
('select', 0x428D50, 0x4298E8, 'e86e6ad89c80b6d1656c3f4697d8f2cb06f79c4d2bc1c403f5449ad391aec9ff'),
('render', 0x402F60, 0x4032C0, '74653924b0988d391478ef1f3cbf96eda8cda0283b5665e22f295b41b9abd462'),
('description_init', 0x4018B4, 0x401A37, '1debbfc78bf08053a878fff43c54c7d38362920fa87d8393f02d86144369d5d7'),
)
# Slices are protected by the full EXE identity and the applicable spans above.
# Retain offsets/bytes for individual review rather than inferred signatures.
SITES = (
('tab_byte', 0x4258EB, 5), ('space_byte', 0x4258F8, 5),
('shared_key_latch', 0x425A7C, 6), ('open_flag_before_toggle', 0x425A99, 5),
('selected_mode_test', 0x425AAE, 8), ('cleanup_before_unequip', 0x425ABC, 6),
('unequip_global', 0x425AC2, 9), ('open_mode_zero', 0x425AE1, 4),
('open_mode_call', 0x425AF1, 6), ('open_game_pause', 0x425F8D, 6),
('open_flag_write', 0x425F9D, 7), ('open_physics_disable', 0x425FE9, 8),
('open_sound_gate_false', 0x426004, 7), ('close_flag_false', 0x425B4C, 6),
('close_game_resume', 0x425BAB, 6), ('close_sound_gate_true', 0x425BFE, 7),
('close_physics_enable', 0x425C05, 8), ('hit_state_skip_zero', 0x403A69, 9),
('hit_state_skip_four', 0x403A72, 10), ('hit_x_lower_strict', 0x403AD1, 9),
('hit_y_lower_strict', 0x403B04, 5), ('hit_state_three', 0x403B2E, 6),
('hit_return_last', 0x403BBF, 5), ('practice_scene500', 0x427794, 7),
('practice_vr_range', 0x4277B5, 20), ('practice_old_state_two', 0x4277DF, 6),
('practice_disarm_three', 0x4277E5, 11), ('practice_arm_two', 0x4277FC, 11),
('return_slot10', 0x427866, 10), ('select_close_before_cleanup', 0x4278DB, 6),
('select_cleanup', 0x4278E5, 6), ('select_from_menu4c8', 0x4278F3, 16),
('select_body_enable_after', 0x42791C, 7), ('select_ui_prelude', 0x428D8F, 15),
('select_table', 0x428DCD, 19), ('default_device_practice_state', 0x428DE0, 19),
('default_device_practice_load', 0x428E26, 44),
('initial_practice_return_state1', 0x4223BE, 20),
('escape_closes_open_panel', 0x42AB6D, 19),
('initial_display_highlight3', 0x401F93, 10),
)
VTABLES = (
(0x4A3BDC, 0x184, 0x425870), (0x4A3BDC, 0x1AC, 0x427370),
(0x4A3BDC, 0x1F8, 0x425EF0), (0x4A3BDC, 0x1FC, 0x425B20),
(0x4A3BDC, 0x174, 0x428D50), (0x48D414, 0x4A4, 0x403A30),
(0x48D414, 0x4A8, 0x403A10), (0x48D414, 0x4B0, 0x405FB0),
(0x48D414, 0x498, 0x406240), (0x48D414, 0x4C4, 0x406590),
)
TILES = ((12, 182), (158, 182), (12, 327), (157, 327),
(342, 182), (487, 182), (342, 327), (487, 327))
IDLE_CANVASES = (52, 46, 47, 48, 49, 50, 51, 45)
DESCRIPTION_CANVASES = (109, 115, 111, 113, 116, 114, 118, 110)
PRACTICE = (
(0, 0x428FCA, 0x4EF650, 'vr01.gam'), (1, 0x4296E8, 0x4EF58C, 'vr02.gam'),
(2, 0x428F51, 0x4EF678, 'vr03.gam'), (3, 0x428E41, 0x4EF6A0, 'vr04.gam'),
(4, 0x429348, 0x4EF628, 'vr05.gam'), (5, 0x42943D, 0x4EF5D8, 'vr06.gam'),
(6, 0x4297CD, 0x4EF564, 'vr07.gam'), (7, 0x4298B2, 0x4EF53C, 'vr08.gam'),
)
def collect(original: Path | str):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
bodies = []
for name, start, end, expected in BODIES:
actual = hashlib.sha256(read_va(pe, start, end - start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed source span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start - pe.base)),
length=end-start, sha256=actual))
sites = [dict(name=name, va=hex(va), file_offset=hex(pe.offset(va - pe.base)),
bytes=read_va(pe, va, length).hex()) for name, va, length in SITES]
tables = []
for base, slot, expected in VTABLES:
target = struct.unpack('<I', read_va(pe, base + slot, 4))[0]
if target != expected:
raise ValueError(f'Changed virtual {base:x}+{slot:x}')
tables.append(dict(table=hex(base), slot=hex(slot), target=hex(target)))
practice = []
for item, call, string, name in PRACTICE:
if read_va(pe, call, 5) != b'\x68' + struct.pack('<I', string) or read_va(pe, string, len(name)+1) != name.encode()+b'\0':
raise ValueError('Changed practice destination')
practice.append(dict(item=item, push_va=hex(call), push_offset=hex(pe.offset(call-pe.base)),
string_va=hex(string), level=name))
return dict(sha256=digest, bodies=bodies, sites=sites, vtables=tables, practice=practice,
selection_table=[hex(v) for v in struct.unpack('<10I', read_va(pe, 0x4298E8, 40))],
tiles=[dict(item=i, x=x, y=y, hover_canvas=11+i, idle_canvas=IDLE_CANVASES[i],
description_canvas=DESCRIPTION_CANVASES[i]) for i, (x, y) in enumerate(TILES)])
def tab_action(panel_open: bool, equipped_mode: int, latched: bool = False):
"""Bounded425870 branch; caller/game/other-key preconditions are separate."""
if latched:
return 'none'
if panel_open:
return 'close'
return 'unequip' if equipped_mode != -1 else 'open_gadgets'
def hit_gadgets(states, x: float, y: float):
if len(states) != 8:
raise ValueError('Eight group0 gadget states required')
result = None
for item, ((left, top), state) in enumerate(zip(TILES, states)):
if state not in (0, 4) and left < x < left + 141 and top < y < top + 141:
result = item
return result
def practice_toggle(current: int, level: str, scene_task: int):
if scene_task >= 500 or 'VR01' <= level <= 'VR08':
return current
return 3 if current == 2 else 2
def default_device_selection(practice_state: int):
"""After ordinary cleanup, item3 keeps source mode−1; UI highlight is3."""
return dict(highlight=3, equipped_mode=-1,
practice_level='VR04' if practice_state == 2 else None,
practice_state=1 if practice_state == 2 else practice_state)
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Read-only heading evidence and bounded projection of OMT2 vector::angles.
This module executes no original code. --emit-probe emits a separate component
probe for the existing isolated copied-DLL reference-capture harness.
"""
from functools import lru_cache
from pathlib import Path
import argparse
import hashlib
import json
import math
import struct
from pe_inspect import PE
EXE_SHA256 = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
DLL_SHA256 = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
ANGLE_EXPORT = '?angles@OMedia3DVector@@QAEXAAF0@Z'
UNITS_TO_DEGREES = 0.02197265625
def f32(value):
return struct.unpack('<f', struct.pack('<f', value))[0]
@lru_cache(maxsize=1)
def half_acos_table():
# OMT2 init_table100EDC8C..100EDCD0; the final endpoint is explicitly zero.
return tuple(int(math.acos(i * 0.0001220703125 - 1.0)
* 2607.5945876921437 * 0.5) for i in range(16384)) + (0,)
def heading_units(x, z):
"""Second output of original vector::angles, finite float32 horizontal input.
Products/division deliberately use Python double, approximating the original
x87 extended intermediates. Values at a ratio integer boundary can need a
copied-DLL check; do not claim arbitrary-input bit equivalence.
"""
x, z = f32(x), f32(z)
if not (math.isfinite(x) and math.isfinite(z)):
raise ValueError('finite float32 components required')
if x == 0 and z == 0:
return 0
index = int(16384.0 * z * z / (x * x + z * z))
angle = half_acos_table()[index]
if z < 0:
angle = 8192 + angle if x < 0 else 8192 - angle
elif x < 0:
angle = 16384 - angle
return (-angle) & 0x3fff
def within_heading_window(x, z, jimmy_yaw):
"""Source426E40's strict comparisons; deliberately no seam wrapping."""
heading = heading_units(x, z) * UNITS_TO_DEGREES
yaw = f32(jimmy_yaw)
return yaw - 5 < heading < yaw + 5
def _read(pe, va, length):
offset = pe.offset(va - pe.base)
if offset < 0 or offset + length > len(pe.data):
raise ValueError('source range outside file')
return pe.data[offset:offset + length]
def evidence(executable, dll):
pe, omt = PE(executable), PE(dll)
for binary, expected in [(pe, EXE_SHA256), (omt, DLL_SHA256)]:
if hashlib.sha256(binary.data).hexdigest() != expected:
raise ValueError('source hash mismatch')
imported = next(i for i in pe.imports() if int(i['iat'], 16) == 0x48d108)
exported = next(e for e in omt.exports() if e['name'] == ANGLE_EXPORT)
if imported['name'] != ANGLE_EXPORT or int(exported['va'], 16) != 0x1001fda0:
raise ValueError('heading import/export mismatch')
guards = [
(pe, 0x4270bf, 'ff1508d14800'),
(pe, 0x4270d7, '0fbf542416'),
(pe, 0x4270df, 'd82550d94800'),
(pe, 0x4270ed, 'd80db4e54800'),
(pe, 0x4270f7, 'f6c4410f8510020000'),
(pe, 0x42711a, 'd80550d94800'),
(pe, 0x427132, 'f6c4010f84d5010000'),
(omt, 0x1001fdf5, '668b0c4d301e1410'),
(omt, 0x1001fe32, '8b542414f7d825ff3f0000668902'),
(omt, 0x10104e13, '80cc0c'),
(omt, 0x10104e1d, 'df7df4'),
(omt, 0x100edcaf, 'e850710100'),
(omt, 0x100edd0d, '6689ae08800200'),
]
for binary, va, pattern in guards:
if _read(binary, va, len(pattern) // 2).hex() != pattern:
raise ValueError(f'instruction mismatch at {va:#x}')
for binary, va, fmt, expected in [
(pe, 0x48d950, '<f', 5.0),
(pe, 0x48e5b4, '<f', UNITS_TO_DEGREES),
(omt, 0x10114850, '<f', -16384.0),
(omt, 0x10114588, '<d', 0.0001220703125),
(omt, 0x101166b8, '<d', 2607.5945876921437),
(omt, 0x10115448, '<d', 0.5)]:
if struct.unpack(fmt, _read(binary, va, struct.calcsize(fmt)))[0] != expected:
raise ValueError(f'constant mismatch at {va:#x}')
table_bytes = b''.join(struct.pack('<H', n) for n in half_acos_table())
fnv = 2166136261
for byte in table_bytes[:-2]:
fnv = ((fnv ^ byte) * 16777619) & 0xffffffff
if fnv != 0x4f800433:
raise ValueError('regenerated half-acos table fingerprint mismatch')
bodies = [(omt, 0x1001fda0, 0x1001ff6e),
(omt, 0x100edc00, 0x100edd2a),
(omt, 0x10104e04, 0x10104e2b),
(pe, 0x4270b1, 0x42713b)]
return dict(imported=imported, exported=exported,
sources=[dict(sha256=EXE_SHA256), dict(sha256=DLL_SHA256)],
bodies=[dict(va=hex(start), end_exclusive=hex(end),
file_offset=hex(binary.offset(start - binary.base)),
sha256=hashlib.sha256(_read(binary, start, end - start)).hexdigest())
for binary, start, end in bodies],
instruction_guards=len(guards), table_fnv32=f'{fnv:08x}',
table_sha256=hashlib.sha256(table_bytes).hexdigest())
PROBE = r'''/* Generated by shrink_heading.py; copied DLL only, isolated harness. */
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef void (__attribute__((thiscall)) *Angles)(const float*,short*,short*);
int main(void) {
setbuf(stdout,NULL);
HMODULE h=LoadLibraryA("Z:\\work\\game\\OMT2.dll");
if(!h){fprintf(stderr,"LoadLibrary failed %lu\n",GetLastError());return 2;}
Angles angles=(Angles)GetProcAddress(h,"?angles@OMedia3DVector@@QAEXAAF0@Z");
if(!angles)return 3;
float vectors[][4]={{0,0,0,0},{0,0,1,0},{-1,0,0,0},{0,0,-1,0},{1,0,0,0},
{-1,0,1,0},{-1,0,-1,0},{1,0,-1,0},{1,0,1,0},
{1,100,1000,0},{-1,-100,1000,0},{1000,0,1,0},{-1000,0,1,0},
{.1234567f,88,.7654321f,0},{-99.1f,-20,15.7f,0}};
for(unsigned i=0;i<sizeof(vectors)/sizeof(vectors[0]);i++) {
short pitch=-123,yaw=-123;angles(vectors[i],&pitch,&yaw);
printf("ANGLE %.9g %.9g %.9g pitch=%d yaw=%d\n",vectors[i][0],vectors[i][1],vectors[i][2],pitch,yaw);
}
/* Cover all lookup-bin interiors/quadrants with synthetic finite vectors. */
unsigned cases=0;uint32_t hash=2166136261u;
for(unsigned i=0;i<=16384;i++)for(unsigned quadrant=0;quadrant<4;quadrant++) {
float a=(float)sqrt((i+.25)/16384.5),b=(float)sqrt(1.-(i+.25)/16384.5);
float v[4]={quadrant&1?-b:b,0,quadrant&2?-a:a,0};
short pitch,yaw;angles(v,&pitch,&yaw);
hash=(hash^(uint16_t)yaw)*16777619u;cases++;
}
printf("HEADING_SWEEP cases=%u fnv_words=%08lx\n",cases,(unsigned long)hash);
puts("SHRINK_HEADING_COMPLETE: isolated copied DLL component, no game entry point");
FreeLibrary(h);return 0;
}
'''
def main():
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('--exe', type=Path, default=Path('artifacts/uncontrolled-phases/rea/Neutron.exe'))
cli.add_argument('--dll', type=Path, default=Path('artifacts/asset-probe/game/OMT2.dll'))
cli.add_argument('--emit-probe', type=Path)
args = cli.parse_args()
report = evidence(args.exe, args.dll)
if args.emit_probe:
originals = Path(__file__).resolve().parents[3] / 'Original'
if args.emit_probe.resolve().is_relative_to(originals.resolve()):
cli.error('probe output must be separate from originals')
args.emit_probe.parent.mkdir(parents=True, exist_ok=True)
args.emit_probe.write_text(PROBE)
print(json.dumps(report, indent=2))
if __name__ == '__main__':
main()
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Read-only ordinary shrink-ray/input/effect source guards and bounded projections."""
import argparse
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import find_case, read_va
from pe_inspect import PE
EXE_SHA256 = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
DLL_SHA256 = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
BODIES = (
('primary_hold', 0x426030, 0x4269CD, 'ec176370191f7c77152e1a69ee9787485f013c6b144b4642a4b40a99271dd438'),
('shrink_scan', 0x426E40, 0x427335, '41d4bdb4c1f5b8254e6590633bcf7235939a26653ef1ade22b62cc2f3658f268'),
('shrink_target', 0x42AC10, 0x42ADB5, '3b89f0e92d4ab6c6cf8c1e6b31021f977b62171d49111a6da78a30a9ec932973'),
('energy', 0x42A920, 0x42AA13, '6d6a880fb1b4e39addc588201b7d5bb86c768dbfa3778b35045fc10380c9c5e4'),
('primary_keys', 0x42A7A0, 0x42A7D6, 'c8fa10f42eefe68a195d9980f1a57558a240cd7877bfeab567e7868c0ddf419f'),
('ray_init', 0x440000, 0x440176, '56e73181c84e439f2030b5f44162910128cdee5def560fcc1e4e7e86e2fff806'),
('ray_tick', 0x440180, 0x44021E, '998f8db1294b5b034611e20535e64424192ff805f62e121f560319ad21d2b438'),
('ray_ctor', 0x43FE20, 0x43FF40, 'd8d9814d90c9095afc8fcbe12439e63c50e2830c122f6eded690f5583cc0d785'),
)
SITES = (
('primary_control_owner', 0x426053, 'a1e4995000'),
('primary_sample', 0x426566, 'e835420000'),
('enter_alternative', 0x426573, '6a0d'),
('zero_controller_speed', 0x4266BD, '89ae08060000'),
('shoot_animation', 0x42671A, '6a016848f44e00'),
('owned_slot3_for_sound', 0x4268BE, '6a0355e88ad0fdff'),
('loop_sound0', 0x4268E0, '6a01556affe896200300'),
('release_hides_ray', 0x42666E, '8bb650090000'),
('invoke_shrink_scan', 0x4269BD, 'ff90b8010000'),
('scan_owned_slot3', 0x426E4C, '6a036a00'),
('scan_owned_exact1', 0x426E5C, '663d0100'),
('scan_mode_minus1', 0x426E66, '66833d88054f00ff'),
('ray_position_copy', 0x426EF1, 'ff9318030000'),
('ray_rotation_copy', 0x426F47, 'ff9330030000'),
('energy_minus_dt', 0x426F4D, 'd984240001000051d9e0'),
('registry', 0x426F5F, '8b0d9c995000'),
('target_body_gate', 0x426F85, '8a853e010000'),
('target_class_name', 0x426F96, '6844e34e00'),
('target_enabled', 0x426FA8, '8a8598080000'),
('target_already_shrunk', 0x42713B, '8a85b0080000'),
('wall_query', 0x4271F5, 'e816500500'),
('wall_hit_rejects', 0x4271FD, '84c00f850b010000'),
('target_callback', 0x42720A, 'ff92dc010000'),
('target_shrink_animation', 0x42AC33, '6a00681cf74e00'),
('target_mode5', 0x42AC50, '6a05ff9224010000'),
('target_timer30', 0x42AC68, 'c780740900000000f041'),
('target_shrunk_flag', 0x42AC8A, 'c6807009000001'),
('ray_ctor_owned', 0x4222C9, 'e852db0100'),
('ray_publish_owned', 0x4222D9, '8985100a0000'),
('ray_ctor_phase0', 0x43FF0F, '66899ebc060000'),
('ray_bind_mesh', 0x440037, '68780b4f00683ce34e00'),
('ray_bind_texture0', 0x44004B, '6a00686c0b4f00'),
('ray_bind_texture1', 0x44006C, '6a0168600b4f00'),
('ray_bind_texture2', 0x44008D, '6a0268540b4f00'),
('ray_opacity_half', 0x440121, '680000003f'),
('ray_timer0', 0x44015F, 'c7870006000000000000'),
('ray_timer_gt_double_point1', 0x4401B5, 'dc1db8cf4900'),
('ray_phase_increment', 0x4401C2, '66ff86fc050000'),
('ray_phase_gt2', 0x4401E3, '6683befc05000002'),
('ray_tick_discards_remainder', 0x44020F, 'c7860006000000000000'),
('alpha_material_pointer', 0x40E503, '8d584c'),
('alpha_not_scale', 0x40E52A, '896b0c'),
('blend_src6', 0x40E535, '897830'),
('blend_dst7_or1', 0x40E53A, 'c7403407000000eb03897034'),
)
def collect(original):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Original EXE identity changed')
bodies = []
for name, begin, end, expected in BODIES:
actual = hashlib.sha256(read_va(pe, begin, end-begin)).hexdigest()
if actual != expected:
raise ValueError(f'Changed function body: {name}')
bodies.append(dict(name=name, va=hex(begin), file_offset=hex(pe.offset(begin-pe.base)),
size=end-begin, sha256=actual))
sites = []
for name, va, expected in SITES:
data = bytes.fromhex(expected)
if read_va(pe, va, len(data)) != data:
raise ValueError(f'Changed source site: {name}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=expected))
constants = {name: struct.unpack('<f', read_va(pe, va, 4))[0] for name, va in (
('lower_y', 0x4A3E34), ('upper_y', 0x49D5B4), ('range', 0x495318),
('yaw_half_angle', 0x48D950), ('angle_unit_degrees', 0x48E5B4))}
constants['texture_period'] = struct.unpack('<d', read_va(pe, 0x49CFB8, 8))[0]
strings = {hex(va): read_va(pe, va, 48).split(b'\0')[0].decode('ascii') for va in (
0x4EE344, 0x4EF71C, 0x4F0B78, 0x4F0B6C, 0x4F0B60, 0x4F0B54)}
dll = PE(find_case(Path(original), 'OMT2.dll'))
if hashlib.sha256(dll.data).hexdigest() != DLL_SHA256:
raise ValueError('Original DLL identity changed')
blend = read_va(dll, 0x10036AB0, 0x35)
if hashlib.sha256(blend).hexdigest() != '5869d3ab07f2797d6b83a60634c95e5faf56e8c806918cb07b4c205210b207eb':
raise ValueError('Changed engine blend adapter')
table = read_va(dll, 0x1013667C, 44)
expected_table = (1, 2, 9, 3, 10, 4, 5, 6, 7, 8, 11)
if struct.unpack('<11I', table) != expected_table:
raise ValueError('Changed engine blend factor table')
return dict(sha256=digest, bodies=bodies, sites=sites, constants=constants, strings=strings,
blend=dict(dll_sha256=DLL_SHA256, body_va='0x10036ab0', body_file_offset=hex(dll.offset(0x36AB0)),
table_va='0x1013667c', table_file_offset=hex(dll.offset(0x13667C)), d3d_table=expected_table,
source_alpha=expected_table[6], additive_destination=expected_table[1], alpha_destination=expected_table[7]))
def target_eligible(player, target, yaw, target_degrees, *, owned_state=1, equipped_mode=-1,
integrates=True, enemy=True, enabled=True, shrunk=False, wall_hit=False):
"""Projection of source gates; caller supplies original quantized target heading."""
return (owned_state == 1 and equipped_mode == -1 and integrates and enemy and enabled and not shrunk
and player[1]-150 < target[1] < player[1]+60 and math.dist(player, target) < 1500
and yaw-5 < target_degrees < yaw+5 and not wall_hit)
def f32(value):
return struct.unpack('<f', struct.pack('<f', value))[0]
def texture_step(phase, elapsed, seconds):
"""440180 float accumulator/double strict threshold, one advance/no carry."""
elapsed = f32(elapsed + seconds)
if elapsed > .1:
return (phase+1) % 3, 0.0
return phase, elapsed
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
args = parser.parse_args()
print(json.dumps(collect(args.original), indent=2))
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Read-only, byte-guarded 3SOL visual/shrink source contract.
REA findings are recorded in docs/gameplay/shrink-targets.md. This utility
rechecks their byte/asset provenance; it neither executes the game nor recovers
the full soldier AI or collision system. Addresses use preferred image bases.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
import sys
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent / 'extractors'))
sys.path.insert(0, str(HERE.parent / 'levels'))
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
from ase import read_ase
import gam
DLL_SHA256 = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
BODIES = (
('Neutron.exe', 'enemy_mode_setter', 0x4089B0, 0x408B93, '0f8a8d6894ff1d246abbf5d8493330c4c9d5508bb5f027deaff0c38dcc969695'),
('Neutron.exe', 'shared_yokian_constructor', 0x44A730, 0x44A97C, '4654b058e18f96c88a081878d432cd11e94ba3165529be6486b5e79d0dd321ed'),
('Neutron.exe', 'soldier_constructor', 0x44BEE0, 0x44C028, 'e4ad6ea59b4d5f4e0c30b08f0161ec677da08b9f3a06efe28f4dd9009c472ddc'),
('Neutron.exe', 'soldier_model_loader', 0x44C0B0, 0x44C1BB, '538a3dbf346547fd7ddfea85a8348acd91ddcb2006f2d9ed1ede594f9b9a367d'),
('Neutron.exe', 'shared_yokian_update_range', 0x44AA00, 0x44AF9B, 'bcc710da864a6954cfa2f61ca39a50aff2244c0965ee28882a62dd942309f8c2'),
('Neutron.exe', 'game_animation_selector', 0x40DA30, 0x40DAAD, 'f5c8baa1dd35b9920da657dbefcdd7bf3e927fcc764ea395bb50269f49dd4738'),
('OMT2.dll', 'engine_sequence_selector', 0x100209F0, 0x10020A9A, 'c430ff3c7036e6415f167579cab749db5811eabc296fbcee5e91bbf43f72173c'),
('OMT2.dll', 'engine_next_frame', 0x10021000, 0x100210B8, '4d39ade2bd9cd9456301146096e493a0b9dcec49e00e4e8fd8d94ecbc86eff72'),
)
SITES = (
('Neutron.exe', 'mode_setter_previous_current_fields', 0x4089E5, '8b8ec80600008dbe60040000505768dccb4e00898ecc0600008986c8060000'),
('Neutron.exe', 'mode5_no_additional_dispatch', 0x408BA8, '8e8b4000'),
('Neutron.exe', 'authored_aistate_property', 0x407F67, '8d867c0800006a06506890ca4e008bceff92fc030000'),
('Neutron.exe', 'yokian_initial_mode_two', 0x44A7D3, 'b802000000'),
('Neutron.exe', 'yokian_current_and_authored_mode', 0x44A7F7, '8986c806000089863c090000'),
('Neutron.exe', 'postload_restores_authored_mode', 0x409503, '8b96080600008d8e40ffffff89967c0800008b96080600008b0152ff9024010000'),
('Neutron.exe', 'capture_authored_reset_mode', 0x409460, '8b817c0800008981080600008b11ffa20c040000'),
('Neutron.exe', 'soldier_calls_yokian_constructor', 0x44BF32, 'e8f9e7ffff'),
('Neutron.exe', 'soldier_class_fourcc', 0x44BFF5, '684c4f5333'),
('Neutron.exe', 'walk_asset', 0x44C0C3, '6884194f00'),
('Neutron.exe', 'walk_action', 0x44C0C8, '6808d84e00'),
('Neutron.exe', 'shrink_asset', 0x44C0DC, '6874194f00'),
('Neutron.exe', 'shrink_action', 0x44C0E1, '685ce14e00'),
('Neutron.exe', 'talk_asset', 0x44C0F0, '6864194f00'),
('Neutron.exe', 'talk_action', 0x44C0F5, '68f0d74e00'),
('Neutron.exe', 'stop_asset', 0x44C104, '6864194f00'),
('Neutron.exe', 'stop_action', 0x44C109, '68f4c94e00'),
('Neutron.exe', 'vr_range_low', 0x44C121, '3d31305256'),
('Neutron.exe', 'vr_range_high', 0x44C128, '3d38305256'),
('Neutron.exe', 'vr_texture_0', 0x44C133, '6850194f00'),
('Neutron.exe', 'vr_texture_1', 0x44C144, '6850194f00'),
('Neutron.exe', 'regular_texture_0', 0x44C14F, '6844194f00'),
('Neutron.exe', 'regular_texture_1', 0x44C160, '6834194f00'),
('Neutron.exe', 'initial_walk', 0x44C184, '6854ca4e00'),
('Neutron.exe', 'body_radius_90', 0x44C19D, '680000b442'),
('Neutron.exe', 'body_radius_setter', 0x44C1A4, 'ff9010010000'),
('Neutron.exe', 'body_factor_1', 0x44C1AC, '680000803f'),
('Neutron.exe', 'body_factor_setter', 0x44C1B3, 'ff9200010000'),
('Neutron.exe', 'soldier_calls_yokian_update', 0x44C1C9, 'e832e8ffff'),
('Neutron.exe', 'initial_shrunk_flag_false', 0x44A905, '889e70090000'),
('Neutron.exe', 'timer_skip_unless_positive', 0x44AE6F, '0f85a4000000'),
('Neutron.exe', 'timer_subtract_delta', 0x44AE75, 'd986b4080000d8642468d996b4080000'),
('Neutron.exe', 'expiry_skip_unless_negative', 0x44AE90, '0f8483000000'),
('Neutron.exe', 'expiry_zero_timer', 0x44AE96, '899eb4080000'),
('Neutron.exe', 'expiry_clear_shrunk', 0x44AE9C, '889eb0080000'),
('Neutron.exe', 'expiry_saved_mode', 0x44AEA8, '8b8e7c080000'),
('Neutron.exe', 'expiry_mode_callback', 0x44AEBD, 'ff9024010000'),
('Neutron.exe', 'expiry_walk', 0x44AEC6, '6854ca4e00'),
('Neutron.exe', 'engine_sequence_call', 0x40DA61, 'ff5210'),
('Neutron.exe', 'game_copy_loop_flag', 0x40DA64, '889fad000000'),
('OMT2.dll', 'engine_restart_or_preserve_ordinal', 0x10020A3A, '8a44241484c07536'),
('OMT2.dll', 'engine_loop_gate', 0x10021079, '8a591d84db7434'),
('OMT2.dll', 'engine_wrap_first_frame', 0x10021080, '8b12'),
('OMT2.dll', 'engine_hold_current_frame', 0x100210B4, '5f5e5bc3'),
)
VTABLES = (
('soldier_complete_mode_setter', 0x4C1E64, 0x124, 0x4089B0),
('soldier_complete_load', 0x4C1E64, 0x10C, 0x44C0B0),
('soldier_complete_select_action', 0x4C1E64, 0xE0, 0x40DD90),
('soldier_complete_select_sequence', 0x4C1E64, 0xE4, 0x40DA30),
('soldier_interface_radius_set', 0x4C19C4, 0x110, 0x471240),
('soldier_interface_factor_set', 0x4C19C4, 0x100, 0x4711E0),
('soldier_interface_update', 0x4C19C4, 0x3C4, 0x44C1C0),
)
STRINGS = {
0x4ECA90: 'AIState',
0x4F1984: 'soldwalk.ase', 0x4F1974: 'soldshrink.ASE',
0x4F1964: 'soldatak.ASE', 0x4ED808: 'HIWALK', 0x4EE15C: 'HISHRINK',
0x4ED7F0: 'HITALK', 0x4EC9F4: 'HISTOP', 0x4F1950: 'vryoksoldier.png',
0x4F1944: 'yoksold.png', 0x4F1934: 'yoksoldtalk.png', 0x4ECA54: 'WALK',
}
ASSETS = {
'soldwalk.ASE': '98b16d95899a9d6f201d48b8f46183314c9570def076c8a038e0f706eda55a19',
'soldshrink.ASE': 'bd79795a878557cd979a97719653aa669130ad778e922f0b78aa2160eddeb59f',
'soldatak.ASE': 'b759a087dc5ab6621e8b9745b5e62bf24b2f131b6bd0e509f2f5392d94d496a1',
}
def timer_step(timer: float, delta: float, shrunk: bool = True) -> tuple[float, bool, bool]:
"""Bounded control-flow projection, not original x87/runtime emulation.
Deliberately retains the source's equality edge case. The caller supplies
original nonnegative game time; this does not model unrelated AI updates.
"""
if timer > 0:
timer -= delta
if timer < 0:
return 0, False, True
return timer, shrunk, False
def collect(root: Path) -> dict:
modules = {name: PE(find_case(root, name)) for name in ('Neutron.exe', 'OMT2.dll')}
identities = {name: hashlib.sha256(pe.data).hexdigest() for name, pe in modules.items()}
bodies, sites, vtables = [], [], []
for module, name, start, end, expected in BODIES:
pe = modules[module]
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
bodies.append(dict(module=module, name=name, va=hex(start), end_exclusive=hex(end),
file_offset=hex(pe.offset(start-pe.base)), sha256=actual, matches=actual == expected))
for module, name, va, expected in SITES:
pe = modules[module]
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
sites.append(dict(module=module, name=name, va=hex(va),
file_offset=hex(pe.offset(va-pe.base)), bytes=actual, matches=actual == expected))
pe = modules['Neutron.exe']
for name, table, slot, expected in VTABLES:
target = struct.unpack('<I', read_va(pe, table+slot, 4))[0]
vtables.append(dict(name=name, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base)), matches=target == expected))
strings = []
for va, expected in STRINGS.items():
actual = pe.cstr(pe.offset(va-pe.base))
strings.append(dict(va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
value=actual, matches=actual == expected))
clips = []
for name, expected in ASSETS.items():
path = find_case(root, 'ASE/'+name)
asset = read_ase(path)
samples = [sample for obj in asset['objects'] for sample in obj['samples']]
clips.append(dict(name=path.name, sha256=asset['sha256'], matches=asset['sha256'] == expected,
frames_per_second=asset['framesPerSecond'], ticks_per_frame=asset['ticksPerFrame'],
sample_count=len(samples), vertex_counts=[len(s['vertices']) for s in samples],
face_counts=[len(s['faces']) for s in samples], times=[s['time'] for s in samples],
y_bounds=[[min(v[1] for v in s['vertices']), max(v[1] for v in s['vertices'])] for s in samples]))
textures = []
for name in ('vryoksoldier.png', 'yoksold.png', 'yoksoldtalk.png'):
path = find_case(root, 'png/'+name)
textures.append(dict(name=path.name, sha256=hashlib.sha256(path.read_bytes()).hexdigest()))
level_path = find_case(root, 'gam/VR04.gam')
level_data = level_path.read_bytes()
targets = [dict(kind=e.kind, file_offset=hex(e.offset), fields=e.values())
for e in gam.parse(level_data).entities if e.kind == '3SOL']
return dict(scope='Static source and original asset data only; no original runtime execution.',
modules=identities, known_binary=identities == {'Neutron.exe': EXE_SHA256, 'OMT2.dll': DLL_SHA256},
bodies=bodies, sites=sites, vtables=vtables, strings=strings, clips=clips, textures=textures,
radius=90, factor=1,
modes=dict(current_complete='0x6c8', previous_complete='0x6cc',
authored_complete='0x93c', authored_interface='0x87c',
authored_property='AIState', initial_authored=2,
shrink_snapshots_authored=False, expiry_restores='authored'),
vr04=dict(sha256=hashlib.sha256(level_data).hexdigest(), targets=targets))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
args = parser.parse_args()
result = collect(args.original)
print(json.dumps(result, indent=2, allow_nan=False))
guards = result['bodies'] + result['sites'] + result['vtables'] + result['strings'] + result['clips']
if not result['known_binary'] or not all(item['matches'] for item in guards):
raise SystemExit(1)
if __name__ == '__main__':
main()
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Export original gadget-screen canvases; resource identity is not gameplay policy."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
from pathlib import Path
from omt import Database, FormatError, read_canvas, validate_output, write_png
@dataclass(frozen=True)
class CanvasSpec:
id: int
name: str
width: int
height: int
role: str
TILE_LABELS = ('BUBBLE', 'ROCKETSHIP', 'INVISIBLE', 'SHRINK RAY',
'SCOOTER', 'REMOTE', 'BASEBALL', 'GRAPPLER')
TILE_IDS = tuple(range(11, 19))
TILE_B_IDS = (52, 46, 47, 48, 49, 50, 51, 45)
TILE_C_IDS = (178, 171, 172, 173, 174, 175, 176, 177)
def specifications() -> tuple[CanvasSpec, ...]:
specs = [CanvasSpec(20, 'menu', 640, 480, 'background')]
for index, (plain, alternate_b, alternate_c) in enumerate(zip(TILE_IDS, TILE_B_IDS, TILE_C_IDS), 1):
for identity, suffix in ((plain, ''), (alternate_b, 'b'), (alternate_c, 'c')):
specs.append(CanvasSpec(identity, f'item{index:02d}{suffix}', 141, 141, f'tile{suffix}'))
for identity, name in ((109, 'Bubble'), (110, 'Grappler'), (111, 'Invisible'),
(112, 'JetPack'), (113, 'RayGun'), (114, 'Remote'),
(115, 'Rocketship'), (116, 'Scooter'), (118, 'Baseball')):
specs.append(CanvasSpec(identity, 'BmenuL'+name, 393, 69, 'controls-left'))
for identity, name in ((108, 'BmenuR2'), (117, 'BmenuR1')):
specs.append(CanvasSpec(identity, name, 247, 69, 'controls-right'))
for identity, name in ((24, 'return'), (181, 'return2'), (182, 'return3'),
(170, 'practice'), (179, 'practice2'), (180, 'practice3')):
specs.append(CanvasSpec(identity, name, 141, 78, 'button'))
for identity, name in ((94, '1bubble'), (87, '2rocket'), (88, '3invisible'),
(89, '4raygun'), (90, '5scooter'), (91, '6remote'),
(92, '7baseball'), (93, '8grappler'), (119, '9jetpack')):
specs.append(CanvasSpec(identity, name, 80, 70, 'hud'))
for identity, name in ((84, 'backpack'), (85, 'backpack2')):
specs.append(CanvasSpec(identity, name, 141, 141, 'backpack'))
specs.append(CanvasSpec(253, 'CrossHairs', 15, 210, 'crosshairs-strip'))
return tuple(specs)
CANVASES = specifications()
def export_gadget_resources(database: Database, output: Path) -> dict:
"""Copy exact decoded pixels and metadata to a separate generated directory.
Tile roles preserve original resource suffixes. Which suffix means selected,
hovered, unavailable or enabled must come from the original dispatcher.
"""
validate_output(database, output)
# Supplied archives live beneath Original/omt. Protect that entire source
# tree, including sibling ASE/png/gam directories, rather than only omt/.
source_directory = database.path.parent.resolve()
source_root = source_directory.parent if source_directory.name.casefold() == 'omt' else source_directory
if output.resolve().is_relative_to(source_root):
raise ValueError('Gadget output must be separate from the source asset tree')
entries = {entry.id: entry for entry in database.entries if entry.type == 'Canv'}
recovered = []
for spec in CANVASES:
entry = entries.get(spec.id)
if entry is None or entry.name != spec.name:
raise FormatError(f'Missing or changed gadget canvas {spec.id}:{spec.name}')
canvas = read_canvas(database.payload(entry))
if (canvas['width'], canvas['height']) != (spec.width, spec.height):
raise FormatError(f'Unexpected gadget canvas dimensions {spec.id}')
recovered.append((spec, entry, canvas))
output.mkdir(parents=True, exist_ok=True)
textures = []
for spec, entry, canvas in recovered:
name = f'canvas_{spec.id}'
rgba = canvas['rgba']
(output/(name+'.rgba')).write_bytes(rgba)
write_png(output/(name+'.png'), spec.width, spec.height, rgba)
textures.append(dict(id=spec.id, name=entry.name, role=spec.role,
width=spec.width, height=spec.height, path=name+'.rgba', png=name+'.png',
sourceOffset=entry.offset, sourceBytes=entry.size,
sourceSha256=hashlib.sha256(database.payload(entry)).hexdigest(),
rgbaSha256=hashlib.sha256(rgba).hexdigest()))
manifest = dict(schema=1, source=database.path.name,
sourceSha256=hashlib.sha256(database.data).hexdigest(),
referenceWidth=640, referenceHeight=480, textures=textures,
tiles=[dict(artItem=index+1, label=TILE_LABELS[index], canvas=plain,
alternateB=alternate_b, alternateC=alternate_c)
for index, (plain, alternate_b, alternate_c) in enumerate(zip(TILE_IDS, TILE_B_IDS, TILE_C_IDS))])
(output/'gadgets.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)
args = parser.parse_args()
manifest = export_gadget_resources(Database(args.database), args.output)
print(f"{len(manifest['textures'])} original gadget canvases exported to {args.output}")
if __name__ == '__main__':
main()
+7 -1
View File
@@ -10,6 +10,7 @@ from png import read_png
from entities import prepare_entities from entities import prepare_entities
from models import prepare_models from models import prepare_models
from ui import export_ui from ui import export_ui
from gadget_resources import export_gadget_resources
from sound_bank import export_sound_bank from sound_bank import export_sound_bank
@@ -48,7 +49,7 @@ def main():
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('--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', 'jimtalk', 'jimfly']) parser.add_argument('--animations', nargs='*', default=['jimstop', 'jimrun', 'jimjump', 'jimscratch', 'jimbackpedal', 'jimfall', 'jimtalk', 'jimfly', 'jimshoot'])
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')
@@ -78,6 +79,7 @@ def main():
catalog['prepared'].append({'level': name+'.gam', 'archive': source.name, 'scene': source.stem+'/scene.json'}) 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') (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')) export_ui(Database(find_archive(args.original, 'screens')), args.output / 'ui', Database(args.original / 'alpha.omt'))
export_gadget_resources(Database(find_archive(args.original, 'screens')), args.output / 'gadgets')
effects = export_sound_bank(args.original, args.output / 'effects') effects = export_sound_bank(args.original, args.output / 'effects')
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities") print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
for name in args.audio: for name in args.audio:
@@ -109,6 +111,10 @@ def main():
prepare_actor(args.original, args.output, 'trophy', 'trophy.png', {'STOP': 'trophy'}) prepare_actor(args.original, args.output, 'trophy', 'trophy.png', {'STOP': 'trophy'})
# C3DJetpackFire421F30..96: DEFAULT fire.ase, HINONE fire2.ase, fire.png. # C3DJetpackFire421F30..96: DEFAULT fire.ase, HINONE fire2.ase, fire.png.
prepare_actor(args.original, args.output, 'jetpack', 'fire.png', {'DEFAULT': 'fire', 'NONE': 'fire2'}, 'fire') prepare_actor(args.original, args.output, 'jetpack', 'fire.png', {'DEFAULT': 'fire', 'NONE': 'fire2'}, 'fire')
#Recovered C3DShrinkRay440000 and3SOL44C0B0 bindings; see docs/gameplay/.
prepare_actor(args.original, args.output, 'shrink-ray', 'ray0000.png', {'RAY': 'ray'})
prepare_actor(args.original, args.output, 'soldier', 'yoksold.png', {'WALK': 'soldwalk', 'SHRINK': 'soldshrink'}, 'soldatak')
prepare_actor(args.original, args.output, 'soldier-vr', 'vryoksoldier.png', {'WALK': 'soldwalk', 'SHRINK': 'soldshrink'}, 'soldatak')
if __name__ == '__main__': main() if __name__ == '__main__': main()