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 | 44x 44x 44x 2x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 26x 26x 26x 26x 26x 26x 26x 26x 3x 3x 26x 26x 26x 26x 2x 1x 26x 3x 3x 23x 23x 23x 26x 26x 26x 26x 26x 26x 26x 26x 1x 26x 10x 10x 10x 10x 41x 10x 10x 12x 12x 11x 11x 11x 11x 11x 12x 12x 12x 12x 11x 11x 25x 12x 2x 2x 11x 10x 7x 11x 5x 12x 8x 6x 6x 6x 6x 6x 12x 21x 21x 21x 17x 17x 21x 3x 3x 13x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 5x 5x 5x 5x 5x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 4x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 249x 223x 249x 249x 86x 86x 16x 2x 55x 41x 14x 72x 72x 34x 34x 68x 68x 75x 75x 75x 2x 73x 109x 109x 71x 38x 38x 38x 324x 126x 12x 3x 3x 9x 2x 2x 643x 4x 639x 18x 4x 4x 5x 4x 4x 4x 4x 57x 57x 57x 13x 211x 211x 211x 135x 135x 135x 78x 78x 211x 137x 2x 33x 3x 3x 3x 44x 4x 87x 3x 84x | import { clampJudgeTimingMs, resolvePlayOptionValue } from '@be-music/player-scene-model';
/**
* The play session: one play's behaviour, whatever skin family draws it (ADR 0001). It composes the play's parts around
* one `PlayState` — the chart (`play-chart.ts`), the media (`play-media.ts`, through the audio service's play graph when
* the host gives one), the engine (`play-engine.ts`), the play's own input (`play-input.ts`), the view settings
* (`play-view-settings.ts`) and the ending (`play-ending.ts`) — and keeps the clocks, the pause, the recording and the
* result. Each part takes the session as its context.
*
* The session draws nothing. What it needs of the view that draws it — the timing of its intro and fade-out, the scene
* moments it animates against, the key-beam fade, the view's own loading and the GPU upload of the BGA — comes through
* {@link PlaySessionTheme}; the view's touch lanes come back as `lane` intents. `createPlayScene` (`host/play.ts`) pairs a session with the
* play view of the kit's family (built-in or LR2) and reads a `PlayFrame` off it every tick.
*/
import { compileChartGaugeOptions, mirrorBeatAtTempoReversal } from '@be-music/chart-model';
import { nonstopBPMAt } from '@be-music/player-engine/course';
import { DEFAULT_REPLAY_PLAYBACK_OPTIONS, type BeMusicReplay } from '@be-music/player-engine/replay';
import { resolveChartGaugeType, type GaugePick } from '@be-music/player-engine/ruleset';
import { createHiSpeedState, createPlayState, type LibraryChart, type PlayResult } from '@be-music/player-scene-model';
import type { BeMusicLongNote } from '@be-music/player-skin-sdk';
import type { Application, Texture } from 'pixi.js';
import type { BrowserAssetSource } from '../../collection/types.ts';
import { logger } from '../../logger.ts';
import { GameplayRecorder, type GameplayRecorderResult } from '../../recording/gameplay-recorder.ts';
import {
DEFAULT_RECORDING_QUALITY,
resolveRecordingBitrates,
type RecordingFormat,
type RecordingQuality,
} from '../../recording/recording-format.ts';
import {
sanitizeBusVolume,
type AudioBusChannel,
type CompressorParams,
type CompressorStage,
type TunableCompressor,
} from '../../runtime/audio-bus.ts';
import {
clampPlayTempo,
resolveReplayTempo,
supportsLiveTempoChange,
type ReplayTempo,
} from '../../runtime/play-tempo.ts';
import { NO_SKIN_ADJUST, type PlayDisposeOptions, type PlaySessionOptions, type SkinAdjust } from './play-options.ts';
import { resolveBeMusicLongNoteMode } from './long-note-tracker.ts';
import { FALLBACK_INTRO_DELAY_MS, KEY_ON_FADE_OUT_MS } from '../../stage/design.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import { LiveTempo } from './live-tempo.ts';
import { releaseTexturesOnHost } from '../../stage/pixi-utils.ts';
import { QuitHoldController } from './quit-hold.ts';
import type { BeMusicLaneCover } from '../../skin/be-music/types.ts';
import type { RuntimeNote } from '../../view/shared/playfield/context.ts';
import type { PlayViewTiming } from '../../view/types.ts';
import { prepareChart } from './play-chart.ts';
import { prepareGhost } from './ghost/prepare-ghost.ts';
import { toPlayOptionMismatch } from './play-option-mismatch.ts';
import { beginExitSequence, getResultData } from './play-ending.ts';
import { finishPlayOnExit, interruptSharedEngine, launchSharedEngine, stopSharedEngine } from './play-engine.ts';
import { chartSecondsFromFrame } from './play-clock.ts';
import { seekPlay } from './play-seek.ts';
import {
attachPlayInput,
detachPlayInput,
handleSharedEngineExitKey,
handleVisibilityChange,
handleWindowBlur,
handleWindowFocus,
isQuickRetryHeld,
playControlActions,
recordControlKey,
releasePlayKeys,
trackPlayKey,
togglePause,
} from './play-input.ts';
import { decodePlayAudio, disposeBGAVideos, disposePlayAudio, openPlayAudio, prepareBGA } from './play-media.ts';
import { PlaySessionState } from './play-session-state.ts';
import type { PlaySessionTheme } from './play-session-theme.ts';
import { applyPlayEvent } from './play-state.ts';
import { resolveLaneCovers, resolveVisibleMs } from './play-view-settings.ts';
const log = logger('gameplay');
const NO_TIMING: PlayViewTiming = { loadEndOffsetMs: 0, playStartOffsetMs: 0, fadeOutMs: 0, closeMs: 0 };
/** The theme of a session without a view: skinless timing, no moments heard, the default beam fade. */
const NO_THEME: PlaySessionTheme = {
timing: () => NO_TIMING,
moment: () => {},
keyOnFadeMs: () => KEY_ON_FADE_OUT_MS,
};
/** The play session. See the module comment. */
export class PlaySession extends PlaySessionState {
/**
* The play tempo in force ({@link PlaySessionOptions.tempo}, or a replay's recorded one, then every live change):
* chart seconds per clock second.
*/
tempo: number;
/** The tempo a replay plays at and the changes it follows (`resolveReplayTempo`). */
readonly replayTempo: ReplayTempo | undefined;
/** The live tempo changes asked for ({@link setTempo}), pushed to the engine (held until its input bus is up). */
readonly liveTempo: LiveTempo;
readonly options: PlaySessionOptions;
/** What the session asks of the view that draws it. */
readonly theme: PlaySessionTheme;
/**
* Whether the view shows the play: from {@link start}, or from the chart's preparation when the play is already on
* the stage (no splash covers the load), so the playfield draws in its loading state.
*/
shown = false;
public constructor(options: PlaySessionOptions = {}, theme: PlaySessionTheme = NO_THEME) {
super();
const recordedHSFix =
(options.replayView?.hiSpeed ?? true)
? resolvePlayOptionValue('hsFix', options.replay?.play.options?.hsFix ?? options.replay?.play.view?.hsFix)
: undefined;
if (recordedHSFix !== undefined) options = { ...options, hsFix: recordedHSFix };
this.options = options;
this.practice = options.practice === true;
this.theme = theme;
// A replay plays back at the tempo it was played at, unless its viewer keeps their own (`replayView.tempo`).
this.replayTempo =
options.replay !== undefined
? resolveReplayTempo(options.replay.play, {
ownTempo: options.tempo,
pitchMode: options.tempoPitchMode ?? 'pitch',
// The recorded tempo timeline only when the viewer's replay options reproduce the tempo (default on).
reproduce: (options.replayView ?? DEFAULT_REPLAY_PLAYBACK_OPTIONS).tempo,
})
: undefined;
this.tempo = this.replayTempo?.tempo ?? clampPlayTempo(options.tempo);
// Only in pitch mode (kept pitch stretched the samples to the tempo they loaded at), and not for a replay.
this.liveTempo = new LiveTempo(
this.tempo,
options.replay === undefined && supportsLiveTempoChange(options.tempoPitchMode ?? 'pitch'),
);
// The player's hi-speed, snapped to the 1/1000 grid the hotkey steps on, so a host-supplied `1.5000000000000002`
// (the float drift of repeated +0.1 steps) lands on the canonical grid value; the default without a valid one.
// HS-FIX applies once the chart is prepared.
this.playState = createPlayState({
view: {
hiSpeed: createHiSpeedState({
...(options.initialHiSpeed !== undefined ? { hiSpeed: options.initialHiSpeed } : {}),
classic: options.classicHiSpeed,
floating: options.floatingHiSpeed,
normalLevel: options.classicHiSpeed ? undefined : options.normalHiSpeedLevel,
locked: options.hiSpeedLocked === true,
}),
},
});
this.scrollHiSpeed.jump(this.playState.view.hiSpeed.drawn);
this.autoPauseOnBlur = options.autoPauseOnBlur ?? false;
this.audioVolumes = {
key: sanitizeBusVolume(options.audioVolumes?.key ?? 1),
bgm: sanitizeBusVolume(options.audioVolumes?.bgm ?? 1),
};
this.audioCompressorParams = { ...options.audioCompressorParams };
}
/**
* Convenience accessor for the host's `Application`. Throws before the play has a host; this is intentional — every
* code path that touches `this.app` runs once the play is prepared or shown.
*/
get app(): Application {
if (!this.host) {
throw new Error('PlaySession: app accessed before the play has a host');
}
return this.host.app;
}
/**
* Loads the play: parses the chart, opens its audio graph and decodes every audio sample the chart references — the
* slow part of going from "song picked" to "gameplay can begin". It touches no stage and adds no listeners. Behind a
* splash it returns once chart audio is decoded; a play already on the stage returns once the audio graph is open and
* decodes on through its intro. The BGA preload runs on in the background either way, and {@link start} waits for the
* samples and the BGA before the chart begins (the ffmpeg.wasm fallback for unsupported codecs can take tens of
* seconds, and the play should show its LOADING animation meanwhile instead of freezing the decide screen).
*/
public async load(chartEntry: LibraryChart, source?: BrowserAssetSource): Promise<void> {
this.chart = chartEntry;
this.source = source;
// Hidden until {@link start} fires, so a play shown before it begins draws nothing of it yet.
this.shown = false;
this.loadProgress = 0;
this.assetsLoading = true;
try {
prepareChart(this, chartEntry);
} catch (error) {
// An option that does not fit the chart is the player's to change: the host says which, other errors go on.
throw toPlayOptionMismatch(error, this.options) ?? error;
}
if (this.entered) {
// No splash covers the load window: hold the chart clock before its start (see `start()`) and draw the loading
// playfield while assets decode, instead of a blank stage.
this.startTime = Number.POSITIVE_INFINITY;
this.shown = true;
}
// The view's own assets (an LR2 skin's images, fonts and timer spans) load now, before the samples decode.
await this.theme.prepareView?.();
Iif (this.disposed) return;
// The graph opens now, so the play has its AudioContext when load returns (a recording starts on it).
this.loadProgress = 0.1;
const samplesDecoded = openPlayAudio(this)
? decodePlayAudio(
this,
(fraction) => {
this.loadProgress = 0.1 + 0.4 * fraction;
},
(fraction) => {
this.loadProgress = 0.5 + 0.19 * fraction;
},
)
: Promise.resolve();
if (this.entered) {
// Nothing covers this play's load: its intro runs while the samples decode, and START holds the chart until they
// are in, so the wait is the longer of the two instead of both.
this.assetsReadyPromise = samplesDecoded
.catch((error: unknown) => {
log.warn('sample decoding failed; playing what decoded', error);
})
.then(() => this.loadAfterSamples());
} else {
// Behind a splash the samples decode before the play takes the stage.
await samplesDecoded;
Iif (this.disposed) return;
this.assetsReadyPromise = this.loadAfterSamples();
}
void this.assetsReadyPromise.then(() => {
this.loadProgress = 1;
this.assetsLoading = false;
});
}
/** Builds the engine on the decoded samples and preloads the BGA; resolves once the BGA is in. */
private loadAfterSamples(): Promise<void> {
Iif (this.disposed) return Promise.resolve();
this.samplesDecoded = true;
// Build the engine while BGA and the skin intro are still loading; START opens its chart gate.
launchSharedEngine(this);
this.loadProgress = 0.7;
this.bgaReadyPromise = prepareBGA(this, (fraction) => {
this.loadProgress = 0.7 + 0.25 * fraction;
}).catch((error) => {
log.warn('BGA preload failed; continuing without it', error);
});
// The ghost's replay is read and simulated while the BGA loads; the chart waits for both.
return Promise.all([this.bgaReadyPromise, prepareGhost(this)]).then(() => undefined);
}
/**
* The play goes on the stage: wires its keys (ESC / F5 / Space / arrows, the Backspace hold), canvas focus and the
* auto-pause on losing focus (the touch lanes are the view's, sent as `lane` intents). The play itself starts with
* {@link start}.
*/
public attachInput(host: PixiSceneHost): void {
Iif (this.disposed || this.entered) return;
this.host ??= host;
this.entered = true;
attachPlayInput(this, host);
}
/** The play leaves the stage: its input stops. The engine and sound run on, a play that ended keeps its tail. */
public detachInput(): void {
if (!this.entered) return;
this.entered = false;
detachPlayInput(this);
}
/**
* Shows the play and starts the intro timeline (the theme's `scene-start`, `load-end` and `play-start` moments). Must
* be called after {@link load} resolves; calling it before skips the chart-start scheduling because
* `audioContextStartTime` only lands in the right ballpark when the audio context is up.
*
* Idempotent — repeated calls after the play has already started no-op.
*/
public start(): void {
Iif (this.disposed) return;
if (this.sceneStartTime !== 0) return;
this.shown = true;
// The intro timeline comes from the theme (the LR2 family maps `#LOADSTART` / `#LOADEND` / `#PLAYSTART`). `start()`
// only runs when `paused` is false and `pauseTotal` is still 0, so `playClock()` and `performance.now()` are
// equivalent here — but seeding through `playClock()` keeps the animation clocks all in the same coordinate system
// as the pause-aware reads further below.
const now = this.playClock();
this.sceneStartTime = now;
const { loadEndOffsetMs, playStartOffsetMs, inputStartOffsetMs, playStartAfterLoadEndMs } = this.theme.timing();
// Skinless / non-LR2 players have no timing directives; fall back to the legacy 3-second wait so the slide-in chrome
// of the built-in fallback frame still has room to land before notes begin.
const introMs =
playStartAfterLoadEndMs !== undefined
? loadEndOffsetMs + playStartAfterLoadEndMs
: playStartOffsetMs > 0
? playStartOffsetMs
: FALLBACK_INTRO_DELAY_MS;
this.scheduledIntroMs = introMs;
// The chart waits on BOTH the configured PLAY START delay AND the BGA preload (which may still be transcoding video
// in the background — see `load()`). Until the gate opens below, `startTime = +Infinity` keeps `isIntroPlaying`
// true and the play in the intro (LR2 LOADING) phase.
this.startTime = Number.POSITIVE_INFINITY;
// Scene start fires immediately; load-end and play-start — the events that drive "READY" / chart-start cues — fire
// later via the `Promise.all` gates below so they wait for the BGA preload too. Exit-phase events are deliberately
// NOT raised here: `beginExitSequence` raises them at the actual transition moment (ESC / chart end / failure).
this.theme.moment({ kind: 'scene-start', at: now });
// A play still decoding builds its engine once the samples are in (`loadAfterSamples`).
if (this.samplesDecoded) launchSharedEngine(this);
// The `start()` invocation we belong to — captured so the gate handlers below can detect a dispose-and-re-mount and
// bail out instead of mutating a fresh play's state.
const sceneEpoch = this.sceneStartTime;
// The samples (on a play that decodes through its intro) and the BGA.
const bgaReady = this.assetsReadyPromise ?? Promise.resolve();
// LOAD END gate — both the configured load-end delay AND the BGA preload need to finish.
const isCurrent = () => !this.disposed && !this.exiting && this.sceneStartTime === sceneEpoch;
if (inputStartOffsetMs !== undefined) {
void this.delaySceneStage(inputStartOffsetMs).then(() => {
Eif (isCurrent()) this.theme.moment({ kind: 'input-start', at: this.playClock() });
});
}
const loadEnd = Promise.all([bgaReady, this.delaySceneStage(loadEndOffsetMs)]).then(() => {
if (!isCurrent()) return;
this.theme.moment({ kind: 'load-end', at: this.playClock() });
});
// beatoraja's READY interval starts at actual load end, so a slow preload cannot consume it. LR2 keeps its
// absolute PLAY START gate. Both anchor the animation, engine and BGM clocks at the same chart start.
const playStart =
playStartAfterLoadEndMs === undefined
? Promise.all([bgaReady, this.delaySceneStage(introMs)])
: loadEnd.then(() => {
if (isCurrent() && playStartAfterLoadEndMs > 0) return this.delaySceneStage(playStartAfterLoadEndMs);
});
void playStart.then(() => {
if (!isCurrent()) return;
this.theme.moment({ kind: 'play-start', at: this.playClock() });
// `startTime` is consumed by `isIntroPlaying` and `currentSeconds`, both of which work in raw wall-clock units
// (with `currentSeconds` subtracting `pauseTotal` explicitly), so it MUST stay on `performance.now()`.
this.startTime = performance.now();
// The chart's clock until the engine's first frame; the engine's audio session schedules a NONSTOP chart's fades.
Iif (this.audioContext) this.audioContextStartTime = this.audioContext.currentTime;
// The engine is prepared already; opening its gate starts chart time and audio together.
this.engineStartRequested = true;
this.sharedEngineInputSignals?.pushCommand({ kind: 'start' });
});
this.host?.app.canvas.focus();
}
private delaySceneStage(offsetMs: number): Promise<void> {
return new Promise((resolve) => this.setSceneStageTimeout(resolve, Math.max(0, offsetMs)));
}
/** Schedules `callback` after `offsetMs`, tracked so {@link dispose} cancels it. */
private setSceneStageTimeout(callback: () => void, offsetMs: number): void {
let handle = 0;
handle = window.setTimeout(
() => {
this.sceneStageTimeouts.delete(handle);
callback();
},
Math.max(0, offsetMs),
);
this.sceneStageTimeouts.add(handle);
}
/**
* Pauses or resumes the play, as Space does. For hosts that offer on-screen controls — a touch device has no keyboard
* to press Space or Escape on.
*/
public requestTogglePause(): void {
Iif (this.disposed || this.exiting) return;
togglePause(this);
}
/**
* Moves an AUTO play or replay to chart second `seconds` (`seekPlay`): the engine seeks the running play, and the promise resolves
* once it has (its frames are of the new seek generation). A paused play stays paused there. Manual play requires `allowSeek: 'practice'`.
*/
public seek(seconds: number): Promise<void> {
return seekPlay(this, seconds);
}
/** Whether the play is paused (by Space, {@link requestTogglePause}, or the auto-pause on losing focus). */
public isPaused(): boolean {
return this.paused;
}
/**
* The replay of this play once the engine has recorded it — also after Escape, which records the play as given up
* (`play.aborted`) a moment after `onExit` fires. Resolves `undefined` when none arrives within `timeoutMs` (a replay
* records none).
*/
public waitForReplay(timeoutMs = 2000): Promise<BeMusicReplay | undefined> {
Iif (this.replay !== undefined) return Promise.resolve(this.replay);
return new Promise((resolve) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const settle = (replay: BeMusicReplay | undefined): void => {
Eif (timer !== undefined) clearTimeout(timer);
const index = this.replayWaiters.indexOf(settle);
Eif (index >= 0) this.replayWaiters.splice(index, 1);
resolve(replay);
};
timer = setTimeout(() => settle(undefined), timeoutMs);
this.replayWaiters.push(settle);
// Practice and replay playback produce no recording. Wait for the final summary, then settle without a timeout.
void this.sharedEnginePromise?.then(
() => settle(this.replay),
() => settle(undefined),
);
});
}
/**
* Leaves the play the way Escape does: the theme's fade-out runs, then the host's `onExit` fires. Once every note is
* judged or the chart has reversed, it finishes the play and shows the result (`finishPlayOnExit`).
*/
public requestExit(): void {
if (finishPlayOnExit(this)) return;
beginExitSequence(this, () => {
// The quit key held through the fade-out plays the chart again (That-Which-Must-Not-Be-Named PC's quick retry).
Iif (isQuickRetryHeld(this, performance.now())) {
interruptSharedEngine(this, 'restart');
this.sharedEngineAbortController?.abort();
this.options.onRestart?.();
return;
}
interruptSharedEngine(this, 'escape');
this.sharedEngineAbortController?.abort();
this.options.onExit?.();
});
}
/** Plays the chart again the way F5 does: the theme's fade-out runs, then the host's `onRestart` fires. */
public requestRestart(): void {
beginExitSequence(this, () => {
interruptSharedEngine(this, 'restart');
this.sharedEngineAbortController?.abort();
this.options.onRestart?.();
});
}
/**
* Toggles the dynamics compressor stack on the audio bus at runtime. Mid-play safe: the bus's `setMode` only re-wires
* downstream stages, so in-flight `BufferSourceNode`s keep playing through the unchanged `keyMixer` / `bgmMixer`
* nodes.
*
* - `setAudioCompressor(false)` → bus mode `'off'` (every stage bypassed; both mixers connect directly to
* destination).
* - `setAudioCompressor(true)` → bus mode is restored to the architecture the constructor chose
* (`audioCompressorMode`, default `'split'`). To switch architectures at runtime use {@link setAudioCompressorMode}
* instead.
*
* Idempotent and a no-op before `prepareAudio` has run; the constructor's `audioCompressor` option seeds the initial
* state at mount time.
*/
public setAudioCompressor(enabled: boolean): void {
if (!this.audioBus) {
// Bus will be wired with the right mode the next time `prepareAudio` runs. We can't pre-seed
// `audioCompressorMode` here either: the constructor option is the source of truth until then.
return;
}
const next = enabled ? this.audioCompressorMode : 'off';
this.audioBus.setMode(next);
}
/**
* Toggles the auto-pause-on-blur behavior at runtime. Future `visibilitychange` / `blur` events will only auto-pause
* when `enabled` is true; the auto-RESUME path stays unconditional so a user who blurs (auto-pauses) then disables
* this option still gets back to play state on the next focus.
*
* Idempotent — calling with the same value no-ops.
*/
public setAutoPauseOnBlur(enabled: boolean): void {
this.autoPauseOnBlur = enabled;
}
/**
* Switches the compressor architecture between `'split'` (default 3-stage) and `'legacy'` (original
* single-compressor) at runtime. Mostly useful for the player's `?compressor=` URL flag and for live A/B comparison
* while debugging.
*
* Calling this while `setAudioCompressor(false)` has the bus in `'off'` mode just remembers the choice — the new
* architecture will be applied next time compression is re-enabled.
*/
public setAudioCompressorMode(mode: 'split' | 'legacy'): void {
this.audioCompressorMode = mode;
if (this.audioBus && this.audioBus.getMode() !== 'off') {
this.audioBus.setMode(mode);
}
}
/**
* Toggle one compressor stage (`'key'` / `'bgm'` / `'master'`) within the split-bus architecture. The stage flag is
* remembered even when the active mode isn't `'split'` — a future toggle to split mode will pick the user's choice
* back up.
*
* No-op before `prepareAudio` has run; the stage state will be applied via the bus's defaults the next time gameplay
* mounts.
*/
public setAudioCompressorStageEnabled(stage: CompressorStage, enabled: boolean): void {
this.audioBus?.setStageEnabled(stage, enabled);
}
/**
* Sets the user volume of the keysound (`'key'`) or BGM (`'bgm'`) bus, as a linear gain (1 = unity, clamped to
* `0..2`). Applies live to a running chart; before the audio bus exists the value is kept for when it is built.
*/
public setAudioVolume(channel: AudioBusChannel, volume: number): void {
this.audioVolumes[channel] = sanitizeBusVolume(volume);
this.audioBus?.setBusVolume(channel, volume);
}
/**
* Retunes one compressor (`'key'` / `'bgm'` / `'master'` split stages or `'legacy'`); unspecified fields keep their
* current value. Applies live to a running chart; before the audio bus exists the tuning is kept for when it is built.
*/
public setAudioCompressorParams(compressor: TunableCompressor, params: Partial<CompressorParams>): void {
this.audioCompressorParams[compressor] = { ...this.audioCompressorParams[compressor], ...params };
this.audioBus?.setCompressorParams(compressor, params);
}
/**
* Begins recording the play (canvas video + bus audio mix) into a WebM Blob. Throws when the play's audio is not up
* yet, or when the browser doesn't expose `MediaRecorder` / `canvas.captureStream` / a usable codec — UI hosts should
* surface these failures to the user (the codec case is common on older Safari).
*
* Idempotent in the sense that calling while a recording is already active is a no-op (`isRecording()` is the
* canonical gate hosts should check).
*/
public startRecording(options: { format?: RecordingFormat; quality?: RecordingQuality } = {}): void {
if (this.recorder?.isActive()) return;
if (!this.host || !this.audioContext || !this.audioBus) {
throw new Error('PlaySession.startRecording: gameplay audio is not ready yet');
}
// Recreate the recorder per session — instances are one-shot by design (chunk buffer + audio tap lifecycle), so the
// host gets a clean blob on every start.
const host = this.host;
const canvas = host.app.canvas;
// The quality's bitrates for the frames the recorder takes: the canvas at its own size, at the recorder's 60 fps.
const bitrates = resolveRecordingBitrates(options.quality ?? DEFAULT_RECORDING_QUALITY, {
width: canvas.width,
height: canvas.height,
fps: 60,
});
this.recorder = new GameplayRecorder({
canvas,
...bitrates,
subscribeFrame: (onFrame) => host.onAfterRender(onFrame),
audioContext: this.audioContext,
audioOutput: this.audioBus.outputNode,
format: options.format,
});
this.recorder.start();
}
/**
* Ends the active recording and resolves with the assembled Blob plus its MIME type / duration. Resolves with
* `undefined` when no recording is in progress, so callers can call this unconditionally on chart end / unmount.
*/
public async stopRecording(): Promise<GameplayRecorderResult | undefined> {
const recorder = this.recorder;
if (!recorder) return undefined;
this.recorder = undefined;
return recorder.stop();
}
public isRecording(): boolean {
return this.recorder?.isActive() ?? false;
}
/**
* Ends the play: its input, timers, BGA videos, recording, engine and audio (kept until the tail has rung out after a
* natural end with `preserveAudioTail`), then the BGA textures, released over the next frames, and the per-song state.
*/
public dispose(options: PlayDisposeOptions = {}): void {
Iif (this.disposed) return;
this.disposed = true;
this.detachInput();
this.stopPlay(options);
this.lrxBGA?.dispose();
this.lrxBGA = undefined;
const textures = [...this.bgaTextures.values(), ...this.bgaLayerTextures.values()];
this.bgaTextures.clear();
this.bgaLayerTextures.clear();
this.releaseTextures(textures);
this.clearPlay();
}
/**
* Stops what runs on as the play is disposed: the exit and stage timers, the key flashes, the BGA videos, a
* recording, the engine, and the audio graph (after its tail with `preserveAudioTail`). The textures stay.
*/
private stopPlay(options: PlayDisposeOptions): void {
Iif (this.exitFadeOutHandle !== undefined) {
window.clearTimeout(this.exitFadeOutHandle);
this.exitFadeOutHandle = undefined;
}
Iif (this.exitCloseHandle !== undefined) {
window.clearTimeout(this.exitCloseHandle);
this.exitCloseHandle = undefined;
}
for (const timeout of this.sceneStageTimeouts) {
window.clearTimeout(timeout);
}
this.sceneStageTimeouts.clear();
this.chartEndGate = undefined;
Iif (this.chartEndTimeout !== undefined) {
window.clearTimeout(this.chartEndTimeout);
this.chartEndTimeout = undefined;
}
for (const timeout of this.keyFlashTimeouts) {
window.clearTimeout(timeout);
}
this.keyFlashTimeouts.clear();
log.info('listeners detached');
disposeBGAVideos(this);
// Hard-stop any active recording before tearing down the bus. `GameplayRecorder.dispose` calls
// `MediaRecorder.stop()` synchronously (no chunk-flush wait) and disconnects its audio tap from the bus's output
// node, so the bus can be disposed cleanly afterwards.
this.recorder?.dispose();
this.recorder = undefined;
stopSharedEngine(this);
disposePlayAudio(this, options);
}
/**
* Destroys `textures` a few per frame on the host's ticker (a macrotask loop without one), all at once when the host
* itself is going: a sync sweep over a play's textures stalls the next scene's first frames on lower-end devices.
*/
private releaseTextures(textures: readonly (Texture | undefined)[]): void {
try {
releaseTexturesOnHost(this.host, textures);
} catch (error) {
log.warn('texture cleanup threw', error);
}
}
/**
* Drops the large per-song reference holders. Async gates and cancelled browser decode tasks can retain the play for
* a little while after `dispose()` returns; clearing these keeps that short tail from pinning a full chart bundle,
* decoded PCM and BGA timelines.
*/
private clearPlay(): void {
this.decodedSamples.clear();
this.bmsonSlicePlayback = undefined;
this.autoSampleTriggers = [];
this.pressedChannels.clear();
this.lanePressedAt.clear();
this.laneReleasedAt.clear();
this.longNotes.clear();
this.longNoteStyle = undefined;
this.judgeWindows = undefined;
this.keyBeamStartedAt.clear();
this.bombStartedAt.clear();
this.bombJudge.clear();
this.keyBeamFadeStartedAt.clear();
this.wavCmdVolumeMultipliers.clear();
this.bgaSubRegionOrigins.clear();
this.playState = createPlayState();
this.notes = [];
this.drawNotes = [];
this.mineNotes = [];
this.invisibleNotes.length = 0;
this.preparedChart = undefined;
this.engineFrame = undefined;
this.touchTokenByChannel = undefined;
this.resolvedChart = undefined;
this.resolvedPlayChart = undefined;
this.randomDraws = undefined;
this.randomSeeds = {};
this.beatAtSeconds = undefined;
this.scrollMapper = undefined;
this.timingResolver = undefined;
this.bpmGuideEvents = [];
this.bgaTimeline = { base: [], layer: [], poor: [] };
this.laneChannels = [];
this.laneX.clear();
this.poorBGAFallbackKey = undefined;
this.poorBGAFallbackUntilSeconds = Number.POSITIVE_INFINITY;
this.hasBGA = false;
this.bgaReadyPromise = undefined;
this.assetsReadyPromise = undefined;
this.ghost = undefined;
this.samplesDecoded = false;
this.chart = undefined;
this.source = undefined;
this.host = undefined;
}
/**
* The gauge this run actually plays on. A replay restores the recorded pick so the played-back run judges, drains,
* and clears exactly as the original did. Otherwise a chart's GAMELEVEL / EXTRA (#845) wins outside a course and
* PRACTICE, as the engine decides; then the host's selection, defaulting to LR2 GROOVE.
*/
resolveSelectedGauge(): GaugePick {
if (this.options.replay !== undefined) return this.options.replay.play.gauge ?? 'GROOVE';
const chart = this.resolvedChart ?? this.chart?.chart;
const chartGauge =
chart !== undefined && this.options.course === undefined && this.options.practiceRange === undefined
? resolveChartGaugeType(
compileChartGaugeOptions({ initial: chart.bms.options ?? (chart.bms.option ? [chart.bms.option] : []) }),
this.options.judgeRuleset ?? 'lr2',
)
: undefined;
return chartGauge ?? this.options.gauge ?? 'GROOVE';
}
/**
* Does the ruleset this run judges under show empty POORs inside its POOR counter? LR2 does; beatoraja shows a
* figure of its own, and That-Which-Must-Not-Be-Named's counter is unmeasured, so both keep them apart.
*/
resolveEmptyPoorCountsInPoorDisplay(): boolean {
const ruleset = this.options.replay?.play.judgeRuleset ?? this.options.judgeRuleset ?? 'lr2';
return ruleset === 'lr2';
}
/** The compat ruleset judging the play (a replay's recorded one wins). */
resolveJudgeRuleset(): string {
return this.options.replay?.play.judgeRuleset ?? this.options.judgeRuleset ?? 'lr2';
}
/** Whether the engine plays `channel`'s notes itself: every lane under autoplay, the scratch under auto-scratch. */
isAutoplayedChannel(channel: string): boolean {
return this.options.autoPlay === true || this.autoScratchChannels.has(channel);
}
/** True once {@link start} has begun the intro. A view that joins later reads this to seed its skin timers. */
public hasSceneStarted(): boolean {
return this.sceneStartTime !== 0;
}
/** True while the wall-clock playhead is still inside the intro buffer. */
isIntroPlaying(): boolean {
if (this.startTime === 0) {
return true;
}
return performance.now() < this.startTime;
}
/**
* The tempo the BPM readouts show at `seconds`. Past an LR2 negative-BPM reversal (issue #134) it holds the value at
* the reversal — LR2's frozen event pump never applies a later BPM event — even though the reverse scroll itself
* keeps following the forward tempo map.
*/
nowBPM(seconds: number): number | undefined {
const resolver = this.timingResolver;
if (!resolver) return undefined;
// `displayBPMAtBeat`: a negative `#BPMxx` reads as |trunc(BPM)|, LR2's int NOWBPM.
Iif (resolver.reversal && seconds >= resolver.reversal.seconds && resolver.reversalDisplayBPM !== undefined)
return resolver.reversalDisplayBPM;
return resolver.displayBPMAtBeat(this.forwardBeat(seconds));
}
/**
* The BPM the readouts (NOWBPM, the HUD) show at `seconds`: for a stitched NONSTOP chart, whose scroll runs at a
* constant 150 BPM, the BPM of the stage being played, scaled by its FIT rate (`NonstopStitchMap.tempo`), as LR2
* shows it; otherwise {@link nowBPM}.
*/
displayBPM(seconds: number): number | undefined {
const tempo = this.options.nonstop?.tempo;
return tempo !== undefined && tempo.length > 0 ? nonstopBPMAt(tempo, seconds) : this.nowBPM(seconds);
}
/**
* The song's beat at `seconds`, from the BPM- and STOP-aware tempo map: charts change tempo mid-song (`#BPM`), and
* the initial BPM alone would drift notes after a change out of sync with the audio.
*/
currentBeat(seconds: number): number {
// LR2 negative-BPM reversal (issue #134): past the first negative `#BPMxx` the chart *visually* scrolls backwards.
// LR2 mirrors the chart POSITION around the reversal (`2 * pos(R) - pos(now)`), so the reverse scroll runs at the
// post-reversal |BPM| and pauses through post-reversal STOPs. Every display consumer — renderNotes, measure
// lines, beatPhase — funnels through this method, so mirroring here covers them all; the forward beat underneath
// keeps `beatAtSeconds`'s monotonic stop-window cursor intact.
const reversal = this.engineFrame ? this.engineFrame.reversalActivation : this.timingResolver?.reversal;
const forward = this.forwardBeat(seconds);
// CONSTANT mirrors LR2's converted 150-BPM position, then maps back to a beat for every view.
if (
reversal &&
seconds > reversal.seconds &&
this.playState.view.hsFix === 'CONSTANT' &&
this.scrollMapper?.mirrorBeatAt
) {
return this.scrollMapper.mirrorBeatAt(reversal.beat, forward);
}
return mirrorBeatAtTempoReversal(reversal, seconds, forward);
}
private forwardBeat(seconds: number): number {
// Prefer the proper STOP-aware resolver (built once per song in `prepareChart`). Falls back to a flat-BPM
// extrapolation when the resolver isn't ready yet (very early frames during mount).
const resolver = this.timingResolver;
if (this.beatAtSeconds && resolver && resolver.tempoPoints.length > 0) {
return this.beatAtSeconds(seconds);
}
Eif (!resolver || resolver.tempoPoints.length === 0) {
const bpm = this.chart?.bpm ?? 130;
return Math.max(0, seconds * (bpm / 60));
}
let active = resolver.tempoPoints[0]!;
for (const point of resolver.tempoPoints) {
if (point.seconds <= seconds) {
active = point;
} else {
break;
}
}
return Math.max(0, active.beat + ((seconds - active.seconds) * active.bpm) / 60);
}
/** Uploads `textures` to the GPU through the view (the BGA the session loaded), so the first cue does not stall. */
preparePixiUpload(textures: Iterable<Texture | undefined>): Promise<void> {
return this.theme.uploadTextures?.(textures) ?? Promise.resolve();
}
readonly handleVisibilityChange = (): void => handleVisibilityChange(this);
readonly handleWindowBlur = (): void => handleWindowBlur(this);
readonly handleWindowFocus = (): void => handleWindowFocus(this);
readonly focus = (): void => {
this.app.canvas.focus();
};
/** Holding Backspace for `QUIT_HOLD_THRESHOLD_MS` leaves the play the way Escape does. */
readonly quitHold: QuitHoldController = new QuitHoldController({
onComplete: () => this.requestExit(),
now: () => performance.now(),
isQuitKey: (event) => playControlActions(this).is('play.quit-hold', event),
});
readonly handleQuitHoldKeyUp = (event: KeyboardEvent): void => {
this.quitHold.handleKeyUp(event);
recordControlKey(this, 'up', event);
trackPlayKey(this, 'up', event);
};
readonly cancelQuitHold = (): void => {
this.quitHold.cancel();
releasePlayKeys(this);
};
public lastStartTapMs: number | undefined;
/** The player's move and scale of the play skin this play (LR2's 1 / 2 + the arrows), over the one it started with. */
private skinAdjustValue: SkinAdjust | undefined;
/** Where the play skin is moved and how far it is scaled (the frame draws it so). */
public get skinAdjust(): SkinAdjust {
return this.skinAdjustValue ?? this.options.skinAdjust ?? NO_SKIN_ADJUST;
}
/** Moves or scales the play skin, and tells the host for the next play. */
public setSkinAdjust(adjust: SkinAdjust): void {
this.skinAdjustValue = adjust;
this.options.onSkinAdjustChange?.(adjust);
}
readonly handleSharedEngineExitKey = (event: KeyboardEvent): void => handleSharedEngineExitKey(this, event);
/**
* Sets the hi-speed from the host (e.g. a settings menu) during the play. `value` is on the scale of
* {@link PlaySessionOptions.initialHiSpeed}: the chart's HS-FIX multiplier is applied on top, as at the start.
* Snapped and clamped like the in-game hotkey; non-finite values are ignored.
*/
public setJudgeTimingMs(value: number): void {
if (!Number.isFinite(value)) return;
const next = clampJudgeTimingMs(value);
if (next === (this.options.judgeTimingMs ?? 0)) return;
this.options.judgeTimingMs = next;
this.sharedEngineInputSignals?.pushCommand({ kind: 'options', values: { judgeTimingMs: next } });
this.options.onJudgeTimingChange?.(next);
}
public setHiSpeed(value: number): void {
applyPlayEvent(this, {
type: 'hi-speed-set',
value,
bpm: this.timingResolver?.bpmAtBeat(this.currentBeat(this.currentSeconds())),
});
Iif (this.playState.view.hiSpeed.normalLevel !== undefined)
this.options.onHiSpeedChange?.(this.playState.view.hiSpeed.player, this.playState.view.hiSpeed.normalLevel);
}
/**
* Pause-aware monotonic clock used by every "time since X" animation of the play (LR2 timer keyframes,
* scratch-disc rotation, bomb / FC / POOR-BGA windows, NOWJUDGE / NOWCOMBO decay, …). Returns wall clock minus the
* accumulated pause duration, and freezes at `pauseTime - pauseTotal` while the play is paused. Seed sites that
* drive these animations store `playClock()` values, and the read sites compute `playClock() - seed` — so animations
* resume exactly where they left off rather than jumping forward by the pause duration.
*/
playClock(): number {
if (this.paused) {
return this.pauseTime - this.pauseTotal;
}
return performance.now() - this.pauseTotal;
}
/**
* Pauses every BGA video element in the chart's video pool. The `<video>` element doesn't honor the audio-context
* suspend, so without this the video keeps playing during a pause overlay.
*/
pauseAllBGAVideos(): void {
for (const handle of this.bgaVideos.values()) {
Eif (!handle.video.paused) {
handle.video.pause();
}
}
}
/**
* Resumes only the videos tied to currently-active base / layer / layer2 / POOR cues. Avoids touching videos that were paused for a
* different reason (e.g. an earlier cue switched away from them in `syncBGAVideo`).
*/
resumeActiveBGAVideos(): void {
for (const active of Object.values(this.bgaActiveVideos)) {
Iif (!active) continue;
const handle = this.bgaVideos.get(active.key);
Iif (!handle || !handle.video.paused) continue;
void handle.video.play().catch(() => {
// Autoplay-policy / codec rejections — ignore silently.
});
}
}
/**
* Lerps the displayed score toward the real score so the SCORE panel rolls up after each judgement instead of
* jumping. Speed is tuned so a single PERFECT (~1000 score) catches up in ~6 frames at 60 fps.
*/
updateDisplayedScore(): void {
const target = this.score.score;
Eif (this.displayedScore === target) {
return;
}
const diff = target - this.displayedScore;
if (Math.abs(diff) < 1) {
this.displayedScore = target;
return;
}
// Frame-rate independent ease: cover ~30 % of remaining distance per frame.
const next = this.displayedScore + diff * 0.3;
this.displayedScore = diff > 0 ? Math.min(next, target) : Math.max(next, target);
}
/**
* The play as a result so far ({@link PlayResult}): read off the play state, a plain object a result
* screen that outlives the play can keep. `undefined` before a chart is prepared.
*/
public getResultData(): PlayResult | undefined {
return getResultData(this);
}
/**
* The chart second the play is at now. The engine owns chart time: each of its frames carries the second it shows and
* the audio-clock reading that second holds at (`chartSecondsFromFrame`), so the playfield runs on from the latest
* frame on the audio clock — `audioContext.currentTime` without its render-callback steps (`drawClock`), so it moves
* smoothly and stays on the clock the sounds are scheduled on, through pauses, tempo changes and seeks. Before the
* engine's first frame, the chart runs from the play-start gate at the play's tempo (audio clock, else wall clock
* while the audio context is not up).
*/
currentSeconds(): number {
const context = this.audioContext;
const frame = this.engineFrame;
if (context !== undefined && frame !== undefined) {
const contextSeconds = this.drawClock.read(context.currentTime, performance.now(), context.state === 'running');
const seconds = chartSecondsFromFrame(frame, contextSeconds);
if (seconds !== undefined) return seconds;
}
Iif (context !== undefined && this.audioContextStartTime > 0) {
return (context.currentTime - this.audioContextStartTime) * this.playbackTempo;
}
const nowMs = this.paused ? this.pauseTime : performance.now();
return ((nowMs - this.startTime - this.pauseTotal) / 1000) * this.playbackTempo;
}
/** The physical rate, including the chart's authored standard speed. */
get playbackTempo(): number {
return this.tempo * (this.chartPlay?.program?.options.baseSpeed ?? 1);
}
/** The play tempo in force: the one the play started at, or the last change. */
public getTempo(): number {
return this.tempo;
}
/** The player's hi-speed in force (on the scale of `initialHiSpeed`), a replay's recorded one included. */
public getHiSpeed(): number {
return this.playState.view.hiSpeed.player;
}
/**
* Changes the play tempo during the play (clamped by `clampPlayTempo`). Only in `pitch` mode: the samples follow it
* through their playback rate, playing ones included, and so do the BGA videos and a NONSTOP chart's fades. Keep
* pitch stretched the samples to the tempo they loaded at, and a replay follows its log, so both refuse it. The
* engine applies it at the chart time it takes the command and records it in the replay; the view follows from the
* chart second the engine reports. Returns whether the change was taken.
*/
public setTempo(tempo: number): boolean {
return !this.disposed && this.liveTempo.request(tempo);
}
/**
* Milliseconds since the chart's first beat for chrome count-ins. Before the play-start gate opens (`startTime` is
* still +Infinity) it counts toward the scheduled intro end and holds just below zero if the BGA preload runs long.
*/
resolveChartMs(): number | undefined {
Iif (this.startTime === 0) return undefined;
Iif (Number.isFinite(this.startTime)) return this.currentSeconds() * 1000;
return Math.min(-1, this.playClock() - this.sceneStartTime - this.scheduledIntroMs);
}
/** The lane covers each play side shows (`resolveLaneCovers` in `play-view-settings.ts`), for the playfield and chrome. */
resolveLaneCovers(): readonly BeMusicLaneCover[] {
return resolveLaneCovers(this);
}
/** How long a note stays visible below `cover` (`resolveVisibleMs` in `play-view-settings.ts`), for the chrome. */
resolveVisibleMs(
cover: BeMusicLaneCover | undefined,
bpm: number | undefined,
scrollRate: number,
): number | undefined {
return resolveVisibleMs(this, cover, bpm, scrollRate);
}
/** Approximate total duration of the loaded chart in seconds. */
resolveChartDurationSeconds(): number {
if (!this.chart) {
return 0;
}
return Math.max(this.chartDurationSeconds, this.engineFrame?.totalSeconds ?? 0);
}
/**
* The mode a long note plays in: the one the engine announced while it is held, otherwise worked out from the
* ruleset's long-note style (unknown until the engine reports its ruleset).
*/
resolveLongNoteMode(note: RuntimeNote): BeMusicLongNote['mode'] {
const held = this.longNotes.heldMode(note.channel, note.beat);
if (held !== undefined) return held;
return this.longNoteStyle === undefined
? undefined
: resolveBeMusicLongNoteMode(this.longNoteStyle, note.longNoteMode);
}
}
|