All files / player-ui/src/playfield paint.ts

93.56% Statements 247/264
85.51% Branches 124/145
73.07% Functions 19/26
98.28% Lines 229/233

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                                                                                                49x             49x     49x               8x 7x 7x 7x 7x 7x 7x 9x 9x 24x 24x 20x 24x                 9x   6x 6x 6x 6x     7x                       23x 23x 1x 1x 1x 1x   22x 15x 15x 15x                               20x 20x 20x 20x 19x 19x   1x 1x 1x 1x 1x 1x       20x 20x 20x 20x 20x               1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x           16x 16x 2x 2x   16x 16x   14x 14x 14x   14x 14x   14x 14x 8x 8x 7x 7x 7x   8x 8x   6x 6x 6x       14x   14x 8x       8x 8x 8x 8x 8x 8x 49x 8x     6x 6x 6x   14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 5x 1x 1x   14x   16x 6x 6x 6x 6x     16x 2x 2x 2x 2x 2x 2x   16x       49x 49x 49x 49x   49x 49x             2x 2x 2x 2x 2x 2x 2x 2x                       5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x       47x 47x 47x 47x 47x 47x 47x   5x 5x 5x 5x 5x       4x 4x       1x 1x 1x 1x 1x 1x 1x 1x   1x     49x 49x 49x 49x   49x           1x 1x 2x 1x 1x 1x     2x 2x             2x 2x 2x 2x 1x 1x 1x                   1x 10x 1x 1x 1x 2x 1x       49x     10x 10x 10x 10x 10x 10x   10x         1x 1x 1x 1x 1x 1x 1x       7x 1x 1x 1x 1x 1x 1x         16x    
import {
  backSpinChevron,
  hellChargeZigzag,
  layoutTabularRun,
  longNoteCentreLineAlpha,
  resolveNoteHeight,
  resolveHellChargeLook,
  resolveLongNoteMarks,
  type BeMusicLaneKind,
  type BeMusicRect,
} from '@be-music/player-skin-sdk';
import type {
  BeMusicBGAData,
  BeMusicBombsData,
  BeMusicJudgeLineData,
  BeMusicJudgmentDisplayData,
  BeMusicLaneCoversData,
  BeMusicLanesData,
  BeMusicNotesData,
  BeMusicPlayfieldParts,
} from '../models.ts';
 
/** The Canvas 2D calls the playfield painters make; a `CanvasRenderingContext2D` satisfies it. */
export type BeMusicPlayfieldPaintContext = Pick<
  CanvasRenderingContext2D,
  | 'fillStyle'
  | 'strokeStyle'
  | 'globalAlpha'
  | 'lineWidth'
  | 'font'
  | 'textAlign'
  | 'fillRect'
  | 'fillText'
  | 'measureText'
  | 'beginPath'
  | 'moveTo'
  | 'lineTo'
  | 'closePath'
  | 'fill'
  | 'arc'
  | 'rect'
  | 'stroke'
  | 'clip'
  | 'save'
  | 'restore'
  | 'drawImage'
>;
 
const NOTE_COLORS: Record<BeMusicLaneKind, string> = {
  white: '#e5efff',
  black: '#88b9ff',
  scratch: '#ffa8b3',
  'wheel-up': '#ffa8b3',
  'wheel-down': '#ffa8b3',
};
const BOMB_LIFETIME_MS = 300;
 
/** The BMS BGA canvas the BGA rect stands for. */
const BGA_CANVAS_SIZE = 256;
 
/**
 * The BGA as BMS players composite it: the POOR image in place of the base and layer while a POOR shows, the base
 * opaque over black, the layer over it. A still image whose long edge fits the 256x256 BGA canvas keeps its size there,
 * centered horizontally against the top edge; a larger image or a video fills the rect.
 */
export function paintBGA(ctx: BeMusicPlayfieldPaintContext, data: BeMusicBGAData, rect: BeMusicRect): void {
  if (!data.shown) return;
  ctx.fillStyle = '#000000';
  ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  const frame = data.frame;
  Iif (!frame) return;
  const inheritedAlpha = ctx.globalAlpha;
  for (const stack of frame.stacks ?? [frame]) {
    const alpha = inheritedAlpha * ('alpha' in stack ? stack.alpha : 1);
    const draw = (track: 'base' | 'layer' | 'layer2' | 'poor'): void => {
      const image = stack[track];
      if (!image) return;
      ctx.globalAlpha = alpha * (stack.opacity?.[track] ?? 1);
      drawBGAImage(
        ctx,
        image,
        rect,
        frame.stacks !== undefined && (track === 'base' || (track === 'poor' && !stack.poorOverlays)),
        stack.origins?.[track],
        stack.bgaMode,
      );
    };
    if (stack.poorActive && !stack.poorOverlays) draw('poor');
    else {
      draw('base');
      draw('layer');
      draw('layer2');
      if (stack.poorActive && stack.poorOverlays) draw('poor');
    }
  }
  ctx.globalAlpha = inheritedAlpha;
}
 
