All files / player-browser/src/chart bga-timeline.ts

100% Statements 102/102
96% Branches 120/125
100% Functions 27/27
100% Lines 86/86

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                                                      3x                         214x                         143x 143x 143x 76x   143x 36x   143x 3x   143x 143x 143x                     4x 15x 12x       95x       668x       20x       286x   286x 136x 136x         25x 25x       56x                                             174x 172x 3x 3x 3x 3x   169x 3x   166x 166x 166x 174x 174x                                                                           23x 39x 23x 23x 23x   23x 23x 23x 92x 92x 92x   23x                                                                                             2x 7x 2x 5x 3x   3x 2x 8x 13x 13x     2x               96x 47x 96x 71x 49x                 88x                                                                                                   170x 170x                         207x                           39x                                           207x 207x 6x 201x 6x 6x   207x   170x 170x 125x 45x 90x 90x 90x          
import type { BmsonBGAFrame } from '@be-music/player-engine/display';
import type { BeMusicJSON } from '@be-music/chart-source';
import { collectBGASubRegions } from './bga-subregions.ts';
import {
  pickBGAOpacity,
  pickBGATint,
  type BGAOpacityTimelines,
  type BGATimelines,
  type TimingResolver,
  buildBGATimelines,
} from '@be-music/chart-model';
import { pickActiveBGACue as pickActiveCoreBGACue } from '@be-music/player-engine/display';
 
export interface BGACue {
  seconds: number;
  bmpKey: string | undefined;
}
 
export interface BGATextureLoadKeys {
  base: Set<string>;
  layer: Set<string>;
}
 
export function buildBGATimeline(
  chart: BeMusicJSON,
  resolver: TimingResolver,
): { base: BGACue[]; layer: BGACue[]; layer2: BGACue[]; poor: BGACue[] } {
  return toBrowserBGATimeline(buildBGATimelines(chart, resolver));
}
 
/**
 * The browser scenes' BGA cue lists from a chart's BGA timelines (`ResolvedChart.bga`): the base and POOR cues as is,
 * with independent layer channels (`07` / `0A`).
 */
export function toBrowserBGATimeline(timelines: BGATimelines): {
  base: BGACue[];
  layer: BGACue[];
  layer2: BGACue[];
  poor: BGACue[];
} {
  return {
    base: timelines.base.map(toBrowserBGACue),
    layer: timelines.layer.map(toBrowserBGACue),
    layer2: timelines.layer2.map(toBrowserBGACue),
    poor: timelines.poor.map(toBrowserBGACue),
  };
}
 
export function collectBGATextureLoadKeys(
  chart: BeMusicJSON,
  timeline: { base: readonly BGACue[]; layer: readonly BGACue[]; layer2?: readonly BGACue[]; poor: readonly BGACue[] },
  poorBGAFallbackKey: string | undefined,
): BGATextureLoadKeys {
  const base = new Set<string>();
  const layer = new Set<string>();
  for (const cue of [...timeline.base, ...timeline.poor]) {
    Eif (cue.bmpKey) base.add(cue.bmpKey);
  }
  for (const cue of [...timeline.layer, ...(timeline.layer2 ?? [])]) {
    if (cue.bmpKey) layer.add(cue.bmpKey);
  }
  if (poorBGAFallbackKey) {
    base.add(poorBGAFallbackKey);
  }
  addReferencedSubRegionSources(chart, base);
  addReferencedSubRegionSources(chart, layer);
  return { base, layer };
}
 
/**
 * The cues of `cues` (sorted by time) a play of `[startSeconds, endSeconds]` shows: the one in force at its start and
 * those in it. A PRACTICE play of picked bars loads only their images (`prepareBGA`).
 */
export function clipBGACuesToWindow(
  cues: readonly BGACue[],
  window: { readonly startSeconds: number; readonly endSeconds: number },
): BGACue[] {
  let first = 0;
  for (let index = 0; index < cues.length; index += 1) if (cues[index]!.seconds <= window.startSeconds) first = index;
  return cues.slice(first).filter((cue, index) => index === 0 || cue.seconds <= window.endSeconds);
}
 
