All files / player-engine/src/core mine-modifier.ts

96.66% Statements 87/90
94.11% Branches 80/85
100% Functions 12/12
98.59% Lines 70/71

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                                                                                  3521x 3521x 54x 47x 3521x 3521x 3521x 13x   40x   13x 13x   244x   244x 243x       1x 242x 244x 242x                 13x   34x 2x 32x 6x 24x 27x 6x 30x   6x 35x   6x   26x 26x 431x 431x 125x   26x 26x 5x 5x 5x   26x 26x 26x 159x 159x 159x 431x 431x     1381x 159x 1381x 933x 933x 541x 392x 148x   244x 244x 244x   933x     834x 26x         37x 37x 37x 37x 37x 37x 37x                     1070x                            
import { createBeatAtSecondsResolverFromTimingResolver, type ResolvedChart } from '@be-music/chart-model';
import { addNanasiMines } from './nanasi-add-mine.ts';
import { resolveModifierLanes, collectModifierTimelines, type ModifierTimeline } from './chart-modifier-timelines.ts';
import {
  createTimedLandmineNote,
  toTimedLandmineNote,
  type TimedLandmineNote,
  type TimedPlayableNote,
} from '../playable-notes.ts';
 
/**
 * `NANASI_ADD` is nanasigroove's ADDMINE (`addNanasiMines`), which a chart's `774:CRAZY_ADDMINE` selects; the others are
 * beatoraja's.
 */
export type MineModifier = 'OFF' | 'REMOVE' | 'ADD_RANDOM' | 'ADD_NEAR' | 'ADD_BLANK' | 'NANASI_ADD';
 
/** Effective mine placements from a replay; random generation is bypassed when these are supplied. */
export interface MinePlacement {
  channel: string;
  sourceChannel?: string;
  timeUs: number;
  damage?: number;
  silent?: boolean;
}
 
/**
 * beatoraja 0.8.9 MineNoteModifier. Generation visits every decoder timeline in
 * source lane order, including empty measure starts, and reserves LN tails.
 * Its ADD_RANDOM uses an independent unseeded draw per blank cell (> 0.9).
 * The caller supplies that randomness; a replay supplies effective placements.
 */
