All files / player-browser/src/view/beatoraja/play bga.ts

85.16% Statements 178/209
84.32% Branches 156/185
82.35% Functions 14/17
89.5% Lines 162/181

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                                                                                                                                                                                                      25x       25x               25x                                       25x 25x       25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x     25x                                               56x 56x 56x 56x 58x 58x 58x 58x 58x   56x 56x 54x 54x         54x 54x                   58x 2x 1x 1x   2x 2x 2x   54x 53x 24x           24x   53x                     54x 54x 58x   58x 7x 7x 5x 5x   7x 7x 7x                   7x   51x 58x 44x 44x                     51x 58x 21x 21x                     51x 58x 9x 9x                     51x 4x 4x 4x 4x   4x 4x 4x                       54x 54x 54x 3x 3x 3x 1x 3x                     54x 54x                                                                                                         1x 1x 2x 2x         25x 25x             25x 33x 33x           25x 25x 25x 25x         117x 117x         83x 28x             28x 28x   83x                                   88x         88x 87x 51x         87x   87x         88x 36x 36x 36x 36x 36x 36x 36x 36x   87x         88x 88x 88x 88x 88x 88x 88x   261x     88x 88x                             54x 47x 16x   54x 1x 1x   53x 80x 80x 22x   22x           80x 80x 80x 80x     80x 20x 20x         22x 4x 18x   53x                   13x 13x 13x 13x                               25x 25x 24x 24x    
import type { KeyBoundBGAFrame, BmsonBGAFrame } from '@be-music/player-engine/display';
import { keyBoundBGAResourceKey } from '../../../chart/key-bound-bga.ts';
import { resolveChartOptionsAt, type ChartOptionProgram, type BGAOpacityTimelines } from '@be-music/chart-model';
// BGA (background animation) rendering layer for a beatoraja play skin.
//
// The skin's `bga` block holds an `id` referencing one of the destination[] groups; that group's
// keyframes describe where on the skin canvas the BGA should be drawn (gated by `if[]` so multi-layout
// skins like the play24 reference can place the BGA differently for the Half / Hybrid / Separate Lane
// layouts).
//
// The BGA cue lists (`base` / `layer` / `poor`) come from the chart's BGA timeline — same `BGACue[]`
// shape the LR2 gameplay path consumes. The host loads those once when the chart is prepared and hands
// them to the layer alongside the decoded BMP textures keyed by `#BMPxx` slot.
//
// Layering rules, as beatoraja's `BGAProcessor.drawBGA` draws them:
//   - `base` (chart channel `04`) is the always-active BGA.
//   - `layer` (channel `07`) and `layer2` (channel `0A`) independently draw above base, black keyed out.
//   - `poor` (channel `06`) replaces both while the miss layer shows (`misslayerDuration` from the last miss).
//
// A stitched NONSTOP chart draws one such stack per stage at the opacity of its crossfade
// (`resolveBGAStacks`, the stacks the built-in and LR2 scenes draw too), so the BGA cross-fades over
// 3 s at a stage seam as LR2 does.
 
import { Container, Graphics, Sprite, Texture } from 'pixi.js';
import { resolveBGAVideoResync } from '../../shared/bga-renderer.ts';
import type { BGAFeed } from '../../../media/bga-camera.ts';
import { fitBGACameraRect } from '../../../media/bga-camera-fit.ts';
import { destinationToSpriteProps, type BeatorajaRenderContext } from '../../../skin/beatoraja/render.ts';
import {
  normalizeBeatorajaDestinations,
  type BeatorajaDestinationGroup,
  type BeatorajaSkin,
} from '@be-music/skin-beatoraja';
import {
  resolveBGAImageRect,
  resolveBGAStacks,
  type BGACue,
  type NonstopBGAStage,
  type NonstopStageBGATimeline,
} from '../../../chart/bga-timeline.ts';
 