/** Where `image` of `width` x `height` goes in the BGA `rect` (see {@link paintBGA}). */
export function placeBGAImage(
  width: number,
  height: number,
  isVideo: boolean,
  rect: BeMusicRect,
  origin?: { x: number; y: number },
  bgaMode?: 0 | 1 | 2,
): BeMusicRect {
  Iif (bgaMode === 0) return { ...rect };
  if (bgaMode !== undefined && width > 0 && height > 0) {
    const scale = bgaMode === 2 ? 0.8 : 1;
    const w = (width * scale * rect.w) / BGA_CANVAS_SIZE;
    const h = (height * scale * rect.h) / BGA_CANVAS_SIZE;
    return { x: rect.x + (rect.w - w) / 2, y: rect.y, w, h };
  }
  if (isVideo || !(width > 0) || !(height > 0) || Math.max(width, height) > BGA_CANVAS_SIZE) return { ...rect };
  const scaleX = rect.w / BGA_CANVAS_SIZE;
  const scaleY = rect.h / BGA_CANVAS_SIZE;
  return {
    x: rect.x + (origin?.x ?? Math.floor((BGA_CANVAS_SIZE - width) / 2)) * scaleX,
    y: rect.y + (origin?.y ?? 0) * scaleY,
    w: width * scaleX,
    h: height * scaleY,
  };
}
 
function drawBGAImage(
  ctx: BeMusicPlayfieldPaintContext,
  image: CanvasImageSource,
  rect: BeMusicRect,
  fillCanvas = false,
  origin?: { x: number; y: number },
  bgaMode?: 0 | 1 | 2,
): void {
  const { width, height, isVideo } = imageSize(image);
  const placed = placeBGAImage(width, height, isVideo, rect, origin, bgaMode);
  if (fillCanvas && (placed.w < rect.w || placed.h < rect.h)) ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  if (bgaMode === undefined) {
    ctx.drawImage(image, placed.x, placed.y, placed.w, placed.h);
    return;
  }
  ctx.save();
  ctx.beginPath();
  ctx.rect(rect.x, rect.y, rect.w, rect.h);
  ctx.clip();
  ctx.drawImage(image, placed.x, placed.y, placed.w, placed.h);
  ctx.restore();
}
 
function imageSize(image: CanvasImageSource): { width: number; height: number; isVideo: boolean } {
  Iif ('videoWidth' in image) return { width: image.videoWidth, height: image.videoHeight, isVideo: true };
  Iif ('displayWidth' in image) return { width: image.displayWidth, height: image.displayHeight, isVideo: true };
  Iif ('naturalWidth' in image) return { width: image.naturalWidth, height: image.naturalHeight, isVideo: false };
  const { width, height } = image as { width: unknown; height: unknown };
  return {
    width: typeof width === 'number' ? width : 0,
    height: typeof height === 'number' ? height : 0,
    isVideo: false,
  };
}
 
export function paintLanes(ctx: BeMusicPlayfieldPaintContext, { lanes }: BeMusicLanesData): void {
  for (const lane of lanes) {
    const height = lane.bottom - lane.top;
    ctx.fillStyle = lane.kind === 'white' ? '#202d40' : '#152031';
    ctx.fillRect(lane.x, lane.top, lane.w, height);
    Eif (lane.beam > 0) {
      ctx.fillStyle = NOTE_COLORS[lane.kind];
      ctx.globalAlpha = lane.beam * 0.3;
      ctx.fillRect(lane.x, lane.top, lane.w, height);
      ctx.globalAlpha = 1;
    }
    Eif (lane.holding) {
      ctx.fillStyle = '#abcaff';
      ctx.fillRect(lane.x, lane.bottom - 4, lane.w, 4);
    }
  }
}
 
