All files / player-engine/src/core nanasi-notes-double.ts

100% Statements 85/85
91.93% Branches 57/62
100% Functions 14/14
100% Lines 68/68

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                                            344x 344x             344x                 344x                                                           26x                     388x       459x         71x 71x   71x 71x               145x 145x 145x 107x 100x                         19x 19x 18x 18x 18x 128x 56x 66x 128x 128x   18x 18x 18x 128x 128x 128x   67x 67x 157x 157x 110x   67x 145x 145x 145x   128x   67x 67x 95x 95x   67x 24x 24x   67x 121x 121x 74x 73x 71x 71x 69x     71x                     71x     18x 265x 18x 18x 18x   18x 1x 1x   18x    
import type { ChartPlayVariant } from '@be-music/chart-model';
import type { TimedPlayableNote } from '../playable-notes.ts';
 
/**
 * nanasigroove 1.552's NOTES DOUBLE (`774:NOTES_DOUBLE`, #1184), the reading of a version 3 chart gameplay program
 * (docs/adr/0035-chart-authored-notes-options.md).
 *
 * DOUBLE copies whole lanes into other lanes, one copy after another, each copy taking the source lane as it stands (so a
 * lane that has already received a copy passes it on). On 5 KEY the copies are 1→3, 2→4, 3→5, 4→2 and 5→3: keys 3 and 5
 * end up with keys 1, 3 and 5, and keys 2 and 4 with keys 2 and 4. The scratch and FREE ZONE are left alone, and
 * invisible objects travel with their lane; mines do not.
 *
 * Each lane then keeps one object at each instant, preferring in turn the lane's own long note, the lane's own key note,
 * a long note from the same side, a key note from the same side, and otherwise whichever arrived first (the lane's own
 * objects before the copies, the copies in the order they were made). Be-Music keeps two narrow rules of its own:
 *
 * - The chart's own objects always stay (an instant the chart already doubles is the chart's, not DOUBLE's).
 * - A long-note copy stays only when both its ends stay, and a key-note copy is dropped where it would overlap a long
 *   note on its lane: a Be-Music lane plays one object at a time.
 */
 
/** The lane copies DOUBLE makes, in order, per play variant nanasigroove defines them for. */
const DOUBLE_COPIES: Partial<Record<ChartPlayVariant, ReadonlyArray<readonly [string, string]>>> = (() => {
  const fiveKey = [
    ['11', '13'],
    ['12', '14'],
    ['13', '15'],
    ['14', '12'],
    ['15', '13'],
  ] as const;
  const sevenKey = [
    ['11', '13'],
    ['12', '14'],
    ['13', '15'],
    ['14', '12'],
    ['15', '19'],
    ['18', '14'],
    ['19', '15'],
  ] as const;
  return {
    '5': fiveKey,
    '7': sevenKey,
    '9': [
      ['11', '13'],
      ['12', '14'],
      ['13', '15'],
      ['14', '12'],
      ['15', '23'],
      ['22', '14'],
      ['23', '25'],
      ['24', '22'],
      ['25', '23'],
    ],
    '10': [...fiveKey, ['21', '23'], ['22', '24'], ['23', '25'], ['24', '22'], ['25', '23']],
    '14': [
      ...sevenKey,
      ['21', '23'],
      ['22', '24'],
      ['23', '25'],
      ['24', '22'],
      ['25', '29'],
      ['28', '24'],
      ['29', '25'],
    ],
  };
})();
 
/** Whether nanasigroove's DOUBLE is defined for `playVariant`. */
export function nanasiDoubleSupports(playVariant: ChartPlayVariant): boolean {
  return DOUBLE_COPIES[playVariant] !== undefined;
}
 
/** One object in a lane's list: the chart object it copies and the lane that object belongs to. */
interface LaneEntry {
  source: TimedPlayableNote;
  origin: string;
}
 
/** Whole microseconds, the unit replays and lane options group objects by. */
function toMicroseconds(seconds: number): number {
  return Math.round(seconds * 1_000_000);
}
 
function isLongNote(note: TimedPlayableNote): boolean {
  return note.invisible !== true && note.endSeconds !== undefined;
}
 
/** A copied event's channel: the source event's kind (visible, invisible or long note) on `lane` (`1x` / `2x`). */
function eventChannelOnLane(sourceChannel: string, lane: string): string {
  const kind = sourceChannel[0];
  const twoP = lane[0] === '2';
  const prefix =
    kind === '3' || kind === '4' ? (twoP ? '4' : '3') : kind === '5' || kind === '6' ? (twoP ? '6' : '5') : lane[0]!;
  return `${prefix}${lane.slice(1)}`;
}
 
