All files / player-browser/src/view/beatoraja scene-frame.ts

83.16% Statements 84/101
73.61% Branches 53/72
85% Functions 17/20
91.66% Lines 77/84

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                                                                                                35x       19x 19x 19x 3x               3x   19x                             9x       2x   7x                       99x 99x 99x 35x 35x 35x 35x 35x 35x 35x 35x 35x               78x 78x 54x   24x                     35x       78x 33x         132x                                 47x 47x 47x           47x   25x 25x 25x   47x 47x               56x   56x 56x 56x     56x 56x         99x 99x         3x       42x 42x 42x 42x 42x 42x                       37x       37x             37x 37x 37x         34x 34x                               37x 37x 37x 37x 37x 37x       32x 16x 16x 16x               16x       16x 16x                       37x       37x 111x      
/**
 * What the beatoraja decide and result views share: the skin drawn on a black backdrop with its canvas fitted into the
 * window ({@link BeatorajaSkinStage}), the chart's own images ({@link BeatorajaViewChartImages}), the scene timers read
 * off a frame, and the song and skin texts and timing fields they read off the skin.
 */
 
import { TIMER_RESULTGRAPH_BEGIN, TIMER_RESULTGRAPH_END, TIMER_RESULT_UPDATESCORE } from '@be-music/skin-beatoraja';
import {
  BEATORAJA_TEXT,
  TIMER_FADEOUT,
  TIMER_PLAY,
  TIMER_READY,
  TIMER_SCENE_START,
  TIMER_STARTINPUT,
  type BeatorajaSkin,
} from '@be-music/skin-beatoraja';
import {
  resolveBeatorajaSkinText,
  resolveBeatorajaChartText as resolveBeatorajaChartTextOf,
  type BeatorajaChartTextInput,
} from '@be-music/skin-beatoraja/scene';
import { resolveNonstopSongInfoState } from '@be-music/player-engine/course';
import type { LibraryChart } from '@be-music/player-scene-model';
import { Container, Graphics, type Texture } from 'pixi.js';
import { extractChartSubartist } from '../../chart/beatoraja/meta.ts';
import type { BrowserAssetSource } from '../../collection/types.ts';
import { destroyTextureAndRevokeBlobURL } from '../../media/textures.ts';
import type { BeatorajaPlaySkinView } from './skin-view.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import {
  loadBeatorajaChartImage,
  loadBeatorajaChartImages,
  resolveBeatorajaChartImage,
  type BeatorajaChartImages,
} from '../../skin/beatoraja/chart-images.ts';
import type { SceneClock } from '../types.ts';
 
export interface BeatorajaStageFitState {
  width: number;
  height: number;
}
 
interface BeatorajaStageView {
  readonly width: number;
  readonly height: number;
  readonly container: Container;
}
 
const SONG_TEXTS = new WeakMap<LibraryChart, BeatorajaChartTextInput>();
 
/** What a beatoraja skin's song texts read of a library chart (its sub-artist read off the chart once). */
export function beatorajaChartTextOf(chartEntry: LibraryChart | undefined): BeatorajaChartTextInput | undefined {
  Iif (chartEntry === undefined) return undefined;
  let text = SONG_TEXTS.get(chartEntry);
  if (text === undefined) {
    text = {
      title: chartEntry.title,
      subtitle: chartEntry.subtitle,
      genre: chartEntry.genre,
      artist: chartEntry.artist,
      subartist: extractChartSubartist(chartEntry.chart),
      directory: chartEntry.directoryLabel,
    };
    SONG_TEXTS.set(chartEntry, text);
  }
  return text;
}
 
/**
 * The song and skin texts of the decide and result screens (`@be-music/skin-beatoraja/scene`); the difficulty-table
 * texts read `tableTextFallback`.
 */
export function resolveBeatorajaChartText(
  refOp: number,
  options: {
    chart?: LibraryChart;
    skin: BeatorajaSkin;
    tableTextFallback?: string;
  },
): string | undefined {
  switch (refOp) {
    case BEATORAJA_TEXT.TABLE_NAME:
    case BEATORAJA_TEXT.TABLE_LEVEL:
    case BEATORAJA_TEXT.TABLE_FULL:
      return options.tableTextFallback;
  }
  return (
    resolveBeatorajaChartTextOf(refOp, beatorajaChartTextOf(options.chart)) ??
    resolveBeatorajaSkinText(refOp, options.skin)
  );
}
 
