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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 | 10x 2008x 2x 2x 5x 5x 3x 3x 3x 3x 2x 5x 1x 10x 9x 13x 9x 9x 10x 19x 12x 9x 9x 3019x 2698x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 1x 3024x 3024x 132042x 3024x 3027x 3027x 1x 3024x 3024x 3027x 3027x 132066x 3027x 125634x 2702x 3024x 3027x 3027x 1x 3023x 3027x 1x 3022x 1x 3021x 2x 3021x 3021x 3021x 3027x 3027x 3027x 129x 3021x 3027x 3027x 1x 3020x 3020x 3020x 3027x 3027x 3027x 3020x 3020x 3020x 3x 3x 3x 3020x 2888x 3020x 3020x 3020x 3027x 3027x 3020x 3027x 3027x 2623x 3027x 6420x 3027x 3027x 3027x 3027x 3027x 3027x 3019x 210x 210x 3019x 2898x 2898x 3027x 3027x 3027x 3027x 33x 3027x 3027x 3027x 12x 4x 4x 3019x 3019x 3019x 3019x 3027x 3027x 3027x 3027x 3027x 321x 321x 3019x 3019x 3027x 3027x 3027x 3027x 28024x 3027x 3027x 9x 19x 3027x 3027x 3027x 3027x 3027x 2135x 8183x 3922x 234800x 2222x 234800x 234800x 234800x 234800x 234800x 234800x 234800x 3027x 2x 2x 2x 3027x 3482x 60x 3x 6x 2622x 6x 3027x 3027x 3155x 3155x 19x 19x 3136x 3027x 396x 4x 396x 3027x 928x 17x 928x 3027x 116781x 3027x 3035x 3035x 3035x 3035x 3035x 2573x 2638x 3035x 168x 3035x 210x 210x 210x 210x 16x 16x 16x 16x 42x 16x 16x 16x 6x 6x 3036x 127481x 3036x | import { isSoftLanding } from './scroll-modifier.ts';
import { BmsonBGAController } from './bmson-bga.ts';
import { resolveChartGaugeType } from '../ruleset/chart-gauge.ts';
import { resolveChartJudgeOption } from '../ruleset/chart-judge.ts';
import { countRulesetNotesOf } from '../ruleset/facts.ts';
import type { TimedPlayableNote } from '../playable-notes.ts';
import { ChartTextController } from './chart-text.ts';
import { selectPlaybackChartSide, type SecondPlayer } from './two-player.ts';
import { resolveEffectiveBattleMode } from './battle-mode.ts';
import { chartNotesCopies } from './chart-notes-options.ts';
import { arrangeChartPlayLanes } from './chart-play-lanes.ts';
import { resolveChartAddMineModifier, resolveChartPlayProgram } from './chart-play-options.ts';
import { applySevenToNine } from './seven-to-nine.ts';
import { clampExtraNoteDepth } from './extra-note-modifier.ts';
import { buildAutoKeyBoundBGAInputs, KeyBoundBGAController } from './key-bound-bga.ts';
import { resolveAutoScratchChannels, resolveAutoScratchSides } from './auto-scratch.ts';
import {
createBeatAtSecondsResolverFromTimingResolver,
buildKeyBoundBGATimeline,
buildBmsonBGAEventTimeline,
buildChartTextTimeline,
buildChartOptionTimeline,
compileChartGaugeOptions,
compileChartOptions,
compileChartPlayOptions,
isLegacyChartPlayOptionProgram,
resolveChartOptionsAt,
type ChartOptionProgram,
isPlayLaneSoundChannel,
isInvisibleNoteChannel,
type ResolvedChart,
type TempoReversalPoint,
} from '@be-music/chart-model';
import { throwIfAborted } from '@be-music/shared-utils/core';
import { type BeMusicEvent, type BeMusicJSON, normalizeObjectKey, resolveBMSBase } from '@be-music/chart-source';
import { createPlayerStateSignals, type PlayerStateSignals } from '../state-signals.ts';
import { resolveHighSpeedMultiplier } from './high-speed-control.ts';
import { createPlayerUISignalBus, type PlayerUISignalBus, type PlayerHCNLaneState } from './ui-signal-bus.ts';
import { createPlayerInputSignalBus, type PlayerInputSignalBus } from './input-signal-bus.ts';
import { createNoopPlaybackStateLogger, createUIFramePublisher, type PlaybackStateLogger } from './playback-support.ts';
import { createScoreTracker } from './scoring.ts';
import {
judgeWindowLateReachUs,
resolveRuleset,
resolveGaugeEndOnFailure,
rulesetChartFactsFromChart,
type RulesetConfig,
} from '../ruleset/index.ts';
import type { JudgeCoreEffectSink, JudgeCoreScore } from './judge-core.ts';
import { createReplayRecorder, type ReplayRecorder } from '../replay/recorder.ts';
import { courseStageCarryCombo, courseStageRulesetOptions } from '../replay/rulesets.ts';
import { createInitialPlayerSummary, preparePlaybackChart, type PreparedPlaybackChartData } from './bootstrap.ts';
import {
appendShadowedNoteTriggers,
collectRealtimeAudioTriggers,
createDebugActiveAudioEstimator,
} from './engine-audio.ts';
import { createAudioPlaybackClockSource, type PlaybackClock, type PlaybackClockSource } from './engine-clock.ts';
import { createJudgeEffectHandler } from './engine-effects.ts';
import { isLR2JudgeTimingAutoAdjust } from './judge-timing.ts';
import { createTempoClock, type TempoClock } from './tempo-clock.ts';
import {
collectRealtimeAudioVolumeEvents,
formatRandomPatternSummary,
initializePlaybackRuntimeResources,
reportLoadProgress,
reportResolvedRuleset,
resolveAudioBackendLabel,
resolveEngineChart,
resolvePlayerChart,
} from './engine-preparation.ts';
import {
createNoopPlaybackEventTracer,
createNoTUIPlaybackEventTracer,
createNoTUIPlaybackStateLogger,
emitPlayerLog,
resolveOutputWriter,
writePlayableSampleTriggerEventLog,
writeRealtimeTriggeredEventLog,
writeRealtimeVolumeEventLog,
type NoTUIPlaybackEventTracer,
} from './engine-trace.ts';
import type {
AudioSession,
CreatePlayerUIRuntimeContext,
PlayerInputRuntime,
PlayerOptions,
PlayerSummary,
PlayerUIRuntime,
} from './engine-types.ts';
import { createRealtimeAudioCursor, type RealtimeAudioCursor } from './play-audio-cursor.ts';
import { createChainSoundQueue, type ChainSoundQueue } from './chain-audio.ts';
import type { JudgeStrategy } from './play-strategy.ts';
import { resolvePracticePlayWindow } from './practice.ts';
/** A chart sound the realtime audio fires at its time. */
type TimedChartSound = { readonly event: BeMusicEvent; readonly seconds: number };
/** LR2 dispatches generated measure lines through bar 999, even beyond the last authored note. */
function isFinalReversalEvent(chart: ResolvedChart, reversal: TempoReversalPoint): boolean {
for (let measure = 999; measure >= 0; measure--) {
if (chart.timing.beatToSeconds(chart.beatResolver.measureToBeat(measure)) > reversal.seconds) return false;
}
let foundReversal = false;
for (const event of chart.sortedEvents) {
const seconds = chart.timing.eventToSeconds(event);
if (seconds < reversal.seconds) continue;
Iif (seconds > reversal.seconds) return false;
const channel = event.channel.toUpperCase();
Iif (['01', '02', '03', '04', '06', '07', '0A'].includes(channel)) continue;
if (channel !== '08' || foundReversal) return false;
const value = chart.source.resources.bpm[normalizeObjectKey(event.value, chart.idBase)] ?? -1;
if (Math.trunc(value) < 0) foundReversal = true;
}
return foundReversal;
}
async function reversalSongEnd(
chart: ResolvedChart,
playback: PreparedPlaybackChartData,
auto: boolean,
options: PlayerOptions,
): Promise<number> {
if (isFinalReversalEvent(chart, chart.reversal!)) return -Infinity;
let end = 0;
for (const note of playback.notes) end = Math.max(end, (note.endSeconds ?? note.seconds) + 2);
for (const mine of playback.landmineNotes) end = Math.max(end, mine.seconds + 2);
const durations = auto
? await options.loadAudioSampleDurations?.(chart, { baseDir: options.audioBaseDir, signal: options.signal })
: undefined;
for (const trigger of chart.sampleTriggers) {
if (trigger.channel === '01' || (auto && !isInvisibleNoteChannel(trigger.channel))) {
end = Math.max(end, trigger.seconds + (durations?.get(trigger.sampleKey) ?? 0));
}
}
if (auto) for (const cues of [chart.bga.base, chart.bga.layer]) end = Math.max(end, cues.at(-1)?.seconds ?? 0);
return end;
}
/**
* A play session: everything a play is set up with before its loop runs — the chart resolved for play, the tempo clock,
* the ruleset, the score, the replay recorder, the UI / input buses and runtimes, the audio session, the no-TUI
* trace and the realtime audio. The same for every judge strategy.
*/
export interface PlaySession {
readonly options: PlayerOptions;
readonly strategy: JudgeStrategy;
readonly writeOutput: (text: string) => void;
/** The chart after control flow, as the engine plays it. */
readonly resolvedJSON: BeMusicJSON;
readonly resolvedChart: ResolvedChart;
readonly reversalAnchor?: TempoReversalPoint;
/** LR2 checks this deadline once, immediately after dispatching the reversing event. */
readonly reversalEndSeconds?: number;
readonly playbackChart: PreparedPlaybackChartData;
readonly randomPatternSummary: string | undefined;
readonly ruleset: RulesetConfig;
/** The score and gauge every judgment goes through; `score.summary` is the play's summary. */
readonly score: JudgeCoreScore;
readonly summary: PlayerSummary;
/** Chart seconds the play lasts: its last note or sound, or the UI runtime's own end. */
readonly totalSeconds: number;
readonly speed: number;
readonly chartBaseSpeed: number;
/** HIGH-SPEED at the start of the play. */
readonly highSpeed: number;
/** The play tempo over the play clock: `speed` at the start, re-anchored by every tempo change. */
readonly tempoClock: TempoClock;
readonly leadInMs: number;
/** The chart second the play starts at (`PlayerOptions.startAtSeconds`, its first seek): 0 unless asked for later. */
readonly startAtSeconds: number;
/** Where a looping PRACTICE play goes back to (`restartPractice`): its start, unless the first round led in earlier. */
readonly practiceLoopStartSeconds: number;
readonly audioOffsetMs: number;
readonly beatAtSeconds: (seconds: number) => number;
readonly idBase: 36 | 62;
readonly wavResources: Readonly<Record<string, string>>;
/** AUTO SCRATCH in a manual play: the judge plays the scratch lanes. */
readonly autoScratch: boolean;
/** ANY KEY in a manual play: the judge routes each press to the nearest note on any lane. */
readonly anyKey: boolean;
readonly endOnFailure: boolean;
/** The play re-drives a recorded play (`PlayerOptions.replayInputs`). */
readonly replay: boolean;
readonly replayRecorder: ReplayRecorder | undefined;
readonly stateSignals: PlayerStateSignals;
readonly uiSignals: PlayerUISignalBus;
readonly inputSignals: PlayerInputSignalBus;
readonly uiRuntime: PlayerUIRuntime | undefined;
readonly uiEnabled: boolean;
/** The state signals while a UI runtime shows them. */
readonly activeStateSignals: PlayerStateSignals | undefined;
readonly audioSession: AudioSession | undefined;
readonly inputRuntime: PlayerInputRuntime | undefined;
readonly tracer: NoTUIPlaybackEventTracer;
readonly stateLogger: PlaybackStateLogger;
readonly publishUIFrame: (seconds: number, beat: number) => void;
readonly keyBoundBGA?: KeyBoundBGAController;
readonly bmsonBGA?: BmsonBGAController;
readonly chartText?: ChartTextController;
readonly chartOptions: ChartOptionProgram;
/** The judge supplies HCN display facts from its existing state; no second simulation. */
readHCNLanes?: (seconds: number) => readonly PlayerHCNLaneState[];
/** Maps the judge's effects onto audio, the UI buses, the replay and the trace. */
readonly applyJudgeEffect: JudgeCoreEffectSink;
/** Ends a judging pass of a manual play: LR2's automatic judge timing steps here (`JudgeEffectHandler`). */
readonly settleJudgeTiming: () => void;
/**
* Queues a realtime sound due at chart second `seconds` to the audio session: at its due time on the output clock when
* the session schedules ahead (`AudioSession.scheduleEventAt`), otherwise at once (`triggerEvent`).
*/
readonly queueAudioEvent: (event: BeMusicEvent, seconds: number) => void;
/** The chart's volume changes (`#97` / `#98`), queued against the audio write head. */
readonly volumeChanges: RealtimeAudioCursor<TimedChartSound>;
/** The chart's background sounds, queued against the audio write head. */
readonly backgroundAudio: RealtimeAudioCursor<TimedChartSound>;
/** LRX chain notes a press queued (`chain-audio.ts`), fired against the play clock. */
readonly chainSounds: ChainSoundQueue;
/** What the play clock runs on: the audio session's output clock, or the engine scheduler's. */
readonly clockSource: PlaybackClockSource;
/** The play clock, from the moment the chart starts (after the lead-in). */
clock: PlaybackClock | undefined;
/** The seek generation: one more for every seek applied (`play-seek.ts`); a play that sought records no replay. */
seekGeneration: number;
/** Puts the score, the gauge and the combos back to the play's start, in place (a seek rebuilds from there). */
readonly resetScore: () => void;
/** The 2P player of a two-player play (`battleMode: 'TWO-PLAYER'`); the session's own score is the 1P player's. */
readonly secondPlayer?: SecondPlayer;
}
/** The UI runtime's label for the mode. */
function uiModeLabel(strategy: JudgeStrategy, autoScratch: boolean): CreatePlayerUIRuntimeContext['mode'] {
if (strategy.mode === 'auto') return 'AUTO';
return autoScratch ? 'AUTO SCRATCH' : 'MANUAL';
}
/** Sets a play up: resolves its chart, builds its judging setup and starts its runtimes (not the play itself). */
export async function createPlaySession(
json: BeMusicJSON,
options: PlayerOptions,
strategy: JudgeStrategy,
): Promise<PlaySession> {
// Effective calibration is local to this run, even when the caller reuses or freezes its settings.
options = { ...options };
options.scrollModifier ??= options.preparedChart?.scrollModifierApplied;
options.scrollSection ??= options.preparedChart?.scrollSection;
options.scrollRate ??= options.preparedChart?.scrollRate;
options.sevenToNinePattern ??= options.preparedChart?.sevenToNinePattern;
options.sevenToNineType ??= options.preparedChart?.sevenToNineType;
options.hRandomThresholdBPM ??= options.preparedChart?.sevenToNineThresholdBPM;
const { mode } = strategy;
if (options.practice !== undefined) assertPracticeOptions(options);
throwIfAborted(options.signal);
const writeOutput = resolveOutputWriter(options);
reportLoadProgress(options, 0.02, 'Resolving chart...');
const controlFlowResolution = resolvePlayerChart(json, options);
const resolvedJSON = controlFlowResolution.resolvedJSON;
options.onResolvedChart?.(resolvedJSON);
const randomPatternSummary = formatRandomPatternSummary(controlFlowResolution.randomPatterns);
const scratchSides = resolveAutoScratchSides(options);
const autoScratch = mode === 'manual' && (scratchSides.autoScratch1P || scratchSides.autoScratch2P);
const anyKey = mode === 'manual' && options.anyKey === true;
const playerSpeed = options.speed ?? 1;
const leadInMs = options.leadInMs ?? 1500;
const audioOffsetMs = options.audioOffsetMs ?? 0;
const replay = options.replayInputs !== undefined;
let resolvedChart = options.preparedChart?.resolvedChart ?? resolveEngineChart(resolvedJSON, options);
// A host providing the effective program also supplies its player options through recordReplay.
const chartPlay =
options.chartPlayOptionProgram !== undefined
? { program: structuredClone(options.chartPlayOptionProgram), diagnostics: [], playerOptions: undefined }
: resolveChartPlayProgram(
compileChartPlayOptions(buildChartOptionTimeline(resolvedChart.source, resolvedChart.timing)),
options.playerChartPlayOptions,
{
playVariant: resolvedChart.playVariant,
course: options.course !== undefined,
},
);
const chartPlayOptions = chartPlay.program;
const playerChartPlayOptions = chartPlay.playerOptions;
const chartBaseSpeed = chartPlayOptions.options.baseSpeed ?? 1;
const speed = playerSpeed * chartBaseSpeed;
const tempoClock = createTempoClock(speed);
// Without a host-prepared chart (the terminal) the engine applies the chart's ADDMINE and arrangement itself, in place
// of the player's options, as the browser host does (#932). A replay's recorded notes already hold them.
const preparesChartPlayOptions = options.preparedChart === undefined && !replay;
if (preparesChartPlayOptions && chartPlayOptions.options.addMine === true)
options.mineModifier = resolveChartAddMineModifier(chartPlayOptions);
// Dynamic `#EXRANKxx` changes are a chart fact, recorded whatever the ruleset: LR2 applies them, while beatoraja and
// That-Which-Must-Not-Be-Named keep their initial windows (their `windowsAt` ignores the timeline). A log played under one ruleset can then
// be re-simulated under LR2 with the windows LR2 would have used.
const judgeRankChanges = resolvedChart.judgeRank.changes;
const volumeEvents = collectRealtimeAudioVolumeEvents(resolvedChart);
// Background audio: every sound that is not a play lane's — a play lane's keysound is the judge strategy's to play
// (on the player's press, or AUTO play's own note keysounds).
let backgroundTriggers = collectRealtimeAudioTriggers(resolvedChart, (channel) => !isPlayLaneSoundChannel(channel));
const realtimeAudioEndSeconds =
options.audio === false ? 0 : Math.max(backgroundTriggers.at(-1)?.seconds ?? 0, volumeEvents.at(-1)?.seconds ?? 0);
// Prefer the host-provided `preparedChart` over running our own extract pass. See `PlayerOptions.preparedChart`
// for the why — sharing the playable / landmine / invisible note arrays with the renderer eliminates a whole
// class of "view and engine each ran `extractTimedNotes` with subtly different arguments and the parallel
// arrays drifted" bugs.
const playbackChart =
options.preparedChart ??
preparePlaybackChart(
resolvedChart,
{
laneModeExtension: options.laneModeExtension,
longNoteModifier: options.longNoteModifier,
longNoteRate: options.longNoteRate,
battleMode: options.battleMode,
dBattleScratch: options.dBattleScratch,
practice: options.practice,
judgeRuleset: options.judgeRuleset,
autoScratch: options.autoScratch,
autoScratch1P: options.autoScratch1P,
autoScratch2P: options.autoScratch2P,
lr2ExtraMode: options.lr2ExtraMode,
lr2ExtraLevel: options.lr2ExtraLevel,
lr2Mania: options.lr2Mania,
speed: options.speed,
course: options.course,
extraNoteDepth: options.extraNoteDepth,
extraNoteScratch: options.extraNoteScratch,
longNoteModifierPlacements: options.longNoteModifierPlacements,
mineModifier: options.mineModifier,
mineModifierPlacements: options.mineModifierPlacements,
scrollModifier: options.scrollModifier,
scrollSection: options.scrollSection,
scrollRate: options.scrollRate,
scrollModifierTimeline: options.scrollModifierTimeline,
chartNotes: chartPlayOptions.options.notes,
chartNotesLegacy: isLegacyChartPlayOptionProgram(chartPlayOptions),
},
realtimeAudioEndSeconds,
Math.random,
);
if (preparesChartPlayOptions && chartPlayOptions.options.random !== undefined)
arrangeChartPlayLanes(
[playbackChart.notes, playbackChart.landmineNotes, playbackChart.invisibleNotes],
chartPlayOptions.options.random,
playbackChart.resolvedChart.playVariant,
Math.random,
);
resolvedChart = playbackChart.resolvedChart;
// PRACTICE starts at the head of the bar before its range's (#954; beatoraja's `starttimeoffset` is 1000 ms).
const requestedStartAtSeconds =
options.startAtSeconds ??
(options.practice !== undefined
? (playbackChart.practicePlayStartSeconds ??
resolvePracticePlayWindow(resolvedChart, options.practice, {
startMs: Math.max(0, Math.trunc(options.practice.startMs)),
endMs: Math.max(0, Math.trunc(options.practice.startMs)) + 1000,
}).firstStartSeconds)
: 0);
const startAtSeconds =
Number.isFinite(requestedStartAtSeconds) && requestedStartAtSeconds > 0 ? requestedStartAtSeconds : 0;
const practiceLoopStartSeconds =
options.startAtSeconds === undefined && playbackChart.practiceLoopStartSeconds !== undefined
? Math.max(0, playbackChart.practiceLoopStartSeconds)
: startAtSeconds;
backgroundTriggers = collectRealtimeAudioTriggers(resolvedChart, (channel) => !isPlayLaneSoundChannel(channel));
// An LRX chain note tied to a note sounds after the press that sounds that note (`chainSounds`), not at its own time.
// AUTO play sounds every note at its time, which puts each chain note at its own time: it stays background audio.
if (mode !== 'auto') {
const chained = new Set(resolvedChart.notes.flatMap((note) => note.chainSounds?.map((sound) => sound.event) ?? []));
if (chained.size > 0) backgroundTriggers = backgroundTriggers.filter((trigger) => !chained.has(trigger.event));
}
const battleRequested = options.battleMode ?? playbackChart.battleMode ?? 'OFF';
// A chart that copies itself onto the 2P side replaced the player's battle conversion (#932).
const expectedBattle = chartNotesCopies(playbackChart.chartNotes)
? 'OFF'
: resolveEffectiveBattleMode(
battleRequested,
options.judgeRuleset ?? 'lr2',
playbackChart.battleSourceVariant ?? resolvedChart.playVariant,
options.course !== undefined,
resolvedChart.sourceFormat === 'bms' ? resolvedChart.source.bms.player : undefined,
);
if ((playbackChart.battleMode ?? 'OFF') !== expectedBattle)
throw new RangeError('The shared prepared chart must include the selected battle mode.');
const lr2ExtraRequested = options.lr2ExtraMode ?? playbackChart.lr2ExtraMode ?? false;
if ((playbackChart.lr2ExtraMode ?? false) !== (lr2ExtraRequested && options.course === undefined))
throw new RangeError('The shared prepared chart must include the selected LR2 EXTRA mode.');
if (lr2ExtraRequested && options.lr2ExtraLevel !== undefined && playbackChart.lr2ExtraLevel !== options.lr2ExtraLevel)
throw new RangeError('The shared prepared chart must include the selected LR2 EXTRA level.');
if (!options.preparedChart && (options.sevenToNinePattern !== undefined || options.sevenToNineType !== undefined))
applySevenToNine(playbackChart, options);
Iif (
options.preparedChart &&
((options.sevenToNinePattern !== undefined &&
options.sevenToNinePattern !== (playbackChart.sevenToNinePattern ?? 0)) ||
(options.sevenToNineType !== undefined && options.sevenToNineType !== (playbackChart.sevenToNineType ?? 0)) ||
(options.hRandomThresholdBPM !== undefined &&
options.hRandomThresholdBPM !== (playbackChart.sevenToNineThresholdBPM ?? 120)))
)
throw new RangeError('Prepared 7-to-9 conversion does not match selected options.');
resolvedChart = playbackChart.resolvedChart;
const compiledOptions =
options.chartOptionProgram === undefined
? compileChartOptions(buildChartOptionTimeline(resolvedChart.source, resolvedChart.timing))
: { program: structuredClone(options.chartOptionProgram), diagnostics: [] };
const chartOptions = compiledOptions.program;
const chartJudge = resolveChartJudgeOption(chartPlayOptions);
for (const diagnostic of [
...compiledOptions.diagnostics,
...chartPlay.diagnostics,
...(options.chartOptionDiagnostics ?? []),
])
emitPlayerLog(options, 'warn', 'chart.option', { ...diagnostic });
const extraDepth = clampExtraNoteDepth(options.extraNoteDepth ?? playbackChart.extraNoteDepth ?? 0);
const extraScratch = options.extraNoteScratch ?? playbackChart.extraNoteScratch ?? false;
if ((playbackChart.extraNoteDepth ?? 0) !== extraDepth || (playbackChart.extraNoteScratch ?? false) !== extraScratch)
throw new RangeError('The shared prepared chart must include the selected EXTRA note options.');
const beatAtSeconds = createBeatAtSecondsResolverFromTimingResolver(resolvedChart.timing);
const reversal = resolvedChart.reversal;
const reversalEndSeconds =
reversal && !replay && !options.practice
? await reversalSongEnd(resolvedChart, playbackChart, mode === 'auto', options)
: undefined;
const activationSeconds = replay
? options.replayReversalActivationUs === undefined
? reversal?.seconds
: options.replayReversalActivationUs / 1e6
: undefined;
const reversalAnchor =
reversal === undefined
? undefined
: {
seconds: activationSeconds ?? Infinity,
beat: activationSeconds === undefined ? reversal.beat : beatAtSeconds(activationSeconds),
};
Iif ((options.scrollModifier ?? 'OFF') !== (playbackChart.scrollModifierApplied ?? 'OFF'))
throw new RangeError('The shared prepared chart must include the selected scroll modifier.');
Iif (
options.longNoteModifier?.startsWith('ADD_') &&
playbackChart.longNoteModifierApplied !== options.longNoteModifier
)
throw new RangeError('The shared prepared chart must include the selected long-note modifier.');
// Long-note addition builds a chart and is offered under every judge ruleset (#774): the added long notes are judged
// as the ruleset's long notes, so ADD CN / ADD HCN keep their CN / HCN distinction only under beatoraja rules.
Iif (options.mineModifier?.startsWith('ADD_') && playbackChart.mineModifierApplied !== options.mineModifier)
throw new RangeError('The shared prepared chart must include the selected mine modifier.');
if (options.mineModifier === 'REMOVE') {
const removed = playbackChart.landmineNotes.length;
playbackChart.mineModifierChangeCount = (playbackChart.mineModifierChangeCount ?? 0) + removed;
// Keep the shared array identity when the host prepared the chart before choosing REMOVE.
playbackChart.landmineNotes.length = 0;
}
// BMS duplicate keysounds play as BGM. bmson layers belong to the judged note's input instead.
if (resolvedJSON.sourceFormat !== 'bmson')
appendShadowedNoteTriggers(backgroundTriggers, resolvedChart, playbackChart.shadowedNotes);
// Constant for the whole play and read on every tick and judgment: hoisted out of the hot paths.
const idBase = resolveBMSBase(resolvedJSON);
const wavResources = resolvedJSON.resources.wav;
// The gauge the play runs on and the replay records: one value, so a re-simulation runs the same gauge. A host that
// only declared it for the log (`recordReplay.gauge`) gets it played too.
// A chart's GAMELEVEL / EXTRA (#845) wins over the player's gauge pick, outside a course (which keeps its course gauge),
// PRACTICE (which sets its own) and a replay (whose recorded gauge already is the one played).
const chartGauge =
options.course === undefined && options.practice === undefined && !replay
? resolveChartGaugeType(
compileChartGaugeOptions(buildChartOptionTimeline(resolvedChart.source, resolvedChart.timing)),
options.judgeRuleset ?? 'lr2',
)
: undefined;
const selectedGauge = chartGauge ?? options.gauge ?? options.recordReplay?.gauge;
Iif (
options.judgeAlgorithm !== undefined &&
options.judgeAlgorithm !== 'combo' &&
options.judgeRuleset !== 'beatoraja'
) {
throw new RangeError('Selectable judgment algorithms belong to beatoraja 0.8.9.');
}
// Two players judge one side each: each side's notes make its own judgment count and TOTAL.
const twoPlayer = playbackChart.battleMode === 'TWO-PLAYER' || playbackChart.battleMode === 'COUPLE';
const factsChart = twoPlayer ? selectPlaybackChartSide(playbackChart, 1) : playbackChart;
// The notes AUTO SCRATCH plays, for a ruleset that leaves them out of the count (plugout).
const autoScratchChannels = autoScratch
? resolveAutoScratchChannels(
options,
playbackChart.laneBindings.filter((binding) => binding.isScratch).map((binding) => binding.channel),
)
: undefined;
const ruleset = resolveRuleset(
rulesetChartFactsFromChart(resolvedJSON, factsChart, judgeRankChanges, options.stageRanks),
options.judgeRuleset ?? 'lr2',
{
...(autoScratchChannels !== undefined && autoScratchChannels.size > 0
? {
autoScratchNotes: countRulesetNotesOf(
factsChart.scorableNotes.filter((note) => autoScratchChannels.has(note.channel)),
resolvedChart.lnMode,
),
}
: {}),
...uncountedNotesOption(factsChart.scorableNotes, autoScratchChannels, resolvedChart.lnMode),
...(options.judgeAlgorithm !== undefined ? { judgeAlgorithm: options.judgeAlgorithm } : {}),
bmsonTotalMode: options.bmsonTotalMode,
...(options.customJudge !== undefined ? { customJudge: options.customJudge } : {}),
...(options.lr2Gambol === 1 || options.lr2Gambol === 2 ? { lr2Gambol: options.lr2Gambol } : {}),
...(options.practice !== undefined
? {
practice: {
sourceNotes: playbackChart.practiceSourceNotes ?? { normal: 0, long: { 1: 0, 2: 0, 3: 0 } },
gauge: options.practice.gauge,
startGauge: options.practice.startGauge,
...(options.practice.gaugeCategory !== undefined
? { gaugeCategory: options.practice.gaugeCategory }
: {}),
...(options.practice.total !== undefined ? { total: options.practice.total } : {}),
...(options.practice.judgeRank !== undefined ? { judgeRank: options.practice.judgeRank } : {}),
},
}
: {}),
...(selectedGauge !== undefined ? { selectedGauge } : {}),
...(options.bottomShiftableGauge !== undefined ? { bottomShiftableGauge: options.bottomShiftableGauge } : {}),
...(options.gaugeAutoShift !== undefined ? { gaugeAutoShift: options.gaugeAutoShift } : {}),
...(options.judgeWindowMs !== undefined ? { judgeWindowOverrideMs: options.judgeWindowMs } : {}),
...(options.course !== undefined ? { course: courseStageRulesetOptions(options.course) } : {}),
...chartJudge,
},
);
reportResolvedRuleset(options, ruleset);
const endOnFailure = resolveGaugeEndOnFailure(
options.gaugeAutoShift,
options.endOnFailure,
options.course === undefined ? ruleset.gaugeSource : undefined,
);
const courseCarry = options.course !== undefined ? courseStageCarryCombo(options.course) : undefined;
const { score, summary, resetScore: resetPrimaryScore } = createPlayerScore(ruleset, courseCarry);
const secondPlayer = twoPlayer
? createSecondPlayer(
resolvedJSON,
playbackChart,
judgeRankChanges,
options,
selectedGauge,
chartGauge,
chartJudge,
autoScratchChannels,
resolvedChart.lnMode,
)
: undefined;
if (secondPlayer !== undefined) summary.secondPlayer = secondPlayer.summary;
const resetScore = (): void => {
resetPrimaryScore();
secondPlayer?.resetScore();
};
// The source saves nothing from PRACTICE.
const replayRecorder =
options.onReplayRecorded && options.practice === undefined
? (() => {
const { chartSHA256, chartMD5, recorder, sourceChart, includeDeviceNames, ...hostPlaySettings } =
options.recordReplay ?? {};
return createReplayRecorder({
json: resolvedJSON,
chartOptions,
chartPlayOptions,
// The native result carries the score whenever the ruleset has one of its own (LR2's, plugout's).
moneyScore: ruleset.moneyScore || ruleset.plugoutScore === true,
chart: playbackChart,
chartSHA256,
chartMD5,
recorder,
...(includeDeviceNames === true ? { includeDeviceNames: true } : {}),
laneModeExtension: options.laneModeExtension,
// The chart the engine was handed is the source when it resolved the control flow itself.
sourceChart: sourceChart ?? json,
dynamicJudgeRankChanges: judgeRankChanges,
...(options.stageRanks !== undefined ? { stageRanks: options.stageRanks } : {}),
reversalSeconds: resolvedChart.reversal?.seconds,
play: {
mode,
autoScratch,
judgeAlgorithm: ruleset.rulesetId === 'beatoraja' ? (options.judgeAlgorithm ?? 'combo') : undefined,
...(options.bmsonTotalMode !== undefined ? { bmsonTotalMode: options.bmsonTotalMode } : {}),
...(options.customJudge !== undefined ? { customJudge: { ...options.customJudge } } : {}),
...(options.lr2Gambol === 1 || options.lr2Gambol === 2 ? { lr2Gambol: options.lr2Gambol } : {}),
longNoteModifier: options.longNoteModifier,
...(options.autoScratch1P !== undefined || options.autoScratch2P !== undefined
? {
autoScratch1P: mode === 'manual' && scratchSides.autoScratch1P,
autoScratch2P: mode === 'manual' && scratchSides.autoScratch2P,
}
: {}),
...(anyKey ? { anyKey: true } : {}),
judgeWindowOverrideMs: options.judgeWindowMs,
judgeRuleset: options.judgeRuleset,
...(options.randomDraws !== undefined ? { randomDraws: options.randomDraws } : {}),
...(options.course !== undefined ? { course: options.course } : {}),
...(playerChartPlayOptions !== undefined ? { playerChartPlayOptions } : {}),
...hostPlaySettings,
...(options.scrollModifier !== undefined
? {
scrollModifier: options.scrollModifier,
scrollModifierChanged: playbackChart.scrollModifierChanged ?? false,
...(options.scrollModifier === 'ADD'
? {
scrollSection: playbackChart.scrollSection,
scrollRate: playbackChart.scrollRate,
scrollModifierTimeline: playbackChart.scrollModifierTimeline,
}
: {}),
// SOFTLANDING's drawn factors, which a replay plays back instead of drawing again.
...(isSoftLanding(options.scrollModifier)
? { scrollModifierTimeline: playbackChart.scrollModifierTimeline }
: {}),
}
: {}),
...(options.judgeTimingMs !== undefined || options.judgeTimingAutoAdjust !== undefined
? {
options: {
...hostPlaySettings.options,
judgeTimingAutoAdjust: options.judgeTimingAutoAdjust ?? 'OFF',
judgeTimingMs: options.judgeTimingMs ?? 0,
},
}
: {}),
...(options.mineModifier !== undefined
? {
mineModifier: options.mineModifier,
mineModifierChangeCount: playbackChart.mineModifierChangeCount ?? 0,
}
: {}),
...(playbackChart.sevenToNinePattern !== undefined
? {
sevenToNinePattern: playbackChart.sevenToNinePattern,
sevenToNineType: playbackChart.sevenToNineType,
sevenToNineThresholdBPM: playbackChart.sevenToNineThresholdBPM,
sevenToNineApplied: playbackChart.sevenToNineApplied,
}
: {}),
...(options.battleMode !== undefined || playbackChart.battleMode !== undefined
? {
battleMode: playbackChart.battleMode ?? 'OFF',
battleSourceVariant: playbackChart.battleSourceVariant ?? playbackChart.resolvedChart.playVariant,
battleTempo: playbackChart.battleTempo ?? 1,
battleAssist1P: playbackChart.battleAssist1P ?? false,
battleAssist2P: playbackChart.battleAssist2P ?? false,
battleChangedObjectCount: playbackChart.battleChangedObjectCount ?? 0,
battleDroppedObjectCount: playbackChart.battleDroppedObjectCount ?? 0,
...(playbackChart.dBattleScratch !== undefined
? { dBattleScratch: playbackChart.dBattleScratch }
: {}),
}
: {}),
...(playbackChart.lr2Mania !== undefined ? { lr2Mania: playbackChart.lr2Mania } : {}),
...(options.lr2ExtraMode !== undefined || playbackChart.lr2ExtraMode !== undefined
? {
lr2ExtraMode: playbackChart.lr2ExtraMode ?? false,
lr2ExtraLevel: playbackChart.lr2ExtraLevel ?? 0,
lr2ExtraEffectiveLevel: playbackChart.lr2ExtraEffectiveLevel ?? 0,
lr2ExtraConvertedObjectCount: playbackChart.lr2ExtraConvertedObjectCount ?? 0,
lr2ExtraTempo: playbackChart.lr2ExtraTempo ?? 1,
}
: {}),
...(options.extraNoteDepth !== undefined ||
options.extraNoteScratch !== undefined ||
playbackChart.extraNoteDepth !== undefined
? {
extraNoteDepth: playbackChart.extraNoteDepth ?? 0,
extraNoteScratch: playbackChart.extraNoteScratch ?? false,
extraNoteChangeCount: playbackChart.extraNoteChangeCount ?? 0,
}
: {}),
...(options.longNoteModifier?.startsWith('ADD_')
? { longNoteRate: playbackChart.longNoteModifierRate ?? 1 }
: {}),
// The count tells a chart the modifier changed from one it left alone: LEGACY NOTE and LN REMOVE assist
// only an actual conversion, as the additions do.
...(options.longNoteModifier !== undefined && options.longNoteModifier !== 'OFF'
? { longNoteModifierChangeCount: playbackChart.longNoteModifierChangeCount ?? 0 }
: {}),
gaugeAutoShift: options.gaugeAutoShift,
...(options.bottomShiftableGauge !== undefined
? { bottomShiftableGauge: options.bottomShiftableGauge }
: {}),
endOnFailure: endOnFailure ? true : undefined,
gauge: selectedGauge,
// The tempo a live play ran at (its inputs are in chart time either way). A replay's `speed` only sets how
// fast it is re-driven, so it records none.
...(playerSpeed !== 1 && !replay ? { tempo: playerSpeed } : {}),
},
});
})()
: undefined;
const highSpeed = resolveHighSpeedMultiplier(options.highSpeed);
const stateSignals = createPlayerStateSignals(highSpeed);
const { landmineNotes, invisibleNotes, renderNotes, laneBindings, laneDisplayMode, inputTokenToChannels } =
playbackChart;
const finalOptionCue = chartOptions.cues
.filter((cue) => cue.timeUs <= (resolvedChart.reversal?.seconds ?? Infinity) * 1_000_000)
.at(-1);
// An LRX chart ends where plugout ends it, option text or not.
const textExtendsEnd = options.practice === undefined && playbackChart.fixedEnd !== true;
let textPlaybackEndSeconds = textExtendsEnd && finalOptionCue ? finalOptionCue.timeUs / 1_000_000 + 1 : 0;
for (const stage of textExtendsEnd ? (options.chartTextStages ?? []) : []) {
const last = stage.timeline.cues.filter((cue) => cue.seconds <= (stage.freezeSeconds ?? Infinity)).at(-1);
Eif (last)
textPlaybackEndSeconds = Math.max(
textPlaybackEndSeconds,
Math.min(stage.endSeconds, stage.offsetSeconds + (last.seconds + 1) / stage.rate),
);
}
const uiSignals = createPlayerUISignalBus({
currentBeat: 0,
currentSeconds: 0,
totalSeconds: Math.max(playbackChart.totalSeconds, textPlaybackEndSeconds),
summary,
notes: renderNotes,
landmineNotes,
invisibleNotes,
});
const inputSignals = createPlayerInputSignalBus();
const { uiRuntime, totalSeconds, uiEnabled, activeStateSignals, audioSession } =
await initializePlaybackRuntimeResources({
resolvedJSON,
resolvedChart,
options,
mode: uiModeLabel(strategy, autoScratch),
laneDisplayMode,
laneBindings,
speed,
// The BAD gate as a single width, for the host's judge-window readout.
judgeWindowMs: mode === 'auto' ? 0 : judgeWindowLateReachUs(ruleset.windows.note) / 1000,
highSpeed,
randomPatternSummary,
stateSignals,
uiSignals,
totalSeconds: Math.max(playbackChart.totalSeconds, textPlaybackEndSeconds),
fixedEnd: playbackChart.fixedEnd === true,
audioMode: mode,
});
const inputRuntime = options.createInputRuntime?.({ mode, inputSignals, inputTokenToChannels });
const tracer = uiEnabled
? createNoopPlaybackEventTracer()
: createNoTUIPlaybackEventTracer({
resolved: resolvedChart,
writeOutput,
judgeWindowMs: options.judgeWindowMs,
});
const stateLogger = uiEnabled
? createNoopPlaybackStateLogger()
: createNoTUIPlaybackStateLogger({ writeOutput, summary, base: idBase });
throwIfAborted(options.signal);
const audioBackendLabel = resolveAudioBackendLabel(options, audioSession);
let activeAudioEstimator: Awaited<ReturnType<typeof createDebugActiveAudioEstimator>> | undefined;
if (strategy.estimatesActiveAudio) {
activeAudioEstimator = options.debugActiveAudio
? await createDebugActiveAudioEstimator(resolvedChart, {
baseDir: options.audioBaseDir,
signal: options.signal,
loadSampleDurations: options.loadAudioSampleDurations,
})
: undefined;
throwIfAborted(options.signal);
}
reportLoadProgress(options, 1, 'Ready');
options.onLoadComplete?.();
emitPlayerLog(options, 'info', 'playback.prepared', {
mode,
uiEnabled,
audioEnabled: audioSession !== undefined,
totalSeconds,
});
const clockSource = createAudioPlaybackClockSource(audioSession);
// `session` is returned below; the frames read its clock and seek generation as they are published.
let session: PlaySession | undefined;
const keyBoundCues = options.keyBoundBGACues ?? buildKeyBoundBGATimeline(resolvedChart.source, resolvedChart.timing);
const assistedChannels = resolveAutoScratchChannels(
options,
playbackChart.laneBindings.filter((lane) => lane.isScratch).map((lane) => lane.channel),
);
const freezeSeconds = resolvedChart.reversal?.seconds ?? Infinity;
const keyBoundBGA =
keyBoundCues.length === 0
? undefined
: new KeyBoundBGAController(keyBoundCues, {
freezeSeconds,
inputs: [
...(options.replayInputs ?? []).map((input) => ({
seconds: input.timeUs / 1e6,
action: input.action,
channels: input.channels,
})),
...buildAutoKeyBoundBGAInputs(
playbackChart.scorableNotes.filter(
(note) => note.seconds <= freezeSeconds && (mode === 'auto' || assistedChannels.has(note.channel)),
),
),
],
});
const bmsonCues =
options.bmsonBGACues ??
buildBmsonBGAEventTimeline(resolvedChart.source, resolvedChart.timing, {
includeOrdinaryLayerClears: true,
});
const bmsonBGA = bmsonCues.length > 0 ? new BmsonBGAController(bmsonCues, freezeSeconds) : undefined;
const textTimeline = buildChartTextTimeline(resolvedChart.source, resolvedChart.timing);
const chartText =
options.chartTextStages !== undefined || textTimeline.cues.length || textTimeline.missText !== undefined
? new ChartTextController(textTimeline, freezeSeconds, options.chartTextStages)
: undefined;
const publishUIFrame = createUIFramePublisher({
uiEnabled,
uiSignals,
totalSeconds,
summary,
notes: renderNotes,
landmineNotes,
invisibleNotes,
audioBackend: audioBackendLabel,
...(secondPlayer !== undefined ? { summary2P: secondPlayer.summary } : {}),
...(bmsonBGA ? { resolveBmsonBGA: (seconds: number) => bmsonBGA.read(seconds) } : {}),
...(Object.keys(chartOptions.initial).length > 0 || chartOptions.cues.length > 0
? {
resolveChartOptions: (seconds: number) =>
resolveChartOptionsAt(chartOptions, Math.round(Math.min(seconds, freezeSeconds) * 1_000_000)),
}
: {}),
...(chartText ? { resolveChartText: (seconds: number) => chartText.read(seconds) } : {}),
resolveHCNLanes: (seconds) => session?.readHCNLanes?.(seconds),
...(keyBoundBGA ? { resolveKeyBoundBGA: (seconds: number) => keyBoundBGA.read(seconds) } : {}),
resolveJudgedNoteCount: () =>
Math.max(
0,
summary.perfect +
summary.great +
summary.good +
summary.bad +
summary.poor -
(ruleset.emptyPoorCountsInPoorDisplay ? summary.emptyPoor : 0) -
('minePoor' in summary && typeof summary.minePoor === 'number' ? summary.minePoor : 0),
),
resolveDebugActiveAudioState: (seconds) => {
Eif (options.debugActiveAudio !== true) {
return {};
}
const activeAudioFiles = audioSession?.getActiveAudioFiles?.() ?? [];
const activeAudioVoiceCount = audioSession?.getActiveAudioVoiceCount?.() ?? 0;
Iif (activeAudioEstimator === undefined || activeAudioVoiceCount > 0 || activeAudioFiles.length > 0) {
return { activeAudioFiles, activeAudioVoiceCount };
}
const estimated = activeAudioEstimator.resolve(seconds);
return {
activeAudioFiles: estimated?.activeAudioFiles ?? [],
activeAudioVoiceCount: estimated?.activeAudioVoiceCount ?? 0,
};
},
reversal: resolvedChart.reversal,
reversalAnchor,
resolveClock: (seconds) => {
const clock = session?.clock;
return {
generation: session?.seekGeneration ?? 0,
clock: {
outputSeconds:
(clock === undefined ? clockSource.nowMs() : clock.sourceMsAt(tempoClock.clockMsAt(seconds))) / 1000,
tempo: tempoClock.tempo,
paused: clock?.isPaused() ?? true,
},
};
},
});
const chainSounds = createChainSoundQueue((event, seconds) => {
Eif (!uiEnabled)
writePlayableSampleTriggerEventLog(writeOutput, event, seconds, wavResources, 'chain-note', '01', idBase);
audioSession?.triggerEvent?.(event);
});
const applyJudgeEffect = createJudgeEffectHandler({
chainSounds,
...(chartText ? { onChartTextInput: (input) => chartText.addInput(input) } : {}),
...(bmsonBGA ? { onBmsonBGAInput: (input) => bmsonBGA.addInput(input) } : {}),
...(keyBoundBGA && !replay
? {
onInput: (input: { seconds: number; action: 'down' | 'up'; channels: ReadonlySet<string> }) =>
keyBoundBGA.addInput({ seconds: input.seconds, action: input.action, channels: [...input.channels] }),
}
: {}),
judgeTiming: {
// Manual play only, under any judge rules; LR2 skips its own adjustment in a two-player BATTLE (`battle` 1).
mode:
mode !== 'manual' ||
options.replayInputs !== undefined ||
(twoPlayer && isLR2JudgeTimingAutoAdjust(options.judgeTimingAutoAdjust))
? 'OFF'
: (options.judgeTimingAutoAdjust ?? 'OFF'),
currentSeconds: () => (session?.clock ? tempoClock.chartSecondsAt(session.clock.nowMs()) : 0),
get value() {
return options.judgeTimingMs ?? 0;
},
set value(value: number) {
options.judgeTimingMs = value;
},
},
uiEnabled,
writeOutput,
wavResources,
idBase,
audioSession,
playbackStateLogger: stateLogger,
playbackEventTracer: tracer,
uiSignals,
activeStateSignals,
replayRecorder,
publishUIFrame,
beatAtSeconds,
});
// Realtime audio goes only to a session that takes it; without one nothing is queued (or traced).
const queuesAudio = audioSession?.triggerEvent !== undefined;
// The engine queues these as its write head reaches them; a session that schedules ahead gets each one's due time on
// its output clock, so it sounds when due rather than on the tick that reached it.
const queueAudioEvent = (event: BeMusicEvent, seconds: number): void => {
const clock = session?.clock;
if (clock !== undefined && audioSession?.scheduleEventAt !== undefined) {
audioSession.scheduleEventAt(event, clock.sourceMsAt(tempoClock.clockMsAt(seconds)) / 1000);
return;
}
audioSession?.triggerEvent?.(event);
};
const volumeChanges = createRealtimeAudioCursor(queuesAudio ? volumeEvents : [], (change) => {
if (!uiEnabled) {
writeRealtimeVolumeEventLog(writeOutput, change.seconds, change.event);
}
queueAudioEvent(change.event, change.seconds);
});
const backgroundAudio = createRealtimeAudioCursor(queuesAudio ? backgroundTriggers : [], (trigger) => {
if (!uiEnabled) {
writeRealtimeTriggeredEventLog(writeOutput, trigger, wavResources[trigger.sampleKey], 'realtime');
}
queueAudioEvent(trigger.event, trigger.seconds);
});
session = {
options,
strategy,
writeOutput,
resolvedJSON,
resolvedChart,
playbackChart,
randomPatternSummary,
ruleset,
score,
summary,
totalSeconds,
speed,
chartBaseSpeed,
highSpeed,
tempoClock,
leadInMs,
startAtSeconds,
practiceLoopStartSeconds,
audioOffsetMs,
beatAtSeconds,
idBase,
wavResources,
autoScratch,
anyKey,
endOnFailure,
replay,
replayRecorder,
stateSignals,
uiSignals,
inputSignals,
uiRuntime,
uiEnabled,
activeStateSignals,
audioSession,
inputRuntime,
tracer,
stateLogger,
publishUIFrame,
...(keyBoundBGA ? { keyBoundBGA } : {}),
...(bmsonBGA ? { bmsonBGA } : {}),
...(chartText ? { chartText } : {}),
chartOptions,
applyJudgeEffect,
settleJudgeTiming: () => applyJudgeEffect.settleJudgeTiming(),
queueAudioEvent,
volumeChanges,
backgroundAudio,
chainSounds,
clockSource,
clock: undefined,
reversalEndSeconds,
seekGeneration: 0,
resetScore,
reversalAnchor,
...(secondPlayer !== undefined ? { secondPlayer } : {}),
};
return session;
}
/** A player's score and gauge on `ruleset`, and how to put them back to the play's start. */
function createPlayerScore(
ruleset: RulesetConfig,
courseCarry: ReturnType<typeof courseStageCarryCombo> | undefined,
): { score: JudgeCoreScore; summary: PlayerSummary; resetScore: () => void } {
const { reset: resetSummary, ...initialSummary } = createInitialPlayerSummary(ruleset, ruleset.noteCount);
const score: JudgeCoreScore = {
...initialSummary,
scoreTracker: createScoreTracker({
moneyScore: ruleset.moneyScore,
plugoutScore: ruleset.plugoutScore === true,
...(courseCarry !== undefined ? { course: courseCarry } : {}),
}),
};
const summary: PlayerSummary = score.summary;
const tracker = score.scoreTracker;
// The summary reads the combos off the tracker the judges update, so it always shows the live ones.
Object.defineProperties(summary, {
combo: { get: () => tracker.combo, enumerable: true, configurable: true },
maxCombo: { get: () => tracker.maxCombo, enumerable: true, configurable: true },
});
if (tracker.course !== undefined) {
// The same object the tracker updates, so the summary always shows the live course combo.
summary.course = tracker.course;
}
return {
score,
summary,
resetScore: () => {
resetSummary();
tracker.combo = 0;
tracker.maxCombo = 0;
if (tracker.course !== undefined && courseCarry !== undefined) {
tracker.course.combo = courseCarry.combo;
tracker.course.maxCombo = Math.max(courseCarry.maxCombo, courseCarry.combo);
}
},
};
}
/** The 2P player of a two-player play: its own gauge (`gauge2P`) on its own side's notes. */
function createSecondPlayer(
resolvedJSON: BeMusicJSON,
playbackChart: PreparedPlaybackChartData,
judgeRankChanges: ResolvedChart['judgeRank']['changes'],
options: PlayerOptions,
selectedGauge: string | undefined,
chartGauge: string | undefined,
chartJudge: ReturnType<typeof resolveChartJudgeOption>,
autoScratchChannels: ReadonlySet<string> | undefined,
chartLNMode: ResolvedChart['lnMode'],
): SecondPlayer {
const gauge = chartGauge ?? options.gauge2P ?? selectedGauge;
const side = selectPlaybackChartSide(playbackChart, 2);
const autoScratchNotes = side.scorableNotes.filter((note) => autoScratchChannels?.has(note.channel) === true);
const ruleset = resolveRuleset(
rulesetChartFactsFromChart(resolvedJSON, side, judgeRankChanges),
options.judgeRuleset ?? 'lr2',
{
...(autoScratchNotes.length > 0 ? { autoScratchNotes: countRulesetNotesOf(autoScratchNotes, chartLNMode) } : {}),
...uncountedNotesOption(side.scorableNotes, autoScratchChannels, chartLNMode),
bmsonTotalMode: options.bmsonTotalMode,
...(gauge !== undefined ? { selectedGauge: gauge } : {}),
// Gauge auto-shift is the play's, so the second player's gauge shifts as the first's does (and as a replay of
// either side re-simulates it).
...(options.bottomShiftableGauge !== undefined ? { bottomShiftableGauge: options.bottomShiftableGauge } : {}),
...(options.gaugeAutoShift !== undefined ? { gaugeAutoShift: options.gaugeAutoShift } : {}),
...(options.judgeWindowMs !== undefined ? { judgeWindowOverrideMs: options.judgeWindowMs } : {}),
...chartJudge,
},
);
const { score, summary, resetScore } = createPlayerScore(ruleset, undefined);
return {
ruleset,
score,
summary,
resetScore,
endOnFailure: resolveGaugeEndOnFailure(
options.gaugeAutoShift,
options.endOnFailure,
options.course === undefined ? ruleset.gaugeSource : undefined,
),
...(gauge !== undefined ? { gauge } : {}),
};
}
/**
* PRACTICE is a single play without chart modifiers, under every ruleset (#933): beatoraja applies them only in PLAY /
* AUTOPLAY.
*/
function assertPracticeOptions(options: Readonly<PlayerOptions>): void {
Iif (options.course !== undefined) throw new RangeError('PRACTICE plays a single chart.');
Iif (
(options.battleMode ?? 'OFF') !== 'OFF' ||
(options.scrollModifier ?? 'OFF') !== 'OFF' ||
(options.longNoteModifier ?? 'OFF') !== 'OFF' ||
(options.mineModifier ?? 'OFF') !== 'OFF' ||
(options.extraNoteDepth ?? 0) > 0 ||
options.lr2ExtraMode === true
)
throw new RangeError('PRACTICE applies no chart modifier.');
}
/**
* The judged notes a play leaves out of plugout's note count (LRX chain notes that start their lane), as a ruleset
* option; none, or only those AUTO SCRATCH does not already leave out.
*/
function uncountedNotesOption(
notes: readonly TimedPlayableNote[],
autoScratchChannels: ReadonlySet<string> | undefined,
chartLNMode: ResolvedChart['lnMode'],
): { uncountedNotes?: ReturnType<typeof countRulesetNotesOf> } {
const uncounted = notes.filter(
(note) => note.event.lrx?.chain === true && autoScratchChannels?.has(note.channel) !== true,
);
return uncounted.length > 0 ? { uncountedNotes: countRulesetNotesOf(uncounted, chartLNMode) } : {};
}
|