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 | 3019x 12135x 12135x 12104x 31x 31x 6038x 6038x 6038x 6038x 6038x 3019x 3019x 3019x 3019x 3019x 6089x 3019x 3019x 3019x 3019x 3070x 3070x 3070x 3019x 3019x 2066x 2066x 953x 9096x 2837x 6232x 3070x 963x 2107x 2066x 41x 2x 39x 127x 127x 127x 127x 3019x 3019x 3019x 3019x 3019x 3019x 3019x 3019x 3019x 3019x 14x 3039x 3027x 2x 3025x 3038x 3038x 523x 167x 356x 137x 3038x 3027x 3027x 2886x 141x 85x 85x 56x 56x 194x 194x 138x 194x 56x 3024x 3024x 576x 576x 3019x 2066x 953x 2616x 1729x 887x 887x 403x 339x 64x 6989x | import {
drawRandomOutcomes,
firesBeforeTempoReversal,
hasControlFlow,
type RandomDraws,
type ResolvedChart,
} from '@be-music/chart-model';
import { type BeMusicEvent, type BeMusicJSON, cloneJSON } from '@be-music/chart-source';
import { resolveBMSControlFlowWithDraws } from '@be-music/chart-parser/core';
import { type PlayerStateSignals } from '../state-signals.ts';
import { type LaneBinding } from './lane-layout.ts';
import { type PlayerUISignalBus } from './ui-signal-bus.ts';
import { type RulesetConfig } from '../ruleset/index.ts';
import { initializePlayerUIRuntime } from './bootstrap.ts';
import { createAudioSessionIfEnabled } from './engine-audio.ts';
import { resolveChartRulesetFacts, resolveEngineChart, resolvePlayChart } from './play-chart.ts';
import { getEngineScheduler } from './engine-clock.ts';
import { settleWithTimeout } from '@be-music/shared-utils/async';
import {
type AudioSession,
type AudioSessionLoadProgress,
type CreatePlayerUIRuntimeContext,
type PlayerLoadComponentStatus,
type PlayerLoadProgress,
type PlayerOptions,
type RandomPatternSelection,
} from './engine-types.ts';
// The chart-side steps of a play are runtime-neutral and live in `play-chart.ts`; the engine re-exports them.
export { resolveChartRulesetFacts, resolveEngineChart, resolvePlayChart };
/**
* Play preparation: chart resolution for play, load progress, and the UI / audio runtime start-up.
*/
export function reportResolvedRuleset(options: PlayerOptions, ruleset: RulesetConfig): void {
options.onRulesetResolved?.({
id: ruleset.id,
rulesetId: ruleset.rulesetId,
longNoteStyle: ruleset.longNoteStyle,
windows: ruleset.windows,
});
}
interface ControlFlowResolutionResult {
resolvedJSON: BeMusicJSON;
randomPatterns: RandomPatternSelection[];
}
export function reportLoadProgress(
options: PlayerOptions,
ratio: number,
message: string,
detail?: string,
componentStatuses?: Partial<Pick<PlayerLoadProgress, 'audioStatus' | 'graphicsStatus'>>,
): void {
const listener = options.onLoadProgress;
if (!listener) {
return;
}
const normalizedRatio = Math.max(0, Math.min(1, ratio));
listener({
ratio: normalizedRatio,
message,
detail,
...componentStatuses,
});
}
function createTrackedPromise<T>(task: Promise<T>): TrackedPromise<T> {
let state: TrackedPromiseState<T> = { status: 'pending' };
const promise = task.then(
(value) => {
state = { status: 'fulfilled', value };
return value;
},
(reason) => {
state = { status: 'rejected', reason };
throw reason;
},
);
return {
promise,
getState: () => state,
};
}
function createPlaybackPreparationProgressReporter(options: PlayerOptions): PlaybackPreparationProgressReporter {
let uiRatio = 0;
let audioRatio = 0;
let audioStatus: PlayerLoadComponentStatus = createPendingLoadComponentStatus('Waiting for audio setup...');
let graphicsStatus: PlayerLoadComponentStatus = createPendingLoadComponentStatus('Waiting for graphics setup...');
const emit = (message: string, detail?: string): void => {
reportLoadProgress(
options,
PLAYBACK_PREPARATION_BASE_RATIO +
uiRatio * PLAYBACK_PREPARATION_UI_RATIO_WEIGHT +
audioRatio * PLAYBACK_PREPARATION_AUDIO_RATIO_WEIGHT,
message,
detail,
{
audioStatus,
graphicsStatus,
},
);
};
return {
reportUIProgress: (ratio, message, detail) => {
uiRatio = Math.max(0, Math.min(1, ratio));
graphicsStatus = createPendingLoadComponentStatus(message, detail);
emit(message, detail);
},
reportAudioProgress: (progress) => {
audioRatio = Math.max(0, Math.min(1, progress.ratio));
audioStatus = resolveAudioLoadComponentStatus(progress);
emit(progress.message, progress.detail);
},
markUIReady: (enabled) => {
graphicsStatus = enabled
? createReadyLoadComponentStatus('Ready')
: createDisabledLoadComponentStatus('Disabled');
},
markAudioReady: (audioSession, audioRequested) => {
if (audioRequested === false) {
audioStatus = createDisabledLoadComponentStatus('Disabled');
return;
}
audioStatus = audioSession
? createReadyLoadComponentStatus('Ready')
: createDisabledLoadComponentStatus('Unavailable');
},
};
}
function createPendingLoadComponentStatus(message: string, detail?: string): PlayerLoadComponentStatus {
return {
state: 'pending',
message,
detail,
};
}
function createReadyLoadComponentStatus(message: string): PlayerLoadComponentStatus {
return {
state: 'ready',
message,
};
}
function createDisabledLoadComponentStatus(message: string): PlayerLoadComponentStatus {
return {
state: 'disabled',
message,
};
}
function resolveAudioLoadComponentStatus(progress: AudioSessionLoadProgress): PlayerLoadComponentStatus {
if (progress.message === 'Audio ready.') {
return createReadyLoadComponentStatus('Ready');
}
if (progress.message === 'Audio disabled; skipping audio setup.') {
return createDisabledLoadComponentStatus('Disabled');
}
if (progress.message === 'Audio unavailable.') {
return createDisabledLoadComponentStatus('Unavailable');
}
return createPendingLoadComponentStatus(progress.message, progress.detail);
}
interface PlaybackPreparationProgressReporter {
reportUIProgress: (ratio: number, message: string, detail?: string) => void;
reportAudioProgress: (progress: AudioSessionLoadProgress) => void;
markUIReady: (enabled: boolean) => void;
markAudioReady: (audioSession: AudioSession | undefined, audioRequested: boolean | undefined) => void;
}
type TrackedPromiseState<T> =
| { status: 'pending' }
| { status: 'fulfilled'; value: T }
| { status: 'rejected'; reason: unknown };
interface TrackedPromise<T> {
promise: Promise<T>;
getState: () => TrackedPromiseState<T>;
}
const PLAYBACK_PREPARATION_BASE_RATIO = 0.18;
const PLAYBACK_PREPARATION_UI_RATIO_WEIGHT = 0.12;
const PLAYBACK_PREPARATION_AUDIO_RATIO_WEIGHT = 0.68;
const PREPARED_UI_RUNTIME_SETTLE_TIMEOUT_MS = 300;
async function disposePreparedUIRuntime(
initializedUIRuntime: Awaited<ReturnType<typeof initializePlayerUIRuntime>>,
): Promise<void> {
await settleMaybeAsyncWithTimeout(initializedUIRuntime.uiRuntime?.stop(), PREPARED_UI_RUNTIME_SETTLE_TIMEOUT_MS);
await settleMaybeAsyncWithTimeout(initializedUIRuntime.uiRuntime?.dispose(), PREPARED_UI_RUNTIME_SETTLE_TIMEOUT_MS);
}
async function cleanupFailedPlaybackPreparation(
uiInitialization: TrackedPromise<Awaited<ReturnType<typeof initializePlayerUIRuntime>>>,
audioInitialization: TrackedPromise<AudioSession | undefined>,
): Promise<void> {
const uiState = uiInitialization.getState();
if (uiState.status === 'fulfilled') {
await disposePreparedUIRuntime(uiState.value);
} else if (uiState.status === 'pending') {
void uiInitialization.promise.then(disposePreparedUIRuntime).catch(() => undefined);
}
const audioState = audioInitialization.getState();
if (audioState.status === 'fulfilled') {
await disposeAudioSessionSafely(audioState.value);
} else if (audioState.status === 'pending') {
void audioInitialization.promise
.then((audioSession) => disposeAudioSessionSafely(audioSession))
.catch(() => undefined);
}
}
export async function initializePlaybackRuntimeResources(params: {
resolvedJSON: BeMusicJSON;
resolvedChart: ResolvedChart;
options: PlayerOptions;
mode: CreatePlayerUIRuntimeContext['mode'];
laneDisplayMode: string;
laneBindings: LaneBinding[];
speed: number;
judgeWindowMs: number;
highSpeed: number;
randomPatternSummary: string | undefined;
stateSignals: PlayerStateSignals;
uiSignals: PlayerUISignalBus;
totalSeconds: number;
/** `totalSeconds` is the chart's own end, which a longer BGA does not extend. */
fixedEnd?: boolean;
audioMode: 'auto' | 'manual';
}): Promise<
Awaited<ReturnType<typeof initializePlayerUIRuntime>> & {
audioSession: AudioSession | undefined;
}
> {
const progressReporter = createPlaybackPreparationProgressReporter(params.options);
const uiInitialization = createTrackedPromise(
initializePlayerUIRuntime({
options: params.options,
resolvedJSON: params.resolvedJSON,
mode: params.mode,
laneDisplayMode: params.laneDisplayMode,
laneBindings: params.laneBindings,
speed: params.speed,
judgeWindowMs: params.judgeWindowMs,
highSpeed: params.highSpeed,
randomPatternSummary: params.randomPatternSummary,
stateSignals: params.stateSignals,
uiSignals: params.uiSignals,
totalSeconds: params.totalSeconds,
fixedEnd: params.fixedEnd,
onLoadProgress: progressReporter.reportUIProgress,
}).then((initializedUIRuntime) => {
progressReporter.markUIReady(initializedUIRuntime.uiEnabled);
return initializedUIRuntime;
}),
);
const audioInitialization = createTrackedPromise(
createAudioSessionIfEnabled(
params.resolvedChart,
(params.options.speed ?? 1) === params.speed ? params.options : { ...params.options, speed: params.speed },
params.audioMode,
progressReporter.reportAudioProgress,
).then((audioSession) => {
progressReporter.markAudioReady(audioSession, params.options.audio);
return audioSession;
}),
);
try {
const [uiInitResult, audioSession] = await Promise.all([uiInitialization.promise, audioInitialization.promise]);
return {
...uiInitResult,
audioSession,
};
} catch (error) {
await cleanupFailedPlaybackPreparation(uiInitialization, audioInitialization);
throw error;
}
}
/**
* Draws `json`'s `#RANDOM` / `#SWITCH` outcomes with `randomSource` and resolves the chart with them, reporting the
* `#RANDOM` / `#SETRANDOM` patterns for the summary. Shorthand for `drawRandomOutcomes` + `resolveBMSControlFlowWithDraws`.
*/
export function resolveBMSControlFlowForPlayback(
json: BeMusicJSON,
randomSource: () => number = Math.random,
): ControlFlowResolutionResult {
return resolvePlaybackControlFlow(json, drawRandomOutcomes(json, randomSource));
}
/**
* The engine's single control-flow step: a chart that still carries control flow is resolved exactly once with
* `draws`; a resolved chart (no control flow) is played as is. `draws` also feed the RANDOM summary.
*/
function resolvePlaybackControlFlow(json: BeMusicJSON, draws: RandomDraws): ControlFlowResolutionResult {
return {
resolvedJSON: hasControlFlow(json) ? resolveBMSControlFlowWithDraws(json, draws) : cloneJSON(json),
randomPatterns: randomPatternsFromDraws(draws),
};
}
export function resolvePlayerChart(json: BeMusicJSON, options: PlayerOptions): ControlFlowResolutionResult {
if (options.randomDraws === undefined && hasControlFlow(json)) {
// The engine never draws: rolling here would give the play branches nobody outside the engine knows about (the
// host's scene, result screen and replay would show another roll, or stack a second branch on top).
throw new TypeError(
'The chart still carries #RANDOM / #SWITCH control flow. Resolve it once with resolvePlayChart (or ' +
'drawRandomOutcomes + resolveBMSControlFlowWithDraws) and pass the draws as PlayerOptions.randomDraws.',
);
}
return resolvePlaybackControlFlow(json, options.randomDraws ?? []);
}
function randomPatternsFromDraws(draws: RandomDraws): RandomPatternSelection[] {
const patterns: RandomPatternSelection[] = [];
for (const draw of draws) {
if (draw.command === 'RANDOM') {
patterns.push({ index: patterns.length + 1, current: draw.value, total: draw.range });
} else if (draw.command === 'SETRANDOM') {
patterns.push({ index: patterns.length + 1, current: draw.value, total: draw.value });
}
}
return patterns;
}
export function formatRandomPatternSummary(randomPatterns: ReadonlyArray<RandomPatternSelection>): string | undefined {
const count = randomPatterns.length;
if (count === 0) {
return undefined;
}
if (count === 1) {
const only = randomPatterns[0];
return `RANDOM ${only.current}/${only.total}`;
}
let summary = 'RANDOM ';
for (let index = 0; index < count; index += 1) {
const pattern = randomPatterns[index]!;
if (index > 0) {
summary += ' ';
}
summary += `#${pattern.index} ${pattern.current}/${pattern.total}`;
}
return summary;
}
interface TimedAudioVolumeEvent {
event: BeMusicEvent;
seconds: number;
}
/**
* The chart's dynamic volume changes as realtime audio events (times clamped to the chart start). Changes behind an
* LR2 negative-BPM reversal never fire: the event pump froze there (#134).
*/
export function collectRealtimeAudioVolumeEvents(resolved: ResolvedChart): TimedAudioVolumeEvent[] {
const { reversal } = resolved;
return resolved.volumeChanges
.filter((change) => firesBeforeTempoReversal(reversal, change.seconds, change.event.channel))
.map((change) => ({ event: change.event, seconds: Math.max(0, change.seconds) }));
}
export function resolveAudioBackendLabel(options: PlayerOptions, audioSession: AudioSession | undefined): string {
if (options.audio === false) {
return 'off';
}
return audioSession?.backendLabel ?? 'none';
}
export async function finalizeAudioSessionSafely(audioSession: AudioSession | undefined): Promise<void> {
if (!audioSession) {
return;
}
await audioSession.finish().catch(() => undefined);
await settleMaybeAsyncWithTimeout(audioSession.dispose(), 600);
}
export async function disposeAudioSessionSafely(audioSession: AudioSession | undefined): Promise<void> {
if (!audioSession) {
return;
}
await settleMaybeAsyncWithTimeout(audioSession.dispose(), 600);
}
export async function settleMaybeAsyncWithTimeout(
task: void | Promise<void> | undefined,
timeoutMs: number,
): Promise<boolean> {
return settleWithTimeout(task, timeoutMs, (callback, ms) => getEngineScheduler().setTimeout(callback, ms));
}
|