All files / player-engine/src lane-lr2-double.ts

90.59% Statements 106/117
85.34% Branches 99/116
100% Functions 12/12
95.4% Lines 83/87

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                                        29x 11998x   156142x 29x 29x 4091x 4091x 4091x 2058x 11998x 41233x 11998x   2058x   2033x 2033x 2033x 2033x   2033x 2033x 2033x 2033x 2033x 2033x 2033x       2033x 2033x 2033x 2033x 2033x         111x 111x 111x                 111x                 27x 27x 27x 27x 27x 27x 27x 111x 111x 111x 111x 5x   19982x 156116x   27x 27x 27x 27x 27x 16133x 111x 111x 111x     111x 16133x 40x 40x 1x         40x   111x 64x 136x 136x   64x 64x 69x 136x 49x 1x   48x 58x 58x 58x 10x   48x 48x   63x 63x 63x     26x    
import type { SRandomNote } from './lane-random.ts';
import { drawLaneRandomIndex } from './lane-random-source.ts';
 
export interface LR2DoubleRandomOptions {
  scratch: string;
  flipped?: boolean;
  includeScratch?: boolean;
  avoidFarKeys?: boolean;
  /** Non-lane objects present in the reference's sort input. */
  objects?: readonly LR2SortObject[];
}
 
export interface LR2SortObject {
  timeMs: number;
  order?: number;
  op: number;
}
 
/** LR2 beta3's CRT qsort at 0x717f80. Equal elements can move even in the short sort. */
export function sortLR2Objects<T>(items: T[], compare: (a: T, b: T) => number): void {
  const swap = (a: number, b: number) => {
    [items[a], items[b]] = [items[b]!, items[a]!];
  };
  const cmp = (a: number, b: number) => compare(items[a]!, items[b]!);
  const ranges: Array<[number, number]> = [[0, items.length - 1]];
  while (ranges.length) {
    const [start, end] = ranges.pop()!;
    const size = end - start + 1;
    if (size <= 8) {
      for (let last = end; last > start; last--) {
        let max = start;
        for (let i = start + 1; i <= last; i++) if (cmp(i, max) > 0) max = i;
        swap(max, last);
      }
      continue;
    }
    let pivot = start + Math.floor(size / 2);
    Iif (cmp(start, pivot) > 0) swap(start, pivot);
    Iif (cmp(start, end) > 0) swap(start, end);
    Iif (cmp(pivot, end) > 0) swap(pivot, end);
 
    let left = start;
    let right = end;
    for (;;) {
      Eif (left < pivot) while (++left < pivot && cmp(left, pivot) <= 0) {}
      Eif (left >= pivot) while (++left <= end && cmp(left, pivot) <= 0) {}
      while (--right > pivot && cmp(right, pivot) > 0) {}
      Eif (left > right) break;
      swap(left, right);
      if (right === pivot) pivot = left;
    }
    right++;
    while (--right > pivot && cmp(right, pivot) === 0) {}
    Eif (right <= pivot) while (--right > start && cmp(right, pivot) === 0) {}
    if (start < right) ranges.push([start, right]);
    Eif (left < end) ranges.push([left, end]);
  }
}
 
function laneOp(channel: string, flipped: boolean): number {
  const side = (channel[0] === '2') !== flipped ? 20 : 10;
  const lane = '61234589'.indexOf(channel[1] ?? '');
  return side + lane;
}
 
/** Placement runs over the entire sorted object stream, even when only one side is being modified. */
export function randomizeLR2DoubleNotes(
  notes: readonly SRandomNote[],
  lanes: readonly string[],
  options: LR2DoubleRandomOptions & { random: () => number; target?: string; scatter?: boolean },
): string[] {
  const channels = notes.map(({ channel }) => channel);
  const {
    scratch,
    target,
    random,
    flipped = false,
    includeScratch = false,
    avoidFarKeys = true,
    scatter = false,
  } = options;
  const right = scratch === '26';
  const destinations = includeScratch ? [scratch, ...lanes] : lanes;
  const domain = new Set(destinations);
  const far = right ? lanes.slice(0, 4) : lanes.slice(3);
  const objects: Array<LR2SortObject & { index?: number }> = [...(options.objects ?? [])];
  notes.forEach((note, index) => {
    const op = laneOp(note.sourceChannel ?? note.channel, flipped);
    const offset = note.kind === 'invisible' ? 20 : note.kind === 'mine' ? 120 : (note.lr2OpOffset ?? 0);
    objects.push({ timeMs: note.timeMs, order: note.beat, op: op + offset, index });
    if (note.endTimeMs !== undefined && note.lr2SyntheticTail !== true)
      objects.push({ timeMs: note.endTimeMs, order: note.endBeat, op: op + (note.lr2OpOffset ?? 0) });
  });
  objects.sort((a, b) => (a.order ?? a.timeMs) - (b.order ?? b.timeMs) || a.op - b.op);
  sortLR2Objects(objects, (a, b) => Math.trunc(a.timeMs - b.timeMs));
 
  const marked = new Set<string>();
  const rowDestinations = new Set<string>();
  const occupied = new Map<string, { start: number; end: number }>();
  let lastReset = Number.NEGATIVE_INFINITY;
  for (const { index, timeMs } of objects) {
    if (index === undefined) continue;
    const note = notes[index]!;
    const { channel } = note;
    Iif (note.kind === 'invisible') continue;
 
    // The source resets a side's marks before DP FLIP and marks the destination side after it.
    const originalSide = (note.sourceChannel ?? channel)[0];
    if ((originalSide === scratch[0]) !== flipped && lastReset < timeMs) {
      marked.clear();
      if (scatter) {
        for (const lane of rowDestinations) {
          marked.add(lane);
          if (occupied.get(lane)!.end < timeMs) rowDestinations.delete(lane);
        }
      }
      lastReset = timeMs;
    }
    if (channel !== scratch && !domain.has(channel)) continue;
    const canPlace = (lane: string): boolean => {
      const prior = occupied.get(lane);
      return prior === undefined || (prior.start !== timeMs && prior.end < timeMs);
    };
    let destination = channel;
    if (domain.has(channel)) {
      const allMarked = destinations.every((lane) => marked.has(lane));
      const accepted = (lane: string) => canPlace(lane) && (allMarked || !marked.has(lane));
      if (!(target !== undefined && accepted(target)) && !destinations.some(accepted))
        throw new RangeError('LR2 lane randomization has no acceptable destination.');
      // The reference draws before overriding the first candidate with the CONVERGE target.
      for (let attempt = 0; ; attempt++) {
        const draw = destinations[drawLaneRandomIndex(destinations.length, random)]!;
        destination = attempt === 0 && target !== undefined ? target : draw;
        if (accepted(destination)) break;
        Iif (attempt === 1023) throw new RangeError('LR2 lane randomization exceeded its retry limit.');
      }
      marked.add(destination);
      channels[index] = destination;
    }
    if (scatter) rowDestinations.add(destination);
    if (avoidFarKeys && destination === scratch) for (const lane of far) marked.add(lane);
    occupied.set(destination, { start: timeMs, end: note.endTimeMs ?? timeMs });
  }
 
  return channels;
}