All files / player-browser/src/view/built-in play-view.ts

78.01% Statements 110/141
55.55% Branches 40/72
56.75% Functions 21/37
80.8% Lines 101/125

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                                                                                                                28x     28x                 28x   28x                                                               11x 11x 11x     56x   11x 11x               11x                   11x 11x 11x 11x 11x   11x         36x 36x         21x         2x               49x 49x                       20x               4x             16x 2x 2x     2x             16x         4x       5x 5x 5x                     5x   5x 5x 5x 5x   5x   5x         9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 4x   4x 9x   24x       9x                               9x   9x         9x 9x                       9x 9x 9x                                       9x       9x       4x       5x 5x 5x 5x 5x                                           11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x       11x 11x 11x       11x                   11x   25x     24x           24x      
import { ChartTextOverlay } from '../shared/chart-text.ts';
import { DisplayAreaInfoOverlay, resolveDisplayAreaLabels } from '../shared/display-area-info.ts';
import { BPMChangeWarningOverlay } from '../shared/bpm-change-warning.ts';
import { resolveBuiltInBPMChangeWarningStyle } from './bpm-change-warning-style.ts';
import {
  resolveLR2Earthquake,
  resolveLR2ManiaVisual,
  LR2_SCREEN_HEIGHT,
} from '../shared/playfield/lr2-mania-visual.ts';
/**
 * The built-in family's play screen: a Be-Music Skin's chrome around the shared playfield (`view/shared/playfield`),
 * letterboxed into the window. It draws the play session's frames; its skin answers the shared playfield through a
 * {@link PlayfieldSkin} (a Be-Music Skin draws the lanes, notes and bombs as data on its own canvas, so the playfield's
 * own layout and drawing apply). The session times the play and handles its keys; the view follows the fingers on the
 * touch lanes and sends them as `lane` intents.
 */
 
import type {
  BeMusicDOMGameplayFrame,
  BeMusicDOMGameplayActions,
  BeMusicDOMGameplayScreen,
} from '@be-music/player-skin-sdk';
import { SkinDOMMount } from '../../skin/be-music/dom-mount.ts';
import {
  resolveBeMusicSkinSettings,
  resolveStageOrientation,
  type GameplayLayoutMode,
} from '@be-music/player-skin-sdk';
import type { Application, Texture } from 'pixi.js';
import type { BrowserAssetSource } from '../../collection/types.ts';
import type { BuiltInKit } from '../../host/family-kit.ts';
import { logger } from '../../logger.ts';
import type { PlaySessionOptions } from '../../session/play/play-options.ts';
import { KEY_ON_FADE_OUT_MS } from '../../stage/design.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import { BeMusicGameplayBinding, resolveBeMusicSkinStage } from '../../skin/be-music/binding.ts';
import { ChartImageCache } from '../../skin/be-music/chart-images.ts';
import type { BeMusicStage } from '../../skin/be-music/types.ts';
import { DEFAULT_BOMB_DURATION_MS } from '../shared/playfield/default-playfield.ts';
import { build, render, type PlayFrameContext } from '../shared/play-frame.ts';
import { PlayLayers } from '../shared/play-layers.ts';
import type { PlayChrome, PlayfieldRuntime } from '../shared/playfield/context.ts';
import { uploadTextures } from '../shared/texture-upload.ts';
import { playfieldTouchLanes, TouchLaneInput } from '../shared/touch-lane-input.ts';
import type { IntentSink, PlayFrame, PlayIntent, PlayView, PlayViewTiming, PlayfieldSkin } from '../types.ts';
import {
  collectBGATargets,
  LEGACY_STAGE_SIZE,
  renderBuiltInChrome,
  resolveBeMusicLayout,
  resolveSkinlessGameplayChromeRuntime,
  type BGATargetsContext,
  type BuiltInChromeContext,
  type SkinlessGameplayChromeRuntime,
} from './play-chrome.ts';
 
const log = logger('gameplay');
 
