All files / player-engine/src/core play-manual.ts

97.65% Statements 125/128
93.33% Branches 70/75
100% Functions 29/29
99.15% Lines 117/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307                                                                                    2826x 2826x               26445x         26445x                                                         2826x 2826x 169246x 8209x 8209x 9547x 9547x 9429x       9547x     8209x 72x         30x     8209x   2826x 30778x 199794x   2655x 509x           2040x 2040x 2040x 2040x 2040x 126x   2040x 167x   2040x 2040x 2040x 2040x 2040x 2040x 2040x 2040x       511x 511x   511x 511x 511x     511x 511x 3260x 3260x   511x 124197x   511x 511x 9267x             511x 115x           511x 538x     25x   511x             511x 511x 4251x 4251x     511x 5864x 117507x 471x 509x   27x 27x 27x 27x 27x 27x     116781x 12050x   116781x   116781x   116766x   5953x 5953x   1x   5952x 5952x 3315x   17x 17x   3315x 27x 27x 27x   3315x 3315x 3315x           3315x 3315x 1614x 1614x 1614x                       3315x   2637x           2637x 2637x 2637x 63x     2637x 2637x 2637x 2637x 26x   2611x 2611x   2611x 5953x 970x 970x   1641x                             127x            
import { resolveAutoScratchChannels } from './auto-scratch.ts';
import type { PlayerHCNLaneState } from './ui-signal-bus.ts';
import { resolveRulesetLongNoteMode } from './judge-rules.ts';
import { formatSeconds, resolveAltModifierLabel } from '../utils.ts';
import {
  createJudgeCoreState,
  isJudgeCoreSettled,
  isJudgingClosed,
  resolveJudgeInputChannels,
  runJudgeCoreStep,
  type JudgeCoreEffectSink,
  type JudgeCoreInput,
  type JudgeCoreState,
} from './judge-core.ts';
import { resolveJudgeNowMsFromPressedAt } from './engine-clock.ts';
import { formatJudgeWindowSet, printLaneMap, writeRuntimeEventLog } from './engine-trace.ts';
import { createKeyStateInference } from './play-key-inference.ts';
import { createScratchSpinByToken, resolvePressSpin } from './scratch-spin.ts';
import { keyboardInputSource } from './input-source.ts';
import type { PlaySession } from './play-session.ts';
import type { JudgeStrategy, PlayJudge } from './play-strategy.ts';
 
/**
 * The manual judge strategy: the deterministic judge core (`judge-core.ts`) fed the play clock's time once per tick and
 * every key the player presses and releases, stamped with the instant it went down (`pressedAt`). An input runtime that
 * declares its releases (`PlayerInputRuntime.reportsKeyReleases`, a browser) is key-state input from its first key.
 * Otherwise, until the input reports a release (`kitty-state`), its presses go through a key-state inference
 * (`play-key-inference.ts`), which infers when each key came up.
 */
 
/**
 * The judge core of a manual play or a replay. `judgeMsPerChartSecond` is the millisecond domain the release margins
 * and the key-state inference's graces run in: live play runs them on the playback clock at the tempo it started at
 * (after a tempo change, on chart time at that tempo, `TempoClock.initialTempoMsAt`, so the domain stays linear in
 * chart time); a replay has no wall clock to honour, so it runs them on chart time and its judgments do not depend on
 * `speed`.
 */
