v1.0.13 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 371ee4692c.

Feature — Piano

The host-side glue for the gameplay layer. The actual rhythm-game core (chart parsing, judgement cursor, scoring, tick driver, audio adapters) ships as the workspace package @rhythm/engine; this feature owns only:

  • the React-side UI store and the play-mode judgement store (store.ts),
  • the asset manifest for sample playback,
  • the play screen + supporting HUD components,
  • the host-side hooks that wire @rhythm/engine's PlayController + useRhythmEngine to Magic Piano's sampler / backing track / popup / tile-dissolve UI (useMagicGameplay, useMagicJudgement).

If you're looking for the audio / MIDI / gameplay engines themselves, see packages/rhythm-engine/README.md. The legacy @piano/midi + @piano/gameplay-magic packages now thin-re-export from @rhythm/engine for backward compatibility while Learn + Zen migrate.

Files

src/features/piano/
  store.ts                            # usePianoUiStore + useJudgementStore (score/streak/counts)
  judgement.constants.ts              # play-mode pixel windows + popup constants + UI calibration; gameplay constants (points, multiplier tiers, semitone tolerance) live in @rhythm/engine
  hit-window-state.ts                 # module-private holder for the LIVE judgement windows; getJudgementWindowsPx() / setJudgementWindowsPx() — synchronous read path used by useMagicJudgement (no React, no MMKV import)
  hit-window-store.ts                 # MMKV-persisted zustand store (`useHitWindowStore`) for the player's hit-window calibration; subscribes itself to push live values into hit-window-state on every change
  countdown.constants.ts              # 3→2→1→"go"→null pre-roll state machine (constants + nextCountdownFrame; pre-roll timing: no hold, 550 ms digits, 350 ms GO = 2 s)
  prepare-load-progress.ts            # maps the four PlayScreen prepare gates to a 0–100 loading percent (Figma 7411:79766)
  lane-fit.ts                         # auto-fit keyboard window to song note range (min 10 white keys)
  resolve-segment-play-context.ts     # pure resolver for which part/full-song PlayScreen runs; pins the active part index for the play route
  audio-quantize.ts                   # BASE_QUANTIZE_WINDOW_MS (125 @ 120 = 1/16) + computeQuantizeWindowMs (BPM scale) + computeQuantizeWhenSec — early-press sampler delay (RC-gated; TimingPanel edits base)
  audio-quantize-store.ts             # MMKV `piano-audio-quantize-ms` — TimingPanel Audio quantize slider → getAudioQuantizeBaseMs for the hot path
  session-result-store.ts             # ephemeral snapshot passed from PlayScreen → PlayResultScreen on game over (score/stats/segment context); never MMKV-persisted
  session-result-navigation.ts        # pure helpers to build `/(app)/play` route params for Replay / Next section / Play full song
  session-result-tab.ts               # the Learn/Play toggle BOTH result screens run on — `GAMEPLAY_RESULT_TABS` (Play, then Learn) and `LEARN_RESULT_TABS` (Learn, then Play): two named orders over ONE object per half, so the columns share every label and testID and differ only in order, and neither can take the other's by flipping a shared array at its call site. Plus `resolveResultSelection` / `resultSelectionFor` (which card is selected: the tapped one while listed and on its own half, else the top card), `sessionResultNextTarget` (the SELECTED card of the lit half, its 1-based order, and whether it owes a rewarded video — it takes BOTH lists and indexes them by that half, so the pill cannot name a song the column is not showing) and `sessionResultEmptyTabNote` (what a half that has run out says under its toggle). Lives here rather than in `features/learn` because both columns read it and a feature may not reach into another feature's `components/`. See [features/songs.md](./songs.md#the-two-result-columns--one-learnplay-toggle).
  upcoming-highlight.ts               # look-ahead keyboard highlight cursor — driven by @rhythm/engine's headIdxSv
  hooks/
    useMagicGameplay.ts               # builds @rhythm/engine PlayController via host adapters; chart + controller live in refs; SoundFontSampler is `reactive: false` (await `whenReady`, no SF2 setState on PlayScreenBody) — only `isReady` / `error` are load-path React state (pause notifies HUD via `subscribeManualTransport`). Exposes melodyNotes, ticksPerSecond, sampler, controls (start/pause/resume + startPaused gate)
    useMagicJudgement.ts              # wires PlayController into useRhythmEngine; fans onTap/onMiss/onGameEnded into useJudgementStore + popup UI; every consumed hit shrinks in place; Perfect-only ripple/particles
    useAutoPlay.ts                    # converts NoteGroup[] (from PlayController) into auto-press cues for a passive demo path
    useResultSongSelection.ts         # the result column's selected card — the song "Next song" opens. The top card until the player taps another; a tap is kept with its half, so switching the Learn/Play toggle reselects that half's top card with no effect. Held by the Game Mode overlay and by the Learn screen
    useSessionResultSuggestions.ts    # what BOTH result screens' suggestion column offers — one pick + one lock enrichment for both halves of the Learn/Play toggle (`features/learn`'s `useLearnResultSuggestions` is a name over it). Learn half = songs that ship a learn chart only; Play half = the gameplay picker untouched
  components/
    GameplayHeader.tsx                # HeaderBackButton, HeaderPlayPauseButton, GameplayHeaderBackground (interactive chrome only; score digits live on lane canvas via HeaderScoreLayer)
    MultiplierBadgeLayer.tsx          # top-right HUD pill in its OWN `SkiaGraphiteView` (a sibling of the lane `<Canvas>` in `PlayGameCanvas`, not a canvas node): its own `useFrameCallback` steps the sim and records one Graphite frame (`MultiplierBadgeLayer.graphite.ts` — pure draw + record, glow margin `BADGE_GRAPHITE_PAD`) whenever the sim is dirty, at the layer's `tickCadence` (default `60FPS`; the whole frame — sim step and record — is skipped between ticks, `frame-by-frame` = every UI frame), so the crest never re-records the lane scene graph; the mount warmup starts once the view has a context + the label font, so every pulse frame is really recorded. Paints/shaders are rebuilt only when a tier color string changes. (The notes below describe the sim and visuals, unchanged.) Always drawn at its HUD slot; opacity 0 at x1, opacity 1 at x2+ (keeps water fill warm so first show isn't a mid-streak hitch). Mount-time GPU pulse paints tier-2 water/shadow colors at an imperceptible opacity (`BADGE_PIPELINE_WARMUP_PEAK_OPACITY`, ≥ 2/255 so Skia still runs the programs — the scrim does not cover the HUD, and a full-opacity pulse flashed an "x1" badge on song open) while sweeping the pop scale range (`MultiplierBadgeLayer.warmup.ts` — same idea as `GameplayGlowLayer`) so the first live theme 1→2 crossing reuses a compiled LinearGradient path. Rising water-fill toward the next tier — each rise eases out over at least `WATER_RISE_MIN_MS` (450 ms) so a single hit's bump glides instead of stepping. No border stroke; the track under the water is opaque `gameplaySkyBase` (the game-mode backdrop); after a tier-UP while shown (x2 → x3 …) the previous tier's full water gradient is painted over that track (`underOpacity` = `BADGE_WATER_OPACITY`) so the old color stays and the new tier's wave fills over it — a tier-down or reset clears it and carries ONE blurred rrect under the track — `<BlurMask blur={BADGE_SHADOW_BLUR}>` (every tier; a mask filter on Skia's analytic rrect-blur path, not a `<Shadow>` image-filter saveLayer) tinted with the water gradient's first stop (`lightColor`) — flat, never a gradient — so it only shows around the pill. Because Skia scales the blur sigma by the pop transform, the mount warmup sweeps the pill through every pop / drop scale (`badgeWarmupScaleSweep`, 0.94 → 1.35 opaque then back translucent) under the prepare scrim so no blur kernel compiles at the first live x2. The same hold also draws the under layer (a `Rect` + 3-stop gradient at `BADGE_WATER_OPACITY` inside the clip — live, it first appears on the x2 → x3 tier-up, so without it the first x3 after install compiled its GPU program mid-song) and the `xN` label (x1..x6) is baked ONCE into a small image sheet (`MultiplierBadgeLayer.label-atlas.ts`, pure geometry in `MultiplierBadgeLayer.label-layout.ts`) and drawn each frame as an image sub-rect (`drawImageRectOptions`) — never as `drawGlyphs` under the pop scale, because Skia keys a new glyph strike per scale and re-rasterises the label into the Graphite text atlas (~24 MB at startup + a hitch per tier pop in the 2026-11 Instruments trace); `MultiplierBadgeLayer.label.source.test.ts` guards it. The water crest drifts ping-pong (`sampleWaveLoopPhase`, cosine-eased there-and-back over `WAVE_LOOP_MS`) — never wraps, since the gradient rides the path and a wrap snapped its colors. Parent fires imperative `badgeRef.update({ fillRatio, displayMult, tier })` / `setVisible` / `reset` via `useGameplayHudBridge` (leaf never subscribes to the judgement store). Data-driven (`MultiplierBadgeLayer.sim.ts`): the handle only writes a seq-stamped command (latest value + seq per track, published once per microtask); ONE FX-frame runner applies it at the FX clock and steps fill / crest / fade / pop / tier tint / warmup analytically into two render caches (`waterRenderSv`, `badgeRenderSv`) that Skia props read via `useDerivedValue` — no withTiming / withRepeat / rAF, ~5 SharedValues total, idle frames notify nothing, zero React commits on hit. Layout position is pure canvas math (`computeMultiplierBadgeCanvasPosition`).
    HeaderScoreLayer.tsx              # Skia HUD score on PlayGameCanvas — "Score" caption + odometer digit columns (once-baked glyph wheel, UI-thread scroll). Parent pushes score via `scoreRef.setScore` from `useGameplayHudBridge` (no leaf store subscribe); `setScore` only writes the target and an FX-frame runner counts the shown value up to it (`resolveScoreCountUp`, `SCORE_COUNT_UP_MS` ease-out; a lower target snaps). Digits are centered in columns pitched at `SCORE_DIGIT_PITCH_RATIO` of the widest ink.
    JudgementPopup.tsx                # imperative Skia popup pool — fires PER-NOTE `+points` glyphs at each tile column. `fire(centerX, centerY, judgement, points)` takes the score delta the hit awarded (`pointsFor(j) × pre-hit multiplier`, snapshotted by useMagicJudgement from the store before/after `applyHit`); the glyph reads `+N` via `formatPointsLabel` in JudgementPopup.utils.ts. Non-positive deltas skip the per-column popup (Miss is flagged by the central "MISS" label only; defensive skip on NaN / negative). Color still tracks the judgement (the `judgement*` theme tokens) so the player reads timing at a glance — the popup draws two quads per char — the shared white outline cell tinted with that judgement's stroke color (`pointsOutlineTints` ← `strokeByIndex`, so a hit's `+N` always matches its centre label's outline), then the white fill cell over it — and the sheet holds 2 × 11 cells whatever the theme. The `+N` keeps a 1 pt outline (the centre label's is 2.5 pt).
    CenterJudgementLayer.tsx          # single-slot Skia layer pinned at the top-center of the lane — renders the judgement LABEL with combo suffix (PERFECT+ / PERFECT / PERFECT 2 / GOOD / EARLY / LATE / MISS — words from `JUDGEMENT_LABEL`; the `great` / `tooEarly` judgements display as GOOD / EARLY) per tap and per missed GROUP (NOT per missed note, so a chord miss doesn't multi-stack identical labels). Whole words + combo-number streak chars are baked once per theme into ONE merged atlas — MaxRects-packed, each cell cropped to the glyph's ink (`measureText` bounds — cap height to baseline, not the font's whole line) plus `judgementGlyphPad(style)` of margin (when the style glows, the outer halo's tail: `GLYPH_PAD` = 13 pt = 2.25σ of the outer blur, ~1–2 % alpha, for PERFECT / PERFECT+ and their `N` — measured from the glyph's edge, the outline lies inside it; outline half-width + 1 pt, ~3 pt, for GOOD / LATE / EARLY / MISS and ~2 pt for the `+points` popup, which have no halo; the streak number is baked in two white parts per char — its glow alone (`sfx:h:<ch>`, tinted yellow after PERFECT / red after PERFECT+ by `streakHaloTints`; every tier's `sfx:<ch>` aliases it) and its outline + fill with no glow (`sfx:c:<ch>`, cropped to the ink, drawn over the glow at the glow's cell + the origin gap) — so the two tiers no longer bake two identical digit sets and the core carries none of the glow margin; it was 44 pt, then 20 pt (3σ), then 16 pt (2.5σ + outline), on every side). The `+points` glyphs are baked ONCE, not per judgement color: a white outline cell and a white fill cell per char (`pts:o:<ch>` / `pts:f:<ch>`), every `pts:<judgement>:<ch>` aliasing the outline (`pointsAtlasShares`) of the full line), PERFECT / PERFECT+'s combo twins sharing ONE cell (`WORD_KEY_SHARES`) and the space baked as a 1 px cell, which together should take the sheet from ~22 MB to ~5 MB at the same 3× bake (estimated from cell sizes; confirm in the WebGPU Planes panel). The packer is capped at 4096 px on the longer side (`JUDGEMENT_GLYPH_ATLAS_MAX_SIDE`) because smallest-area alone can pick a strip wider than the GPU's texture limit (triple blur + stroke + fill — streak suffix chars are baked once per glow — tier 1 yellow, tier 2 red — so `28` matches PERFECT / PERFECT+). The combo has no `x` prefix — `x4` belongs to the multiplier badge. Outlines are 2.5 pt with round joins, each judgement in its Figma colour (theme tokens `judgementPerfect` Amber/400 for PERFECT and PERFECT+, `judgementGreat` Green/500, `judgementLate` Blue/600, `judgementMiss` Red/600, `judgementTooEarly` Orange — the per-note `+points` popup follows the same map). Only PERFECT / PERFECT+ glow — PERFECT yellow `rgba(255,195,0)`, PERFECT+ red `rgba(255,0,0)`, at any combo, blur sigmas `[5.6, 3, 3]`; the number suffix is baked in both glows and wears the glow of the word it trails: GOOD / LATE / EARLY / MISS bake as outline + fill alone (`judgementWordPaint`, Game Mode's look; the drills' PERFECT look keeps the glow). The bake is ~0.9 s of JS-driven work, so it goes through the process-lifetime cache in `judgement-atlas-cache.ts` (keyed by colors + word look; font + bake scale are process constants) and, on the first play, is **time-sliced**: `useGameplayHudAtlases` asks `judgement-atlas-queue.ts` for the two sheets, which bakes one job at a time — a few cells per idle slot (`JUDGEMENT_BAKE_SLICE_MS`), the surface readback in a slice of its own (`startSpriteAtlasBake` in `sprite-atlas.ts`) — so the loading UI keeps painting instead of freezing for the whole bake; `hud.ready` flips when both settle and the lane waits for it (up to `HUD_WAIT_MS`). There is still no launch prewarm (it held the splash and weighed on FTUE load); replays and later plays are cache hits, and the layers' own synchronous `getJudgementCenterAtlas` / `getJudgementPointsAtlas` read the same cache. Set at `CENTER_FONT_SIZE` 24 on a phone (42 on iPad), letters opened up by `JUDGEMENT_TRACKING_EM` (+0.1 em — the 2.5 pt outline eats the gap) and the word→number gap set by `SUFFIX_WORD_GAP_SCALE` (1.2 spaces) ([`judgement-glyph-layout.ts`](../../src/features/piano/components/judgement-glyph-layout.ts)), its top at `centerJudgementTopY(IS_TABLET)` ([`play-screen-layout.ts`](../../src/features/piano/play-screen-layout.ts)): `PLAY_SCREEN_CENTER_JUDGEMENT_TOP_OFFSET` (42), plus `PLAY_SCREEN_CENTER_JUDGEMENT_TABLET_NUDGE` (44) on iPad, with no safe-area inset — the tutorial's training and song use the same helper, so they sit there too. Pop-scale animated (no upward rise). Mounted inside PlayScreen's unified lane canvas (`PlayGameCanvas`) alongside the per-tile popup / ripple / particles. A re-fire while the label is still on screen swaps it in place at full alpha and punches 1.15 → 1.0 over 100 ms (`CENTER_JUDGEMENT_PUNCH_*`) instead of replaying the 0.6 → 1.18 entrance from alpha 0 (that replay read as a flicker on every hit); a fire on an idle label still plays the entrance; the opt-in `staticPreview` prop (Component Labs → Judgement only) pins a fired label at its rest pose instead of fading it out; the same `formatPopupLabel` helper from JudgementPopup.utils.ts owns the format rule. Also bakes TOO SHORT, which only the training fires (`fireWord`, the hold drill's early release); Game Mode never shows it.
    CountdownOverlay.tsx              # full-screen pre-game overlay — prepare-art background + VIP promo copy (Figma 7411:79764) and the "3 → 2 → 1 → GO!" pre-roll. No React state: both cards are mounted from the first render and cross-fade on opacity SharedValues; the phase is a numeric SharedValue (`COUNTDOWN_OVERLAY_PHASE` in `CountdownOverlay.utils.ts`: `loading`/`countdown`/`dismissing`/`hidden`) owned by `hooks/useCountdownPreRoll.ts`; the Get ready! glyph column is driven by the same step SharedValue (`CountdownGlyphOverlay` `frameSv`). The "Get ready!" column also draws the song's cover above it when handed one (`songTitle` / `cover`) — the shared [`SongCoverDisc`](../../src/components/SongCoverDisc.tsx), Learn Mode's card disc, ringed with the pick-song cover's gradient band (`song-cover-ring.ts`) — on Game Mode and on the tutorial song alike.
    GameOverSummary.tsx               # legacy end-of-song summary overlay — superseded by SessionResultOverlay (kept until tests + old surfaces migrate)
    SessionResultOverlay.tsx          # final result card — centered stars/meta/score/stats (Figma 7399:56020) or split summary + recommendations (Figma 7411:77088). The recommendation column carries the Learn/Play toggle once Learn Mode is open (`useLearnUnlocked`, four finished songs — [songs.md](./songs.md#learn-mode-opens-after-four-finished-songs)); until then there is no toggle, `shownTab` stays on Play, the column is the plain "Recommended for You" Play list and the layout gate ignores the Learn half. The tutorial's result passes `learnTab={false}`: onboarding never offers the Learn half, whatever the install has unlocked. The overlay owns the lit tab (opens on **Play**), takes both halves' picks from [`useSessionResultSuggestions`](../../src/features/piano/hooks/useSessionResultSuggestions.ts), keeps the column's selection in a per-result store (`result-selection-store.ts`: each card reads its own "selected", `SessionResultActions` the pill's glyph, `SessionResultPreviews` the selected id — a tap re-renders only the cards whose ring moves), and its "Next song" pill opens the selected song via `sessionResultNextTarget` — handing it out with its order and the tab on `onPlayRecommendation` / `onUnlockRecommendation`, with the video glyph when it is ad-locked. The split layout is gated on either half having cards, so the toggle never re-runs the reveal. HUD-leaf gate on `selectGameOver`; renders inside a transparent full-screen `<Modal>` with `<SessionResultBackdrop>` and top `<SessionAdPlaceholder>` banner. The three-star badge is the shared [`ResultStarBadge`](../../src/components/ResultStarBadge.tsx) in `src/components/`. The overlay renders once while the result arrives: its previews run in `ResultPreviews` (a leaf that draws nothing, `@core/result`), the reveal's steps (docked, actions up, failsafe) live in a per-result reveal store read by `ResultRevealView` and `SessionResultCelebrate`, and `onRevealComplete` fires from a store subscription. The failsafe only forces the end state when the reflow never reported landing. The banner slot and the content box under it are `SessionResultFrame`, which holds the banner's reported height (the dock measure reads the latest inset from a ref), so the report re-renders the frame alone. "Next song" is a stable handler and the action row, the docked summary and the reveal views' styles are memoized, so a tab flip or a card tap re-renders only the column. The play itself is recorded for the Profile tab at game over (`play-screen-game-over.ts`), before the result mounts — recorded from the result, it re-picked the suggestions and redrew the Song List under it; `PlayResultScreen` keeps only `song_result`, and sets no `<Stack.Screen options>` of its own (the route's options live in `app/(app)/_layout.tsx`).
    SessionResultCountUpScore.tsx     # the result's hero score: grouped score + the block VoiceOver reads as one thing (`Score N`, the landed figure). The paint is the shared [`ScoreFigure`](../../src/components/ScoreFigure.tsx) in `src/components/` (`hero` 70/91 — the tablet celebration's, only drawn on iPad so it always reads 91/118; `compact` 56/72 — the phone result's; both extrabold with a 1pt #FFFFFF outside stroke + `0 0 4px #0084FF` glow and the `scoreNumber` gradient, written as phone numbers and scaled by `TABLET_TYPE_SCALE`). `ScoreFigure` is ONE Skia canvas fed by the count-up store: the store's subscription writes the text to a shared value and `score-figure.layout.ts` lays the glyphs out on the UI thread, so the 1.4 s roll makes no React commit. Learn Mode's accuracy percentage renders through the same component at `compact`, so the two results' big numbers cannot drift apart.
    SessionResultScore.tsx            # a score that does not roll (the part result's summary) — the same `ScoreFigure` on a count-up settled on its first frame.
    SessionResultCelebrate.tsx        # stars + meta + score (+ stats); single instance that docks left beside recommendations via measured translate.
    SessionResultLayout.utils.ts      # content top-inset + left-column width tokens for the result layouts.
    SessionRecommendationList.tsx     # "Recommended for You" stack on the result overlay. Given `tabs`, the heading is replaced by the shared [`SegmentedToggle`](../../src/components/SegmentedToggle.tsx) Learn/Play pair, `songs` is the LIT half's own list (the Learn half lists only songs that ship a learn chart). A tap on a card selects it (`selectedId` / `onSelectSong`); the overlay's "Next song" opens the selected one. A half with nothing left keeps the toggle up over `sessionResultEmptyTabNote`. The halves read Play, then Learn (`GAMEPLAY_RESULT_TABS`) at the Learn result's `large` size on every device; `compact` (banner-shrunk phone) now only shrinks the cards' covers.
    SessionRecommendationCard.tsx     # selectable recommendation row on both results — a short row on a phone (52/48 pt cover, `DifficultyChip` pill, no stars; see songs.md) — no CTA: a tap on the body selects it (2 pt `songCardSelectedBorder` ring, `accessibilityState.selected`) and the host plays its preview in place of the one sounding; a tap on the cover selects it and toggles the preview (also a VoiceOver action). Only the selected song is heard, on a loop (`useSongPreviewLoop`). Each card reads its own "previewing" flag from the result's preview store (`@core/result`), and only its shell and its cover (`SessionRecommendationCover`) redraw when it changes: the artwork (`SessionRecommendationCoverImage`), the text and the pill (`SessionRecommendationDetails`) and the surface are memoized leaves.
    SessionSongMeta.tsx               # text-only song title / artist / chip block (no avatar).
    pick-session-recommendations.ts   # pure picker for recommendation cards (same-genre bias).
    SessionResultBackdrop.tsx         # shared celebration backdrop — static `prepare-asset-background.png` (same as {@link PrepareLoadingOverlay}) cover-fit over `sessionResultBackground` for every post-session overlay. Tutorial interstitials still use [`SessionConfetti`](../../src/components/SessionConfetti.tsx), now geometry-based (~24 Skia rects) instead of a full-screen fragment shader.
    SessionAdPlaceholder.tsx          # ad-slot placeholder banner (Figma 7411:75271) shown while the real ad SDK loads.
    SessionPartResultSummary.tsx      # horizontal song + score/stats row for section-complete overlay (Figma 7411:75297).
    SectionCompleteOverlay.tsx        # section-complete result overlay (Figma 7021:89471 — parts progress bar + ad + horizontal summary).
    PickModeOverlay.tsx               # legacy mid-song pick overlay (Figma 3:5903). Superseded by SectionCompleteOverlay for part-complete results; kept for reference.
    FullSongUnlockedOverlay.tsx       # "Full song unlocked!" celebration overlay (Figma 7021:90779 — labelled {@link PartsProgressBar} + part score summary when finishing the final segment, gradient title, ad banner, prepare-art backdrop). Parent-driven visibility. The former `__DEV__` QA header cycle (`QA → PART → FULL → DONE`) is not mounted on PlayScreen.
    PausePanel.tsx                    # in-game pause overlay (Figma 7021:83231 — top ad skeleton, Background-Audio slider + Piano-Sound slider + Haptic toggle + action bar). The two volume sliders push live into useMagicGameplay's setBackingVolume (OGG track or rhythm-track melody) / setPianoVolume (sampler master) buses. The song's cover (`SongCoverDisc`) sits 36 pt above the volume rows; the stack starts 12 pt below the banner (its reported height), and the 80 pt gap above the actions is a spacer that shrinks to 16 when the panel runs out of height — a phone with the cover — while the iPad keeps 80.
    TimingPanel.tsx                   # hit-window calibration overlay. Rows follow lane order top → hit line → below: Too-early, Great, Perfect, Perfect+ (no Miss row — late miss stays automatic via `perfectLate`). Perfect+ is the nested hitline core (factory = the subdivision ladder `BASE_TIMING_SUBDIVISIONS`: Perfect+ 1/32 = 62.5 ms, Perfect 1/16 = 125, Great 1/8 = 250, Too-early 1/4 = 500 @ 120 BPM, scaled per song by `60000 / (bpm × sub)`; the DevTool **Timing** tab edits the same stores in subdivisions, see docs/devtool.md#timing-tab). Sliders edit base ms @ 120 BPM into useHitWindowStore (MMKV); each row shows **live** signed ms range + lane px from the same `computeTimingWindowsPx` path TimingZoneConfigOverlay paints. Late-Perfect grace (`perfectLate`) stays on the factory default (not a panel slider — avoids Perfect / Perfect-late confusion). **Audio quantize** slider edits base ms @ 120 into `useAudioQuantizeStore` (factory 125 = one 16th = sub 4); live window is `base × 120 / bpm` via `computeQuantizeWindowMs`. A separate **Backtrack fade out** slider edits the auto-pause soft-pause seconds (`useBackingSoftPauseFadeStore` → `getBackingSoftPauseFadeSeconds`, factory 3s). Cascade-clamp + label helpers live in TimingPanel.utils.ts (`clampHitWindows` / `formatRange` / `formatLanePx`). Triggered from HeaderTimingToggle. The pill, the panel and the lane `TimingZoneConfigOverlay` (Perfect bands, Great/Too-early lines, faint accent gradient for the live audio-quantize window above the hit line) all show only when `useTimingToolsEnabled()` is true: env `EXPO_PUBLIC_TIMING_TOOLS_ENABLED=1` **or** RC `timing_config.enabled`. The native FPS HUD is likewise env `EXPO_PUBLIC_PERF_HUD_ENABLED` **or** RC `show_devtools`. Opening pauses the song, closing resumes (defers to the pause panel when both are mounted).
    SessionActionBar.tsx              # shared 3-button action row (Replay / Songs / Next or Play) used by every result/pause overlay; the Game Mode result draws Song list + Replay as round glass glyphs (`secondary="round"`, `@components/GlassGlyphButton`, as the Learn result does) beside a labelled Next song.
    SessionSongHeader.tsx             # shared song header (avatar + title + artist + difficulty chip) used by every result overlay.
    JudgementStatsRow.tsx             # shared result stats row: PERFECT / GOOD / EARLY / LATE / MISS in one row (PERFECT counts Perfect+ — `mapJudgementCountsToStats`), labels from `JUDGEMENT_LABEL`, strokes from `JUDGEMENT_COLOR_TOKEN` — with optional leading Score column. Accepts `visibleColumns` to render a subset.
    PartsProgressBar.tsx              # labelled parts track (Part 1 → Part 2 → Full song) atop SectionCompleteOverlay (Figma 7021:89471).
    VolumeSlider.tsx                  # (dev / mixer surface)
  screens/PlayScreen/                 # play surface folder
    index.tsx                         # re-exports PlayScreen + public props/types
    PlayScreen.tsx                    # outer shell — segment session pin, body remount key, ad lifecycle
    PlayScreenBody.tsx                # composes the Skia gameplay stack (`PlayGameCanvas` + judgement + pre-roll); stays free of `useJudgementStore(...)` hooks
    GameCanvas.tsx                    # the lane (`PlayGameCanvas`): sprite planes presented through WebGPU canvases, hit line + score on small Skia break canvases (`LaneBreakCanvas.tsx`)
    GameplayGroup.tsx                 # memo-isolated lane + keyboard group
    SongProgressRail.tsx              # top-of-lane song progress rail
    BackgroundLayer.tsx               # night-sky backdrop (parked; available for re-enable)
    HudOverlayGroup.tsx               # pause / timing HUD overlays
    PrepareAssetGroup.tsx             # prepare scrim + 3-2-1 countdown
    GameOverBridge.tsx                # null-render leaf — owns `selectGameOver` so song-end does not re-render PlayScreenBody / canvas siblings
    layout.ts                         # hit-line + centre-judgement layout helpers
    utils.ts                          # pure play-session helpers
    types.ts                          # FtueGameplayTracking + shared screen types
  screens/PlayResultScreen.tsx        # post-game result surface — `router.replace` target after game over; unmounts the live play tree before segment-progress writes can re-render it. One `leaveResult(placement)` owns every trip back to the song list, and runs its interstitial before the pop (see [interstitial-ads-logic.md](../interstitial-ads-logic.md))