/** Design px above a lane's top through which notes keep drawing as they scroll in (standard layout). */
const NOTE_OVERSCAN = 48;
 
/**
 * A Be-Music Skin's timing on the play screen: no load or play-start offsets of its own (the play's fallback intro
 * applies), and a 450 ms fade back to black, with the audio, before the result or select screen takes over.
 */
/**
 * The built-in skins that draw each side's LIFT and take the lane cover keys: the ones brought up to the per-side covers.
 */
export const LIFT_SKINS: ReadonlySet<string> = new Set(['plain', 'native', 'synesthesia']);
 
export const BUILT_IN_PLAY_TIMING: PlayViewTiming = {
  loadEndOffsetMs: 0,
  playStartOffsetMs: 0,
  fadeOutMs: 450,
  closeMs: 0,
};
 
/** What the built-in play view draws with besides its kit: the options of the play that change what is drawn. */
export type BuiltInPlayViewOptions = Pick<
  PlaySessionOptions,
  | 'bga'
  | 'visualConstant'
  | 'noteDurationMs'
  | 'constantFadeMs'
  | 'judgeTimingMs'
  | 'judgeTimingAutoAdjust'
  | 'bpmGuide'
  | 'bpmGuideKinds'
  | 'autoPlay'
  | 'nonstop'
  | 'showInvisibleNotes'
  | 'layoutMode'
> & {
  /** Where the chart's files are, for the skin's song images. */
  readonly source?: BrowserAssetSource;
};
 
