v1.0.10 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 63ea8c2b3d.

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 Skia pill inside `PlayGameCanvas`. 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 cycles every x2..x5 label (`warmLabels`) so each glyph is rasterised before play; a label the game sets during the hold is parked and handed back. 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 atlas bakes one stroke color per `JUDGEMENT_INDEX` entry (`strokeByIndex`), so a hit's `+N` always matches its centre label's outline. 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 (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 synchronous JS, so it goes through the process-lifetime cache in `judgement-atlas-cache.ts` (`getJudgementCenterAtlas` / `getJudgementPointsAtlas`, keyed by colors + word look; font + bake scale are process constants) and `<JudgementAtlasPrewarm>` — mounted in `app/(app)/_layout.tsx`, NOT in `PlayScreenBody` (a song loads faster than the font resolves, so a play-screen prewarm loses the race) — fills it on the idle queue while the user browses songs. Replays and later plays are cache hits. 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 `PLAY_SCREEN_CENTER_JUDGEMENT_TOP_OFFSET` (42) — the tutorial uses the same offset; on iPad PlayScreen removes the safe-area top inset and adds `PLAY_SCREEN_CENTER_JUDGEMENT_TABLET_NUDGE` (44). 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. Prepare card fades in/out (`FadeIn`/`FadeOut`); render phase resolved by `CountdownOverlay.utils.ts:selectCountdownOverlayPhase` (`loading`/`dismissing`/`countdown`/`hidden`). 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 overlay owns the lit tab (opens on **Play**), takes both halves' picks from [`useSessionResultSuggestions`](../../src/features/piano/hooks/useSessionResultSuggestions.ts), holds the column's selection (`useResultSongSelection`), 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/`.
    SessionResultScore.tsx            # grouped score + the block VoiceOver reads as one thing; the paint is the shared [`ScoreFigure`](../../src/components/ScoreFigure.tsx) in `src/components/` (`hero` 60/78 — the tablet celebration's bold 2pt `inverse` stroke; `compact` 48/62 — the phone result's extrabold 1pt #FFFFFF stroke + `0 0 4px #0084FF` glow, both scaled by `TABLET_TYPE_SCALE`). Learn Mode's accuracy percentage renders through the same component at `compact`, so the two results' big numbers cannot drift apart.
    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`).
    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                    # unified lane Skia canvas (`PlayGameCanvas`)
    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 defer through a coalesced idle queue (play-screen-press-visuals.ts); a key lifted before that flush marks its pending press released, and the flush calls beam.flash() (full opacity → fade out) so every hit still lights the beam. 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 hides the body (atlas slot inactive) and frees the 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 (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.

  • 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 flips a single enabled prop (true once isReady) and receives a single onComplete callback at the end. Localising the per-second setState to the overlay 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. 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 countdown render-phase decision (loading / countdown / hidden) is a pure helper (selectCountdownOverlayPhase in CountdownOverlay.utils.ts) driven by showLoading + a latched done flag — enabled only gates the interval, not the render, so the prepare card stays put across the "enabled flips true" → "first digit lands" gap without a one-frame flicker. The countdown is armed only once the screen is on view: the play body gets the route's screenEntered (PrepareAssetGroup isReady={prepareReady && screenEntered}), so "3" never runs under the route fade; the tutorial song arms it when its reveal hands over (countdownArmed). With that gate there is no hold left (COUNTDOWN_PREPARE_TO_START_DELAY_MS = 0, still a timer so the glyph mounts first); 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. The frames are a setTimeout chain (gameCountdownFrameDurationMs), not an interval, since GO holds 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 promo unmounts, countdown scrim mounts) so the first digit pulses in as deliberate punctuation. Pass skipCountdown (via <PlayScreenPrepareAssetGroup skipCountdown>) to dismiss prepare as soon as enabled flips 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.

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

<TileFalling> Shared Tile Buffer + Sliding Cursor. Chart notes are converted once at song/layout load into a sorted flat SharedTileLayout[] via buildTileSharedLayout (precomputed lane geometry + appearAtTick / resolveByTick windows). A UI-thread advanceTileCursorWorklet monotonically slides tileCursorSv (startIndex..endIndex) from tickSv — same pattern as leap-sim-guitar's SharedNotesCursor, in tick space. Atlas slots bind/unbind to the active window; consumeTile marks a consumed flag and reuses the same atlas slot for the next unbound in-window note. Body/beam Atlas buffers 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 scroll is still one Group translateY(tickSv), plus a sparse hit-line clamp / held-slot rewrite in TileFalling.hold.ts so active falling bodies never draw below the receptor and held bodies stay screen-anchored. Judgement stays on @rhythm/engine's separate headIdxSv / RhythmCursor. See TileFalling.tsx, TileFalling.slots.ts, TileFalling.utils.ts.

Window-step batching. The frame callback detects the cursor transition itself and hops to JS once per window step through the module-level dispatcher in stable-js-callback.ts — never a component closure, which worklets can free mid-flight during a navigation transition. There is no second reaction worklet re-deriving the same transition on every frame. The one reaction in the layer is the tick-fresh pose pass: the hit-line clamp and the held counter-scroll (clampFallingSlotsAtHitLineOnUI / updateHeldSlotsOnUI) run in a useAnimatedReaction on tickSv, not in the frame callback. Frame callbacks run in activation order and the engine's tick writer (autostart: false, re-activated on every resume) usually activates after TileFalling's, so a callback read tickSv.value one frame stale while the lane <Group transform> mapper used the fresh tick — parked and held bodies sat one frame of scroll off the hit line, by a varying amount whenever the frame delta moved (judder around Perfect / Great). A mapper always runs after the tick write, so clamp, counter-scroll and lane scroll share one tick; fades, beam re-bake and the cursor stay in the frame callback. On the JS side, every bind / release appends to a flat Float32Array op buffer (TileFalling.slot-ops.ts) instead of firing its own scheduleOnUI; one applyTileSlotOps hop ships the whole step and bumps slotRevisionSv once, so a dense bar costs 1 dispatch and 1 atlas re-map rather than N+1 of each. Per-frame pose changes (held counter-scroll + core pulse in updateHeldSlotsOnUI, the hit-line clamp) bump a separate slotPoseRevisionSv (soa.poseRevision) that only the body transforms and the beam transforms + CLIP rects read; body sprites and both color buffers stay on slotRevisionSv (+ fadeTickSv), so a held note no longer re-runs every tile mapper each frame. A hold that appears or hides (tail reached) still bumps the structural revision. Body sprites re-read slotIsBlackSv through useRectBuffer on that same revision bump — there is no SharedValue sprite pool or notifyChange on the hot path. Hold-beam RSXform + CLIP are precomputed into a SoA render cache (pinBeamQuadCache) at activate/reuse; beam useRSXformBuffer / useRectBuffer only copy those floats (Smoke-style) and never re-run computeBeamAtlasParts. The auto-play chord path (reuseSlotsBatchOnUI) coalesces the same way at microtask time.

PlayGameCanvas overlay atlas groups. Imperative FX layers inside the unified lane canvas are served by GameplayAtlasSheetProvider, which bakes separate images: the tile master sheet (bakeGameplayMasterAtlas — tile bodies + hold beam only, per maxBeamPx) and one song-independent FX sheet (bakeGameplayFxAtlasCached, 1-entry LRU — effects no longer live in the master, so a per-song beam layout never re-bakes them). Soft-disc FX (gameplay-fx-atlas.ts — tier glow baked at 1× (a smooth gradient upscales losslessly), ONE smoke blob shape lives in its OWN image (smoke-atlas.ts — 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) — 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 orb is NOT in that sheet: held-ember-atlas.ts bakes TWO white soft ovals — a wide halo and a small solid core on the same cell — into its own tiny cached image (bakeHeldEmberAtlasCached, provided by the same GameplayAtlasSheetProvider). 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 applyEmberTint writes RGB to the pool only while it is changing, so a theme transition recolours embers already in the air (no per-tier variant, no per-seed sprite swap). 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; 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). Both the hold column and the tap puff are 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 continuously while it is held (each ember relaunches every flight) and stops launching at its tail / release — 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 (140 embers of a 160-ember slot buffer at alphaGain 1, 90 px flight, rise 150, min apex 0.1, drift 32, vent 24, pinch 0.75, birth 1). 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 scaled down everywhere, so no ember ever upscales and DEFAULT_TAP_EMBER_TUNING (80-ember one-shot puff at alphaGain 104 / 80, rank base 80, 115 px flight, rise 150, min apex 0.035, drift 70, vent 16, pinch 1 = pointed tip, birth 0.4); both fade out with pow 0.6 and shrink to 0.2; 8 slots × 160 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 33 / 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 both keyboard sheets are already in their LRU (Retry, the next part, the same layout), AtlasPianoKeyboard takes them at once (peekKeyboardKeyAtlas / peekKeyboardOverlayAtlas) instead of waiting for an idle task; otherwise it bakes on idle, guarded by the 2.5 s GAMEPLAY_READY_WATCHDOG_MS.
  • 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. While the entrance plays, useTutorialSongPrebake bakes the lane's master atlas on the idle JS queue for the chart's beam (planTutorialSongMasterAtlasBeamPx → computeLaneMaxBeamPx, the helper PlayGameCanvas sizes it with), so the canvas mounts onto a cache hit instead of baking it in its render (~340 ms on device) inside the 0.7 s hold. The keyboard's sheets never bake under the reveal — they did (on the keyboard's first idle slot, in the hold) and the reveal stuttered while they did: a key sheet (~9 MB) and an overlay sheet (~14 MB), each a GPU render, a read-back and a crop. They do not depend on the song: computeAutoFitKeyRange widens any song narrower than MIN_VISIBLE_WHITE_KEYS (10) white keys to exactly 10, and a sheet is cut for the key sizes alone, so every tutorial song asks for one geometry per screen. KeyboardAtlasPrewarm, mounted in app/(onboarding)/_layout.tsx (a first run: the (tutorial) group mounts only once onboarding is over, so a prewarm there landed on the turn to landscape — a ~0.7 s JS stall at Start on the simulator) and in app/(tutorial)/_layout.tsx (a relaunch part-way; a cache hit otherwise), bakes that geometry (planGameplayKeyboardPrewarmGeometry: the window's long side as the strip width, since it runs in portrait behind the splash) one sheet per idle slot, and the splash waits for it (trackLaunchWarmup("keyboard-atlas")) as it does for the judgement labels. The song's keyboard then takes both sheets from the cache (peekKeyboard*Atlas) and reports ready at once. No GPU bake in the background (AppState). A screen whose keyboard is not that geometry (an iPad window that is not full screen) bakes its own, as before. <JudgementAtlasPrewarm /> is also mounted in app/(tutorial)/_layout.tsx, and 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.
  • First-hit rehearsal (loading gate): PlayScreenGameplayGroup's onReady fires once the keyboard bake and GameplayHitRehearsal are done (gameplay-ready-gate.ts). The rehearsal, mounted inside PlayGameCanvas, fires one Perfect tap's effects through the real layer handles under the opaque loading card / song reveal, then clears them, so the first note's GPU pipelines compile there instead of on the first note (device only; see docs/investigations/streak-tier-fps-2026-10.md). Add any new first-hit effect to it, with a clear() on its handle.
  • Effect toggles (Lab, dev only): gameplay-effect-toggles.ts + gameplay-effect-toggles-store.ts switch any Game Mode effect layer (and the first-hit rehearsal) 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).
  • 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; fitKeyboardAtlasSpecs shrinks the scale only if a 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 sheets are ~9 MB / ~14 MB CPU rasters and pure functions of (key geometry, bake scale), so both go through a small LRU (bake-lru.ts, 3 entries) — a replay reuses them; 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 atlas is cached the same way by maxBeamPx (bakeGameplayMasterAtlasCached, 2 entries). 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). Press-travel useFrameCallback starts inactive and sleeps when every key's progress matches its target. 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: synchronous UI-prop updates (iOS)

package.json → reanimated.staticFeatureFlags.IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS = true. With the flag off (Reanimated 4.7 default) every animated style update — even a lone opacity/transform such as the song-progress bar's translateX — goes through a full Fabric shadow-tree commit (cloneShadowTreeWithNewProps → calculateShadowViewMutations → Yoga layout → mount) on the main thread every frame. On the simulator that was 18–36 % of main-thread time during gameplay; with the flag, whitelisted props (opacity, transform, colors, border radii, shadows — see Reanimated's SynchronousPropNames.h) are applied directly (~2–3 %). A static flag: changing it needs pod install + a native rebuild. Android has the matching ANDROID_SYNCHRONOUSLY_UPDATE_UI_PROPS (not enabled / not verified here).

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 × 100 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: stopHold, 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). 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, flight time, drift, vent width (pyramid base), pyramid pinch, size, embers per hold / tap, first wave, fade in / out, shrink. Per-frame fields (rise, curve, drift, 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} (120) so embers-per-hold can go above gameplay's fixed 80-ember slot buffer; gameplay keeps the default. Halo blur (HOLD_EMBER_GLOW_SCALE 4.6, HELD_EMBER_CORE_SHRINK 0.6 in held-ember-atlas.ts) is baked into the atlas and is not a lab knob.

Graphite renderer + benchmark (lab only). The Hold ember lab has a Renderer chip: CANVAS (Atlas) is the gameplay path; GRAPHITE VIEW mounts a SkiaGraphiteView over the lane and passes HoldEmberLayer a graphite sink (HoldEmberLayer.graphite.ts). The sim is unchanged; the UI frame that wrote the live-slot quads records them itself (beginRecording → drawAtlas ×2 → submit) and the layer renders no <Atlas>. Because the view sits over the Canvas, embers draw above the tiles (not between beam and body) and plus blends against a transparent layer, not the lane. The STRESS ×8 note type drops 8-hold chords to keep every slot live; the HUD (EmberBenchReadout.tsx) shows UI fps, worst frame, Graphite record ms and JS stall per second. The Tiles renderer chip does the same for the falling beams + bodies (TileFallingLayer graphite sink, TileFalling.graphite.ts): the SoA is mapped into persistent quad arrays only when a revision / tempo / fade moves, and every tick re-records translate(scroll) → drawAtlas(beams) → drawAtlas(bodies) into a second SkiaGraphiteView stacked under the ember one; the declarative buffer mappers early-out in that mode. In gameplay (EXPO_PUBLIC_GAMEPLAY_GRAPHITE, default on; 0 = Canvas) the lane is split into canvas A (glow … tiles host) → ONE Graphite lane view (lane-graphite.ts: the tile and ember layers publish their quads into a shared state and a single recording per frame draws beams → hold embers → bodies; the Hold ember lab's Single view chip shows it) → canvas B (star rise, light beam, judgement, score, badge, rehearsal), so the order matches the Canvas path (beam < ember < body, HUD on top). Canvas B has its own GameplayAtlasSheetProvider (a Skia canvas does not bridge React context); the sheets come from the bake LRU. Tutorial / Learn never pass graphite.