export function pickActiveBGAKey(cues: ReadonlyArray<BGACue>, seconds: number): string | undefined {
  return pickActiveBGACue(cues, seconds)?.bmpKey;
}
 
export function pickActiveBGACue(cues: ReadonlyArray<BGACue>, seconds: number): BGACue | undefined {
  return pickActiveCoreBGACue(cues, seconds);
}
 
function toBrowserBGACue(cue: { seconds: number; key?: string }): BGACue {
  return { seconds: cue.seconds, bmpKey: cue.key };
}
 
function addReferencedSubRegionSources(chart: BeMusicJSON, keys: Set<string>): void {
  const regions = collectBGASubRegions(chart);
  // Set iteration visits newly discovered dependencies too, and visits each key only once (including cycles).
  for (const key of keys) {
    const region = regions.get(key);
    if (region) keys.add(region.sourceBMP);
  }
}
 
export function isVideoExtension(path: string): boolean {
  const lower = path.toLowerCase();
  return /\.(mpg|mpeg|mp4|m4v|avi|mov|wmv|webm|mkv)$/u.test(lower);
}
 
/** Edge length of the BMS BGA canvas: every BGA rect on screen stands for this 256x256 image space. */
export const BMS_BGA_CANVAS_SIZE = 256;
 
export interface BGARect {
  x: number;
  y: number;
  w: number;
  h: number;
}
 
/**
 * Where a still BGA image of `imageWidth` x `imageHeight` px lands inside the BGA `rect`, which stands for the 256x256
 * BMS canvas. An image whose long edge fits the canvas keeps its own pixel size on it, centered horizontally and
 * against the top edge — the BM98 convention LR2 and beatoraja (`BGImageProcessor`) follow — so a 256x161 frame leaves
 * an empty band at the bottom rather than being stretched. A larger image fills the whole rect, as in LR2 and
 * beatoraja. `origin` places a `#BGAxx` sub-region at its authored `dx dy` on the canvas instead of centering it.
 */
export function resolveBGAImageRect(
  imageWidth: number,
  imageHeight: number,
  rect: BGARect,
  origin?: { x: number; y: number },
  bgaMode?: 0 | 1 | 2,
): BGARect {
  if (bgaMode === 0) return { ...rect };
  if (bgaMode !== undefined && imageWidth > 0 && imageHeight > 0) {
    const scale = bgaMode === 2 ? 0.8 : 1;
    const w = (imageWidth * scale * rect.w) / BMS_BGA_CANVAS_SIZE;
    const h = (imageHeight * scale * rect.h) / BMS_BGA_CANVAS_SIZE;
    return { x: rect.x + (rect.w - w) / 2, y: rect.y, w, h };
  }
  if (!(imageWidth > 0) || !(imageHeight > 0) || Math.max(imageWidth, imageHeight) > BMS_BGA_CANVAS_SIZE) {
    return { x: rect.x, y: rect.y, w: rect.w, h: rect.h };
  }
  const scaleX = rect.w / BMS_BGA_CANVAS_SIZE;
  const scaleY = rect.h / BMS_BGA_CANVAS_SIZE;
  const canvasX = origin ? origin.x : Math.floor((BMS_BGA_CANVAS_SIZE - imageWidth) / 2);
  const canvasY = origin ? origin.y : 0;
  return {
    x: rect.x + canvasX * scaleX,
    y: rect.y + canvasY * scaleY,
    w: imageWidth * scaleX,
    h: imageHeight * scaleY,
  };
}
 
/** The BGA keys showing this frame, as `renderBGA` resolved them (`#SWBGA` frames already picked). */
export interface ActiveBGAKeys {
  opacity?: Record<keyof BGAOpacityTimelines, number>;
  tint?: Record<keyof BGAOpacityTimelines, number>;
  base: string | undefined;
  layer: string | undefined;
  layer2?: string | undefined;
  /** Set only while a POOR is being shown. */
  poor: string | undefined;
  poorOverlays?: boolean;
}
 