/** The built-in play view. See the module comment. */
export class BuiltInPlayView
  extends PlayLayers
  implements PlayView, PlayFrameContext, BuiltInChromeContext, BGATargetsContext
{
  private readonly displayInfo = new DisplayAreaInfoOverlay();
  private readonly bpmChangeWarning = new BPMChangeWarningOverlay();
  private readonly chartText = new ChartTextOverlay();
  /** LIFT integration is currently enabled for Plain and Native. */
  public get drawsLift(): boolean {
    return LIFT_SKINS.has(this.kit.skin.id);
  }
  public readonly family = 'built-in' as const;
  public readonly timing: PlayViewTiming = BUILT_IN_PLAY_TIMING;
  /** The play options the view draws with; the setters change them during the play. */
  public readonly options: BuiltInPlayViewOptions & { beMusicEffects?: BuiltInKit['effects'] };
  /** How the Be-Music Skin answers the shared playfield. */
  public readonly playfieldSkin: PlayfieldSkin;
  /** The Be-Music Skin's chrome around the shared playfield. */
  public readonly chrome: PlayChrome;
  /** The fingers on the lanes, sent to the session as `lane` intents while attached. */
  private readonly touchLanes: TouchLaneInput = new TouchLaneInput(playfieldTouchLanes(this));
  private domSettings: ReturnType<typeof resolveBeMusicSkinSettings>;
  private kit: BuiltInKit;
  /** Shared only within one draw; published snapshots from earlier frames stay untouched. */
  private chromeRuntime: SkinlessGameplayChromeRuntime | undefined;
  /** The frame being drawn: the chrome's runtime reads its best record, course and player from it. */
  public playFrame: PlayFrame | undefined;
  private dom: SkinDOMMount<BeMusicDOMGameplayFrame, BeMusicDOMGameplayActions, BeMusicDOMGameplayScreen> | undefined;
 
  public constructor(kit: BuiltInKit, play: PlayfieldRuntime, options: BuiltInPlayViewOptions = {}) {
    super(play);
    this.kit = kit;
    this.domSettings = resolveBeMusicSkinSettings(kit.skin, kit.settings);
    this.options = { ...options, ...(kit.effects !== undefined ? { beMusicEffects: kit.effects } : {}) };
    this.playfieldSkin = createBuiltInPlayfieldSkin(this);
    // A Be-Music Skin draws notes from data: no text of its own after the bombs, and nothing for a retired bomb.
    this.chrome = { draw: () => renderBuiltInChrome(this, undefined, this.resolveChromeRuntime()) };
  }
 
  /** The host's `Application`; the view draws only once attached (or built for a host ahead of its first frame). */
  get app(): Application {
    Iif (!this.host) throw new Error('BuiltInPlayView: app accessed before attach');
    return this.host.app;
  }
 
  /** Whether the skin's DOM gameplay screen draws the playfield, so nothing of the play is drawn on the canvas. */
  get drawsOnCanvas(): boolean {
    return !(this.kit.skin.gameplay.drawsOnDOM === true && this.kit.skin.dom?.gameplay !== undefined);
  }
 
  /** A Be-Music Skin always paints the chrome: the screen fades up from black as it appears. */
  get paintsThroughBeMusicSkin(): boolean {
    return true;
  }
 
  /**
   * The skin's stage: its portrait stage while the screen is upright and the chart fits a portrait playfield, its
   * landscape stage otherwise. Read every frame, so a rotation mid-play re-lays the screen out on the next frame.
   */
  get beMusicStage(): BeMusicStage | undefined {
    const screen = this.host?.app.screen;
    return resolveBeMusicSkinStage(
      this.kit.skin,
      screen && screen.width > 0 && screen.height > 0 ? screen : undefined,
      {
        laneChannels: this.play.laneChannels,
        playVariant: this.play.chartPlayVariant,
      },
    );
  }
 
  /** `'touch'` when the play asks for it; the play mode may still fall back to standard (`resolveLaneGeometry`). */
  get layoutMode(): GameplayLayoutMode {
    return this.options.layoutMode === 'touch' ? 'touch' : 'standard';
  }
 
  /**
   * How far above a lane's top notes still draw while they scroll in: the standard lanes start at the stage's top edge,
   * so notes enter from off-stage; the touch and portrait lanes start below the skin's header band.
   */
  get noteOverscan(): number {
    return this.layoutMode === 'touch' || resolveStageOrientation(this.playfieldSkin.stage) === 'portrait'
      ? 0
      : NOTE_OVERSCAN;
  }
 
  /** The Be-Music Skin's gameplay binding: lanes, notes and hit effects go to it as data and it draws them. */
  get skinBinding(): BeMusicGameplayBinding {
    if (!this.skinBindingInstance) {
      const source = this.options.source;
      this.chartImages = new ChartImageCache({
        resolveSource: (chartEntry) => (source !== undefined && chartEntry.sourceId === source.id ? source : undefined),
      });
      this.skinBindingInstance = new BeMusicGameplayBinding(this.kit.skin, {
        chartImage: this.chartImages.lookup,
        settings: this.kit.settings,
        renderer: this.host?.app.renderer,
        drawPlayfield: (frame) => this.dom?.connectedScreen?.drawPlayfield?.(frame),
      });
    }
    return this.skinBindingInstance;
  }
 
  /** Builds the layers on `host` ahead of the first frame (a play loading off stage), so its textures can upload. */
  public prepareOn(host: PixiSceneHost): void {
    build(this, host);
  }
 
  public attach(host: PixiSceneHost, emit: IntentSink<PlayIntent>): void {
    build(this, host);
    const factory = this.kit.skin.dom?.gameplay;
    Iif (factory && !this.dom)
      this.dom = new SkinDOMMount(
        factory,
        {
          pause: () => emit({ type: 'pause' }),
          restart: () => emit({ type: 'restart' }),
          quit: () => emit({ type: 'quit' }),
          seek: (seconds) => emit({ type: 'seek', seconds }),
        },
        'gameplay',
      );
    this.dom?.attach(host.domRoot);
    // Without the canvas the fingers land on the screen's mount, which covers the same area.
    const mount = this.drawsOnCanvas ? undefined : this.dom?.root;
    Iif (mount) mount.style.pointerEvents = 'auto';
    this.touchLanes.attach(host, emit, mount);
    if (this.drawsOnCanvas) this.displayInfo.attachCanvas(this.designRoot);
    else Ethis.displayInfo.attach(host.domRoot);
    if (this.drawsOnCanvas) this.bpmChangeWarning.attachCanvas(this.designRoot);
    else Ethis.bpmChangeWarning.attach(host.domRoot);
    if (this.drawsOnCanvas) this.chartText.attachCanvas(this.designRoot);
    else Ethis.chartText.attach(host.domRoot);
  }
 
  public draw(frame: PlayFrame): void {
    this.play = frame.playfield;
    this.playFrame = frame;
    this.playOptions = frame.playOptions;
    this.options.judgeTimingMs = frame.playOptions.judgeTimingMs;
    this.options.judgeTimingAutoAdjust = frame.playOptions.judgeTimingAutoAdjust;
    this.options.visualConstant = frame.playOptions.visualConstant;
    this.options.noteDurationMs = frame.playOptions.noteDurationMs;
    this.options.constantFadeMs = frame.playOptions.constantFadeMs;
    this.root.visible = frame.shown;
    if (!frame.shown) this.displayInfo.hide();
    if (!frame.shown) this.bpmChangeWarning.hide();
    if (!frame.shown) this.chartText.hide();
    if (!frame.shown) return;
    this.perf.beginTick();
    this.chromeRuntime = undefined;
    // With effects off the skins' audio drive is silent, so the frame's analysis is left unread (and unrun).
    const reactsToAudio = frame.playfield.audioAnalyzer !== undefined && this.options.beMusicEffects !== 'off';
    render(this, frame.seconds, reactsToAudio ? frame.audio : undefined);
    // A skin drawing through the player's renderer or on its DOM screen draws the frame just collected now.
    const overlayLanes = Array.from(this.play.laneX, ([channel, lane]) => ({
      ...lane,
      side: this.play.chartPlayVariant === '9' || !channel.startsWith('2') ? ('1P' as const) : ('2P' as const),
    }));
    this.displayInfo.update(
      resolveDisplayAreaLabels({
        mode: frame.playOptions.displayAreaInfo,
        lanes: overlayLanes,
        covers: this.play.resolveLaneCovers(),
        visibleMs: (cover) =>
          this.play.resolveVisibleMs(
            cover,
            frame.bpm,
            this.play.scrollMapper?.rateAt?.(this.play.currentBeat(frame.seconds)) ?? 1,
          ),
      }),
      this.playfieldSkin.stage,
      this.app.screen,
      this.designRoot.alpha,
    );
    this.chartText.show(frame.chartText ?? '', this.playfieldSkin.stage, this.app.screen, this.designRoot.alpha);
    // LR2's EARTHQUAKE sways the whole play screen.
    const quake = resolveLR2Earthquake(
      resolveLR2ManiaVisual(frame.playOptions),
      this.play.playClock(),
      this.app.screen.height / LR2_SCREEN_HEIGHT,
    );
    this.root.position.set(quake.x, quake.y);
    this.bpmChangeWarning.show({
      enabled: frame.playOptions.bpmChangeWarning,
      judgePosition: frame.playOptions.judgePosition,
      timing: this.play.timingResolver,
      seconds: frame.seconds,
      lanes: overlayLanes,
      stage: this.playfieldSkin.stage,
      screen: this.app.screen,
      opacity: this.designRoot.alpha,
      style: resolveBuiltInBPMChangeWarningStyle(this.kit.skin.id),
      resolution: this.app.renderer.resolution,
    });
    this.skinBindingInstance?.flush();
    this.dom?.setOpacity(this.designRoot.alpha);
    this.dom?.update({
      layout: resolveBeMusicLayout(this),
      settings: this.domSettings,
      effects: this.kit.effects ?? 'full',
      chart: frame.chart,
      state: frame.state,
      runtime: this.resolveChromeRuntime(),
      playOptions: frame.playOptions,
      emptyPoor: frame.playfield.score.emptyPoor,
      ...(frame.state2P !== undefined ? { state2P: frame.state2P } : {}),
      course: frame.course,
      seconds: frame.seconds,
      bpm: frame.bpm,
      progress: frame.progress,
      stage: frame.stage,
      autoPlay: frame.autoPlay,
      replay: frame.replay,
      seekable: frame.seekable,
    });
    // `?perf`: the per-second section summary, as the LR2 play view reports it.
    const report = this.perf.endFrame(() => ({
      note: this.noteLayer.children.length,
      notesTotal: this.play.notes.length,
    }));
    Iif (report) log.debug('perf', report);
  }
 
  private resolveChromeRuntime(): SkinlessGameplayChromeRuntime {
    return (this.chromeRuntime ??= resolveSkinlessGameplayChromeRuntime(this));
  }
 
  public detach(): void {
    this.displayInfo.detach();
    this.bpmChangeWarning.detach();
    this.chartText.detach();
    this.touchLanes.detach();
    this.dom?.detach();
  }
 
  /** Uploads `textures` to the GPU through the host's renderer (the BGA the play loads), when the view has a host. */
  public uploadTextures(textures: Iterable<Texture | undefined>, isCancelled: () => boolean): Promise<void> {
    return uploadTextures(this.host?.app.renderer, textures, isCancelled);
  }
 
  /** Whether this view is drawing `skin`. A different Be-Music Skin replaces the view. */
  public drawsSkin(skin: BuiltInKit['skin']): boolean {
    return this.kit.skin === skin;
  }
 
  /** Takes the player's new kit (skin settings, effects); the next frame draws with them. */
  public updateKit(kit: BuiltInKit): void {
    this.kit = kit;
    this.domSettings = resolveBeMusicSkinSettings(kit.skin, kit.settings);
    if (kit.effects !== undefined) this.options.beMusicEffects = kit.effects;
    this.skinBindingInstance?.setSettings(kit.settings);
  }
 
  public dispose(): void {
    this.displayInfo.dispose();
    this.bpmChangeWarning.dispose();
    this.chartText.dispose();
    this.dom?.dispose();
    this.dom = undefined;
    // Drop every per-frame child pool before the scene graph so each pooled child is freed through its own `destroy()`.
    try {
      this.skinBindingInstance?.dispose();
      this.skinBindingInstance = undefined;
      this.chartImages?.dispose();
      this.chartImages = undefined;
      for (const crop of this.skinBGACrops.values()) crop?.close();
      this.skinBGACrops.clear();
      this.noteLayerPool.destroy();
      this.skinLayerPool.destroy();
      this.overlayLayerPool.destroy();
      this.textLayerPool.destroy();
      this.bombLayerPool.destroy();
      this.bgaLayerPool.destroy();
    } catch (error) {
      log.warn('child pool teardown threw', error);
    }
    Iif (this.root.parent) this.root.parent.removeChild(this.root);
    try {
      this.root.destroy({ children: true, context: true });
    } catch (error) {
      log.warn('root.destroy threw', error);
    }
    this.bgaTargetsScratch.length = 0;
  }
}
 
/**
 * How a Be-Music Skin answers the shared playfield: its stage (the LR2-compatible 640x480 without one); the
 * playfield's own lane layout, notes, measure lines and bombs (the skin draws them as data); the built-in BGA rect;
 * the skin's bomb length and the default key-beam fade.
 */
function createBuiltInPlayfieldSkin(view: BuiltInPlayView): PlayfieldSkin {
  return {
    get stage() {
      return view.beMusicStage ?? LEGACY_STAGE_SIZE;
    },
    ownsLanes: false,
    laneRect: () => undefined,
    noteCell: () => undefined,
    measureLines: () => undefined,
    bgaTargets: (out) => collectBGATargets(view, out),
    bombCell: () => undefined,
    bombDurationMs: () => view.skinBinding.bombDurationMs ?? DEFAULT_BOMB_DURATION_MS,
    keyOnFadeMs: () => KEY_ON_FADE_OUT_MS,
  };
}