Immersive input — system gesture deferral (iOS) + keep-awake. Bottom-edge Home / app-switcher deferral is app-wide (AppProviders → setGameplayGestureDeferralEnabled → modules/screen-gesture-defer). PlayScreen, LearnModeScreen, and KeyboardScreen each call useKeepGameplayAwake so the device does not auto-lock mid-session. Android gesture deferral is a no-op today. See architecture.md § System gesture deferral.

Dependencies

The feature imports @piano/sdk for catalog / song-config / sampler config, and @rhythm/engine directly for chart parsing, judgement, scoring, and the React bindings. Adapter wrappers (src/core/sdk/adapters/rhythm-engine-adapters.ts) bridge the host's piano sampler (PianoSamplerLike — the iOS native engine, see audio-engine.md) into ISamplerAdapter.

Engines

Magic mode runs on @rhythm/engine's PlayController + useRhythmEngine React binding. The host hooks useMagicGameplay (lifecycle) and useMagicJudgement (UI bridge) compose them. Learn and Zen still run on the legacy @piano/gameplay-{learn,zen} packages until they migrate.

Play-mode judgement system

playMode === "play" is judged: every melody tile is scored against the player's tap timing.

  • Where the rules live. Pure gameplay rules — the Judgement type, the classifyHit classifier, the bitmask RhythmCursor, and the evaluateTap / sweepMissedGroups primitives — live in packages/rhythm-engine/src/{cursor,judgement}/ and carry a 'worklet' directive so they're callable from the UI thread. The package speaks ticks (the engine's native unit); the feature folder converts pixel windows to ticks at the boundary inside useMagicJudgement.

  • Bitmask cursor over a queue. RhythmCursor packs the chart into typed arrays (Float64Array noteTimes, Uint8Array noteCounts, Uint32Array groupOffsets, Uint8Array noteClaimed / claimedCount) allocated once at song load. Claims are O(1) byte writes, "fully claimed group?" is claimedCount[i] === noteCounts[i], and look-up scans run from headIdx bounded by the early window. This replaced the legacy set-based JudgementCursor (lazy Set<number>[] over a copied groups list) which churned GC on long songs.

  • Best-judgement claim policy. evaluateTap scans every eligible group containing a note within MAGIC_NOTE_TOLERANCE_SEMITONES of the pressed key (or — at the current strict default of 0 — only exact-key matches) AND inside the cursor's group-lookahead window (MAGIC_MAX_GROUPS_AHEAD, which defaults to 1 — see "Head-only lookahead" below). It claims the one whose timing produces the BEST judgement (perfectPlus > perfect > great > tooEarly > miss), with ties resolved by smaller note-distance (so an exact match wins over a near-miss with the same judgement) and finally by EARLIEST group. This fixes a cascading-miss bug in fast same-key passages: when notes repeat at e.g. 1000/1020/1040 ticks and the player taps slightly late, the first-match policy used to claim the earlier note as a late miss and shift the cascade — turning four perfects into four misses. Picking the best-rank candidate leaves the un-tapped earlier group to the periodic miss-sweep instead. The note added to the per-group claimed Set is the EXPECTED note (not the pressed key), so a near-miss claim doesn't leave the actual expected note un-tappable on a follow-up press.

  • UI calibration. judgement.constants.ts (in the feature folder) holds the pixel windows / popup constants / labels / color tokens / streak-tier table — everything that's UI calibration rather than gameplay rule. Tweaking gameplay feel is a single-file edit. The window widths are runtime-tunable by the player via <TimingPanel>; the constants file holds the FACTORY DEFAULTS that the persisted useHitWindowStore (in hit-window-store.ts) hydrates from on first launch.

    • Pixel-based bands (signed offset p of the tile from the hit line, negative = above the line / playable, positive = past the line). Lane top → hit line nests Perfect+ (exact hitline core, 12 pts) inside Perfect (10 pts). Perfect is the only band that extends past the line — perfectLate grace defaults to 4 px so a tap landing a hair after the tile crosses still scores Perfect / Perfect+ (matches the small input lag players unconsciously expect on touch displays). Late grace is factory-tuned (not exposed on <TimingPanel> — Perfect / Perfect-late as two knobs confused calibration). Defaults shown — the player can widen / narrow Perfect+ / Perfect / Great / Too-early via <TimingPanel>:
      • -2 ≤ p ≤ 0 → Perfect+ (12 pts) — hitline core, nested inside Perfect
      • 0 < p ≤ min(2, 4) → Perfect+ (12 pts) — late-side hitline core inside perfectLate
      • -8 ≤ p < -2 → Perfect (10 pts) — early-side Perfect envelope outside Perfect+
      • min(2, 4) < p ≤ 4 → Perfect (10 pts) — remainder of late-side perfectLate grace
      • 4 < p ≤ 4 + greatLate → Great (7 pts) — optional extra late Great grace (greatLate, ms @ 120 BPM past perfectLate, default 1/8 = 250 ms, 0 = off; <TimingPanel> "Great late grace" row, DevTool set_timing subdivisions.greatLate, 0 = off). The claim gate and miss sweep both wait until perfectLate + greatLate (lateClaimTicks in @rhythm/engine).
      • -18 ≤ p < -8 → Great (7 pts) — early-only
      • -33 ≤ p < -18 → Too early (2 pts) — early-only
      • p > 4 (tile past the late-Perfect grace) → Miss (0 pts) — automatic; the periodic miss-sweep registers it within ~one frame of the deadline, not the tap path
      • p < -early (before the Early window) → Early while the tile is on screen (visibleAhead = lane top → hit line in ticks, computeVisibleAheadTicks): the note is claimed and consumed like any Early. Before the tile shows, the press is a plain key — sampler sounds, nothing is judged, the note is untouched
    • Streak bands live in one STREAK_BANDS table (judgement.constants.ts), with score multiplier = badge = theme tier: 0–9 x1 (badge hidden, Cyan) · 10–24 x2 (Blue) · 25–44 x3 (Purple) · 45–69 x4 (Pink) · 70+ x5 (Red orange). Theme palette 6 (Orange) is kept for the effect labs only. Perfect+ and Perfect both extend the streak by 1; every other judgement applies STREAK_PENALTY (streakAfterJudgement) at every tier: Great keeps the streak (no +1), Too early / Late / Miss drop it by 5 (floored at 0, the multiplier follows) — per judged note, so a missed N-note chord costs 5 × N. A right-key press before the Early window on a visible tile is a real Early (points, −5 streak, tile consumed); MISS only comes from a note left frozen on the hit line past the 1.2 s Late grace (or the miss sweep when auto-pause is off). Points are never subtracted. Stars (computeLogicStarsFromCounts) use only the Perfect rate, so the streak rules never change them. Score helpers live in the feature store (streakMultiplier / pointsFor / keepsStreak); the hot path folds hits through a mutable ScoreAcc (applyJudgementInPlace / closed-form applyPerfectsInPlace for Perfect runs). Score / badge / theme tables (MULTIPLIER_TIERS, DISPLAY_MULTIPLIER_TIERS, THEME_TIERS, SCORE_MULTIPLIER_FLOORS, nextScoreMultFloor) are derived from STREAK_BANDS so retuning tiers cannot drift. Auto-play / note-press batches mutate one preview acc then applyScoreSnapshot once — no second for-loop on commit. @rhythm/engine keeps a simpler reducer for package tests only. Each tier also drives a full visual color story via MULTIPLIER_THEMES — when the streak crosses a tier, every gameplay layer (tile palettes, hit-line glow, night-sky background sky-base + nebula tint, ripple / particle hues) flips palettes in lockstep so the lane reads as one cohesive color story per tier.
      • <a id="multiplier-driven-color-theming"></a>Tier transitions cross-fade over THEME_TRANSITION_DURATION_MS on the cheap surfaces — the night-sky background u_deep/u_rim SkSL uniforms (per-channel withTiming via useAnimatedThemeRgb; the parked energy-gradient backdrop uses the same hook), the hit-line downward glow gradient (peak + fade stops cross-fade via useTierThemeColor, driven straight off the gameplay tier SharedValue on the UI thread so the color eases instead of snapping with the tile-picture rebuild — the thin core stroke stays a static white #FFFFFF). Falling-tile bodies snap atlas sprite keys on the flip; falling beams retint via <ColorMatrix> on geometry-only mask pictures (BEAM_LANE_TINT_MATRICES) — no beam SkPicture rebuild on tier cross. Held-tile palettes still snap (pinned pictures). Tap-ripples + spawn-particles read the tier at fire time, so new instances arrive in the new color while in-flight ones finish in the old. The duration constant lives next to the table in multiplier-theme.ts; the two animated-theme hooks live in hooks/useAnimatedTheme.ts.
      • Keyboard highlight (no React re-render). Next-note wash uses fixed white/black lane accents from tile-colors (same as <TileFalling>). Imperative setHighlightNotes on AtlasPianoKeyboard builds a plain payload, skips the hop when the highlighted set is unchanged, and applies it with one scheduleOnUI — no React commit and no JS-side .value reads (a JS .value get is a synchronous UI round-trip; it cost ~10 ms per update). Overlay visibility lives in one per-key flag cache (overlayFlagsSv) rebuilt on the UI thread; key/overlay transforms never wake on press frames. Gameplay wraps the keyboard in <MultiplierAwarePianoKeyboard> (passthrough + remote-config interactionBlocked only).
      • Tier crossings never re-render the play tree. GameplayThemeTierProvider mirrors selectThemeTier onto one SharedValue via useJudgementStore.subscribe (no React setState). Skia leaves (<TileFalling>, <MultiplierAwareNightSky>, keyboard highlight) read that SharedValue on the UI thread — prefer the SharedValue provider over React setState for tier-driven props. MultiplierBadgeLayer does not consume the provider — the parent pushes tier via badgeRef.update.
    • Note-pitch tolerance. A tap is "right enough" when the pressed note is within MAGIC_NOTE_TOLERANCE_SEMITONES of an unclaimed expected note in the candidate group. The current default is 2 — ±2-semitone near-miss substitution: a tile expecting C4 (60) claims on any pressed key in [58, 62]; exact matches keep their full timing rating while near-miss matches (distance > 0) are CAPPED at Great even with Perfect timing. Set the constant to 0 for strict exact-match scoring. The same tolerance applies during auto-pause wait mode — a frozen head tile resumes when the player taps within ±N semitones of the expected note (still capped at Great for near-misses); keys outside tolerance stay frozen. Auto-pause always keeps head-only lookahead (maxGroupsAhead = 1) regardless of this setting. Tie-break order inside evaluateTap: best judgement rank, then closest note (exact wins over near-miss), then earliest group. The single source of truth is MAGIC_NOTE_TOLERANCE_SEMITONES in src/features/piano/judgement.constants.ts (fed to the engine via the getNoteTolerance callback in useMagicJudgement).
    • Audible-note substitution. When a near-miss claim happens (only possible while MAGIC_NOTE_TOLERANCE_SEMITONES > 0), registerTapRef returns { audibleNote, claimed: true } with the EXPECTED note number (e.g. 60 / C4) so PlayScreen.onNotePressed can route sampler.playNote to that note instead of the pressed key — keeping the song musical even when the player taps one or two semitones off. Unclaimed taps return { audibleNote: pressedKey, claimed: false }; PlayScreen still voices the pressed key but skips beam press visuals. The press → played note pair is remembered in noteSubstitutionsRef only on claimed taps so onNoteReleased stops the SAME note we voiced. At the strict default substitution rarely fires — only near-miss claims within ±N semitones.
    • Early-press audio quantize. When Remote Config audio_quantize_enabled is on, a claimed tap that is early by at most the BPM-scaled quantize window schedules sampler.playNote(..., when) so the voice starts on the matched noteTime instead of at press time. Factory base is 125 ms @ 120 BPM (one sixteenth note); live window is base × (120 / bpm) via computeQuantizeWindowMs — e.g. 375 ms @ 40 BPM, ~166.7 ms @ 90 BPM (15000 / bpm ms when base is factory). TimingPanel edits the base (persisted in audio-quantize-store.ts → getAudioQuantizeBaseMs). On-time / late / too-early-beyond-window / unclaimed taps still play immediately. Gated via selectAudioQuantizeEnabled at call time in play-screen-note-input.ts (no React subscription on the hot path). registerTap returns noteTime + tapTick on claims so the host can compute the delay.
    • Taps further than MAGIC_NOTE_TOLERANCE_SEMITONES from every unclaimed note in the candidate group (or any non-exact tap at the strict default) are ignored — sampler still plays the pressed key for audible feedback, but score/streak don't move.
  • Head-only lookahead (piano-strict sequencing). MAGIC_MAX_GROUPS_AHEAD (in src/features/piano/judgement.constants.ts) caps how many falling-tile groups ahead of the cursor head can claim a tap. Default is 1 — when 3 tap notes are falling the player can ONLY tap the head (next-in-queue) tile; presses matching tile #2 / #3's key in the early window do nothing for scoring (sampler still rings). Tiles behind the head become tappable only after the head resolves (claimed by a correct tap or swept as a Miss). Flip the constant to Number.POSITIVE_INFINITY to enable "guitar mode" — evaluateTap then considers every group inside the early window and the player can effectively "catch up" by tapping an upcoming tile's key before the head resolves. The knob is plumbed through the getMaxGroupsAhead callback on useMagicJudgement (mirrors the getNoteTolerance shape) and fed into useRhythmEngine's MaxGroupsAheadProvider. Auto-pause ALWAYS hard-caps lookahead at 1 regardless of this setting — a frozen head tile cannot be skipped by a future-group key, so guitar mode can never strand the player on a tile waiting to resume.

  • Slide = glissando on every surface. <AtlasPianoKeyboard> treats a finger dragging from key A onto key B as release A + fresh press on B (PlayScreen, tutorial, Learn and free-play alike) — there is no per-screen slide lock. Exception — a scoring finger stays put: when a press claims a tile, PlayScreen (playScreenNotePressed) and the tutorial song phase call the handle's lockSlide(key), which locks every finger on that key until it lifts — drifting onto a neighbour or off the board neither fires a note nor releases the key, so a landscape grip can't play stray notes or break a hold. Unclaimed fingers (nothing due, wrong key) keep sliding, and a slide that lands on a due note claims it and locks from there. Every claim locks, a far-early Early included. Decision lives in resolveTouchMove (PianoKeyboard.utils.ts); the lock lands one JS→UI hop after the press. Every touch-down is a fresh press: a stale record left under a recycled pointer id by a touch that stopped arriving is released first, so it can never swallow the next tap or leave its key muted.

  • Auto-pause wait grace (AUTO_PAUSE_PERFECT_GRACE_MS = 500 ms, AUTO_PAUSE_LATE_GRACE_MS = 1200 ms, fixed — not BPM-scaled). When AUTO_PAUSE_ENABLED, the engine freezes the moment the head tile reaches the hit line and stays frozen until the player taps. Auto-pause is evaluated on every successful tap that advances the head (dense back-to-back groups cannot slip past the line during the inter-anchor gap), on the JS anchor step (every ~20 ms sequencer pulse), and via a UI-thread tickSv fast path when extrapolation leads the engine tick. The frozen tick often sits a few ticks past the note time (anchor-poll overshoot), so classifyHit would normally return late — wall-clock grace overrides that: resume taps within 0.5 s score Perfect+; taps after 0.5 s up to 1.2 s score Late (−5 streak); taps after 1.2 s score Miss (−5 streak) — the Miss still claims the tile (it dissolves like a Late) and resumes the song. Unlike the hit windows, both graces are fixed wall-clock times for every song (no BPM scaling). The Late limit is owned by @rhythm/engine (dispatchTapWithAutoPause); the app and engine Perfect graces are pinned equal by judgement-constants-sync.test.ts. Near-miss great claims are untouched. HUD isPlaying from useMagicGameplay (isPlayingRef + subscribeManualTransport) intentionally does not flip on auto-pause — only manual pause/resume (HUD panel, app-state pause, game over) notifies React leaves — so the header pause icon stays stable while the player waits on the hit line. Raw transport is mirrored into refs on stateChanged (no React setState); the UI thread reads isRunningSv inside useRhythmEngine to freeze tile extrapolation while the engine is paused.

  • Press-path stall mitigation. Piano touches are marshalled UI → JS via scheduleOnRN and invoke playScreenNotePressed / playScreenNoteReleased immediately (no rAF coalesce) so melody playNote fires without an extra frame of latency. The keyboard stamps the live gameplay clock (tickSv / judgementTickSv) on the UI-thread gesture edge and forwards it as atTick into registerTap / registerRelease, so scoring uses press-time ticks instead of a late JS-thread getCurrentTick() sample after the hop. On that path, audio + scoring + judgement popups + consumeTile + decorative tap cues (ripple, particles, shrink, perfect haptic via tap-decorations-defer.ts) stay synchronous; beam press visuals also run in the same JS turn (play-screen-press-visuals.ts — no idle queue, which used to hold the beam up to 300 ms while JS stayed busy); a key lifted right after simply calls beam.release(), and the beam fades out. A re-hit on a key whose <LightBeamLayer> beam is still fading out re-uses that slot and snaps it back to full opacity. <TileFalling> hides consumed tile bodies immediately via atlas visible=false but defers beam mask SkPicture rebuild to idle (scheduleDeferredBeamRepaint) so consumeTile stays off the note-press hot path; on tier cross it retints beams via ColorMatrix + atlas sprites from tierSv and only pushes hit-line glow colors from JS (no beam picture rebuild, avoiding the GC spike from re-recording paints/RRects). Keyboard lane highlights defer through requestIdleCallback (play-screen-keyboard-highlight.ts). <MultiplierBadgeLayer> parks off-canvas until display multiplier ≥ x2, updates label / water fill / scale via SharedValues from useJudgementStore.subscribe (no React setState on hit), takes host visibility through imperative setVisible() on a ref (never a showMultiplierBadge prop), and snaps tier glow colors from JS via resolveBadgeTierColors + useAnimatedReaction. The rhythm anchor loop skips non-critical miss/hold sweeps when a step exceeds ANCHOR_STALL_THRESHOLD_MS (anchor-stall.utils.ts).

    • Pixel windows (vs. ms) are tempo-invariant by design: <TileFalling> keeps fall speed constant in px/sec via computeTicksPerPixel, so the same Perfect+ / Perfect / Great / Too-early px windows feel identical on every catalog song. useMagicJudgement's getWindows callback multiplies all five px knobs (perfectPlus, perfect, perfectLate, great, early) by ticksPerPixel once per call and useRhythmEngine passes the tick-based windows into evaluateTap / sweepMissedGroups — both honor the late-Perfect grace, so a tap right at the deadline never races the sweep into a duplicate Miss popup.
  • Live calibration. useMagicJudgement.getWindows reads the current pixel windows via getJudgementWindowsPx() (in hit-window-state.ts) on every tap and frame-callback miss-sweep — a module-level holder updated by useHitWindowStore on every slider drag. The state file is React-and-MMKV-free so test runtimes (bun:test, which can't load react-native-mmkv) can import it without the persisted store entering the import graph. The store lives in hit-window-store.ts, persists { perfectPlus, perfect, perfectLate, great, early } under MMKV key piano-hit-window-ms, and is eagerly loaded from core/entrySetup.ts so the calibrated values are live before the player ever taps. Older persisted blobs without perfectPlus / perfectLate pick up the factory defaults automatically through zustand's shallow-merge rehydration (no migration step required).

  • useJudgementStore (zustand ephemeral) holds { score, streak, bestStreak, multiplier, counts, gameOver }. PlayScreenBody must not call useJudgementStore(...) — writers use getState().applyHit / applyHitsBatch / applyScoreSnapshot / applyMissesBatch / reset. React hook subscribers are limited to: PlayScreenGameOverBridge (selectGameOver — song-end only), and post-game overlays (SessionResultOverlay / result screens). HUD score + multiplier badge are driven by useGameplayHudBridge (one parent subscribe → scoreRef.setScore / badgeRef.update) — the Skia leaves themselves never subscribe. Night-sky / tiles still mirror theme tier via GameplayThemeTierProvider (subscribe → SharedValue). Judgement feedback is split across surfaces driven imperatively from useMagicJudgement: per-tile <JudgementPopupLayer> (+points), central <CenterJudgementLayer>.fire(judgement, combo), and badge water-fill / label / tier from the parent bridge via computeMultiplierProgress. Chord misses call applyMissesBatch(n) once so the score leaf updates once, not once per chord member. Manual pause/resume is the only other intentional React state flip during a song (subscribeManualTransport → HUD chrome).

  • useMagicGameplay load-path React state is only isReady + error. The parsed Chart and PlayController live in refs (chartRef / controllerRef); the SoundFont sampler is loaded with useSoundFontSampler({ reactive: false }) and awaited via whenReady() so SF2 completion does not re-render PlayScreenBody. The ready commit exposes derived snapshots (controller, sampler, melodyNotes, ticks metadata) for one React pass. Do not put chart/controller/sampler back into useState on the play path. Imperative paths (pause, game-over totalChartGroups) read controllerRef.current.

  • useMagicJudgement builds the RhythmCursor (lazily, inside useRhythmEngine) from controller.engine.notes, anchors a JS-side miss-sweep step driven by controller.tickFrame() on every song-sequencer pulse (sampler.createClockPump() — the audio-thread AudioPositionPump on RNA, the native onClockPulse on the iOS engine; no setInterval), and exposes a stable registerTapRef PlayScreen calls inside onNotePressed. Cursor mutations stay on the JS thread in a ref only (cursorRef — no React setState on arm); the UI thread only reads tickSv + headIdxSv. UI-frame useFrameCallback.setActive follows GameStateMachine.isPlaying() via stateChanged, not a React mirror of “frame active”.

  • Live audio-clock judgement (sample-accurate). Human taps stamp the UI-thread gameplay clock (tickSv, driven from the song sequencer's Transport (AudioTickClock) via the shared clock channel) at the gesture edge and pass that tick into registerTap / registerRelease while the engine is running. Auto-pause wait ignores the gesture stamp and judges against the frozen audio pausedTick — a leading tickSv past resumeLate would otherwise make evaluateTap skip the head group and block resume. Miss-sweep still reads the live audio tick on the JS anchor.

  • Consumed tiles vanish in place. Every Perfect / Great / Too-early resolution calls <TileFalling>'s consumeTile(noteNumber, noteTime, currentTick), which publishes the note as CONSUMED in the lane's note status table; the UI runtime then hides the body and frees its slot for the next in-window note. There is no separate exit overlay — hit feedback is the ripple / particles / smoke / popups. Miss never consumes early so missed tiles keep falling and the player can see what they whiffed.

  • Tap vs hold. isHoldNote(noteLength, ticksPerBeat, ticksPerSecond) in hold.ts is the single classifier for the cursor, the tile layout (isHoldTile) and ChartJson.type_note. A note is a hold only when it is longer than half a beat and lasts at least HOLD_MIN_SECONDS (≈ 0.333 s = a 20 px tail past the 30 px body at 150 px/s), so every hold shows a visible beam. Shorter notes play as taps; their sound is unchanged (the sampler still plays the MIDI length), only the tile and the hold haptic differ. The floor only matters above 90 BPM.

  • Hold heads defer overlay/haptic (HOLD_VISUAL_ARM_MS = 120 ms). A hold head press fires popup / ripple cues immediately and a Perfect head's body is pinned at the press (pinHoldAtPress → tileRef.pinHold() at the press tick): it stops where it stood — above the hit line on an early press — and its tail drains from that moment. The ember field, flare column, and continuous hold haptic arm only after the finger stays down for 120 ms — but the ember field counts its launches from the press (PressPin.pressTick → emberRef.start(…, pressTick)), so at the arm the first 120 ms of embers are already in the air and a short hold does not lose them to the arm delay (lineup pick S1, 2026-10-29) (armHold reuses the press pin; it pins late only if the press pin found no tile). Before 27/10/2026 the pin also waited for the arm: the head kept falling, the hit-line clamp froze the whole tile (tail included) for ~85–160 ms so a close next note ran into the stopped tail, and the hold-end burst always landed on the line. A quick tap-and-release (before arm) unpins at once (finishUnarmedHold → releaseHold) with the Perfect hold-end burst and fires the Perfect tap game haptic (factory: a tone, strength 0.5 / sharpness 0.35, tuned by the PO from the DevTool; the rush limiter's min gap folds the head press and this release into one tick); a sustained hold keeps the pinned-tile + completion-dissolve path; an early release after arm still silently vanishes. Falling bodies visually clamp at the hit line (clampFallingSlotsAtHitLineOnUI in TileFalling.hold.ts) so a head waiting for its press / miss / consume never scrolls past the receptor — judgement windows still use live tick math. Only the body parks: a hold's beam top keeps its chart position, so a head that reached the line before a late press still drains its tail on time (the beam quad drops once it reaches the body), and the press pin takes it over with no jump. Before 27/10/2026 the beam shifted with the body, freezing the tail while the next notes fell into it. Hold pin (beam + body) lives on <TileFallingLayer> via tileRef.pinHold() — the falling pool switches the body slot to held mode and counter-scrolls chart geometry so the body bottom stays at the (hit-line-capped) press screen Y while the beam CLIP drains with tickSv. After arm, useMagicJudgement also calls emberRef.start() on the sibling HoldEmberLayer mounted between beam and body (betweenBeamAndBody). Keyboard release calls tileRef.releaseHold() + emberRef.release() in parallel with registerReleaseRef (scoring only); the UI thread hides held slots when tickSv reaches the hold's effective tail even if the finger is still down. A hold finishes when its tail meets the note core, not at the chart tail: the beam is drawn behind the core, so its last bodyHeight px of fall are invisible. The engine therefore completes a hold (sweepHoldCompletions / evaluateHoldRelease / auto-pause) at noteTime + noteLength - holdTailInset - 10 % × (noteLength - holdTailInset) — the last HOLD_COMPLETE_TAIL_FRACTION (10 %) of the visible tail is forgiven so a one-finger player can lift before the next note reaches the line (effectiveHoldEnd in hold.ts), where holdTailInset = bodyHeightPx × ticksPerPixel is supplied by useMagicJudgement through JudgementWindowsTicks.holdTailInset; the UI uses the same tick via effectiveHoldTailTick in HeldTile.utils.ts (a test asserts parity). A hold no longer than the core gives up only 10 % of its own length. onHoldComplete calls Haptics.stopHold() only for a hold that armed (startHold is ref-counted). Gameplay haptics (tap, holdComplete, miss, the hold rumble via Haptics.startGameHold()) are configured by gameplay-config.ts and tuned live from the DevTool's Haptics tab (tone strength or preset pattern per event; a density-aware rush limiter thins taps on fast charts) — see devtool.md. Miss has no haptic unless the DevTool turns it on. Engine callbacks (onHoldComplete / onHoldBreak / onHoldAutoBreak) award the hold bonus, unpin (releaseHold, also for an unarmed press-pinned hold) or detach a pinless head (consumeTile), and — for Perfect heads on complete or early release — fire the ripple / particle burst on the pinned body (fireHoldEndBurst's pin; the hit line only when no pin is known). useRhythmEngine mirrors only headIdxSv (judgement cursor); hold tail timing stays on TileFalling held slots + HoldEmber per-slot fields. Auto-pause freezes on the JS anchor loop — no head noteTime SharedValue in the engine hook.

  • Progressive hold rumble. On arm, startHoldHaptic passes the tail's real-ms length (press pin tick → effectiveHoldTailTick, at ticksPerSecond × m) and the time already held to Haptics.startGameHold(noteNumber, holdDurationMs, elapsedMs) (holdHapticTiming): the rumble starts at hold.startGain × hold.amplitude and ramps linearly to hold.amplitude over the first hold.rampFraction of the tail, then holds at the max. Every armed-hold end calls Haptics.stopGameHold(noteNumber); a resume after pause restarts it from the song-time elapsed, so the ramp continues instead of starting light again. Tunable in the DevTool Haptics tab.

  • learn mode is unchanged (un-judged, no popups, no scoring, no dissolves). The same <PlayScreen> handles both modes — gating is playMode === "play" around the judgement hook + HUD overlays + dissolve overlay.

Pre-roll countdown + session lifecycle

PlayScreen is session-scoped: every visit to the screen is a fresh play attempt, so the judgement store is reset on mount, on unmount, AND inside the back / retry handlers — a stale "game over" overlay from the previous attempt MUST NOT flash on screen when the player re-enters, and the dismissal animation MUST NOT slide out with the summary still visible.

Segmented songs (free tier). Part boundaries come from the cached catalog — sheet Section 1/2/3 URLs (one .mid per part) or legacy time-based segments in songs.json — not from the MIDI marker track at runtime (buildSongSegmentPlan ignores marker notes; see parse-song-segment-plan.ts). A song is segmented only when the catalog declares ≥ 2 parts (catalog-segmentation.ts). On game over, PlayScreen checks whether the full song was already unlocked before this run (read from progress before markPartCompleted). If yes — or the run was full-song mode — PlayResultScreen shows SessionResultOverlay (stars + recommended next songs). Otherwise it shows SectionCompleteOverlay (parts progress bar): middle parts include Next section; clearing the final part (which silently sets fullSongUnlocked) shows Replay and Back to list only. All result UIs render embedded on /(app)/play-result (no Modal). Re-entering play without ?segment= resumes on nextPlayablePart until every part is cleared, then auto-starts the full song. Explicit ?segment=N or Replay still replays a single part. If the sheet drops Section columns, pull-to-refresh so MMKV picks up the new catalog; unlock progress for that song is reset automatically when segmentation is removed.

Logic stars (session result only). The three-star badge on SessionResultOverlay uses Perfect Rate = (perfect + perfectPlus) / totalChartGroups, where totalChartGroups is the falling-tile group count in the played chart (controller.engine.notes.length at game over — clipped when a segment playRangeSec is active). Perfect+ is the same tier as Perfect for stars (HUD label only); Great / Late / Too Early / Miss do not count toward the numerator. Thresholds (inclusive): ≥ 90% → 3★, ≥ 70% → 2.5★, ≥ 50% → 2★, ≥ 30% → 1.5★, ≥ 15% → 1★, else 0★. Pure math lives in ResultStarBadge.utils.ts (totalPerfectTierHits, computeLogicStarsFromCounts). Section-complete overlays never show logic stars. The tutorial Congrats result uses the song thumbnail (SongRevealCover) instead of a star badge; computeAccuracyStarsFromCounts remains available for other accuracy-based surfaces.

To make space for the reset and to give the player a beat to scan the lane before tiles start falling, useMagicGameplay accepts startPaused: true — it builds the PlayController + audio chain but leaves the tick clock and rhythm-track scheduler inert until the caller invokes the returned start() action. The 3 → 2 → 1 → "go" → null state machine (nextCountdownFrame in countdown.constants.ts) lives inside <CountdownOverlay>: PlayScreen only hands it a readySv SharedValue (true once isReady) and receives a single onComplete callback at the end. Keeping the per-frame work inside the overlay — in SharedValues, not setState — keeps the heavy gameplay tree (<TileFalling>, <AtlasPianoKeyboard>, <JudgementPopup>, <TileDissolveEffect>) untouched while "3 / 2 / 1 / GO!" plays — the parent body re-renders exactly once for the entire pre-roll instead of once per frame, and the overlay's own tree renders zero times after mount (every flag it reads is a SharedValue). On the final "go" → null transition the overlay invokes onComplete, which calls start() so the engine begins ticking exactly as the overlay clears. <PlayScreenHudOverlayGroup> mounts with the gameplay tree (canMountGameplay) — not after preRollComplete — but the header chrome (play/pause, timing toggle, score) and <PlayScreenSongProgressRail> stay hidden until preRollComplete flips true on onComplete. The overlay's scrim is pointerEvents="auto" so taps during the pre-roll don't fire judgements / wake the sampler.

<CountdownOverlay> owns the loading card framing — while the pre-roll has not started it renders the bundled prepare-art background with "Unlock all songs" + gradient "VIP BENEFITS" headline (Figma 7411:79764). The song progress rail at the top of the lane (PlayScreenSongProgressRail in PlayScreen/SongProgressRail.tsx, wrapping GameplayHeaderBackground) mounts with the gameplay tree but stays hidden through load + countdown; it appears when the pre-roll completes alongside the rest of the HUD chrome. The pre-roll state machine (loading → countdown → hidden, or dismissing for skipCountdown) lives in useCountdownPreRoll and runs entirely on the UI thread — no useState, no effects, no timers. Its inputs are SharedValues: readySv (useBooleanSharedValue(prepareReady) in the owner), armedSv (the tutorial's countdownArmed) and the route's entered flag (PlayScreenEnteredContext now carries a SharedValue<boolean> made once in PlayScreen/index.tsx), so a flag flip re-renders neither PrepareAssetGroup nor CountdownOverlay. One useAnimatedReaction turns them into a preRollTarget (pure worklet in CountdownOverlay.utils.ts: wait / ready / run / dismiss) and acts once per change: cross-fade the prepare card out and the Get ready! card in (withTiming, PREPARE_OVERLAY_FADE_MS), start the clock, or — skipCountdown — fade the prepare card out and finish from the fade's own completion callback. The 3-2-1 is one linear clock SharedValue (clockSv, GAME_COUNTDOWN_RUN_MS); frameSv = preRollStepAt(clockSv) (countdown.constants.ts) is the glyph column's row, and a second reaction on it beeps (a module-stable scheduleOnRN(playCountdownBeep)), flips the hidden phase code at GO and calls finish at PRE_ROLL_STEP_DONE. The overlay root's pointerEvents / accessibility props follow phaseSv through useAnimatedProps (countdownOverlayRootProps, a worklet); only the loading phase takes touches. CountdownOverlay renders a memoised CountdownOverlayView whose props never change, so no React tree renders while the pre-roll plays. The prepare card is never unmounted either — PianoKeysLoader gets an activeSv and stops its loop on the UI thread once the card has faded out. onComplete reaches JS through a stable callback id (useStableJsCallbackId + invokeStableJsCallback), so a new callback identity can never restart the countdown. The Get ready! card appears as soon as the song is ready (armed or not) and the digits start once armed. The route's screenEntered reaches the overlay through that context, never as a PlayScreenBody prop: the flip rides the stack's transitionEnd navigation commit and, as a prop, re-rendered the whole body, so "3" never runs under the route fade; the tutorial song arms it when its reveal hands over. With that gate there is no hold left (COUNTDOWN_PREPARE_TO_START_DELAY_MS = 0; the clock starts at -delay); each digit holds GAME_COUNTDOWN_TICK_MS (550 ms) and "GO!" GAME_COUNTDOWN_GO_HOLD_MS (350 ms) — GAME_COUNTDOWN_TOTAL_MS = 2 s, down from 5 s (preRollStepAt walks the same frames as nextCountdownFrame, GO holding shorter than a digit). The 1.2 s beep overlaps three deep at that cadence; countDown321 keeps 4 voices. Learn Mode's stage pre-roll uses the same 2 s cadence (PRE_ROLL_CADENCE in learn-countdown.model.ts) and also waits for its keyboard bake (countdownShows → keyboardReady); its challenge count-in keeps the music's 1 s beat (COUNT_IN_CADENCE). The loading→"3" transition is a card swap (prepare card fades out while the countdown scrim fades in) so the first digit pulses in as deliberate punctuation. Pass skipCountdown (via <PlayScreenPrepareAssetGroup skipCountdown>) to dismiss prepare as soon as the song is ready and fire onComplete with no digit sequence — used by tutorial practice training (TutorialPracticeSurface). The overlay is suppressed on the terminal error path (error !== null) so the error card has the surface to itself. Nothing unmounts or re-renders the gameplay tree at the end of the pre-roll: judgement and the rhythm engine are enabled with the prepared screen (enabled: prepareReady, before "3"), so GO has no state to flip; onCountdownComplete reveals the HUD imperatively and calls start() directly (AUTO play, a QA switch, is the one exception: it mounts its driver first, then starts from an effect). The overlay itself is never unmounted — finish() (a worklet) sets its root opacity to 0 and slides it off screen (COUNTDOWN_OVERLAY_OFFSCREEN_X), both UI-thread style writes; the accessibility flip (hidden phase code) is written at GO, a beat before the song starts, never at its first frame — and GameplayHeaderBar seeds its play/pause mirror as "playing" while countdownActiveRef is up, so start()'s transport emit is a same-value setState (no render).

The Skia rendering composition (AtlasPianoKeyboard + TileFalling + HitEffect + lane-geometry) is documented in .cursor/skills/piano-simulation-screen/SKILL.md.

<TileFalling> UI-owned slot pool + note status table. Chart notes are converted once at song/layout load into a sorted flat SharedTileLayout[] via buildTileSharedLayout (precomputed lane geometry + appearAtTick / resolveByTick windows). JS keeps that layout (binary search, and the geometry consumeTile returns synchronously for FX) and copies it once to the UI runtime as the immutable column set TileChartSoA. The UI runtime owns the whole slot lifecycle in tile-pool.worklet.ts: the beam system's beforeUpdate runs reconcileTiles every frame — advanceTileCursorWorklet slides the startIndex..endIndex window over the chart columns (same pattern as leap-sim-guitar's SharedNotesCursor, in tick space), culled slots retire, new in-window notes bind to free slots (free stacks + chart ↔ slot maps are plain typed arrays, no JS mirror), and nothing hops back to JS — a stalled JS thread cannot make a tile appear late. Judgement only says what happened to a note. It publishes a status per chart index into tile-note-status.ts — FALLING / CONSUMED / HOLDING / ENDING_FADE / ENDED, plus the press tick + tempo of a hold per note number. The entries travel through a status ring of lock-free Worklets Synchronizable number cells (tile-note-status-cells.ts: head, tail and 64 slots, in-process fallback on web / tests): each change is ONE number (((chartId·2²⁰ + chartIndex)·8 + status)·2, or a press payload (tick·100, m·1000, note) sent just before its HOLDING), written into the slot BEFORE head moves, so an entry is never torn and nothing is cloned or serialized per change. JS is the single producer and never drops: a full ring keeps the rest queued and retries about a frame later (the UI publishes tail after draining). The UI runtime drains the ring every frame in reconcileTiles and keeps the per-note table itself (noteStatus, pressTick / pressM); entries of an older chart are skipped, an entry of a newer chart (and the press before it) waits for the pool rebuilt for it. Each entry moves its slot to the note's status: CONSUMED frees the slot, HOLDING pins the body where it was pressed (pose derived from the press payload — pinSlot fixes the press Y, the body system derives the rest each frame), ENDING_FADE starts the release fade, ENDED hides at once — and the UI frees the slot / beam itself, including when the fade ends. After a drain that changed anything every bound slot is re-anchored once. Judgement itself stays on JS: it also drives audio, score, haptics and stores, so running it off-thread would not remove the hop. The lane also reads the engine's flat game-state block (GAME_STATE: tick, rate, epoch, stamp, isRunning) from a Worklets Shareable hosted on the UI runtime. The TileFallingHandle API (consumeTile / pinHold / releaseHold) is unchanged; it now only writes statuses. Body/beam sprite regions are a lifetime-fixed object pool (sized once at mount from chart peak, or from poolCapacity / beamTileCapacity props — practice uses SINGLE_NOTE_TILE_POOL_CAPACITY); slots stay idle or active and never resize when the note list toggles. Per-frame motion is the sprite systems' update (chart + status + tick, see Frame order), so active falling bodies never draw below the receptor and held bodies stay screen-anchored without any stored geometry. Judgement stays on @rhythm/engine's separate headIdxSv / RhythmCursor. See TileFalling.tsx, TileFalling.step.ts, tile-pool.worklet.ts, TileFalling.utils.ts.

Frame order (sprite systems). The lane is two ordinary sprite layers — hold beams, then (after the hold embers) tile bodies — each a useSpriteSystem in TileFalling.tsx; it has no surface, no mapper and no scroll uniform. The beam system's beforeUpdate runs reconcileTiles once per frame (registration order puts it before the body system). Each bound slot carries its own motion (tile-pool.worklet.ts): headY (body bottom), headEndY (the hit line, or the press Y of a pinned hold), headV, tailY (beam top, keeps falling after the head parks / pins and drains a hold's beam) and tailV, in screen px and px/s; size and x stay in the immutable chart columns. A frame does y += v · dt (dt = the FX clock's delta, clamped to 250 ms) and clamps the head at its end — no pose is recomputed from the tick, so the audio anchor, its slew and the engine's frame order never move a tile. reconcileTiles then slides the cursor (the only per-frame use of the tick), retires culled and fully-faded slots, drains the status ring (each judgement change is one lock-free ring entry; the pool keeps its own per-note table, see tile-note-status.ts) and binds the notes that entered the window. A bound slot is queued (bodyWake / beamWake) only once it can be seen — its head within TILE_WAKE_MARGIN_PX of the lane's top edge, or a pinned / fading hold; until then the pool keeps integrating its motion but the systems neither write nor upload it (wakeVisibleSlots). Each system wakes its own in beforeUpdate; a retired slot needs no counterpart — its update finds it unbound and the system hides and sleeps it. Each awake slot's update(slot, now, w) (TileFalling.step.ts) only draws what the pool moved: the body at headY − bodyHeight; a HOLDING / ENDING_FADE tile adds the halo + pulsing core (the pulse / buzz still reads tick − noteTime, cosmetic) and its beam runs from tailY to headY until the tail has drained into the body; the release fade is holdReleaseFadeAlpha(now, fadeStart). A hold parked at the hit line (adaptive-tempo wait) has lane rate = 0, so nothing moves, yet the pool still reconciles every frame, so a tap frees its tile. The sprite systems run on the shared FX frame, which the provider skips while the pause panel freezes the lane. What the engine tells the tiles (one flat Float64Array game-state block, driver/game-state.ts, hosted on the UI runtime as a worklets Shareable and returned by useRhythmEngine().gameState / useMagicJudgement().gameState and provided to the lane layers by the screen through GameStateContext (useGameStateCell()); the frame callback is its single writer, positional writeGameState, no per-frame object; labs have none and follow tickSv): isRunning, tick, rate (ticks/ms the lane advanced over the last frame, slew and tempo curve included, 0 while paused / held / stalled), epoch (bumped whenever the tick was ASSIGNED rather than integrated: seed on start / resume / seek, catch-up snap, a write from outside the frame such as the rewind slide or a song swap, and the edge where the lane stops) and stamp (the frame that wrote the block). Tile speed is rate · 1000 / (ticksPerPixel · m) px/s; a rate read one frame late is off by the change of the rate over one frame, not by a frame of position. Re-anchoring (closed form (chartY + tick / tpp) / m + hitLineY): when a note is bound, when a status entry is drained (any tap wipes the error free-running tiles collected), and when epoch moves. Tempo change: (y − hitLineY) · m is invariant, so every unpinned head and every tail is rescaled by m_old / m_new and the speeds re-derived — no tick read; a pinned head is a screen position and stays. Tick freshness. The FX frame callback runs before the engine's tick writer (re-activated on every resume), so the raw tickSv is one frame old; the pool adds rate · dt to it once, when stamp differs from the FX frame's timestamp (useGameplayFxFrameStamp), and only for anchoring and the cursor. A lane that stands still (rate = 0) while its tick moves — labs with no publisher, the paused rewind slide — is followed: the pool re-anchors every tile to the new tick. The engine frame callback is switched off while the song is paused, so it can never report the stop itself: the pause freeze (freezeLaneDisplayTick → freezeGameState) writes isRunning = 0, rate = 0 and bumps epoch.

Lane render-target bounds. Play and tutorial song gameplay pass the actual keyboard top into PlayGameCanvas. Both lane targets end 12 logical px below that edge (computePlayScreenLaneSurfaceHeight), trimming the area hidden behind the keyboard. The hit line keeps its original lane coordinates. The keyboard portal uses its own strip-sized target. The outer Skia canvas retains the wave bleed and keyboard area.

PlayGameCanvas overlay atlas groups. Imperative FX layers inside the unified lane canvas are served by GameplayAtlasSheetProvider, which resolves the layouts of two sheets: the tile master sheet (getGameplayMasterAtlas — tile bodies + the hold-beam column; per song only "beams or not" varies. Each body cell is packed at its content extent, not the full glow-pad cell: the halo / full sprites at TILE_BODY_HALO_SCALE × the body, the core-only sprite at the body circle (tileBodyCellPx), centred in the cell, and computeTileBodyAtlasTransform takes the packed width (spriteW) to shift the quad by the trimmed margin so the body centre does not move. The sprite engine packs every texture through packSpriteTexture (src/core/sprite-engine/atlas-layout.ts), preferring a compact shape within a shared 10% area budget; a texture may set optimize: false to retain minimum-area layout) and one song-independent, mipmapped FX sheet (getGameplayFxAtlas — FX discs, smoke cells and hold-ember ovals in ONE image; backdrop clouds, smoke and embers are packed at their cropped size, and neighbours sit the engine's SPRITE_ATLAS_GAP_PX × the sheet's bake ratio apart — no per-sheet gutter; layers read each frame's cell / bakeScale from useSpriteSource). Both — and the light-beam columns — are keyed bake sources (SpriteAtlasBakeSource): the WebGPU planes bake them on upload and free the raster, so no CPU copy sits next to the GPU texture (kept warm on the GPU for Replay / Next; see the engine README). Soft-disc FX (gameplay-fx-atlas.ts — tier glow baked at 1× (a smooth gradient upscales losslessly), the smoke blob cells are FX-sheet cells (smoke-atlas.ts buildSmokeAtlasSpecs — a 96 × 48 cell on phone, 144 × 72 on iPad — each baked for that device's largest puff so it always minifies, never upscales; the halo/core rects are centre-cropped to the blob's bounding box (smokeSpriteCropPx, ~19 % less fill, same pixels); aspect 0.44): a wide white HALO cell plus a small solid white CORE cell, no per-tier variants. SmokeParticleLayer draws two <Atlas> nodes over the SAME transforms — the halo tinted per particle at fire time from fxTierTintTable (the x2…x6 bgAccentRgb; the middle centre-flash puffs stay white), the core with white colors (alpha mirrored)), the StarRise orb (star-rise-orb-atlas.ts — the starRiseOrb FX cell, a solid white disc used as each orb's core; the halo reuses the tapTierGlow soft disc), tile bodies (full / halo / core × 2 lanes — full keeps a falling tile at one quad), and ONE white hold-beam column tinted per lane through the beam color buffer (BEAM_LANE_RGB; a short cap + flat-shaft bake — a longer beam draws the cap 1:1 and stretches the flat shaft on the GPU, writeInstanceStretch, so the texture no longer grows with the song's longest hold) — the last two (tile bodies, beam) are the master sheet. No Figma glyph is baked — no gameplay layer samples one (the note / sparkle / star shapes stay path-only in sparticle-paths.ts for Learn). The hold-ember ovals are FX-sheet cells too: held-ember-atlas.ts contributes TWO white soft ovals — a wide halo and a small solid core of the same size (buildHeldEmberAtlasSpecs, each clipped to its cell). HoldEmberLayer draws two <Atlas> nodes over the SAME transforms: the halo tinted live through its color buffer (colorBlendMode="modulate"; useGameplayFxTierTintRgb cross-fades the x1…x6 tint, fxTierEmberTintTable, pure accent) and the core with white colors (only its alpha mirrors the halo's, so it never changes hue) and the halo is drawn with the live tint on every write (emberTintChanged only forces a rewrite while the tint moves), so a theme transition recolours embers already in the air (no per-tier variant, no per-seed sprite swap). Since 2026-11-03 the layer is data-driven like the tile lane: settleEmberSlots decides which slots are drawn, then each awake slot's update runs writeEmberSlotSprites, which evaluates every ember once and putSprites its halo + core straight into the plane — no Skia quad store, no host objects (each one is a JSI hop per property read on the UI runtime; the old copy cost ~3 ms/frame per hold on a device trace). Layers read slices through useGameplayFxAtlas / useGameplayHeldEmberAtlas / useGameplaySmokeAtlas / useGameplayTileAtlas. A new sprite needs no warmup of its own beyond its sheet: it is a source rect in an already-baked texture, and the GPU program depends on the layer's <Atlas> paint (modulate + FX_ATLAS_SAMPLING), which GameplayGlowLayer's mount warmup draws under the prepare scrim — that first draw also uploads the sheet with its mips. It does not cover a plus blend (blend state is part of the Metal pipeline) or another texture, so three layers prewarm themselves for 30 UI frames under the prepare scrim — otherwise each compiled or uploaded on the first note: HoldEmberLayer shows one 2/255 quad (HOLD_EMBER_PREWARM_*, the only plus Atlas — the first Perfect tap fires its puff), LightBeamLayer draws a prewarm plus gradient Rect at 1/255 then opaque 1 px wide (LIGHT_BEAM_PREWARM_* — Skia picks a second program at opacity 1), and CenterJudgementLayer / JudgementPopupLayer draw one 2/255 glyph quad so their own atlas textures upload (judgement-atlas-prewarm.ts). Game Mode's song_start analytics also waits for the idle queue (scheduleSongStartOnce in play-screen-note-input.ts; the playtime clock is still stamped at the press). Tile hit burst — SparticleLayer replaces the old hit ring: on a judged hit the falling tile frees its slot immediately and the layer draws the tile's own baked outer halo (scales 1 → 1.25, holds opacity for 30 % then fades) and core (scales 1 → 0.3 while fading) from the master atlas tile-body slices, over HIT_BURST_LIFE_MS = 280 / 1.35 ≈ 207 ms (faster than the hold ember) — 2 quads × 5 burst slots in one <Atlas>, fired via spawnRef.current.fire(...). It samples the raw FX clock every UI frame while live (no cadence throttle); once the last burst ends it flushes once and goes idle, so the three buffer mappers stop re-running between hits. Perfect-head holds fire their one burst at the hold end, centered on the held body at the hit line; that release skips the hold fade (releaseHold without fadeOut also cuts a fade the finger-lift already started) so the burst takes over on the same frame. Auto-pause completes (not breaks) an active hold whose tail is within the perfectLate grace, so a next note starting at the tail no longer swallows the burst + holdComplete haptic. SmokeParticleLayer uses an effect-slot pool (fixed concurrent bursts × capped sprites; analytic FX-clock life — a burst fired after the quantized render clock has negative progress for a frame and is kept, not freed — see .cursor/skills/effect-slot-atlas-pool/SKILL.md). Every tier shares SMOKE_SHARED_TIER_CONFIG in SmokeParticles.utils.ts (puff count, radius, reach and life live there; edge puffs run on 90 % of the life); the middle two puffs draw the all-white x1 cell for ~110 ms as the one white flash at the hit point. SmokeWaveLayer (x3+) is a 6 px wave (130 px humps, 25 px gaps, speed 0.6 ≈ 103 px/s outward; iPad scales the geometry ×1.25 via SMOKE_WAVE_DEFAULT_TABLET — it's a shader, so nothing is baked) whose humps each take a stable random 60–100 % height, tinted with the tier color mixed 45 % toward white at alpha 0.65. It ramps per tier (SMOKE_WAVE_TIER_SCALE): x3 as authored, x4 ×1.15 hump height / ×1.15 speed, x5 ×1.25 / ×1.3 (6 → 6.9 → 7.5 px on phone). Height only (the wavelength stays fixed) and eased with the tier tint; the phase is accumulated (advanceSmokeWavePhase) so a speed change never makes the humps jump. The band rect is sized for the x5 height, so tiers only change shader uniforms — never the GPU program. Its mount warmup draws the real band at 1/255 for 30 FX frames (SMOKE_WAVE_PREWARM_HOLD_FRAMES). Hold pin (beam + body counter-scroll) is owned by TileFallingLayer via pinHold / releaseHold; HoldEmberLayer is a GameCanvas sibling injected through betweenBeamAndBody (tick-analytic field of soft upright ovals (HELD_EMBER_OVAL_ASPECT 0.84) — 6 / 7 px embers drawn as a 4.6× quad whose baked solid core is only HELD_EMBER_CORE_SHRINK (42 %) of that diameter, so most of the sprite is wide soft halo; the white core's cell is baked cropped to its own extent (HELD_EMBER_CORE_EXTENT of the radius, in held-ember-crop.ts) — a small dot, not the halo's footprint — and writeHaloCoreInstances is given the half-size gap (coreDx / coreDy) to centre it on the halo, they rise from the hit line on an ease-out curve (riseCurvePow 2.5) up to 150 px, fading to 0 at their peak and never falling back, and shrink while fading (fadeOutScale 0.2 on the same p^fadeOutPow curve). The phone hold field is a funnel (lineup pick "D · Phễu loe", 2026-10-29): a negative pyramidPinch (−1.4, raised from −0.8) inverts the pyramid, so the field starts as narrow as its 16 px vent at the hit line and flares to 2.4× its offsets at the full rise (taper = 1 − pinch · climb / risePx, unclamped above 1), with a small 6 px drift, apexes from 0.3 of the rise skewed low (riseSkew 2) and no lean. Two more shape knobs stay available in the lab: leanStart / leanDeg (past that share of its apex an ember tilts outward on its own side up to that angle, tied to the climb so it never turns flat or goes down) and riseSkew (apex = risePx · (min + (1 − min) · spawnPhase^riseSkew)). The iPad hold uses the same funnel shape with its own sizes; tap puffs keep lean off and riseSkew 1. With a positive pinch the field is a pyramid: every ember launches straight up and its sideways offset from the vent axis (launch spot + drift) is scaled by max(0, 1 − pyramidPinch · climb / risePx), so the field is the full vent + drift wide low down (columnWidthPx = the base, capped at 1.5× the note) and narrows toward the top. There are no tilted side embers any more — the pyramid replaces them. A hold field streams embers at a constant rate while it is held and stops launching at its tail / release: every ember relaunches on ONE shared cadence (resolveEmberCadencePx = the longest jittered flight, periodPx × 1.06) and the first wave is spread over that same cadence, so launches sit on an even grid — N / cadence embers per px. The density is set directly as holdRatePerSec — embers launched per second held at 1× speed (phone 300 / s, iPad 160 / s; quoted at EMBER_RATE_FALL_PX_PER_SECOND 150 = the lane's default fall speed, so it scales with tempo like every ember timing) — and the field seeds round(rate × cadence / 150) embers (resolveHoldEmberCount, clamped to the slot buffer: a clamped field launches fewer per second than asked), so changing the rate never changes the flight, a hold of any length launches embers in proportion to how long it is held, and there is no thin patch when the first wave hands over to the relaunches (before 2026-10-29 each ember relaunched on its own jittered flight time, so after the first wave launches bunched into 5–18 per 10 px). Only the flight length is still jittered (≤ the cadence), so heights and fades vary without bunching the launches — the embers already in the air finish their rise. A hold that ends very soon after its press is simply cut off (no minimum wave). Holds and tap puffs have separate tunings — DEFAULT_HOLD_EMBER_TUNING (phone, lab pick 2026-10-29 in the lineup's funnel shape: 300 embers / s = 244 embers filling the 244-ember slot buffer, alphaGain 1.4, 6 / 7 px, 115 px flight, rise 180, min apex 0.3 with riseSkew 2, curve 3.5, riseCarry 0.15, drift 6 steady, vent 16, pinch −1.4 (funnel), lean off, birth 1, fade out 0.6, shrink 0.35; the iPad hold has its own funnel, a suggested start for the DEV to tune (2026-10-29): 160 embers / s = 158 embers (cut from 240 / 237 on 2026-11-10: the iPad GPU was fragment-bound), gain 1.5, 12 / 14 px, 140 px flight, rise 300, min apex 0.3 with riseSkew 2.5 (lab-tuned on iPad), carry 0.15, drift 8 steady, vent 28, pinch −1.4, no lean, fade out 0.6, shrink 0.35). iPad has its OWN config (DEFAULT_HOLD_EMBER_TUNING_TABLET / DEFAULT_TAP_EMBER_TUNING_TABLET; picked in the lab on device: embers 12 / 14 px, rise 330, vent 44, hold drift 48 / 140 embers / flight 115, tap drift 105 / 88 embers / flight 140) tuned from Lab → Hold ember with the Device row; the ember cell HELD_EMBER_SPRITE_CELL is baked at 74 for the largest iPad size chip (14·16) and at 37 on phone for the 8 px tap ember and scaled down everywhere, so no ember ever upscales and DEFAULT_TAP_EMBER_TUNING (lab picks 2026-10-29 — phone: 64-ember one-shot puff at alphaGain 104 / 64 (the gain clips the bright first half of each flight; the previewed look), rank base 104, 7 / 8 px embers, 90 px flight, rise 180, min apex 0.2, curve 3, riseCarry 0.35 so a third of the rise / drift runs at constant speed and the embers are still floating up and out as they fade (fadeOutPow 0.6, all embers since 2026-10-29) and shrink to 0.35 (the hold field keeps carry 0: it eases to a stop at its apex), drift 24 with ease-out driftCurvePow 2, vent 28, pinch 0.85, birth 0.5, launch window TAP_EMBER_BURST_PX 80; iPad has its OWN values, not scaled from phone: rise 330, min 0.2, flight 140, 10 / 12 px, drift 36, vent 52, the rest as phone); both fade out with pow 0.6 and shrink to 0.2; 8 slots × 244 quads — not an effect-slot burst. Fill / CPU trims that keep the look: the counts were trimmed from the tuned 140 / 104 and each ember's alpha raised by the same ratio (HOLD_EMBER_ALPHA_GAIN, TAP_EMBER_ALPHA_GAIN, capped at 1), so the additive field carries the same total light; the drawn sprite rect is centre-cropped to the baked oval (held-ember-crop.ts, ~14 % less fill per quad, no pixel change); evaluateEmber writes into one reused sample per frame (no per-ember allocation); and the live view publishes only each slot's seeded embers; a sustained hold ignores sub-30 px display-tick plateaus so its pause credit never piles up into a pulsing field). Perfect+ / Perfect tap-note hits fire emberRef.burst(geom, currentTick, themeTier) (shouldFireTapEmberBurst — Great / Too Early / Late hits dissolve the tile with no embers) — a one-shot TAP_EMBER_COUNT puff on a draining slot that never evicts a live hold. JS emberRef.start(note, geom, currentTick, themeTier) never reads SharedValues (runOnUISync); callers pass the JS audio/display tick and the layer write-publishes scalar pending ops for the shared FX frame to seed. Keyboard stays on its own bake (separate window / GPU cap). Judgement center + points remain theme-keyed glyph groups; the center N streak suffix is baked once in the PERFECT red/yellow style (SUFFIX_TIER_COUNT = 1) and does not follow the streak/multiplier color. Lane accents are fixed: white keys yellow, black keys cyan (tile-colors.ts). Each layer still owns its fixed slot pool and buffer modifiers — only the source SkImage is shared. See .cursor/skills/skia-atlas-object-pool/SKILL.md.