export function paintNotes(ctx: BeMusicPlayfieldPaintContext, data: BeMusicNotesData): void {
  ctx.fillStyle = '#e5efff';
  for (const line of data.measureLines) {
    ctx.globalAlpha = 0.25 * (line.alpha ?? 1);
    ctx.fillRect(line.x, line.y - 1, line.w, 1);
  }
  ctx.globalAlpha = 1;
  for (const note of data.longNotes) {
    // A note is as tall as a share of its lane's width (every note as a white key's), standing on its bottom edge.
    const noteHeight = resolveNoteHeight(note.w, data.whiteLaneWidth);
    const bodyTop = note.top - noteHeight;
    const bodyHeight = Math.max(1, note.bottom - note.top);
    // The kinds apart by shape (`resolveLongNoteMarks`): an HCN's centre line zigzags, a BSS's tail carries a chevron.
    const marks = resolveLongNoteMarks(note);
    const capAlpha = (note.state === 'dropped' ? 0.5 : 1) * (note.alpha ?? 1);
    // A hell charge note shows how it stands: colour, glow and zigzag motion change together (`resolveHellChargeLook`).
    const look = marks.hellCharge ? resolveHellChargeLook(note.state, data.nowMs) : undefined;
    if (look) {
      ctx.fillStyle = hexColor(look.color);
      if (look.glow > 0) {
        ctx.globalAlpha = 0.3 * look.glow * capAlpha;
        ctx.fillRect(note.x - 3, bodyTop, note.w + 6, bodyHeight);
        ctx.fillRect(note.x - 3, note.bottom - noteHeight - 3, note.w + 6, noteHeight + 6);
      }
      ctx.globalAlpha = (0.2 + 0.3 * look.glow) * capAlpha;
      ctx.fillRect(note.x, bodyTop, note.w, bodyHeight);
    } else {
      ctx.fillStyle = NOTE_COLORS[note.kind];
      ctx.globalAlpha = (note.state === 'dropped' ? 0.15 : 0.35) * (note.alpha ?? 1);
      ctx.fillRect(note.x, bodyTop, note.w, bodyHeight);
    }
    // A centre line down the body, the long-note shape every built-in skin shares; let go early, it fades out. An HCN's
    // zigzags, flowing into the judgement line while it charges, back up while it drains, and still otherwise.
    const line =
      (note.state === 'dropped' ? 0.3 : 0.6) * (note.alpha ?? 1) * longNoteCentreLineAlpha(note.releasedElapsedMs);
    if (look) {
      const points = hellChargeZigzag(note.x, note.w, bodyTop, bodyTop + bodyHeight, {
        nowMs: data.nowMs,
        flow: look.flow,
      });
      Eif (points.length >= 4) {
        ctx.strokeStyle = hexColor(look.lineColor);
        ctx.lineWidth = 2;
        ctx.globalAlpha = line * (0.9 + 0.75 * look.glow);
        ctx.beginPath();
        ctx.moveTo(points[0]!, points[1]!);
        for (let index = 2; index < points.length; index += 2) ctx.lineTo(points[index]!, points[index + 1]!);
        ctx.stroke();
      }
    } else {
      ctx.fillStyle = '#ffffff';
      ctx.globalAlpha = line;
      ctx.fillRect(note.x + note.w / 2 - 1, bodyTop, 2, bodyHeight);
    }
    ctx.fillStyle = NOTE_COLORS[note.kind];
    ctx.globalAlpha = capAlpha;
    ctx.fillRect(note.x, note.bottom - noteHeight, note.w, noteHeight);
    Iif (!marks.judgedTail) ctx.globalAlpha *= 0.4;
    ctx.fillRect(note.x, note.top - noteHeight, note.w, noteHeight);
    if (marks.backSpin) {
      ctx.globalAlpha = capAlpha;
      ctx.fillStyle = '#ffffff';
      const points = backSpinChevron(note.x, note.w, note.top, noteHeight);
      ctx.beginPath();
      ctx.moveTo(points[0]!, points[1]!);
      for (let index = 2; index < points.length; index += 2) ctx.lineTo(points[index]!, points[index + 1]!);
      ctx.closePath();
      ctx.fill();
    }
    ctx.globalAlpha = 1;
  }
  for (const note of data.notes) {
    const noteHeight = resolveNoteHeight(note.w, data.whiteLaneWidth);
    ctx.globalAlpha = note.alpha ?? 1;
    ctx.fillStyle = NOTE_COLORS[note.kind];
    ctx.fillRect(note.x, note.y - noteHeight, note.w, noteHeight);
  }
  // A mine reads as something to avoid: a red bar with a dark core, unlike any playable note.
  for (const mine of data.mines) {
    const noteHeight = resolveNoteHeight(mine.w, data.whiteLaneWidth);
    ctx.globalAlpha = mine.alpha ?? 1;
    ctx.fillStyle = '#ff5c6c';
    ctx.fillRect(mine.x, mine.y - noteHeight, mine.w, noteHeight);
    ctx.fillStyle = '#10151f';
    ctx.fillRect(mine.x + 2, mine.y - noteHeight + 2, Math.max(0, mine.w - 4), Math.max(0, noteHeight - 4));
  }
  ctx.globalAlpha = 1;
}
 