export interface BeatorajaBGALayerOptions {
  skin: BeatorajaSkin;
  chartOptionProgram?: ChartOptionProgram;
  subRegionOrigins?: ReadonlyMap<string, { x: number; y: number }>;
  poorBGAMode?: 0 | 1 | 2;
  /**
   * Decoded BGA textures keyed by `#BMPxx` slot label (`'00'`..`'ZZ'`). Same map the LR2 path's BGA
   * loader produces; the player can build it once and share it across the gameplay views.
   */
  textures: ReadonlyMap<string, Texture>;
  /**
   * The layer track's textures, black keyed out for a BMS chart. A layer key missing here is looked up in `textures`.
   */
  layerTextures?: ReadonlyMap<string, Texture>;
  /**
   * Chart-time BGA cue lists. Built via `buildBGATimeline(chart, resolver)` in `chart/bga-timeline.ts`.
   * Pass an empty `{ base: [], layer: [], poor: [] }` if the chart has no BGA — the layer hides itself.
   */
  cues: {
    opacity?: BGAOpacityTimelines;
    base: ReadonlyArray<BGACue>;
    layer: ReadonlyArray<BGACue>;
    layer2?: ReadonlyArray<BGACue>;
    poor: ReadonlyArray<BGACue>;
  };
  /**
   * Optional video-element map for keys whose BMPxx resolves to a video file. The layer
   * pauses / plays / seeks these elements when their texture becomes the active cue.
   * Sparse (only video keys present); empty / undefined = no video BGAs in the chart.
   */
  videoElements?: ReadonlyMap<string, HTMLVideoElement>;
  /**
   * Skin-config-level op set (selected layout / option ops). Used to resolve INNER if-gated
   * keyframe alternatives — beatoraja's BGA destinations stash variant rects per layout option
   * (compact vs. full BGA, etc.) and the loader picks one at skin-load time. Without this set
   * the resolver falls back to the catch-all (empty `if`) alternative — fine for the default
   * layout but mismatches the rect when the user has a non-default skin option active.
   */
  skinConfigOps?: ReadonlySet<number>;
  /**
   * A stitched NONSTOP chart's stages and each stage's own cues (`splitNonstopBGATimeline`): the layer draws each
   * stage's BGA at the opacity of its crossfade instead of `cues`.
   */
  nonstop?: { stages: readonly NonstopBGAStage[]; timelines: readonly NonstopStageBGATimeline[] } | undefined;
}
 
/** One stack's sprites: the black canvas behind a small base image, the base (or POOR) image and the layer image. */
interface BGASpritePair {
  readonly canvas: Sprite;
  readonly sprite: Sprite;
  readonly layer: Sprite;
  readonly layer2: Sprite;
  readonly poor: Sprite;
}
 
type BGADestinationProps = ReturnType<typeof destinationToSpriteProps>;
 
export class BeatorajaBGALayer {
  readonly container: Container = new Container();
  private background: Sprite | undefined;
  private clip?: Graphics;
  private readonly chartOptionProgram?: ChartOptionProgram;
  private keyBoundSprite = new Sprite({ visible: false, label: 'bga/key-bound' });
  /** The camera's picture, made the first time a camera shows. */
  private cameraSprite: Sprite | undefined;
  /**
   * One sprite set per stack drawn (one, or a NONSTOP chart's stages at a seam), earlier stacks behind. Each set is a
   * black fill behind a base image smaller than the BGA canvas, which beatoraja leaves black around it, the base image
   * (or the POOR image in its place) and the layer image over it. The first set is mounted at construction.
   */
  private readonly pairs: BGASpritePair[] = [];
  private readonly group: BeatorajaDestinationGroup | undefined;
  private readonly textures: ReadonlyMap<string, Texture>;
  private readonly subRegionOrigins: ReadonlyMap<string, { x: number; y: number }>;
  private readonly layerTextures: ReadonlyMap<string, Texture>;
  private readonly videoElements: ReadonlyMap<string, HTMLVideoElement>;
  private readonly cues: {
    opacity?: BGAOpacityTimelines;
    base: ReadonlyArray<BGACue>;
    layer: ReadonlyArray<BGACue>;
    layer2?: ReadonlyArray<BGACue>;
    poor: ReadonlyArray<BGACue>;
  };
  private readonly nonstop: BeatorajaBGALayerOptions['nonstop'];
  /**
   * Skin canvas height in skin-pixel units. Read from `skin.h` at construction so we can flip
   * the BGA's Y-UP dst rect into Pixi Y-DOWN — same convention the play skin view uses.
   */
  private readonly canvasHeight: number;
  /** The keys the stacks show now, whose videos play. */
  private currentKeys = new Map<string, number>();
  private disposed = false;
  private readonly poorBGAMode: 0 | 1 | 2;
 