export function createPlayJudgeCore(
  session: PlaySession,
  judgeMsPerChartSecond: number,
  practiceFromSeconds?: number,
): JudgeCoreState {
  const { playbackChart, resolvedJSON } = session;
  return createJudgeCoreState(
    {
      ruleset: session.ruleset,
      scorableNotes: playbackChart.scorableNotes,
      landmineNotes: playbackChart.landmineNotes,
      invisibleNotes: playbackChart.invisibleNotes,
      laneSoundNotes: playbackChart.laneSoundNotes,
      scratchChannels: new Set(
        playbackChart.laneBindings.filter((binding) => binding.isScratch).map((binding) => binding.channel),
      ),
      autoScratch: session.autoScratch,
      autoScratchChannels: resolveAutoScratchChannels(
        session.options,
        playbackChart.laneBindings.filter((binding) => binding.isScratch).map((binding) => binding.channel),
      ),
      ...(session.anyKey ? { anyKey: true } : {}),
      judgeMsPerChartSecond,
      // Only the terminal log writes traces; with a UI they would be built and discarded on every judgment.
      omitTraceEffects: session.uiEnabled,
      wavResources: session.wavResources,
      ...(session.options.landmineSampleKeys !== undefined
        ? { landmineSampleKeys: session.options.landmineSampleKeys }
        : {}),
      idBase: session.idBase,
      sourceFormat: resolvedJSON.sourceFormat,
      // LR2 negative-BPM reversal (#134): timing stays monotonic (the resolver integrates |BPM|), but from this chart
      // time on LR2's event pump freezes and presses are judged on the mirrored clock. The realtime audio streams are
      // already cut there (`collectRealtimeAudioTriggers` / `collectRealtimeAudioVolumeEvents`).
      reversalSeconds: session.resolvedChart.reversal?.seconds,
      reversalAnchor: session.reversalAnchor,
      endOnFailure: session.endOnFailure,
      ...(practiceFromSeconds !== undefined ? { practiceFromSeconds } : {}),
    },
    session.score,
  );
}
 
/** The parts of a {@link PlayJudge} every judge-core strategy shares. */
export function judgeCoreJudge(
  session: PlaySession,
  judgeCore: JudgeCoreState,
): Pick<PlayJudge, 'isSettled' | 'isClosed' | 'finish' | 'settledThroughSeconds'> {
  const empty: readonly PlayerHCNLaneState[] = [];
  session.readHCNLanes = (seconds) => {
    if (judgeCore.hcnPassing.size === 0 && judgeCore.pendingAutoScratchLongNotes.length === 0) return empty;
    const lanes: PlayerHCNLaneState[] = [];
    for (const [channel, first] of judgeCore.hcnPassing) {
      for (let passing: typeof first | undefined = first; passing !== undefined; passing = passing.next) {
        if (seconds < passing.note.seconds || seconds >= passing.endUs / 1e6) continue;
        lanes.push({
          channel,
          gaining: passing.tailGood || (judgeCore.laneHolds.get(channel)?.activeTokens.size ?? 0) > 0,
        });
        break;
      }
    }
    for (const { note, endSeconds } of judgeCore.pendingAutoScratchLongNotes) {
      if (
        seconds >= note.seconds &&
        seconds < endSeconds &&
        resolveRulesetLongNoteMode(session.ruleset.longNoteStyle, note) === 3
      ) {
        lanes.push({ channel: note.channel, gaining: true });
      }
    }
    return lanes;
  };
  return {
    isSettled: () => isJudgeCoreSettled(judgeCore),
    isClosed: () => isJudgingClosed(judgeCore),
    finish: () =>
      runJudgeCoreStep(judgeCore, { kind: 'finish', totalSeconds: session.totalSeconds }, session.applyJudgeEffect),
    settledThroughSeconds: () => judgeCore.advancedThroughSeconds,
  };
}
 
/** The no-TUI introduction of a manual play (and a replay). */
export function writeManualIntro(session: PlaySession): void {
  const { writeOutput, playbackChart, ruleset } = session;
  const highSpeedModifierLabel = resolveAltModifierLabel();
  writeOutput('Manual play start\n');
  writeOutput(`Lane mode: ${playbackChart.laneDisplayMode}\n`);
  if (session.randomPatternSummary) {
    writeOutput(`${session.randomPatternSummary}\n`);
  }
  if (session.autoScratch) {
    writeOutput('Mode: AUTO SCRATCH (16ch/26ch only)\n');
  }
  writeOutput(`Judgment window (${ruleset.id}): ${formatJudgeWindowSet(ruleset.windows.note)}\n`);
  writeOutput('Press Space to pause/resume.\n');
  writeOutput('Press Shift+R to restart.\n');
  writeOutput(`Press ${highSpeedModifierLabel}+odd lane key to decrease HIGH-SPEED.\n`);
  writeOutput(`Press ${highSpeedModifierLabel}+even lane key to increase HIGH-SPEED.\n`);
  writeOutput('Press Ctrl+C to quit.\n');
  writeOutput('Press Esc to stop and open result.\n');
  printLaneMap(writeOutput, playbackChart.laneBindings);
}
 
