Files
kinect/docs/game-internals.md

186 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# DanceEvolution Arcade (DEA / `gamekdm.dll`) — game internals & RE jumpstart
Everything reverse-engineered about how DEA consumes the emulated Kinect, plus a
jump‑start so another agent can continue a full RE/decompilation **without
redoing this work**. All gamekdm addresses use image base `0x10000000`.
The emulator presents an ordinary webcam as a Kinect v1: the native tracker
(`tracker-native/`, MediaPipe/BlazePose + ONNX) publishes a synthetic
depth/color/skeleton frame over a shared‑memory contract, and the Windows NUI
shim (`fallback/windows-nui/`, a drop‑in `Kinect10.dll`) serves it to the game.
We never modify any game file.
---
## 1. How DEA consumes the Kinect
- DEA loads `Kinect10.dll` (MS NUI v1 API). Our shim implements that ABI and
feeds the game our frames. The game's own NUI stack computes nothing extra for
the skeleton — we publish the 20‑joint skeleton directly; the game *does* run
its own selection/validation and a Flash menu cursor on top (below).
- Resolution: the game only accepts a **4:3** image. The tracker enforces 4:3
(`PopulateResolutions` filters to 4:3; depth/color are 640×480).
- The in‑process introspection tool (section 5) reads the game's live manager at
`*(gamekdm+0x3cf1b4)` — this is how everything below was discovered.
## 2. Skeleton rendering & the selection/validity gate *(solved)*
For the in‑game skeleton to render, our candidate skeleton must pass the game's
orientation/validity gate, decoded from `gamekdm`:
- `FUN_10018570` builds a gravity/floor‑relative transform `M`. If the gravity
vector at `manager+0x2c` is the sentinel, `M` is derived from the skeleton's
TRACKED joints (weighted ratio of tracked joints must exceed `0.85`, weights
`DAT_102a49e8`; then 5 limb‑direction dot‑products must each exceed `0.9`).
Feeding `vNormalToGravity = (0,1,0)` populates `manager+0x2c` and takes the
simpler gravity branch instead.
- `FUN_100e4140 → FUN_101ab6d0` is the candidate‑validity filter: it computes
`P1 = (-px, py + m13, -pz + m14)` (no perspective divide) and accepts only if
`P1` is within `0.05` of the box `[A-B, A+B]` where `A = DAT_103d3230 =
(0,1,0)`, `B = (1.22, 1, 0.675)` → box x∈[-1.22,1.22], y∈[0,2], z∈[-0.675,
0.675]. `m14 = 2.5` matches our published `z0`; `m13` is taken straight from
the skeleton frame's `vFloorClipPlane.w`.
- **The fix** (`sensor.cpp BuildSkeletonFrame`): publish all 20 joints as
`TRACKED`, `vNormalToGravity = {0,1,0,0}`, and **`vFloorClipPlane = {0,1,0,
1.0 - hip.y}`** so `P1.y = hip.y + (1 - hip.y) = 1.0` (box centre) every frame.
This auto‑centres the candidate and the skeleton renders. (Commit `36035cc`.)
## 3. The menu hand‑cursor (Flash/`afp` PhIZ) *(solved)*
This one is *not* in any DLL — it lives in the game's Flash runtime:
- `afp` is a **Flash/ActionScript runtime** (`libafp-win32.dll` exports
`flash.display.InteractiveObject`, `flash.ui.MouseCursor`, `useHandCursor`).
Menu UI (incl. the cursor sprite) is compiled Flash packed in the `.ifs`
archives under `contents/data/bm2d/*.ifs`.
- The moving cursor is the controller's own movie clip. gamekdm global
**`DAT_103d2bb8`** is the cursor‑controller object pointer; the live 1P cursor
is at `(*DAT_103d2bb8)+0x108/+0x10c` and 2P at `+0x110/+0x114`, in **screen
pixels (1280×720)**. `FUN_1007fbf0` reads it via `afp_mc_get_param(ctrl+8,
0x1008)` and snaps to the OK buttons (`_but_ok_1p/2p_usr`) when `dist² <
0x1fa4` (~90 UI units). The `_icon_1p/2p/only_usr` strings are the **OK‑button
icons**, *not* the cursor.
- **No gamekdm code writes the cursor from the hand** (no `afp_mc_set_param`
with `0x1008`; 53 decompiled menu AS scripts reference no hand/cursor/natal).
The hand→cursor PhIZ is inside the Flash/Natal runtime — a body‑relative,
reach‑normalised mapping we can't modify. The only lever is **our skeleton**.
- **Root causes & fixes** (all shim‑side, `BuildSkeletonFrame`; no tracker
rebuild needed):
1. **Handedness.** Our projection is byte‑identical to a real Kinect's
`NuiTransformDepthImageToSkeleton` (`kDepthProjectionScale = 3.501e-3 =
NUI_CAMERA_DEPTH_NOMINAL_INVERSE_FOCAL_LENGTH_IN_PIXELS`). But the tracker
mirrors the camera (selfie view, like a real Kinect's mirrored depth
image), and **mirroring swaps MediaPipe's L/R labels** (verified: a
mirrored frame's `RIGHT_WRIST.x ≈ 1 - LEFT_WRIST.x` of the normal frame).
So the shim swaps L/R joints back (`kSwap[]`) → the player's right hand
lands in `HAND_RIGHT` with +x relative to `SHOULDER_CENTER`, matching real
Kinect recordings (`HAND_R - SHOULDER_CENTER.x ∈ [-0.35, +0.86]`).
2. **Reach compression.** Measured against real Kinect v1 recordings (UTKinect
`waveHands` + MSR arm‑waves; see section 6), MediaPipe reports the hand
~**1.6× (x) / 1.3× (y)** *closer* to the shoulder than a real Kinect does
(scale‑invariant, shoulder‑width‑normalised — a genuine joint‑placement
difference), so one arm only covered part of the screen. The shim amplifies
each arm outward from its shoulder by `kArmGainX / kArmGainY` (tuned to
**3.2 / 2.6** empirically for full coverage without over‑sensitivity). The
hip/center‑of‑mass is left untouched, so the validity box stays centred.
## 4. Two‑player
- **The game supports 2P**: dual cursor slots (`CUR1`/`CUR2` above),
`NuiSkeletonSetTrackedSkeletons([id0, id1])`, and NUI's 6 skeleton slots.
- **The emulator does not** (yet): it's single‑person end‑to‑end — the contract
carries one `SkeletonFrame`, the shim fills only `SkeletonData[0]`, and the
tracker runs single‑person BlazePose. `tracker-native/build/two_person_probe`
is the reproducible Linux evidence: it composes a 24-frame two-person
prominence sequence from the committed `testdata/sample_rgb.bin`, drives the
shipping `PoseEstimator::acquire`/`run` policy, and prints the selected
nose/hip x-region every frame. The 2026-11-27 run emitted exactly one tracked
skeleton in all 24 frames; the ROI held A while B overtook it, then switched
to B at frame 14, and back to A at frame 22 (two identity switches, no loss).
- **Experimental CUR2 probe (off by default):** setting `KINECT_SHIM_2P=1`
makes `BuildSkeletonFrame` copy slot 0 to `SkeletonData[1]`, offset it
horizontally, and assign a distinct tracking ID. It is deliberately not a
claim of real 2P (both slots are the same pose and depth player mask). With
the variable unset or not exactly `1`, slot 1 remains `NOT_TRACKED`; slot 0's
hip and `Position` remain byte-identical. The env read + decision + fill live
in one shared `PopulateSecondSkeletonFromEnv` that both the production
`BuildSkeletonFrame` and the `two_person_shim_probe` host unit call, so the
probe asserts the real shipping gate (unset/`0`/empty/`2` -> off, `1` -> on,
on->off transition, slot-0 bytes unchanged) over the real environment
variable. This only permits an in-game check
whether DEA lights `CUR2`. Real 2P still needs a multi-person pose stage and
a two-skeleton tracker contract.
## 5. Debug tooling: in‑process game introspection
Because the shim runs inside `gamekdm.dll`, it can read the game's live memory.
`sensor.cpp DumpGameDisplayState()` dumps the manager, the skeleton‑selection
state, the validity matrix/box, and the live cursor; the per‑frame `handcur:`
log pairs our published joints with the live cursor value. Both are gated behind
`constexpr bool kShimDebug` (`sensor.cpp`, default **false**). Flip it true,
rebuild, and watch `kinect_shim.log` (`game-introspect` / `game-skel[1-4]` /
`game-cursor` / `handcur` lines). This is the method that cracked §2 and §3 —
reimplement the game's math in Python from a single dump, don't guess.
## 6. RE / decompilation jump‑start (for a fresh agent)
Everything you need to continue without redoing the groundwork:
### Ghidra (gamekdm.dll)
- Analyse **once** into a persistent project, then reuse it (re‑analysing per run
wasted 3–5 min each):
```
analyzeHeadless /home/athapa/ghidra gkproj -import gamekdm.dll # once, NO -deleteProject
analyzeHeadless /home/athapa/ghidra gkproj -process gamekdm.dll -noanalysis -postScript <script.py>
```
JDK21 at `/home/athapa/jdk`; scripts in `/home/athapa/ghidra/scripts/`
(`getFunctionContaining` + `decompileFunction`). Full objdump at `/tmp/gk.asm`.
- Key functions/globals (base `0x10000000`): cursor controller global
`DAT_103d2bb8`; cursor read `FUN_101d84c0`→`afp_mc_get_param(_,0x1008)`;
button‑hit `FUN_1007fbf0`; cursor state machine `FUN_1007e330`; icon‑reader
`FUN_10080360`; validity transform `FUN_10018570`; candidate filter
`FUN_100e4140`/`FUN_101ab6d0`; validity box `DAT_103d3230`, matrix
`DAT_103d4a80`; manager pointer `*(gamekdm+0x3cf1b4)`.
### afp / Flash data (the cursor PhIZ lives here)
- `ifstools` (pip, pure‑Python) extracts `data/bm2d/*.ifs` → `afp/<name>` (Flash)
+ `afp/bsi/<name>` (bytecode) + `geo/` + `tex/`.
- **bemaniutils** has the AFP ActionScript decompiler, but it is **not on PyPI**
and needs **Python 3.12** (not 3.14) — install from git and import only the afp
parser (its `mysqlclient`/server deps fail but aren't needed):
```
git clone --depth 1 https://github.com/DragonMinded/bemaniutils /tmp/bemaniutils
python3.12 -m pip install --break-system-packages Pillow pycryptodome cython
PYTHONPATH=/tmp/bemaniutils python3.12 -c "from bemani.format.afp import SWF, ByteCodeDecompiler"
```
Decompile a clip: `SWF("<name>", open(afp,'rb').read(), open(bsi,'rb').read())`,
`.parse()`, then walk `AP2DoActionTag.bytecode.decompile()` (see
`bemani/utils/afputils.py decompile_and_write_bytecode`). The menu scripts do
**not** contain the hand→cursor map — it's in the Flash/Natal runtime —
so next step is `libafp-win32.dll` (Ghidra project `afpproj`, already analysed)
around its `flash.ui.MouseCursor` / pointer handling.
### Real‑Kinect reference data (for calibrating our skeleton)
- UTKinect‑Action3D: RGB (1.79G) + synced 20‑joint skeletons (3.3M) +
`actionLabel.txt`, `https://cvrc.ece.utexas.edu/KinectDatasets/` (`RGB.zip`,
`joints.zip`). Joint order = NUI (HIP_CENTER=0 … HAND_R=11 … FOOT_R=19);
real‑world metres. `waveHands` frames are a clean hand sweep.
- MSR‑Action3D `MSRAction3DSkeletonReal3D` (github `Mabdou11/Activity-
Recognition-skeleton-datasets`): `a01`=high‑arm‑wave, `a02`=horizontal‑arm‑
wave. Compare `HAND_R - SHOULDER_CENTER` (shoulder‑width‑normalised) against
our published joints to re‑derive the reach gains.
### Can't run the game here
Wine is not installed and the build is an 8.2 GB spice2x arcade build needing
DirectX + a real camera — iterate with the build→deploy→playtest loop, not an
emulator. Deep‑low RE subagents repeatedly failed on this (armed a monitor and
exited, then hit a 429 at ~2.1M tokens) — do the game RE directly with the local
Ghidra setup.
## 7. Top remaining latency lever
Inference is now multi‑threaded (ONNX intra‑op, `pose_estimator.cpp`). The
biggest further win is a **GPU execution provider (DirectML)**: swap the
`onnxruntime-win-x64` CPU binary for `onnxruntime-directml` and
`so.AppendExecutionProvider_DML(0)`. Also optional: a short fixed camera
exposure (cuts sensor lag + motion blur, needs good lighting).