  constructor(options: BeatorajaBGALayerOptions) {
    this.chartOptionProgram = options.chartOptionProgram;
    this.poorBGAMode = options.poorBGAMode ?? 0;
    this.textures = options.textures;
    this.subRegionOrigins = options.subRegionOrigins ?? new Map();
    this.layerTextures = options.layerTextures ?? new Map();
    this.videoElements = options.videoElements ?? new Map();
    this.cues = options.cues;
    this.nonstop = options.nonstop;
    this.group = resolveBGADestinationGroup(options.skin, options.skinConfigOps);
    const rawH = (options.skin as { h?: unknown }).h;
    this.canvasHeight = typeof rawH === 'number' && Number.isFinite(rawH) && rawH > 0 ? rawH : 720;
    // Mounted with no texture — `update()` swaps in the active BGA texture per frame. Kept invisible
    // until the destination group resolves with `visible = true` so a chart with no BGA stays clean.
    this.pairAt(0);
  }
 
  /**
   * Re-place + repaint the BGA for the current frame. Call once per Pixi tick from the gameplay view
   * after `view.update(context)` has run, so the BGA layer reads the same activeOps / nowMs the skin
   * view used.
   */
  update(
    seconds: number,
    context: BeatorajaRenderContext,
    poorBGAActive: boolean,
    playback: {
      seconds?: number;
      bgaMode?: 0 | 1 | 2;
      tempo?: number;
      paused?: boolean;
      started?: boolean;
      keyBoundBGA?: KeyBoundBGAFrame;
      bmsonBGA?: BmsonBGAFrame;
      /** The camera to show in place of the chart's BGA (`PlayScene.setBGACamera`). */
      camera?: BGAFeed;
    } = {},
  ): void {
    Iif (this.disposed) return;
    this.keyBoundSprite.visible = false;
    if (this.background) this.background.visible = false;
    for (const pair of this.pairs) {
      pair.canvas.visible = false;
      pair.sprite.visible = false;
      pair.layer.visible = false;
      pair.layer2.visible = false;
      pair.poor.visible = false;
    }
    Iif (this.cameraSprite !== undefined) this.cameraSprite.visible = false;
    if (this.group === undefined) return;
    const props = destinationToSpriteProps(this.group, context, this.canvasHeight);
    Iif (playback.camera !== undefined) {
      this.drawCamera(playback.camera, props);
      return;
    }
    // One stack, or a NONSTOP chart's stages at their crossfade opacity, earlier stages behind.
    const program = this.chartOptionProgram;
    const stacks = resolveBGAStacks({
      bgaMode: playback.bgaMode,
      stageBGAMode: program && ((start) => resolveChartOptionsAt(program, Math.round(start * 1_000_000)).bgaMode),
      timeline: this.cues,
      poorBGAMode: this.poorBGAMode,
      nonstop: this.nonstop,
      seconds,
      inPoorWindow: poorBGAActive,
      bmsonBGA: playback.bmsonBGA,
    });
    if (stacks.some(({ bgaMode }) => bgaMode !== undefined)) {
      if (this.clip === undefined) {
        this.clip = new Graphics({ label: 'bga/clip' });
        this.container.addChild(this.clip);
      }
      this.clip.clear().rect(0, 0, props.width, props.height).fill(0xffffff);
      this.clip.position.set(props.x, props.y);
      this.clip.angle = props.angle;
    }
    if (props.visible) {
      if (this.background === undefined) {
        this.background = new Sprite({
          texture: Texture.WHITE,
          tint: 0x000000,
          visible: false,
          label: 'bga/background',
        });
        this.container.addChildAt(this.background, 0);
      }
      Object.assign(this.background, {
        visible: true,
        x: props.x,
        y: props.y,
        width: props.width,
        height: props.height,
        alpha: props.alpha,
        angle: props.angle,
        blendMode: props.blendMode,
      });
    }
    const keys = new Map<string, number>();
    stacks.forEach((stack, index) => {
      const pair = this.pairAt(index);
      // The miss layer replaces both the base and the layer; outside it the layer draws over the base.
      if (stack.poorKey !== undefined && !stack.poorOverlays) {
        let cueSeconds = stack.poorCue?.seconds ?? seconds;
        for (const cue of this.cues.poor) {
          Iif (cue.seconds > seconds) break;
          Eif (stack.poorCue === undefined && cue.bmpKey === stack.poorKey) cueSeconds = cue.seconds;
        }
        const poorKey = this.videoKey(stack.poorKey, 'poor')!;
        keys.set(poorKey, cueSeconds);
        this.drawImage(
          pair.sprite,
          pair.canvas,
          poorKey,
          this.textures,
          props,
          stack.alpha * (stack.opacity?.poor ?? 1),
          stack.tint?.poor,
          stack.bgaMode,
        );
        return;
      }
      const baseKey = stack.baseCue?.bmpKey;
      if (baseKey !== undefined) {
        keys.set(baseKey, stack.baseCue!.seconds);
        this.drawImage(
          pair.sprite,
          pair.canvas,
          baseKey,
          this.textures,
          props,
          stack.alpha * (stack.opacity?.base ?? 1),
          stack.tint?.base,
          stack.bgaMode,
        );
      }
      const layerKey = this.videoKey(stack.layerCue?.bmpKey, 'layer');
      if (layerKey !== undefined) {
        keys.set(layerKey, stack.layerCue!.seconds);
        this.drawImage(
          pair.layer,
          undefined,
          layerKey,
          this.layerTextures,
          props,
          stack.alpha * (stack.opacity?.layer ?? 1),
          stack.tint?.layer,
          stack.bgaMode,
        );
      }
      const layer2Key = this.videoKey(stack.layer2Cue?.bmpKey, 'layer2');
      if (layer2Key !== undefined) {
        keys.set(layer2Key, stack.layer2Cue!.seconds);
        this.drawImage(
          pair.layer2,
          undefined,
          layer2Key,
          this.layerTextures,
          props,
          stack.alpha * (stack.opacity?.layer2 ?? 1),
          stack.tint?.layer2,
          stack.bgaMode,
        );
      }
      if (stack.poorKey !== undefined && stack.poorOverlays) {
        let cueSeconds = stack.poorCue?.seconds ?? seconds;
        for (const cue of this.cues.poor) {
          Iif (cue.seconds > seconds) break;
          Eif (stack.poorCue === undefined && cue.bmpKey === stack.poorKey) cueSeconds = cue.seconds;
        }
        const poorKey = this.videoKey(stack.poorKey, 'poor')!;
        keys.set(poorKey, cueSeconds);
        this.drawImage(
          pair.poor,
          undefined,
          poorKey,
          this.textures,
          props,
          stack.alpha * (stack.opacity?.poor ?? 1),
          stack.tint?.poor,
          stack.bgaMode,
        );
      }
    });
    this.keyBoundSprite.visible = false;
    const keyBound = playback.keyBoundBGA;
    if (keyBound) {
      const key = keyBoundBGAResourceKey(keyBound.definitionId, keyBound.bmpKey);
      keys.set(key, keyBound.frameStartSeconds);
      if (this.keyBoundSprite.parent !== this.container) this.container.addChild(this.keyBoundSprite);
      else this.container.setChildIndex(this.keyBoundSprite, this.container.children.length - 1);
      this.drawImage(
        this.keyBoundSprite,
        undefined,
        key,
        this.layerTextures,
        props,
        1,
        undefined,
        stacks.at(-1)?.bgaMode,
      );
    }
    if (this.clip) this.clip.includeInBuild = false;
    this.syncVideos(keys, playback.seconds ?? seconds, playback);
  }
 
