From d6ca417e9ef71a6e20450e8ae8b9fb0d0d316285 Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Mon, 2 Nov 2026 22:54:19 -0500 Subject: [PATCH] Implement Baseball aiming, pooled projectiles and VR07 targets --- AGENTS.md | 6 +- README.md | 11 +- docs/architecture.md | 10 + docs/compatibility.md | 13 ++ docs/debug-menu.md | 3 + docs/decisions.md | 12 ++ docs/gameplay/baseball-assets.md | 145 +++++++++++++ docs/gameplay/baseball-font.md | 114 ++++++++++ docs/gameplay/baseball-implementation.md | 88 ++++++++ docs/gameplay/baseball-review.md | 81 +++++++ docs/gameplay/baseball-targets.md | 98 +++++++++ docs/gameplay/baseball.md | 144 +++++++++++++ docs/gameplay/gadget-assets.md | 5 +- docs/gameplay/scooter.md | 204 ++++++++++++++++++ docs/gameplay/vehicle-assets.md | 97 +++++++++ docs/progress.md | 32 +++ docs/tasks.md | 15 +- scripts/package.sh | 8 + scripts/test.sh | 4 + .../Application/BaseballAimOverlay.cs | 76 +++++++ src/GamePort/Application/BaseballSmoke.cs | 72 +++++++ src/GamePort/Application/BaseballVisuals.cs | 125 +++++++++++ src/GamePort/Application/DebugMenu.cs | 13 +- .../Application/SceneSpriteVisuals.cs | 2 +- src/GamePort/Game/BaseballGadget.cs | 138 ++++++++++++ src/GamePort/Game/LabSimulation.cs | 13 +- src/GamePort/Game/OriginalBodyPhysics.cs | 36 +++- src/GamePort/Game/OriginalCameraRay.cs | 2 +- src/GamePort/Game/OriginalStaticCollision.cs | 2 +- src/GamePort/Game/PlayerSceneBinding.cs | 11 +- src/GamePort/Game/SceneBaseballs.cs | 149 +++++++++++++ src/GamePort/Game/SceneInteractions.cs | 3 +- src/GamePort/Program.cs | 66 +++++- .../GamePort.BaseballTests.csproj | 6 + tests/GamePort.BaseballTests/Program.cs | 141 ++++++++++++ .../GamePort.BaseballVisualTests.csproj | 11 + tests/GamePort.BaseballVisualTests/Program.cs | 153 +++++++++++++ .../GamePort.InteractionTests.csproj | 1 + .../GamePort.PatrolTests.csproj | 1 + tests/test_baseball.py | 61 ++++++ tests/test_baseball_resources.py | 94 ++++++++ tests/test_baseball_targets.py | 33 +++ tests/test_scooter.py | 90 ++++++++ tests/test_scooter_resources.py | 98 +++++++++ tools/binary/baseball.py | 187 ++++++++++++++++ tools/binary/baseball_targets.py | 79 +++++++ tools/binary/scooter.py | 199 +++++++++++++++++ tools/extractors/baseball_resources.py | 127 +++++++++++ tools/extractors/prepare.py | 2 + tools/extractors/scooter_resources.py | 100 +++++++++ 50 files changed, 3149 insertions(+), 32 deletions(-) create mode 100644 docs/gameplay/baseball-assets.md create mode 100644 docs/gameplay/baseball-font.md create mode 100644 docs/gameplay/baseball-implementation.md create mode 100644 docs/gameplay/baseball-review.md create mode 100644 docs/gameplay/baseball-targets.md create mode 100644 docs/gameplay/baseball.md create mode 100644 docs/gameplay/scooter.md create mode 100644 docs/gameplay/vehicle-assets.md create mode 100644 src/GamePort/Application/BaseballAimOverlay.cs create mode 100644 src/GamePort/Application/BaseballSmoke.cs create mode 100644 src/GamePort/Application/BaseballVisuals.cs create mode 100644 src/GamePort/Game/BaseballGadget.cs create mode 100644 src/GamePort/Game/SceneBaseballs.cs create mode 100644 tests/GamePort.BaseballTests/GamePort.BaseballTests.csproj create mode 100644 tests/GamePort.BaseballTests/Program.cs create mode 100644 tests/GamePort.BaseballVisualTests/GamePort.BaseballVisualTests.csproj create mode 100644 tests/GamePort.BaseballVisualTests/Program.cs create mode 100644 tests/test_baseball.py create mode 100644 tests/test_baseball_resources.py create mode 100644 tests/test_baseball_targets.py create mode 100644 tests/test_scooter.py create mode 100644 tests/test_scooter_resources.py create mode 100644 tools/binary/baseball.py create mode 100644 tools/binary/baseball_targets.py create mode 100644 tools/binary/scooter.py create mode 100644 tools/extractors/baseball_resources.py create mode 100644 tools/extractors/scooter_resources.py diff --git a/AGENTS.md b/AGENTS.md index 9125a1c..5c58aeb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,7 +46,11 @@ changes. Current gadget controls/resources/primary-fire findings belong in 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. -Latest continuation: docs/gameplay/bubble-implementation.md. Bubble's mode2, +Latest continuation: docs/gameplay/baseball-implementation.md. Baseball's20-slot +pool, hold/release aiming, original TIME art and boundedVR07 moving targets are +implemented; original dynamic pair discovery/other enemy consumers remain open. +Scooter recovery is saved in docs/gameplay/scooter.md; do not invent wheel supports. +Bubble's mode2, original sprite and boundedVR01 source body/floor state are implemented and tested; Invisible, ray/jetpack and shared energy state remain integrated. Other gadgets and broader collision/camera/retained-helper behavior remain separate gates. diff --git a/README.md b/README.md index eecfd42..f329bd1 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,11 @@ 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 and the bounded VR01 Bubble tutorial now use recovered static body response/support/friction with original-code +VR04 and the bounded VR01/VR07 tutorials use recovered static body response/support/friction with original-code numeric references. Lab/outside retain the capsule until special contacts and dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md). -**Current milestone: Bubble, Invisible, shrink ray and their gadget screen.** +**Current milestone: Baseball, Bubble, Invisible, shrink ray and their gadget screen.** 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. Invisible uses the recovered recharge, @@ -32,6 +32,8 @@ The [Invisible continuation](docs/gameplay/invisible-implementation.md) records the later implementation and shared energy-warning sounds. The [Bubble continuation](docs/gameplay/bubble-implementation.md) adds its source controller, original sprite, automatic/high bounces and VR01 floor behavior. +The [Baseball continuation](docs/gameplay/baseball-implementation.md) adds hold/ +release aiming, original ball/TIME art and VR07's moving targets and trophy gate. The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and @@ -80,6 +82,11 @@ F1→Player can also Give/Select Bubble. **Up or primary fire** accelerates, arr steer, and holding jump makes higher bounces. Tab/Space first unequips it; the original sprite fades afterward. VR01 uses source body/floor rules; lab/outside collision remains provisional. +F1→Player also has **Give/Select Baseball**. Hold **Enter/Ctrl/left mouse** to +aim, use **Up/Down** to change elevation and **Left/Right** to turn, then release +fire to throw. Practice on its owned tile opens VR07. The twenty-ball pool, +target respawn and original aim display are implemented; full enemy combat and +original dynamic contact scheduling remain incomplete. **F2** toggles a compact live debug overlay without pausing play. It shows frame timing, position/velocity, movement, control/force state, tasks, camera/clipping diff --git a/docs/architecture.md b/docs/architecture.md index 57ce627..77ba4bb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,6 +5,16 @@ SDL3 for platform windowing, input and audio. Linux x64 and Windows x64 are equally required. Source is `src/GamePort/`; root executable csproj allows `dotnet build` and `dotnet run` from GamePort. No runtime network dependencies. +`BaseballGadget` keeps pending/saved/displayed aim, camera adjustments and20 owned +`BaseballProjectile` entries distinct from equipped raw mode. Cleanup hides its +UI/restores the companion but retains the latch and flying balls. `SceneBaseballs` +steps bodies before controller input and target frame state afterward; six duplicate +3TAR tags retain source-instance identities. The source body has an explicit ball +profile for delayed landing impulse, prevent-lowering=false and reflection/friction. +Sphere-pair discovery remains a declared bounded adapter. `BaseballVisuals` and +`BaseballAimOverlay` append source Canv2/253 and TIME16-pixel glyphs using the +existing world/overlay pipelines and uniform viewport. See baseball-implementation.md. + Bubble adds separate `BubbleMotion` input/apply, `BubbleEffect` owned clock and `BubbleVisuals` original canvas. LabSimulation keeps body factor, current maximum, movement mode and captured sprite root distinct. The source static factory also diff --git a/docs/compatibility.md b/docs/compatibility.md index 4b6a6f3..7ec7572 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -3,6 +3,19 @@ Compilation, native runtime, original behavior and full feature completion are separate evidence categories. **The game is not fully reconstructed/playable yet.** +Baseball (2026-11-02): source hold/release/20-slot pool, exact ball/aim/TIME art, +bounded ball body, VR07 moving-target callbacks and F1 grant are implemented. +12 managed/6 visual/16 Baseball Python groups and independent review pass. +Native Linux GTX1070/private Xvfb1920×1080 passes real SDL Ctrl/Left/Up/Tab, +all eight render phases, actual target hit/respawn and zero enabled Vulkan +validation errors. Its1010 extra ordinary player/target ticks are an accelerated +port fixture. Sphere contact discovery, angular wall response, full enemy combat, +retained helper lifetime and original/native Windows comparisons remain open. +Complete regression passes232 Python+2 HUD, all managed suites,32 GPU runs and +17 material checks;539 originals verify. Package status is in progress.md; gameplay/baseball-implementation.md +records the coverage map. Scooter's recovered wheel/control dependencies are +documented but not implemented as invented Jimmy movement. + Bubble (2026-11-02): original mode2 controller, sprite/flags/pulse/fade, controlled drain, loop/boing ownership, cleanup650 and boundedVR01 source body/floor111 are integrated. Six isolated copied-original body references match managed output. diff --git a/docs/debug-menu.md b/docs/debug-menu.md index 5c42de7..fc664a9 100644 --- a/docs/debug-menu.md +++ b/docs/debug-menu.md @@ -35,6 +35,9 @@ energy/recharge gates; a grant is not instant activation. The header shows remaining time, recharge and targetability. Full enemy sensing is not implied. Give/Select Bubble uses the implemented mode2 controller, while Unequip starts its original fade. Diagnostics show Bubble phase and source radius/factor. +Give/Select Baseball grants item6 and shows aim/pending/throw diagnostics. Hold +primary fire and use Up/Down to aim; release to throw. Cleanup preserves its +source pending latch and existing flying balls. See gameplay/baseball-implementation.md. State0 means unowned,1 enabled and4 disabled by the level. The full availability action re-enables the matching VR practice gadget and applies LV1B restrictions on gadgets1/7 after the common prefix. Other level-specific tails remain incomplete. These controls expose diff --git a/docs/decisions.md b/docs/decisions.md index eb8a379..c578c49 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -219,3 +219,15 @@ not invented sphere geometry. Keep the render bridge, generic camera/Euler, other damage states and retained helper lifetime explicit. Bubble practice precedes live equip; menu gating reads raw mode, not display selection. +39. **Keep Baseball ownership beyond selection.** Preserve the original20-slot + ring, pending release after cleanup, prior-capture label and source release + cost/sound order. Landing queues a full impulse before support clears Y; + use a ball-specific profile rather than Jimmy callbacks. VR07 target state + belongs to source instances despite duplicate tags, with strict parent hit + threshold and conditional collision activation. Exact TIME glyph binding + replaces the temporary font policy. Keep current sphere-pair discovery, + angular reflection, mouse/analog aim and helper retention across loads explicit. +40. **Save Scooter recovery before implementing it.** Its separate C3DJEEP actor, + mount/control handoff and wheel-dependent drive/support cannot be represented + by a Jimmy mode or an invented constant wheel count. Preserve the source + report/exporter and close wheel bodies before live Scooter integration. diff --git a/docs/gameplay/baseball-assets.md b/docs/gameplay/baseball-assets.md new file mode 100644 index 0000000..3e0b602 --- /dev/null +++ b/docs/gameplay/baseball-assets.md @@ -0,0 +1,145 @@ +# Baseball original resources and VR07 fixture + +2026-11-02. Original serialized resources and decoded pixels were read locally; +originals were not modified or executed. Binary activation/projectile/target +behavior belongs to the separate Baseball contract investigation. This report +records asset identity and a resource interface suitable for integration. + +`tools/extractors/baseball_resources.py` exposes `export_baseball(original, output)` +and writes schema1 `baseball.json`. It preserves five exact canvases from +RetainedSprites.omt and the authored VR07 start/target/intro properties, including +every property source offset/raw bytes and duplicate target tags. It rejects +original subtree/ancestor outputs and existing descendant symlinks, checks both +archive and GAM identities before writing, and guards dimensions/pixel hashes. + +```bash +python3 tools/extractors/baseball_resources.py ../Original --output artifacts/vehicle-assets/baseball +python3 -m unittest discover -s tests -p test_baseball_resources.py -v +``` + +Six regression checks pass: exact RGBA/PNG/provenance, original aim/glyph pixels, +six distinct target +records with authored property bytes, protected output paths, changed decoded +pixels and changed archive identity. Local output and test log are +`artifacts/vehicle-assets/baseball/` and `artifacts/vehicle-assets/baseball-tests.log`. +No shared prepare/runtime/build files were changed by this investigator. + +## Port visual implementation and tested limits + +`Application/BaseballVisuals.cs` appends20 hidden world alpha quads to a supplied +Mesh, preserving its collision metadata and existing draws/textures. `Update` +uses the caller's pool visibility/position, exact Canv2 and25×25 world dimensions. +It does not animate frames2..5 or invent a lifetime. Camera-facing centered +billboard orientation is a declared modern policy pending exact inherited sprite +render recovery. Degenerate straight-up/down cameras use a finite orthonormal +basis. Resource paths are bounded to the prepared Baseball directory, input +size/depth/dimensions and exact original pixel hashes are validated. + +`Application/BaseballAimOverlay.cs` uses exact screens.omt Canv253 CrossHairs +15×210 pixels, SHA256 +`2e16e11b151c8474ba68fd5017d1a3a6304a594a7f34c3b423f3417c7edfb453`. +The complete strip stays stationary at logical(315,100), without frame cropping. +Visibility follows AimVisible; text reads the separate prior-capture DisplayPitch, +not the newly captured SavedPitch. Source numeric position is +`y=trunc((45-DisplayPitch)*4.3+100)`, source text anchorx286, with positive-space +plus two zero-padded decimal digits from `% .2d`. + +The subsequent [TIME font recovery](baseball-font.md) closes that binding: +set5 digits use alpha.omt118,127,120..126,119, all16×16. A null positive-space +glyph has zero advance; visible digits begin286 and302. Exact green pixels are +preserved with white vertex tint. Runtime/exporter/tests now use that source +mapping; the temporary SMAL policy is superseded. +The exporter writes these plus the source strip into `aimTextures`, each with +its source database key, byte range and decoded hash. `aimArchiveSha256` guards +screens.omt and alpha.omt. Source table, formatting and advance Evidence is in +baseball-font.md. + +UiViewport retains uniform scale and centered640×480 placement at widescreen +and portrait sizes. Screen/world quads use alpha blending with unmodified source +texture alpha. Six standalone checks pass in +`artifacts/vehicle-assets/baseball-visual-tests.log`:20-slot/pixel/source metadata, +billboard bounds/camera degeneracies, stationary aim/number/selected glyphs, +widescreen and portrait scaling, combined world/overlay isolation and rejection +of altered pixels/dimensions/path traversal. Invocation: + +```bash +source scripts/env.sh +dotnet run --project tests/GamePort.BaseballVisualTests +``` + +These are compiled port-side deterministic mesh/pixel checks. They do not verify +a displayed Vulkan frame, original source execution or native Windows behavior. + +## Projectile and retained target artwork + +Archive `omt/RetainedSprites.omt` SHA256 +`b584ffa4a38f4bc809b3ea8f4321e0c08f2719e22df41a3fb4cd143ed89b3bef`. +This archive contains Canv resources, not 3D shapes. + +| Canv / name | Offset / bytes | Dimensions | Decoded RGBA SHA256 | +| --- | --- | --- | --- | +|2 ball0000|72372 /3786|32×32|`68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9`| +|3 ball0001|68582 /3790|32×32|`005def070e18111fbdb067e75285dad8ec677c1608020f55c3db7a4b9745205c`| +|4 ball0002|64788 /3794|32×32|`c368a59d5d7a57824c1c6b56b617cf058f5d5d53e18e5e48989710413490c536`| +|5 ball0003|58830 /3794|32×32|`e5da21c359d3215759e5c3c238107f526f7109203c0ff9fa391a3c8bc40c17ed`| +|8 target|48796 /10034|64×64|`8d31014cb9b9661ebed902c864bf740f562460e74da3f6b86ed3d2be4d10f0ec`| + +Manifest `textures` records id/name/width/height/path/png/sourceOffset/sourceBytes/ +sourceSha256/rgbaSha256. `ballCanvasIds` lists source IDs2..5 in source-number +order, without assigning animation cadence. `retainedTargetCanvasId:8` names +the literal retained artwork only; it is not the six VR07 target actors' artwork. +Pixels are neither recolored nor resized. The source target8 image visibly has +a four-corner frame/cross pattern; inspected original pixels are available as +`artifacts/vehicle-assets/retained_8.png`. + +The contract investigator corrected an early interpretation of constructor40FC50: +its complete57C=25 is the inherited sprite dimension, complete580=2 the initial +canvas ID, and complete5F8..604 retain IDs2..5. It is not shape25. Exact REA +Evidence, frame selection, billboarding, size and render-state policy belong in +that investigator's source report; this exporter embeds no unverified cadence. + +## Actual VR07 target visuals + +All six authored `3TAR` records explicitly serialize `SpriteDatabase=sprites.omt`, +`SpriteIndex=135`, `SpriteSize=150`. The source resource is Canv135 **star**, +128×128 at offset2750568/35394 bytes. It is a pale purple jagged starburst with +8,016 alpha255 and8,368 alpha0 pixels. Exact RGBA SHA256: +`42bbea6c33fc2889cad0cd659af2274f936be10643254af233779c44f1e41e07`. +Archive SHA256: +`c8e016ea73e6104b9b672139b1d0b0ac83afc4feff6cc744a7fa4f6ba919e2a2`. +Inspected pixels: `artifacts/vehicle-assets/sprites_135.png`. + +The existing `prepare_entities` exporter already follows this explicit sprite +database/index and can supply the exact texture; no duplicate sprite export is +necessary. Primary independently traced actual factory45CA06 to430220, inheriting +the sprite base441980; it is distinct from the Jimmy-owned retained target actor +and from the other class constructor4453B0 sharing a FourCC. That factory/default +recovery is separate from the serialized values verified here. The integration +must establish that the source loader respects the serialized overrides before +claiming runtime target appearance parity. + +## Authored tutorial instances + +VR07.gam SHA256 +`1260b75d82ec794f9375ada30e186424746bc1dd4e4b0540c9b69bb7ad12d0b1`. +Six target offsets are0x885,0xAD6,0xD27,0xF78,0x11C9,0x141C. Every target uses +the same tag `C3DMOVINGTARGET`; identify instances by source offset/ordinal. +All serialize Speed100, HitsRequired3, NumPoints10, RespawnTime15 and +ActivateObject=`none`. These are data values, not reconstructed hit/motion rules. + +| Offsets | Authored start | Authored destination | +| --- | --- | --- | +|885,AD6,D27|(-755,188,277)|(815,188,277)| +|F78,11C9,141C|(815,333,1520)|(-755,333,1520)| + +Do not silently replace each instance's serialized Position with StartPos; both +are retained in the manifest. Constructor/postload/frame behavior determines how +these fields interact. PHONEBOOTH is STRT0x48C, authored position +(7.5705023,216.7101440,-1525.1119385), yaw0, StartTrigger=`bb1`. +Intro3MCA0x1892 serializes PlayerControlled=`NULL`, DeactivateInv1, +NextTrigger=`default` and source voicepractice IDs36,19,35,33,34. + +This fixture has authored visuals sufficient for projectile and six target +rendering using the current sprite infrastructure. Source targeting, motion, +contacts, inventory/intro state, score, respawn and original/native Windows +execution comparison remain independent implementation/verification gates. diff --git a/docs/gameplay/baseball-font.md b/docs/gameplay/baseball-font.md new file mode 100644 index 0000000..13ba994 --- /dev/null +++ b/docs/gameplay/baseball-font.md @@ -0,0 +1,114 @@ +# Baseball TIME font closure + +2026-11-02. Static original-binary and asset recovery. No original executable was +run or original file modified. This closes the font resource/advance/tint +questions, not displayed original pixel alignment or general renderer parity. +Primary owns the exporter and runtime changes; this investigation edits only this +report and generated `artifacts/baseball-font/`. + +## Recommended integration + +Replace the temporary SMAL digits with TIME set5's original **16×16** alpha.omt +canvases. Decimal0..9 maps to **118,127,120,121,122,123,124,125,126,119**. +The format is `% .2d`, but TIME's leading positive space maps to a null glyph +and has **zero advance**. For the current declared logical overlay rectangles, +draw the visible digits at **x286 and302**, width/height16, and the existing +source y formula. Do not add an8- or16-unit leading-space advance. + +Retain the exact source RGBA with white vertex tint. All ten glyphs have opaque +RGB **(17,255,73)** and alpha0/255; preserve these green pixels without recoloring. +The leaf sets material RGB=(1,1,1), alpha from global4F4ED4 (initially1), and blend +enums from4F4ECC/4F4ED0 (initial6/7). The text function resets that alpha global +to1 after ordinary text. The Baseball caller does not supply an additional tint. +Exact shared-alpha scheduling across all possible text callers is outside this +bounded recovery; ordinary opaque glyph material alpha1 is the evidenced default. + +## REA Evidence and supporting bytes + +REA analyzed the existing generated copy +`artifacts/uncontrolled-phases/rea/Neutron.exe`, SHA256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Ghidra12.1.4 returned all four requested routines. Complete replies, exported +Evidence and the closed snapshot are in `artifacts/baseball-font/rea-local/`. + +| Routine | REA Evidence | +| --- | --- | +|4683E0 font initialization|`ev_f5dd8e211882ec340474745de486b4d431a981816a512773fd57a51cb6bfa1bc`| +|468660 formatted text/layout|`ev_e20b6c0cc47aa285935609ad63ea77cf92d9d23b3ca18fe52c7dd6fc286f2308`| +|4689F0 glyph emission|`ev_8a5c0ce796b76993a6e86e19a1d2a36fb1945f1a23c6416ad446213e1e0e043c`| +|468B80 font/character selection|`ev_bd91c2e5548e4e627af7f3faf7e8d5f2a70fa830bff9c3a5bbcbeb55c545e5d9`| + +The first sandboxed attempt failed when Ghidra's local Unix socket bind returned +Operation not permitted. The task's owned failed batch was interrupted and its +session closed; its complete failure replies remain in `rea/`. The approved +local static run resolved that host IPC restriction without configuration edits. +This was not a source-execution observation. Both owned sessions are closed. + +`font-assembly.txt` and `aim-call-assembly.txt` cross-check the same generated +EXE's instructions. `source-spans.json` records original VAs/file offsets/lengths/ +SHA256 for the four functions, bounded Baseball call and font table. Ghidra's +468660 prototype loses its variadic arguments, and4689F0 reports a spurious +unaff_retaddr parameter. Argument and x-advance facts below therefore come from +checked instructions, not literal translation of those pseudocode signatures. +The four code entries map to file offsets683E0,68660,689F0,68B80; the font +table maps toF4ED8. `tools/binary/baseball.py` also guards/exports the table hash, +TIME digit IDs and null-space mapping so this binding remains reproducible. + +## Table and glyph identity + +4683E0 loads alpha.omt via string4F51D8, then at46844A..46849F walks six groups +of64 signed16-bit table entries startingVA4F4ED8. Index−1 stores a null pointer; +all other IDs are looked up through477890. Runtime pointer table is5091E0. +468B80 uppercases the character, admits ASCII32..95, and selects TIME +`54494D45`→set5 at468C23; SMAL `534D414C` instead selects set1 at468C39. +Runtime index is `font*64+uppercase(character)-32`. The set5 table starts4F5158; +digit0's word is4F5178. The768 source table bytes have SHA256 +`910bef1d7aca6f1aa328ba9f671831bdbbda19b419fb0c693117cb096d542226`. + +alpha.omt SHA256 +`53cb9f47a588b1f19eb0adc4d43c8066a8b78aedd764b9e9314c81e287991126`. +Every digit below is16×16. `glyphs.json` records exact source resource byte +ranges, RGBA SHA256, alpha counts and opaque RGB. No regenerated substitute font +or scaling of the existing8×8 SMAL images is needed. + +| Character | Canv / name | Source offset / bytes | RGBA SHA256 | +| --- | --- | --- | --- | +|0|118 t1600|74484 /642|`edc60e65dcf7320813a80d4312e3c45951ccfc566ea79dfabf7a22ebc4b96049`| +|1|127 t1601|25406 /466|`1fd058ad5bdc0f8a064ef7d2d52b2b036df3f35515691a366799d7e8aab5297f`| +|2|120 t1602|73236 /450|`62aaeaaf107300a6f4f7ff52e98106c1520a9edbe2137626ee41091cf243e5c5`| +|3|121 t1603|76660 /450|`d78bf1895f5838b9eb8c6a22565a9588dae4fc8f7106697df373f4408aae634c`| +|4|122 t1604|19604 /562|`f6d628639de4e40005f62f63a49308ff9ee0656a36bb6eb7787230b4830a5ed9`| +|5|123 t1605|19154 /450|`9f58cad5621d89b7a7012036daa8532b2397b0d9d267ab7d1aa5a7cd10d7ae87`| +|6|124 t1606|73872 /530|`49cdc9ec812f4ef3826011d542c30afbb10229c4b4ce549e7820233bbaa53dd9`| +|7|125 t1607|17298 /458|`aaef2d59c2636c059b446bed643985ca55d15b2d070b0582b2d8994b3bf74f1e`| +|8|126 t1608|23440 /610|`bade574a4624a3f763ddd9c87fa2f102562b00d8d604e9faf32a43b372de64e0`| +|9|119 t1609|2438 /530|`0a663ddf2df9f1065f5e4ffe27b4d1fa96edd5f19b6323217bad4148f8d2f3d7`| +|space|−1 /null|table word4F5158|no canvas/no advance| +|minus|−1 /null|table word4F5172|no canvas/no advance| + +## Formatting, advance and material facts + +Baseball426754..42678D truncates the previously captured1D68 pitch to an integer, +pushes format string4EF440 (`25 20 2e 32 64 00`, `% .2d`), fontTIME, computed y +andx286 into468660. Y is `trunc((45-priorPitch)*4.3+100)`, with45 as source +float49D5C8 and4.3/100 as doubles4A3E40/4A3130. This occurs before4268A3..8A9 +captures current camera pitch into1D68, supporting the separate DisplayPitch. + +468660 formats into its local buffer and iterates characters.46891A gets the +glyph pointer,468931 calls the glyph emitter, and468939 tests that pointer. +For null pointers46893B jumps directly to46894C, skipping the x addition. +For non-null pointers46893D..468948 advances by `canvas.width*screenWidth/640`. +Therefore TIME space and minus are absent and zero-width. Every available digit +advances16 logical units; there is no kerning or extra letter spacing in this +path. A format result ` 09` draws0 and9 consecutively with no leading gap. +Pitch is clamped0..45 in the sustained-hold path, so a negative-number glyph is +not required for this bounded Baseball label. + +4689F0 rejects null glyphs immediately at4689F8..4689FA and allocates no slot. +For a real glyph it binds the source canvas, sets custom width/height from its +pixel dimensions scaled byscreenWidth/640 andscreenHeight/480, alignment fields +BC=1/C0=2, source blend globals, white RGB at468AFE/468B08/468B0F and alpha from +4F4ED4 at468B17. 4689BF resets global alpha to1 after ordinary formatted text. +This closes the resource sizes, per-glyph step and material tint. General sprite +alignment caches, original frame scheduling, fixed-function alpha tests and +widescreen policy remain renderer boundaries rather than font-table gaps. diff --git a/docs/gameplay/baseball-implementation.md b/docs/gameplay/baseball-implementation.md new file mode 100644 index 0000000..b59021a --- /dev/null +++ b/docs/gameplay/baseball-implementation.md @@ -0,0 +1,88 @@ +# Baseball gameplay integration + +2026-11-02. User-directed gadget continuation after clean1ae5f42/50fcb87 Bubble. +Broad collision investigation remains parked. Scooter's recovered separate vehicle +and wheel dependencies are saved in scooter.md; no invented drive support was added. + +## Coverage map + +| Recovered original | Current implementation | Evidence / remaining boundary | +| --- | --- | --- | +| Item6/raw6 equip without energy gate | Source selection, Goddard hide/body flags, F1 grant | baseball.md; availability and display remain separate from raw mode | +| Hold/first-arm/later capture/release | Supported SHOOT, source Up/Down pitch, Left/Right yaw, first-arm saved value, prior label | Keyboard/primary subset; mouse/analog aim and global suppressor lifecycle remain open | +| complete84C camera scalar and7CC height | Default10, equipped height+30, source eye/target scalar terms, cleanup0/height200 then ordinary reset10 | Existing camera ray/smoothing/Euler/viewport boundaries remain | +| Release even after cleanup/at zero energy | Sound10 before launch, then pending clear and fixed−1 shared energy helper | Twenty owned entries persist independently of raw mode; no invented ammo or TTL | +| Launch local point/vector, speed1800 | Local(0,80,50), aim slope saved/45, quick magnitude, full transform bridge | Upright yaw tested; full source trig/Euler equivalence is unverified | +| Ball radius15/factor1/friction.46 | Explicit source body profile, prevent-lowering=false, delayed full-vector landing impulse, horizontal wall response | Angular reflection tail and general dynamic pairs remain open | +| Ball appearance | Exact RetainedSprites Canv2, source25-square billboard | Other preloaded ball canvases are not animated without a proven cadence | +| Aim strip/text | Exact screens253 at315,100; exact TIME set5 green16-square glyphs at286/302 | Full original sprite alignment/render state remains separate; uniform widescreen policy retained | +| VR07 registration/body | False game filter and bounded static Jimmy/ball body, textureless collision retained | Full material/scene flags and dynamic body interactions remain incomplete | +| Six moving3TAR records | Source-instance identity, source speed/destination/reset-to-start, hidden movement and15-second respawn | Body/controller partial order is implemented; full original registry order remains open | +| Target/parent callbacks |10-point hit, missing-parent198, strict>HitsRequired, parent collision/visibility and199 | Current sphere overlap discovers contacts; other enemies/ball consumers remain unported | +| Cutscene/debug/reset/load | Dedicated unconditional Baseball companion restoration, named-Jimmy cleanup, modern reset clears pool | Original retained helper/pool/latch lifetime across ordinary loads remains unresolved | + +Source addresses/file offsets, fields, guarded bytes, REA Evidence and provider +limits are in [Baseball](baseball.md), [targets](baseball-targets.md), +[resources](baseball-assets.md), [TIME font](baseball-font.md) and +[review](baseball-review.md). All investigations used local generated copies; +originals were neither modified nor executed. Static projections, managed tests, +port GPU/native checks and original gameplay observations are separate categories. + +## Runtime ownership + +LabSimulation owns BaseballGadget, its shared camera scalar/height bridge and20 +projectiles. Input updates camera adjustment before follow, then primary actions +after ordinary steering. Hold clears controller speed, requires support and the +shared energy gate for a new arm/capture, and selects SHOOT. First hold retains +old saved pitch; later hold captures clamped0..45. DisplayPitch stores the value +used before that capture. Release hides the UI and checks pending alone, so cleanup +does not silently cancel a throw. Audio request precedes launch; energy follows it. + +SceneBaseballs owns source moving-target state and the bounded world/pair adapter. +Bodies run before player control; target timers and next velocity run afterward. +Landing sets an impulse from the old live velocity before support zeros Y; the +next body tick consumes it, including X/Z. Pool reuse preserves pending impulse +and support. Unequip retains flying balls. Modern reset/new scene clears the +port-owned pool explicitly; it is not a claim of original retained-loader parity. + +Target activation calls the parent's source428 behavior, not the script trigger +interpreter. VR07's initially hidden trophy cannot be collected before activation. +Its HasCollision property controls pair enable independently of visibility and +integration. Baseball cleanup restores Goddard even in Invisible's six blocked +levels; that policy is covered separately in regressions. + +The shared body remains the ordinary source composition for Jimmy. Ball response +is an explicit profile; allowing ball wall materials does not imply recovered +special Jimmy contacts or lab/outside source-body replacement. Its horizontal +reflection uses the source normal/damping; the angular tail is omitted. Current +target/Jimmy recovery detection uses per-tick sphere overlap, with no claim of +source pair membership, discovery order, swept discovery or full enemy combat. + +## Verification + +Twelve managed groups cover arm/capture/display order, sound/launch/cost ordering, +release after cleanup, twenty-slot reuse, upright launch, queued landing impulse/.46 floor friction, wall reflection, +actual VR07 duplicate identities, target respawn/start reset, cutscene cleanup, +all six companion restoration exceptions, and real target contacts activating +the trophy on the strict fourth hit with HasCollision0/−1. Six visual groups +cover exact pixels, ball dimensions, degenerate camera bases, source aim layout, +widescreen/portrait scaling, combined mesh isolation and bounded resources. +Sixteen Baseball Python groups cover source projections, byte guards and exports. +Scooter source/resource regressions are separate. Independent review findings +were corrected and rerun; see baseball-review.md. + +Headless and native Linux GTX1070/private Xvfb1920×1080 pass all eight rendered +phases: equip, first hold, prior-label/capture, release, flight, actual authored +target hit, unequip retaining the ball, and respawn. Real SDL Ctrl/Left/Up/Tab +arrives; enabled Vulkan validation reports zero errors. The fixture advances1010 +extra ordinary player/body/target ticks between captures, preserving VR07 energy20. +No actor relocation or direct timer/body-state writes are used. This is an +accelerated port fixture, not original cadence/manual tutorial completion. +Aim/flight/hit readbacks are inspected. Logs: artifacts/baseball-implementation/. + +Complete scripts/test.sh passes232 Python+2 HUD, all managed suites,32 main GPU +completions and17 material checks, zero enabled validation errors, SDL dummy +lifecycle and539 unchanged originals. Final focused12-group/16-source-group checks +cover the additional callback numeric assertions and font table guard. Clean package +results are recorded in progress.md when available. Native Windows, whole-original runtime/visual comparison, retained +helper lifetime and complete combat remain open. diff --git a/docs/gameplay/baseball-review.md b/docs/gameplay/baseball-review.md new file mode 100644 index 0000000..ff471d5 --- /dev/null +++ b/docs/gameplay/baseball-review.md @@ -0,0 +1,81 @@ +# Baseball implementation review + +2026-11-02. Independent read-only review of BaseballGadget, SceneBaseballs, +OriginalBodyPhysics, LabSimulation, PlayerSceneBinding and Program wiring. +Source baseline/evidence and provider limitations are in +[baseball.md](baseball.md); no unchanged REA queries were repeated. + +## Resolved findings + +1. **Companion cleanup policy differs by gadget.** The initial implementation + subscribed Baseball.EquippedChanged to InvisibleEquipped, incorrectly skipping + restoration in LEV6/LEV7/LV1C/LV1D/LV4A/LV6A. Source raw6 cleanup42871D..878D + restores Goddard when its pointer exists without Invisible's9E8 skip test + (compare428144). PlayerSceneBinding now uses a dedicated BaseballEquipped + handler with unconditional restoration. A regression verifies all six levels. + +2. **Initially hidden tutorial trophy contact must be disabled.** At review time + SceneBaseballs activated its parent with Active=Visible=true, while + SceneInteractions3TRO contacts used Active regardless of visibility or pair + enable. This permits collecting VR07's initially hidden trophy before earning + it. Primary subsequently added a narrow trophy pair-enable/activation correction + in SceneBaseballs and requires trophy pair enable in SceneInteractions. The + regression exercises real ball/target contacts, strict fourth-hit activation, + and HasCollision0/−1 behavior. It passes. + Do not replace this with a scene Trigger: target430570 calls parent428(1). + +The source alias needed for the second correction is proven: pickup property +reader40D41A passes interface+584 and literal4ED26C=`HasCollision` to3FC, type6. +C3DVRTrophy interface table4BE404 has428→40E1F0. For argument1 it calls +3AC→4730E0→224(true) only when HasCollision is nonzero, then unhides through +complete58(0) when needed. Argument0 calls3A4→473030→224(false), then hides. +It does not enable214 integration, award score or invoke the script interpreter. +These are supplemental reviewed instructions; primary owns adding the exact +guards to baseball_targets.py. They are not attributed to new REA pseudocode. + +## Checked source contracts + +- Equip has no fresh energy gate. Camera height adds30; cleanup restores200 + through170→437740 and clears pitch to0. Ordinary non-raw6 input subsequently + restores pitch10. Current Forward/Backward mapping correctly increases pitch + on Up and decreases on Down,20*fixed-dt; this source keyboard field is unrelated + to PageUp/PageDown. +- First supported hold shows the aim strip and arms without refreshing saved + pitch. Later holds clamp0..45. DisplayPitch is copied before capture, matching + the original one-invocation label delay. Release hides the strip and launches + once from the saved pitch, including after unequip and at zero energy. +- Cleanup retains pending throw, saved pitch and20 projectile entries. Source + ring reuse does not clear pending impulse/support; current Launch preserves + both. Modern scene reset clears the pool and is an explicit lifecycle boundary. +- Projectile launch uses local(0,80,50), normalized local aim slope pitch/45, + source quick magnitude and speed1800. Upright yaw cases pass. Continuous + full-Euler transform remains a declared original table-precision boundary. +- Ball floor friction and wall damping both read slot248/live150=.46; + authored24=3.2 belongs to a different field. Floor support uses radius15, + factor1, prevent-lowering=false. Current Projectile.Step explicitly supplies.46. +- Landing queues oldX,−.65*oldY,oldZ into impulse before support zeros velocityY; + next body consumes it. Current implementation preserves this phase order. +- Program runs ball/target bodies before player input, and target frame callbacks + afterward. Input ownership follows LabSimulation's controlled path. Release + from a pending latch is processed even when raw6 is no longer equipped. + +## Declared limits, not release claims + +SceneBaseballs uses per-tick sphere overlap instead of original pair membership, +registry order and swept discovery. It can re-hit an overlapping ball after a +target respawns, whereas original enter callback timing still needs the pair +scheduler. Whole-scene pair response and other ball consumers remain incomplete. +Ball angular wall response is omitted, and each managed ball tick supplies zero +angular state; its billboard's positional path is the bounded tested subset. +Only Canv2 is used because no four-canvas animation advancement was recovered. +The full original game and native Windows input have not been runtime-compared +by this review. + +## Verification + +`dotnet run --project tests/GamePort.BaseballTests --no-restore` passed11 groups +with the local .NET environment. Python discovery `test_baseball*.py` passed16 +groups covering source guards, resources and target projections. These results +were rerun after the companion/trophy fixes. No remaining concrete blocker was +found within this bounded review; the declared limits above remain. No runtime +or shared source was edited by this reviewer. diff --git a/docs/gameplay/baseball-targets.md b/docs/gameplay/baseball-targets.md new file mode 100644 index 0000000..3fdb747 --- /dev/null +++ b/docs/gameplay/baseball-targets.md @@ -0,0 +1,98 @@ +# VR07 moving targets and Baseball contacts + +2026-11-02. Static recovery and source projections; original whole-game execution +has not been observed. Original EXE SHA256 is +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +`tools/binary/baseball_targets.py` guards the reviewed spans, virtual bindings, +factory and false registration filter. It reports PE-mapped offsets. All code +addresses below have file offset VA−400000 in this executable. + +## Evidence and identity + +The generated EXE copy was inspected with local REA/Ghidra12.1.4, profile digest +`e1ad533d4cc0333c2136fe0894217de2d61feea098240326e78633f9e4ddcbf9`. +Complete Evidence and a closed snapshot are retained in +`artifacts/baseball-targets/rea-local-ipc/`: + +| Procedure | Evidence | +| --- | --- | +|430220 moving-target construction|ev_3e420d49b2d4d524b6a80f3aebddef7d54863186d417cfc3b48d0f2a20b0fa29| +|430570 Baseball contact|ev_3a2778c478e072e201b1e3baaf87434837fd570a00b5ee84022491175c00c7c4| +|441AC0 sprite PostLoad|ev_236e87925819c8924f5becb9a72da56152655b79d0527a2d81bdef32c912917f| +|4573F0 VR07 construction|ev_11fddbe40ea4b959e27cba000aa4557cb04b2d4d104b11f155feedf88a97f04c| + +4306B0 and475CD0 were not recognized procedures and the provider's numeric +fallback interpreted them as unmapped file offsets. Their behavior is supported +by guarded disassembly, not attributed to pseudocode. The initial restricted +attempt failed at the Ghidra local socket; its owned batch was interrupted and +closed. Permitted local IPC resolved that host restriction. No client configuration +or original bytes changed. REA inspection is static, not target execution. + +3TAR's actual factory45CA06 constructs430220, complete table4A8E74, game interface +complete+C8/table4A8A10. Do not confuse it with Jimmy's C3DTarget aim helper or the +different4453B0 class also registering3TAR. Actual runtime type is C3DMOVINGTARGET. +VR07 constructor4573F0 binds complete game4CFAE0; slot134→475CD0 returns false +(`32c0c21800`), permitting the previously recovered NC/checkpoint registration +filters. VR07 has134 serialized triangles and no special Jimmy wall materials. +Textureless triangles remain collision candidates even though rendering skips them. + +## State and interaction + +| Complete field | Meaning / writer | +| --- | --- | +|57C/580/584|Sprite size/index/database; defaults100/98/sprites.omt; GAM overrides150/135/sprites.omt| +|5EC..5F8|Start XYZ/W, W initialized1| +|5FC..608|Destination XYZ/W, W initialized1| +|60C|Speed, default100| +|610|Respawn timer, initialized0| +|614|ActivateObject name| +|678/67C/680|HitsRequired(default5), NumPoints(default10), RespawnTime(default15)| + +Source radius75 is set at430485. World response and support are disabled by +430478/430480; integration is enabled430495. Frame game3C4→4306B0 first invokes +463090, then updates orientation, respawn and velocity. Positive respawn subtracts +dt with a float store; <=0 clamps0 and unhides. Hidden targets keep moving. +The vector to Destination is quick-normalized and multiplied by Speed. Ordinary +sqrt distance<100 then teleports to Start through314. Endpoints are not swapped; +the just-published velocity survives the teleport into the next integration phase. +Zero-length normalization is explicitly bounded to zero in the modern port. + +Contact game40→430570 first calls470A90, then accepts C3DBASEBALL only while +timer<=0. It hides the target, copies RespawnTime, and awards NumPoints through +42ADC0. It does not hide/destroy the ball. Lookup of ActivateObject returns the +first matching tagged actor. Missing parent requests SFX198. A C3DTROPHY or +C3DPICKUPITEM parent has its respective hit counter incremented; activation +occurs only when count **> HitsRequired**, then resets counter and requests199. +This strict comparison requires four qualifying contacts for VR07's value3. + +Trophy interface4BE404 slot428→40E1F0 takes activation1, conditionally enables +collision via3AC when interface584 is nonzero, then unhides. It does not execute +the script trigger interpreter or restart integration. Activation0 disables +collision via3A4 and hides. The port preserves that limited visibility/contact +operation; its existing actor flags remain a narrower adapter than all source flags. + +## Actual tutorial and implementation boundary + +VR07 GAM SHA256 is +`1260b75d82ec794f9375ada30e186424746bc1dd4e4b0540c9b69bb7ad12d0b1`. +Six3TAR records at file offsets885,AD6,D27,F78,11C9,141C all use the same tag +C3DMOVINGTARGET. They must be stored by source instance/offset, never collapsed +by a tag dictionary. Each has speed100, score10, respawn15 and HitsRequired3. +Only record11C9 names parent `trophy`; the others name `none` and produce198. +The original visible target is the explicitly serialized sprites.omt Canv135 +star,150×150.441AC0 proves that binding; RetainedSprites Canv8 `target` is separate. + +SceneBaseballs separates body integration before controller from target frame +updates after controller. Pair discovery currently checks current sphere overlap +at radii15+75 and Jimmy recovery15+player radius. This is a declared modern adapter, +not recovered47A580 registry ordering, swept dynamic contacts or full enemy combat. +Static ball response uses the source body/grid/support with ball callbacks; its +angular reflection tail and full logical/render Euler lifecycle remain open. +VR07's hidden trophy has contact disabled until its source activation so the +existing pickup adapter cannot collect it while invisible. + +Four Python groups cover identity/spans, duplicate source identities, hit gate, +stored respawn subtraction and strict parent threshold. Modern managed/native +results are recorded separately in baseball-implementation.md. Retained helpers +across level loads, moving target generic flags/rotation, full original cadence, +original runtime and native Windows comparison remain unresolved. diff --git a/docs/gameplay/baseball.md b/docs/gameplay/baseball.md new file mode 100644 index 0000000..74b4cb6 --- /dev/null +++ b/docs/gameplay/baseball.md @@ -0,0 +1,144 @@ +# Baseball source contract + +2026-11-02. Static recovery; original EXE SHA256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Text raw offsets equal VA−400000. The helper PE-maps and guards15 reviewed +source ranges,13 virtual targets and8 constants. No original game code was run. + +## Practical scope + +Baseball is feasible as the next bounded gadget with VR07 targets. It needs a +20-entry projectile pool, original sprite, primary hold/release state and narrow +ball-specific physics callbacks. Broad enemy AI is unnecessary for VR07's six +3TAR objects. Target behavior/registration is independently owned in +[baseball-targets.md](baseball-targets.md); resources in +[baseball-assets.md](baseball-assets.md). Generic full-scene collisions remain +outside a claim of finished gadget fidelity. + +## Evidence and provider boundary + +Local REA/Ghidra successfully decompiled constructor40FC50, Evidence +`ev_5c45397cd90b6247920a64a8b27d2838d805a8e1eebba69886f7ffd81d62993a`, +and physics scheduler479BC0, Evidence +`ev_56b7e074ec8509d1c5b3576d02361ff051963b777d7ccb8259ed9c65dc2db52f`. +Complete replies, exported bundle and closed snapshot are in +artifacts/baseball-contract/rea-local/. The initial sandbox attempt could not bind +the Ghidra Unix socket; its errors remain in rea/. The local permitted execution +completed. Queries426030,429A30,40FF40,40FF80,427FF0,428D50,472B10 were not +recognized as procedures; provider then interpreted numeric selectors as unmapped +file offsets. Their behavior below uses reviewed guarded disassembly, not claimed +successful pseudocode. Whole-game execution, original runtime comparison and +arbitrary-input x87 equivalence are unverified. + +## Owners, equip and cleanup + +Jimmy complete table4A3BDC:174→428D50 equip,178→427FF0 cleanup, +180→429A30 throw,148→429A00 stops saved soundA44 only,170→437740 camera defaults. +Item6 dispatch table4298E8+7*4→4296F8; raw6 cleanup428844+6*4→42871D. + +Equip4296F8 sets raw4F0588=6 with **no energy gate**, adds30 to camera scalar +complete7CC, hides menu+4E4 if needed, then hides Goddard and disables its body +214 and visibilityD0. Practice item9==2 then selects VR07 through42976C..7D8. +Cleanup42871D clears complete84C (camera/aim scalar), restores Goddard and shadow, +calls170 camera defaults, hides menu4E4, then common tail sets mode−1. +It **does not clear** pending throw complete1E26 or saved pitch1E28, and does not +destroy or hide the20 flying balls. A later release can therefore still throw. + +Constructor422609..269C allocates20 C3DBaseball complete objects of61C bytes, +stores pointers at Jimmy+AB4..B00 and initializes signed WORD B04=0. Ball game +interface is complete+C8 (table49141C), unlike Jimmy+C0. Pool capacity is not an +ammo count; current nonnull slot is reused and B04 increments modulo20. Null +slot leaves index unchanged. No ammo decrement is present in this launch path. + +## Hold, pitch and release + +426030's existing ownership/modal gates and movement438A60 precede primary +actions. Held predicate is helper42A7A0 OR separately polled Enter; release means +both false. Helper includes mouse/Enter/Ctrl/controller and suppressor4F83E0. +42668F..66BD rejects busy1D65, modal4F8182 or raw0, then zeroes controller +speed608. Energy helper4269D0 rejects energy<=0 unless complete9F8 override. +No minimum1-energy threshold is required. Ground support is necessary to enter +the raw6 aiming branch; airborne raw6 follows existing primary behavior. + +Ground hold426718 selects SHOOT, calls148 to stop sound, then raw6: + +1. Emit angle text for the **previous saved pitch**1E28, before any new capture. +2. Show fixed menu4E4 crosshair strip. +3. First held tick sets pending1E26 and calls148 again; it does not capture pitch. +4. Later held ticks clamp complete84C to[0,45], then copy it to1E28. + +The same complete84C is modified by ordinary input438C2C..CC6;4267D3 reads it +as interface+78C. It is **not logical EulerX**. Down(VK_DOWN28/address509860) decreases +it20*dt; Up(VK_UP26/address50985E) increases it20*dt. Otherwise signed mouseY*dt +is added, with analog threshold branches. Raw6 preserves it when not firing; +other modes ordinarily reset10. The camera uses it through439625 (eyeY offset +7CC−2*84C) and4396A9 (targetY7DC+scale*84C). This is independent of throw's +full logical-Euler point/vector transform. + +Menu4E4 is screens Canv253,15×210 at logical(315,100), scale1, initialized hidden +at4020DD..2104. Hold shows it, release426585 hides it. The adjacent numeric text +call468660 is variadic formatted text (vsprintf at468694), not sprite animation: +x286,y=trunc((45−savedPitch)*4.3+100), identity54494D45, format`% .2d`, +value=trunc(savedPitch). This yields a positive blank plus two precision digits. +TIME selector468C23 uses font5;46844A loads its64-word map from4F4ED8. +Digits0..9 map to alphaCanv[118,127,120,121,122,123,124,125,126,119]. +SPACE maps−1/null; null-glyph advance is separate asset/UI work. + +Release42659F..65F9 tests pending alone, plays SFX10 once, stops soundA44, +calls complete180 with(0,80,50,savedPitch), sets interfaceA48=0, clears pending, +then energy42A920(−1). It performs **no fresh mode, support or energy gate**. +Shared energy exemptions/clamps/warnings apply; VR07 is exempt. SHOOT uses the +existing authored shooting clip; no bespoke baseball throw clip was established. + +## Launch and body callbacks + +429A30 transforms local spawn point(0,80,50) through interface384 (472980), +unhides selected pool entry, enables collision224 and integration214, publishes +root314, transforms local vector(0,float32(savedPitch*float32(1/45)),1) through +38C (472B10), quick-normalizes, then sets velocityXYZ×1800 through2C4. +It does not clear pending impulse or support on reuse. For upright logical +pitch/roll0, yaw theta gives spawn root+(−50sin(theta),80,50cos(theta)) and +velocity1800*normalize(−sin(theta),savedPitch/45,cos(theta)). Source trig-table +quantization and imported quick magnitude differ from continuous host math. + +Constructor40FC50 binds retainedsprites.omt Canv2 with sprite size25; preloads +Canv2..5. Complete57C=25 is size, **not a3D shapeID** (435430→464430). +It sets radius15, authored property24=3.2, wall damping28=.46, and leaves the +floor support factor1. Floor friction also reads slot248 and is.46 (47A356); suppression scale.5. +Pool initialization hides it, disables integration214 and collision224; launch +enables both. Generic defaults include support1C8=true, world1D0=true, +reflection1D8=true, prevent-lowering208=false. Constructor sets authored204=false +and224=false. Do not confuse authored field offsets, live fields and slots. + +|Ball interface slot / implementation|Effect| +|---|---| +|370→40FF50→472690|Ceiling callback: independently clear positive velocityY and positive accelerationY.| +|374→40FEE0→458890→378472750|Generic wall reflection. Normalize horizontal velocity; reflect using supplied normal; rescale by old horizontal magnitude; preserve oldY; damp resulting XZ by(1−slot248), where slot248 reads wall damping.46. Angular heading response is an additional source tail.| +|37C→40FF80|Read live velocity2BC; store queued impulse288=(oldX,−.65*oldY,oldZ). **This is not a velocity write.**| +|3C4→40FF40→463090→458930→473240|Generic update; no baseball-specific TTL or canvas-frame advancement recovered.| + +Support47BB10..BBA7 publishes floor root, zeros accelerationY, invokes37C only +on previous-support=false, then zeros velocityY and sets support true. Next +ordinary body tick consumes queued impulse before acceleration/gravity. Because +37C queued full X/Z, horizontal speed can increase on the next tick; do not +silently discard those components. See existing +[body composition](../checkpoint/collision-body-composition-source.md) for +gravity, displacement, static support/friction and publication order. Ball's +factor1/radius15 and no prevent-lowering must be supplied to a ball adapter; +Jimmy-specific callbacks are unsuitable. No automatic first-hit destruction or +fixed-distance/time expiry is justified by this class. + +Jimmy enter423014..307D recognizes C3DBASEBALL, disables ball214/224 and hides +it. Other objects own their contact effects. A target hit cannot be presumed to +consume a ball solely from its name; target and dynamic-contact scheduling need +their own source boundary. Cleanup6 leaves balls active; scene/pool ownership +must survive until its actual loader/reset boundary. + +## Verification + +tests/test_baseball.py verifies source identity/ranges/virtuals, first-hold versus +later pitch capture, stale displayed pitch, hold gates, release after cleanup, +ring reuse/null behavior, upright launch offsets and delayed full-vector landing +impulse. These are bounded static projections, not original execution or modern +runtime verification. Frame animation of the four preloaded ball canvases, +general dynamic collision response and exact trig precision remain unresolved. diff --git a/docs/gameplay/gadget-assets.md b/docs/gameplay/gadget-assets.md index 1a17d4d..640fab6 100644 --- a/docs/gameplay/gadget-assets.md +++ b/docs/gameplay/gadget-assets.md @@ -103,8 +103,9 @@ prepared standing mesh, so existing morph preparation can preserve its topology. |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 +scooter.omt contains shape0 `goddard01`, shape1 `wheel`; material0 `goddard128` +links Canv1 `goddard128`, material1 `scooterwheel2` links Canv0 `scooterwheel2`. +This corrects the earlier ambiguous material/canvas association; 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. diff --git a/docs/gameplay/scooter.md b/docs/gameplay/scooter.md new file mode 100644 index 0000000..8a1eefa --- /dev/null +++ b/docs/gameplay/scooter.md @@ -0,0 +1,204 @@ +# Scooter: separate vehicle and deferred implementation + +2026-11-02. Static source recovery only; **no live Scooter implementation or +original gameplay verification**. User parked broad collision. Scooter cannot +faithfully reuse only Jimmy's current body: original drive/steering depends on +separately constructed wheel children. Primary was advised before runtime work +and selected another gadget for the next implementation slice. + +Original EXE SHA-256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +`tools/binary/scooter.py` guards17 complete bounded spans,13 virtual bindings, +10 constants,4 strings and the always-false sprint predicate. Generated ledger +`artifacts/scooter-contract/source-contract.json` contains exact VAs, PE offsets, +lengths and hashes. For every code VA in this report, file offset is VA−400000. +Data/table addresses must use the ledger's PE reader; do not assume this identity +for an arbitrary PE. Supplementary instructions are in the same artifact directory. + +## REA evidence and coverage + +Local `scripts/rea.sh`/Ghidra12.1.4 analyzed the generated copy +`artifacts/uncontrolled-phases/rea/Neutron.exe`; originals were not executed. +`rea-vehicle/01.json` recovered465220 with Evidence +`ev_09ecf350c8705d5f9c1da5b444eb8cd027f64f4859713b29c9d04bc4c55c2bc8`; +`02.json` recovered465830 with Evidence +`ev_dbb6ac283387e14f08d527a750c14af44c52ed80c612c40393a5434a16589916`. +Profile digest is +`e1ad533d4cc0333c2136fe0894217de2d61feea098240326e78633f9e4ddcbf9`. +Complete bundle and closed snapshot are retained.465220 pseudocode contains +incorrect float/pointer/local aliases and loses some x87 scalar producers; +the guarded instructions resolve the gates and arithmetic cited below. + +421580 and412A90 returned explicit procedure-lookup/unmapped-file-offset +provider errors. Initial exploratory437F90/43A120 (Jimmy routines, subsequently +excluded from Scooter) also failed; `rea-native/` retains failures, empty export +and closed snapshot. No unchanged failed request was repeated. The first +sandboxed `rea-equip/` attempt saved only successful target-open metadata and no +pseudocode/Evidence or closed snapshot before its worker ended; no success is +attributed to it. Local static IPC allowance resolved the host restriction for +the later complete batches without changing client configuration. + +## Actor, construction and selection + +Inventory item4/raw mode4 is Scooter. Movement mode is a **separate vehicle +state**, not Jimmy movementmode3. C3DJEEP constructor4211A0 calls412870→464B90; +complete vtable4A2F8C, game interface+C0/vtable4A2AEC.4213F0 loads +`omt\\scooter.omt` (string4EEF2C). Radius is150 at42128E via game110→471240; +inherited factor is float.2 at412942 via4711E0. These are distinct from body +friction; do not replace friction with.2. + +Jimmy game initialization423CE8..423DC1 lazily allocates6AC bytes, constructs +4211A0, and stores complete actor at Jimmy+A30 (game+970). Complete168→412A90 +receives `(73,-30,3,3,1,true,true)` at423D58..75.412A90 constructs **four** +C3D wheel actors through type33574845/459CB0 into the first4 of6 pointer slots +complete578..58C and stores relative offsets in complete5A0+16*i. It also adds +mutual collision exclusions3A8. The slots are initialized null in464C9A..BC. +Thus the last2 generally remain absent in this constructor path; support code +still scans6. Wheel collision/body scheduling and wheel-type implementation are +not closed by this investigation. + +Panel4278D7 already closes and invokes Jimmy cleanup178 before174(4), as in +[gadget-controls](gadget-controls.md). Item4 leaf4290B7 requires Jimmy+A1C +companion. It hides companion+994 via58(true), requires companion gameCC true, +sets raw4, copies companion root310/Euler328 into vehicle via16C/174, hides +vehicle and children through complete174→421800, enables vehicle gameD0/214, +then hides/disables companion gameD0/214. **This does not mount Jimmy or change +controlled pointer directly.** Failed companion gates still continue to practice +handling429297. Armed practice switches item9 to1 and loads VR05. Do not add an +energy requirement: the reviewed equip leaf has none. + +Mount is a later Jimmy interaction callback:422F13..422FB9 recognizes target +`C3DJEEP`, invokes Jimmy complete1E0, calls game118(vehicle game interface), +stores Jimmy complete pointer into vehicle69C, hides Jimmy+A2C, adds Jimmy's +vehicle collision exclusion3A8, selects `SCOOT` with E0(...,true), then refresh148. +The callback's full interaction eligibility/caller and complete1E0 effect remain +separate gates. Merely selecting the tile must not fabricate a mount event. + +## Fields, input and apply + +Offsets here are **vehicle complete object** unless explicitly marked game. + +| Offset | Source owner | +| --- | --- | +|578..58C|6 child pointer slots;4 populated by this setup| +|600/602/604|signed WORD front2/rear4/total child support counts| +|610/618/620/628|acceleration700/deceleration1200/base maximum2250/current maximum1485| +|61C|previous source scalar speed| +|63C/640|steering wheel angle/applied yaw rate| +|658/659|throttle/braking flags| +|65D/65F|keyboard-turn/reverse-held latch| +|650/654|camera mode/previous camera mode| +|690/694|engine channel/base sample frequency| +|698/69C/6A0|jump edge latch/mounted Jimmy pointer/animation clock| + +464F60(100), called by base constructor, sets acceleration=100+600, +deceleration1200, base maximum=100*4.5+1800=2250 and default maximum=base*.66. +Vehicle game268/26C get/set scalar speed. Complete130→413A60 always returns false +in C3DJEEP, so the inherited sprint branch is inactive and normal maximum is +float1485. Mouse, controller and inherited AI/camera paths are not included in +the pure keyboard projection. + +Input421880 rejects407060 true,475CA0 false or open gadget panel. Primary fire +509834 sets global4F8182; input then delegates465830. That input first copies +current scalar speed into61C, clears analog throttle/brake flags and fetches +mouse axes through completeF8. With mouseX0, keyboard Left precedes Right, +adds/subtracts200dt to angle63C and sets keyboard-turn latch. With no turn key, +that latch permits return toward0 by200dt, clamped at crossing. Angle caps±45. +Nonzero mouseX uses2*dt*mouseX and clears keyboard-turn latch; inherited return +does not necessarily continue after mouse release. Left/Right also accept +analogX<−.5/>.5 through421C10/40. + +Forward predicate421C70 requires rear support count602>0 plus Up, primary fire, +controller button509AC4 or analogY>.5. It adds acceleration700dt while below +maximum and clamps there; at/above maximum normal no-sprint branch preserves +speed. Backward421CB0 also requires602>0 and supports Down/analogY<−.5, with +the source primary-fire/controller qualifications retained in instructions. +First accepted backward call sets reverse latch: positive speed subtracts1200dt +and clamps0; negative speed adds1200dt and clamps0. Subsequent held calls +subtract1200dt, allowing reverse down to−currentMaximum*.4 (about−594). +Braking flag659 persists through the continued-held path; release clears both +braking and reverse latch. Forward executes before backward. These are dt-based +vehicle increments, unlike Jimmy's fixed-per-callback Bubble throttle. + +Apply421580 calls412ED0→465220, which calls462520 first, then requires475CA0 +and game210. It scans actual nonnull children and their game218, recomputing +600/602/604. Steering requires nonzero incoming horizontal live velocity and +front count600>0. Scalar speed gives scale=min(horizontalMagnitude*.005,1); +ordinary yaw rate640=frontCount*angle63C*scale (inherited AI uses2 instead). +The dot between normalized horizontal velocity and rotated local forward +chooses forward/reverse yaw sign; yaw increment is rate*dt. + +The drive-velocity rewrite at465594 requires **vehicle game218 AND total child +support604>=2**. Missing/unsupported children do not imply support. Unsupported +vehicle still publishes scalar speed but does not execute that rewrite. +Supported scalar decay/turn drag/slope terms, normalized live/forward direction +mixing and friction can change speed and velocity; the whole465220 span and +Evidence are retained but no full numerical drive projection is claimed. The +`drive_eligible` helper tests only its recovered eligibility gate. Jimmy's +ordinary application formula is not equivalent to this routine. + +## Mounted update, animation, sound and cleanup + +After vehicle apply,421580 with mounted69C calls Jimmy complete1AC(dt), handles +the five standard jump inputs and copies vehicle root/Euler into Jimmy. Jump +uses its own edge latch698: release clears it; held with latchfalse and vehicle +support queues `(0,700,0)` through game28C, then sets latch. Airborne hold does +not latch, so support can accept it later. This is pending velocity/impulse state, +not an immediate Y700 live-velocity assignment. No mounted pointer takes a +different stop/reset path421794; it does not run mounted jump/pose updates. + +Animation timer6A0 stores float(timer+dt), compares to **double.3**, and when +greater selects Jimmy `SCOOTSTOP` for signed scalar speed<10, otherwise `SCOOT`, +both E0(...,true), then clears timer. Reverse speed therefore chooses stop at +this site. float32(.3) is already greater than double.3. Do not replace the +threshold with.3f equality. No Goddard195-vertex morph binding was proven; +[asset inspection](gadget-assets.md) and vehicle asset export retain that gap. + +412ED0 starts positional looping SFX46 (`Scooter`) through4589C0 when vehicle +gameCC and audio global696008 are true and engine channel690 is−1. It captures +channel base frequency in694; later frames write a speed-dependent frequency, +minimum7000. No direct energy debit42A920 was found in the reviewed equip, +vehicle input/apply/update spans. This bounded result does not prove global +energy policy for every interaction/caller. + +Cleanup178 raw4 jumps4281B3. If companion absent or companion gameCC already +true it proceeds to common raw−1 return42882F without the full vehicle teardown. +Otherwise it clears menu4B4, writes JimmyA20=.5 (consumer remains unknown), +copies vehicle root/Euler back to companion, shows/enables companion D0/214, +resets42AE90 clocks, removes Jimmy vehicle exclusion3B0, exposes vehicle children +through completeD8→464F00, disables vehicle D0/214, destroys retained helper via +complete164, stops engine690 and clears it−1. If mounted69C nonnull it additionally +clears Jimmy action latch1E25 and4F8182, restores game118(Jimmy interface), raises +Jimmy rootY by constant49FAD4, clears acceleration278/live velocity2C4, requests +`RUN`4ECA64, exposes Jimmy+A2C (unless509A13), and finally clears vehicle69C. +Every completed return sets raw−1. The exact elevation constant is intentionally +left in guarded source pending the full dismount/body policy; no new cleanup +Euler blend or Jimmy movement-mode reset was inferred. + +## Camera and implementation boundary + +Vehicle camera completeEC→4130A0 runs at the end of465830; it uses camera +mode650, previous654, global eye509A50, vehicle rotations/speed and native +collision clipping. Default mode1 is set in464D1F and its source branch begins +413234; Down/reverse and camera-mode inputs remain separate concepts. Full +camera branch arithmetic/obstruction ownership is unresolved, and using Jimmy +camera439900 for Scooter would be a declared approximation. There is no proven +complete camera contract here merely because source is retained. + +Practical next slice, in order: + +1. Close C3D wheel child transforms, support/contact scheduling, source body + properties and static VR05 eligibility; preserve actual4-child constructor. +2. Add distinct registered Scooter actor, spawned/mounted/control-owner state, + child exclusions, mount eligibility and atomic cleanup handoff. +3. Port465830 keyboard and465220 full arithmetic with regression projections, + then jump/pose/SFX46/camera. Preserve scalar/live/pending state separation. +4. Compare original mount/drive/jump/reverse/dismount runtime before claiming + faithful playability. Native Windows comparison remains unverified. + +These dependencies make a movement-only Jimmy flag insufficient. Broad collision +remains parked; no runtime source was edited by this investigator. Nine Python +groups pass: identity/span/binding guards, spawn-vs-mount, real support gating, +steering caps/release, rear-support throttle, brake/reverse ordering, jump edge, +animation float/double boundary and bounded inputs. They validate source +projections, not original execution or port vehicle behavior. diff --git a/docs/gameplay/vehicle-assets.md b/docs/gameplay/vehicle-assets.md new file mode 100644 index 0000000..43b50b7 --- /dev/null +++ b/docs/gameplay/vehicle-assets.md @@ -0,0 +1,97 @@ +# Scooter / Rocketship resource contract + +2026-11-02. Read-only original asset inspection. No original executable was run +and no original file was modified. Source binding recovery belongs to +`scooter_contract`; geometry/sample/pixel observations here do not establish +attachment, steering, visibility, sound ownership or interpolation policy. + +`tools/extractors/scooter_resources.py` exposes `export_scooter(original, output)`. +Its schema1 `scooter.json` references two independent original OMT shape scenes, +Jimmy's two renderable Scooter animation manifests, and the two unbound Goddard +Scooter source morphs. It checks original hashes before output, rejects original +subtrees/ancestors and existing descendant symlinks, and uses portable +case-insensitive asset lookup. Original PNG pixels and OMT canvas alpha are kept. + +```bash +python3 tools/extractors/scooter_resources.py ../Original --output artifacts/vehicle-assets/scooter +python3 -m unittest discover -s tests -p test_scooter_resources.py -v +``` + +Five checks pass: shape/material/pixel identity, exact Jimmy base topology and +sample positions, preserved unbound source times/absent UVs, source/output +protection and changed-source rejection before output. Generated inspection data +is `artifacts/vehicle-assets/inventory.json`; generated resources are under +`artifacts/vehicle-assets/scooter/`. No shared prepare/runtime files were edited. + +## Usable Scooter geometry + +Archive `omt/scooter.omt` SHA256 +`8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81`. + +| Original resource | Offset / bytes | Geometry / exact texture link | +| --- | --- | --- | +|3DSh0 `goddard01`|104 /19342|98 indexed vertices,176 triangles; material0| +|3DSh1 `wheel`|92304 /5814|32 indexed vertices,56 triangles; material1 plus null-material polygons| +|3DMa0 `goddard128`|19446 /52|Canv1| +|3DMa1 `scooterwheel2`|19498 /52|Canv0| +|Canv0 `scooterwheel2`|22568 /3966|32×32, RGBA SHA256 `92dfef71def8079db70ba4eaa47e973d45a0b3987418e87dbf65cc3cf0bf823b`| +|Canv1 `goddard128`|26534 /65770|128×128, RGBA SHA256 `b22651171a7b9f2c99831a1ff4fd8d01d11ccabfc276d71dd91bacd710cd1cba`| + +This corrects the ambiguous material/canvas ordering in gadget-assets.md: +body material0 points to **canvas1**, wheel material1 to **canvas0**. +Each shape gets a separate `shape_ID/scene.json` compatible with the existing +OMT scene loader, expanded source positions, source normals/materials/UVs, +transitively referenced decoded canvas and provenance. Null wheel materials stay +null (`material:-1`), rather than receiving an invented visible material. +Neither shape is translated, scaled or instanced by this exporter. Runtime must +use the separately recovered original body/wheel attachment contract. + +## Morph compatibility + +| Original ASE | Indexed vertices / faces | Sample times | fps / ticks per frame | Available base | +| --- | --- | --- | --- | --- | +|jimscooter|426 /814|0,480|10 /480|jimstop426; base supplies original UV/topology| +|jimscooterstop|426 /814|0,480|10 /480|jimstop426; base supplies original UV/topology| +|godscooter|195 /370|0,161|30 /160|none recovered| +|godscooter2|195 /370|0,161|30 /160|none recovered| +|godrocket|222 /411|0,960,1920|5 /960|count-compatible godpoint222, binding separate| +|jimdrive|426 /814|0,480|10 /480|count-compatible jimstop426, binding separate| + +Jimmy exports use the existing `export_ase` family format and exact original +`png/jimycarl.png` (SHA256 +`55ed165aaffe177cb62558a08d13fc3b2210da6e353065b108849d46df9dacb6`). +Each animation is source-named, with relative `../jimycarl.rgba` texture and +two expanded geometry frames. No family action names or playback times are +assigned. Existing `prepare_actor` can express these Jimmy clips directly. +Flat reconstructed ASE normals remain the existing exporter limitation. + +Both Scooter dog morphs have **no UV tables**. Their195 positions differ from +both OMT body98 and the existing Goddard godpoint222 base. Existing morph export +correctly rejects these combinations. `godscooter-unbound.json` and +`godscooter2-unbound.json` preserve all parsed positions/faces and exact sample +times, without fabricated UVs or rendering them as a valid actor. The second +sample's161 ticks is intentionally retained, not rounded to160. Material-list +filenames include many unrelated scene leftovers; these do not prove binding. + +## Rocketship and Baseball boundary + +`godrocket.ASE` lacks UVs but has222 vertices/411 faces, the same count as +`godpoint.ASE` (textured high-detail Goddard base). This permits existing actor +export mechanics *if* binary binding establishes that base. It does not justify +claiming the gadget renders that clip. `jimdrive.ASE` similarly has426 positions +and no UVs. `rocket.ASE` is a separate textured16-vertex/22-face mesh (one sample, +5fps/960 ticks), and `rocketfire.ASE` has4 vertices/3 faces at0/960/1920 with UVs. +The material texts mention rocket.bmp/fire.png; no Rocketship gadget attachment +is inferred. `objects.omt` contains3DSh26 `rocketship`135 vertices/236 polygons; +that name also does not close the gadget's resource binding. + +No baseball-named ASE or PNG was found by bounded filename search. This does not +establish that the source lacks a ball asset. The separate Baseball investigation +has recovered constructor40FC50 using RetainedSprites.omt Canv2 at sprite size25; +25 is not a shape ID. Exact resources and TIME font are in `baseball-assets.md` +and `baseball-font.md`. Original HUD/control/sound identity +is already inventoried in `gadget-assets.md` and should not be duplicated. + +Static asset extraction and the five Python checks are verified. Gadget rendering, +wheel motion, source animation timing, original execution comparison and native +Windows behavior remain unverified. diff --git a/docs/progress.md b/docs/progress.md index d33efc2..0536ce8 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,37 @@ # Progress — 2026-11-02 +## Baseball continuation + +Continued gadgets after clean1ae5f42/50fcb87. Local REA investigations recovered +Baseball's20-slot pool, hold/release and delayed landing impulse, VR07 moving +targets/strict parent activation and exact TIME font. Original addresses/offsets, +fields, hashes, provider limitations and closed Evidence are in gameplay/baseball*, +with separate source guards and tests. Scooter recovery is saved in scooter.md +and vehicle-assets.md; its separate C3DJEEP/wheel body gates prohibit pretending +that a Jimmy mode implements it. All investigator file ownership has returned. + +Implemented BaseballGadget/Projectile, explicit ball body response, SceneBaseballs, +original ball/aim/TIME rendering, VR07 source static registration and F1 grant/ +diagnostics. Pending throws/flying balls survive unequip; source scalar/label and +sound/launch/cost order are separate. Six identical target tags preserve distinct +instances. Review corrected gadget-specific companion restoration and hidden +trophy contact/conditional activation;12 managed/6 visual and16 Baseball Python +groups pass. Bounded pair discovery and angular/world/Euler/helper retention +limits remain explicit; full enemy AI/combat is not claimed. + +Headless and native GTX1070/private Xvfb1920×1080 pass all eight rendered phases, +including real SDL Ctrl/Left/Up/Tab, actual target hit, retained projectile and +respawn; enabled Vulkan validation reports zero errors. Fixture advances1010 +extra ordinary player/target ticks, preserves tutorial energy20 and does not +relocate actors or directly modify timers. Captures were inspected. Complete +scripts/test.sh passes232 Python+2 HUD, all managed suites,32 main GPU completions +and17 isolated material checks with zero enabled validation errors. SDL dummy +lifecycle and539 original hashes pass. A final focused12-group Baseball run adds +source wall-reflection and.46 floor-friction numeric checks;16 Baseball Python +groups pass after adding the font-table guard. Clean package validation follows. Logs: +artifacts/baseball-implementation/. No new native Windows/original whole-game +runtime claim is made. + ## Bubble continuation User continued gadgets after clean1897dd2/9ea5784. Bubble mode2 motion, body, diff --git a/docs/tasks.md b/docs/tasks.md index fa49226..a990fa8 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -80,10 +80,21 @@ the resume backlog, not prerequisites imposed on this user-directed gadget work. SDL Bubble checks;539 original hashes unchanged. - [x] Commit clean1ae5f42 Bubble milestone, rebuild Linux/Windows packages, verify exact Canv1 pixels in both and standalone Linux gameplay/debug view from /tmp. -- [ ] Rocketship, Scooter, Remote, Baseball and Grappler; full enemy AI and +- [x] Recover Baseball equip/hold/release, owned20-slot pool, queued landing + impulse, exact original TIME font and VR07 moving-target/parent contracts. +- [x] Implement Baseball, original ball/aim rendering, F1 grant, bounded VR07 + source body/targets, eleven integration/six visual groups; independent review. +- [x] Headless and native1920×1080 actual SDL aim/release/target-hit/respawn pass; + 1010 extra complete player/target ticks are an explicit accelerated port fixture. +- [x] Complete232 Python+2 HUD/all managed/32 GPU+17 material regression; final + 12-group Baseball callbacks and16 source groups pass;539 original hashes verify. +- [ ] Clean Baseball Linux/Windows package validation. +- [x] Save Scooter separate actor/mount/vehicle and original asset contracts; + wheel body/support lifecycle remains a gate before faithful live integration. +- [ ] Rocketship, Scooter, Remote and Grappler; full enemy AI and original/native Windows comparison. Retain collision/camera/retained-helper gates. -Details: [first gadget slice](gameplay/gadgets-implementation.md). Investigators +Details: [Baseball continuation](gameplay/baseball-implementation.md). Investigators have returned all file ownership to primary. Complete final regression, native Linux input and release checks pass; the remaining gadget effects are the next gameplay backlog. Native Windows gadget verification remains open. diff --git a/scripts/package.sh b/scripts/package.sh index a5ecee1..2f08caa 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -19,6 +19,8 @@ for rid in linux-x64 win-x64; do cp -a artifacts/extracted/invisible-meter/. "$out/scenes/invisible-meter/" mkdir -p "$out/scenes/bubble" cp -a artifacts/extracted/bubble/. "$out/scenes/bubble/" + mkdir -p "$out/scenes/baseball" + cp -a artifacts/extracted/baseball/. "$out/scenes/baseball/" mkdir -p "$out/scenes/effects" cp -a artifacts/extracted/effects/. "$out/scenes/effects/" cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json" @@ -83,6 +85,12 @@ Bubble is implemented too: F1/Player can Give/Select Bubble, Up or primary fire accelerates, arrows steer, and jump holds produce higher bounces. Tab/Space first unequips it, then the original sprite fades. VR01 uses recovered static body and floor111 behavior; lab/outside still have provisional collision. +Baseball is implemented: F1/Player can Give/Select Baseball. Hold Enter/Ctrl/left +mouse, Up/Down changes elevation and Left/Right turns; release fire to throw. +Its owned tile's Practice Mode opens VR07 with original moving targets,15-second +respawn and source trophy activation. Original ball/crosshair/TIME glyphs scale +uniformly on widescreen. Full enemy combat and original pair scheduling remain +incomplete; flying balls and a pending throw can survive unequipping. Append --inspect to start directly in the old scene inspector. The default runs the recovered lab camera/speech sequence; Escape/Space skips its actions and restores control. --skip-intro starts with control; --mute disables diff --git a/scripts/test.sh b/scripts/test.sh index 4f7c011..6b5bc58 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -17,6 +17,8 @@ dotnet run --project tests/GamePort.InvisibleTests dotnet run --project tests/GamePort.BubbleMotionTests dotnet run --project tests/GamePort.BubbleVisualTests dotnet run --project tests/GamePort.BubbleTests +dotnet run --project tests/GamePort.BaseballTests +dotnet run --project tests/GamePort.BaseballVisualTests dotnet run --project tests/GamePort.HeadingTests dotnet run --project tests/GamePort.BlendTests dotnet run --project tests/GamePort.CameraRayTests @@ -59,6 +61,7 @@ dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json 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 --scene artifacts/extracted/VR03/scene.json --level gam/VR03.gam --smoke-invisible --screenshot artifacts/test-invisible.ppm dotnet run --no-build -- --headless --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-bubble --screenshot artifacts/test-bubble.ppm +dotnet run --no-build -- --headless --scene artifacts/extracted/VR07/scene.json --level gam/VR07.gam --smoke-baseball --screenshot artifacts/test-baseball.ppm dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk dotnet run --no-build -- --headless --load-save artifacts/test-checkpoint.tsk --skip-intro dotnet run --no-build -- --headless --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro @@ -75,6 +78,7 @@ 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 python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then + dotnet run --no-build -- --scene artifacts/extracted/VR07/scene.json --level gam/VR07.gam --smoke-baseball --width 1920 --height 1080 --screenshot artifacts/test-baseball-window.ppm dotnet run --no-build -- --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-bubble --width 1920 --height 1080 --screenshot artifacts/test-bubble-window.ppm dotnet run --no-build -- --scene artifacts/extracted/VR03/scene.json --level gam/VR03.gam --smoke-invisible --width 1920 --height 1080 --screenshot artifacts/test-invisible-window.ppm dotnet run --no-build -- --smoke-gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu-window.ppm diff --git a/src/GamePort/Application/BaseballAimOverlay.cs b/src/GamePort/Application/BaseballAimOverlay.cs new file mode 100644 index 0000000..71c6595 --- /dev/null +++ b/src/GamePort/Application/BaseballAimOverlay.cs @@ -0,0 +1,76 @@ +using System.Numerics; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// Source stationary crosshair strip and prior-capture pitch label. +/// Original TIME set5 glyphs preserve their green pixels and null-space advance. UiViewport supplies the port's uniform centered widescreen policy. +public sealed class BaseballAimOverlay +{ + private static readonly Dictionary Expected = new() + { + [253]=(15,210,"2e16e11b151c8474ba68fd5017d1a3a6304a594a7f34c3b423f3417c7edfb453"), + [118]=(16,16,"edc60e65dcf7320813a80d4312e3c45951ccfc566ea79dfabf7a22ebc4b96049"), + [127]=(16,16,"1fd058ad5bdc0f8a064ef7d2d52b2b036df3f35515691a366799d7e8aab5297f"), + [120]=(16,16,"62aaeaaf107300a6f4f7ff52e98106c1520a9edbe2137626ee41091cf243e5c5"), + [121]=(16,16,"d78bf1895f5838b9eb8c6a22565a9588dae4fc8f7106697df373f4408aae634c"), + [122]=(16,16,"f6d628639de4e40005f62f63a49308ff9ee0656a36bb6eb7787230b4830a5ed9"), + [123]=(16,16,"9f58cad5621d89b7a7012036daa8532b2397b0d9d267ab7d1aa5a7cd10d7ae87"), + [124]=(16,16,"49cdc9ec812f4ef3826011d542c30afbb10229c4b4ce549e7820233bbaa53dd9"), + [125]=(16,16,"aaef2d59c2636c059b446bed643985ca55d15b2d070b0582b2d8994b3bf74f1e"), + [126]=(16,16,"bade574a4624a3f763ddd9c87fa2f102562b00d8d604e9faf32a43b372de64e0"), + [119]=(16,16,"0a663ddf2df9f1065f5e4ffe27b4d1fa96edd5f19b6323217bad4148f8d2f3d7") + }; + private static readonly int[] DigitIds = [118,127,120,121,122,123,124,125,126,119]; + private readonly int[] offsets = new int[21]; + private readonly uint[] firstIndices = new uint[21]; + public Mesh Mesh { get; } + + public BaseballAimOverlay(Mesh combined, string preparedRoot) + { + var images = BaseballResourcePixels.Load(preparedRoot,"aimTextures",Expected); + var builder = new BaseballQuadBuilder(combined); + (offsets[0],firstIndices[0]) = builder.AddQuad(builder.AddTexture(images[253]),true); + //TextureId is immutable. Two banks of ten digit quads select exact glyphs + //without modifying shared draws or allocating per-frame geometry. + for(var digit=0;digit<10;digit++) + { + var texture=builder.AddTexture(images[DigitIds[digit]]); + for(var place=0;place<2;place++) + { + var index=1+place*10+digit; + (offsets[index],firstIndices[index])=builder.AddQuad(texture,true); + } + } + Mesh=builder.Build(); + } + + public void Update(Mesh destination, BaseballGadget device, uint width, uint height) + { + if(destination.Vertices.Length45)throw new ArgumentOutOfRangeException(nameof(device),"Source pitch label must remain0..45"); + var number=(int)pitch; + var y=(int)((45-(double)pitch)*4.3+100); + Quad(0,new(315,100),new(15,210),device.AimVisible); + for(var digit=0;digit<10;digit++) + { + //TIME set5 has a null space pointer; source468939 skips both + //drawing and advance for the positive sign blank. + Quad(1+digit,new(286,y),new(16,16),device.AimVisible&&digit==number/10); + Quad(11+digit,new(302,y),new(16,16),device.AimVisible&&digit==number%10); + } + void Quad(int index,Vector2 position,Vector2 size,bool visible) + { + var draw=destination.Draws.First(d=>d.ScreenSpace&&d.FirstIndex==firstIndices[index]&&d.IndexCount==6); + draw.Visible=visible; + if(!visible)return; + var p=position+viewport.CenterOffset; + var corners=new[]{p,p+new Vector2(size.X,0),p+size,p+new Vector2(0,size.Y)}; + for(var corner=0;corner<4;corner++) + destination.Vertices[offsets[index]+corner].Position=viewport.ToNdc(corners[corner]); + } + } +} diff --git a/src/GamePort/Application/BaseballSmoke.cs b/src/GamePort/Application/BaseballSmoke.cs new file mode 100644 index 0000000..da4f70e --- /dev/null +++ b/src/GamePort/Application/BaseballSmoke.cs @@ -0,0 +1,72 @@ +using GamePort.Game; + +namespace GamePort.Application; + +/// Actual VR07 input fixture. Extra ticks run ordinary body, input, +/// target-frame and director paths; no actor relocation or timer mutation. +public sealed class BaseballSmoke +{ + private readonly LabSimulation player; + private readonly PlayerSceneBinding binding; + private readonly SceneInventory inventory; + private readonly SceneBaseballs scene; + private readonly SceneDirector director; + private readonly bool[] checks=new bool[8]; + private readonly float initialEnergy; + private int extraTicks; + private bool hitObserved; + + public BaseballSmoke(LabSimulation player,PlayerSceneBinding binding,SceneInventory inventory, + SceneBaseballs scene,SceneDirector director) + { + this.player=player;this.binding=binding;this.inventory=inventory;this.scene=scene;this.director=director; + initialEnergy=player.Energy; + inventory.SetState(0,6,1);inventory.SelectGadget(6); + } + + public void BeforeFrame(int count,Action key,bool headless) + { + if(count==1&&!headless){key(224,true);key(80,true);} + if(count==2&&!headless){key(80,false);key(82,true);} + if(count==3&&!headless){key(224,false);key(82,false);} + if(count is 4 or 5)Advance(40); + if(count==6){if(headless)inventory.SelectGadget(-1);else key(43,true);} + if(count==7) + { + if(!headless)key(43,false); + Advance(930); + } + } + + private void Advance(int ticks) + { + for(var i=0;i0; + extraTicks++; + } + } + + public void AfterFrame(int count) + { + var gadget=player.Baseball; + if(count==0)checks[0]=gadget.Equipped&&player.GadgetMode==6&&!gadget.PendingThrow; + if(count==1)checks[1]=gadget.PendingThrow&&gadget.AimVisible&&gadget.SavedPitch==0; + if(count==2)checks[2]=gadget.PendingThrow&&gadget.AimVisible&&gadget.SavedPitch>10&&gadget.DisplayPitch==0; + if(count==3)checks[3]=gadget.Throws==1&&!gadget.PendingThrow&&!gadget.AimVisible&&gadget.Projectiles[0].Visible; + if(count==4)checks[4]=gadget.Projectiles[0].Visible&&gadget.Projectiles[0].Position!=gadget.Projectiles[0].PreviousPosition; + if(count==5)checks[5]=scene.Hits>0&&scene.Targets.Any(t=>t.Remaining>0&&!t.Actor.Visible); + if(count==6)checks[6]=player.GadgetMode==-1&&!gadget.Equipped&&gadget.Projectiles.Any(b=>b.Visible); + if(count==7)checks[7]=hitObserved&&scene.Targets.All(t=>t.Remaining==0&&t.Actor.Visible); + } + + public bool Passed=>checks.All(v=>v)&&player.Energy==initialEnergy; + public string Report=>$"Baseball fixture: equipped={checks[0]}, arm={checks[1]}, prior-label/capture={checks[2]}, release={checks[3]}, flight={checks[4]}, actual target hit={checks[5]}, unequip retains ball={checks[6]}, respawn={checks[7]}, hits={scene.Hits}, recovered={scene.Recovered}, extra full player/target ticks={extraTicks}, energy={player.Energy:F3}/{initialEnergy:F3}."; + public static PlayerInput Input(int count)=>new(count==2,false,count==1,false,false,Fire:count is 1 or 2); + public static string? StageName(int count)=>count switch + {0=>"equipped",1=>"arm",2=>"aim",3=>"throw",4=>"flight",5=>"hit",6=>"unequip",7=>"respawn",_=>null}; +} diff --git a/src/GamePort/Application/BaseballVisuals.cs b/src/GamePort/Application/BaseballVisuals.cs new file mode 100644 index 0000000..cdcc4be --- /dev/null +++ b/src/GamePort/Application/BaseballVisuals.cs @@ -0,0 +1,125 @@ +using System.Numerics; +using System.Security.Cryptography; +using System.Text.Json; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// Source25-unit ball sprites. Camera-facing centered quads are a +/// declared port policy; frame selection belongs to source gameplay state. +public sealed class BaseballVisuals +{ + private readonly int[] offsets = new int[20]; + private readonly uint[] firstIndices = new uint[20]; + private readonly Dictionary textures = []; + public Mesh Mesh { get; } + + public BaseballVisuals(Mesh combined, string preparedRoot) + { + var resources = BaseballResourcePixels.Load(preparedRoot, "textures", BaseballResourcePixels.Balls); + var builder = new BaseballQuadBuilder(combined); + foreach (var (id, image) in resources.Where(p => p.Key is >= 2 and <= 5)) + textures.Add(id, builder.AddTexture(image)); + for (var i = 0; i < 20; i++) + (offsets[i], firstIndices[i]) = builder.AddQuad(textures[2], false); + Mesh = builder.Build(); + } + + public void Update(Mesh destination, IReadOnlyList balls, Vector3 eye, Vector3 target) + { + if (balls.Count > 20) throw new ArgumentException("Baseball source pool contains20 slots", nameof(balls)); + if (destination.Vertices.Length < offsets[^1] + 4) throw new ArgumentException("Destination omits Baseball vertices", nameof(destination)); + if (!Finite(eye) || !Finite(target)) throw new ArgumentException("Baseball camera must be finite"); + var direction = target - eye; + direction = direction.LengthSquared() < .000001f ? Vector3.UnitZ : Vector3.Normalize(direction); + var right = Vector3.Cross(Vector3.UnitY, direction); + right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right); + var up = Vector3.Normalize(Vector3.Cross(direction, right)); + var x = right * 12.5f; var y = up * 12.5f; + for (var i = 0; i < 20; i++) + { + var draw = destination.Draws.First(d => !d.ScreenSpace && d.FirstIndex == firstIndices[i] && d.IndexCount == 6); + draw.Visible = i < balls.Count && balls[i].Visible; + if (!draw.Visible) continue; + var ball = balls[i]; + if (!Finite(ball.Position)) throw new ArgumentException("Baseball position must be finite", nameof(balls)); + if (!textures.TryGetValue(ball.CanvasId, out var texture) || texture != draw.TextureId) + throw new InvalidDataException("Baseball frame differs from its fixed source canvas2"); + var p = ball.Position; var offset = offsets[i]; + destination.Vertices[offset] = new(p-x-y, new(0,1), Vector3.One); + destination.Vertices[offset+1] = new(p+x-y, new(1,1), Vector3.One); + destination.Vertices[offset+2] = new(p+x+y, new(1,0), Vector3.One); + destination.Vertices[offset+3] = new(p-x+y, new(0,0), Vector3.One); + } + } + + private static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z); +} + +internal static class BaseballResourcePixels +{ + internal static readonly Dictionary Balls = new() + { + [2]=(32,32,"68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9"), + [3]=(32,32,"005def070e18111fbdb067e75285dad8ec677c1608020f55c3db7a4b9745205c"), + [4]=(32,32,"c368a59d5d7a57824c1c6b56b617cf058f5d5d53e18e5e48989710413490c536"), + [5]=(32,32,"e5da21c359d3215759e5c3c238107f526f7109203c0ff9fa391a3c8bc40c17ed"), + [8]=(64,64,"8d31014cb9b9661ebed902c864bf740f562460e74da3f6b86ed3d2be4d10f0ec") + }; + + internal static Dictionary Load(string preparedRoot, string array, + IReadOnlyDictionary expected) + { + var manifest = Path.GetFullPath(Path.Combine(preparedRoot,"baseball/baseball.json")); + if (new FileInfo(manifest).Length > 256*1024) throw new InvalidDataException("Baseball manifest exceeds limit"); + using var document = JsonDocument.Parse(File.ReadAllBytes(manifest), new JsonDocumentOptions { MaxDepth=12 }); + var root = document.RootElement; + if (root.GetProperty("schema").GetInt32()!=1 || root.GetProperty(array).GetArrayLength()!=expected.Count) + throw new InvalidDataException("Unsupported Baseball resources"); + var directory = Path.GetDirectoryName(manifest)!; + var result = new Dictionary(); + foreach (var entry in root.GetProperty(array).EnumerateArray()) + { + var id = entry.GetProperty("id").GetInt32(); + if (!expected.TryGetValue(id,out var source) || result.ContainsKey(id) + || entry.GetProperty("width").GetInt32()!=source.Width || entry.GetProperty("height").GetInt32()!=source.Height + || entry.GetProperty("rgbaSha256").GetString()!=source.Hash) + throw new InvalidDataException("Invalid original Baseball canvas"); + var path = Path.GetFullPath(Path.Combine(directory,entry.GetProperty("path").GetString()!)); + if (!path.StartsWith(directory+Path.DirectorySeparatorChar,StringComparison.Ordinal) + || new FileInfo(path).Length != source.Width*source.Height*4) + throw new InvalidDataException("Invalid Baseball pixel path/length"); + var pixels = File.ReadAllBytes(path); + if (Convert.ToHexStringLower(SHA256.HashData(pixels))!=source.Hash) + throw new InvalidDataException("Baseball pixels differ from original canvas"); + result.Add(id,new((uint)source.Width,(uint)source.Height,pixels)); + } + return result; + } +} + +internal sealed class BaseballQuadBuilder(Mesh source) +{ + private readonly List vertices = source.Vertices.ToList(); + private readonly List indices = source.Indices.ToList(); + private readonly List draws = source.HasExplicitDraws ? source.Draws.ToList() + : source.Indices.Length == 0 ? [] : [new(0,(uint)source.Indices.Length,-1)]; + private readonly Dictionary textures = new(source.Textures); + internal int AddTexture(PngImage image) + { + var id=int.MinValue+17000; while(textures.ContainsKey(id))id++; + textures.Add(id,image); return id; + } + internal (int Offset,uint FirstIndex) AddQuad(int texture, bool screen) + { + var offset=vertices.Count; var first=(uint)indices.Count; var vertex=(uint)offset; + 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([vertex,vertex+1,vertex+2,vertex,vertex+2,vertex+3]); + draws.Add(new(first,6,texture){Visible=false,ScreenSpace=screen,Blend=MeshBlend.Alpha}); + return(offset,first); + } + internal Mesh Build() => new(vertices.ToArray(),indices.ToArray()) { HasExplicitDraws=true, Draws=draws.ToArray(), + Textures=textures, CollisionPolygons=source.CollisionPolygons, HasCollisionMaterialIds=source.HasCollisionMaterialIds }; +} diff --git a/src/GamePort/Application/DebugMenu.cs b/src/GamePort/Application/DebugMenu.cs index d463e36..1d87b04 100644 --- a/src/GamePort/Application/DebugMenu.cs +++ b/src/GamePort/Application/DebugMenu.cs @@ -8,7 +8,7 @@ public sealed record DebugScene(string LevelFile, string Code, string[] Starts); public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay, Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState, CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice, - GiveInvisible, UnequipGadget, GiveBubble } + GiveInvisible, UnequipGadget, GiveBubble, GiveBaseball } public sealed record DebugMenuView(string[] Lines, int SelectedLine); public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed, bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled, @@ -30,6 +30,7 @@ public sealed record DebugSystems public float InvisibleRecharge { get; init; } public bool Targetable { get; init; } = true; public string BubblePhase { get; init; } = "OFF"; + public string BaseballState { get; init; } = "OFF"; public float BodyRadius { get; init; } = 60; public float BodyFactor { get; init; } = 1.265f; public int Objective { get; init; } @@ -55,7 +56,7 @@ public sealed class DebugMenu public const int ItemCount = 12; public const int PageCount = 3; public int Page { get; private set; } - public int PageItems => Page switch { 1 => 13, 2 => 9, _ => ItemCount }; + public int PageItems => Page switch { 1 => 14, 2 => 9, _ => ItemCount }; private static readonly float[] FlySpeeds = [300, 600, 1200, 2400]; private int flySpeedIndex = 1, jetpackStateIndex = 1; private static readonly int[] JetpackStates = [0, 1, 4]; @@ -118,7 +119,8 @@ public sealed class DebugMenu 3 => DebugAction.ShowObjective, 4 => DebugAction.ReturnNoclipEntry, 5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder, 8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy, - 10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble, _ => DebugAction.None + 10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble, + 13 => DebugAction.GiveBaseball, _ => DebugAction.None }; if (Page == 2) return Selected switch { @@ -157,14 +159,15 @@ public sealed class DebugMenu : $"EFFECT BYTES {system.EffectBytes} AUDIO AVAILABLE {system.AudioAvailable}", $"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}", $"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}", - $"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", ""]; + $"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", + $"BASEBALL {system.BaseballState}", ""]; string[] items = Page == 1 ? [ $"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)", $"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE", "RETURN TO NOCLIP ENTRY POSITION", "APPLY THIS LEVEL'S GADGET AVAILABILITY", $"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)", $"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100", - "GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE"] : [ + "GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE", "GIVE / SELECT BASEBALL"] : [ $"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}", $"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}", "RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"]; diff --git a/src/GamePort/Application/SceneSpriteVisuals.cs b/src/GamePort/Application/SceneSpriteVisuals.cs index 53d8584..a5d0ba0 100644 --- a/src/GamePort/Application/SceneSpriteVisuals.cs +++ b/src/GamePort/Application/SceneSpriteVisuals.cs @@ -25,7 +25,7 @@ public sealed class SceneSpriteVisuals var textures = new Dictionary(combined.Textures); foreach (var actor in director.Actors) { - if (actor.Kind is not ("3PIC" or "3ANI") || actor.SourceGam is not { } source) continue; + if (actor.Kind is not ("3PIC" or "3ANI" or "3TAR") || actor.SourceGam is not { } source) continue; var database = source.Text("SpriteDatabase") ?? "none"; var identities = actor.Kind == "3ANI" ? Enumerable.Range(1, 9) .Select(i => source.Integer("Sprite" + i, -1)).TakeWhile(i => i >= 0).ToArray() diff --git a/src/GamePort/Game/BaseballGadget.cs b/src/GamePort/Game/BaseballGadget.cs new file mode 100644 index 0000000..49b3ad0 --- /dev/null +++ b/src/GamePort/Game/BaseballGadget.cs @@ -0,0 +1,138 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// Jimmy's raw6 aim/release state (42659F/426744). The twenty owned +/// projectiles survive unequip; this object is reset only with the modern scene. +/// Source evidence and precision boundaries: gameplay/baseball.md. +public sealed class BaseballGadget +{ + public const int PoolSize = 20; + private readonly BaseballProjectile[] projectiles = Enumerable.Range(0, PoolSize).Select(_ => new BaseballProjectile()).ToArray(); + public IReadOnlyList Projectiles => projectiles; + public bool Equipped { get; private set; } + public bool PendingThrow { get; private set; } + public bool AimVisible { get; private set; } + public float CameraPitch { get; private set; } = 10; + public float CameraHeight { get; private set; } = 200; + public float SavedPitch { get; private set; } + public float DisplayPitch { get; private set; } + public int NextSlot { get; private set; } + public int Throws { get; private set; } + public event Action? EquippedChanged; + public event Action? Thrown; + + public void Equip() + { + Equipped = true; + CameraHeight += 30; //429707..429713 complete7CC; cleanup resets its defaults. + EquippedChanged?.Invoke(true); + } + + public void Release() + { + Equipped = AimVisible = false; + CameraPitch = 0; + CameraHeight = 200; + //42871D does not write Jimmy1E26/1E28 or destroy its AB4 pool. + EquippedChanged?.Invoke(false); + } + + public void StepInput(PlayerInput input, Vector3 root, Vector3 euler, bool supported, + float energy, bool exempt, Action stop, Action shooting, Action adjustEnergy) + { + if (!input.Fire) + { + AimVisible = false; + shooting(false); + if (!PendingThrow) return; + Thrown?.Invoke(); //4265A9 requests10 before the launch virtual. + projectiles[NextSlot].Launch(root, euler, SavedPitch); + NextSlot = (NextSlot + 1) % PoolSize; + PendingThrow = false; + Throws++; + adjustEnergy(-1); + return; + } + if (!Equipped) return; + stop(); + if (energy <= 0 && !exempt || !supported) return; + shooting(true); + AimVisible = true; + DisplayPitch = SavedPitch; + if (!PendingThrow) + { + PendingThrow = true; + return; //First hold arms without refreshing the saved pitch. + } + CameraPitch = Math.Clamp(CameraPitch, 0, 45); + SavedPitch = CameraPitch; + } + + public void StepCameraInput(PlayerInput input) + { + if (!Equipped) { CameraPitch=10; return; } + if (!input.Fire) return; + if (input.Backward) CameraPitch -= 20 * FixedStepClock.Step; + else if (input.Forward) CameraPitch += 20 * FixedStepClock.Step; + } + + public void Reset() + { + if (Equipped) Release(); + PendingThrow = AimVisible = false; + CameraPitch = 10; SavedPitch = DisplayPitch = 0; + CameraHeight = 200; + NextSlot = Throws = 0; + foreach (var projectile in projectiles) projectile.Reset(); + } +} + +/// C3DBaseball owned pool entry. No invented ammo count or lifetime. +public sealed class BaseballProjectile +{ + public Vector3 Position { get; private set; } + public Vector3 PreviousPosition { get; private set; } + public Vector3 Velocity { get; private set; } + public Vector3 PendingImpulse { get; private set; } + public bool Supported { get; private set; } + public bool Visible { get; private set; } + public int CanvasId => 2; //40FB50 initializes2; a sequence caller is not recovered. + public int Landings { get; private set; } + + public void Launch(Vector3 root, Vector3 euler, float pitch) + { + if (!float.IsFinite(root.X + root.Y + root.Z + euler.X + euler.Y + euler.Z + pitch) + || pitch < 0 || pitch > 45) throw new ArgumentOutOfRangeException(nameof(pitch)); + //384/38C use the player's full local transform. This bridge matches the + //port's recovered Bubble Euler convention; generic original Euler remains + //a declared precision/ownership boundary. Upright yaw is the tested path. + var rotation = Matrix4x4.CreateRotationZ(-euler.Z * MathF.PI / 180) + * Matrix4x4.CreateRotationX(-euler.X * MathF.PI / 180) + * Matrix4x4.CreateRotationY(-euler.Y * MathF.PI / 180); + Position = root + Vector3.Transform(new Vector3(0, 80, 50), rotation); + var direction = Vector3.Transform(new Vector3(0, pitch * .02222222276031971f, 1), rotation); + Velocity = direction / OriginalBodySupport.QuickMagnitude(direction) * 1800; + //429A30 does not clear a reused entry's impulse/support state. + PreviousPosition = Position; + Visible = true; + } + + public void Step(OriginalBodyPhysics physics, float seconds) + { + if (!Visible) return; + PreviousPosition = Position; + var result = physics.Step(new(Position, Velocity, Vector3.Zero, PendingImpulse, Supported), seconds, + radius: 15, factor: 1, friction: .46f, profile: BodyResponseProfile.Baseball); + Position = result.Body.Position; Velocity = result.Body.Velocity; + PendingImpulse = result.Body.Impulse; Supported = result.Body.Supported; + if (result.Landing != null) Landings++; + } + + public void Hide() => Visible = false; //Source disables integration/pairs and hides, retaining body state. + public void Reset() + { + Visible=Supported=false; Position=PreviousPosition=Velocity=PendingImpulse=Vector3.Zero; + Landings=0; + } +} diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index 59725b1..5e149cb 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -41,6 +41,7 @@ public sealed class LabSimulation public string LevelCode { get; set; } = "LV1B"; public InvisibleGadget Invisible { get; } = new(); public BubbleEffect Bubble { get; } = new(); + public BaseballGadget Baseball { get; } = new(); public PlayerAppearance Appearance { get; } = new(); public Vr01FloorState FloorState { get; } = new(); public Vector3 BubbleRoot { get; private set; } @@ -58,6 +59,7 @@ public sealed class LabSimulation var previousPose=Pose; if (gadgetMode == 0) ReleaseBubble(); if (gadgetMode == 2) Invisible.Release(); + if (gadgetMode == 6) Baseball.Release(); gadgetMode = -1; if (value == 0) { @@ -70,6 +72,7 @@ public sealed class LabSimulation return; } if (value == 2 && !Invisible.Equip(Energy, IgnoresGadgetEnergy)) return; + if (value == 6) Baseball.Equip(); gadgetMode = value; } } @@ -124,7 +127,7 @@ public sealed class LabSimulation public Func? DynamicRootResolver { get; set; } public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight; public Vector3 CameraEye { get; private set; } - public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0); + public Vector3 CameraTarget => ActorRoot + new Vector3(0, 80 + 1.9f * Baseball.CameraPitch, 0); public Matrix4x4 Model => Matrix4x4.CreateRotationZ(-(TracksBubbleOrientation?Roll:0) * MathF.PI / 180) * Matrix4x4.CreateRotationX(-(TracksBubbleOrientation?Pitch:0) * MathF.PI / 180) * Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180) * Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0)); @@ -141,6 +144,7 @@ public sealed class LabSimulation this.energy = energy ?? new PlayerEnergy(); Invisible.AlphaRequested += Appearance.SetAlpha; Invisible.BlendRequested += Appearance.SetBlend; + Baseball.Thrown += () => GadgetSound?.Invoke(10,false); sourceStart = start; startYaw = yaw; var bounds = standingPose.Bounds(); @@ -161,6 +165,8 @@ public sealed class LabSimulation if (gadgetMode == 0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); } if (gadgetMode == 2) gadgetMode = -1; Invisible.Reset(); + Baseball.Reset(); + if (gadgetMode == 6) gadgetMode = -1; Bubble.Reset(); FloorState.Reset(); Appearance.Reset(); retainedSupportMaterial=null; Pitch=Roll=targetPitch=targetRoll=0; BubbleBounces=0; TracksBubbleOrientation=false; @@ -404,6 +410,7 @@ public sealed class LabSimulation //438011..43802B adds the independent turn rate directly to yaw. targetYaw = Yaw; } + Baseball.StepCameraInput(input); StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state. if (movementMode==2) { @@ -415,6 +422,8 @@ public sealed class LabSimulation BubbleRoot=ActorRoot+Vector3.UnitY*50-direction*80; } InputActions?.Invoke(input); + Baseball.StepInput(input,ActorRoot,new(Pitch,Yaw,Roll),Grounded,Energy,IgnoresGadgetEnergy, + StopForPrimaryFire,SetShooting,AdjustEnergy); } private void StepPlayer(PlayerInput input) @@ -541,7 +550,7 @@ public sealed class LabSimulation private (Vector3 Eye, float Gain) DesiredEye() { var (sin, cos) = Trig(Yaw); - var eye = ActorRoot + new Vector3(sin * 350, 180, -cos * 350); + var eye = ActorRoot + new Vector3(sin * 350, Baseball.CameraHeight - 2 * Baseball.CameraPitch, -cos * 350); if (Noclip) return (eye, 1); // Debug exploration also bypasses camera obstruction. if (cameraRay == null) return (collision.ClipCamera(CameraTarget, eye), 1); //43B820: query from the computed look target; first accepted static hit diff --git a/src/GamePort/Game/OriginalBodyPhysics.cs b/src/GamePort/Game/OriginalBodyPhysics.cs index c925005..52cd0f2 100644 --- a/src/GamePort/Game/OriginalBodyPhysics.cs +++ b/src/GamePort/Game/OriginalBodyPhysics.cs @@ -13,6 +13,8 @@ public readonly record struct OrdinaryBodyStep(OrdinaryBodyState Body, Vector3 P Vector3 SupportAnchor, SupportHit? SupportHit, BodyLandingObservation? Landing, CameraRayPolygon? Contact, int CollisionPasses, int TriangleTests); +public enum BodyResponseProfile { Jimmy, Baseball } + /// /// Bounded479D20 composition: enabled integration/support/pairs/static flags, /// prevent-lowering true, ordinary Jimmy370/374/37C and no dynamic body pass. @@ -26,10 +28,10 @@ public sealed class OriginalBodyPhysics { private readonly OriginalStaticCollision collision; - public OriginalBodyPhysics(OriginalStaticCollision collision) + public OriginalBodyPhysics(OriginalStaticCollision collision, bool allowSpecialMaterials = false) { ArgumentNullException.ThrowIfNull(collision); - if (collision.HasSpecialPlayerContacts) + if (collision.HasSpecialPlayerContacts && !allowSpecialMaterials) throw new NotSupportedException("Ordinary body composition requires recovered special-contact policies for this scene"); this.collision = collision; } @@ -38,7 +40,8 @@ public sealed class OriginalBodyPhysics public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds, float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor, - float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true) + float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true, + BodyResponseProfile profile = BodyResponseProfile.Jimmy) { Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse); Finite(body.AngularVelocity); Finite(body.Rotation); @@ -77,6 +80,21 @@ public sealed class OriginalBodyPhysics if (velocity.Y > 0) velocity.Y = 0; if (acceleration.Y > 0) acceleration.Y = 0; } + else if (profile == BodyResponseProfile.Baseball && move.CallbackPolygon is { } wall) + { + //40FEE0 ->458890 ->472750: reflect horizontal direction, keep Y, + //then damp horizontal components by1-.46. Its angular tail does not + //change position/velocity; sprite/Euler side effects remain separate. + var horizontal = velocity with {Y=0}; + var magnitude = OriginalBodySupport.QuickMagnitude(horizontal); + if (magnitude > 0) + { + var direction = horizontal / magnitude; + var reflected = direction - 2 * Vector3.Dot(direction, wall.StoredNormal) * wall.StoredNormal; + velocity = new(reflected.X * magnitude * (1-.46f), velocity.Y, + reflected.Z * magnitude * (1-.46f)); + } + } var position = move.Position; if (horizontalFirst) position.Y += delta.Y; position.Y = MathF.Max(position.Y, -25000); @@ -86,13 +104,21 @@ public sealed class OriginalBodyPhysics BodyLandingObservation? landing = null; if (geometryEnabled) { - var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor), + var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor, + PreventLowering: profile == BodyResponseProfile.Jimmy), wasSupported, (start, end, sides) => collision.TraceSupport(start, end, sides)); if (support.Supported) { //37C observes new root/zero acceleration but old velocity/support. //Jimmy's inherited37C is a no-op; the observation is diagnostic. - if (support.Landed) landing = new(support.Body.Position, velocity, support.Body.Acceleration, false); + if (support.Landed) + { + landing = new(support.Body.Position, velocity, support.Body.Acceleration, false); + //40FF80 receives old live velocity after root/acceleration + //publication and writes impulse288, before support zeros Y. + if (profile == BodyResponseProfile.Baseball) + body = body with {Impulse = new(velocity.X, velocity.Y * -.65f, velocity.Z)}; + } body = body with { Position = support.Body.Position, Velocity = support.Body.Velocity, Acceleration = support.Body.Acceleration, Supported = true }; anchor = support.SupportAnchor; diff --git a/src/GamePort/Game/OriginalCameraRay.cs b/src/GamePort/Game/OriginalCameraRay.cs index 125c8ed..17764a7 100644 --- a/src/GamePort/Game/OriginalCameraRay.cs +++ b/src/GamePort/Game/OriginalCameraRay.cs @@ -65,7 +65,7 @@ public sealed class OriginalCameraRay public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode) { ArgumentNullException.ThrowIfNull(mesh); - if (levelCode is not ("LV1B" or "VR01" or "VR04" or "LEV1")) + if (levelCode is not ("LV1B" or "VR01" or "VR04" or "VR07" or "LEV1")) throw new NotSupportedException("Static camera game-filter recovery covers the route and VR01"); if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) throw new InvalidDataException("Original camera query requires source polygon metadata"); diff --git a/src/GamePort/Game/OriginalStaticCollision.cs b/src/GamePort/Game/OriginalStaticCollision.cs index ed02e4c..b1ce786 100644 --- a/src/GamePort/Game/OriginalStaticCollision.cs +++ b/src/GamePort/Game/OriginalStaticCollision.cs @@ -61,7 +61,7 @@ public sealed class OriginalStaticCollision public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level) { ArgumentNullException.ThrowIfNull(mesh); - if (level is not ("LV1B" or "VR01" or "VR04" or "LEV1")) + if (level is not ("LV1B" or "VR01" or "VR04" or "VR07" or "LEV1")) throw new NotSupportedException("Original static game-filter recovery covers the route and VR01"); if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) throw new InvalidDataException("Source static collision requires original polygon metadata"); diff --git a/src/GamePort/Game/PlayerSceneBinding.cs b/src/GamePort/Game/PlayerSceneBinding.cs index 15e3c5c..36a659c 100644 --- a/src/GamePort/Game/PlayerSceneBinding.cs +++ b/src/GamePort/Game/PlayerSceneBinding.cs @@ -20,6 +20,7 @@ public sealed class PlayerSceneBinding : IDisposable director.GadgetReleaseRequested += Release; inventory.GadgetSelected += Selected; player.Invisible.EquippedChanged += InvisibleEquipped; + player.Baseball.EquippedChanged += BaseballEquipped; player.DefaultGadgetRequested += DefaultGadget; Selected(inventory.SelectedGadget); } @@ -49,7 +50,7 @@ public sealed class PlayerSceneBinding : IDisposable if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return; //427FF0 switches raw mode, not display selection. A rejected Invisible //equip can leave display2 with raw mode-1; cleanup does not equip it. - if (player.GadgetMode is 0 or 2 || inventory.SelectedGadget is -1 or 3) + if (player.GadgetMode is 0 or 2 or 6 || inventory.SelectedGadget is -1 or 3) { inventory.SelectGadget(-1); player.GadgetMode = -1; } else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++; } @@ -70,6 +71,13 @@ public sealed class PlayerSceneBinding : IDisposable companion.Visible = companion.MovementEnabled = companion.BodyEnabled = !equipped; } + private void BaseballEquipped(bool equipped) + { + //Raw6 cleanup42871D has no Invisible's complete9E8 restoration veto. + if(director.FindActor("C3DGODDARD") is {} companion) + companion.Visible=companion.MovementEnabled=companion.BodyEnabled=!equipped; + } + private void Transform(DirectorActor actor) { if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) @@ -83,6 +91,7 @@ public sealed class PlayerSceneBinding : IDisposable director.GadgetReleaseRequested -= Release; inventory.GadgetSelected -= Selected; player.Invisible.EquippedChanged -= InvisibleEquipped; + player.Baseball.EquippedChanged -= BaseballEquipped; player.DefaultGadgetRequested -= DefaultGadget; } } diff --git a/src/GamePort/Game/SceneBaseballs.cs b/src/GamePort/Game/SceneBaseballs.cs new file mode 100644 index 0000000..196eae3 --- /dev/null +++ b/src/GamePort/Game/SceneBaseballs.cs @@ -0,0 +1,149 @@ +using System.Numerics; +using GamePort.Assets; + +namespace GamePort.Game; + +/// Owned Baseball bodies and source3TAR callbacks. Pair discovery uses +/// a bounded sphere-overlap adapter; original pair scheduling remains unported. +public sealed class SceneBaseballs +{ + private readonly LabSimulation player; + private readonly OriginalBodyPhysics physics; + private readonly SceneDirector director; + private readonly Dictionary parentHits = []; + public IReadOnlyList Targets { get; } + public int Hits { get; private set; } + public int Recovered { get; private set; } + public event Action? Sound; + public event Action? ScoreAwarded; + + public SceneBaseballs(SceneDirector director, LabSimulation player, Mesh world) + { + this.director=director; this.player=player; + physics=new(OriginalStaticCollision.FromRouteScene(world,player.LevelCode),allowSpecialMaterials:true); + Targets=director.Actors.Where(a=>a.Kind=="3TAR").Select(a=>new MovingBaseballTarget(a)).ToArray(); + InitializeTrophyContacts(); + } + + public void StepBodies(float seconds) + { + foreach(var target in Targets) target.StepBody(seconds); + foreach(var ball in player.Baseball.Projectiles) + { + ball.Step(physics,seconds); + if(!ball.Visible) continue; + //This modern discovery adapter supplies real source callback rules. + //It does not claim original47A580 pair ordering or swept contacts. + foreach(var target in Targets) + if(target.Actor.BodyEnabled && Vector3.DistanceSquared(ball.Position,target.Actor.Position)<90*90 + && target.Hit()) + { + Hits++; ScoreAwarded?.Invoke(target.Points); + ActivateParent(target); + } + if(Vector3.DistanceSquared(ball.Position,player.ActorRoot)<(15+player.InteractionRadius)*(15+player.InteractionRadius)) + { ball.Hide(); Recovered++; } + } + } + + public void StepTargets(float seconds) + { + foreach(var target in Targets) target.StepFrame(seconds); + } + + private void ActivateParent(MovingBaseballTarget target) + { + var parent=director.FindActor(target.ActivateObject); + if(parent==null) { Sound?.Invoke(198); return; } + if(parent.Kind is not ("3TRO" or "3PIC")) return; + var count=parentHits.GetValueOrDefault(parent)+1; + if(count>target.HitsRequired) + { + parentHits[parent]=0; + //The source invokes parent428(1), not the trigger interpreter. + parent.Visible=true; + if(parent.SourceGam?.Integer("HasCollision",-1)!=0)parent.BodyEnabled=true; + Sound?.Invoke(199); + } + else parentHits[parent]=count; + } + + public void Reset() + { + Hits=Recovered=0; parentHits.Clear(); + foreach(var target in Targets) target.Reset(); + InitializeTrophyContacts(); + } + + private void InitializeTrophyContacts() + { + if(player.LevelCode!="VR07")return; + foreach(var trophy in director.Actors.Where(a=>a.Kind=="3TRO")) + trophy.BodyEnabled=trophy.Visible && trophy.SourceGam?.Integer("HasCollision",-1)!=0; + } +} + +/// Factory45CA06's C3DMOVINGTARGET, not Jimmy's C3DTarget helper. +public sealed class MovingBaseballTarget +{ + public DirectorActor Actor { get; } + private readonly Vector3 initial; + private readonly bool initialVisible; + public Vector3 Start { get; } + public Vector3 Destination { get; } + public Vector3 Velocity { get; private set; } + public float Speed { get; } + public float Remaining { get; private set; } + public float RespawnTime { get; } + public int Points { get; } + public int HitsRequired { get; } + public string ActivateObject { get; } + + public MovingBaseballTarget(DirectorActor actor) + { + Actor=actor; + if(actor.Kind!="3TAR" || actor.SourceGam is not {} source) + throw new ArgumentException("Moving target needs its actual source entity",nameof(actor)); + initial=actor.Position; + initialVisible=actor.Visible; + Start=new(source.Number("StartPosX"),source.Number("StartPosY"),source.Number("StartPosZ")); + Destination=new(source.Number("DestPosX"),source.Number("DestPosY"),source.Number("DestPosZ")); + Speed=source.Number("Speed",100); RespawnTime=source.Number("RespawnTime",15); + Points=source.Integer("NumPoints",10); HitsRequired=source.Integer("HitsRequired",5); + ActivateObject=source.Text("ActivateObject")??"none"; + } + + public void StepBody(float seconds) + { + if(!Actor.BodyEnabled) return; + //Source target disables world response and support. Preserve the common + //integrate-before-frame partial order. Full registry/global-flag timing + //remains a separate boundary; this is not a new general actor scheduler. + Velocity+=RecoveredMotion.Gravity*seconds; + Actor.Position+=Velocity*seconds; + } + + public void StepFrame(float seconds) + { + if(!float.IsFinite(seconds)||seconds<0||seconds>=1)throw new ArgumentOutOfRangeException(nameof(seconds)); + if(Remaining>0) + { + Remaining-=seconds; + if(Remaining<=0) { Remaining=0; Actor.Visible=true; } + } + var delta=Destination-Actor.Position; + var distance=delta.Length(); //Source tests ordinary sqrt distance, normalizes with quick magnitude. + var magnitude=OriginalBodySupport.QuickMagnitude(delta); + Velocity=magnitude>0?delta/magnitude*Speed:Vector3.Zero; + if(distance<100) Actor.Position=Start; //430826 teleports to Start, it does not exchange endpoints. + } + + public bool Hit() + { + if(Remaining>0) return false; + Actor.Visible=false; Remaining=RespawnTime; + return true; + } + + public void Reset() { Actor.Position=initial; Actor.Visible=initialVisible; Velocity=Vector3.Zero; Remaining=0; } +} diff --git a/src/GamePort/Game/SceneInteractions.cs b/src/GamePort/Game/SceneInteractions.cs index a045991..04f9806 100644 --- a/src/GamePort/Game/SceneInteractions.cs +++ b/src/GamePort/Game/SceneInteractions.cs @@ -96,7 +96,8 @@ public sealed class SceneInteractions } // Carl InitObject413E2F..45 sets radius100 and support factor0.75. var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius")); - var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius; + var overlaps = actor.Active && (source.Kind!="3TRO" || actor.BodyEnabled) + && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius; if (!overlaps) { contacts.Remove(source.Offset); continue; } if (!contacts.Add(source.Offset)) continue; switch (source.Kind) diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index 7a63423..c969414 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -88,6 +88,7 @@ internal static class Program --smoke-jetpack 300-step powered steering/jump check in VR04 --smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture --smoke-invisible Accelerated recharge/activation/flash/expiry/unequip fixture in VR03 + --smoke-baseball VR07 aim/release/flight/target/respawn fixture --smoke-bubble VR01 expand/throttle/bounce/cleanup/fade input 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) @@ -260,6 +261,7 @@ internal static class Program var shrinkSmoke = args.Contains("--smoke-shrink-ray"); var invisibleSmoke = args.Contains("--smoke-invisible"); var bubbleSmoke = args.Contains("--smoke-bubble"); + var baseballSmoke = args.Contains("--smoke-baseball"); var carlSmoke = args.Contains("--smoke-carl-cutscene"); var controlPhaseSmoke = args.Contains("--smoke-control-phases"); var objectiveWindowSmoke = args.Contains("--smoke-objective-window"); @@ -280,7 +282,7 @@ internal static class Program var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") && animationPath == null && !args.Contains("--time"); var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time") - || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; + || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window"))) throw new ArgumentException("Story playback requires its own simulation mode."); if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode."); @@ -310,6 +312,9 @@ internal static class Program ShrinkSoldierVisuals? soldierVisuals = null; JetpackVisuals? jetpackVisuals = null; BubbleVisuals? bubbleVisuals = null; + SceneBaseballs? baseballs = null; + BaseballVisuals? baseballVisuals = null; + BaseballAimOverlay? baseballAim = null; var practice = new PracticePrompt(); ObjectivePanel? objectivePanel = null; var patrols = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -338,13 +343,13 @@ internal static class Program var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase")); if (walking) { - var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "LEV1" + var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "VR07" or "LEV1" ? OriginalCameraRay.FromRouteScene(world, level.Code) : null; debugCameraRay = cameraRay; simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y, cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye), cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end), - level.Code is "VR01" or "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy) + level.Code is "VR01" or "VR04" or "VR07" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy) { LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null }; if (carriedPlayer != null) { @@ -389,6 +394,11 @@ internal static class Program gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world); gadgets.ScoreAwarded += interactions.ChangeScore; } + if(level.Code is "LV1B" or "VR01" or "VR04" or "VR07" or "LEV1") + { + baseballs=new(director,simulation,world); + baseballs.ScoreAwarded+=interactions.ChangeScore; + } mechanisms = new SceneMechanisms(director); interactions.Transition += RequestTransition; interactions.PracticeRequested += practice.Show; @@ -445,6 +455,8 @@ internal static class Program mesh = jetpackVisuals.Mesh; bubbleVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,".."))); mesh = bubbleVisuals.Mesh; + baseballVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,".."))); + mesh = baseballVisuals.Mesh; if (gadgets != null) { rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root); @@ -454,6 +466,8 @@ internal static class Program mesh = hud.Mesh; invisibleMeter = new InvisibleMeterOverlay(mesh,Path.Combine(Path.GetDirectoryName(scene!)!,"../invisible-meter/meter.json")); mesh = invisibleMeter.Mesh; + baseballAim = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,".."))); + mesh = baseballAim.Mesh; gadgetOverlay = new GadgetMenuOverlay(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../gadgets/gadgets.json")); mesh = gadgetOverlay.Mesh; Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}."); @@ -486,7 +500,7 @@ internal static class Program var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); - var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke || bubbleSmoke ? "8" : gadgetWindowSmoke ? "24" : 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" : invisibleSmoke || bubbleSmoke || baseballSmoke ? "8" : 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)) @@ -495,6 +509,8 @@ internal static class Program throw new ArgumentException("Invisible smoke requires a fresh VR03 and at least8 frames"); if (bubbleSmoke && (level?.Code!="VR01" || frames<8 || loadedSave!=null)) throw new ArgumentException("Bubble smoke requires a fresh VR01 and at least8 frames"); + if(baseballSmoke && (level?.Code!="VR07" || frames<8 || loadedSave!=null)) + throw new ArgumentException("Baseball fixture requires a fresh VR07 and at least8 frames"); if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null)) throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames"); if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) @@ -529,6 +545,8 @@ internal static class Program var sawShrinkKey = false; InvisibleSmoke? invisibleFixture = null; BubbleSmoke? bubbleFixture = null; + BaseballSmoke? baseballFixture = null; + var sawBaseballKeys=0; var sawBubbleKeys=0; 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}."); { @@ -541,6 +559,7 @@ internal static class Program simulation.GadgetSound += (id,loop) => sceneAudio?.Effect(id,loop?"bubble":null); simulation.BubbleSoundStopped += () => sceneAudio?.StopLoop("bubble"); } + if(baseballs!=null)baseballs.Sound+=id=>sceneAudio?.Effect(id); if (gadgets != null) { gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null); @@ -568,6 +587,7 @@ internal static class Program } director.Begin(originalStart!, activateStartTrigger: !returning); gadgets?.Reset(); + baseballs?.Reset(); interactions!.Reset(); mechanisms!.Reset(); director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0)); @@ -583,7 +603,7 @@ internal static class Program Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}."); if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions"); } - if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } + if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); } if (controlPhaseSmoke) { @@ -664,6 +684,7 @@ internal static class Program gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE")); } if (invisibleSmoke) invisibleFixture = new(simulation!,interactions!.Inventory); + if(baseballSmoke)baseballFixture=new(simulation!,playerBinding!,interactions!.Inventory,baseballs!,director); if (bubbleSmoke) bubbleFixture = new(simulation!,interactions!.Inventory); if (shrinkSmoke) { @@ -756,7 +777,7 @@ internal static class Program if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; } if (practice.Active) practice.Key(17, Vector2.Zero); simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!); - interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); mouseFire = false; + interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); baseballs?.Reset(); mouseFire = false; director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); } void ToggleCamera() @@ -843,6 +864,10 @@ internal static class Program debugMenu.Message = simulation?.GadgetMode==0 ? "BUBBLE EQUIPPED - FIRE/UP ACCELERATES, JUMP BOUNCES HIGH" : simulation?.Bubble.Collapsing==true ? "WAIT FOR THE BUBBLE TO FADE BEFORE REEQUIPPING" : "ENERGY REQUIRED TO EQUIP"; break; + case DebugAction.GiveBaseball when interactions != null: + interactions.Inventory.SetState(0,6,1); interactions.Inventory.SelectGadget(6); + debugMenu.Message="BASEBALL EQUIPPED - HOLD FIRE, UP/DOWN AIM, RELEASE TO THROW"; + break; case DebugAction.CameraObstruction when debugCameraRay != null: debugCameraRay.Enabled = !debugCameraRay.Enabled; debugMenu.Message = "STATIC CAMERA QUERY TOGGLED"; break; case DebugAction.MuteMusic or DebugAction.MuteSpeech or DebugAction.MuteEffects when sceneAudio != null: @@ -908,6 +933,11 @@ internal static class Program } while (running) { + baseballFixture?.BeforeFrame(count,(key,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); + },headless); bubbleFixture?.BeforeFrame(count,(key,down)=> { var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0}; @@ -964,6 +994,8 @@ internal static class Program } while (!headless && Sdl.SDL_PollEvent(out var e)) { + if(baseballSmoke && e.Type==Sdl.KeyDown) + sawBaseballKeys|=e.Scancode switch{224=>1,80=>2,82=>4,43=>8,_=>0}; if (bubbleSmoke && e.Type==Sdl.KeyDown) sawBubbleKeys |= e.Scancode switch {224=>1,80=>2,225=>4,43=>8,_=>0}; if (e.Type is Sdl.Quit or 0x210) running = false; @@ -1090,12 +1122,13 @@ internal static class Program } } if (debugMenu.Open) animationStarted += elapsed; - if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke)) + if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke)) { - var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); + var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); for (var step = 0; step < steps; step++) { var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true) + : baseballSmoke && headless ? BaseballSmoke.Input(count) : bubbleSmoke && headless ? BubbleSmoke.Input(count) : invisibleSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:count==1) : shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true) @@ -1107,12 +1140,14 @@ internal static class Program 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); + baseballs?.StepBodies(FixedStepClock.Step); var before = simulation.Position; var powered = simulation.JetpackEffectVisible && !simulation.Grounded; bool acceptsInput; if (playerBinding != null) acceptsInput = playerBinding.Step(input); else { simulation.Step(input); acceptsInput = true; } gadgets?.StepTimers(FixedStepClock.Step); + baseballs?.StepTargets(FixedStepClock.Step); if (jetpackSmoke && powered) { poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); @@ -1179,6 +1214,8 @@ internal static class Program if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase; jetpackVisuals?.Update(mesh, simulation!); bubbleVisuals?.Update(mesh,simulation!.Bubble,simulation.BubbleRoot,renderEye,renderTarget); + baseballVisuals?.Update(mesh,simulation!.Baseball.Projectiles,renderEye,renderTarget); + baseballAim?.Update(mesh,simulation!.Baseball,renderer.Width,renderer.Height); spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh); objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && director is { Controlled: true, InventoryEnabled: true }); @@ -1211,6 +1248,7 @@ internal static class Program Targetable = simulation?.Invisible.Targetable ?? true, BubblePhase = simulation?.Bubble.Active==true ? "ACTIVE" : simulation?.Bubble.Expanding==true ? "EXPAND" : simulation?.Bubble.Collapsing==true ? "FADE" : "OFF", + BaseballState=simulation==null?"OFF":$"{(simulation.Baseball.Equipped?"ON":"OFF")} AIM {simulation.Baseball.SavedPitch:F1} PENDING {simulation.Baseball.PendingThrow} THROWS {simulation.Baseball.Throws}", BodyRadius = simulation?.InteractionRadius ?? 60, BodyFactor=simulation?.BodyFactor ?? 1.265f, Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0, CameraObstruction = debugCameraRay?.Enabled, CameraPolygons = debugCameraRay?.PolygonCount ?? 0, @@ -1249,6 +1287,12 @@ internal static class Program } renderer.UpdateVertices(mesh.Vertices); renderer.Render(view * projection); + if(baseballFixture!=null) + { + baseballFixture.AfterFrame(count); + if(BaseballSmoke.StageName(count) is{} stage && Option(args,"--screenshot") is{} capture) + renderer.SavePpm(Path.ChangeExtension(capture,$".{stage}.ppm")); + } if (bubbleFixture!=null) { bubbleFixture.AfterFrame(count); @@ -1529,6 +1573,12 @@ internal static class Program if (!headless) Console.WriteLine($"Invisible SDL primary received: {sawShrinkKey}."); if (!invisibleFixture.Passed || !headless && !sawShrinkKey) return 2; } + if(baseballFixture!=null) + { + Console.WriteLine(baseballFixture.Report); + if(!headless)Console.WriteLine($"Baseball SDL keys received: {sawBaseballKeys==15}."); + if(!baseballFixture.Passed || !headless && sawBaseballKeys!=15)return 2; + } if (bubbleFixture!=null) { Console.WriteLine(bubbleFixture.Report); diff --git a/tests/GamePort.BaseballTests/GamePort.BaseballTests.csproj b/tests/GamePort.BaseballTests/GamePort.BaseballTests.csproj new file mode 100644 index 0000000..7ee881f --- /dev/null +++ b/tests/GamePort.BaseballTests/GamePort.BaseballTests.csproj @@ -0,0 +1,6 @@ + + Exenet10.0 + enableenablefalse + + + diff --git a/tests/GamePort.BaseballTests/Program.cs b/tests/GamePort.BaseballTests/Program.cs new file mode 100644 index 0000000..f5f8223 --- /dev/null +++ b/tests/GamePort.BaseballTests/Program.cs @@ -0,0 +1,141 @@ +using System.Numerics; +using System.Text; +using System.Buffers.Binary; +using GamePort.Game; +using GamePort.Assets; + +var count=0; +void Check(bool value,string message){if(!value)throw new Exception(message);} +void Near(float a,float b,string message)=>Check(MathF.Abs(a-b)<.02f,$"{message}: {a} != {b}"); +void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");} +void Hold(BaseballGadget device,bool down=false,bool up=false,float energy=20,bool supported=true) +{ + var input=new PlayerInput(down,up,false,false,false,Fire:true); + device.StepCameraInput(input); + device.StepInput(input,Vector3.Zero,Vector3.Zero,supported,energy,false,()=>{},_=>{},_=>{}); +} +void Release(BaseballGadget device,Action? cost=null)=>device.StepInput(default,Vector3.Zero,Vector3.Zero,false,0,false,()=>{},_=>{},cost??(_=>{})); +Mesh Floor()=>new([new(new(-4000,0,-4000),Vector2.Zero,Vector3.One),new(new(4000,0,-4000),Vector2.Zero,Vector3.One), + new(new(4000,0,4000),Vector2.Zero,Vector3.One),new(new(-4000,0,4000),Vector2.Zero,Vector3.One)], [0,1,2,0,2,3]) + {HasCollisionMaterialIds=true,CollisionPolygons=[new(0,0,Vector3.UnitY,"floor","floor",0),new(0,1,Vector3.UnitY,"floor","floor",0)]}; +Test("first hold arms, next captures pitch, label retains prior capture",()=>{ + var g=new BaseballGadget();g.Equip();Hold(g,true); + Check(g.PendingThrow&&g.AimVisible&&g.SavedPitch==0,"first hold arms only"); + Hold(g,true);Near(g.SavedPitch,10+2f/3,"camera pitch");Check(g.DisplayPitch==0,"first numeric label precedes capture"); + var old=g.SavedPitch;Hold(g,true);Check(g.DisplayPitch==old&&g.SavedPitch>old,"stored label order"); + for(var i=0;i<200;i++)Hold(g,true);Check(g.SavedPitch==45,"upper clamp"); + for(var i=0;i<200;i++)Hold(g,up:true);Check(g.SavedPitch==0,"lower clamp"); +}); +Test("release launches once with sound before fixed energy debit",()=>{ + var g=new BaseballGadget();g.Equip();Hold(g);Hold(g);var order=new List();g.Thrown+=()=>{ + Check(g.PendingThrow&&!g.Projectiles[0].Visible,"sound callback precedes launch and pending clear");order.Add("sound");}; + Release(g,cost=>{Check(cost==-1,"fixed cost");order.Add("cost");});Release(g); + Check(order.SequenceEqual(new[]{"sound","cost"})&&g.Throws==1&&!g.PendingThrow,"one release transaction"); + Check(g.Projectiles[0].Visible&&g.NextSlot==1,"first owned pool slot"); +}); +Test("pending throw survives cleanup and can release at zero energy",()=>{ + var g=new BaseballGadget();g.Equip();Hold(g);Hold(g,true);var saved=g.SavedPitch;g.Release(); + Check(g.PendingThrow&&!g.AimVisible&&g.CameraPitch==0&&g.SavedPitch==saved,"source cleanup scalar ownership"); + Release(g);Check(g.Throws==1&&g.Projectiles[0].Visible,"release predicate has no fresh energy or raw-mode gate"); +}); +Test("twenty reused slots, no invented ammo or lifetime",()=>{ + var g=new BaseballGadget();g.Equip(); + for(var i=0;i<23;i++){Hold(g);Release(g);} + Check(g.Throws==23&&g.NextSlot==3&&g.Projectiles.Count==20&&g.Projectiles.All(b=>b.Visible),"fixed wraparound pool"); + g.Release();Check(g.Projectiles.All(b=>b.Visible),"unequip retains helper bodies"); + g.Reset();Check(g.Throws==0&&g.Projectiles.All(b=>!b.Visible),"modern new scene clears port-owned pool"); +}); +Test("upright launch offset, quick-normalized speed and45-degree slope",()=>{ + var ball=new BaseballProjectile();ball.Launch(new(100,200,300),Vector3.Zero,45); + Check(ball.Position==new Vector3(100,280,350),"local80/50 offset");Near(ball.Velocity.Y/ball.Velocity.Z,1,"slope45/45"); + Near(OriginalBodySupport.QuickMagnitude(ball.Velocity),1800,"published speed"); + ball.Launch(Vector3.Zero,new(0,90,0),0);Near(ball.Position.X,-50,"rotated offset");Near(ball.Velocity.X,-1800,"yaw90 velocity"); +}); +Test("landing queues old horizontal velocity and-.65Y before support clearsY",()=>{ + var physics=new OriginalBodyPhysics(OriginalStaticCollision.FromRouteScene(Floor(),"VR07")); + var result=physics.Step(new(new(0,16,0),new(60,-120,0),Vector3.Zero,Vector3.Zero),1f/60, + radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball); + Check(result.Landing!=null&&result.Body.Supported&&result.Body.Velocity.Y==0,"landing and liveY reset"); + Near(result.Body.Impulse.X,60,"queued oldX");Near(result.Body.Impulse.Y,(120+800f/60)*.65f,"queued bounce"); + Near(result.Body.Velocity.X,59.54f,"source .46 floor friction follows landing callback"); + var next=physics.Step(result.Body,1f/60,radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball); + Check(next.Body.Impulse==Vector3.Zero,"one consumption");Check(next.Body.Velocity.X>result.Body.Velocity.X,"horizontal impulse is added, not replaced"); +}); +Test("ball wall callback reflects and damps horizontal velocity while preserving falling Y",()=>{ + var wall=new CameraRayPolygon(new(new(-1000,-1000,0),new(-1000,1000,0),new(1000,1000,0)),Vector3.UnitZ); + var physics=new OriginalBodyPhysics(new([wall])); + var result=physics.Step(new(new(0,100,30),new(0,-10,-1800),Vector3.Zero,Vector3.Zero),1f/60, + radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball); + Check(result.Contact==wall,"source static dispatcher finds the actual wall"); + Near(result.Body.Velocity.Z,972,"horizontal reflection and1-.46 damping"); + Near(result.Body.Velocity.Y,-10-800f/60,"wall callback keeps liveY"); + Check(result.Body.Impulse==Vector3.Zero&&!result.Body.Supported,"wall is not a landing callback"); +}); +Test("target cooldown runs while hidden and end arrival teleports to Start",()=>{ + var actor=new SceneDirector(new("VR07",[Entity("3TAR","target",("StartPosX",-500f),("DestPosX",500f),("RespawnTime",1f))]),new TaskStates([]),(_,_)=>1).Actors[0]; + var t=new MovingBaseballTarget(actor);Check(t.Hit()&&!t.Hit()&&!actor.Visible,"one callback per respawn"); + t.StepFrame(.5f);Check(!actor.Visible,"still hidden");t.StepFrame(.5f);Check(actor.Visible&&t.Remaining==0,"exact zero expires"); + actor.Position=new(450,0,0);t.StepFrame(0);Check(actor.Position==t.Start&&t.Velocity.X>0,"source teleports without swapping endpoints"); +}); +Test("VR07 keeps six duplicate-tag targets by source instance",()=>{ + var level=GamLevel.Load("../Original/gam/VR07.gam");var d=new SceneDirector(level,new TaskStates([]),(_,_)=>1); + var mesh=Mesh.LoadSceneJson("artifacts/extracted/VR07/scene.json");var collision=OriginalStaticCollision.FromRouteScene(mesh,"VR07"); + Check(!collision.HasSpecialPlayerContacts&&collision.PolygonCount>0,"ordinary source wall profile"); + var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),level.Entities.First(e=>e.Kind=="STRT").Position,0){LevelCode="VR07"}; + var scene=new SceneBaseballs(d,p,mesh);Check(scene.Targets.Count==6,"all source records"); + Check(scene.Targets.Select(t=>t.Actor.SourceGam!.Offset).Distinct().Count()==6,"instances are never resolved by duplicate tag"); + var first=scene.Targets[0];var second=scene.Targets[1];first.Hit();Check(!first.Actor.Visible&&second.Actor.Visible,"per-instance state"); +}); +Test("named-Jimmy cutscene restores companion while retaining pending throw",()=>{ + var mesh=Floor();var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0){LevelCode="LV1B"}; + var d=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1"),Entity("3DOG","C3DGODDARD"),Entity("3MCA","cleanup",("CameraTarget0","none"))]),new TaskStates([]),(_,_)=>1); + var bag=new SceneInventory(new int[19]);bag.SetState(0,6,1);using var binding=new PlayerSceneBinding(d,p,bag,"JIM1"); + bag.SelectGadget(6);binding.Step(new(false,false,false,false,false,Fire:true)); + Check(!d.FindActor("C3DGODDARD")!.Visible&&p.Baseball.PendingThrow,"equip hides companion and arms"); + d.Trigger("cleanup");Check(p.GadgetMode==-1&&p.Baseball.PendingThrow&&d.FindActor("C3DGODDARD")!.Visible,"named cleanup preserves source latch"); +}); +Test("Baseball cleanup restores companion even in Invisible's blocked levels",()=>{ + foreach(var code in new[]{"LEV6","LEV7","LV1C","LV1D","LV4A","LV6A"}) + { + var p=new LabSimulation(new SceneCollision(Floor()),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0){LevelCode=code}; + var d=new SceneDirector(new(code,[Entity("3JIM","JIM1"),Entity("3DOG","C3DGODDARD")]),new TaskStates([]),(_,_)=>1); + var bag=new SceneInventory(new int[19]);bag.SetState(0,6,1);using var binding=new PlayerSceneBinding(d,p,bag,"JIM1"); + bag.SelectGadget(6);bag.SelectGadget(-1);var companion=d.FindActor("C3DGODDARD")!; + Check(companion.Visible&&companion.BodyEnabled&&companion.MovementEnabled,"raw6 unconditional restoration "+code); + } +}); +Test("actual contact activates trophy only after strict fourth hit and honors HasCollision",()=>{ + foreach(var hasCollision in new[]{0,-1}) + { + var mesh=Floor();var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),new(1000,80,0),0){LevelCode="VR07"}; + var d=new SceneDirector(new("VR07",[Entity("3TAR","target",("PositionY",100f),("PositionZ",100f), + ("StartPosY",100f),("StartPosZ",100f),("DestPosX",1000f),("RespawnTime",.25f),("ActivateObject","trophy"),("HitsRequired",3)), + Entity("3TRO","trophy",("InitiallyVisible",0),("HasCollision",hasCollision))]),new TaskStates([]),(_,_)=>1); + var scene=new SceneBaseballs(d,p,mesh);var trophy=d.FindActor("trophy")!; + Check(!trophy.Visible&&!trophy.BodyEnabled,"initial hidden trophy contact disabled"); + var score=0;var sounds=new List();scene.ScoreAwarded+=x=>score+=x;scene.Sound+=sounds.Add; + for(var i=0;i<4;i++) + { + p.Baseball.Projectiles[i].Launch(new(0,20,0),Vector3.Zero,0); + scene.StepBodies(1f/60); + foreach(var ball in p.Baseball.Projectiles)ball.Hide(); + if(i<3)Check(!trophy.Visible,"strict threshold must not activate at "+(i+1)); + scene.StepTargets(.5f); + } + Check(scene.Hits==4&&score==40&&trophy.Visible&&trophy.BodyEnabled==(hasCollision!=0),"source contact and conditional enable"); + Check(sounds.SequenceEqual(new[]{199})&&!d.Blocked,"parent428 does not invoke trigger interpreter"); + } +}); +Console.WriteLine($"Baseball:{count} groups passed; pair scheduling/full enemy combat remain separate."); + +GamEntity Entity(string kind,string tag,params(string Name,object Value)[] values) +{ + var props=new Dictionary(StringComparer.Ordinal); + foreach(var(name,value) in new[]{("ObjectTag",(object)tag)}.Concat(values)) + { + if(value is string text)props[name]=new(name,1,Encoding.Latin1.GetBytes(text)); + else{var raw=new byte[4];if(value is float f)BinaryPrimitives.WriteInt32BigEndian(raw,BitConverter.SingleToInt32Bits(f)); + else BinaryPrimitives.WriteInt32BigEndian(raw,(int)value);props[name]=new(name,value is float?3u:6u,raw);} + } + return new(kind,props.Count,props,[]); +} diff --git a/tests/GamePort.BaseballVisualTests/GamePort.BaseballVisualTests.csproj b/tests/GamePort.BaseballVisualTests/GamePort.BaseballVisualTests.csproj new file mode 100644 index 0000000..6016e31 --- /dev/null +++ b/tests/GamePort.BaseballVisualTests/GamePort.BaseballVisualTests.csproj @@ -0,0 +1,11 @@ + + Exenet10.0 + enableenablefalse + + + + + + + + diff --git a/tests/GamePort.BaseballVisualTests/Program.cs b/tests/GamePort.BaseballVisualTests/Program.cs new file mode 100644 index 0000000..f4d269d --- /dev/null +++ b/tests/GamePort.BaseballVisualTests/Program.cs @@ -0,0 +1,153 @@ +using System.Numerics; +using System.Security.Cryptography; +using System.Text.Json.Nodes; +using GamePort.Application; +using GamePort.Assets; +using GamePort.Game; + +var prepared=args.Length==0?"artifacts/extracted":args[0]; +var count=0; +void Check(bool condition,string message){if(!condition)throw new Exception(message);} +void Near(float actual,float expected,string message)=>Check(MathF.Abs(actual-expected)<.001f,$"{message}: {actual} != {expected}"); +void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");} +void Invalid(Action action) +{ + try{action();}catch(Exception e)when(e is ArgumentException or InvalidDataException){return;} + throw new Exception("Invalid visual input accepted"); +} +BaseballGadget Aim(float pitch,bool visible=true) +{ + var device=new BaseballGadget(); + //Visual contract fixtures set published state directly, independently of + //input/timing tests owned by BaseballGadget's separate test project. + typeof(BaseballGadget).GetProperty("DisplayPitch")!.SetValue(device,pitch); + typeof(BaseballGadget).GetProperty("AimVisible")!.SetValue(device,visible); + return device; +} +Vector2 Pixels(MeshVertex vertex,uint width,uint height)=>new((vertex.Position.X+1)*width/2,(vertex.Position.Y+1)*height/2); + +Test("twenty exact source balls append hidden alpha quads and preserve scene metadata",()=> +{ + var source=new Mesh([new(new(1,2,3),Vector2.Zero,Vector3.One)],[0,0,0]) + { + CollisionPolygons=[new(1,2,Vector3.UnitY,"floor")],HasCollisionMaterialIds=true, + Textures=new(){[int.MinValue+17000]=PngImage.White} + }; + var visual=new BaseballVisuals(source,prepared); + Check(visual.Mesh.Vertices.Length==81&&visual.Mesh.Indices.Length==123,"append20 quads"); + Check(visual.Mesh.Draws.Length==21&&!visual.Mesh.Draws[0].ScreenSpace,"preserve implicit scene draw"); + Check(visual.Mesh.Vertices[0].Position==new Vector3(1,2,3),"original vertex retained"); + Check(ReferenceEquals(visual.Mesh.CollisionPolygons,source.CollisionPolygons)&&visual.Mesh.HasCollisionMaterialIds,"collision metadata retained"); + Check(visual.Mesh.Draws.Skip(1).All(d=>!d.Visible&&!d.ScreenSpace&&d.Blend==MeshBlend.Alpha),"hidden alpha world sprites"); + var image=visual.Mesh.Textures[visual.Mesh.Draws[^1].TextureId]; + Check(image.Width==32&&image.Height==32,"source32x32 canvas"); + Check(Convert.ToHexStringLower(SHA256.HashData(image.Rgba))=="68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9","exact ball0000 pixels"); + Check(visual.Mesh.Draws[^1].TextureId!=int.MinValue+17000,"texture collision avoided"); +}); + +Test("source25-unit ball corners face camera with finite degenerate bases and full UVs",()=> +{ + var visual=new BaseballVisuals(new([],[]),prepared); + var ball=new BaseballProjectile();ball.Launch(new(5,10,15),Vector3.Zero,0); + foreach(var target in new[]{Vector3.Zero,Vector3.UnitY,-Vector3.UnitY,new Vector3(2,3,4)}) + { + visual.Update(visual.Mesh,[ball],Vector3.Zero,target); + var v=visual.Mesh.Vertices.Take(4).ToArray(); + Check(v.All(c=>float.IsFinite(c.Position.X+c.Position.Y+c.Position.Z)),"finite basis"); + Near(Vector3.Distance(v[0].Position,v[1].Position),25,"source width"); + Near(Vector3.Distance(v[1].Position,v[2].Position),25,"source height"); + Check(Vector3.Distance(v.Aggregate(Vector3.Zero,(a,b)=>a+b.Position)/4,ball.Position)<.0001f,"source published position is center"); + Check(v.Select(c=>c.Uv).SequenceEqual(new Vector2[]{new(0,1),new(1,1),new(1,0),new(0,0)}),"full source UV"); + Check(visual.Mesh.Draws.Count(d=>d.Visible)==1,"unused19 slots remain hidden"); + } + ball.Hide();visual.Update(visual.Mesh,[ball],Vector3.Zero,Vector3.UnitZ); + Check(visual.Mesh.Draws.All(d=>!d.Visible),"hide removes stale draw"); + Invalid(()=>visual.Update(new([],[]),[ball],Vector3.Zero,Vector3.UnitZ)); + Invalid(()=>visual.Update(visual.Mesh,[ball],new(float.NaN),Vector3.UnitZ)); + Invalid(()=>visual.Update(visual.Mesh,Enumerable.Range(0,21).Select(_=>ball).ToArray(),Vector3.Zero,Vector3.UnitZ)); +}); + +Test("aim uses stationary original strip, prior-capture pitch and source integer truncation",()=> +{ + var overlay=new BaseballAimOverlay(new([],[]),prepared); + foreach(var pitch in new[]{0f,9.9f,17.5f,44.99f,45f}) + { + overlay.Update(overlay.Mesh,Aim(pitch),640,480); + Check(overlay.Mesh.Draws.Count(d=>d.Visible)==3,"one strip and two digits"); + var visible=overlay.Mesh.Draws.Where(d=>d.Visible).ToArray(); + var strip=visible.Single(d=>overlay.Mesh.Textures[d.TextureId].Height==210); + var start=overlay.Mesh.Indices[strip.FirstIndex]; + Near(Pixels(overlay.Mesh.Vertices[start],640,480).X,315,"strip x stationary"); + Near(Pixels(overlay.Mesh.Vertices[start],640,480).Y,100,"strip y stationary"); + var digits=visible.Where(d=>d!=strip).OrderBy(d=>Pixels(overlay.Mesh.Vertices[overlay.Mesh.Indices[d.FirstIndex]],640,480).X).ToArray(); + for(var place=0;place<2;place++) + { + var point=Pixels(overlay.Mesh.Vertices[overlay.Mesh.Indices[digits[place].FirstIndex]],640,480); + Near(point.X,286+place*16,"null TIME space has zero advance"); + Near(point.Y,(int)((45-(double)pitch)*4.3+100),"label integer y"); + var digit=place==0?(int)pitch/10:(int)pitch%10; + Check(overlay.Mesh.Textures[digits[place].TextureId].Rgba.SequenceEqual( + File.ReadAllBytes(Path.Combine(prepared,$"baseball/aim_{new[]{118,127,120,121,122,123,124,125,126,119}[digit]}.rgba"))),"exact selected source digit pixels"); + } + Check(strip.Blend==MeshBlend.Alpha&&strip.ScreenSpace,"screen alpha path"); + } + overlay.Update(overlay.Mesh,Aim(0,false),640,480); + Check(overlay.Mesh.Draws.All(d=>!d.Visible),"unequip hides all owned aim draws"); + Invalid(()=>overlay.Update(overlay.Mesh,Aim(float.NaN),640,480)); + Invalid(()=>overlay.Update(overlay.Mesh,Aim(46),640,480)); + Invalid(()=>overlay.Update(overlay.Mesh,Aim(0),0,480)); + Invalid(()=>overlay.Update(new([],[]),Aim(0),640,480)); +}); + +Test("widescreen preserves aim pixel proportions and centered640x480 placement",()=> +{ + var overlay=new BaseballAimOverlay(new([],[]),prepared); + foreach(var size in new[]{(640u,480u),(1920u,1080u),(3440u,1440u),(480u,800u)}) + { + var(w,h)=size;var scale=MathF.Min(w/640f,h/480f); + overlay.Update(overlay.Mesh,Aim(45),w,h); + var strip=overlay.Mesh.Draws.Single(d=>d.Visible&&overlay.Mesh.Textures[d.TextureId].Height==210); + var start=overlay.Mesh.Indices[strip.FirstIndex]; + var a=Pixels(overlay.Mesh.Vertices[start],w,h);var b=Pixels(overlay.Mesh.Vertices[start+2],w,h); + Near(a.X,w/2f-5*scale,"centered strip x"); + Near(a.Y,(h-480*scale)/2+100*scale,"centered strip y"); + Near(b.X-a.X,15*scale,"uniform source width");Near(b.Y-a.Y,210*scale,"uniform source height"); + } +}); + +Test("world plus overlay updates retain each other's vertices and draws",()=> +{ + var balls=new BaseballVisuals(new([],[]),prepared);var overlay=new BaseballAimOverlay(balls.Mesh,prepared); + var ball=new BaseballProjectile();ball.Launch(Vector3.Zero,Vector3.Zero,0); + balls.Update(overlay.Mesh,[ball],Vector3.Zero,Vector3.UnitZ); + var position=overlay.Mesh.Vertices[0].Position; + overlay.Update(overlay.Mesh,Aim(12),1920,1080); + Check(overlay.Mesh.Vertices[0].Position==position&&overlay.Mesh.Draws[0].Visible,"overlay retains world state"); + Check(overlay.Mesh.Draws.Count(d=>d.Visible)==4,"one world and three overlay draws"); +}); + +Test("altered pixels, dimensions and manifest traversal are rejected",()=> +{ + var directory=Path.Combine(Path.GetTempPath(),"neutron-baseball-visual-"+Guid.NewGuid()); + var output=Path.Combine(directory,"baseball");Directory.CreateDirectory(output); + try + { + var source=Path.Combine(prepared,"baseball"); + foreach(var path in Directory.EnumerateFiles(source,"*.rgba"))File.Copy(path,Path.Combine(output,Path.GetFileName(path))); + var original=File.ReadAllText(Path.Combine(source,"baseball.json")); + var root=JsonNode.Parse(original)!; + void Save()=>File.WriteAllText(Path.Combine(output,"baseball.json"),root.ToJsonString()); + root["textures"]![0]!["path"]="../outside.rgba";Save(); + File.Copy(Path.Combine(source,"canvas_2.rgba"),Path.Combine(directory,"outside.rgba")); + Invalid(()=>new BaseballVisuals(new([],[]),directory)); + root=JsonNode.Parse(original)!;root["aimTextures"]![0]!["width"]=16;Save(); + Invalid(()=>new BaseballAimOverlay(new([],[]),directory)); + root=JsonNode.Parse(original)!;Save(); + File.WriteAllBytes(Path.Combine(output,"canvas_2.rgba"),new byte[4096]); + Invalid(()=>new BaseballVisuals(new([],[]),directory)); + File.WriteAllBytes(Path.Combine(output,"aim_253.rgba"),new byte[15*210*4]); + Invalid(()=>new BaseballAimOverlay(new([],[]),directory)); + } + finally{Directory.Delete(directory,true);} +}); +Console.WriteLine($"Baseball visual checks passed: {count}"); diff --git a/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj b/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj index 8ac6653..7cca487 100644 --- a/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj +++ b/tests/GamePort.InteractionTests/GamePort.InteractionTests.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj b/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj index 8519a92..5031394 100644 --- a/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj +++ b/tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj @@ -23,6 +23,7 @@ + diff --git a/tests/test_baseball.py b/tests/test_baseball.py new file mode 100644 index 0000000..e48efe1 --- /dev/null +++ b/tests/test_baseball.py @@ -0,0 +1,61 @@ +"""Source guard/projection checks; these do not execute original gameplay.""" +from pathlib import Path +import sys +import unittest + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tools/binary')) +from baseball import Aim, aim_hold, aim_label, cleanup, collect, landing_impulse, launch_yaw_only, next_slot, release, f32 + + +class BaseballSourceTests(unittest.TestCase): + def test_identity_ranges_and_virtuals(self): + report=collect(ROOT.parent/'Original') + self.assertEqual(len(report['bodies']),15) + self.assertEqual(len(report['vtables']),13) + self.assertEqual(report['wall_damping'],f32(.46)) + self.assertEqual(report['pool_size'],20) + self.assertTrue(all(int(b['va'],16)-int(b['file_offset'],16)==0x400000 for b in report['bodies'])) + + def test_first_hold_does_not_capture_then_clamps_and_displays_previous(self): + state=aim_hold(Aim(saved_pitch=12),30) + self.assertEqual(state,Aim(True,12)) + self.assertEqual(aim_label(state.saved_pitch),(286,241,12)) + self.assertEqual(aim_hold(state,80),Aim(True,45)) + self.assertEqual(aim_hold(state,-3),Aim(True,0)) + for flags in ({'mode':0},{'mode':2},{'supported':False},{'energy':0},{'modal':True},{'busy':True}): + self.assertEqual(aim_hold(state,42,**flags),state) + self.assertEqual(aim_hold(Aim(),20,energy=0,exempt=True),Aim(True,0)) + + def test_release_survives_cleanup_without_fresh_energy_or_mode_gate(self): + state=Aim(True,30) + self.assertEqual(cleanup(state),state) + self.assertEqual(release(state,primary=True),(state,None)) + after,event=release(cleanup(state)) + self.assertEqual(after,Aim(False,30)) + self.assertEqual(event,dict(pitch=30,sound=10,energy=-1.)) + self.assertEqual(release(after),(after,None)) + + def test_ring_is_capacity_not_ammo_and_null_slot_does_not_advance(self): + self.assertEqual(next_slot(19),0) + self.assertEqual(next_slot(19,exists=False),19) + for index in (-1,20): + with self.assertRaises(ValueError): next_slot(index) + + def test_launch_origin_and_aim_slope(self): + root,velocity=launch_yaw_only((1,2,3),0,0) + self.assertEqual(root,(1.,82.,53.)) + self.assertEqual(velocity,(-0.,0.,1800.)) + root,v=launch_yaw_only((0,0,0),90,45) + self.assertAlmostEqual(root[0],-50) + self.assertAlmostEqual(v[0],-v[1],places=4) + self.assertAlmostEqual(sum(x*x for x in v),1800**2,places=5) + + def test_landing_queues_full_vector_before_velocity_y_is_zeroed(self): + impulse=landing_impulse((100,-200,50)) + self.assertEqual(impulse,(100.,130.,50.)) + # Source support then stores velocity(100,0,50); next body adds impulse. + self.assertEqual(tuple(a+b for a,b in zip((100.,0.,50.),impulse)),(200.,130.,100.)) + + +if __name__=='__main__': unittest.main() diff --git a/tests/test_baseball_resources.py b/tests/test_baseball_resources.py new file mode 100644 index 0000000..a2dcb9c --- /dev/null +++ b/tests/test_baseball_resources.py @@ -0,0 +1,94 @@ +from pathlib import Path +import hashlib +import json +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 baseball_resources import ARCHIVE_SHA256, VR07_SHA256, CANVASES, AIM_CANVASES, AIM_ARCHIVES, export_baseball +from omt import FormatError +from png import read_png + + +@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures') +class BaseballResourceTests(unittest.TestCase): + def test_exact_original_pixels_and_provenance(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'baseball' + manifest = export_baseball(ORIGINAL, output) + self.assertEqual(manifest, json.loads((output/'baseball.json').read_text())) + self.assertEqual((manifest['schema'], manifest['sourceSha256']), (1, ARCHIVE_SHA256)) + self.assertEqual([e['id'] for e in manifest['textures']], [2, 3, 4, 5, 8]) + for entry, expected in zip(manifest['textures'], CANVASES): + self.assertEqual((entry['id'], entry['name'], entry['sourceOffset'], entry['sourceBytes'], + entry['width'], entry['height'], entry['rgbaSha256']), expected) + rgba = (output/entry['path']).read_bytes() + self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256']) + self.assertEqual(read_png(output/entry['png'])['rgba'], rgba) + + def test_aim_strip_and_original_gameplay_glyphs_are_not_substituted(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'baseball' + manifest = export_baseball(ORIGINAL, output) + self.assertEqual(manifest['aimArchiveSha256'], AIM_ARCHIVES) + for entry, expected in zip(manifest['aimTextures'], AIM_CANVASES): + self.assertEqual((entry['database'], entry['id'], entry['width'], entry['height'], entry['rgbaSha256']), expected) + rgba = (output/entry['path']).read_bytes() + self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256']) + self.assertEqual(read_png(output/entry['png'])['rgba'], rgba) + + def test_tutorial_retains_six_duplicate_tags_and_exact_properties(self): + with tempfile.TemporaryDirectory() as directory: + manifest = export_baseball(ORIGINAL, Path(directory)/'baseball') + tutorial = manifest['tutorial'] + self.assertEqual(tutorial['sha256'], VR07_SHA256) + targets = [e for e in tutorial['entities'] if e['kind'] == '3TAR'] + self.assertEqual([e['offset'] for e in targets], [0x885, 0xAD6, 0xD27, 0xF78, 0x11C9, 0x141C]) + for target in targets: + values = {p['name']: p['value'] for p in target['properties']} + self.assertEqual((values['ObjectTag'], values['SpriteDatabase'], values['SpriteIndex']), + ('C3DMOVINGTARGET', 'sprites.omt', 135)) + self.assertEqual((values['HitsRequired'], values['Speed'], values['NumPoints'], values['RespawnTime']), + (3, 100.0, 10, 15.0)) + source = next(p for p in target['properties'] if p['name'] == 'SpriteIndex') + self.assertEqual(source['raw'], '00000087') + self.assertGreater(source['offset'], target['offset']) + + def test_source_outputs_and_descendant_symlinks_rejected(self): + for output in (ORIGINAL, ORIGINAL/'omt/baseball-generated', ORIGINAL.parent): + with self.subTest(output=output), self.assertRaises(ValueError): + export_baseball(ORIGINAL, output) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'baseball' + output.mkdir() + target = Path(directory)/'unchanged' + target.write_bytes(b'unchanged') + (output/'canvas_2.rgba').symlink_to(target) + with self.assertRaises(ValueError): + export_baseball(ORIGINAL, output) + self.assertEqual(target.read_bytes(), b'unchanged') + + def test_bad_pixels_rejected_before_output(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'baseball' + with patch('baseball_resources.read_canvas', return_value=dict(width=32, height=32, rgba=b'\0'*4096)), \ + self.assertRaises(FormatError): + export_baseball(ORIGINAL, output) + self.assertFalse(output.exists()) + + def test_bad_source_identity_rejected_before_decode(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'baseball' + with patch('baseball_resources.digest', return_value='0'*64), \ + patch('baseball_resources.read_canvas') as decoder, self.assertRaises(FormatError): + export_baseball(ORIGINAL, output) + decoder.assert_not_called() + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_baseball_targets.py b/tests/test_baseball_targets.py new file mode 100644 index 0000000..24695b7 --- /dev/null +++ b/tests/test_baseball_targets.py @@ -0,0 +1,33 @@ +import sys +from pathlib import Path +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/binary')) +import baseball_targets as source + + +class BaseballTargetTests(unittest.TestCase): + def test_original_guards_and_six_distinct_records(self): + report = source.collect(Path(__file__).resolve().parents[2] / 'Original') + self.assertEqual(len(report['targets']), 6) + self.assertEqual(len({e['offset'] for e in report['targets']}), 6) + self.assertEqual({e['properties']['ObjectTag'] for e in report['targets']}, {'C3DMOVINGTARGET'}) + self.assertTrue(all(e['properties']['SpriteIndex'] == 135 for e in report['targets'])) + + def test_hit_respawn_gate_and_score(self): + self.assertEqual(source.hit_target(0, 10, 15), dict(accepted=True, hidden=True, timer=15, points=10)) + self.assertFalse(source.hit_target(.0001, 10, 15)['accepted']) + self.assertTrue(source.hit_target(-1, 10, 15)['accepted']) + + def test_expiry_uses_stored_subtraction(self): + self.assertEqual(source.step_respawn(1, 1), (0, True)) + self.assertEqual(source.step_respawn(0, .5), (0, False)) + self.assertEqual(source.step_respawn(.75, .5), (.25, False)) + + def test_parent_threshold_is_strict(self): + self.assertEqual(source.parent_hits(2, 3), (3, False)) + self.assertEqual(source.parent_hits(3, 3), (0, True)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_scooter.py b/tests/test_scooter.py new file mode 100644 index 0000000..3b7c22f --- /dev/null +++ b/tests/test_scooter.py @@ -0,0 +1,90 @@ +"""Static source guards/projections, not original runtime Scooter tests.""" +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT/'tools/binary')) +import scooter as s + + +class ScooterTests(unittest.TestCase): + def test_identity_and_source_guards(self): + source = ROOT.parent/'Original' + if not source.exists(): + self.skipTest('Original source directory unavailable') + result = s.collect(source) + self.assertEqual(17, len(result['bodies'])) + self.assertEqual(150, result['radius']) + self.assertEqual(4, result['wheel_construction_count']) + self.assertFalse(result['runtime_implemented']) + + def test_spawn_does_not_mount(self): + self.assertEqual('raw4_vehicle_visible_unmounted', s.equip_result()) + self.assertEqual('unchanged', s.equip_result(companion_enabled=False)) + self.assertEqual('unchanged', s.equip_result(companion_exists=False)) + self.assertEqual('practice_VR05', s.equip_result(practice=True)) + + def test_actual_child_support_required(self): + self.assertFalse(s.drive_eligible(True, (None,)*6)['drive']) + state = s.drive_eligible(True, (True, False, True, False, None, None)) + self.assertEqual(dict(front=1, rear=1, total=2, drive=True), state) + self.assertFalse(s.drive_eligible(False, (True,)*6)['drive']) + self.assertFalse(s.drive_eligible(True, (True, False, None, None, None, None))['drive']) + with self.assertRaises(ValueError): + s.drive_eligible(True, (True, True)) + + def test_steering_keyboard_priority_cap_and_release(self): + state = s.keyboard_input(s.Steering(), .1, left=True, right=True) + self.assertAlmostEqual(20, state.turn, places=5) + state = s.keyboard_input(state, .2, left=True) + self.assertEqual(45, state.turn) + self.assertEqual(0, s.keyboard_input(state, .3).turn) + self.assertEqual(-45, s.keyboard_input(state, .5, right=True).turn) + + def test_forward_requires_rear_support_and_uses_dt(self): + self.assertEqual(0, s.keyboard_input(s.Steering(), .1, forward=True).speed) + state = s.keyboard_input(s.Steering(), .1, forward=True, rear_supports=1) + self.assertAlmostEqual(70, state.speed, places=4) + for _ in range(30): + state = s.keyboard_input(state, .1, forward=True, rear_supports=2) + self.assertEqual(s.f32(2250*s.f32(.66)), state.speed) + self.assertEqual(state.speed, s.keyboard_input(state, .1).speed) + + def test_reverse_first_call_brakes_then_reverses(self): + state = s.keyboard_input(s.Steering(speed=100), .1, backward=True, rear_supports=2) + self.assertEqual(0, state.speed) + self.assertTrue(state.braking) + state = s.keyboard_input(state, .1, backward=True, rear_supports=2) + self.assertAlmostEqual(-120, state.speed, places=4) + for _ in range(10): + state = s.keyboard_input(state, .1, backward=True, rear_supports=2) + self.assertEqual(s.f32(-s.f32(2250*s.f32(.66))*s.f32(.4)), state.speed) + state = s.keyboard_input(state, .1) + self.assertFalse(state.reverse_latch) + self.assertFalse(state.braking) + + def test_jump_edge_and_support_gates(self): + self.assertEqual((False, None), s.jump_pending(mounted=True, grounded=False, held=True, latched=False)) + self.assertEqual((True, (0.,700.,0.)), s.jump_pending(mounted=True, grounded=True, held=True, latched=False)) + self.assertEqual((True, None), s.jump_pending(mounted=True, grounded=True, held=True, latched=True)) + self.assertEqual((False, None), s.jump_pending(mounted=True, grounded=True, held=False, latched=True)) + self.assertEqual((True, None), s.jump_pending(mounted=False, grounded=True, held=False, latched=True)) + + def test_animation_strict_timer_and_signed_speed(self): + self.assertEqual((0., 'SCOOTSTOP'), s.animation_step(0., .31, -100)) + self.assertEqual((0., 'SCOOT'), s.animation_step(0., .31, 10)) + self.assertIsNone(s.animation_step(0., .29, 100)[1]) + # float32(.3) is greater than the source double.3 comparison operand. + self.assertEqual((0., 'SCOOT'), s.animation_step(0., .3, 10)) + + def test_bounded_projection(self): + for value in [-1, 1, float('nan'), float('inf')]: + with self.assertRaises(ValueError): + s.keyboard_input(s.Steering(), value) + with self.assertRaises(ValueError): + s.keyboard_input(s.Steering(), .1, rear_supports=5) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_scooter_resources.py b/tests/test_scooter_resources.py new file mode 100644 index 0000000..85369dd --- /dev/null +++ b/tests/test_scooter_resources.py @@ -0,0 +1,98 @@ +from pathlib import Path +import hashlib +import json +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 ase import expand_mesh, read_ase +from entities import resolve_asset +from omt import FormatError +from png import read_png +from scooter_resources import SOURCES, export_scooter + + +@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures') +class ScooterResourceTests(unittest.TestCase): + def test_original_shape_material_links_and_pixels(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'scooter' + manifest = export_scooter(ORIGINAL, output) + self.assertEqual(manifest, json.loads((output/'scooter.json').read_text())) + self.assertEqual(manifest['sources'], SOURCES) + self.assertEqual([s['triangles'] for s in manifest['shapes']], [176, 56]) + for identity, expected_canvas in ((0, 1), (1, 0)): + scene = json.loads((output/f'shape_{identity}/scene.json').read_text()) + self.assertEqual(len(scene['materials']), 1) + self.assertEqual(scene['materials'][0]['texture'], dict(type='Canv', id=expected_canvas)) + texture = scene['textures'][0] + self.assertEqual(texture['id'], expected_canvas) + image = read_png(output/f'shape_{identity}'/texture['png']) + self.assertEqual(image['rgba'], (output/f'shape_{identity}'/texture['path']).read_bytes()) + wheel = json.loads((output/'shape_1/scene.json').read_text()) + self.assertIn(-1, [m['material'] for m in wheel['meshes']]) + self.assertEqual((output/'jimycarl.rgba').read_bytes(), + read_png(resolve_asset(ORIGINAL, 'png/jimycarl.png'))['rgba']) + + def test_jimmy_exact_base_topology_and_morph_positions(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'scooter' + export_scooter(ORIGINAL, output) + base = read_ase(resolve_asset(ORIGINAL, 'ASE/jimstop.ASE'))['objects'][0]['samples'][0] + for stem in ('jimscooter', 'jimscooterstop'): + source = read_ase(resolve_asset(ORIGINAL, f'ASE/{stem}.ASE')) + animation = json.loads((output/stem/'animation.json').read_text()) + self.assertEqual((animation['framesPerSecond'], animation['ticksPerFrame']), (10, 480)) + self.assertEqual([f['time'] for f in animation['frames']], [0, 480]) + self.assertEqual(animation['sha256'], source['sha256']) + for index, sample in enumerate(source['objects'][0]['samples']): + expected = expand_mesh(dict(sample, faces=base['faces'], uvs=base['uvs'], + textureFaces=base['textureFaces'])) + actual = json.loads((output/stem/animation['frames'][index]['path']).read_text()) + self.assertEqual(actual['vertices'], [list(v) for v in expected['vertices']]) + self.assertEqual(actual['uvs'], [list(v) for v in expected['uvs']]) + + def test_unbound_morphs_retain_source_161_ticks_and_no_guessed_uvs(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'scooter' + manifest = export_scooter(ORIGINAL, output) + for entry in manifest['unboundMorphs']: + morph = json.loads((output/entry['path']).read_text()) + self.assertEqual((morph['framesPerSecond'], morph['ticksPerFrame']), (30, 160)) + samples = morph['objects'][0]['samples'] + self.assertEqual([s['time'] for s in samples], [0, 161]) + self.assertEqual([len(s['vertices']) for s in samples], [195, 195]) + self.assertTrue(all(not s['uvs'] and not s['textureFaces'] for s in samples)) + self.assertEqual(morph['sha256'], hashlib.sha256( + resolve_asset(ORIGINAL, 'ASE/'+entry['source']).read_bytes()).hexdigest()) + + def test_original_subtrees_ancestors_and_symlinks_rejected(self): + for output in (ORIGINAL, ORIGINAL/'png/generated-scooter', ORIGINAL.parent): + with self.subTest(output=output), self.assertRaises(ValueError): + export_scooter(ORIGINAL, output) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'scooter' + output.mkdir() + outside = Path(directory)/'unchanged' + outside.write_text('unchanged') + for relative in ('scooter.json', 'shape_0', 'jimscooter', 'jimycarl.rgba'): + (output/relative).symlink_to(outside) + with self.subTest(relative=relative), self.assertRaises(ValueError): + export_scooter(ORIGINAL, output) + self.assertEqual(outside.read_text(), 'unchanged') + (output/relative).unlink() + + def test_changed_source_identity_rejected_before_writes(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory)/'scooter' + with patch.dict(SOURCES, {'omt/scooter.omt': '0'*64}), self.assertRaises(FormatError): + export_scooter(ORIGINAL, output) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/binary/baseball.py b/tools/binary/baseball.py new file mode 100644 index 0000000..3cfac4d --- /dev/null +++ b/tools/binary/baseball.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Identity-guarded Baseball evidence and bounded arithmetic projections. + +No original code executes. The yaw-only launch projection uses continuous host +trig; source full-Euler table quantization remains a separate precision boundary. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass, replace +import hashlib +import json +import math +from pathlib import Path +import struct + +from checkpoint_script_state import EXE_SHA256, find_case, read_va +from pe_inspect import PE + +BODIES = ( + ('constructor', 0x40fc50, 0x40fe67, 'f539ae6099b61f9f1f7007cd185f211b3165dc484cf502c80eb4b5dfc1c2ef0b'), + ('pool', 0x422609, 0x4226a3, '8324ec8b6bd8d9ce6c65782611781d2a5e990e8f73359fd0403e6795ba1a9771'), + ('primary', 0x426566, 0x4268b4, 'be39a4022aaaf35b9e629597bd04a50e957dcdbe8c8e64fd6ca91e7060b66565'), + ('equip', 0x4296f8, 0x4297dd, '2c530179e91a377e31e9bc169c25332bf3821cec614e927d3d5bc51871d69d10'), + ('cleanup', 0x42871d, 0x4287ac, '7fdcf6718f6a53a5136240894dbd8c9f840968afbf7c5e10f2d2f766da48a3dd'), + ('launch', 0x429a30, 0x429c03, 'fb35366b25c4a6b1503a8028aeb354d8bbfc8d32f60a850a2fde109913e34a53'), + ('ball_callbacks', 0x40fee0, 0x410020, '0b0a8ca521c8f92583a57586af945860bb21042240b72b8bc57ff13e061ac45c'), + ('jimmy_contact', 0x423014, 0x423080, '997533ba4cd830f11af35b19aa926ebc52a5fce2ee394a7da2c0b82410d9b4d3'), + ('aim_input', 0x438bc0, 0x438cd0, '329acdc727d4d68fcc7d2cc85dcfe408f6e18700574af891d889673a780ec7d5'), + ('support_order', 0x47bb10, 0x47bba7, '7f34edef3fad0a511d8af4ff8add816d9169b8407b05f1093683969ee4a21669'), + ('wall_reflection', 0x472750, 0x472970, 'cae4ae6987680cb97264a918efc33e5bdd25f3b419096d201fc948130bc52315'), + ('defaults', 0x46fd90, 0x46fe49, 'c04ff2c68b8b2ce5cbee48675a54e73f85dcf3014c9b9efd93a42213c75792ab'), + ('aim_art', 0x402084, 0x402107, '4a839c828fe971f0629796f8dfe5523e695a448bd5812768a74f3976071b561e'), + ('stop_sound', 0x429a00, 0x429a25, '09501f7e7ec80126459cd211ad9520f65c66d1ca4c6e644781a05137d620c3fd'), + ('energy_gate', 0x4269d0, 0x426a69, '0a97a24b016fa6743b518cd6ebadce5966a717b84e4ca0bdfa583bcdc65d16b5'), +) +VTABLES = ( + (0x4a3bdc, 0x174, 0x428d50), (0x4a3bdc, 0x178, 0x427ff0), + (0x4a3bdc, 0x180, 0x429a30), (0x4a3bdc, 0x148, 0x429a00), + (0x4a3bdc, 0x170, 0x437740), (0x49141c, 0x370, 0x40ff50), + (0x49141c, 0x374, 0x40fee0), (0x49141c, 0x378, 0x472750), + (0x49141c, 0x37c, 0x40ff80), (0x49141c, 0x3c4, 0x40ff40), + (0x49141c, 0x40c, 0x410000), (0x49141c, 0x288, 0x471cc0), + (0x49141c, 0x2c4, 0x471f40), +) +CONSTANTS = ((0x49195c, 'f', -0.6499999761581421), + (0x49fabc, 'f', 0.02222222276031971), + (0x4a311c, 'f', 1800.), (0x49d5c8, 'f', 45.), + (0x48d404, 'f', 30.), (0x4a3e40, 'd', 4.3), + (0x4a3130, 'd', 100.), (0x495324, 'f', 20.)) + + +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)) + for table, slot, target in VTABLES: + if struct.unpack(' 0: + return dict(accepted=False, hidden=False, timer=timer, points=0) + return dict(accepted=True, hidden=True, timer=respawn, points=points) + + +def step_respawn(timer: float, seconds: float): + """4306FA..43074F: expiry is <=0 after the stored float subtraction.""" + if timer <= 0: + return timer, False + value = struct.unpack(', not >=; only after a matching parent lookup.""" + count += 1 + return (0, True) if count > required else (count, False) + + +if __name__ == '__main__': + cli = argparse.ArgumentParser(description=__doc__) + cli.add_argument('original', type=Path) + print(json.dumps(collect(cli.parse_args().original), indent=2)) diff --git a/tools/binary/scooter.py b/tools/binary/scooter.py new file mode 100644 index 0000000..778e608 --- /dev/null +++ b/tools/binary/scooter.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Read-only Scooter identity guards and bounded static projections. + +No target execution. Input projection is keyboard-only; drive gate deliberately +requires child support observations instead of fabricating wheel contacts. +""" +from __future__ import annotations +import argparse +from dataclasses import dataclass, replace +import hashlib +import json +import math +from pathlib import Path +import struct + +from checkpoint_script_state import EXE_SHA256, find_case, read_va +from pe_inspect import PE + +BODIES = ( + ('equip', 0x4290b7, 0x429375, '4e65ee2007a20cd3a78a4529c8177fb6245c539041b82417095a267c193d9ec1'), + ('cleanup', 0x4281b3, 0x4284fb, '8ac21a2f27a6703058d18965e86759a878e7d31da86fa827015394164e1a06ec'), + ('spawn', 0x423ce8, 0x423dc1, 'dbfa1a7b5609eef20a3ef3d9bd86320d79ee616b06220bedce71bb014d04c5a6'), + ('mount', 0x422f13, 0x422fb9, '4d51aa5e2324e3af45632eeae417e976d4cbee9e421a10b1b47ca0a5758811d5'), + ('constructor', 0x4211a0, 0x4212f7, 'dd15bf6a55325da3247fe6fe9d9986b2a718ee5945dc10f5dfcbd1ed23a7c741'), + ('frame', 0x421580, 0x4217ca, '0d05dda2520f9063d66b256098ad4e63f42eeb1139620d458c86d9a9b6d4b458'), + ('input', 0x421880, 0x4218be, 'e46056df24b730111fbaa9a02878ad954762e4b23ac2cec602bbf875677ce14c'), + ('predicates', 0x421c10, 0x421cf7, '7461aaff87634a270874304ad4a4618fdc020c3643cc21d605d5cf3b4581820e'), + ('vehicle_frame', 0x465220, 0x46582d, '22a766ca5ccd38bcb524d75b1620dfd4718b2ddef2997dedae3f6f84d0984ec8'), + ('vehicle_input', 0x465830, 0x465dfe, '62cb4e87ab784d45a13fc763cb79b00d23942a95776568209cbd2b0b625f191f'), + ('vehicle_constructor', 0x464b90, 0x464de2, 'af460774f65ffa90dde8407145ffee72643f3e81586a033162b5b22985067017'), + ('parameters', 0x464f60, 0x464fcb, 'd32e32495b39a261b6f778d5a24da9a70309c4766dc0994cc2a4973253f57aa9'), + ('wheel_setup', 0x412a90, 0x412c77, '2f44692c4545b8088711168dff16269461a862c400b591e091a20ce89c9576ff'), + ('sound', 0x412ed0, 0x412f8b, '93ae7fb944aaeff732fa99bcc89db5546bdf8a379a3922575d79b693c03f4408'), + ('camera', 0x4130a0, 0x413a60, '9614e6e4ae80f576c060706bd6da453e8f29d8568330c60293570f57c3f4dcc2'), + ('collision_callback', 0x421910, 0x421ba4, 'a5a0cd543bf833aa87a896c33144c4d374bb55aae7d7726619011ce6b3611ebc'), + ('base_factor', 0x412940, 0x41294c, '5bd12b37bcf408ee68ea761709182ba1781a4b7debbf0bae4a236ac1aa0ae238'), +) +VTABLES = ( + (0x4a2f8c, 0x168, 0x412a90), (0x4a2f8c, 0x174, 0x421800), + (0x4a2f8c, 0xec, 0x4130a0), (0x4a2f8c, 0x120, 0x421c10), + (0x4a2f8c, 0x124, 0x421c40), (0x4a2f8c, 0x128, 0x421c70), + (0x4a2f8c, 0x12c, 0x421cb0), (0x4a2f8c, 0x130, 0x413a60), + (0x4a2aec, 0x110, 0x471240), (0x4a2aec, 0x100, 0x4711e0), + (0x4a2aec, 0x214, 0x471a00), (0x4a2aec, 0x28c, 0x471c90), + (0x4a2aec, 0x438, 0x4218c0), +) +CONSTANTS = ((0x4a3110, 'd', .3), (0x48e5dc, 'f', 200.), + (0x49d5cc, 'f', -45.), (0x49d5c8, 'f', 45.), + (0x4a3118, 'f', 0.6600000262260437), + (0x4afce0, 'f', 0.4000000059604645), + (0x4a311c, 'f', 1800.), (0x4a3120, 'f', 4.5), + (0x4a3124, 'f', 600.), (0x48e5ec, 'f', 10.)) + + +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)) + for base, slot, expected in VTABLES: + if struct.unpack('= 2)) + + +@dataclass(frozen=True) +class Steering: + speed: float = 0. + turn: float = 0. + keyboard_turn: bool = False + reverse_latch: bool = False + braking: bool = False + + +def keyboard_input(state: Steering, seconds: float, *, left=False, right=False, + forward=False, backward=False, rear_supports=0): + """465830 keyboard subset, no AI/sprint/mouse/analog/camera/contact phase. + + 413A60 sprint predicate always returns false for this vehicle. Values round + at source storage boundaries, without claiming x87 bit parity. + """ + timestep(seconds) + finite(state.speed, state.turn) + if type(rear_supports) is not int or not 0 <= rear_supports <= 4: + raise ValueError('Rear source support count0..4 required') + dt = f32(seconds) + turn = state.turn + key_turn = state.keyboard_turn + if left: + turn += dt*200 + key_turn = True + elif right: + turn -= dt*200 + key_turn = True + elif key_turn: + turn = max(0., turn-dt*200) if turn > 0 else min(0., turn+dt*200) + turn = f32(min(45., max(-45., turn))) + speed = state.speed + reverse_latch, braking = state.reverse_latch, state.braking + maximum = f32(2250*f32(.66)) + throttle = forward and rear_supports > 0 + if throttle: + if speed < maximum: + speed = f32(min(maximum, speed+dt*700)) + reverse_latch = False + if backward and rear_supports > 0: + if not reverse_latch: + reverse_latch = True + if speed > 0: + speed = f32(max(0., speed-dt*1200)) + braking = True + elif speed < 0: + speed = f32(min(0., speed+dt*1200)) + braking = True + else: + speed = f32(max(-maximum*f32(.4), speed-dt*1200)) + else: + braking = False + reverse_latch = False + return Steering(speed, turn, key_turn, reverse_latch, braking) + + +def jump_pending(*, mounted: bool, grounded: bool, held: bool, latched: bool): + """4215BA..421618: source pending vector write, not direct live velocity.""" + if not mounted: + return latched, None + if not held: + return False, None + if not latched and grounded: + return True, (0., 700., 0.) + return latched, None + + +def animation_step(timer: float, seconds: float, speed: float): + """42171A: strict double.3 comparison after float timer store.""" + finite(timer, speed) + timestep(seconds) + timer = f32(timer+f32(seconds)) + return (0., 'SCOOTSTOP' if speed < 10 else 'SCOOT') if timer > .3 else (timer, None) + + +if __name__ == '__main__': + cli = argparse.ArgumentParser(description=__doc__) + cli.add_argument('original', type=Path) + print(json.dumps(collect(cli.parse_args().original), indent=2)) diff --git a/tools/extractors/baseball_resources.py b/tools/extractors/baseball_resources.py new file mode 100644 index 0000000..ca6cbbf --- /dev/null +++ b/tools/extractors/baseball_resources.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Export exact Baseball canvases and authored VR07 data without timing guesses.""" +from __future__ import annotations + +import argparse +from dataclasses import asdict +import hashlib +import json +from pathlib import Path + +from entities import resolve_asset +from gam import parse +from omt import Database, FormatError, read_canvas, write_png + +ARCHIVE_SHA256 = 'b584ffa4a38f4bc809b3ea8f4321e0c08f2719e22df41a3fb4cd143ed89b3bef' +VR07_SHA256 = '1260b75d82ec794f9375ada30e186424746bc1dd4e4b0540c9b69bb7ad12d0b1' +# Identity, source name, offset, bytes, width, height, decoded RGBA SHA256. +CANVASES = ( + (2, 'ball0000', 72372, 3786, 32, 32, '68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9'), + (3, 'ball0001', 68582, 3790, 32, 32, '005def070e18111fbdb067e75285dad8ec677c1608020f55c3db7a4b9745205c'), + (4, 'ball0002', 64788, 3794, 32, 32, 'c368a59d5d7a57824c1c6b56b617cf058f5d5d53e18e5e48989710413490c536'), + (5, 'ball0003', 58830, 3794, 32, 32, 'e5da21c359d3215759e5c3c238107f526f7109203c0ff9fa391a3c8bc40c17ed'), + (8, 'target', 48796, 10034, 64, 64, '8d31014cb9b9661ebed902c864bf740f562460e74da3f6b86ed3d2be4d10f0ec'), +) +AIM_ARCHIVES = { + 'omt/screens.omt': 'e8e95231f5d302b41f4fbf33df1c5a08ce4645370f9f519527ff1727b73b7a5e', + 'alpha.omt': '53cb9f47a588b1f19eb0adc4d43c8066a8b78aedd764b9e9314c81e287991126', +} +AIM_CANVASES = ( + ('omt/screens.omt', 253, 15, 210, '2e16e11b151c8474ba68fd5017d1a3a6304a594a7f34c3b423f3417c7edfb453'), + ('alpha.omt', 118, 16, 16, 'edc60e65dcf7320813a80d4312e3c45951ccfc566ea79dfabf7a22ebc4b96049'), + ('alpha.omt', 127, 16, 16, '1fd058ad5bdc0f8a064ef7d2d52b2b036df3f35515691a366799d7e8aab5297f'), + ('alpha.omt', 120, 16, 16, '62aaeaaf107300a6f4f7ff52e98106c1520a9edbe2137626ee41091cf243e5c5'), + ('alpha.omt', 121, 16, 16, 'd78bf1895f5838b9eb8c6a22565a9588dae4fc8f7106697df373f4408aae634c'), + ('alpha.omt', 122, 16, 16, 'f6d628639de4e40005f62f63a49308ff9ee0656a36bb6eb7787230b4830a5ed9'), + ('alpha.omt', 123, 16, 16, '9f58cad5621d89b7a7012036daa8532b2397b0d9d267ab7d1aa5a7cd10d7ae87'), + ('alpha.omt', 124, 16, 16, '49cdc9ec812f4ef3826011d542c30afbb10229c4b4ce549e7820233bbaa53dd9'), + ('alpha.omt', 125, 16, 16, 'aaef2d59c2636c059b446bed643985ca55d15b2d070b0582b2d8994b3bf74f1e'), + ('alpha.omt', 126, 16, 16, 'bade574a4624a3f763ddd9c87fa2f102562b00d8d604e9faf32a43b372de64e0'), + ('alpha.omt', 119, 16, 16, '0a663ddf2df9f1065f5e4ffe27b4d1fa96edd5f19b6323217bad4148f8d2f3d7'), +) +TIME_DIGITS = (118, 127, 120, 121, 122, 123, 124, 125, 126, 119) + + +def digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def export_baseball(original: Path, output: Path) -> dict: + original, output = original.resolve(), output.resolve() + if output.is_relative_to(original) or original.is_relative_to(output): + raise ValueError('Output must be separate from the original installation') + if output.exists() and any(p.is_symlink() for p in output.rglob('*')): + raise ValueError('Generated Baseball paths must not contain symlinks') + database = Database(resolve_asset(original, 'omt/RetainedSprites.omt')) + if digest(database.data) != ARCHIVE_SHA256: + raise FormatError('Unexpected original Baseball archive identity') + textures, pixels = [], [] + for identity, name, offset, size, width, height, rgba_sha in CANVASES: + matches = [e for e in database.entries if e.type == 'Canv' and e.id == identity] + if len(matches) != 1: + raise FormatError('Missing original Baseball canvas') + entry = matches[0] + if (entry.name, entry.offset, entry.size) != (name, offset, size): + raise FormatError('Unexpected original Baseball canvas metadata') + payload = database.payload(entry) + canvas = read_canvas(payload) + rgba = canvas['rgba'] + if (canvas['width'], canvas['height'], len(rgba), digest(rgba)) != (width, height, width*height*4, rgba_sha): + raise FormatError('Unexpected original Baseball decoded pixels') + textures.append(dict(id=identity, name=name, width=width, height=height, + path=f'canvas_{identity}.rgba', png=f'canvas_{identity}.png', + sourceOffset=offset, sourceBytes=size, sourceSha256=digest(payload), rgbaSha256=rgba_sha)) + pixels.append(rgba) + aim_databases = {name: Database(resolve_asset(original, name)) for name in AIM_ARCHIVES} + for name, expected in AIM_ARCHIVES.items(): + if digest(aim_databases[name].data) != expected: + raise FormatError('Unexpected Baseball aim archive identity') + aim_textures, aim_pixels = [], [] + for archive, identity, width, height, rgba_sha in AIM_CANVASES: + aim_database = aim_databases[archive] + entry = next(e for e in aim_database.entries if e.type == 'Canv' and e.id == identity) + payload = aim_database.payload(entry) + canvas = read_canvas(payload) + rgba = canvas['rgba'] + if (canvas['width'], canvas['height'], len(rgba), digest(rgba)) != (width, height, width*height*4, rgba_sha): + raise FormatError('Unexpected Baseball aim decoded pixels') + aim_textures.append(dict(id=identity, name=entry.name, database=archive, + width=width, height=height, path=f'aim_{identity}.rgba', png=f'aim_{identity}.png', + sourceOffset=entry.offset, sourceBytes=entry.size, sourceSha256=digest(payload), rgbaSha256=rgba_sha)) + aim_pixels.append(rgba) + source = resolve_asset(original, 'gam/VR07.gam') + source_data = source.read_bytes() + if digest(source_data) != VR07_SHA256: + raise FormatError('Unexpected original Baseball tutorial identity') + level = parse(source_data) + records = [dict(ordinal=index, **asdict(entity)) for index, entity in enumerate(level.entities) + if entity.kind in ('STRT', '3TAR', '3MCA')] + targets = [r for r in records if r['kind'] == '3TAR'] + if len(targets) != 6: + raise FormatError('Unexpected original Baseball tutorial target count') + manifest = dict(schema=1, source=database.path.name, sourceSha256=ARCHIVE_SHA256, + textures=textures, ballCanvasIds=[2, 3, 4, 5], retainedTargetCanvasId=8, + aimTextures=aim_textures, aimArchiveSha256=AIM_ARCHIVES.copy(), + aimFontPolicy='Original TIME set5; null space has zero advance;16-unit digits', + aimDigitIds=list(TIME_DIGITS), + tutorial=dict(source=source.name, sha256=VR07_SHA256, entities=records), + bindingPolicy='Exact resource identities; caller owns source timing, dimensions, billboarding and attachments') + output.mkdir(parents=True, exist_ok=True) + for entry, rgba in zip(textures+aim_textures, pixels+aim_pixels): + (output/entry['path']).write_bytes(rgba) + write_png(output/entry['png'], entry['width'], entry['height'], rgba) + (output/'baseball.json').write_text(json.dumps(manifest, indent=2)+'\n', encoding='utf-8') + return manifest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('original', type=Path) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + export_baseball(args.original, args.output) + print(f'Original Baseball resources exported: {args.output}/baseball.json') + + +if __name__ == '__main__': + main() diff --git a/tools/extractors/prepare.py b/tools/extractors/prepare.py index 8edf6e2..568102c 100644 --- a/tools/extractors/prepare.py +++ b/tools/extractors/prepare.py @@ -13,6 +13,7 @@ from ui import export_ui from gadget_resources import export_gadget_resources from gadget_followup_assets import export_meter from bubble_resources import export_bubble +from baseball_resources import export_baseball from sound_bank import export_sound_bank @@ -84,6 +85,7 @@ def main(): export_gadget_resources(Database(find_archive(args.original, 'screens')), args.output / 'gadgets') export_meter(args.original, args.output / 'invisible-meter') export_bubble(args.original,args.output/'bubble') + export_baseball(args.original,args.output/'baseball') effects = export_sound_bank(args.original, args.output / 'effects') print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities") for name in args.audio: diff --git a/tools/extractors/scooter_resources.py b/tools/extractors/scooter_resources.py new file mode 100644 index 0000000..8f8b216 --- /dev/null +++ b/tools/extractors/scooter_resources.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Export original Scooter resource data; do not assign attachments or playback. + +The two Scooter ASE morphs have 195 indexed positions, whereas scooter.omt's +body has 98. Keep these samples unbound rather than inventing UVs or a base. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +from ase import export_ase, read_ase +from entities import resolve_asset +from models import export_omt_model +from omt import Database, FormatError, read_shape +from png import read_png + +SOURCES = { + 'omt/scooter.omt': '8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81', + 'ASE/jimstop.ASE': 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0', + 'ASE/jimscooter.ASE': 'b27c8cb80811eb70e391fc061dab99c7d5f0b4d884c109b34c673a1815508299', + 'ASE/jimscooterstop.ASE': 'edcdcc879a28757994525f815c88cd6dd46dc788b69ba2f902323d6de48cb873', + 'ASE/godscooter.ASE': 'c18f1414ec2b397e0c8f8320f63830ab88630ea05a354bb99af34ce7fea79bd1', + 'ASE/godscooter2.ASE': 'fcf9ca5e8298efa7b4d551d9d09878c04f1f2647b6a30edfa2297617a7d63189', + 'png/jimycarl.png': '55ed165aaffe177cb62558a08d13fc3b2210da6e353065b108849d46df9dacb6', +} + + +def _json(path: Path, value): + path.write_text(json.dumps(value, separators=(',', ':'), allow_nan=False)+'\n', encoding='utf-8') + + +def export_scooter(original: Path, output: Path) -> dict: + original, output = original.resolve(), output.resolve() + if output.is_relative_to(original) or original.is_relative_to(output): + raise ValueError('Output must be separate from the original installation') + # Existing descendants are checked before any helper writes into them. + if output.exists() and any(p.is_symlink() for p in output.rglob('*')): + raise ValueError('Generated Scooter paths must not contain symlinks') + paths = {name: resolve_asset(original, name) for name in SOURCES} + for name, path in paths.items(): + if hashlib.sha256(path.read_bytes()).hexdigest() != SOURCES[name]: + raise FormatError(f'Unexpected original Scooter source identity: {name}') + database = Database(paths['omt/scooter.omt']) + shapes = {} + for identity, expected in ((0, ('goddard01', 98, 176)), (1, ('wheel', 32, 56))): + entry = next(e for e in database.entries if e.type == '3DSh' and e.id == identity) + shape = read_shape(database.payload(entry)) + if (entry.name, len(shape['vertices']), len(shape['polygons'])) != expected: + raise FormatError('Unexpected original Scooter shape metadata') + shapes[identity] = shape + animations = {name: read_ase(path) for name, path in paths.items() if name.startswith('ASE/')} + for name, animation in animations.items(): + expected_count = 195 if 'godscooter' in name else 426 + if len(animation['objects']) != 1 or len(animation['objects'][0]['samples']) != 2: + raise FormatError('Unexpected original Scooter animation objects/samples') + if any(len(s['vertices']) != expected_count for s in animation['objects'][0]['samples']): + raise FormatError('Unexpected original Scooter morph vertex count') + texture_path = resolve_asset(original, 'png/jimycarl.png') + texture = read_png(texture_path) + rgba = texture.pop('rgba') + texture.update(source=texture_path.name, sourceSha256=hashlib.sha256(texture_path.read_bytes()).hexdigest(), + rgbaSha256=hashlib.sha256(rgba).hexdigest(), path='../jimycarl.rgba') + manifest = dict(schema=1, sources=SOURCES.copy(), shapes=[], animations=[], unboundMorphs=[], + bindingPolicy='Resource-only export; caller owns original attachment, transforms and timing') + output.mkdir(parents=True, exist_ok=True) + for identity in shapes: + folder = f'shape_{identity}' + details = export_omt_model(database, identity, output/folder) + manifest['shapes'].append(dict(id=identity, path=folder+'/scene.json', **details)) + (output/'jimycarl.rgba').write_bytes(rgba) + for stem in ('jimscooter', 'jimscooterstop'): + animation = export_ase(paths[f'ASE/{stem}.ASE'], output/stem, paths['ASE/jimstop.ASE']) + animation['texture'] = texture + _json(output/stem/'animation.json', animation) + manifest['animations'].append(dict(source=stem+'.ASE', path=stem+'/animation.json')) + for stem in ('godscooter', 'godscooter2'): + animation = animations[f'ASE/{stem}.ASE'] + filename = stem+'-unbound.json' + _json(output/filename, animation) + manifest['unboundMorphs'].append(dict(source=stem+'.ASE', path=filename, + vertices=195, sourceTimes=[s['time'] for s in animation['objects'][0]['samples']], + reason='No matching textured base recovered; OMT body 98 and existing Goddard base 222 differ')) + _json(output/'scooter.json', manifest) + return manifest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('original', type=Path) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + export_scooter(args.original, args.output) + print(f'Original Scooter resources exported: {args.output}/scooter.json') + + +if __name__ == '__main__': + main()