/**
 * The `frame.bga` a skin that sets `drawsBGA` receives: the image behind each active key (`resolve` reads the base or
 * layer texture map), with `poorActive` set when a POOR image is there to show in place of the base and layer.
 */
export function buildSkinBGAFrame<Image>(
  keys: ActiveBGAKeys,
  resolve: (key: string, track: 'base' | 'layer', tint?: number) => Image | undefined,
  subRegionOrigins?: ReadonlyMap<string, { x: number; y: number }>,
): {
  base?: Image;
  layer?: Image;
  layer2?: Image;
  poor?: Image;
  poorActive: boolean;
  poorOverlays?: boolean;
  opacity?: Record<keyof BGAOpacityTimelines, number>;
  origins?: Partial<Record<keyof BGAOpacityTimelines, { x: number; y: number }>>;
} {
  const image = (key: string, map: 'base' | 'layer', plane: keyof BGAOpacityTimelines): Image | undefined =>
    keys.tint ? resolve(key, map, keys.tint[plane]) : resolve(key, map);
  const base = keys.base !== undefined ? image(keys.base, 'base', 'base') : undefined;
  const layer = keys.layer !== undefined ? image(keys.layer, 'layer', 'layer') : undefined;
  const layer2 = keys.layer2 !== undefined ? image(keys.layer2, 'layer', 'layer2') : undefined;
  // POOR images decode like the base (no chroma key), so they live in the base map.
  const poor = keys.poor !== undefined ? image(keys.poor, 'base', 'poor') : undefined;
  const origins: Partial<Record<keyof BGAOpacityTimelines, { x: number; y: number }>> = {};
  for (const track of ['base', 'layer', 'layer2', 'poor'] as const) {
    const key = keys[track];
    const origin = key !== undefined ? subRegionOrigins?.get(key) : undefined;
    if (origin !== undefined) origins[track] = origin;
  }
  return {
    ...(base !== undefined ? { base } : {}),
    ...(layer !== undefined ? { layer } : {}),
    ...(layer2 !== undefined ? { layer2 } : {}),
    ...(poor !== undefined ? { poor } : {}),
    poorActive: poor !== undefined,
    ...(Object.keys(origins).length > 0 ? { origins } : {}),
    ...(keys.opacity !== undefined ? { opacity: keys.opacity } : {}),
    ...(keys.poorOverlays ? { poorOverlays: true } : {}),
  };
}
 
/** One stage of a stitched NONSTOP chart as its BGA needs it (`NonstopStitchStage` from `@be-music/player-engine/course`). */
export interface NonstopBGAStage {
  bgaOpacity?: BGAOpacityTimelines;
  poorBGAMode?: 0 | 1 | 2;
  windowStart: number;
  windowEnd: number;
  bmpKeys: readonly string[];
  bgaFadeIn?: { start: number; end: number };
  bgaFadeOut?: { start: number; end: number };
}
 
/**
 * A stage's own base, layer and POOR BGA cues, the stitched timeline's cues split by the stage that owns each BMP key.
 */
export interface NonstopStageBGATimeline {
  base: BGACue[];
  layer: BGACue[];
  layer2?: BGACue[];
  poor: BGACue[];
}
 
/**
 * Splits a stitched NONSTOP chart's base, layer and POOR BGA cues by stage (its stitched BMP keys are per stage), as
 * LR2 keeps a base, layer and POOR image per stage (OpenLR2 `LR2f.cpp` L12726-L12780). A cue that clears a layer (no
 * key) goes to the stage whose window it falls in.
 *
 * LR2 draws one stage's three images each frame: `LR2body.exe` 0x4350df picks the stage by the crossfade weights
 * (`bgaMixer`) and copies its base, layer and POOR image into the ones it draws, so a miss shows the POOR image of the
 * stage on screen, never a `#BMP00` fallback. The scenes draw each stage's stack at its crossfade opacity instead of
 * picking one at random, and a stage's POOR image replaces that stage's base and layer.
 */