Note visual lab. Lab → Note visual (NoteVisualEffectLab) previews the real TileFallingLayer over a white/black-key chart with toggles for hold notes and scrolling.

Device sizing. On iPad the hit smoke is ×1.5 (SMOKE_DEVICE_SCALE: size + spread), the rising orbs ×1.5 (STAR_RISE_DEVICE_SCALE: halo + core), the hit-line wave ×1.25, and embers use their own iPad config; backdrop glow and tap bloom stay the phone size. Falling notes are 42 pt on every iPad (TILE_BODY_WIDTH_TABLET = phone 30 × 1.4), and the tile body atlas bakes at the largest width (42) so no device upscales it. Rise HEIGHTS (orbs, embers) use a taller factor, TABLET_RISE_HEIGHT_SCALE 2.2× in gameplay-rise-scale.ts: gameplay is landscape and the 4:3 iPad has ~2.2× more room above the hit line, while its width grows only ~1.4×. Atlas sprites are baked at the LARGEST size the running device class draws them and scaled down (smoke cell 96×48 phone / 144×72 iPad, ember cell 37 / 74) — never baked at phone size and upscaled on iPad, which reads as noise. Smoke puffs and rising orbs also skip any quad whose alpha is under half an 8-bit step (SMOKE_INVISIBLE_ALPHA, STAR_RISE_INVISIBLE_ALPHA): the color buffer rounds it to 0, so it would draw nothing but still cost fill. The HUD (badge, score, judgement label) and layout (hit-line offset) also scale on iPad. tablet-fx-sizing.test.ts pins these rules.

