All files / player-browser/src/view/beatoraja/skin-view lua-context.ts

57.4% Statements 31/54
43.75% Branches 21/48
42.85% Functions 12/28
66.66% Lines 30/45

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                            36x                                 96x               96x 96x 96x 96x 96x 96x                 71x 71x       71x 71x 71x 71x             41x 41x 2x 1x         17x 17x   3x 6x     25x               13x 12x 25x                 2x 2x                   20x 20x                                              
import {
  BEATORAJA_LUA_TIMER_OFF_VALUE,
  BEATORAJA_NUM,
  evaluateBeatorajaLuaNumber,
  evaluateBeatorajaLuaString,
  type BeatorajaFloatPropertyRef,
  type BeatorajaIntegerPropertyRef,
  type BeatorajaLuaRuntimeContext,
  type BeatorajaStringPropertyRef,
} from '@be-music/skin-beatoraja';
import type { BeatorajaRenderContext } from '../../../skin/beatoraja/render.ts';
import type { BeatorajaPlaySkinViewOptions } from './options.ts';
 
/** `main_state.judge(n)`'s number ids: PERFECT, GREAT, GOOD, BAD, POOR, combo break. */
const LUA_JUDGE_NUMBERS = [
  BEATORAJA_NUM.PERFECT,
  BEATORAJA_NUM.GREAT,
  BEATORAJA_NUM.GOOD,
  BEATORAJA_NUM.BAD,
  BEATORAJA_NUM.POOR,
  BEATORAJA_NUM.COMBOBREAK,
] as const;
 
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
 
/**
 * The Lua side of a {@link BeatorajaPlaySkinView}: the `main_state` runtime context that a skin's Lua functions read
 * each frame, and the integer / string / float properties that are either a ref id or a Lua function.
 */
export class BeatorajaSkinLuaContext {
  private readonly resolveRefValue: (ref: number) => number;
  private readonly customTimerStarts = new Map<number, number | undefined>();
  private readonly resolveTextContent: (refOp: number) => string | undefined;
  private readonly resolveNumberValue: (refOp: number) => number | undefined;
  private readonly resolveGraphValue: (type: number) => number | undefined;
  private readonly resolveSliderValue: (type: number) => number | undefined;
  private readonly resolveGaugePercent: () => number | undefined;
 
  constructor(options: BeatorajaPlaySkinViewOptions) {
    this.resolveRefValue = options.resolveRefValue ?? (() => 0);
    this.resolveTextContent = options.resolveTextContent ?? (() => undefined);
    this.resolveNumberValue = options.resolveNumberValue ?? (() => undefined);
    this.resolveGraphValue = options.resolveGraphValue ?? (() => undefined);
    this.resolveSliderValue = options.resolveSliderValue ?? (() => undefined);
    this.resolveGaugePercent = options.resolveGaugePercent ?? (() => undefined);
  }
 
  /**
   * The Lua runtime context for this frame. Built once and kept: its functions read the frame through
   * {@link luaFrame}, set here each frame, instead of a fresh set of closures being made every frame. The Lua bridge
   * only reads the context while it evaluates a call (`update` does that synchronously), never later.
   */
  buildLuaRuntimeContext(context: BeatorajaRenderContext): BeatorajaLuaRuntimeContext {
    this.luaFrame = context;
    const lua = (this.luaRuntimeContext ??= this.createLuaRuntimeContext());
    // Forward host audio hooks so BooleanProperty / customEvent callbacks evaluated at draw
    // time can fire SE. The hooks are the audio service's skin sounds, owned by the scene,
    // which the beatoraja view hands in (`skinSounds`); the skin-view never owns audio state.
    lua.audioPlay = context.audioPlay;
    lua.audioLoop = context.audioLoop;
    lua.audioStop = context.audioStop;
    return lua;
  }
 
  private luaFrame: BeatorajaRenderContext | undefined;
  private luaRuntimeContext: Mutable<BeatorajaLuaRuntimeContext> | undefined;
 
  private createLuaRuntimeContext(): Mutable<BeatorajaLuaRuntimeContext> {
    const frame = (): BeatorajaRenderContext => this.luaFrame!;
    return {
      option: (id) => frame().activeOps.has(id),
      number: (id) => this.resolveNumberValue(id),
      floatNumber: (id) => this.resolveSliderValue(id) ?? this.resolveGraphValue(id),
      text: (id) => this.resolveTextContent(id),
      offset: (id) => frame().resolveOffset?.(id),
      timer: (id) => {
        const start = id === 0 ? 0 : this.getTimerStart(id);
        return start === undefined ? BEATORAJA_LUA_TIMER_OFF_VALUE : start * 1000;
      },
      time: () => frame().nowMs * 1000,
      eventIndex: (id) => this.resolveRefValue(id),
      setTimer: (id, value) => {
        // Only skin animation timers are writable; engine and scene-stage timers remain protected.
        if (
          !Number.isInteger(id) ||
          id < 10000 ||
          id > 19999 ||
          !Number.isFinite(value) ||
          value < BEATORAJA_LUA_TIMER_OFF_VALUE ||
          value > -BEATORAJA_LUA_TIMER_OFF_VALUE
        )
          return false;
        this.customTimerStarts.set(id, value === BEATORAJA_LUA_TIMER_OFF_VALUE ? undefined : Math.trunc(value) / 1000);
        return true;
      },
      rate: () => this.resolveNumberValue(BEATORAJA_NUM.SCORE_RATE),
      exscore: () => this.resolveNumberValue(BEATORAJA_NUM.POINT),
      judge: (judge) => {
        const ref = LUA_JUDGE_NUMBERS[judge];
        return ref === undefined ? undefined : this.resolveNumberValue(ref);
      },
      gauge: () => {
        const percent = this.resolveGaugePercent();
        return percent;
      },
      // `main_state.gauge_type()` — beatoraja's `BEATORAJA_GAUGE_MODE.*` int constant.
      // Sourced from the play bridge's `resolveGaugeState`. Returns `undefined` when no
      // frame has landed yet; the Lua bridge defaults to 0 in that case.
      gaugeType: () => frame().resolveGaugeState?.()?.mode,
    };
  }
 
  /** The same timer overlay is read by Lua and numeric destination timers, including same-frame writes. */
  readonly getTimerStart = (id: number): number | undefined =>
    this.customTimerStarts.has(id) ? this.customTimerStarts.get(id) : this.luaFrame?.getTimerStart(id);
 
  resolveIntegerProperty(property: BeatorajaIntegerPropertyRef, luaContext: BeatorajaLuaRuntimeContext): number {
    if (typeof property === 'number') return this.resolveNumberValue(property) ?? 0;
    return evaluateBeatorajaLuaNumber(property, luaContext) ?? 0;
  }
 
  resolveStringProperty(property: BeatorajaStringPropertyRef, luaContext: BeatorajaLuaRuntimeContext): string {
    if (typeof property === 'number') return this.resolveTextContent(property) ?? '';
    return evaluateBeatorajaLuaString(property, luaContext) ?? '';
  }
 
  resolveFloatProperty(
    property: BeatorajaFloatPropertyRef,
    luaContext: BeatorajaLuaRuntimeContext,
    kind: 'graph' | 'slider',
  ): number | undefined {
    if (typeof property === 'number') {
      return kind === 'graph' ? this.resolveGraphValue(property) : this.resolveSliderValue(property);
    }
    return evaluateBeatorajaLuaNumber(property, luaContext);
  }
}