/**
 * The class an entry takes on `lane` at one instant: lower wins. The lane's own long note, its own key note, a same-side
 * long note, a same-side key note, then anything else.
 */
function entryClass(entry: LaneEntry, lane: string): number {
  const longNote = isLongNote(entry.source);
  const visible = entry.source.invisible !== true;
  if (entry.origin === lane) return longNote ? 0 : visible ? 1 : 4;
  if (entry.origin[0] !== lane[0] || !visible) return 4;
  return longNote ? 2 : 3;
}
 
/**
 * DOUBLE in place on `notes` and `invisible`: adds the copies that stay (new objects with their own event identity on
 * their lane, so a replay tells them apart, with the source's keysound and timing and no long-note modifier mark).
 * Returns the number of objects added; `0` where nanasigroove defines no DOUBLE for the variant.
 */
export function doubleNanasiChartNotes(
  notes: TimedPlayableNote[],
  invisible: TimedPlayableNote[],
  playVariant: ChartPlayVariant,
): number {
  const copies = DOUBLE_COPIES[playVariant];
  if (copies === undefined) return 0;
  const lanes = new Set(copies.flat());
  const lists = new Map<string, LaneEntry[]>();
  const owned = new Map<string, number>();
  for (const lane of lanes) lists.set(lane, []);
  for (const source of [...notes, ...invisible].sort((a, b) => a.seconds - b.seconds))
    lists.get(source.channel)?.push({ source, origin: source.channel });
  for (const lane of lanes) owned.set(lane, lists.get(lane)!.length);
  for (const [from, to] of copies) lists.get(to)!.push(...lists.get(from)!.slice());
 
  const addedNotes: TimedPlayableNote[] = [];
  const addedInvisible: TimedPlayableNote[] = [];
  for (const lane of lanes) {
    const list = lists.get(lane)!;
    const ownCount = owned.get(lane)!;
    if (list.length === ownCount) continue;
    // The winner at each instant (µs): the lowest class, then the earliest in the list.
    const winners = new Map<number, { index: number; rank: number }>();
    const contend = (time: number, index: number, rank: number): void => {
      const current = winners.get(time);
      if (current === undefined || rank < current.rank || (rank === current.rank && index < current.index))
        winners.set(time, { index, rank });
    };
    list.forEach((entry, index) => {
      const rank = entryClass(entry, lane);
      contend(toMicroseconds(entry.source.seconds), index, rank);
      if (isLongNote(entry.source)) contend(toMicroseconds(entry.source.endSeconds!), index, rank);
    });
    const wins = (time: number, index: number): boolean => winners.get(time)?.index === index;
    // Spans the lane's visible objects hold (µs, inclusive); a key note is a point.
    const spans: Array<[number, number]> = [];
    const spanOf = (note: TimedPlayableNote): [number, number] => {
      const start = toMicroseconds(note.seconds);
      return [start, isLongNote(note) ? Math.max(start, toMicroseconds(note.endSeconds!)) : start];
    };
    for (let index = 0; index < ownCount; index++) {
      const source = list[index]!.source;
      Eif (source.invisible !== true) spans.push(spanOf(source));
    }
    for (let index = ownCount; index < list.length; index++) {
      const { source } = list[index]!;
      if (!wins(toMicroseconds(source.seconds), index)) continue;
      if (isLongNote(source) && !wins(toMicroseconds(source.endSeconds!), index)) continue;
      if (source.invisible !== true) {
        const [start, end] = spanOf(source);
        if (spans.some(([from, to]) => from <= end && start <= to)) continue;
        spans.push([start, end]);
      }
      // Overriding in a spread keeps the field order (one hidden class for every play note).
      const copy: TimedPlayableNote = {
        ...source,
        generatedLongNote: undefined,
        channel: lane,
        judged: false,
        event: {
          ...source.event,
          position: [...source.event.position] as [number, number],
          channel: eventChannelOnLane(source.event.channel, lane),
        },
      };
      (source.invisible === true ? addedInvisible : addedNotes).push(copy);
    }
  }
  const order = (a: TimedPlayableNote, b: TimedPlayableNote): number =>
    a.seconds - b.seconds || a.channel.localeCompare(b.channel);
  Eif (addedNotes.length > 0) {
    notes.push(...addedNotes);
    notes.sort(order);
  }
  if (addedInvisible.length > 0) {
    invisible.push(...addedInvisible);
    invisible.sort(order);
  }
  return addedNotes.length + addedInvisible.length;
}