export function prepareMineModifier(
  resolved: ResolvedChart,
  mode: MineModifier,
  options: {
    laneModeExtension?: string;
    notes?: readonly TimedPlayableNote[];
    random?: () => number;
    placements?: readonly MinePlacement[];
  } = {},
): { mines: TimedLandmineNote[]; changes: number } {
  const original = resolved.mines.map(toTimedLandmineNote);
  if (mode === 'OFF') return { mines: original, changes: 0 };
  if (mode === 'REMOVE') return { mines: [], changes: original.length };
  const notes = options.notes ?? resolved.notes.map((note) => ({ ...note, judged: false }));
  const lanes = resolveModifierLanes(resolved, options.laneModeExtension);
  const timelines = collectModifierTimelines(resolved, lanes);
  if (options.placements !== undefined) {
    Iif (options.placements.length < original.length)
      throw new RangeError('Recorded added-mine population is missing authored mines.');
    const rows = new Map(timelines.map((row) => [Math.round(resolved.timing.beatToSeconds(row.beat) * 1e6), row]));
    // nanasigroove's ADDMINE places mines between source rows: those are located from their time.
    const beatAt = mode === 'NANASI_ADD' ? createBeatAtSecondsResolverFromTimingResolver(resolved.timing) : undefined;
    const mines = options.placements.map((placement) => {
      const row =
        rows.get(placement.timeUs) ??
        (beatAt === undefined ? undefined : locateRow(resolved, beatAt(placement.timeUs / 1e6)));
      if (!row) throw new RangeError('Recorded mine is not on a source timeline.');
      if (
        !/^[12][0-9A-Z]$/.test(placement.channel) ||
        (placement.sourceChannel !== undefined && !/^[12][0-9A-Z]$/.test(placement.sourceChannel))
      )
        throw new RangeError('Invalid recorded mine lane.');
      const damage = placement.damage ?? 4;
      Iif (!Number.isFinite(damage) || damage < 0) throw new RangeError('Invalid recorded mine damage.');
      return makeMine(
        row,
        placement.channel,
        placement.timeUs / 1e6,
        damage,
        placement.silent === true,
        placement.sourceChannel,
      );
    });
    return { mines, changes: Math.max(0, mines.length - original.length) };
  }
  if ((mode === 'ADD_RANDOM' || mode === 'NANASI_ADD') && !options.random)
    throw new RangeError('Mine ADD RANDOM requires supplied randomness or recorded placements.');
  if (mode === 'NANASI_ADD') {
    const noteBeats = new Map<string, number[]>();
    for (const note of notes) noteBeats.set(note.channel, [...(noteBeats.get(note.channel) ?? []), note.beat]);
    const endBeat = Math.max(0, ...timelines.map((row) => row.beat), ...notes.map((note) => note.endBeat ?? note.beat));
    const added = addNanasiMines(lanes, noteBeats, endBeat, options.random!).map((mine) =>
      makeMine(locateRow(resolved, mine.beat), mine.lane, resolved.timing.beatToSeconds(mine.beat), mine.damage, false),
    );
    const mines = [...original, ...added].sort(
      (a, b) => a.beat - b.beat || lanes.indexOf(a.channel) - lanes.indexOf(b.channel),
    );
    return { mines, changes: added.length };
  }
  const scoring = new Map<number, (typeof notes)[number][]>();
  for (const note of notes) {
    const row = scoring.get(note.beat);
    if (row) row.push(note);
    else scoring.set(note.beat, [note]);
  }
  const existing = new Map<number, Set<string>>();
  for (const mine of original) {
    const row = existing.get(mine.beat) ?? new Set<string>();
    row.add(mine.channel);
    existing.set(mine.beat, row);
  }
  const held = new Map<string, number>();
  const mines = [...original];
  for (const row of timelines) {
    for (const [lane, end] of held) if (end < row.beat) held.delete(lane);
    const occupied = new Set(existing.get(row.beat));
    for (const note of scoring.get(row.beat) ?? []) {
      occupied.add(note.channel);
      if (note.endBeat !== undefined && note.endBeat > row.beat) held.set(note.channel, note.endBeat);
    }
    // Snapshot before generation: newly inserted mines must not expand ADD NEAR.
    const blank = lanes.map((lane) => !occupied.has(lane) && !held.has(lane));
    for (const [index, lane] of lanes.entries()) {
      if (!blank[index]) continue;
      let add = false;
      if (mode === 'ADD_BLANK') {
        add = true;
      } else if (mode === 'ADD_NEAR') {
        add = (index > 0 && !blank[index - 1]) || (index < lanes.length - 1 && !blank[index + 1]);
      } else {
        const draw = options.random!();
        Iif (!Number.isFinite(draw) || draw < 0 || draw >= 1) throw new RangeError('Mine randomness must be in [0, 1).');
        add = draw > 0.9;
      }
      if (add) mines.push(makeMine(row, lane, resolved.timing.beatToSeconds(row.beat), 10, true));
    }
  }
  mines.sort((a, b) => a.beat - b.beat || lanes.indexOf(a.channel) - lanes.indexOf(b.channel));
  return { mines, changes: mines.length - original.length };
}
 
/** A modifier row at `beat`, with its measure and position, for a mine placed between source rows. */
function locateRow(resolved: ResolvedChart, beat: number): ModifierTimeline {
  const POSITION_STEPS = 1_000_000;
  let measure = 0;
  while (measure < 4999 && resolved.beatResolver.measureToBeat(measure + 1, 0) <= beat) measure += 1;
  const start = resolved.beatResolver.measureToBeat(measure, 0);
  const length = resolved.beatResolver.measureToBeat(measure + 1, 0) - start;
  const fraction = length > 0 ? Math.min(1 - 1 / POSITION_STEPS, Math.max(0, (beat - start) / length)) : 0;
  return { beat, event: { measure, position: [Math.round(fraction * POSITION_STEPS), POSITION_STEPS] } };
}
 
function makeMine(
  row: ModifierTimeline,
  channel: string,
  seconds: number,
  damage: number,
  silent: boolean,
  sourceChannel = channel,
): TimedLandmineNote {
  return createTimedLandmineNote(
    {
      measure: row.event.measure,
      position: [...row.event.position],
      channel: `${sourceChannel[0] === '1' ? 'D' : 'E'}${sourceChannel[1]}`,
      value: '0A',
      bmson: { damage },
    },
    channel,
    row.beat,
    seconds,
    silent ? true : undefined,
  );
}