function createManualJudge(session: PlaySession): PlayJudge {
  const { tempoClock, uiEnabled, writeOutput, tracer, applyJudgeEffect } = session;
  const { inputTokenToChannels } = session.playbackChart;
  // The odd-even rule: each scratch key's spin, for presses whose input reports none.
  const scratchSpinByToken = createScratchSpinByToken(session.playbackChart.laneBindings);
  let judgeCore = createPlayJudgeCore(session, 1000 / tempoClock.initialTempo);
  let coreJudge = judgeCoreJudge(session, judgeCore);
  // Input that reports its key releases: declared by the input runtime before the play, or else detected from the first
  // `kitty-state` command. Until then when each key came up is inferred, and the inference watches the judge's effects.
  let inputReportsReleases = session.inputRuntime?.reportsKeyReleases === true;
  const inferringSink: JudgeCoreEffectSink = (effect) => {
    keyState.observe(effect);
    applyJudgeEffect(effect);
  };
  const step = (input: JudgeCoreInput): void => {
    runJudgeCoreStep(judgeCore, input, inputReportsReleases ? applyJudgeEffect : inferringSink);
  };
  const candidateChannelsBuffer = new Set<string>();
  const mapInputChannels = (tokens: readonly string[], additionalTokens?: readonly string[]): ReadonlySet<string> =>
    resolveJudgeInputChannels(
      judgeCore.config,
      inputTokenToChannels,
      candidateChannelsBuffer,
      tokens,
      additionalTokens,
    );
  const traceInput = (seconds: number, action: string, tokens: readonly string[]): void => {
    writeRuntimeEventLog(writeOutput, 'input', [
      ['time', formatSeconds(seconds)],
      ['action', action],
      ['tokens', tokens.join(',')],
    ]);
  };
  const createKeyState = () =>
    createKeyStateInference(
      judgeCore,
      step,
      uiEnabled ? undefined : (seconds, tokens) => traceInput(seconds, 'inferred-release', tokens),
    );
  let keyState = createKeyState();
  // The instant (playback-clock ms) the last press or release was stamped at. Each lane command is stamped as it is
  // drained: the playback clock read then, moved back by the age of its `pressedAt` on the wall clock. The playback
  // clock follows the audio clock, which moves a render quantum at a time (Web Audio's `currentTime`), while the wall
  // clock moves smoothly, so a command drained just after another can read older than it even though it happened later:
  // a short tap's release came out a few hundred µs before its press. Commands are drained in the order they happened,
  // so none is stamped before the one drained ahead of it.
  let lastStampMs = Number.NEGATIVE_INFINITY;
  const stampMs = (drainNowMs: number, pressedAt: number | undefined): number => {
    lastStampMs = Math.max(lastStampMs, resolveJudgeNowMsFromPressedAt(drainNowMs, pressedAt));
    return lastStampMs;
  };
 
  return {
    isSettled: () => coreJudge.isSettled(),
    isClosed: () => coreJudge.isClosed(),
    finish: () => coreJudge.finish(),
    settledThroughSeconds: () => coreJudge.settledThroughSeconds(),
    seek: (seconds) => {
      keyState.stop();
      judgeCore = createPlayJudgeCore(session, 1000 / tempoClock.initialTempo, seconds);
      coreJudge = judgeCoreJudge(session, judgeCore);
      keyState = createKeyState();
      lastStampMs = Number.NEGATIVE_INFINITY;
      return { judgments: [], heldLongNotes: [] };
    },
    judge: (tick) => {
      if (!inputReportsReleases) {
        keyState.releaseBefore(tick.nowSec);
      }
      step({ kind: 'advance', nowSec: tick.nowSec, nowMs: tempoClock.initialTempoMsAt(tick.nowMs) });
      // The presses drained since the last tick and this advance make one judging pass, as LR2's loop judges them.
      session.settleJudgeTiming();
    },
    judgedThroughSeconds: (tick) => tick.nowSec,
    handleLaneCommand: (command) => {
      const clock = session.clock;
      if (clock === undefined) {
        // Before the chart starts there is nothing to judge.
        return;
      }
      const commandSeconds = (): number => tempoClock.chartSecondsAt(clock.nowMs());
      if (command.kind === 'kitty-state') {
        if (!inputReportsReleases) {
          // The input reports its keys' state: its own releases take over from the inference.
          inputReportsReleases = true;
          keyState.stop();
        }
        if (!uiEnabled) {
          if (command.pressTokens.length > 0) traceInput(commandSeconds(), 'press', command.pressTokens);
          Iif (command.repeatTokens.length > 0) traceInput(commandSeconds(), 'repeat', command.repeatTokens);
          if (command.releaseTokens.length > 0) traceInput(commandSeconds(), 'release', command.releaseTokens);
        }
        const heldTokens = [...command.pressTokens, ...command.repeatTokens];
        const holdSource = command.source ?? keyboardInputSource(heldTokens);
        step({
          kind: 'hold',
          channels: mapInputChannels(command.pressTokens, command.repeatTokens),
          tokens: heldTokens,
          ...(holdSource !== undefined ? { source: holdSource } : {}),
        });
        const releasedChannels = mapInputChannels(command.releaseTokens);
        if (releasedChannels.size > 0) {
          const releaseNowMs = clock.nowMs();
          const releaseSource = command.source ?? keyboardInputSource(command.releaseTokens);
          step({
            kind: 'release',
            channels: releasedChannels,
            tokens: command.releaseTokens,
            ...(releaseSource !== undefined ? { source: releaseSource } : {}),
            nowSec: tempoClock.chartSecondsAt(releaseNowMs),
            nowMs: tempoClock.initialTempoMsAt(releaseNowMs),
            // The replay records the release at the key event's own instant, like a press.
            recordSec: tempoClock.chartSecondsAt(stampMs(releaseNowMs, command.pressedAt)),
            ...(command.code !== undefined ? { code: command.code } : {}),
          });
        }
        return;
      }
      Iif (clock.isPaused()) {
        return;
      }
      // The runtime adapter (web / node) stamps the OS-level key event as `pressedAt`; moving the playback clock back by
      // the wall-clock delta judges the press at the player's true timing instead of the engine's drain time (see
      // `resolveJudgeNowMsFromPressedAt` for the bounds), and no earlier than the command drained before it.
      const pressedAtMs = stampMs(clock.nowMs(), command.pressedAt);
      const nowSec = tempoClock.chartSecondsAt(pressedAtMs);
      if (!uiEnabled) {
        traceInput(nowSec, 'lane-input', command.tokens);
      }
      // The volume changes due by the write head apply to the keysound the press plays.
      session.volumeChanges.triggerUntil(tempoClock.chartSecondsAt(clock.scheduledMs()));
      tracer.flushUntil(nowSec);
      const candidateChannels = mapInputChannels(command.tokens);
      if (candidateChannels.size === 0) {
        return;
      }
      const nowMs = tempoClock.initialTempoMsAt(pressedAtMs);
      const spin = resolvePressSpin(command.spin, command.tokens, scratchSpinByToken);
      // Each physical key is its own source; a touch zone or a controller names its own.
      const source = command.source ?? keyboardInputSource(command.tokens);
      if (!inputReportsReleases) {
        keyState.press(candidateChannels, command.tokens, nowSec, nowMs, source, spin);
        return;
      }
      step({
        kind: 'press',
        channels: candidateChannels,
        tokens: command.tokens,
        nowSec,
        nowMs,
        ...(source !== undefined ? { source } : {}),
        ...(spin !== undefined ? { spin } : {}),
        ...(command.code !== undefined ? { code: command.code } : {}),
      });
    },
  };
}
 
/** Manual play: the player's keys, judged live. */
export const manualStrategy: JudgeStrategy = {
  mode: 'manual',
  estimatesActiveAudio: false,
  writeIntro: writeManualIntro,
  createJudge: createManualJudge,
};