/** The lane covers' fill, their faint stripes and the line along the edge the notes come from. */
const COVER_FILL = '#0b0f17';
const COVER_STRIPE = '#88b9ff';
const COVER_STRIPE_ALPHA = 0.08;
const COVER_EDGE = '#3a4d6b';
/** The distance between two stripes and a stripe's width, along a horizontal edge. */
const COVER_STRIPE_SPACING = 12;
const COVER_STRIPE_WIDTH = 4;
 
/**
 * Each side's SUDDEN+, HIDDEN+ and LIFT covers, opaque, with rising diagonal stripes that move with the cover's inner
 * edge (the one facing the notes) and a line along that edge.
 */
export function paintLaneCovers(ctx: BeMusicPlayfieldPaintContext, { areas }: BeMusicLaneCoversData): void {
  for (const area of areas) {
    const width = area.right - area.left;
    const height = area.bottom - area.top;
    const lift = area.lift ?? 0;
    Eif (area.sudden > 0) paintCover(ctx, area.left, area.top, width, height * area.sudden, 'bottom');
    Eif (area.hidden > 0)
      paintCover(ctx, area.left, area.bottom - height * (lift + area.hidden), width, height * area.hidden, 'top');
    if (lift > 0) paintCover(ctx, area.left, area.bottom - height * lift, width, height * lift, 'top');
  }
}
 
function paintCover(
  ctx: BeMusicPlayfieldPaintContext,
  x: number,
  y: number,
  w: number,
  h: number,
  inner: 'top' | 'bottom',
): void {
  Iif (!(w > 0) || !(h > 0)) return;
  ctx.globalAlpha = 1;
  ctx.fillStyle = COVER_FILL;
  ctx.fillRect(x, y, w, h);
  const anchorY = inner === 'top' ? y : y + h;
  ctx.save();
  ctx.beginPath();
  ctx.rect(x, y, w, h);
  ctx.clip();
  ctx.globalAlpha = COVER_STRIPE_ALPHA;
  ctx.fillStyle = COVER_STRIPE;
  ctx.beginPath();
  // A point's place across the stripes is `u = (px - x) + (py - anchorY)`; a stripe holds u in [k·spacing, +width).
  const top = y - anchorY;
  const bottom = y + h - anchorY;
  for (
    let k = Math.floor((top - COVER_STRIPE_WIDTH) / COVER_STRIPE_SPACING) + 1;
    k * COVER_STRIPE_SPACING < w + bottom;
    k++
  ) {
    const from = k * COVER_STRIPE_SPACING;
    const to = from + COVER_STRIPE_WIDTH;
    ctx.moveTo(x + from - top, y);
    ctx.lineTo(x + to - top, y);
    ctx.lineTo(x + to - bottom, y + h);
    ctx.lineTo(x + from - bottom, y + h);
    ctx.closePath();
  }
  ctx.fill();
  ctx.restore();
  ctx.globalAlpha = 1;
  ctx.fillStyle = COVER_EDGE;
  ctx.fillRect(x, inner === 'top' ? y : y + h - 1, w, 1);
}
 
export function paintJudgeLine(ctx: BeMusicPlayfieldPaintContext, { runs, y }: BeMusicJudgeLineData): void {
  ctx.fillStyle = '#ffa8b3';
  for (const run of runs) ctx.fillRect(run.left, run.y ?? y, run.right - run.left, 2);
}
 
export function paintBombs(ctx: BeMusicPlayfieldPaintContext, { bombs }: BeMusicBombsData): void {
  ctx.strokeStyle = '#e5efff';
  ctx.lineWidth = 2;
  for (const bomb of bombs) {
    const age = Math.min(1, bomb.elapsedMs / BOMB_LIFETIME_MS);
    ctx.globalAlpha = 1 - age;
    ctx.beginPath();
    ctx.arc(bomb.x + bomb.w / 2, bomb.y, 5 + age * 20, 0, Math.PI * 2);
    ctx.stroke();
  }
  ctx.globalAlpha = 1;
}
 