Update rates. One FX frame driver runs every display frame; each layer throttles itself with shouldRunGameplayFxUpdate (jitter-tolerant). Ambient layers step at the 40FPS default (glow, SmokeWave phase) or GameCanvas.tsx's per-layer cadence (tap bloom 40, StarRise 60, smoke puff / judgement 60); the badge pop uses its "30FPS" cadence. Everything else runs every display frame: badge water fill + crest and tint, score count-up, Sparticle, light-beam fade, SmokeWave fades, the header progress bar, and the scroll-bound loops (tiles, hold embers). The keyboard press travel in AtlasPianoKeyboard steps at the 60FPS cadence (every 2nd frame on 120 Hz): frame time accumulates between steps so the travel keeps its real duration, and a press's first step is still taken on the touch itself. While the pause panel is open, PlayScreenBody sets fxFrozenSv: the FX driver and the tile loop return at once, so the canvas stops redrawing. ProMotion iPhones and iPad Pro run up to 120 Hz (CADisableMinimumFrameDurationOnPhone: true). A 60 Hz iPhone lock and 30/s cuts tried on 2026-10-23 were reverted on 2026-10-26 (choppy on device). Details: docs/investigations/game-mode-thermal-2026-10.md.

Streak tier effects. What each badge band (x1–x5) turns on — badge, glow opacity, hue cross-fades, SmokeWave, tap bloom, StarRise, smoke size — lives in streak-tier-effects.ts (derived from the gameplay constants) and is previewed in Lab → Full stack (tier walk + per-layer toggles). First-use FPS analysis: docs/investigations/streak-tier-fps-2026-10.md. The background glow (GameplayGlowLayer, x2+) is the tap tier glow without the tap: soft smoke clouds (backdropGlow = a near-round billow (a broad centre puff ringed by six soft puffs), backdropGlowOval = a slightly tall rounded puff; lobe layouts in glow-backdrop-cloud.ts, each puff the Gaussian falloff in glow-backdrop-falloff.ts; billows turn to a seeded angle each life so the one baked shape never repeats on screen) (backdropGlow, one <Atlas>) fire by themselves in six fixed lanes — GLOW_BLOOM_LANES_X, four in the centre and one at each side — with two blooms per lane half a loop apart (12 in flight), on interleaved timings (GLOW_BLOOM_LANE_PHASE). A bloom takes GLOW_RISE_PERIOD_MS_BY_TIER to travel bottom → top — a progressive ramp: 13 s at x2, 12 s at x3, 8.5 s at x4, 7.5 s at x5 (7 s at the lab-only x6); the rise is accumulated at the live tier's pace, so a streak change speeds blooms up without moving them. Each life picks a seeded peak radius from GLOW_BLOOM_PEAK_R_VARIANTS (18 / 21 / 24 / 27 % of lane width, same on iPad; each puff uses a Gaussian-style falloff with no hot centre and no knee in the slope, so no core or disc edge shows; each bloom peaks at TINT_ALPHA 0.3 × tier opacity so it stays quiet background). Two fixed slots (GLOW_BLOOM_OVAL_INDICES, one in each of two side-centre lanes) draw the squeezed backdropGlowOval sprite instead (the rounded wisp cloud, ×GLOW_BLOOM_OVAL_RADIUS_SCALE, tilted ± GLOW_BLOOM_OVAL_TILT_MAX per life via computeGlowBloomXform; billows turn ± GLOW_BLOOM_CLOUD_TILT_MAX), so the field is mostly circles with the odd oval and a small X wobble, blooms in, then narrows and fades, so black background always shows between circles. The sim fills a per-bloom render cache (only while the glow is visible) that the Atlas buffers copy. Each bloom draws a sprite rect centre-cropped to its cloud's lobes (cropGlowCloudRect; the dropped border is fully transparent), anchored on the crop's half extents in computeGlowBloomXform — about 37 % (billow) / 51 % (wisp) less fill per bloom with the same pixels. The rising orbs (StarRiseLayer, x4+) are 24 glowing dots at x4 and 28 at x5 (STAR_RISE_STREAM_COUNT; the 4 extras, isStarRiseExtraSlot, are spread along the line and fade in over STAR_RISE_FADE_MS) in three seeded sizes (STAR_RISE_SIZE_VARIANTS_PX 6 / 9 / 13 px on phone, ×1.5 on iPad = 9 / 13.5 / 19.5 px — halo and core scale together; rise 20 px on phone, 44 px on iPad; drift 4 px) that loop up off the hit line. Each is two quads: a soft tapTierGlow halo (STAR_RISE_HALO_DRAW_SCALE 1.6 × the size) tinted with the current streak glow color (STAR_RISE_ACCENT_BY_TIER = bgAccentRgb per tier, cross-faded over THEME_TRANSITION_DURATION_MS on x4 → x5), and a solid white core (STAR_RISE_CORE_FRACTION 0.45 × the size) on top; both twinkle (alpha × 0.7 ± 0.3). The tap bloom (TapTierGlowLayer, x4+) is the backdrop hue × TAP_TIER_GLOW_DARKEN (0.7) so it reads as a distinct deeper patch, at one of four seeded sizes (TAP_TIER_GLOW_SIZE_VARIANTS) per fire. The press light beam (LightBeam) fades in over 70 ms ease-out and, on release, tops up to full before its 350 ms fade-out, so even a quick tap's beam lights fully. The fades are sampled analytically (sampleBeamFade in LightBeam.utils.ts, same out-cubic / in-out-quad curves as the former withTimings) by ONE FX-frame runner for all slots, which returns at once when no beam is fading.