export function splitNonstopBGATimeline(
  timeline: { base: readonly BGACue[]; layer: readonly BGACue[]; layer2?: readonly BGACue[]; poor?: readonly BGACue[] },
  stages: readonly NonstopBGAStage[],
): NonstopStageBGATimeline[] {
  const stageOfKey = new Map<string, number>();
  stages.forEach((stage, index) => stage.bmpKeys.forEach((key) => stageOfKey.set(key, index)));
  const stageAt = (seconds: number): number => {
    const index = stages.findIndex((stage) => seconds < stage.windowEnd);
    return index < 0 ? stages.length - 1 : index;
  };
  const split = stages.map((): NonstopStageBGATimeline => ({ base: [], layer: [], layer2: [], poor: [] }));
  for (const track of ['base', 'layer', 'layer2', 'poor'] as const) {
    for (const cue of timeline[track] ?? []) {
      const stage = (cue.bmpKey !== undefined ? stageOfKey.get(cue.bmpKey) : undefined) ?? stageAt(cue.seconds);
      split[stage]?.[track]?.push(cue);
    }
  }
  return split;
}
 
/**
 * How opaque a NONSTOP stage's BGA is at `seconds`: fully inside its window, fading in over the 3 s before it and out
 * over the 3 s after it, linearly as LR2 mixes its stage BGA layers (OpenLR2 L27047-L27052).
 */
export function resolveNonstopBGAAlpha(stage: NonstopBGAStage, seconds: number): number {
  const ramp = (window: { start: number; end: number }): number =>
    window.end > window.start ? Math.min(1, Math.max(0, (seconds - window.start) / (window.end - window.start))) : 1;
  if (seconds < stage.windowStart) return stage.bgaFadeIn !== undefined ? ramp(stage.bgaFadeIn) : 0;
  if (seconds >= stage.windowEnd) return stage.bgaFadeOut !== undefined ? 1 - ramp(stage.bgaFadeOut) : 0;
  return 1;
}
 
/**
 * Whether a miss layer shows at `seconds`: from the last miss (`missSeconds`, on the same second clock) for
 * `durationSeconds`, whatever is judged in between, as `BGAProcessor.drawBGA` draws it for `misslayerDuration` ms from
 * `misslayertime`. The shared built-in/LR2 renderer supplies pause-aware elapsed seconds. A later miss restarts the window.
 */
export function isMissLayerShown(missSeconds: number | undefined, seconds: number, durationSeconds: number): boolean {
  return missSeconds !== undefined && seconds >= missSeconds && seconds - missSeconds < durationSeconds;
}
 
/** One BGA stack to draw: its base and layer cues (and a POOR image in place of them) at `alpha`. */
export interface BGAStack {
  bgaMode?: 0 | 1 | 2;
  tint?: Record<keyof BGAOpacityTimelines, number>;
  opacity?: Record<keyof BGAOpacityTimelines, number>;
  poorOverlays?: boolean;
  alpha: number;
  baseCue: BGACue | undefined;
  layerCue: BGACue | undefined;
  layer2Cue?: BGACue | undefined;
  /** Set only while a POOR is being shown and the stack has a POOR cue. */
  poorKey?: string | undefined;
  /** Explicit engine frame start for a conditional POOR movie. */
  poorCue?: BGACue;
}
 
/** What {@link resolveBGAStacks} reads: the chart's cues, a stitched NONSTOP chart's stages and the BGA rect's flags. */
export interface BGAStacksInput {
  bgaMode?: 0 | 1 | 2;
  stageBGAMode?: (windowStart: number) => 0 | 1 | 2 | undefined;
  bmsonBGA?: BmsonBGAFrame;
  noPoor?: boolean;
  poorBGAMode?: 0 | 1 | 2;
  /** The chart's cues; its POOR cues, when given, are picked during a POOR. */
  timeline: {
    base: readonly BGACue[];
    layer: readonly BGACue[];
    layer2?: readonly BGACue[];
    poor?: readonly BGACue[];
    opacity?: BGAOpacityTimelines;
  };
  /** A stitched NONSTOP chart's stages and their own cues (`splitNonstopBGATimeline`), in stage order. */
  nonstop?: { stages: readonly NonstopBGAStage[]; timelines: readonly NonstopStageBGATimeline[] } | undefined;
  /** The cue clock in chart seconds. */
  seconds: number;
  noBase?: boolean;
  noLayer?: boolean;
  /** A POOR is being shown. */
  inPoorWindow: boolean;
}
 
