Working-tree content. Subject to change and not yet released. Commit: e3d4530507.
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'sPlayController+useRhythmEngineto 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
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
Judgementtype, theclassifyHitclassifier, the bitmaskRhythmCursor, and theevaluateTap/sweepMissedGroupsprimitives — live inpackages/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 insideuseMagicJudgement. -
Bitmask cursor over a queue.
RhythmCursorpacks 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?" isclaimedCount[i] === noteCounts[i], and look-up scans run fromheadIdxbounded by the early window. This replaced the legacy set-basedJudgementCursor(lazySet<number>[]over a copied groups list) which churned GC on long songs. -
Best-judgement claim policy.
evaluateTapscans every eligible group containing a note withinMAGIC_NOTE_TOLERANCE_SEMITONESof the pressed key (or — at the current strict default of0— only exact-key matches) AND inside the cursor's group-lookahead window (MAGIC_MAX_GROUPS_AHEAD, which defaults to1— 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 latemissand 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-groupclaimedSet 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 persisteduseHitWindowStore(inhit-window-store.ts) hydrates from on first launch.- Pixel-based bands (signed offset
pof 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 —perfectLategrace 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 Perfect0 < p ≤ min(2, 4)→ Perfect+ (12 pts) — late-side hitline core insideperfectLate-8 ≤ p < -2→ Perfect (10 pts) — early-side Perfect envelope outside Perfect+min(2, 4) < p ≤ 4→ Perfect (10 pts) — remainder of late-sideperfectLategrace4 < p ≤ 4 + greatLate→ Great (7 pts) — optional extra late Great grace (greatLate, ms @ 120 BPM pastperfectLate, default 1/8 = 250 ms,0= off;<TimingPanel>"Great late grace" row, DevToolset_timingsubdivisions.greatLate,0= off). The claim gate and miss sweep both wait untilperfectLate + greatLate(lateClaimTicksin@rhythm/engine).-18 ≤ p < -8→ Great (7 pts) — early-only-33 ≤ p < -18→ Too early (2 pts) — early-onlyp > 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 pathp < -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_BANDStable (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 appliesSTREAK_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 mutableScoreAcc(applyJudgementInPlace/ closed-formapplyPerfectsInPlacefor Perfect runs). Score / badge / theme tables (MULTIPLIER_TIERS,DISPLAY_MULTIPLIER_TIERS,THEME_TIERS,SCORE_MULTIPLIER_FLOORS,nextScoreMultFloor) are derived fromSTREAK_BANDSso retuning tiers cannot drift. Auto-play / note-press batches mutate one preview acc thenapplyScoreSnapshotonce — no second for-loop on commit.@rhythm/enginekeeps a simpler reducer for package tests only. Each tier also drives a full visual color story viaMULTIPLIER_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_MSon the cheap surfaces — the night-sky backgroundu_deep/u_rimSkSL uniforms (per-channelwithTimingviauseAnimatedThemeRgb; the parked energy-gradient backdrop uses the same hook), the hit-line downward glow gradient (peak + fade stops cross-fade viauseTierThemeColor, driven straight off the gameplay tierSharedValueon 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 beamSkPicturerebuild 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 inmultiplier-theme.ts; the two animated-theme hooks live inhooks/useAnimatedTheme.ts. - Keyboard highlight (no React re-render). Next-note wash uses fixed white/black lane accents from
tile-colors(same as<TileFalling>). ImperativesetHighlightNotesonAtlasPianoKeyboardbuilds a plain payload, skips the hop when the highlighted set is unchanged, and applies it with onescheduleOnUI— no React commit and no JS-side.valuereads (a JS.valueget 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-configinteractionBlockedonly). - Tier crossings never re-render the play tree.
GameplayThemeTierProvidermirrorsselectThemeTieronto one SharedValue viauseJudgementStore.subscribe(no ReactsetState). Skia leaves (<TileFalling>,<MultiplierAwareNightSky>, keyboard highlight) read that SharedValue on the UI thread — prefer the SharedValue provider over ReactsetStatefor tier-driven props.MultiplierBadgeLayerdoes not consume the provider — the parent pushestierviabadgeRef.update.
- <a id="multiplier-driven-color-theming"></a>Tier transitions cross-fade over
- Note-pitch tolerance. A tap is "right enough" when the pressed note is within
MAGIC_NOTE_TOLERANCE_SEMITONESof an unclaimed expected note in the candidate group. The current default is2— ±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 to0for 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 insideevaluateTap: best judgement rank, then closest note (exact wins over near-miss), then earliest group. The single source of truth isMAGIC_NOTE_TOLERANCE_SEMITONESinsrc/features/piano/judgement.constants.ts(fed to the engine via thegetNoteTolerancecallback inuseMagicJudgement). - Audible-note substitution. When a near-miss claim happens (only possible while
MAGIC_NOTE_TOLERANCE_SEMITONES > 0),registerTapRefreturns{ audibleNote, claimed: true }with the EXPECTED note number (e.g. 60 / C4) soPlayScreen.onNotePressedcan routesampler.playNoteto 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 innoteSubstitutionsRefonly on claimed taps soonNoteReleasedstops 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_enabledis on, a claimed tap that is early by at most the BPM-scaled quantize window schedulessampler.playNote(..., when)so the voice starts on the matchednoteTimeinstead of at press time. Factory base is 125 ms @ 120 BPM (one sixteenth note); live window isbase × (120 / bpm)viacomputeQuantizeWindowMs— e.g. 375 ms @ 40 BPM, ~166.7 ms @ 90 BPM (15000 / bpmms when base is factory). TimingPanel edits the base (persisted inaudio-quantize-store.ts→getAudioQuantizeBaseMs). On-time / late / too-early-beyond-window / unclaimed taps still play immediately. Gated viaselectAudioQuantizeEnabledat call time inplay-screen-note-input.ts(no React subscription on the hot path).registerTapreturnsnoteTime+tapTickon claims so the host can compute the delay. - Taps further than
MAGIC_NOTE_TOLERANCE_SEMITONESfrom 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.
- Pixel-based bands (signed offset
-
Head-only lookahead (piano-strict sequencing).
MAGIC_MAX_GROUPS_AHEAD(insrc/features/piano/judgement.constants.ts) caps how many falling-tile groups ahead of the cursor head can claim a tap. Default is1— 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 toNumber.POSITIVE_INFINITYto enable "guitar mode" —evaluateTapthen 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 thegetMaxGroupsAheadcallback onuseMagicJudgement(mirrors thegetNoteToleranceshape) and fed intouseRhythmEngine'sMaxGroupsAheadProvider. Auto-pause ALWAYS hard-caps lookahead at1regardless 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'slockSlide(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 inresolveTouchMove(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). WhenAUTO_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-threadtickSvfast path when extrapolation leads the engine tick. The frozen tick often sits a few ticks past the note time (anchor-poll overshoot), soclassifyHitwould normally returnlate— 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 byjudgement-constants-sync.test.ts. Near-missgreatclaims are untouched. HUDisPlayingfromuseMagicGameplay(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 onstateChanged(no React setState); the UI thread readsisRunningSvinsideuseRhythmEngineto freeze tile extrapolation while the engine is paused. -
Press-path stall mitigation. Piano touches are marshalled UI → JS via
scheduleOnRNand invokeplayScreenNotePressed/playScreenNoteReleasedimmediately (no rAF coalesce) so melodyplayNotefires without an extra frame of latency. The keyboard stamps the live gameplay clock (tickSv/judgementTickSv) on the UI-thread gesture edge and forwards it asatTickintoregisterTap/registerRelease, so scoring uses press-time ticks instead of a late JS-threadgetCurrentTick()sample after the hop. On that path, audio + scoring + judgement popups +consumeTile+ decorative tap cues (ripple, particles, shrink, perfect haptic viatap-decorations-defer.ts) stay synchronous; beam press visuals also run in the same JS turn (play-screen-press-visuals.ts— no idle queue, which used to hold the beam up to 300 ms while JS stayed busy); a key lifted right after simply callsbeam.release(), and the beam fades out. A re-hit on a key whose<LightBeamLayer>beam is still fading out re-uses that slot and snaps it back to full opacity.<TileFalling>hides consumed tile bodies immediately via atlasvisible=falsebut defers beam maskSkPicturerebuild to idle (scheduleDeferredBeamRepaint) soconsumeTilestays off the note-press hot path; on tier cross it retints beams via ColorMatrix + atlas sprites fromtierSvand 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 throughrequestIdleCallback(play-screen-keyboard-highlight.ts).<MultiplierBadgeLayer>parks off-canvas until display multiplier ≥ x2, updates label / water fill / scale via SharedValues fromuseJudgementStore.subscribe(no ReactsetStateon hit), takes host visibility through imperativesetVisible()on a ref (never ashowMultiplierBadgeprop), and snaps tier glow colors from JS viaresolveBadgeTierColors+useAnimatedReaction. The rhythm anchor loop skips non-critical miss/hold sweeps when a step exceedsANCHOR_STALL_THRESHOLD_MS(anchor-stall.utils.ts).- Pixel windows (vs. ms) are tempo-invariant by design:
<TileFalling>keeps fall speed constant in px/sec viacomputeTicksPerPixel, so the same Perfect+ / Perfect / Great / Too-early px windows feel identical on every catalog song.useMagicJudgement'sgetWindowscallback multiplies all five px knobs (perfectPlus,perfect,perfectLate,great,early) byticksPerPixelonce per call anduseRhythmEnginepasses the tick-based windows intoevaluateTap/sweepMissedGroups— both honor the late-Perfect grace, so a tap right at the deadline never races the sweep into a duplicate Miss popup.
- Pixel windows (vs. ms) are tempo-invariant by design:
-
Live calibration.
useMagicJudgement.getWindowsreads the current pixel windows viagetJudgementWindowsPx()(inhit-window-state.ts) on every tap and frame-callback miss-sweep — a module-level holder updated byuseHitWindowStoreon every slider drag. The state file is React-and-MMKV-free so test runtimes (bun:test, which can't loadreact-native-mmkv) canimportit without the persisted store entering the import graph. The store lives inhit-window-store.ts, persists{ perfectPlus, perfect, perfectLate, great, early }under MMKV keypiano-hit-window-ms, and is eagerly loaded fromcore/entrySetup.tsso the calibrated values are live before the player ever taps. Older persisted blobs withoutperfectPlus/perfectLatepick 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 calluseJudgementStore(...)— writers usegetState().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 byuseGameplayHudBridge(one parentsubscribe→scoreRef.setScore/badgeRef.update) — the Skia leaves themselves never subscribe. Night-sky / tiles still mirror theme tier viaGameplayThemeTierProvider(subscribe→ SharedValue). Judgement feedback is split across surfaces driven imperatively fromuseMagicJudgement: per-tile<JudgementPopupLayer>(+points), central<CenterJudgementLayer>.fire(judgement, combo), and badge water-fill / label / tier from the parent bridge viacomputeMultiplierProgress. Chord misses callapplyMissesBatch(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). -
useMagicGameplayload-path React state is onlyisReady+error. The parsedChartandPlayControllerlive in refs (chartRef/controllerRef); the SoundFont sampler is loaded withuseSoundFontSampler({ reactive: false })and awaited viawhenReady()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 intouseStateon the play path. Imperative paths (pause, game-overtotalChartGroups) readcontrollerRef.current. -
useMagicJudgementbuilds theRhythmCursor(lazily, insideuseRhythmEngine) fromcontroller.engine.notes, anchors a JS-side miss-sweep step driven bycontroller.tickFrame()on every song-sequencer pulse (sampler.createClockPump()— the audio-threadAudioPositionPumpon RNA, the nativeonClockPulseon the iOS engine; nosetInterval), and exposes a stableregisterTapRefPlayScreen calls insideonNotePressed. Cursor mutations stay on the JS thread in a ref only (cursorRef— no ReactsetStateon arm); the UI thread only readstickSv+headIdxSv. UI-frameuseFrameCallback.setActivefollowsGameStateMachine.isPlaying()viastateChanged, 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'sTransport(AudioTickClock) via the shared clock channel) at the gesture edge and pass that tick intoregisterTap/registerReleasewhile the engine is running. Auto-pause wait ignores the gesture stamp and judges against the frozen audiopausedTick— a leadingtickSvpastresumeLatewould otherwise makeevaluateTapskip 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>'sconsumeTile(noteNumber, noteTime, currentTick), which publishes the note asCONSUMEDin the lane's note status table; the UI runtime then hides the body and frees its slot for the next in-window note. There is no separate exit overlay — hit feedback is the ripple / particles / smoke / popups. Miss never consumes early so missed tiles keep falling and the player can see what they whiffed. -
Tap vs hold.
isHoldNote(noteLength, ticksPerBeat, ticksPerSecond)inhold.tsis the single classifier for the cursor, the tile layout (isHoldTile) andChartJson.type_note. A note is a hold only when it is longer than half a beat and lasts at leastHOLD_MIN_SECONDS(≈ 0.333 s = a 20 px tail past the 30 px body at 150 px/s), so every hold shows a visible beam. Shorter notes play as taps; their sound is unchanged (the sampler still plays the MIDI length), only the tile and the hold haptic differ. The floor only matters above 90 BPM. -
Hold heads defer overlay/haptic (
HOLD_VISUAL_ARM_MS= 120 ms). A hold head press fires popup / ripple cues immediately and a Perfect head's body is pinned at the press (pinHoldAtPress→tileRef.pinHold()at the press tick): it stops where it stood — above the hit line on an early press — and its tail drains from that moment. The ember field, flare column, and continuous hold haptic arm only after the finger stays down for 120 ms — but the ember field counts its launches from the press (PressPin.pressTick→emberRef.start(…, pressTick)), so at the arm the first 120 ms of embers are already in the air and a short hold does not lose them to the arm delay (lineup pick S1, 2026-10-29) (armHoldreuses 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 Perfecttapgame 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 (clampFallingSlotsAtHitLineOnUIinTileFalling.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>viatileRef.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 withtickSv. After arm,useMagicJudgementalso callsemberRef.start()on the siblingHoldEmberLayermounted between beam and body (betweenBeamAndBody). Keyboard release callstileRef.releaseHold()+emberRef.release()in parallel withregisterReleaseRef(scoring only); the UI thread hides held slots whentickSvreaches 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 lastbodyHeightpx of fall are invisible. The engine therefore completes a hold (sweepHoldCompletions/evaluateHoldRelease/ auto-pause) atnoteTime + noteLength - holdTailInset - 10 % × (noteLength - holdTailInset)— the lastHOLD_COMPLETE_TAIL_FRACTION(10 %) of the visible tail is forgiven so a one-finger player can lift before the next note reaches the line (effectiveHoldEndinhold.ts), whereholdTailInset = bodyHeightPx × ticksPerPixelis supplied byuseMagicJudgementthroughJudgementWindowsTicks.holdTailInset; the UI uses the same tick viaeffectiveHoldTailTickinHeldTile.utils.ts(a test asserts parity). A hold no longer than the core gives up only 10 % of its own length.onHoldCompletecallsHaptics.stopHold()only for a hold that armed (startHoldis ref-counted). Gameplay haptics (tap,holdComplete,miss, the hold rumble viaHaptics.startGameHold()) are configured bygameplay-config.tsand 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'spin; the hit line only when no pin is known).useRhythmEnginemirrors onlyheadIdxSv(judgement cursor); hold tail timing stays on TileFalling held slots + HoldEmber per-slot fields. Auto-pause freezes on the JS anchor loop — no headnoteTimeSharedValue in the engine hook. -
Progressive hold rumble. On arm,
startHoldHapticpasses the tail's real-ms length (press pin tick →effectiveHoldTailTick, atticksPerSecond × m) and the time already held toHaptics.startGameHold(noteNumber, holdDurationMs, elapsedMs)(holdHapticTiming): the rumble starts athold.startGain×hold.amplitudeand ramps linearly tohold.amplitudeover the firsthold.rampFractionof the tail, then holds at the max. Every armed-hold end callsHaptics.stopGameHold(noteNumber); a resume after pause restarts it from the song-time elapsed, so the ramp continues instead of starting light again. Tunable in the DevTool Haptics tab. -
learnmode is unchanged (un-judged, no popups, no scoring, no dissolves). The same<PlayScreen>handles both modes — gating isplayMode === "play"around the judgement hook + HUD overlays + dissolve overlay.
Pre-roll countdown + session lifecycle
PlayScreen is session-scoped: every visit to the screen is a fresh play attempt, so the judgement store is reset on mount, on unmount, AND inside the back / retry handlers — a stale "game over" overlay from the previous attempt MUST NOT flash on screen when the player re-enters, and the dismissal animation MUST NOT slide out with the summary still visible.
Segmented songs (free tier). Part boundaries come from the cached catalog — sheet Section 1/2/3 URLs (one .mid per part) or legacy time-based segments in songs.json — not from the MIDI marker track at runtime (buildSongSegmentPlan ignores marker notes; see parse-song-segment-plan.ts). A song is segmented only when the catalog declares ≥ 2 parts (catalog-segmentation.ts). On game over, PlayScreen checks whether the full song was already unlocked before this run (read from progress before markPartCompleted). If yes — or the run was full-song mode — PlayResultScreen shows SessionResultOverlay (stars + recommended next songs). Otherwise it shows SectionCompleteOverlay (parts progress bar): middle parts include Next section; clearing the final part (which silently sets fullSongUnlocked) shows Replay and Back to list only. All result UIs render embedded on /(app)/play-result (no Modal). Re-entering play without ?segment= resumes on nextPlayablePart until every part is cleared, then auto-starts the full song. Explicit ?segment=N or Replay still replays a single part. If the sheet drops Section columns, pull-to-refresh so MMKV picks up the new catalog; unlock progress for that song is reset automatically when segmentation is removed.
Logic stars (session result only). The three-star badge on SessionResultOverlay uses Perfect Rate = (perfect + perfectPlus) / totalChartGroups, where totalChartGroups is the falling-tile group count in the played chart (controller.engine.notes.length at game over — clipped when a segment playRangeSec is active). Perfect+ is the same tier as Perfect for stars (HUD label only); Great / Late / Too Early / Miss do not count toward the numerator. Thresholds (inclusive): ≥ 90% → 3★, ≥ 70% → 2.5★, ≥ 50% → 2★, ≥ 30% → 1.5★, ≥ 15% → 1★, else 0★. Pure math lives in ResultStarBadge.utils.ts (totalPerfectTierHits, computeLogicStarsFromCounts). Section-complete overlays never show logic stars. The tutorial Congrats result uses the song thumbnail (SongRevealCover) instead of a star badge; computeAccuracyStarsFromCounts remains available for other accuracy-based surfaces.
To make space for the reset and to give the player a beat to scan the lane before tiles start falling, useMagicGameplay accepts startPaused: true — it builds the PlayController + audio chain but leaves the tick clock and rhythm-track scheduler inert until the caller invokes the returned start() action. The 3 → 2 → 1 → "go" → null state machine (nextCountdownFrame in countdown.constants.ts) lives inside <CountdownOverlay>: PlayScreen only hands it a readySv SharedValue (true once isReady) and receives a single onComplete callback at the end. Keeping the per-frame work inside the overlay — in SharedValues, not setState — keeps the heavy gameplay tree (<TileFalling>, <AtlasPianoKeyboard>, <JudgementPopup>, <TileDissolveEffect>) untouched while "3 / 2 / 1 / GO!" plays — the parent body re-renders exactly once for the entire pre-roll instead of once per frame, and the overlay's own tree renders zero times after mount (every flag it reads is a SharedValue). On the final "go" → null transition the overlay invokes onComplete, which calls start() so the engine begins ticking exactly as the overlay clears. <PlayScreenHudOverlayGroup> mounts with the gameplay tree (canMountGameplay) — not after preRollComplete — but the header chrome (play/pause, timing toggle, score) and <PlayScreenSongProgressRail> stay hidden until preRollComplete flips true on onComplete. The overlay's scrim is pointerEvents="auto" so taps during the pre-roll don't fire judgements / wake the sampler.
<CountdownOverlay> owns the loading card framing — while the pre-roll has not started it renders the bundled prepare-art background with "Unlock all songs" + gradient "VIP BENEFITS" headline (Figma 7411:79764). The song progress rail at the top of the lane (PlayScreenSongProgressRail in PlayScreen/SongProgressRail.tsx, wrapping GameplayHeaderBackground) mounts with the gameplay tree but stays hidden through load + countdown; it appears when the pre-roll completes alongside the rest of the HUD chrome. The pre-roll state machine (loading → countdown → hidden, or dismissing for skipCountdown) lives in useCountdownPreRoll and runs entirely on the UI thread — no useState, no effects, no timers. Its inputs are SharedValues: readySv (useBooleanSharedValue(prepareReady) in the owner), armedSv (the tutorial's countdownArmed) and the route's entered flag (PlayScreenEnteredContext now carries a SharedValue<boolean> made once in PlayScreen/index.tsx), so a flag flip re-renders neither PrepareAssetGroup nor CountdownOverlay. One useAnimatedReaction turns them into a preRollTarget (pure worklet in CountdownOverlay.utils.ts: wait / ready / run / dismiss) and acts once per change: cross-fade the prepare card out and the Get ready! card in (withTiming, PREPARE_OVERLAY_FADE_MS), start the clock, or — skipCountdown — fade the prepare card out and finish from the fade's own completion callback. The 3-2-1 is one linear clock SharedValue (clockSv, GAME_COUNTDOWN_RUN_MS); frameSv = preRollStepAt(clockSv) (countdown.constants.ts) is the glyph column's row, and a second reaction on it plays the tick, or GO!'s own sound (a module-stable scheduleOnRN(playCountdownBeep, step === PRE_ROLL_STEP_GO)), flips the hidden phase code at GO and calls finish at PRE_ROLL_STEP_DONE. The overlay root's pointerEvents / accessibility props follow phaseSv through useAnimatedProps (countdownOverlayRootProps, a worklet); only the loading phase takes touches. CountdownOverlay renders a memoised CountdownOverlayView whose props never change, so no React tree renders while the pre-roll plays. The prepare card is never unmounted either — PianoKeysLoader gets an activeSv and stops its loop on the UI thread once the card has faded out. onComplete reaches JS through a stable callback id (useStableJsCallbackId + invokeStableJsCallback), so a new callback identity can never restart the countdown. The Get ready! card appears as soon as the song is ready (armed or not) and the digits start once armed. The route's screenEntered reaches the overlay through that context, never as a PlayScreenBody prop: the flip rides the stack's transitionEnd navigation commit and, as a prop, re-rendered the whole body, so "3" never runs under the route fade; the tutorial song arms it when its reveal hands over. With that gate there is no hold left (COUNTDOWN_PREPARE_TO_START_DELAY_MS = 0; the clock starts at -delay); each digit holds GAME_COUNTDOWN_TICK_MS (800 ms) and "GO!" GAME_COUNTDOWN_GO_HOLD_MS (800 ms) — GAME_COUNTDOWN_TOTAL_MS = 3.2 s: DEV's prototype's 0.8 s digits (26/11/2026; it was 550 / 350 ms = 2 s), GO! held 0.8 s rather than its 0.75 s, room for the keyboard's GO! light (DEV, 27/11/2026). The glyph (CountdownGlyphOverlay, motion in countdown-glyph.motion.ts) plays the prototype's curves on its own clock from each row: a digit drops in from 1.6× with an overshoot, holds and shrinks to 0.7 as it fades, gone by 0.75 s; "GO!" drops in from 1.8× and swells to 1.06 while it holds, in a blue glow (two stacked texts, countdownGoGlowNear / countdownGoGlowFar). 132 pt on a 150 pt line, tracked −2, Nunito ExtraBold (the prototype's 900 is not shipped); each glyph's own Text carries 48 pt of padding as glow room — iOS draws a text shadow only inside the Text's box, and a box hugging the letters cut GO!'s glow into a rectangle (DEV, 27/11/2026). "Get ready!" is 22 pt / 800 (29 pt on tablet), drops 10 pt into place with an overshoot as its card shows, and fades out from 0.1 s before GO! to 0.15 s after; the cover disc stays (getReadyAt, GET_READY_MOTION). The keyboard's GO! light (DEV's prototype, 26/11/2026; slowed and brightened, and the keyboard's slide-up dropped, 27/11/2026 — Game Mode and the tutorial song, which provide the pre-roll's clock through KeyboardIntroProvider; useCountdownPreRoll runs that clock, the keyboard reads it; free-play, Learn and the labs have no provider and stay dark): as "GO!" shows, a blue light (#4FA8FF) comes up the white keys from the middle key out, reaching the outermost keys 0.25 s later whatever the keyboard's width — each flares in 0.13 s, holds full to 0.32 s and settles to 0.35 by 0.58 s — and all of it goes out over the last 0.13 s of GO!'s 0.8 s hold, before the song's first frames. Motion in keyboard-intro.motion.ts. How it is drawn: two more instances per white key (resting / pressed, crossfaded by press like the washes) from a white light sprite baked into the keyboard sheet per notch variant (8 cells; alpha 0.08 at the top, 0.7 at 55 %, full at the foot) with its colour multiplied in per key — another colour (per difficulty, say) bakes nothing more. The keyboard's frame step (AtlasPianoKeyboardLayers) wakes every key only while the light plays, then writes them once dark and lets them sleep. No new layer, sheet, texture or shader in Game Mode: the light rides the key sheet uploaded before the loading card lifts, so there is nothing to prewarm (preRollStepAt walks the same frames as nextCountdownFrame, GO holding shorter than a digit). The 1.04 s tick (countdown_tick) keeps 4 voices; GO! plays countdown_go. Learn Mode's stage pre-roll uses the same 3.2 s cadence (PRE_ROLL_CADENCE in learn-countdown.model.ts) and also waits for its keyboard bake (countdownShows → keyboardReady); its challenge count-in keeps the music's 1 s beat (COUNT_IN_CADENCE). The loading→"3" transition is a card swap (prepare card fades out while the countdown scrim fades in) so the first digit pulses in as deliberate punctuation. Pass skipCountdown (via <PlayScreenPrepareAssetGroup skipCountdown>) to dismiss prepare as soon as the song is ready and fire onComplete with no digit sequence — used by tutorial practice training (TutorialPracticeSurface). The overlay is suppressed on the terminal error path (error !== null) so the error card has the surface to itself. Nothing unmounts or re-renders the gameplay tree at the end of the pre-roll: judgement and the rhythm engine are enabled with the prepared screen (enabled: prepareReady, before "3"), so GO has no state to flip; onCountdownComplete reveals the HUD imperatively and calls start() directly (AUTO play, a QA switch, is the one exception: it mounts its driver first, then starts from an effect). The overlay itself is never unmounted — finish() (a worklet) sets its root opacity to 0 and slides it off screen (COUNTDOWN_OVERLAY_OFFSCREEN_X), both UI-thread style writes; the accessibility flip (hidden phase code) is written at GO, a beat before the song starts, never at its first frame — and GameplayHeaderBar seeds its play/pause mirror as "playing" while countdownActiveRef is up, so start()'s transport emit is a same-value setState (no render).
The Skia rendering composition (AtlasPianoKeyboard + TileFalling + HitEffect + lane-geometry) is documented in .cursor/skills/piano-simulation-screen/SKILL.md.
<TileFalling> UI-owned slot pool + note status table. Chart notes are converted once at song/layout load into a sorted flat SharedTileLayout[] via buildTileSharedLayout (precomputed lane geometry + appearAtTick / resolveByTick windows). JS keeps that layout (binary search, and the geometry consumeTile returns synchronously for FX) and copies it once to the UI runtime as the immutable column set TileChartSoA. The UI runtime owns the whole slot lifecycle in tile-pool.worklet.ts: the beam system's beforeUpdate runs reconcileTiles every frame — advanceTileCursorWorklet slides the startIndex..endIndex window over the chart columns (same pattern as leap-sim-guitar's SharedNotesCursor, in tick space), culled slots retire, new in-window notes bind to free slots (free stacks + chart ↔ slot maps are plain typed arrays, no JS mirror), and nothing hops back to JS — a stalled JS thread cannot make a tile appear late. Judgement only says what happened to a note. It publishes a status per chart index into tile-note-status.ts — FALLING / CONSUMED / HOLDING / ENDING_FADE / ENDED, plus the press tick + tempo of a hold per note number. The entries travel through a status ring of lock-free Worklets Synchronizable number cells (tile-note-status-cells.ts: head, tail and 64 slots, in-process fallback on web / tests): each change is ONE number (((chartId·2²⁰ + chartIndex)·8 + status)·2, or a press payload (tick·100, m·1000, note) sent just before its HOLDING), written into the slot BEFORE head moves, so an entry is never torn and nothing is cloned or serialized per change. JS is the single producer and never drops: a full ring keeps the rest queued and retries about a frame later (the UI publishes tail after draining). The UI runtime drains the ring every frame in reconcileTiles and keeps the per-note table itself (noteStatus, pressTick / pressM); entries of an older chart are skipped, an entry of a newer chart (and the press before it) waits for the pool rebuilt for it. Each entry moves its slot to the note's status: CONSUMED frees the slot, HOLDING pins the body where it was pressed (pose derived from the press payload — pinSlot fixes the press Y, the body system derives the rest each frame), ENDING_FADE starts the release fade, ENDED hides at once — and the UI frees the slot / beam itself, including when the fade ends. After a drain that changed anything every bound slot is re-anchored once. Judgement itself stays on JS: it also drives audio, score, haptics and stores, so running it off-thread would not remove the hop. The lane also reads the engine's flat game-state block (GAME_STATE: tick, rate, epoch, stamp, isRunning) from a Worklets Shareable hosted on the UI runtime. The TileFallingHandle API (consumeTile / pinHold / releaseHold) is unchanged; it now only writes statuses. Body/beam sprite regions are a lifetime-fixed object pool (sized once at mount from chart peak, or from poolCapacity / beamTileCapacity props — practice uses SINGLE_NOTE_TILE_POOL_CAPACITY); slots stay idle or active and never resize when the note list toggles. Per-frame motion is the sprite systems' update (chart + status + tick, see Frame order), so active falling bodies never draw below the receptor and held bodies stay screen-anchored without any stored geometry. Judgement stays on @rhythm/engine's separate headIdxSv / RhythmCursor. See TileFalling.tsx, TileFalling.step.ts, tile-pool.worklet.ts, TileFalling.utils.ts.
Frame order (sprite systems). The lane is two ordinary sprite layers — hold beams, then (after the hold embers) tile bodies — each a useSpriteSystem in TileFalling.tsx; it has no surface, no mapper and no scroll uniform. The beam system's beforeUpdate runs reconcileTiles once per frame (registration order puts it before the body system). Each bound slot carries its own motion (tile-pool.worklet.ts): headY (body bottom), headEndY (the hit line, or the press Y of a pinned hold), headV, tailY (beam top, keeps falling after the head parks / pins and drains a hold's beam) and tailV, in screen px and px/s; size and x stay in the immutable chart columns. A frame does y += v · dt (dt = the FX clock's delta, clamped to 250 ms) and clamps the head at its end — no pose is recomputed from the tick, so the audio anchor, its slew and the engine's frame order never move a tile. reconcileTiles then slides the cursor (the only per-frame use of the tick), retires culled and fully-faded slots, drains the status ring (each judgement change is one lock-free ring entry; the pool keeps its own per-note table, see tile-note-status.ts) and binds the notes that entered the window. A bound slot is queued (bodyWake / beamWake) only once it can be seen — its head within TILE_WAKE_MARGIN_PX of the lane's top edge, or a pinned / fading hold; until then the pool keeps integrating its motion but the systems neither write nor upload it (wakeVisibleSlots). Each system wakes its own in beforeUpdate; a retired slot needs no counterpart — its update finds it unbound and the system hides and sleeps it. Each awake slot's update(slot, now, w) (TileFalling.step.ts) only draws what the pool moved: the body at headY − bodyHeight; a HOLDING / ENDING_FADE tile adds the halo + pulsing core (the pulse / buzz still reads tick − noteTime, cosmetic) and its beam runs from tailY to headY until the tail has drained into the body; the release fade is holdReleaseFadeAlpha(now, fadeStart). A hold parked at the hit line (adaptive-tempo wait) has lane rate = 0, so nothing moves, yet the pool still reconciles every frame, so a tap frees its tile. The sprite systems run on the shared FX frame, which the provider skips while the pause panel freezes the lane. What the engine tells the tiles (one flat Float64Array game-state block, driver/game-state.ts, hosted on the UI runtime as a worklets Shareable and returned by useRhythmEngine().gameState / useMagicJudgement().gameState and provided to the lane layers by the screen through GameStateContext (useGameStateCell()); the frame callback is its single writer, positional writeGameState, no per-frame object; labs have none and follow tickSv): isRunning, tick, rate (ticks/ms the lane advanced over the last frame, slew and tempo curve included, 0 while paused / held / stalled), epoch (bumped whenever the tick was ASSIGNED rather than integrated: seed on start / resume / seek, catch-up snap, a write from outside the frame such as the rewind slide or a song swap, and the edge where the lane stops) and stamp (the frame that wrote the block). Tile speed is rate · 1000 / (ticksPerPixel · m) px/s; a rate read one frame late is off by the change of the rate over one frame, not by a frame of position. Re-anchoring (closed form (chartY + tick / tpp) / m + hitLineY): when a note is bound, when a status entry is drained (any tap wipes the error free-running tiles collected), and when epoch moves. Tempo change: (y − hitLineY) · m is invariant, so every unpinned head and every tail is rescaled by m_old / m_new and the speeds re-derived — no tick read; a pinned head is a screen position and stays. Tick freshness. The FX frame callback runs before the engine's tick writer (re-activated on every resume), so the raw tickSv is one frame old; the pool adds rate · dt to it once, when stamp differs from the FX frame's timestamp (useGameplayFxFrameStamp), and only for anchoring and the cursor. A lane that stands still (rate = 0) while its tick moves — labs with no publisher, the paused rewind slide — is followed: the pool re-anchors every tile to the new tick. The engine frame callback is switched off while the song is paused, so it can never report the stop itself: the pause freeze (freezeLaneDisplayTick → freezeGameState) writes isRunning = 0, rate = 0 and bumps epoch.
Lane render-target bounds. Play and tutorial song gameplay pass the actual keyboard top into PlayGameCanvas. Both lane targets end 12 logical px below that edge (computePlayScreenLaneSurfaceHeight), trimming the area hidden behind the keyboard. The hit line keeps its original lane coordinates. The keyboard portal uses its own strip-sized target. The outer Skia canvas retains the wave bleed and keyboard area.
PlayGameCanvas overlay atlas groups. Imperative FX layers inside the unified lane canvas are served by GameplayAtlasSheetProvider, which resolves the layouts of two sheets: the tile master sheet (getGameplayMasterAtlas — tile bodies + the hold-beam column; per song only "beams or not" varies. Each body cell is packed at its content extent, not the full glow-pad cell: the halo / full sprites at TILE_BODY_HALO_SCALE × the body, the core-only sprite at the body circle (tileBodyCellPx), centred in the cell, and computeTileBodyAtlasTransform takes the packed width (spriteW) to shift the quad by the trimmed margin so the body centre does not move. The sprite engine packs every texture through packSpriteTexture (src/core/sprite-engine/atlas-layout.ts), preferring a compact shape within a shared 10% area budget; a texture may set optimize: false to retain minimum-area layout) and one song-independent, mipmapped FX sheet (getGameplayFxAtlas — FX discs, smoke cells and hold-ember ovals in ONE image; backdrop clouds, smoke and embers are packed at their cropped size, and neighbours sit the engine's SPRITE_ATLAS_GAP_PX × the sheet's bake ratio apart — no per-sheet gutter; layers read each frame's cell / bakeScale from useSpriteSource). Both — and the light-beam columns — are keyed bake sources (SpriteAtlasBakeSource): the WebGPU planes bake them on upload and free the raster, so no CPU copy sits next to the GPU texture (kept warm on the GPU for Replay / Next; see the engine README). Soft-disc FX (gameplay-fx-atlas.ts — tier glow baked at 1× (a smooth gradient upscales losslessly), the smoke blob cells are FX-sheet cells (smoke-atlas.ts buildSmokeAtlasSpecs — a 96 × 48 cell on phone, 144 × 72 on iPad — each baked for that device's largest puff so it always minifies, never upscales; the halo/core rects are centre-cropped to the blob's bounding box (smokeSpriteCropPx, ~19 % less fill, same pixels); aspect 0.44): a wide white HALO cell plus a small solid white CORE cell, no per-tier variants. SmokeParticleLayer draws two <Atlas> nodes over the SAME transforms — the halo tinted per particle at fire time from fxTierTintTable (the x2…x6 bgAccentRgb; the middle centre-flash puffs stay white), the core with white colors (alpha mirrored)), the StarRise orb (star-rise-orb-atlas.ts — the starRiseOrb FX cell, a solid white disc used as each orb's core; the halo reuses the tapTierGlow soft disc), tile bodies (full / halo / core × 2 lanes — full keeps a falling tile at one quad), and ONE white hold-beam column tinted per lane through the beam color buffer (BEAM_LANE_RGB; a short cap + flat-shaft bake — a longer beam draws the cap 1:1 and stretches the flat shaft on the GPU, writeInstanceStretch, so the texture no longer grows with the song's longest hold) — the last two (tile bodies, beam) are the master sheet. No Figma glyph is baked — no gameplay layer samples one (the note / sparkle / star shapes stay path-only in sparticle-paths.ts for Learn). The hold-ember ovals are FX-sheet cells too: held-ember-atlas.ts contributes TWO white soft ovals — a wide halo and a small solid core of the same size (buildHeldEmberAtlasSpecs, each clipped to its cell). HoldEmberLayer draws two <Atlas> nodes over the SAME transforms: the halo tinted live through its color buffer (colorBlendMode="modulate"; useGameplayFxTierTintRgb cross-fades the x1…x6 tint, fxTierEmberTintTable, pure accent) and the core with white colors (only its alpha mirrors the halo's, so it never changes hue) and the halo is drawn with the live tint on every write (emberTintChanged only forces a rewrite while the tint moves), so a theme transition recolours embers already in the air (no per-tier variant, no per-seed sprite swap). Since 2026-11-03 the layer is data-driven like the tile lane: settleEmberSlots decides which slots are drawn, then each awake slot's update runs writeEmberSlotSprites, which evaluates every ember once and putSprites its halo + core straight into the plane — no Skia quad store, no host objects (each one is a JSI hop per property read on the UI runtime; the old copy cost ~3 ms/frame per hold on a device trace). Layers read slices through useGameplayFxAtlas / useGameplayHeldEmberAtlas / useGameplaySmokeAtlas / useGameplayTileAtlas. A new sprite needs no warmup of its own beyond its sheet: it is a source rect in an already-baked texture, and the GPU program depends on the layer's <Atlas> paint (modulate + FX_ATLAS_SAMPLING), which GameplayGlowLayer's mount warmup draws under the prepare scrim — that first draw also uploads the sheet with its mips. It does not cover a plus blend (blend state is part of the Metal pipeline) or another texture, so three layers prewarm themselves for 30 UI frames under the prepare scrim — otherwise each compiled or uploaded on the first note: HoldEmberLayer shows one 2/255 quad (HOLD_EMBER_PREWARM_*, the only plus Atlas — the first Perfect tap fires its puff), LightBeamLayer draws a prewarm plus gradient Rect at 1/255 then opaque 1 px wide (LIGHT_BEAM_PREWARM_* — Skia picks a second program at opacity 1), and CenterJudgementLayer / JudgementPopupLayer draw one 2/255 glyph quad so their own atlas textures upload (judgement-atlas-prewarm.ts). Game Mode's song_start analytics also waits for the idle queue (scheduleSongStartOnce in play-screen-note-input.ts; the playtime clock is still stamped at the press). Tile hit burst — SparticleLayer replaces the old hit ring: on a judged hit the falling tile frees its slot immediately and the layer draws the tile's own baked outer halo (scales 1 → 1.25, holds opacity for 30 % then fades) and core (scales 1 → 0.3 while fading) from the master atlas tile-body slices, over HIT_BURST_LIFE_MS = 280 / 1.35 ≈ 207 ms (faster than the hold ember) — 2 quads × 5 burst slots in one <Atlas>, fired via spawnRef.current.fire(...). It samples the raw FX clock every UI frame while live (no cadence throttle); once the last burst ends it flushes once and goes idle, so the three buffer mappers stop re-running between hits. Perfect-head holds fire their one burst at the hold end, centered on the held body at the hit line; that release skips the hold fade (releaseHold without fadeOut also cuts a fade the finger-lift already started) so the burst takes over on the same frame. Auto-pause completes (not breaks) an active hold whose tail is within the perfectLate grace, so a next note starting at the tail no longer swallows the burst + holdComplete haptic. SmokeParticleLayer uses an effect-slot pool (fixed concurrent bursts × capped sprites; analytic FX-clock life — a burst fired after the quantized render clock has negative progress for a frame and is kept, not freed — see .cursor/skills/effect-slot-atlas-pool/SKILL.md). Every tier shares SMOKE_SHARED_TIER_CONFIG in SmokeParticles.utils.ts (puff count, radius, reach and life live there; edge puffs run on 90 % of the life); the middle two puffs draw the all-white x1 cell for ~110 ms as the one white flash at the hit point. SmokeWaveLayer (x3+) is a 6 px wave (130 px humps, 25 px gaps, speed 0.6 ≈ 103 px/s outward; iPad scales the geometry ×1.25 via SMOKE_WAVE_DEFAULT_TABLET — it's a shader, so nothing is baked) whose humps each take a stable random 60–100 % height, tinted with the tier color mixed 45 % toward white at alpha 0.65. It ramps per tier (SMOKE_WAVE_TIER_SCALE): x3 as authored, x4 ×1.15 hump height / ×1.15 speed, x5 ×1.25 / ×1.3 (6 → 6.9 → 7.5 px on phone). Height only (the wavelength stays fixed) and eased with the tier tint; the phase is accumulated (advanceSmokeWavePhase) so a speed change never makes the humps jump. The band rect is sized for the x5 height, so tiers only change shader uniforms — never the GPU program. Its mount warmup draws the real band at 1/255 for 30 FX frames (SMOKE_WAVE_PREWARM_HOLD_FRAMES). Hold pin (beam + body counter-scroll) is owned by TileFallingLayer via pinHold / releaseHold; HoldEmberLayer is a GameCanvas sibling injected through betweenBeamAndBody (tick-analytic field of soft upright ovals (HELD_EMBER_OVAL_ASPECT 0.84) — 6 / 7 px embers drawn as a 4.6× quad whose baked solid core is only HELD_EMBER_CORE_SHRINK (42 %) of that diameter, so most of the sprite is wide soft halo; the white core's cell is baked cropped to its own extent (HELD_EMBER_CORE_EXTENT of the radius, in held-ember-crop.ts) — a small dot, not the halo's footprint — and writeHaloCoreInstances is given the half-size gap (coreDx / coreDy) to centre it on the halo, they rise from the hit line on an ease-out curve (riseCurvePow 2.5) up to 150 px, fading to 0 at their peak and never falling back, and shrink while fading (fadeOutScale 0.2 on the same p^fadeOutPow curve). The phone hold field is a funnel (lineup pick "D · Phễu loe", 2026-10-29): a negative pyramidPinch (−1.4, raised from −0.8) inverts the pyramid, so the field starts as narrow as its 16 px vent at the hit line and flares to 2.4× its offsets at the full rise (taper = 1 − pinch · climb / risePx, unclamped above 1), with a small 6 px drift, apexes from 0.3 of the rise skewed low (riseSkew 2) and no lean. Two more shape knobs stay available in the lab: leanStart / leanDeg (past that share of its apex an ember tilts outward on its own side up to that angle, tied to the climb so it never turns flat or goes down) and riseSkew (apex = risePx · (min + (1 − min) · spawnPhase^riseSkew)). The iPad hold uses the same funnel shape with its own sizes; tap puffs keep lean off and riseSkew 1. With a positive pinch the field is a pyramid: every ember launches straight up and its sideways offset from the vent axis (launch spot + drift) is scaled by max(0, 1 − pyramidPinch · climb / risePx), so the field is the full vent + drift wide low down (columnWidthPx = the base, capped at 1.5× the note) and narrows toward the top. There are no tilted side embers any more — the pyramid replaces them. A hold field streams embers at a constant rate while it is held and stops launching at its tail / release: every ember relaunches on ONE shared cadence (resolveEmberCadencePx = the longest jittered flight, periodPx × 1.06) and the first wave is spread over that same cadence, so launches sit on an even grid — N / cadence embers per px. The density is set directly as holdRatePerSec — embers launched per second held at 1× speed (phone 300 / s, iPad 160 / s; quoted at EMBER_RATE_FALL_PX_PER_SECOND 150 = the lane's default fall speed, so it scales with tempo like every ember timing) — and the field seeds round(rate × cadence / 150) embers (resolveHoldEmberCount, clamped to the slot buffer: a clamped field launches fewer per second than asked), so changing the rate never changes the flight, a hold of any length launches embers in proportion to how long it is held, and there is no thin patch when the first wave hands over to the relaunches (before 2026-10-29 each ember relaunched on its own jittered flight time, so after the first wave launches bunched into 5–18 per 10 px). Only the flight length is still jittered (≤ the cadence), so heights and fades vary without bunching the launches — the embers already in the air finish their rise. A hold that ends very soon after its press is simply cut off (no minimum wave). Holds and tap puffs have separate tunings — DEFAULT_HOLD_EMBER_TUNING (phone, lab pick 2026-10-29 in the lineup's funnel shape: 300 embers / s = 244 embers filling the 244-ember slot buffer, alphaGain 1.4, 6 / 7 px, 115 px flight, rise 180, min apex 0.3 with riseSkew 2, curve 3.5, riseCarry 0.15, drift 6 steady, vent 16, pinch −1.4 (funnel), lean off, birth 1, fade out 0.6, shrink 0.35; the iPad hold has its own funnel, a suggested start for the DEV to tune (2026-10-29): 160 embers / s = 158 embers (cut from 240 / 237 on 2026-11-10: the iPad GPU was fragment-bound), gain 1.5, 12 / 14 px, 140 px flight, rise 300, min apex 0.3 with riseSkew 2.5 (lab-tuned on iPad), carry 0.15, drift 8 steady, vent 28, pinch −1.4, no lean, fade out 0.6, shrink 0.35). iPad has its OWN config (DEFAULT_HOLD_EMBER_TUNING_TABLET / DEFAULT_TAP_EMBER_TUNING_TABLET; picked in the lab on device: embers 12 / 14 px, rise 330, vent 44, hold drift 48 / 140 embers / flight 115, tap drift 105 / 88 embers / flight 140) tuned from Lab → Hold ember with the Device row; the ember cell HELD_EMBER_SPRITE_CELL is baked at 74 for the largest iPad size chip (14·16) and at 37 on phone for the 8 px tap ember and scaled down everywhere, so no ember ever upscales and DEFAULT_TAP_EMBER_TUNING (lab picks 2026-10-29 — phone: 64-ember one-shot puff at alphaGain 104 / 64 (the gain clips the bright first half of each flight; the previewed look), rank base 104, 7 / 8 px embers, 90 px flight, rise 180, min apex 0.2, curve 3, riseCarry 0.35 so a third of the rise / drift runs at constant speed and the embers are still floating up and out as they fade (fadeOutPow 0.6, all embers since 2026-10-29) and shrink to 0.35 (the hold field keeps carry 0: it eases to a stop at its apex), drift 24 with ease-out driftCurvePow 2, vent 28, pinch 0.85, birth 0.5, launch window TAP_EMBER_BURST_PX 80; iPad has its OWN values, not scaled from phone: rise 330, min 0.2, flight 140, 10 / 12 px, drift 36, vent 52, the rest as phone); both fade out with pow 0.6 and shrink to 0.2; 8 slots × 244 quads — not an effect-slot burst. Fill / CPU trims that keep the look: the counts were trimmed from the tuned 140 / 104 and each ember's alpha raised by the same ratio (HOLD_EMBER_ALPHA_GAIN, TAP_EMBER_ALPHA_GAIN, capped at 1), so the additive field carries the same total light; the drawn sprite rect is centre-cropped to the baked oval (held-ember-crop.ts, ~14 % less fill per quad, no pixel change); evaluateEmber writes into one reused sample per frame (no per-ember allocation); and the live view publishes only each slot's seeded embers; a sustained hold ignores sub-30 px display-tick plateaus so its pause credit never piles up into a pulsing field). Perfect+ / Perfect tap-note hits fire emberRef.burst(geom, currentTick, themeTier) (shouldFireTapEmberBurst — Great / Too Early / Late hits dissolve the tile with no embers) — a one-shot TAP_EMBER_COUNT puff on a draining slot that never evicts a live hold. JS emberRef.start(note, geom, currentTick, themeTier) never reads SharedValues (runOnUISync); callers pass the JS audio/display tick and the layer write-publishes scalar pending ops for the shared FX frame to seed. Keyboard stays on its own bake (separate window / GPU cap). Judgement center + points remain theme-keyed glyph groups; the center N streak suffix is baked once in the PERFECT red/yellow style (SUFFIX_TIER_COUNT = 1) and does not follow the streak/multiplier color. Lane accents are fixed: white keys yellow, black keys cyan (tile-colors.ts). Each layer still owns its fixed slot pool and buffer modifiers — only the source SkImage is shared. See .cursor/skills/skia-atlas-object-pool/SKILL.md.
Note visual lab. Lab → Note visual (NoteVisualEffectLab) previews the real TileFallingLayer over a white/black-key chart with toggles for hold notes and scrolling.
Device sizing. On iPad the hit smoke is ×1.5 (SMOKE_DEVICE_SCALE: size + spread), the rising orbs ×1.5 (STAR_RISE_DEVICE_SCALE: halo + core), the hit-line wave ×1.25, and embers use their own iPad config; backdrop glow and tap bloom stay the phone size. Falling notes are 42 pt on every iPad (TILE_BODY_WIDTH_TABLET = phone 30 × 1.4), and the tile body atlas bakes at the largest width (42) so no device upscales it. Rise HEIGHTS (orbs, embers) use a taller factor, TABLET_RISE_HEIGHT_SCALE 2.2× in gameplay-rise-scale.ts: gameplay is landscape and the 4:3 iPad has ~2.2× more room above the hit line, while its width grows only ~1.4×. Atlas sprites are baked at the LARGEST size the running device class draws them and scaled down (smoke cell 96×48 phone / 144×72 iPad, ember cell 37 / 74) — never baked at phone size and upscaled on iPad, which reads as noise. Smoke puffs and rising orbs also skip any quad whose alpha is under half an 8-bit step (SMOKE_INVISIBLE_ALPHA, STAR_RISE_INVISIBLE_ALPHA): the color buffer rounds it to 0, so it would draw nothing but still cost fill. The HUD (badge, score, judgement label) and layout (hit-line offset) also scale on iPad. tablet-fx-sizing.test.ts pins these rules.
Update rates. One FX frame driver runs every display frame; each layer throttles itself with shouldRunGameplayFxUpdate (jitter-tolerant). Ambient layers step at the 40FPS default (glow, SmokeWave phase) or GameCanvas.tsx's per-layer cadence (tap bloom 40, StarRise 60, smoke puff / judgement 60); the badge pop uses its "30FPS" cadence. Everything else runs every display frame: badge water fill + crest and tint, score count-up, Sparticle, light-beam fade, SmokeWave fades, the header progress bar, and the scroll-bound loops (tiles, hold embers). The keyboard press travel in AtlasPianoKeyboard steps at the 60FPS cadence (every 2nd frame on 120 Hz): frame time accumulates between steps so the travel keeps its real duration, and a press's first step is still taken on the touch itself. While the pause panel is open, PlayScreenBody sets fxFrozenSv: the FX driver and the tile loop return at once, so the canvas stops redrawing. ProMotion iPhones and iPad Pro run up to 120 Hz (CADisableMinimumFrameDurationOnPhone: true). A 60 Hz iPhone lock and 30/s cuts tried on 2026-10-23 were reverted on 2026-10-26 (choppy on device). Details: docs/investigations/game-mode-thermal-2026-10.md.
Streak tier effects. What each badge band (x1–x5) turns on — badge, glow opacity, hue cross-fades, SmokeWave, tap bloom, StarRise, smoke size — lives in streak-tier-effects.ts (derived from the gameplay constants) and is previewed in Lab → Full stack (tier walk + per-layer toggles). First-use FPS analysis: docs/investigations/streak-tier-fps-2026-10.md. The background glow (GameplayGlowLayer, x2+) is the tap tier glow without the tap: soft smoke clouds (backdropGlow = a near-round billow (a broad centre puff ringed by six soft puffs), backdropGlowOval = a slightly tall rounded puff; lobe layouts in glow-backdrop-cloud.ts, each puff the Gaussian falloff in glow-backdrop-falloff.ts; billows turn to a seeded angle each life so the one baked shape never repeats on screen) (backdropGlow, one <Atlas>) fire by themselves in six fixed lanes — GLOW_BLOOM_LANES_X, four in the centre and one at each side — with two blooms per lane half a loop apart (12 in flight), on interleaved timings (GLOW_BLOOM_LANE_PHASE). A bloom takes GLOW_RISE_PERIOD_MS_BY_TIER to travel bottom → top — a progressive ramp: 13 s at x2, 12 s at x3, 8.5 s at x4, 7.5 s at x5 (7 s at the lab-only x6); the rise is accumulated at the live tier's pace, so a streak change speeds blooms up without moving them. Each life picks a seeded peak radius from GLOW_BLOOM_PEAK_R_VARIANTS (18 / 21 / 24 / 27 % of lane width, same on iPad; each puff uses a Gaussian-style falloff with no hot centre and no knee in the slope, so no core or disc edge shows; each bloom peaks at TINT_ALPHA 0.3 × tier opacity so it stays quiet background). Two fixed slots (GLOW_BLOOM_OVAL_INDICES, one in each of two side-centre lanes) draw the squeezed backdropGlowOval sprite instead (the rounded wisp cloud, ×GLOW_BLOOM_OVAL_RADIUS_SCALE, tilted ± GLOW_BLOOM_OVAL_TILT_MAX per life via computeGlowBloomXform; billows turn ± GLOW_BLOOM_CLOUD_TILT_MAX), so the field is mostly circles with the odd oval and a small X wobble, blooms in, then narrows and fades, so black background always shows between circles. The sim fills a per-bloom render cache (only while the glow is visible) that the Atlas buffers copy. Each bloom draws a sprite rect centre-cropped to its cloud's lobes (cropGlowCloudRect; the dropped border is fully transparent), anchored on the crop's half extents in computeGlowBloomXform — about 37 % (billow) / 51 % (wisp) less fill per bloom with the same pixels. The rising orbs (StarRiseLayer, x4+) are 24 glowing dots at x4 and 28 at x5 (STAR_RISE_STREAM_COUNT; the 4 extras, isStarRiseExtraSlot, are spread along the line and fade in over STAR_RISE_FADE_MS) in three seeded sizes (STAR_RISE_SIZE_VARIANTS_PX 6 / 9 / 13 px on phone, ×1.5 on iPad = 9 / 13.5 / 19.5 px — halo and core scale together; rise 20 px on phone, 44 px on iPad; drift 4 px) that loop up off the hit line. Each is two quads: a soft tapTierGlow halo (STAR_RISE_HALO_DRAW_SCALE 1.6 × the size) tinted with the current streak glow color (STAR_RISE_ACCENT_BY_TIER = bgAccentRgb per tier, cross-faded over THEME_TRANSITION_DURATION_MS on x4 → x5), and a solid white core (STAR_RISE_CORE_FRACTION 0.45 × the size) on top; both twinkle (alpha × 0.7 ± 0.3). The tap bloom (TapTierGlowLayer, x4+) is the backdrop hue × TAP_TIER_GLOW_DARKEN (0.7) so it reads as a distinct deeper patch, at one of four seeded sizes (TAP_TIER_GLOW_SIZE_VARIANTS) per fire. The press light beam (LightBeam) fades in over 70 ms ease-out and, on release, tops up to full before its 350 ms fade-out, so even a quick tap's beam lights fully. The fades are sampled analytically (sampleBeamFade in LightBeam.utils.ts, same out-cubic / in-out-quad curves as the former withTimings) by ONE FX-frame runner for all slots, which returns at once when no beam is fading.
Song load sequencing
- Runner prep in parallel:
useMagicGameplaywaits onwhenSamplerReady()andensurePlayableSongChart(songFileName, songVersion)together (Promise.all); the backing lookup (lookupSongBacking) is chained on the chart that plays (playable.key— a new version has no recording, so it plays its rhythm track), then it builds the chart and opens the backing. - Keyboard sheets from cache: when the keyboard sheet is already in its LRU (Retry, the next part, the same layout),
AtlasPianoKeyboardtakes it at once (peekKeyboardSheets) instead of waiting for an idle task; otherwise it bakes on idle, guarded by the 6 sGAMEPLAY_READY_WATCHDOG_MS. - Loading gate — everything drawn before 3-2-1:
PlayScreenGameplayGroup'sonReady(→gameplayReady→prepareReady) fires once three parts are in, in any order (gameplay-ready-gate.ts): the keyboard's sheet is painted (onAtlasReady), the lane is settled — itsSpriteRootholds every sheet it was given or published, the judgement glyph ("hud") sheet included (onSheetsSettled,lane-settled.pure.ts) — and, for a host that passesrehearse(Game Mode, the tutorial song), the first-hit rehearsal has drawn and cleared under the card (GameplayRehearsal.tsx: tap, the other judgements, a hold and tiers 2–5 on the lane's middle white key, fired through the same handlesuseMagicJudgementfires; it never consumes a real tile and leaves the badge's visibility to the host). The engine is disposed between songs (it lowered memory crashes), so every song's card pays its own warmup; the first song after a launch also pays the process's Graphite / Dawn compiles there instead of in its first seconds. A new first-hit effect is added togameplay-rehearsal-shots.tswith its fire and its clear (the tier glow'sclear()included: its 3 s blooms otherwise outlived the card and showed through the countdown);gameplay-rehearsal-shots.contract.test.tsfails when a fired handle has no clear. The onboarding's hidden stage fires the same shots. Game Mode's hit line stays hidden under the card and the countdown (HitLineRevealContext, drawn atHIT_LINE_HIDDEN_OPACITY= 1/255 so it keeps drawing and its gradients stay warm) and fades in overHIT_LINE_REVEAL_MSwhen the countdown shows GO (useCountdownPreRoll); hosts without the provider (tutorial, labs) draw it always on. The 6 sGAMEPLAY_READY_WATCHDOG_MSstarts the song anyway if a part never signals. While it waits, the card keeps its piano keys and adds a progress bar (PrepareProgressReadout): a 3 pt white bar along the bottom edge (scaleXon the UI thread), no label or percent, tokensprepareProgressTrack/prepareProgressFill. The share comes fromusePrepareProgressStore, which the gameplay group (withrehearse) feeds: song loaded on mount, keyboard, each late sheet's paint (onSheetProgress←paintInSlices), lane settled and the rehearsal's shots, weighted inprepare-progress.pure.ts; it never goes back and reaches 100% only when every part is in. Hosts opt in withshowProgressonPlayScreenPrepareAssetGroup(Game Mode, the tutorial song); tutorial practice shows the keys only. - The lane presents itself (no Skia patch):
PlayGameCanvasbuilds its root oncreateWebGpuSpriteBackend({ present: "canvas" }). The sprite planes (glow; tiles, FX, popups and the keyboard strip) are drawn into react-native-webgpu canvases and presented by the sprite engine on the UI thread right after the frame's writers, so a frame never waits on Skia's display link (which showed a late frame merged with the next: the iPad lane at ~46 fps). The hit line (HitLineGlowLayer+HitLineCoreLayer, FX-sheet strips tinted per tier), the smoke wave between them (SmokeWaveLayer, the engine's proceduralsmokeWavematerial, added onto the glow) and the header score are all sprite layers: the lane has no Skia canvas, so its planes share one WebGPU canvas run. Details:src/core/sprite-engine/README.md, "Presenting into WebGPU canvases". Fallback if this path misbehaves on a device: branchrelease/1.0.11-skia-patch(Skia patch, present on submit). - Tutorial song under its reveal: opened from the choose screen (
?revealed=1),TutorialGameplayScreenhas no reveal: it opens on the song's loading card and mounts the song once the route has arrived (onboarding.md, "Choose → play, step by step"). Otherwise it mounts the song surface once the reveal has settled (songRevealSettledMs(), 950 ms) and draws the reveal over it (zIndexabove the song's own overlays) until the song is ready, so the chart, runner and sampler use the reveal's hold (2 s,TUTORIAL_SONG_REVEAL_HOLD_MS); at the hand-over, the rays at rest, the lane and keyboard mount under the still reveal, and the reveal leaves onto the Get ready! card once the song is ready (tutorialRevealLeaves; the loading card shows only if that takes over 2.5 s,TUTORIAL_REVEAL_READY_WAIT_MS); its 3-2-1 waits oncountdownArmed. The settle is reported by the reveal itself (SongRevealShowcase'sonSettled, awithDelayon the UI thread started with its moves, hopping to JS throughstable-js-callback), not a JS timer: the moves start on the UI thread's first frame, later when the screen's first frames are slow, and a song mounted on a JS timer could land on the end of the entrance (the name still fading in). The hand-over mounts the song too, should the settle never come. No atlas is baked ahead of the reveal: the lane's master atlas and the keyboard's key / overlay sheets bake on the surface's own mount (the old launch / idle prewarms —JudgementAtlasPrewarm,KeyboardAtlasPrewarm,TutorialPracticePrewarm,useTutorialSongPrebake— were dropped: they held the splash and loaded the app before the FTUE). The tutorial arms the same keyboard watchdog as the play screen. - Reveal smoothness — what is and is not measured: the chart steps are cheap (bun, cold:
chartJsonToChart0.05–1.1 ms andbuildRhythmCursor≤ 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=1records one session per song (tutorial and Game Mode): UI frames over the hitch threshold (checked inGameplayFxFrameProvider, only hitches cross to JS), JS rAF stalls ≥ 50 ms, and marks — reveal / prepare / countdown,canvas_layout:lane, each layer'sprewarm_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](Crashlytics breadcrumb, plus console.warn outside release builds, which strip every console call) and Lab → Hitch traces keeps the last 5. Every session is also saved as its own file<start>_<screen>-<session>.jsonin the app'sDocuments/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.tssummary + hints,hitch-trace.tsJS half,hitch-trace.worklet.tsUI half). Off, every call returns at once. How to read it: docs/investigations/streak-tier-fps-2026-10.md → Tutorial first song. - Effect toggles (Lab, dev only):
gameplay-effect-toggles.ts+gameplay-effect-toggles-store.tsswitch any Game Mode effect layer off inPlayGameCanvasandTutorialGameplayCanvas, 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, atrate = 1 + clamp(errorMs / 250)(speed-up capped at +10 %, down to a standstill when ahead).errorMsis 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:
PlayControllerre-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 pastBACKING_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
seedTicktogether 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 byresumeLate), 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:
- Add a catalog row in the Google Sheet (or src/assets/config/songs.json for offline bootstrap) with
fileNameandmidiUrl. - (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/disposedrive 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 withbun 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 underpackages/*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 andheld-voice.ts - Melody (
sampler.melody) — auto-play, pre-scheduled by the controller's song sequencer (melodySamplerlane, enabled viasetMelodyAutoPlay).useAutoPlay.voicing.tskeeps 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 viacreateRhythmSamplerAdapter(converts the engine's absoluteatTimeto 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).
- User (
- 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 leavesactive(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 thatstopAllcovers the whole shared pool,previewincluded, 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 fromentrySetup.ts;ensurePianoSampler()runs fromAppProvidersand from each screen'suseSoundFontSampler. - Memory pressure.
releaseMemoryPressuredisposes 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). useSoundFontSamplersubscribes to the process-wide singleton viausePianoSamplerStore. 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 (
AtlasPianoKeyboarddefers key/label/overlay bake viascheduleIdleTaskafter first paint; free-playKeyboardScreenstill limits the visible MIDI window to viewport + overscan viabakeWhiteKeysForView). A refused key-sheet bake (offscreen surface unavailable under memory pressure or in the background) is retried on a short backoff (keyboard-bake-retry.ts) and again on the next return to the foreground. No bake runs while the app is backgrounded, and a sheet whose sprites cropped to nothing is rejected before the LRU can cache it (isKeyboardSheetIntact). Every offscreen bake goes throughguardedBakeinsprite-atlas.ts: Skia THROWS (not returnsnull) when the GPU refuses the readback (makeRasterImageSync: reading the image back failed, 1.0.9), so a refusal is reported as a handled error and becomesnull. The judgement atlases retry on the same schedule (atlas-bake-retry.ts,useAtlasBakeRetry); tests insprite-atlas.readback.test.tsfake the GPU failure. - Song previews.
core/audio/song-preview: a cover tap plays ~15 s of the song's bundled gameplay chart through the sampler (ChartPreviewPlayer); one preview at a time, none under a screen cover. - Production three-layer keyboard:
AtlasPianoKeyboard+keyboard-key-atlas.tsbake base (housing — white: ONEwhite_baseshell 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 bywhiteBaseOffsetY,#494949→#787878gradient across the lip, no border) + top static (white:#D4D4D4→#E5E5E5rim — 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 argba(23,23,23,0)→#404040gradient 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 atATLAS_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 withATLAS_KEYBOARD_VERTICAL_GAP_PX(2px) top/bottom. Press travel: whiteKEYBOARD_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); blackKEYBOARD_KEY_BLACK_PRESS_DROP_PX= 5 — lip-clamped, the pressed cap lengthens down. A press goes down inKEYBOARD_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 inKEYBOARD_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 by1/bakeScale;bakeKeyboardSheetsshrinks the scale only if the sheet would exceedKEYBOARD_KEY_ATLAS_MAX_TEXTURE_DIMENSION(8192). White-key note labels bake into a separate sheet (keyboard-key-label-atlas.ts) — two atlas quads per key. The key and overlay sprites share ONE sheet (keyboard-sheet-atlas.ts: registered together with the engine’s shared compact texture layout under the 8192 cap — overlays at up to 1.5×, keys at full scale; the grid bands it replaced padded every short cell to its row's tallest. The Learntint_bandcells are baked only for a keyboard handedkeyTints(Learn, the lab):buildOverlaySpecs(…, tints)/bakeKeyboardSheets(…, tints), and the LRU key carries the flag — a third of the overlay cells less on Play, tutorial and free-play) — so the white / shadow / black regions and their washes sample one texture and the plane draws the keyboard in 2–3 calls (keys + washes, labels; an idle shadow region splits the key sheet's draw) instead of 5. The keyboard owns its canvas and plane (createLayeredPlane,AtlasPianoKeyboardLayers.tsx); keys are fouruseSpriteSystems (white / shadow / black / labels, slot = key) inAtlasPianoKeyboardLayers, woken per key by press travel or an overlay change (AtlasPianoKeyboard.wake.ts). That sheet is a ~10 MB CPU raster and a pure function of (key geometry, bake scale), so it goes through a small LRU (bake-lru.ts, 3 entries); a miss bakes as a sliced job (startKeyboardSheetsBake: cells drawn ~6 ms per idle slot, readback in a slice of its own) rather than one frozen call — a replay reuses it; re-baking per mount left ~22 MB of native pixels per play session behind Hermes GC (which paces on JS heap, not on the pixels behind anSkImage). The gameplay master / FX / light-beam sheets keep no CPU raster at all: only their layouts are cached and the sprite engine bakes them on upload (keyed bake sources). Overlay washes (keyboard-key-overlay-atlas.ts) bake highlight / Learn tint / wrong-key alpha sprites once and modulate per slot (no per-framecreatePicture). Highlight / tint / wrong rides press travel with the key face (whitepressWhiteSinkTy, blackpressBlackTopTy) 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 isPianoKeyboardHandle(setHighlightNotes/setPressedNotes). No built-in haptics — parents fireHaptics.playfromonNotePressed/onNoteReleased(free-play + Learn key click; Play/Tutorial leave key-edge buzz off so judgement owns perfect/hold). Countdown / prepare gates ononAtlasReady(not a snapshot blit). The press-travel runner (in the keyboard's ownGameplayFxFrameProvider) idles when every key's progress matches its target (pressActiveSv). Learn number chips stay as RNKeyNumberBadges— passstripBottomGap={ATLAS_KEYBOARD_VERTICAL_GAP_PX}andpressSinkByNote. Preview in Component Labs (atlas-piano-keyboard). Wired on Play (MultiplierAwarePianoKeyboard), Tutorial, Learn, and free-play Keyboard screens. Play and the tutorial draw it atGAMEPLAY_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.poolCapacitysizes 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:trimAtlasOpaqueExtentsreads 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 productionAtlasPianoKeyboardon the process-wide sampler and togglessampler.setSustainso you can A/B pedal on vs off without leaving the labs shell (same engine path chart pedal spans use viaPlayController). 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.tspins singleton ensure / dispose / error-retry semantics using fake samplers — the service has onlyimport typereferences toPianoSamplerLike, 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):
- Reuse the gameplay hook.
useMagicGameplayalready loads the song, builds a@rhythm/enginePlayController, and exposes aSharedValue<number>tick clock viauseMagicJudgement. Wrap or fork it for engines other than the Magic flavor. - Compose the Skia stack the same way. Same per-key window (
startNote/endNote, fromcomputeAutoFitKeyRange) andwidthflowing to<AtlasPianoKeyboard>,<TileFalling>,<HitEffect>, and any new overlay — see .cursor/skills/piano-simulation-screen/SKILL.md. - Decide if the surface is judged. For a scored surface, mount
useMagicJudgement+ the HUD leaves (HeaderScore,MultiplierBadge,SessionResultOverlay, PlayScreenPlayGameCanvas— which hosts every lane*Layerincluding<JudgementPopupLayer>and<CenterJudgementLayer>) and gate them with ajudgementEnabledboolean 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+pointsglyph; the central<CenterJudgementLayer>carries the label + combo suffix. Tweak gameplay rules in@rhythm/engine'sjudgement/constants.ts; tweak host-side UI windows injudgement.constants.ts— never inline new windows / point values / tier rules in the screen code. - 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 onPlayScreen,LearnModeScreen, andKeyboardScreen. (iOS bottom-edge gesture deferral is app-wide inAppProviders— do not re-toggle it per screen.) - Add the route. Drop the screen under
app/(app)/and forward to it from the catalog list (or the home grid).
Performance: PlayScreen must not subscribe to judgement store on the gameplay tree — use imperative HUD leaves and getState() at write sites. See gameplay-hot-path.mdc and the trimmed piano-simulation-screen skill; full layer inventory stays in this doc's Files section above.
Reanimated: static feature flags (none set)
package.json sets no reanimated.staticFeatureFlags: the app runs on Reanimated 4.7's defaults. An earlier build turned on IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS (apply whitelisted props — opacity, transform, colors, border radii, shadows — directly instead of a Fabric shadow-tree commit per animated style update) and tried FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS = false; both were dropped. A static flag is compiled into the native build, so adding one back needs pod install + a rebuild.
With the defaults, two things show up in profiles:
- Per-frame shadow-tree commit. Every animated style update — even a lone
opacity/transformsuch as the song-progress bar'stranslateX— goes throughcloneShadowTreeWithNewProps→ Yoga layout → mount on the main thread. Keep the number of animated views on the play screen small and prefer the sprite engine for gameplay visuals. settledStylerenders.FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS(defaulttrue) writes an animated style's settled value back into theAnimated.*component with asetState, flushed every 500 ms. The Profiler shows "Props changed:style,ref" on aView (AnimatedComponent)while the memo-isolated parents above it did not render (the progress rail's opacity gate andtranslateXfill, countdown, HUD chrome, pause panel). The render stops at that view; it is not a bug in the rail's own props. Android'sANDROID_SYNCHRONOUSLY_UPDATE_UI_PROPSwas never enabled.
Skia canvas cost model (why idle pools are compact)
Each <Canvas> has one Reanimated mapper that re-applies every animated prop of every node on each frame any of them changes, then re-records the scene. The gameplay lane canvas changes every frame, so Atlas arrays are marshalled through JSI every frame regardless of liveness. HoldEmberLayer (8 slots × 244 quads) and SmokeParticleLayer (4 × 24 = 96-quad pool) therefore publish only the quads of live slots (buildEmberLiveView / buildSmokeLiveView; empty when idle) instead of the full fixed pool: measured on the simulator, ember alone fell from ~10 % to ~1 % of main-thread time. Texture size / atlas splitting does not change this cost. See .cursor/skills/skia-atlas-object-pool (§2b).
Hold embers on pause
Pausing ends every hold (PlayScreenBody.pauseGameplay → HoldEmberHandle.drainAll()), but it does not cut the embers: slots go SLOT_DRAINING, nothing new launches, and the embers already in the air finish their rise. Launches ride the playback tick, but a flight in progress also advances on the shared FX clock while the tick is frozen (advanceEmberPause / pauseCreditPx → evaluateEmber's pausePx / pauseCreditPx), so a paused game no longer freezes an ember mid-air. After the pause outlasts the longest flight (HOLD_EMBER_MAX_FLIGHT_PX) the layer stops writing frames (pauseDone). Teardown still uses clear(), which cuts instantly. On the first moving frame after a pause, bakeEmberPauseOnResume moves the cursor's credit onto each live slot (pool.pauseTick / pool.pauseCreditPx) so a later tick plateau cannot hand landed flights their age back. A real pause (≥ EMBER_REAL_PAUSE_MIN_PX of wall clock — e.g. auto-pause at the hit line) also ends every released field and tap puff (pool.burst) at the pause tick and frees the ones whose embers already landed; otherwise a puff's remaining tick-axis launches fired after the player hit the NEXT note, replaying the previous note's embers. Slots seeded during the pause (seededInPause — the resuming note) are left alone.
Short holds, stale arms and lost ember seeds
Dense charts (Rush E) are full of holds that the engine completes before HOLD_VISUAL_ARM_MS (120 ms): effectiveHoldEnd pulls the tail back by the note core, so a ~260 ms hold can finish 5–116 ms after the press. useMagicJudgement handles every hold exit per hold (noteNumber + noteTime), not per key:
- Ended before arm — the arm timer is cancelled;
finishUnarmedHoldunpins 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;scheduleHoldVisualArmthen never arms that hold (an arm after the end used to pin + rumble a finished hold and leave its armed flag set forever, which skipped the key's NEXT hold and left its tile on screen with a full tail). It only detaches the head (plus the Perfect hold-end hit burst) instead. - Stale armed flag — scheduling a new hold on a key still marked armed closes the old one first (
closeStaleArmedHold:stopGameHold,releaseHold, emberrelease); 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 —
pauseGameplaycallscancelPendingHoldArms()so no arm fires while frozen. - Ember publishes merge — JS publishes its pending ops with
pendingOpsSv.modify(...)→mergeHoldEmberPendingOpson the UI runtime instead of replacingpendingOpsSv.value, so a publish no frame has applied yet is never lost (a RELEASE on a not-yet-applied SEED keeps the seed withreleaseAtSeed). - Known, not fixed: the JS ember slot mirror never learns that the UI freed a slot (every slot reads draining); draining slots are reused oldest-first, so this is harmless until the pool is truly full.
Hold ember lab presets
Every ember animation knob lives in one HoldEmberTuning object (HeldTile.utils.ts); gameplay uses DEFAULT_HOLD_EMBER_TUNING (the HOLD_EMBER_* constants) and never passes HoldEmberLayer's optional tuning prop. The Labs → Hold ember screen drops real notes on a TileFallingLayer and auto-plays them like a perfect player (hold-ember-lab.chart.ts: tap → consumeTile + burst; hold → HOLD_VISUAL_ARM_MS → pinHold + start, tail → releaseHold + release; fixed 1.5-beat hold tail). It is a layout: "fill" lab (the modal folds its lab list away and hands it the whole panel): the lane is pinned on the left at 1:1 px — sized from the window by resolveHoldEmberLabPreviewSize (hold-ember-lab.layout.ts), tiles stay 30 px, only the lane narrows — with a one-line transport (Play / HIT, note type, static TAP / HOLD) under it, while the controls scroll on their own on the right: Device / Tune / Speed / Group (ALL · SHAPE · MOTION · FADE · COUNT) pinned at the top, then one-line knob rows (EffectLabCompactChips: title + horizontally scrolling chips, ● = gameplay default, hint behind ⓘ), the readout + reset, and a collapsed Advanced section (renderer rows, bench HUD, notes). Chip rows from hold-ember-lab.presets.ts swap one field at a time (5 chips per row, the gameplay DEFAULT in the center — or first when it is the knob's floor, e.g. drift 0) — rise height, lowest ember, launch kick, keep floating (riseCarry), flight time, drift, drift fan-out (driftCurvePow), vent width (pyramid base), height spread (riseSkew), lean start / lean angle, pyramid pinch, size, embers per second (hold) / embers per tap, first wave, fade in / out, shrink. Per-frame fields (rise, curve, carry, drift, drift curve, pinch, fades, shrink) change embers already in the air; seed-time fields apply from the next note. The tap-puff launch window is derived (resolveTapEmberBurstPx) so any count / speed still launches every puff ember exactly once. The lab mounts the layer with emberCapacity={EMBER_LAB_EMBER_CAPACITY} (300) so the hold rate / tap count can go above gameplay's fixed 100-ember slot buffer (the readout shows RATE n/s (m embers) — the embers that rate needs); gameplay keeps the default. Halo blur (HOLD_EMBER_GLOW_SCALE 4.6, HELD_EMBER_CORE_SHRINK in held-ember-crop.ts) is baked into the atlas and is not a lab knob.
Benchmark HUD (lab only). The STRESS ×8 note type drops 8-hold chords to keep every slot live; the HUD (EmberBenchReadout.tsx) shows UI fps, worst frame and JS stall per second. Skia records the declarative <Atlas> pair on its native pool, so the record cost is not visible there — compare through fps / worst frame (and Instruments).
Shared gameplay HUD glyph sheet
useGameplayHudAtlases packs points, centre words and streak characters directly into one MaxRects sheet (judgement-hud-atlas.ts). The queue bakes it in idle slices, caches it per theme, and retries refused allocations. PlayScreen passes the same atlas to JudgementPopupLayer and CenterJudgementLayer, which sample hud with alpha blend and can share one draw when both fixed pools are submitted. Glyph advances, origins, font sizes and PERFECT aliases are preserved. Standalone tutorial and lab callers retain their existing sheets and word looks. Plane boundaries preserve the soft-FX resolution, Skia hit-line order and keyboard strip target. Actual texture area depends on font metrics and packing. Device FPS and memory gains require profiling.
The shared HUD sheet is registered once by PlayGameCanvas in WebGPU devtools as “Judgement HUD glyphs (points + words + streak chars)”. Shared-atlas layer instances omit their standalone registrations. Dev registrations use a mounted-owner id so overlapping screens cannot remove each other’s entries during cleanup. beam-white and beam-black are the key-aligned LightBeam columns, whose widths follow the white and black key feet (black = 0.6 × white).