export function fitBeatorajaViewToStage(
  host: PixiSceneHost | undefined,
  view: BeatorajaStageView,
  backdrop: Graphics,
  previous: BeatorajaStageFitState,
): BeatorajaStageFitState | undefined {
  Iif (!host) return undefined;
  const { width, height } = host.app.screen;
  if (width === previous.width && height === previous.height) return undefined;
  Iif (width <= 0 || height <= 0) return undefined;
  const scale = Math.min(width / view.width, height / view.height);
  Iif (!Number.isFinite(scale) || scale <= 0) return undefined;
  const c = view.container;
  c.scale.set(scale, scale);
  c.x = (width - view.width * scale) / 2;
  c.y = (height - view.height * scale) / 2;
  backdrop.clear().rect(0, 0, width, height).fill(0x000000);
  return { width, height };
}
 
export function resolveBeatorajaSkinTimingMs(
  value: number | undefined,
  fallbackMs: number,
  options: { min?: number } = {},
): number {
  const min = options.min ?? Number.NEGATIVE_INFINITY;
  if (typeof value === 'number' && Number.isFinite(value) && value >= min) {
    return value;
  }
  return fallbackMs;
}
 
/**
 * Default fadeout window when the skin omits the field. A beatoraja screen leaves over upstream's `TIMER_FADEOUT` +
 * `Skin.getFadeout()` pattern (`MusicDecide.render` / `MusicResult.render` / `BMSPlayer.render`'s STATE_FINISHED
 * branch): a trigger starts timer 2, the skin's elements gated on it animate from then, and the screen hands over once
 * `Skin.fadeout` ms have passed. Upstream's `Skin` declares `private int fadeout` with no initializer (Java's 0, an
 * instant transition), but every reference skin (`select.json`, `decidemain.lua`, `resultmain.lua`) ships 500, so
 * an unauthored skin or a hand-rolled test fixture falls back to that.
 */
export const DEFAULT_BEATORAJA_FADEOUT_MS = 500;
 
/** A beatoraja screen's fade-out: the skin's `fadeout`, else {@link DEFAULT_BEATORAJA_FADEOUT_MS}. */
export function resolveBeatorajaFadeOutMs(fadeout: number | undefined): number {
  if (typeof fadeout === 'number' && Number.isFinite(fadeout) && fadeout >= 0) return fadeout;
  return DEFAULT_BEATORAJA_FADEOUT_MS;
}
 
/** A beatoraja screen's own clock: the ms since it was entered. */
export function beatorajaSceneNowMs(clock: SceneClock): number {
  return clock.nowMs - clock.enteredAtMs;
}
 
/**
 * The beatoraja timers of a decide or result frame, on the screen's own clock ({@link beatorajaSceneNowMs}): the scene
 * (0) from the entry, input (1) from when input opens, READY (40) and PLAY (41) from when input opens or from the entry
 * (`readyAt`), and the fade-out (2) from when the screen started leaving.
 */
export function resolveBeatorajaSceneTimers(
  frame: {
    readonly clock: SceneClock;
    readonly inputOpenAtMs: number;
    readonly leaving?: { readonly atMs: number };
  },
  readyAt: 'input' | 'entry',
  scene?: 'result',
): Map<number, number> {
  const inputAtMs = frame.inputOpenAtMs - frame.clock.enteredAtMs;
  const readyAtMs = readyAt === 'input' ? inputAtMs : 0;
  const timers = new Map<number, number>([
    [TIMER_SCENE_START, 0],
    [TIMER_STARTINPUT, inputAtMs],
    [TIMER_READY, readyAtMs],
    [TIMER_PLAY, readyAtMs],
  ]);
  if (scene === 'result') {
    // JSON/Lua result skins leave MusicResultSkin.ranktime at its upstream zero default.
    timers.set(TIMER_RESULTGRAPH_BEGIN, 0);
    timers.set(TIMER_RESULTGRAPH_END, 0);
    timers.set(TIMER_RESULT_UPDATESCORE, 0);
  }
  if (frame.leaving !== undefined) timers.set(TIMER_FADEOUT, frame.leaving.atMs - frame.clock.enteredAtMs);
  return timers;
}
 
/**
 * A beatoraja skin view on a black backdrop, its canvas scaled to fit the window and centred: what a beatoraja family
 * view puts on the stage.
 */
export class BeatorajaSkinStage {
  public readonly root: Container = new Container();
  public readonly view: BeatorajaPlaySkinView;
  private readonly backdrop: Graphics = new Graphics();
  private fit: BeatorajaStageFitState = { width: 0, height: 0 };
  private disposed = false;
 
  public constructor(view: BeatorajaPlaySkinView) {
    this.view = view;
    this.root.addChild(this.backdrop, view.container);
  }
 