  /**
   * Draws the camera on a black canvas in the BGA destination, fitted whole, in place of the chart's BGA; the chart's
   * videos pause, and the next frame without the camera starts the active cues' videos again at chart time.
   */
  private drawCamera(camera: BGAFeed, props: BGADestinationProps): void {
    for (const key of this.currentKeys.keys()) this.videoElements.get(key)?.pause();
    this.currentKeys.clear();
    if (!props.visible) return;
    const shared = { alpha: props.alpha, angle: props.angle, blendMode: props.blendMode };
    if (this.background === undefined) {
      this.background = new Sprite({ texture: Texture.WHITE, tint: 0x000000, visible: false, label: 'bga/background' });
      this.container.addChildAt(this.background, 0);
    }
    Object.assign(this.background, {
      visible: true,
      x: props.x,
      y: props.y,
      width: props.width,
      height: props.height,
      ...shared,
    });
    const texture = camera.texture();
    if (texture === undefined) return;
    if (this.cameraSprite === undefined) {
      this.cameraSprite = new Sprite({ visible: false, label: 'bga/camera' });
      this.container.addChild(this.cameraSprite);
    }
    const placed = fitBGACameraRect(texture.width, texture.height, {
      x: props.x,
      y: props.y,
      w: props.width,
      h: props.height,
    });
    if (this.cameraSprite.texture !== texture) this.cameraSprite.texture = texture;
    Object.assign(this.cameraSprite, {
      visible: true,
      x: placed.x,
      y: placed.y,
      width: placed.w,
      height: placed.h,
      tint: props.tint,
      ...shared,
    });
  }
 