Song load sequencing

  • Runner prep in parallel: useMagicGameplay waits on whenSamplerReady() and ensurePlayableSongChart(songFileName, songVersion) together (Promise.all); the backing lookup (lookupSongBacking) is chained on the chart that plays (playable.key — a new version has no recording, so it plays its rhythm track), then it builds the chart and opens the backing.
  • Keyboard sheets from cache: when the keyboard sheet is already in its LRU (Retry, the next part, the same layout), AtlasPianoKeyboard takes it at once (peekKeyboardSheets) instead of waiting for an idle task; otherwise it bakes on idle, guarded by the 6 s GAMEPLAY_READY_WATCHDOG_MS.
  • Loading gate — everything drawn before 3-2-1: PlayScreenGameplayGroup's onReady (→ gameplayReady → prepareReady) fires once three parts are in, in any order (gameplay-ready-gate.ts): the keyboard's sheet is painted (onAtlasReady), the lane is settled — its SpriteRoot holds every sheet it was given or published, the judgement glyph ("hud") sheet included (onSheetsSettled, lane-settled.pure.ts) — and, for a host that passes rehearse (Game Mode, the tutorial song), the first-hit rehearsal has drawn and cleared under the card (GameplayRehearsal.tsx: tap, the other judgements, a hold and tiers 2–5 on the lane's middle white key, fired through the same handles useMagicJudgement fires; it never consumes a real tile and leaves the badge's visibility to the host). The engine is disposed between songs (it lowered memory crashes), so every song's card pays its own warmup; the first song after a launch also pays the process's Graphite / Dawn compiles there instead of in its first seconds. A new first-hit effect is added to gameplay-rehearsal-shots.ts with its fire and its clear (the tier glow's clear() included: its 3 s blooms otherwise outlived the card and showed through the countdown); gameplay-rehearsal-shots.contract.test.ts fails when a fired handle has no clear. The onboarding's hidden stage fires the same shots. Game Mode's hit line stays hidden under the card and the countdown (HitLineRevealContext, drawn at HIT_LINE_HIDDEN_OPACITY = 1/255 so it keeps drawing and its gradients stay warm) and fades in over HIT_LINE_REVEAL_MS when the countdown shows GO (useCountdownPreRoll); hosts without the provider (tutorial, labs) draw it always on. The 6 s GAMEPLAY_READY_WATCHDOG_MS starts the song anyway if a part never signals. While it waits, the card keeps its piano keys and adds a progress bar (PrepareProgressReadout): a 3 pt white bar along the bottom edge (scaleX on the UI thread), no label or percent, tokens prepareProgressTrack / prepareProgressFill. The share comes from usePrepareProgressStore, which the gameplay group (with rehearse) feeds: song loaded on mount, keyboard, each late sheet's paint (onSheetProgress ← paintInSlices), lane settled and the rehearsal's shots, weighted in prepare-progress.pure.ts; it never goes back and reaches 100% only when every part is in. Hosts opt in with showProgress on PlayScreenPrepareAssetGroup (Game Mode, the tutorial song); tutorial practice shows the keys only.
  • The lane presents itself (no Skia patch): PlayGameCanvas builds its root on createWebGpuSpriteBackend({ present: "canvas" }). The sprite planes (glow; tiles, FX, popups and the keyboard strip) are drawn into react-native-webgpu canvases and presented by the sprite engine on the UI thread right after the frame's writers, so a frame never waits on Skia's display link (which showed a late frame merged with the next: the iPad lane at ~46 fps). The hit line + smoke wave and the header score stay Skia, each on a canvas sized to its band (lane-break-box.pure.ts). The keyboard strip now paints under the score (they never overlap) so it shares the tiles' canvas. Details: src/core/sprite-engine/README.md, "Presenting into WebGPU canvases". Fallback if this path misbehaves on a device: branch release/1.0.11-skia-patch (Skia patch, present on submit).
  • Tutorial song under its reveal: TutorialGameplayScreen mounts the song surface once the reveal has settled (songRevealSettledMs(), 950 ms) and draws the reveal over it (zIndex above the song's own overlays) until it hands over, so the chart, runner and first frames use the reveal's hold (0.7 s, TUTORIAL_SONG_REVEAL_HOLD_MS; past it the loading card shows until the song is ready); its 3-2-1 waits on countdownArmed. The settle is reported by the reveal itself (SongRevealShowcase's onSettled, a withDelay on the UI thread started with its moves, hopping to JS through stable-js-callback), not a JS timer: the moves start on the UI thread's first frame, later when the screen's first frames are slow, and a song mounted on a JS timer could land on the end of the entrance (the name still fading in). The hand-over mounts the song too, should the settle never come. No atlas is baked ahead of the reveal: the lane's master atlas and the keyboard's key / overlay sheets bake on the surface's own mount (the old launch / idle prewarms — JudgementAtlasPrewarm, KeyboardAtlasPrewarm, TutorialPracticePrewarm, useTutorialSongPrebake — were dropped: they held the splash and loaded the app before the FTUE). The tutorial arms the same keyboard watchdog as the play screen.
  • Reveal smoothness — what is and is not measured: the chart steps are cheap (bun, cold: chartJsonToChart 0.05–1.1 ms and buildRhythmCursor ≤ 0.5 ms per tutorial chart, 26–50 notes). The heavy pre-play work is the Skia sheets above and the surface's mount: the native view mount, the UI runtime's first runs of the gameplay layers' worklets and mappers, and the layers' 30-frame GPU warmups (pipeline compiles run on Skia's render pool, not the main thread, in react-native-skia 3.7.3). The mount's main-thread share still lands in the hold, where the reveal's only motion is the 24 s ray turn. To measure on a device: EXPO_PUBLIC_PERF_HUD_ENABLED=1, fresh install, play the tutorial's first song and watch UI FPS from the tap to "3"; Instruments → Time Profiler on the main thread shows what the hold still carries.
  • Hitch trace (diagnostics builds): EXPO_PUBLIC_HITCH_TRACE=1 records one session per song (tutorial and Game Mode): UI frames over the hitch threshold (checked in GameplayFxFrameProvider, only hitches cross to JS), JS rAF stalls ≥ 50 ms, and marks — reveal / prepare / countdown, canvas_layout:lane, each layer's prewarm_begin/end:*, first_press, first_judgement, tier_change:n, and timed first calls (first_haptic, first_register_tap, song_start_analytics, first_tap_analytics, atlas_prebake:lane). The summary goes to [hitch] (console.warn + Crashlytics breadcrumb) and Lab → Hitch traces keeps the last 5. Every session is also saved as its own file <start>_<screen>-<session>.json in the app's Documents/hitch-traces/; the Lab's Share file (one session) / Share all (file) sends it through the share sheet, e.g. AirDrop from a TestFlight build to the Mac. Code: src/features/piano/diagnostics/ (hitch-trace.pure.ts summary + hints, hitch-trace.ts JS half, hitch-trace.worklet.ts UI half). Off, every call returns at once. How to read it: docs/investigations/streak-tier-fps-2026-10.md → Tutorial first song.
  • Effect toggles (Lab, dev only): gameplay-effect-toggles.ts + gameplay-effect-toggles-store.ts switch any Game Mode effect layer off in PlayGameCanvas and TutorialGameplayCanvas, read once per canvas mount. All on by default; used to bisect a first-play GPU hitch on a fresh install (protocol in docs/investigations/streak-tier-fps-2026-10.md).

Gameplay clock

The falling lane (tickSv, the playhead P) and the audio clock A are two clocks, and audio is the master (useRhythmEngine). Tiles are drawn at f(P) and taps are judged against P, so every window (zone timing, visibleAhead, holdTailInset, resumeLate — all px → tick conversions) is only as accurate as |P − A|; the design keeps that to a few ms and keeps P smooth.

  • Lane (advanceDisciplinedLaneTick): integrates the frame delta along the adaptive-tempo curve, at rate = 1 + clamp(errorMs / 250) (speed-up capped at +10 %, down to a standstill when ahead). errorMs is the lane − audio offset, measured where the lane lands THIS frame against the audio tick extrapolated by the time since the anchor was sampled (extrapolateAudioTick; a new anchor counts as half a frame old), then low-passed (LANE_ERROR_FILTER_MS = 100 ms). Never backward, no hard clamp, no staircase of the 20 ms anchor.
  • Catch-up: if the lane is more than LANE_CATCH_UP_SNAP_MS (60 ms) behind (a JS / UI stall just ended) it jumps FORWARD onto the audio tick in one step. Audio is never rewound for the lane while playing — there is no drift guard.
  • Audio watchdog: if the anchor stands still for more than AUDIO_STALL_HOLD_MS (150 ms) while running (a blocked JS thread, a suspended iOS context) the lane holds, then catches up as above.
  • Pause / resume: PlayController re-aligns the paused song clock onto the lane tick (setDisplayTickSource → realignTo) — inaudible, since audio is paused, and the lane is within a few ms of it. It does not seek; the recorded backing is only re-seeked past BACKING_REALIGN_MIN_SEC (15 ms). A wait-mode tempo snap anchors on the tick on screen.
  • Start / resume seed: the hook publishes a one-shot seedTick together with an audio anchor on it (audio tick on start, lane tick on resume), so the lane starts with no error.
  • Wait mode: the hook publishes holdAtTick (the head group's tick plus a margin of at least 2 frames, capped by resumeLate), so the lane parks on the hit line by itself.

Who reads which tick: taps / releases use the lane tick stamped on the UI thread at the touch (atTick); the paused resume tap uses the frozen lane tick; the anchor step (miss sweep, hold completion, auto-pause, onStep) uses the audio tick, so a UI hitch never delays a miss; adaptive tempo and cue / pinned-hold geometry read the lane mirror (VisualClockChannel, getDisplayTick). Diagnostics: with the perf HUD on, the SYNC row shows the live lane − audio offset (onClockDrift → reportGameplayClockDriftMs). Tunables (LANE_ERROR_FILTER_MS, LANE_SLEW_GAIN_PER_MS, LANE_SLEW_MAX_SPEEDUP, LANE_CATCH_UP_SNAP_MS) are sim-tuned, not device-tuned — check the SYNC row on hardware.

Simulation: packages/rhythm-engine/tests/lane-discipline.sim.test.ts (60/120 Hz jittered frames, render-quantum audio clock, late pulses, JS / UI stalls, a stopped audio clock, a +0.5 % display clock, tempo ramp).

Adaptive tempo (hidden, default OFF)

PlayScreenBody mounts useAdaptiveTempo (adaptive-tempo/): a per-play policy that slows the song (multiplier m 0.5–1.0) after repeated wait-mode pauses and recovers on clean play. Default OFF (Remote Config adaptive_tempo.enabled:true turns it on); active only while that is on, wait mode on and a normal song; judgement windows stay real-ms (getTempoMultiplier → useMagicJudgement / syncPlayScreenNoteInput), the lane scrolls via TempoMultiplierContext, recorded backing is held while m < 0.995. Full contract, wiring, findings and the by-hand play guide: docs/adaptive-tempo.md.

Backing accompaniment — the MIDI rhythm track

Every song that reaches PlayScreen carries an accompaniment under the player's melody taps: the chart's MIDI rhythm track. midiToChart selects the named rhythm track (or the legacy heuristic split) and PlayController's rhythm-track auto-scheduler schedules those notes through the sampler: each chord voice uses its raw MIDI velocity (fallback DEFAULT_RHYTHM_VELOCITY = 60 when the chart carries none — never scaled); backing loudness is a gain on the rhythm role (TrackSamplerLike.setVolume ← PlayController slider), and note-offs fire after computeAutoReleaseMs(noteLength, ticksPerSecond) so voices don't ring their full SoundFont sample tails.

There is no recorded (OGG / MP3) backing any more: it played through react-native-audio-api, which was removed (see audio-engine.md). The IBackingTrackAdapter seam stays in @rhythm/engine, but the host supplies none, so controller.backingSource is always "rhythm".

Learn Mode plays the learn chart's demo on the sampler's melody track; its stage-7 backing is the chart's rhythm track on the rhythm bus (useLearnBacking).

The PausePanel "Background-Audio" slider calls PlayController.setBackingLevel(slider), scaling the rhythm-track velocity multiplier. The "Piano-Sound" slider drives setPianoVolume on the sampler master. Slider position 1.0 lands on the calibrated default mix; 0.0 silences the respective bus.

Default slider positions live in src/features/piano/gameplay-volume.constants.ts (DEFAULT_GAMEPLAY_PIANO_VOLUME, DEFAULT_GAMEPLAY_BACKING_VOLUME). useSoundFontSampler seeds the piano master fader from the piano constant on every sampler load (Play, Learn, tutorial, Keyboard free-play). useMagicGameplay seeds the backing level when the controller becomes ready; PlayScreenHudOverlayGroup initializes its PausePanel sliders from the same constants.

Mix calibration

src/core/sdk/adapters/mix-calibration.ts holds the master shaper curves (buildShaperCurve, LIMITER_KNEE) and the preview headroom (PREVIEW_HEADROOM_SCALE, applied per note via amplitudeScaleToVelocityScale). Piano headroom is full scale (the Sound model has no headroom knob); the native FxLimiter takes the sum when taps stack. Melody / rhythm release is the sampler's SF2 ADSR — screens only call releaseVoice / releaseNote.

Hold durations (computeAutoReleaseMs / computeRhythmHoldMs) live in note-release.ts and packages/rhythm-engine auto-release helpers. Release fade is never chosen by PlayScreen / PlayController / stores — only when to trigger release.

Adding a new song:

  1. Add a catalog row in the Google Sheet (or src/assets/config/songs.json for offline bootstrap) with fileName and midiUrl.
  2. (Optional, build-time) Add the song to the Google Sheet with a MIDI URL and run catalog:sync-sheet — MIDI is converted to chart JSON under src/assets/charts/ and registered in src/core/sdk/song-assets.ts.

Remote midiUrl bytes are fetched on first play and cached under MediaStore; bundled assets are tried first when registered.

Tested end-to-end in packages/rhythm-engine/tests/play-controller.test.ts:

  • Rhythm notes are pre-scheduled by the song sequencer at exact audio start / release times (playNote(…, atTime), releaseVoice(voice, atTime)), never on timers; pause cancels voices not yet sounding and resume re-schedules them.
  • start / pause / resume / dispose drive the engine in lockstep.
  • setBackingLevel(slider) clamps inputs to [0, 1] and silences the rhythm role on non-finite values.

Why a separate feature folder

  • Audio + game engines are an isolated subsystem with a heavy dependency cone — that cone now lives in packages/@piano/* so it can be swapped, unit-tested with bun test, or shipped to a different host without dragging Expo with it.
  • The host feature folder stays small: just the UI store, the screen, the asset manifest, and (eventually) the hook wrappers that bridge engine events to React Native primitives.
  • Removing the gameplay surface is rm -rf src/features/piano + dropping the route — the engines under packages/* are unaffected and remain consumable by other hosts.

Sample bank

Production uses the bundled SF2 in src/assets/soundfonts/; the native engine loads the file itself (TinySoundFont) from its resolved file:// path (resolveSoundFontAssetPath). The boot font is Steinway; Steinway is the only bundled font; the DevTool Sound tab can switch to a key of soundfontAssets (or a font synced from the desktop DevTool) on the live sampler for the rest of the session. A load that fails leaves the previous font playing and the DevTool shows an error. All bundled SF2s are stereo (a left zone and a linked right zone per key); the native sampler renders both channels.

Piano sampler lifecycle — one native engine

The piano engine is the iOS AVAudioEngine backend (NativePianoSampler) behind the PianoSamplerLike surface — see audio-engine.md. There is one process-wide instance; all piano surfaces (Play, Learn, free-play keyboard, tutorial, song previews) share it and its SF2 bank, and screens do not dispose it on unmount. Android has no engine yet, so ensurePianoSampler fails there and the screens stay silent.

  • Roles. The engine's three roles share one voice pool with a per-role gain:
    • User (sampler.user / playNote) — keyboard taps and held-voice.ts
    • Melody (sampler.melody) — auto-play, pre-scheduled by the controller's song sequencer (melodySampler lane, enabled via setMelodyAutoPlay). useAutoPlay.voicing.ts keeps the synthetic tap + key visuals on the UI crossing and only voices audio itself for a head already behind the clock on enable (or with a fixed-velocity override).
    • Rhythm (sampler.rhythm) — chart rhythm lane via createRhythmSamplerAdapter (converts the engine's absolute atTime to the track's relative delay) Same-pitch voices overlap across roles; a note-off names the exact voice and the pitch stays held while another holder owns it. Polyphony is capped natively (oldest voice stolen first).
  • Held notes at the end. The SF2 zones loop, so a voice that never gets a note-off rings forever: the play screen and the tutorial song release the player's held keys (releaseAllHeldVoices) at game over, on unmount, and the moment the app leaves active (the keyboard drops its touches there without key-ups). On unmount the play screen then sweeps the user / melody / rhythm tracks (fadeOutStrayGameVoices, 0.3 s — ignored natively, which releases through the SF2's own tail); natively that stopAll covers the whole shared pool, preview included, so it runs only at unmount, seconds before the result's preview can start.
  • Looped SF2 zones (sample modes 1 / 3 — e.g. Steinway) decay through the zone's own envelope in the native sampler core; see the module README.
  • Boot. registerSamplerFactory(nativeSamplerFactory) and the mixer sync are installed from entrySetup.ts; ensurePianoSampler() runs from AppProviders and from each screen's useSoundFontSampler.
  • Memory pressure. releaseMemoryPressure disposes the sampler (disposePianoSampler) so a screen opened later builds a new one — and skips that while gameplay is active, while a fullscreen ad (or its post-close latch) is up, or while a screen holds the live audio surface (holdLiveAudioSurface: Learn Mode, the tutorial's song and practice, the free-mode Keyboard).
  • useSoundFontSampler subscribes to the process-wide singleton via usePianoSamplerStore. A failed build is retried once per mount.
  • usePianoSamplerStore (zustand, ephemeral) tracks singleton status (idle / loading / ready / error) and the live handle.
  • Prepare still waits on segment plan, layout, and keyboard atlas bake (AtlasPianoKeyboard defers key/label/overlay bake via scheduleIdleTask after first paint; free-play KeyboardScreen still limits the visible MIDI window to viewport + overscan via bakeWhiteKeysForView). A refused key-sheet bake (offscreen surface unavailable under memory pressure or in the background) is retried on a short backoff (keyboard-bake-retry.ts) and again on the next return to the foreground. No bake runs while the app is backgrounded, and a sheet whose sprites cropped to nothing is rejected before the LRU can cache it (isKeyboardSheetIntact). Every offscreen bake goes through guardedBake in sprite-atlas.ts: Skia THROWS (not returns null) when the GPU refuses the readback (makeRasterImageSync: reading the image back failed, 1.0.9), so a refusal is reported as a handled error and becomes null. The judgement atlases retry on the same schedule (atlas-bake-retry.ts, useAtlasBakeRetry); tests in sprite-atlas.readback.test.ts fake the GPU failure.
  • Song previews. core/audio/song-preview: a cover tap plays ~15 s of the song's bundled gameplay chart through the sampler (ChartPreviewPlayer); one preview at a time, none under a screen cover.
  • Production three-layer keyboard: AtlasPianoKeyboard + keyboard-key-atlas.ts bake base (housing — white: ONE white_base shell for every notch variant and both states, only the lip below the cap — the notches sit far above it (whiteShellNotchBottom < whiteBaseLipTop, unit-tested) — its cell cropped to that lip so ~90 % less transparent fill per white key, the quad dropped by whiteBaseOffsetY, #494949→#787878 gradient across the lip, no border) + top static (white: #D4D4D4→#E5E5E5 rim — thin top/sides, thick foot — full shell width so only the shell's lip shows, crisp inner edge, face inset inside, soft inner shadow over the whole top) + top pressed (white: the same cap lengthened by the press into the lip, notch cut deeper, under black at 50%; black: both caps a rgba(23,23,23,0)→#404040 gradient with a hairline white inner shadow on the sides and bottom only, fading in from transparent at the top to 25%, pressed lengthened and dimmed 50%, body with a soft grey line down each side (small gap at the top, square end at the foot, fading to black at both ends); below the cap a small trapezoid front piece in the flipped gradient with a dark centre line, baked into the cap sprites so a press shortens it) per key (13 sprites: 1 shell + 4 notch variants × 2 caps, black base + 2 caps + drop shadow; the shell packs last so the sheet's slack crop trims its row to the lip). Black keys draw at ATLAS_BLACK_KEY_WIDTH_SCALE (0.85) of the lane ratio, centred on the same seam — lanes and tiles keep the full width. Keys sit in a strip with ATLAS_KEYBOARD_VERTICAL_GAP_PX (2px) top/bottom. Press travel: white KEYBOARD_KEY_WHITE_PRESS_DROP_PX = 5 — the key's top never moves; the pressed face is baked that much longer, down into the lip (13.2 at the design height, so a sliver of foot stays), the notch beside a black key cuts that much deeper, and the labels and Learn chips sink with it (pressLabelTy / pressWhiteSinkTy); black KEYBOARD_KEY_BLACK_PRESS_DROP_PX = 5 — lip-clamped, the pressed cap lengthens down. A press goes down in KEYBOARD_KEY_PRESS_IN_MS (40 ms) and its first step is taken in the frame that took the touch (KEYBOARD_KEY_PRESS_FIRST_STEP_MS) — the frame loop that carries the rest only wakes after a hop through the JS thread; a release comes up in KEYBOARD_KEY_PRESS_OUT_MS (110 ms). Key, overlay and label sheets bake at the device pixel ratio (keyboardKeyAtlasBakeScale → ceil(DPR), 2× floor on low-DPR, 1 on web) and RSXforms downsample by 1/bakeScale; bakeKeyboardSheets shrinks the scale only if the sheet would exceed KEYBOARD_KEY_ATLAS_MAX_TEXTURE_DIMENSION (8192). White-key note labels bake into a separate sheet (keyboard-key-label-atlas.ts) — two atlas quads per key. The key and overlay sprites share ONE sheet (keyboard-sheet-atlas.ts: registered together with the engine’s shared compact texture layout under the 8192 cap — overlays at up to 1.5×, keys at full scale; the grid bands it replaced padded every short cell to its row's tallest. The Learn tint_band cells are baked only for a keyboard handed keyTints (Learn, the lab): buildOverlaySpecs(…, tints) / bakeKeyboardSheets(…, tints), and the LRU key carries the flag — a third of the overlay cells less on Play, tutorial and free-play) — so the white / shadow / black regions and their washes sample one texture and the plane draws the keyboard in 2–3 calls (keys + washes, labels; an idle shadow region splits the key sheet's draw) instead of 5. The keyboard owns its canvas and plane (createLayeredPlane, AtlasPianoKeyboardLayers.tsx); keys are four useSpriteSystems (white / shadow / black / labels, slot = key) in AtlasPianoKeyboardLayers, woken per key by press travel or an overlay change (AtlasPianoKeyboard.wake.ts). That sheet is a ~10 MB CPU raster and a pure function of (key geometry, bake scale), so it goes through a small LRU (bake-lru.ts, 3 entries); a miss bakes as a sliced job (startKeyboardSheetsBake: cells drawn ~6 ms per idle slot, readback in a slice of its own) rather than one frozen call — a replay reuses it; re-baking per mount left ~22 MB of native pixels per play session behind Hermes GC (which paces on JS heap, not on the pixels behind an SkImage). The gameplay master / FX / light-beam sheets keep no CPU raster at all: only their layouts are cached and the sprite engine bakes them on upload (keyed bake sources). Overlay washes (keyboard-key-overlay-atlas.ts) bake highlight / Learn tint / wrong-key alpha sprites once and modulate per slot (no per-frame createPicture). Highlight / tint / wrong rides press travel with the key face (white pressWhiteSinkTy, black pressBlackTopTy) and stays visible through held/auto — wrong-key red still replaces highlight. Canvas z-order is whites → white overlays → shadow → blacks → black overlays → labels. Imperative handle is PianoKeyboardHandle (setHighlightNotes / setPressedNotes). No built-in haptics — parents fire Haptics.play from onNotePressed / onNoteReleased (free-play + Learn key click; Play/Tutorial leave key-edge buzz off so judgement owns perfect/hold). Countdown / prepare gates on onAtlasReady (not a snapshot blit). The press-travel runner (in the keyboard's own GameplayFxFrameProvider) idles when every key's progress matches its target (pressActiveSv). Learn number chips stay as RN KeyNumberBadges — pass stripBottomGap={ATLAS_KEYBOARD_VERTICAL_GAP_PX} and pressSinkByNote. Preview in Component Labs (atlas-piano-keyboard). Wired on Play (MultiplierAwarePianoKeyboard), Tutorial, Learn, and free-play Keyboard screens. Play and the tutorial draw it at GAMEPLAY_KEYBOARD_HEIGHT_SCALE (1.05×) the reserved strip (computeGameplayKeyboardHeight, keyboard-strip-height.ts) — it grows up over the lane's foot while the lane keeps the base strip, so the hit line doesn't move; free-play keeps the plain strip.
  • Changing the window without a flash (Free mode's zoom): the keyboard draws and hit-tests the layout its sheets were baked for, and takes a new layout together with its key and overlay sheets in one update. Drawn against another layout, a sheet put the old key size at the new positions, which is how Free mode's keys overlapped after + / −. Key transforms are plain arrays built with the sprites in the same commit, and the layout's shared values sync in layout effects. poolCapacity sizes every pool beyond the layout, because a Skia buffer that changes size draws one frame of its defaults (black, at the origin); Free mode passes the whole piano. A sheet bakes in about 0.1–0.2 s on the simulator: trimAtlasOpaqueExtents reads only the transparent margin it trims, where it used to scan every pixel in JS (about 0.5 s a sheet, and Free mode's keyboard waits for two).
  • Piano audio lab: Component Labs entry piano-audio (PianoAudioLab) mounts a production AtlasPianoKeyboard on the process-wide sampler and toggles sampler.setSustain so you can A/B pedal on vs off without leaving the labs shell (same engine path chart pedal spans use via PlayController). Its Audio backend panel (AudioBackendPanel) shows the live engine, capabilities, the shared mixer and diagnostics (CPU, xruns, latency, voices, peak / RMS).
  • Tests: src/core/audio/__tests__/pianoSamplerService.test.ts pins singleton ensure / dispose / error-retry semantics using fake samplers — the service has only import type references to PianoSamplerLike, so tests never pull the native module into the bun runtime.

If you need to add another audio engine (recorder, second sampler bank, FX bus), follow the same pattern: thin service in src/core/audio/, hook subscribing to the singleton, factory registered from the app entry.

There is no in-app Sound settings screen, metronome or volume meter: the first was replaced by the desktop DevTool Sound tab, the rest played through react-native-audio-api. UI sound effects and the app-open chime use the native module's SFX player (audio-engine.md).

Adding a new gameplay surface

The Magic Tiles pattern (Skia rendering stack + judgement) lives in screens/PlayScreen/. To add another flavor (e.g. a Zen surface, a Learn drill, a debug runner):

  1. Reuse the gameplay hook. useMagicGameplay already loads the song, builds a @rhythm/engine PlayController, and exposes a SharedValue<number> tick clock via useMagicJudgement. Wrap or fork it for engines other than the Magic flavor.
  2. Compose the Skia stack the same way. Same per-key window (startNote / endNote, from computeAutoFitKeyRange) and width flowing to <AtlasPianoKeyboard>, <TileFalling>, <HitEffect>, and any new overlay — see .cursor/skills/piano-simulation-screen/SKILL.md.
  3. Decide if the surface is judged. For a scored surface, mount useMagicJudgement + the HUD leaves (HeaderScore, MultiplierBadge, SessionResultOverlay, PlayScreen PlayGameCanvas — which hosts every lane *Layer including <JudgementPopupLayer> and <CenterJudgementLayer>) and gate them with a judgementEnabled boolean so an unscored mode keeps the same screen file. Pass the <TileFalling> ref into the hook so consumed hits detach the matching tile. The per-tile <JudgementPopupLayer> carries the +points glyph; the central <CenterJudgementLayer> carries the label + combo suffix. Tweak gameplay rules in @rhythm/engine's judgement/constants.ts; tweak host-side UI windows in judgement.constants.ts — never inline new windows / point values / tier rules in the screen code.
  4. Keep the screen awake during play. Call useKeepGameplayAwake() at the top of any new immersive piano surface so auto-lock does not interrupt mid-session. Already wired on PlayScreen, LearnModeScreen, and KeyboardScreen. (iOS bottom-edge gesture deferral is app-wide in AppProviders — do not re-toggle it per screen.)
  5. Add the route. Drop the screen under app/(app)/ and forward to it from the catalog list (or the home grid).

Performance: PlayScreen must not subscribe to judgement store on the gameplay tree — use imperative HUD leaves and getState() at write sites. See gameplay-hot-path.mdc and the trimmed piano-simulation-screen skill; full layer inventory stays in this doc's Files section above.

Reanimated: static feature flags (none set)

package.json sets no reanimated.staticFeatureFlags: the app runs on Reanimated 4.7's defaults. An earlier build turned on IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS (apply whitelisted props — opacity, transform, colors, border radii, shadows — directly instead of a Fabric shadow-tree commit per animated style update) and tried FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS = false; both were dropped. A static flag is compiled into the native build, so adding one back needs pod install + a rebuild.

With the defaults, two things show up in profiles:

  • Per-frame shadow-tree commit. Every animated style update — even a lone opacity/transform such as the song-progress bar's translateX — goes through cloneShadowTreeWithNewProps → Yoga layout → mount on the main thread. Keep the number of animated views on the play screen small and prefer the sprite engine for gameplay visuals.
  • settledStyle renders. FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS (default true) writes an animated style's settled value back into the Animated.* component with a setState, flushed every 500 ms. The Profiler shows "Props changed: style, ref" on a View (AnimatedComponent) while the memo-isolated parents above it did not render (the progress rail's opacity gate and translateX fill, countdown, HUD chrome, pause panel). The render stops at that view; it is not a bug in the rail's own props. Android's ANDROID_SYNCHRONOUSLY_UPDATE_UI_PROPS was never enabled.

Skia canvas cost model (why idle pools are compact)

Each <Canvas> has one Reanimated mapper that re-applies every animated prop of every node on each frame any of them changes, then re-records the scene. The gameplay lane canvas changes every frame, so Atlas arrays are marshalled through JSI every frame regardless of liveness. HoldEmberLayer (8 slots × 244 quads) and SmokeParticleLayer (4 × 24 = 96-quad pool) therefore publish only the quads of live slots (buildEmberLiveView / buildSmokeLiveView; empty when idle) instead of the full fixed pool: measured on the simulator, ember alone fell from ~10 % to ~1 % of main-thread time. Texture size / atlas splitting does not change this cost. See .cursor/skills/skia-atlas-object-pool (§2b).

Hold embers on pause

Pausing ends every hold (PlayScreenBody.pauseGameplay → HoldEmberHandle.drainAll()), but it does not cut the embers: slots go SLOT_DRAINING, nothing new launches, and the embers already in the air finish their rise. Launches ride the playback tick, but a flight in progress also advances on the shared FX clock while the tick is frozen (advanceEmberPause / pauseCreditPx → evaluateEmber's pausePx / pauseCreditPx), so a paused game no longer freezes an ember mid-air. After the pause outlasts the longest flight (HOLD_EMBER_MAX_FLIGHT_PX) the layer stops writing frames (pauseDone). Teardown still uses clear(), which cuts instantly. On the first moving frame after a pause, bakeEmberPauseOnResume moves the cursor's credit onto each live slot (pool.pauseTick / pool.pauseCreditPx) so a later tick plateau cannot hand landed flights their age back. A real pause (≥ EMBER_REAL_PAUSE_MIN_PX of wall clock — e.g. auto-pause at the hit line) also ends every released field and tap puff (pool.burst) at the pause tick and frees the ones whose embers already landed; otherwise a puff's remaining tick-axis launches fired after the player hit the NEXT note, replaying the previous note's embers. Slots seeded during the pause (seededInPause — the resuming note) are left alone.

Short holds, stale arms and lost ember seeds

Dense charts (Rush E) are full of holds that the engine completes before HOLD_VISUAL_ARM_MS (120 ms): effectiveHoldEnd pulls the tail back by the note core, so a ~260 ms hold can finish 5–116 ms after the press. useMagicJudgement handles every hold exit per hold (noteNumber + noteTime), not per key:

  • Ended before arm — the arm timer is cancelled; finishUnarmedHold unpins the press-pinned body (or consumes a head that never pinned, so no tile parks on the hit line). No ember field — the hold is cut off, as a tap-looking short hold should be. No completion bloom (holdComplete) — that haptic is only for a hold that armed; an unarmed one already had its head's tap haptic.
  • End before its own tap cue — the engine can fire a hold's end in the same tick as, and before, the head's tap cue. Each end records endedHoldNoteTimeRef; scheduleHoldVisualArm then never arms that hold (an arm after the end used to pin + rumble a finished hold and leave its armed flag set forever, which skipped the key's NEXT hold and left its tile on screen with a full tail). It only detaches the head (plus the Perfect hold-end hit burst) instead.
  • Stale armed flag — scheduling a new hold on a key still marked armed closes the old one first (closeStaleArmedHold: stopGameHold, releaseHold, ember release); an older hold's press pin that never armed is unpinned too (releaseStalePressPin), or the new pin would orphan its slot. The arm timer also re-checks that its hold is still the key's current one and not ended.
  • Pause — pauseGameplay calls cancelPendingHoldArms() so no arm fires while frozen.
  • Ember publishes merge — JS publishes its pending ops with pendingOpsSv.modify(...) → mergeHoldEmberPendingOps on the UI runtime instead of replacing pendingOpsSv.value, so a publish no frame has applied yet is never lost (a RELEASE on a not-yet-applied SEED keeps the seed with releaseAtSeed).
  • Known, not fixed: the JS ember slot mirror never learns that the UI freed a slot (every slot reads draining); draining slots are reused oldest-first, so this is harmless until the pool is truly full.

Hold ember lab presets

Every ember animation knob lives in one HoldEmberTuning object (HeldTile.utils.ts); gameplay uses DEFAULT_HOLD_EMBER_TUNING (the HOLD_EMBER_* constants) and never passes HoldEmberLayer's optional tuning prop. The Labs → Hold ember screen drops real notes on a TileFallingLayer and auto-plays them like a perfect player (hold-ember-lab.chart.ts: tap → consumeTile + burst; hold → HOLD_VISUAL_ARM_MS → pinHold + start, tail → releaseHold + release; fixed 1.5-beat hold tail). It is a layout: "fill" lab (the modal folds its lab list away and hands it the whole panel): the lane is pinned on the left at 1:1 px — sized from the window by resolveHoldEmberLabPreviewSize (hold-ember-lab.layout.ts), tiles stay 30 px, only the lane narrows — with a one-line transport (Play / HIT, note type, static TAP / HOLD) under it, while the controls scroll on their own on the right: Device / Tune / Speed / Group (ALL · SHAPE · MOTION · FADE · COUNT) pinned at the top, then one-line knob rows (EffectLabCompactChips: title + horizontally scrolling chips, ● = gameplay default, hint behind ⓘ), the readout + reset, and a collapsed Advanced section (renderer rows, bench HUD, notes). Chip rows from hold-ember-lab.presets.ts swap one field at a time (5 chips per row, the gameplay DEFAULT in the center — or first when it is the knob's floor, e.g. drift 0) — rise height, lowest ember, launch kick, keep floating (riseCarry), flight time, drift, drift fan-out (driftCurvePow), vent width (pyramid base), height spread (riseSkew), lean start / lean angle, pyramid pinch, size, embers per second (hold) / embers per tap, first wave, fade in / out, shrink. Per-frame fields (rise, curve, carry, drift, drift curve, pinch, fades, shrink) change embers already in the air; seed-time fields apply from the next note. The tap-puff launch window is derived (resolveTapEmberBurstPx) so any count / speed still launches every puff ember exactly once. The lab mounts the layer with emberCapacity={EMBER_LAB_EMBER_CAPACITY} (300) so the hold rate / tap count can go above gameplay's fixed 100-ember slot buffer (the readout shows RATE n/s (m embers) — the embers that rate needs); gameplay keeps the default. Halo blur (HOLD_EMBER_GLOW_SCALE 4.6, HELD_EMBER_CORE_SHRINK in held-ember-crop.ts) is baked into the atlas and is not a lab knob.

Benchmark HUD (lab only). The STRESS ×8 note type drops 8-hold chords to keep every slot live; the HUD (EmberBenchReadout.tsx) shows UI fps, worst frame and JS stall per second. Skia records the declarative <Atlas> pair on its native pool, so the record cost is not visible there — compare through fps / worst frame (and Instruments).

Shared gameplay HUD glyph sheet

useGameplayHudAtlases packs points, centre words and streak characters directly into one MaxRects sheet (judgement-hud-atlas.ts). The queue bakes it in idle slices, caches it per theme, and retries refused allocations. PlayScreen passes the same atlas to JudgementPopupLayer and CenterJudgementLayer, which sample hud with alpha blend and can share one draw when both fixed pools are submitted. Glyph advances, origins, font sizes and PERFECT aliases are preserved. Standalone tutorial and lab callers retain their existing sheets and word looks. Plane boundaries preserve the soft-FX resolution, Skia hit-line order and keyboard strip target. Actual texture area depends on font metrics and packing. Device FPS and memory gains require profiling.

The shared HUD sheet is registered once by PlayGameCanvas in WebGPU devtools as “Judgement HUD glyphs (points + words + streak chars)”. Shared-atlas layer instances omit their standalone registrations. Dev registrations use a mounted-owner id so overlapping screens cannot remove each other’s entries during cleanup. beam-white and beam-black are the key-aligned LightBeam columns, whose widths follow the white and black key feet (black = 0.6 × white).