  /** Fits the skin's canvas to `host`'s screen, when the screen's size changed since the last fit. */
  public fitTo(host: PixiSceneHost): void {
    const fitted = fitBeatorajaViewToStage(host, this.view, this.backdrop, this.fit);
    if (fitted !== undefined) this.fit = fitted;
  }
 
  /** The skin's canvas and its authored size, for screenshots. */
  public getStageInfo(): { container: Container; width: number; height: number } {
    return { container: this.view.container, width: this.view.width, height: this.view.height };
  }
 
  public dispose(): void {
    Iif (this.disposed) return;
    this.disposed = true;
    this.root.parent?.removeChild(this.root);
    this.view.dispose();
    Eif (!this.backdrop.destroyed) this.backdrop.destroy({ children: false, context: true });
    Eif (!this.root.destroyed) this.root.destroy({ children: false });
  }
}
 
/**
 * The chart's own images a beatoraja view shows in the skin's synthetic slots (-100 to -102): loaded once, before the
 * view's first frame, and destroyed with the view.
 */
export class BeatorajaViewChartImages {
  private readonly chart: Pick<LibraryChart, 'chart' | 'chartPath'> | undefined;
  private readonly source: BrowserAssetSource | undefined;
  private readonly nonstop: BeatorajaNonstopBackBMP | undefined;
  private images: BeatorajaChartImages = {};
  /** Each stitched NONSTOP stage's `#BACKBMP`, when a stage has one (`nonstop`). */
  private stageBackBMPs: (Texture | undefined)[] | undefined;
  private loading: Promise<void> | undefined;
  private disposed = false;
 
  public constructor(
    chart: Pick<LibraryChart, 'chart' | 'chartPath'> | undefined,
    source: BrowserAssetSource | undefined,
    nonstop?: BeatorajaNonstopBackBMP,
  ) {
    this.chart = chart;
    this.source = source;
    this.nonstop = nonstop?.stages.some((stage) => stage.backBMP !== undefined) === true ? nonstop : undefined;
  }
 
  /** Loads the images, the first time it is called; nothing loads without a chart. */
  public load(): Promise<void> {
    this.loading ??= this.loadOnce();
    return this.loading;
  }
 
  /**
   * The image of a synthetic slot, once loaded. In a stitched NONSTOP play the back image (-101) is the `#BACKBMP` of
   * the stage shown, which moves at each stage's window as the song info does; a stage without one hides it.
   */
  public resolve(syntheticId: number): Texture | undefined {
    if (syntheticId === -101 && this.nonstop !== undefined) {
      const { stage } = resolveNonstopSongInfoState(this.nonstop.stages, this.nonstop.currentSeconds(), 0);
      return this.stageBackBMPs?.[stage];
    }
    return resolveBeatorajaChartImage(this.images, syntheticId);
  }
 
  public dispose(): void {
    Iif (this.disposed) return;
    this.disposed = true;
    destroyChartImages(this.images);
    this.images = {};
    destroyStageBackBMPs(this.stageBackBMPs);
    this.stageBackBMPs = undefined;
  }
 
  private async loadOnce(): Promise<void> {
    if (this.chart === undefined) return;
    const chart = this.chart;
    const source = this.source;
    const [images, stageBackBMPs] = await Promise.all([
      loadBeatorajaChartImages(chart, source),
      this.nonstop === undefined || source === undefined
        ? Promise.resolve(undefined)
        : Promise.all(
            this.nonstop.stages.map((stage) => loadBeatorajaChartImage(chart.chartPath, stage.backBMP, source)),
          ),
    ]);
    Iif (this.disposed) {
      destroyChartImages(images);
      destroyStageBackBMPs(stageBackBMPs);
    } else {
      this.images = images;
      this.stageBackBMPs = stageBackBMPs;
    }
  }
}
 
/** The stages of a stitched NONSTOP play whose `#BACKBMP` a beatoraja view shows, and the play's stitched time. */
export interface BeatorajaNonstopBackBMP {
  readonly stages: ReadonlyArray<{ readonly windowStart: number; readonly backBMP?: string }>;
  readonly currentSeconds: () => number;
}
 
function destroyStageBackBMPs(textures: readonly (Texture | undefined)[] | undefined): void {
  for (const texture of textures ?? []) if (texture !== undefined) destroyTextureAndRevokeBlobURL(texture, true);
}
 
function destroyChartImages(images: BeatorajaChartImages): void {
  for (const texture of [images.stageFile, images.backBMP, images.banner]) {
    Iif (texture !== undefined) destroyTextureAndRevokeBlobURL(texture, true);
  }
}