  /**
   * Plays the current cues' videos again when they are paused: a paused play pauses every BGA video, and the layer only
   * starts one on a cue change.
   */
  resume(): void {
    Iif (this.disposed) return;
    for (const key of this.currentKeys.keys()) {
      const video = this.videoElements.get(key);
      Eif (video !== undefined && video.paused) playVideo(video);
    }
  }
 
  dispose(): void {
    Iif (this.disposed) return;
    this.disposed = true;
    // Pause the active videos before tearing down the container — otherwise the
    // `requestVideoFrameCallback` poll keeps running on the compositor thread, fighting
    // for frame slots even though no Pixi sprite consumes the frames anymore. The prep
    // pipeline's `dispose()` clears `src` + revokes the URL on EVERY video; this layer
    // pause is just the "stop the in-flight cue" half so a rapid scene-swap (replaceSkin
    // mid-play) doesn't briefly drive two videos before the prep cleanup runs.
    for (const key of this.currentKeys.keys()) {
      try {
        this.videoElements.get(key)?.pause();
      } catch {
        // Already paused / disposed.
      }
    }
    // The camera's texture belongs to its feed, which the scene disposes.
    Iif (this.cameraSprite !== undefined) this.cameraSprite.texture = Texture.EMPTY;
    Eif (!this.keyBoundSprite.destroyed) this.keyBoundSprite.destroy();
    Eif (!this.container.destroyed) {
      this.container.destroy({ children: true });
    }
  }
 
  private videoKey(key: string | undefined, track: 'layer' | 'layer2' | 'poor'): string | undefined {
    const videoKey = String.fromCharCode(0) + track + ':' + key;
    return this.videoElements.has(videoKey) ? videoKey : key;
  }
 
  /** The sprite set of the stack at `index`, mounted on first use. */
  private pairAt(index: number): BGASpritePair {
    while (this.pairs.length <= index) {
      const pair: BGASpritePair = {
        canvas: new Sprite({ texture: Texture.WHITE, tint: 0x000000, visible: false, label: 'bga/canvas' }),
        sprite: new Sprite({ visible: false, label: 'bga/base' }),
        layer: new Sprite({ visible: false, label: 'bga/layer' }),
        layer2: new Sprite({ visible: false, label: 'bga/layer2' }),
        poor: new Sprite({ visible: false, label: 'bga/poor' }),
      };
      this.pairs.push(pair);
      this.container.addChild(pair.canvas, pair.sprite, pair.layer, pair.layer2, pair.poor);
    }
    return this.pairs[index]!;
  }
 
  /**
   * Draws `key` (looked up in `textures`, then the base textures) on `sprite` into the destination `props`, at `alpha`
   * (a NONSTOP stage's crossfade) on top of its own. `canvas`, given for the base track, fills the rect black behind
   * an image smaller than it; the layer track's canvas stays transparent.
   */
  private drawImage(
    sprite: Sprite,
    canvas: Sprite | undefined,
    key: string,
    textures: ReadonlyMap<string, Texture>,
    props: BGADestinationProps,
    alpha: number,
    tint = 0xffffff,
    bgaMode?: 0 | 1 | 2,
  ): void {
    const texture = textures.get(key) ?? this.textures.get(key);
    // No decoded texture (or Pixi's source-less EMPTY singleton) must not enter the renderer's
    // batch. Other beatoraja skin paths already skip EMPTY because WebGPU can crash while creating
    // the bind group for that source; BGA cues can hit the same path when a chart references a
    // missing/corrupt BMP slot mid-play.
    if (!props.visible || texture === undefined || texture === Texture.EMPTY) return;
    if (sprite.texture !== texture) {
      sprite.texture = texture;
    }
    // The destination stands for the 256x256 BMS canvas: a still image that fits it is centered horizontally and
    // top-aligned at its pixel size on a black canvas (beatoraja's `BGImageProcessor`), anything larger and videos
    // fill the rect.
    const rect = { x: props.x, y: props.y, w: props.width, h: props.height };
    const placed =
      bgaMode !== undefined
        ? resolveBGAImageRect(texture.frame.width, texture.frame.height, rect, undefined, bgaMode)
        : this.videoElements.has(key) && !this.subRegionOrigins.has(key)
          ? rect
          : resolveBGAImageRect(texture.frame.width, texture.frame.height, rect, this.subRegionOrigins.get(key));
    if (canvas !== undefined && (placed.w < rect.w || placed.h < rect.h)) {
      canvas.visible = true;
      canvas.x = rect.x;
      canvas.y = rect.y;
      canvas.width = rect.w;
      canvas.height = rect.h;
      canvas.alpha = props.alpha * alpha;
      canvas.angle = props.angle;
      canvas.blendMode = props.blendMode;
    }
    sprite.mask =
      bgaMode !== undefined &&
      (placed.x < rect.x || placed.x + placed.w > rect.x + rect.w || placed.y + placed.h > rect.y + rect.h)
        ? (this.clip ?? null)
        : null;
    sprite.visible = true;
    sprite.x = placed.x;
    sprite.y = placed.y;
    sprite.width = placed.w;
    sprite.height = placed.h;
    sprite.alpha = props.alpha * alpha;
    sprite.tint = [16, 8, 0].reduce(
      (value, shift) =>
        value | (Math.round((((props.tint >>> shift) & 255) * ((tint >>> shift) & 255)) / 255) << shift),
      0,
    );
    sprite.angle = props.angle;
    sprite.blendMode = props.blendMode;
  }
 