/**
 * The BGA stacks to draw at `seconds`: the chart's base and layer cues at full opacity, or for a stitched NONSTOP chart
 * each stage's own cues (and, during a POOR, its own POOR image) at the opacity of its crossfade
 * ({@link resolveNonstopBGAAlpha}), earlier stages first. Every skin family draws a NONSTOP chart's BGA from these.
 */
export function resolveBGAStacks(input: BGAStacksInput): BGAStack[] {
  const { seconds } = input;
  const pick = (
    timeline: {
      base: readonly BGACue[];
      layer: readonly BGACue[];
      layer2?: readonly BGACue[];
      poor?: readonly BGACue[];
    },
    alpha: number,
    mode: 0 | 1 | 2 = 0,
    opacity?: BGAOpacityTimelines,
    stage?: number,
    bgaMode?: 0 | 1 | 2,
  ): BGAStack => {
    const stack: BGAStack = {
      ...(bgaMode !== undefined ? { bgaMode } : {}),
      ...(opacity !== undefined
        ? {
            opacity: {
              base: pickBGAOpacity(opacity.base, seconds),
              layer: pickBGAOpacity(opacity.layer, seconds),
              layer2: pickBGAOpacity(opacity.layer2, seconds),
              poor: pickBGAOpacity(opacity.poor, seconds),
            },
          }
        : {}),
      ...(opacity !== undefined &&
      [opacity.base, opacity.layer, opacity.layer2, opacity.poor].some((cues) =>
        cues.some((cue) => cue.tint !== undefined),
      )
        ? {
            tint: {
              base: pickBGATint(opacity.base, seconds),
              layer: pickBGATint(opacity.layer, seconds),
              layer2: pickBGATint(opacity.layer2, seconds),
              poor: pickBGATint(opacity.poor, seconds),
            },
          }
        : {}),
      alpha,
      baseCue: input.noBase ? undefined : pickActiveBGACue(timeline.base, seconds),
      layerCue: input.noLayer ? undefined : pickActiveBGACue(timeline.layer, seconds),
      ...(timeline.layer2 !== undefined
        ? { layer2Cue: input.noLayer ? undefined : pickActiveBGACue(timeline.layer2, seconds) }
        : {}),
      ...(mode === 1 ? { poorOverlays: true } : {}),
      ...(input.inPoorWindow && !input.noPoor && mode !== 2 && timeline.poor !== undefined
        ? { poorKey: pickActiveBGAKey(timeline.poor, seconds) }
        : {}),
    };
    const frame = input.nonstop === undefined || input.bmsonBGA?.stage === stage ? input.bmsonBGA : undefined;
    if (frame?.plane === 'layer' && !input.noLayer) {
      stack.layerCue = { seconds: frame.frameStartSeconds, bmpKey: frame.key };
    } else if (frame?.plane === 'poor' && !input.noPoor && mode !== 2) {
      stack.poorKey = frame.key;
      stack.poorCue = { seconds: frame.frameStartSeconds, bmpKey: frame.key };
    }
    return stack;
  };
  const nonstop = input.nonstop;
  if (nonstop === undefined)
    return [pick(input.timeline, 1, input.poorBGAMode, input.timeline.opacity, undefined, input.bgaMode)];
  return nonstop.stages.flatMap((stage, index) => {
    const timeline = nonstop.timelines[index];
    const alpha = resolveNonstopBGAAlpha(stage, seconds);
    return timeline !== undefined && alpha > 0
      ? [pick(timeline, alpha, stage.poorBGAMode, stage.bgaOpacity, index, input.stageBGAMode?.(stage.windowStart))]
      : [];
  });
}