const JUDGMENT_FONT = 'bold 20px system-ui';
const COMBO_FONT = '600 16px system-ui';
const COMBO_OFFSET = 24;
const COMBO_COLOR = '#e5efff';
/** How far apart the keys' and the scratch's judge details sit when they are shown apart. */
const JUDGE_DETAIL_SPREAD = 84;
 
export function paintJudgmentDisplay(
  ctx: BeMusicPlayfieldPaintContext,
  { words, y }: BeMusicJudgmentDisplayData,
): void {
  ctx.textAlign = 'center';
  for (const word of words) {
    if (word.mode) {
      ctx.font = 'bold 10px sans-serif';
      ctx.fillStyle = COMBO_COLOR;
      ctx.fillText(word.mode, word.x, (word.y ?? y) - 28);
    }
    // The judge detail sits above the word, and above the play label when the side has one.
    const details = word.details ?? [];
    details.forEach((detail, index) => {
      ctx.font = 'bold 10px sans-serif';
      ctx.fillStyle = detail.color;
      const spread = details.length > 1 ? (index - (details.length - 1) / 2) * JUDGE_DETAIL_SPREAD : 0;
      // Tabular figures: the milliseconds keep their place as they change from hit to hit.
      paintTabular(ctx, detail.text, word.x + spread, (word.y ?? y) - (word.mode ? 40 : 24));
    });
    ctx.font = JUDGMENT_FONT;
    ctx.fillStyle = word.color;
    ctx.fillText(word.text, word.x, word.y ?? y);
    if (word.combo !== undefined && word.combo > 0) {
      ctx.font = COMBO_FONT;
      ctx.fillStyle = COMBO_COLOR;
      paintTabular(ctx, String(word.combo), word.x, (word.y ?? y) + COMBO_OFFSET);
    }
  }
}
 
/**
 * Digits in fixed-width cells, the run centred on `x`. Canvas 2D exposes no `font-feature-settings`, so OpenType
 * `tnum` cannot be turned on; each digit takes the widest digit's advance instead.
 */
function paintTabular(ctx: BeMusicPlayfieldPaintContext, text: string, x: number, y: number): void {
  const font = ctx.font;
  const run = layoutTabularRun(text, (char) => measureChar(ctx, font, char));
  const left = x - run.width / 2;
  const align = ctx.textAlign;
  ctx.textAlign = 'center';
  for (const glyph of run.glyphs) ctx.fillText(glyph.char, left + glyph.x + glyph.w / 2, y);
  ctx.textAlign = align;
}
 
/** Advances of the characters {@link paintTabular} has measured, by font: the combo redraws them every frame. */
const CHAR_WIDTHS = new Map<string, Map<string, number>>();
 
function measureChar(ctx: BeMusicPlayfieldPaintContext, font: string, char: string): number {
  let widths = CHAR_WIDTHS.get(font);
  if (!widths) CHAR_WIDTHS.set(font, (widths = new Map()));
  let width = widths.get(char);
  Eif (width === undefined) {
    width = ctx.measureText(char).width;
    widths.set(char, width);
  }
  return width;
}
 
/** Paints every part on one stage-sized surface, each clipped to its rect as its own canvas would clip it. */
export function paintPlayfieldParts(ctx: BeMusicPlayfieldPaintContext, parts: BeMusicPlayfieldParts): void {
  clipped(ctx, parts.bga.rect, () => paintBGA(ctx, parts.bga.data, parts.bga.rect));
  clipped(ctx, parts.lanes.rect, () => paintLanes(ctx, parts.lanes.data));
  clipped(ctx, parts.notes.rect, () => paintNotes(ctx, parts.notes.data));
  clipped(ctx, parts.laneCovers.rect, () => paintLaneCovers(ctx, parts.laneCovers.data));
  clipped(ctx, parts.judgeLine.rect, () => paintJudgeLine(ctx, parts.judgeLine.data));
  clipped(ctx, parts.bombs.rect, () => paintBombs(ctx, parts.bombs.data));
  clipped(ctx, parts.judgmentDisplay.rect, () => paintJudgmentDisplay(ctx, parts.judgmentDisplay.data));
}
 
function clipped(ctx: BeMusicPlayfieldPaintContext, rect: BeMusicRect, paint: () => void): void {
  if (rect.w <= 0 || rect.h <= 0) return;
  ctx.save();
  ctx.beginPath();
  ctx.rect(rect.x, rect.y, rect.w, rect.h);
  ctx.clip();
  paint();
  ctx.restore();
}
 
/** `0xrrggbb` → `#rrggbb`, for colours the skin SDK hands out as numbers. */
function hexColor(color: number): string {
  return `#${color.toString(16).padStart(6, '0')}`;
}