  /** Keeps every visible stack's video at chart time since its cue, including after seeks and stalls. */
  private syncVideos(
    keys: Map<string, number>,
    seconds: number,
    playback: {
      tempo?: number;
      paused?: boolean;
      started?: boolean;
      keyBoundBGA?: KeyBoundBGAFrame;
      bmsonBGA?: BmsonBGAFrame;
    },
  ): void {
    for (const key of this.currentKeys.keys()) {
      if (keys.has(key) && playback.started !== false) continue;
      this.videoElements.get(key)?.pause();
    }
    if (playback.started === false) {
      this.currentKeys.clear();
      return;
    }
    for (const [key, cueSeconds] of keys) {
      const video = this.videoElements.get(key);
      if (video === undefined) continue;
      const frame = playback.keyBoundBGA;
      const rate =
        frame && key === keyBoundBGAResourceKey(frame.definitionId, frame.bmpKey)
          ? (frame.playbackRate ?? 1)
          : playback.bmsonBGA !== undefined &&
              key === this.videoKey(playback.bmsonBGA.key, playback.bmsonBGA.plane === 'poor' ? 'poor' : 'layer')
            ? (playback.bmsonBGA.playbackRate ?? 1)
            : 1;
      video.playbackRate = (playback.tempo ?? 1) * rate;
      const expected = Math.max(0, (seconds - cueSeconds) * rate);
      const changedCue = this.currentKeys.get(key) !== cueSeconds;
      const offset = changedCue
        ? Math.min(expected, Math.max(0, video.duration - 0.05) || expected)
        : resolveBGAVideoResync(video.currentTime, expected, video.duration);
      if (offset !== undefined && !video.seeking) {
        try {
          video.currentTime = offset;
        } catch {
          // Not seekable yet: the next frame retries the drift correction.
        }
      }
      if (playback.paused) {
        if (!video.paused) video.pause();
      } else if (video.paused && !video.ended) playVideo(video);
    }
    this.currentKeys = keys;
  }
}
 
/**
 * Plays `video`. Browsers gate `.play()` behind the user-gesture autoplay policy — when the gameplay scene mounts as a
 * result of a click / keypress (the typical entry path), the gesture transfers and play() resolves. Otherwise the
 * promise rejects silently and the video stays on its frame until the next cue brings it into focus.
 */
function playVideo(video: HTMLVideoElement): void {
  try {
    const playPromise = video.play();
    Eif (playPromise !== undefined && typeof playPromise.catch === 'function') {
      playPromise.catch(() => undefined);
    }
  } catch {
    // Autoplay policy or a codec refused it: the video stays on its frame.
  }
}
 
/**
 * Look up the destination group the skin's `bga.id` points at. Returns `undefined` when the skin has no
 * `bga` block (some custom themes ship a chart-area-only play layout without BGA support) or when the
 * destination[] doesn't carry a matching id.
 */
function resolveBGADestinationGroup(
  skin: BeatorajaSkin,
  skinConfigOps: ReadonlySet<number> | undefined,
): BeatorajaDestinationGroup | undefined {
  const bgaId = skin.bga?.id;
  if (typeof bgaId !== 'number' && typeof bgaId !== 'string') return undefined;
  const groups = normalizeBeatorajaDestinations(skin.destination, skinConfigOps);
  return groups.find((group) => group.id === bgaId);
}