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 | 132x 122504x 122504x 122504x 132x 132x 132x 132x 2040x 8160x 8160x 3979x 3501x 478x 3979x 478x 478x 17295x 8007x 83452x 83452x 420608x 420608x 420608x 420608x 420608x 420608x 420608x 2516976x 6124x 2510852x 420608x 2090244x 420608x 122028x 122028x 122028x 83435x 83435x 7884x 7884x 7884x 2096x 2096x 2096x 100708x 100708x 100708x 92945x 30709x 30709x 30709x 2096x 2096x 4x 4x 4x 313677x 313677x 313677x 122504x 2096x 2096x 2096x 160666x 7927x 2096x 402x 402x 12x 402x 402x 2096x 2096x 2096x 10834x 10834x 8184x 8184x 2650x 2650x 2650x 2650x 2096x 8384x 8384x 8384x 642664x 641719x 945x 945x 642664x 8384x 42903x 42903x 42903x 42903x 2580x 2580x 1016x 1016x 1564x 42903x 945x 945x 945x 57989x 57989x 57989x 57989x 57989x 57989x 57989x 250807x 125834x 124973x 57989x 66984x 57989x 478597x 478597x 478597x 2767783x 478597x 478597x 2289186x 478597x 8535x 8535x 20960x 2096x 2096x 10631x 10631x 106310x 106310x 73680x 32630x 12462x 12462x 10631x 2096x 8535x 8535x 2096x 923x 236248x 2096x 2096x 2096x 2096x 2096x 2096x 2096x 2650x 2650x 2096x 3123x 3123x 2096x 649x 649x 649x 2096x 101x 101x 101x 2096x 432x 864x 2096x 203x 203x 203x 2096x 2096x 2096x 2096x 2096x 2096x 308x 308x 2096x 103x 103x 2096x 267x 267x 2096x 267x 267x 2096x 2096x 2096x 2096x 2096x 2096x 2096x 2096x 42903x 42903x 984x 41919x 1x 41918x 2096x 122848x 122848x 22768x 22768x 14236x 8532x 8532x 42903x 42903x 42903x 42903x 42957x 36406x 6551x 6551x 2096x 2096x 21544x 3015x 3015x 3015x 3015x 3015x 3015x 3015x 3015x 3015x 3015x | import {
createBeatResolver,
createBPMTimeline,
createStopBeatWindows,
isBmsBGMVolumeChangeChannel,
isBMSKeyVolumeChangeChannel,
type ResolvedChart,
type TimedSampleTrigger,
type TimingResolver,
} from '@be-music/chart-model';
import type { LogLevel } from '@be-music/shared-utils/log';
import {
type BeMusicEvent,
type BeMusicJSON,
normalizeChannel,
normalizeObjectKey,
resolveBMSBase,
} from '@be-music/chart-source';
import { type LaneBinding } from './lane-layout.ts';
import { formatSeconds } from '../utils.ts';
import { type PlaybackStateLogger } from './playback-support.ts';
import { _____EX_SCORE_PER_PGREAT, LR2_MONEY_SCORE_MAX } from './scoring.ts';
import { resolveBMSJudgeWindowsMsForExRankValue } from './judge-window.ts';
import { type JudgeWindowSetUs } from '../ruleset/index.ts';
import { RULESET_JUDGE_KINDS } from './judge-rules.ts';
import { REALTIME_AUDIO_TRIGGER_EPSILON_SECONDS } from './engine-clock.ts';
import { type PlayerOptions, type PlayerSummary } from './engine-types.ts';
/**
* No-TUI output of a play: runtime event lines, the playback-state logger, the scheduled
* chart-event tracer and the result summary text.
*/
// Hand-rolled stand-in for `node:path.basename`: the engine stays free of `node:`-prefixed imports so it runs unchanged
// in the browser. Only the trailing-segment semantics the log output needs.
const basename = (path: string): string => {
// Match `node:path.basename`'s "drop the trailing separator(s) and return the final segment" semantics for both
// POSIX and Windows-style separators. An all-separator input ("/" / "\\") returns an empty string.
const trimmed = path.replace(/[\\/]+$/, '');
const lastSep = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
return lastSep === -1 ? trimmed : trimmed.slice(lastSep + 1);
};
type LoggedBGALayer = 'base' | 'poor' | 'layer' | 'layer2';
interface LoggedBGACue {
seconds: number;
key?: string;
resourcePath?: string;
layer: LoggedBGALayer;
}
interface NoTUIScheduledPlaybackEvent {
seconds: number;
order: number;
text: string;
}
type RuntimeEventFieldValue = string | number | boolean;
type RuntimeEventField = readonly [key: string, value: RuntimeEventFieldValue | undefined];
export interface NoTUIPlaybackEventTracer {
flushUntil: (seconds: number) => void;
logPoorTriggered: (seconds: number) => void;
logPoorCleared: (seconds: number) => void;
}
const BGA_BASE_CHANNEL = '04';
const BGA_POOR_CHANNEL = '06';
const BGA_LAYER_CHANNEL = '07';
const BGA_LAYER2_CHANNEL = '0A';
/** Renders one window set as `PGREAT -8.0/+8.0ms ...` (early / late reach) for the TUI's start banner. */
export function formatJudgeWindowSet(windows: JudgeWindowSetUs): string {
return RULESET_JUDGE_KINDS.map((kind, index) => {
const [lateBoundUs, earlyBoundUs] = windows.judges[index]!;
return `${kind} -${(earlyBoundUs / 1000).toFixed(1)}/+${(-lateBoundUs / 1000).toFixed(1)}ms`;
}).join(' ');
}
export function resolveOutputWriter(options: PlayerOptions): (text: string) => void {
if (typeof options.writeOutput === 'function') {
return options.writeOutput;
}
const stdout = (globalThis as { process?: { stdout?: { write?: (value: string) => unknown } } }).process?.stdout;
if (stdout && typeof stdout.write === 'function') {
const write = stdout.write.bind(stdout);
return (text: string): void => {
write(text);
};
}
return (): void => undefined;
}
export function emitPlayerLog(
options: PlayerOptions,
level: LogLevel,
event: string,
fields?: Record<string, unknown>,
): void {
options.onLog?.({
source: 'engine',
level,
event,
fields: {
emittedAtUnixMs: Date.now(),
emittedAtMonotonicMs: performance.now(),
...fields,
},
});
}
export function writeRealtimeTriggeredEventLog(
writeOutput: (text: string) => void,
trigger: Pick<TimedSampleTrigger, 'seconds' | 'channel' | 'sampleKey' | 'event'>,
resourcePath?: string,
source = 'realtime',
): void {
const normalizedResourcePath =
typeof resourcePath === 'string' ? normalizeLoggedResourcePath(resourcePath) : undefined;
writeRuntimeEventLog(writeOutput, 'sample-trigger', [
['time', formatSeconds(trigger.seconds)],
['source', source],
['channel', normalizeChannel(trigger.channel)],
['value', trigger.event.value],
['sample', trigger.sampleKey],
['asset', normalizedResourcePath],
['file', normalizedResourcePath ? basename(normalizedResourcePath) : undefined],
]);
}
export function writeRuntimeEventLog(
writeOutput: (text: string) => void,
kind: string,
fields: readonly RuntimeEventField[],
): void {
const orderedFields = orderRuntimeEventFields(fields);
let line = 'EVENT';
const timeField = orderedFields.find(([key]) => key === 'time');
Eif (timeField && timeField[1] !== undefined) {
line += ` time:${String(timeField[1])}`;
}
line += ` kind:${kind}`;
for (const [key, value] of orderedFields) {
if (value === undefined) {
continue;
}
if (key === 'time') {
continue;
}
line += ` ${key}:${String(value)}`;
}
writeOutput(`${line}\n`);
}
function resolveEventResourceInfo(
resources: Readonly<Record<string, string>>,
event: Pick<BeMusicEvent, 'value'>,
base: 36 | 62 = 36,
): { sampleKey: string; resourcePath?: string } {
const exactKey = normalizeObjectKey(event.value, base, true);
const sampleKey = Object.hasOwn(resources, exactKey) ? exactKey : normalizeObjectKey(event.value, base);
return {
sampleKey,
resourcePath: resources[sampleKey],
};
}
export function writePlayableSampleTriggerEventLog(
writeOutput: (text: string) => void,
event: BeMusicEvent,
seconds: number,
resources: Readonly<Record<string, string>>,
source: 'auto-note' | 'auto-scratch' | 'manual-note' | 'lane-fallback' | 'mine-hit' | 'long-note-end' | 'chain-note',
channel?: string,
base: 36 | 62 = 36,
): void {
const { sampleKey, resourcePath } = resolveEventResourceInfo(resources, event, base);
writeRealtimeTriggeredEventLog(
writeOutput,
{
seconds,
channel: channel ?? event.channel,
sampleKey,
event,
},
resourcePath,
source,
);
}
export function writeSampleStopEventLog(
writeOutput: (text: string) => void,
channel: string,
seconds: number,
reason: 'long-note-release' | 'long-note-break',
event?: BeMusicEvent,
resources?: Readonly<Record<string, string>>,
base: 36 | 62 = 36,
): void {
const resourceInfo = event && resources ? resolveEventResourceInfo(resources, event, base) : undefined;
const normalizedResourcePath =
typeof resourceInfo?.resourcePath === 'string' ? normalizeLoggedResourcePath(resourceInfo.resourcePath) : undefined;
writeRuntimeEventLog(writeOutput, 'sample-stop', [
['time', formatSeconds(seconds)],
['channel', normalizeChannel(channel)],
['reason', reason],
['sample', resourceInfo?.sampleKey],
['asset', normalizedResourcePath],
['file', normalizedResourcePath ? basename(normalizedResourcePath) : undefined],
]);
}
export function createNoTUIPlaybackStateLogger(params: {
writeOutput: (text: string) => void;
summary: PlayerSummary;
/**
* Object-ID radix used for resolving sample keys in `logLongNoteState`. Defaults to base 36; pass `62` for charts
* that opted into `#BASE 62` so lowercase IDs hit the right resource entry instead of being case-folded.
*/
base?: 36 | 62;
}): PlaybackStateLogger {
const { writeOutput, summary } = params;
const base = params.base ?? 36;
return {
logGaugeChange: (seconds, logParams): void => {
const gauge = summary.gauge;
Iif (!gauge) {
return;
}
writeRuntimeEventLog(writeOutput, 'gauge-change', [
['time', formatSeconds(seconds)],
['value', formatLoggedNumericValue(gauge.current)],
['max', formatLoggedNumericValue(gauge.max)],
['delta', logParams.delta === undefined ? undefined : formatLoggedNumericValue(logParams.delta)],
['reason', logParams.reason],
['judge', logParams.judge],
['cleared', gauge.cleared],
]);
},
logComboChange: (seconds, logParams): void => {
writeRuntimeEventLog(writeOutput, 'combo-change', [
['time', formatSeconds(seconds)],
['value', logParams.value],
['reason', logParams.reason],
['judge', logParams.judge],
['channel', logParams.channel ? normalizeChannel(logParams.channel) : undefined],
]);
},
logLongNoteState: (seconds, logParams): void => {
const { sampleKey, resourcePath } = resolveEventResourceInfo(logParams.resources, logParams.event, base);
const normalizedResourcePath =
typeof resourcePath === 'string' ? normalizeLoggedResourcePath(resourcePath) : undefined;
writeRuntimeEventLog(writeOutput, 'long-note', [
['time', formatSeconds(seconds)],
['channel', normalizeChannel(logParams.channel)],
['state', logParams.state],
['mode', logParams.mode],
['sample', sampleKey],
['asset', normalizedResourcePath],
['file', normalizedResourcePath ? basename(normalizedResourcePath) : undefined],
['end', logParams.endSeconds === undefined ? undefined : formatSeconds(logParams.endSeconds)],
]);
},
logResult: (seconds, logParams): void => {
const gauge = logParams.summary.gauge;
writeRuntimeEventLog(writeOutput, 'result', [
['time', formatSeconds(seconds)],
['reason', logParams.reason],
['total', logParams.summary.total],
['perfect', logParams.summary.perfect],
['great', logParams.summary.great],
['good', logParams.summary.good],
['bad', logParams.summary.bad],
['poor', logParams.summary.poor],
['fast', logParams.summary.fast],
['slow', logParams.summary.slow],
['exScore', logParams.summary.exScore],
['score', logParams.summary.score],
['gauge', gauge ? formatLoggedNumericValue(gauge.current) : undefined],
['gaugeMax', gauge ? formatLoggedNumericValue(gauge.max) : undefined],
['gaugeCleared', gauge?.cleared],
]);
},
};
}
export function writeRealtimeVolumeEventLog(
writeOutput: (text: string) => void,
seconds: number,
event: BeMusicEvent,
): void {
const normalizedChannel = normalizeChannel(event.channel);
const target = isBMSKeyVolumeChangeChannel(normalizedChannel)
? 'key'
: isBmsBGMVolumeChangeChannel(normalizedChannel)
? 'bgm'
: 'master';
writeRuntimeEventLog(writeOutput, 'volume-change', [
['time', formatSeconds(seconds)],
['target', target],
['channel', normalizedChannel],
['value', event.value],
]);
}
function formatLoggedNumericValue(value: number, maximumFractionDigits = 3): string {
Iif (!Number.isFinite(value)) {
return '0';
}
const rounded = value.toFixed(maximumFractionDigits);
return rounded.replace(/(?:\.0+|(\.\d*?[1-9])0+)$/, '$1');
}
function normalizeLoggedResourcePath(resourcePath: string): string {
return resourcePath.replaceAll('\\', '/');
}
function resolveLoggedMeasureLengthTimeline(
json: BeMusicJSON,
resolver: TimingResolver,
beatResolver: ReturnType<typeof createBeatResolver>,
): Array<{ measure: number; length: number; seconds: number }> {
const measureLengths = new Map<number, number>();
let maxMeasure = 0;
for (const event of json.events) {
if (event.measure > maxMeasure) {
maxMeasure = event.measure;
}
}
for (const measure of json.measures) {
const index = Math.max(0, Math.floor(measure.index));
if (index > maxMeasure) {
maxMeasure = index;
}
Iif (!Number.isFinite(measure.length) || measure.length <= 0) {
continue;
}
measureLengths.set(index, measure.length);
}
const timeline: Array<{ measure: number; length: number; seconds: number }> = [];
let previousLength = 1;
for (let measure = 0; measure <= maxMeasure; measure += 1) {
const length = measureLengths.get(measure) ?? 1;
if (measure > 0 && Math.abs(length - previousLength) < 1e-9) {
previousLength = length;
continue;
}
const seconds = resolver.beatToSeconds(beatResolver.measureToBeat(measure, 0));
Iif (!Number.isFinite(seconds)) {
previousLength = length;
continue;
}
timeline.push({
measure,
length,
seconds: Math.max(0, seconds),
});
previousLength = length;
}
return timeline;
}
function buildLoggedBGACueTimeline(
sortedEvents: readonly BeMusicEvent[],
resolver: TimingResolver,
resources: Record<string, string>,
channel: string,
layer: LoggedBGALayer,
base: 36 | 62 = 36,
): LoggedBGACue[] {
const normalizedChannel = normalizeChannel(channel);
const timeline: LoggedBGACue[] = [];
for (const event of sortedEvents) {
if (normalizeChannel(event.channel) !== normalizedChannel) {
continue;
}
const key = normalizeObjectKey(event.value, base);
const normalizedKey = key === '00' ? undefined : key;
timeline.push({
seconds: Math.max(0, resolver.eventToSeconds(event)),
key: normalizedKey,
resourcePath: normalizedKey ? resources[normalizedKey] : undefined,
layer,
});
}
return timeline;
}
function findActiveLoggedBGACue(timeline: readonly LoggedBGACue[], seconds: number): LoggedBGACue | undefined {
let low = 0;
let high = timeline.length - 1;
let answer = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (timeline[mid]!.seconds <= seconds) {
answer = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return answer >= 0 ? timeline[answer] : undefined;
}
function formatLoggedBGACueText(cue: LoggedBGACue): string {
Iif (!cue.key) {
return createRuntimeEventLine('bga-cue', [
['time', formatSeconds(cue.seconds)],
['layer', cue.layer],
['state', 'clear'],
]);
}
const normalizedResourcePath = cue.resourcePath ? normalizeLoggedResourcePath(cue.resourcePath) : undefined;
return createRuntimeEventLine('bga-cue', [
['time', formatSeconds(cue.seconds)],
['layer', cue.layer],
['key', cue.key],
['asset', normalizedResourcePath],
['file', normalizedResourcePath ? basename(normalizedResourcePath) : undefined],
]);
}
function createRuntimeEventLine(kind: string, fields: readonly RuntimeEventField[]): string {
const orderedFields = orderRuntimeEventFields(fields);
let line = 'EVENT';
const timeField = orderedFields.find(([key]) => key === 'time');
Eif (timeField && timeField[1] !== undefined) {
line += ` time:${String(timeField[1])}`;
}
line += ` kind:${kind}`;
for (const [key, value] of orderedFields) {
if (value === undefined) {
continue;
}
if (key === 'time') {
continue;
}
line += ` ${key}:${String(value)}`;
}
return `${line}\n`;
}
function orderRuntimeEventFields(fields: readonly RuntimeEventField[]): RuntimeEventField[] {
const timeFields: RuntimeEventField[] = [];
const otherFields: RuntimeEventField[] = [];
for (const field of fields) {
if (field[0] === 'time') {
timeFields.push(field);
continue;
}
otherFields.push(field);
}
return [...timeFields, ...otherFields];
}
function createScheduledPlaybackEvent(
seconds: number,
order: number,
text: string,
): NoTUIScheduledPlaybackEvent | undefined {
Iif (!Number.isFinite(seconds)) {
return undefined;
}
return {
seconds: Math.max(0, seconds),
order,
text,
};
}
function mergeScheduledPlaybackEventGroups(
groups: ReadonlyArray<ReadonlyArray<NoTUIScheduledPlaybackEvent>>,
): NoTUIScheduledPlaybackEvent[] {
const cursors = Array.from({ length: groups.length }, () => 0);
const merged: NoTUIScheduledPlaybackEvent[] = [];
while (true) {
let selectedGroupIndex = -1;
let selectedEvent: NoTUIScheduledPlaybackEvent | undefined;
for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
const event = groups[groupIndex]?.[cursors[groupIndex] ?? 0];
if (!event) {
continue;
}
if (
!selectedEvent ||
event.seconds < selectedEvent.seconds ||
(event.seconds === selectedEvent.seconds && event.order < selectedEvent.order)
) {
selectedEvent = event;
selectedGroupIndex = groupIndex;
}
}
if (selectedGroupIndex < 0 || !selectedEvent) {
break;
}
merged.push(selectedEvent);
cursors[selectedGroupIndex] = (cursors[selectedGroupIndex] ?? 0) + 1;
}
return merged;
}
export function createNoopPlaybackEventTracer(): NoTUIPlaybackEventTracer {
return {
flushUntil: () => undefined,
logPoorTriggered: () => undefined,
logPoorCleared: () => undefined,
};
}
export function createNoTUIPlaybackEventTracer(params: {
resolved: ResolvedChart;
writeOutput: (text: string) => void;
judgeWindowMs?: number;
}): NoTUIPlaybackEventTracer {
const { resolved, writeOutput, judgeWindowMs } = params;
const json = resolved.source;
const resolver = resolved.timing;
const beatResolver = resolved.beatResolver;
const sortedEvents = resolved.sortedEvents;
let nextOrder = 0;
const measureLengthEvents = resolveLoggedMeasureLengthTimeline(json, resolver, beatResolver)
.map((point) =>
createScheduledPlaybackEvent(
point.seconds,
nextOrder++,
createRuntimeEventLine('measure-length-change', [
['time', formatSeconds(point.seconds)],
['measure', point.measure],
['length', formatLoggedNumericValue(point.length)],
]),
),
)
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const bpmEvents = createBPMTimeline(json, resolver)
.map((point) =>
createScheduledPlaybackEvent(
point.seconds,
nextOrder++,
createRuntimeEventLine('bpm-change', [
['time', formatSeconds(point.seconds)],
['value', formatLoggedNumericValue(point.bpm)],
]),
),
)
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const scrollEvents = resolved.scroll
.map((point) => {
const seconds = resolver.beatToSeconds(point.beat);
return createScheduledPlaybackEvent(
seconds,
nextOrder++,
createRuntimeEventLine('scroll-change', [
['time', formatSeconds(seconds)],
['value', formatLoggedNumericValue(point.speed)],
]),
);
})
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const speedEvents = resolved.speed
.map((point) => {
const seconds = resolver.beatToSeconds(point.beat);
return createScheduledPlaybackEvent(
seconds,
nextOrder++,
createRuntimeEventLine('speed-change', [
['time', formatSeconds(seconds)],
['value', formatLoggedNumericValue(point.speed)],
]),
);
})
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const stopEvents = createStopBeatWindows(resolver)
.flatMap((window) => [
createScheduledPlaybackEvent(
window.startSeconds,
nextOrder++,
createRuntimeEventLine('stop', [
['time', formatSeconds(window.startSeconds)],
['state', 'start'],
['duration', `${formatLoggedNumericValue(window.durationSeconds)}s`],
]),
),
createScheduledPlaybackEvent(
window.endSeconds,
nextOrder++,
createRuntimeEventLine('stop', [
['time', formatSeconds(window.endSeconds)],
['state', 'end'],
]),
),
])
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const judgeRankEvents = resolved.judgeRank.changes
.map((change) => {
const badWindow = resolveBMSJudgeWindowsMsForExRankValue(change.exRankValue, judgeWindowMs).bad;
return createScheduledPlaybackEvent(
change.seconds,
nextOrder++,
createRuntimeEventLine('judge-rank-change', [
['time', formatSeconds(change.seconds)],
['rank', formatLoggedNumericValue(change.exRankValue)],
['bad', `${formatLoggedNumericValue(badWindow)}ms`],
]),
);
})
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const idBase = resolveBMSBase(json);
const baseBGATimeline = buildLoggedBGACueTimeline(
sortedEvents,
resolver,
json.resources.bmp,
BGA_BASE_CHANNEL,
'base',
idBase,
);
const poorBGATimeline = buildLoggedBGACueTimeline(
sortedEvents,
resolver,
json.resources.bmp,
BGA_POOR_CHANNEL,
'poor',
idBase,
);
const layerBGATimeline = buildLoggedBGACueTimeline(
sortedEvents,
resolver,
json.resources.bmp,
BGA_LAYER_CHANNEL,
'layer',
idBase,
);
const layer2BGATimeline = buildLoggedBGACueTimeline(
sortedEvents,
resolver,
json.resources.bmp,
BGA_LAYER2_CHANNEL,
'layer2',
idBase,
);
const baseBGAEvents = baseBGATimeline
.map((cue) => createScheduledPlaybackEvent(cue.seconds, nextOrder++, formatLoggedBGACueText(cue)))
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const poorBGAEvents = poorBGATimeline
.map((cue) => createScheduledPlaybackEvent(cue.seconds, nextOrder++, formatLoggedBGACueText(cue)))
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const layerBGAEvents = layerBGATimeline
.map((cue) => createScheduledPlaybackEvent(cue.seconds, nextOrder++, formatLoggedBGACueText(cue)))
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const layer2BGAEvents = layer2BGATimeline
.map((cue) => createScheduledPlaybackEvent(cue.seconds, nextOrder++, formatLoggedBGACueText(cue)))
.filter((event): event is NoTUIScheduledPlaybackEvent => event !== undefined);
const scheduledEvents = mergeScheduledPlaybackEventGroups([
measureLengthEvents,
bpmEvents,
scrollEvents,
speedEvents,
stopEvents,
judgeRankEvents,
baseBGAEvents,
poorBGAEvents,
layerBGAEvents,
layer2BGAEvents,
]);
// LR2 starts its miss layer from `#BMP00`; only `#POORBGA 2` (no POOR image) turns that off, and a missing,
// unparsable or out-of-range value is `0`, the usual behaviour.
const shouldUsePoorBMP00Fallback =
(json.bms.poorBGA === undefined || Number.parseInt(json.bms.poorBGA.trim(), 10) !== 2) &&
typeof json.resources.bmp['00'] === 'string' &&
json.resources.bmp['00'].length > 0;
const poorFallbackKey = shouldUsePoorBMP00Fallback ? '00' : undefined;
const poorFallbackResourcePath = poorFallbackKey ? json.resources.bmp[poorFallbackKey] : undefined;
const poorFallbackUntilSeconds = poorBGATimeline[0]?.seconds ?? Number.POSITIVE_INFINITY;
let cursor = 0;
let poorActive = false;
const resolvePoorCueAt = (seconds: number): LoggedBGACue | undefined => {
const activeCue = findActiveLoggedBGACue(poorBGATimeline, seconds);
if (activeCue?.key) {
return activeCue;
}
if (poorFallbackKey && seconds < poorFallbackUntilSeconds) {
return {
seconds,
key: poorFallbackKey,
resourcePath: poorFallbackResourcePath,
layer: 'poor',
};
}
return undefined;
};
return {
flushUntil: (seconds) => {
const safeSeconds = Math.max(0, seconds) + REALTIME_AUDIO_TRIGGER_EPSILON_SECONDS;
while (cursor < scheduledEvents.length) {
const scheduledEvent = scheduledEvents[cursor]!;
if (scheduledEvent.seconds > safeSeconds) {
break;
}
writeOutput(scheduledEvent.text);
cursor += 1;
}
},
logPoorTriggered: (seconds) => {
const cue = resolvePoorCueAt(seconds);
const normalizedResourcePath =
typeof cue?.resourcePath === 'string' ? normalizeLoggedResourcePath(cue.resourcePath) : undefined;
poorActive = true;
writeOutput(
createRuntimeEventLine('bga-poor', [
['time', formatSeconds(seconds)],
['state', 'trigger'],
['key', cue?.key],
['asset', normalizedResourcePath],
['file', normalizedResourcePath ? basename(normalizedResourcePath) : undefined],
]),
);
},
logPoorCleared: (seconds) => {
if (!poorActive) {
return;
}
poorActive = false;
writeOutput(
createRuntimeEventLine('bga-poor', [
['time', formatSeconds(seconds)],
['state', 'clear'],
]),
);
},
};
}
export function printLaneMap(writeOutput: (text: string) => void, bindings: LaneBinding[]): void {
writeOutput('Channel map:\n');
for (const binding of bindings) {
writeOutput(` ${binding.channel} => ${binding.keyLabel}\n`);
}
}
function formatGrooveGaugeNumber(value: number): string {
Iif (!Number.isFinite(value)) {
return '-';
}
const rounded = Math.round(value);
return Math.abs(value - rounded) <= 1e-9 ? String(rounded) : value.toFixed(2);
}
function formatGrooveGaugeStatus(summary: PlayerSummary): string {
return summary.gauge?.cleared === true ? 'CLEAR' : 'FAILED';
}
export function renderSummary(summary: PlayerSummary, moneyScore: boolean | number): string {
const maxExScore = Math.max(0, summary.total * _____EX_SCORE_PER_PGREAT);
const exScoreRate = maxExScore > 0 ? summary.exScore / maxExScore : 0;
// `true` is LR2's money score; a number is a ruleset score's maximum (plugout's 100000).
const scoreMax = moneyScore === true ? LR2_MONEY_SCORE_MAX : moneyScore === false ? undefined : moneyScore;
const scoreRate = scoreMax !== undefined ? summary.score / scoreMax : 0;
const gauge = summary.gauge;
return (
[
'--- Result ---',
`TOTAL : ${summary.total}`,
...(gauge
? [
`GAUGE : ${gauge.current.toFixed(2)} / ${gauge.max.toFixed(2)} ${formatGrooveGaugeStatus(summary)} (TOTAL ${formatGrooveGaugeNumber(gauge.effectiveTotal)})`,
]
: []),
`PGREAT : ${summary.perfect}`,
`GREAT : ${summary.great}`,
`GOOD : ${summary.good}`,
`BAD : ${summary.bad}`,
`POOR : ${summary.poor}`,
`EMPTY : ${summary.emptyPoor}`,
`FAST : ${summary.fast}`,
`SLOW : ${summary.slow}`,
`EX-SCORE: ${summary.exScore} / ${maxExScore} (${(exScoreRate * 100).toFixed(2)}%)`,
// Only LR2 defines a money score; the other rulesets report EX-SCORE in this field, so printing a
// percentage of 200000 there would be meaningless.
...(scoreMax !== undefined
? [`SCORE : ${summary.score} / ${scoreMax} (${(scoreRate * 100).toFixed(2)}%)`]
: []),
].join('\n') + '\n'
);
}
|