All files / player-browser/src/collection course.ts

94.96% Statements 151/159
82.85% Branches 145/175
95.83% Functions 46/48
99.2% Lines 125/126

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                                                                                        55x         73x                 58x 58x     52x                       23x 23x 2x           21x 23x 4x 4x 4x 3x 3x 6x       3x   17x 17x 23x 13x                                         41x 26x   39x   3x       2x 3x 2x 4x 4x   4x     2x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 3x               2x   2x           89x 89x   89x 18x 18x 18x 18x   89x                       43x 43x     61x                                 41x 24x 22x         23x   2x                       4x                     7x     7x           55x                                           31x   31x     31x 31x                                 31x 31x   186x   31x 6x 6x   31x 31x 31x 6x 6x   31x 31x 31x 17x     11x 11x       31x                   7x 7x 7x 7x 7x 7x   15x 15x 15x 2x 2x 1x 13x 11x   7x 7x 7x     7x   7x 7x 7x 7x                             2x 2x 1x 1x   2x 2x 2x 2x 2x                               3x 2x 6x                 2x 2x 1x         3x          
import { isHeldLongNote, resolveChart } from '@be-music/chart-model';
import type { BeMusicJSON } from '@be-music/chart-source';
import {
  createCourseChartScore,
  drawRandomCourse,
  isClassCourseConstraints,
  parseBeatorajaCommandFolderFile,
  parseBeatorajaCourseFile,
  parseCourseChartFilter,
  parseLR2CourseFile,
  parseN2XCourseFile,
  resolveCourseStages,
  type CourseChartLookup,
  type CourseDefinition,
  type CourseChartInformation,
  type CourseChartRecord,
  type RandomCourseDefinition,
  type RandomCourseDrawFailure,
} from '@be-music/player-engine/course';
import type { BestRecord } from '@be-music/player-engine/records';
import { resolveBeatorajaDefaultTotal } from '@be-music/player-engine/replay';
import { isScratchLaneForVariant } from '@be-music/player-skin-sdk';
import { dirname, normalizePath } from '@be-music/shared-utils/core';
import {
  resolveLibraryChartDifficultyValue,
  resolveLibraryChartPlayVariant,
  type LibraryChart,
  type LibraryCourse,
  type LibraryFolder,
} from '@be-music/player-scene-model';
import { computeBeatorajaChartDensityValues } from '../chart/beatoraja/density.ts';
import { resolveChartBPMRange } from '../chart/bpm-range.ts';
import { resolveShownChartMainBPM } from '../chart/main-bpm.ts';
 
/** A course file's courses, under the label its folder bar shows. */
export interface CourseDefinitionGroup {
  label: string;
  kind?: 'difficulty-table';
  courses: readonly CourseDefinition[];
  /** beatoraja random courses, listed after the fixed ones; their stages are drawn when one is started. */
  randomCourses?: readonly RandomCourseDefinition[];
}
 
function isUnderFolder(lowerPath: string, folder: string): boolean {
  return lowerPath.startsWith(`${folder}/`) || lowerPath.includes(`/${folder}/`);
}
 
/** beatoraja's command-folder file (`folder/default.json`), which holds its random courses. */
function isCommandFolderPath(lowerPath: string): boolean {
  return lowerPath.endsWith('.json') && isUnderFolder(lowerPath, 'folder') && !isUnderFolder(lowerPath, 'course');
}
 
/**
 * The course formats a host reads from dropped files: LR2's `.lr2crs`, beatoraja's `course/*.json`, beatoraja's
 * command-folder file `folder/default.json`, which holds its random courses, and Nanasi Groove 2's `.n2x` chart lists.
 * Every `.n2x` is taken, since only its contents tell a list from a skin or settings file.
 */
export function isCourseFilePath(path: string): boolean {
  const lower = path.toLowerCase().replaceAll('\\', '/');
  if (lower.endsWith('.lr2crs') || lower.endsWith('.n2x')) return true;
  // beatoraja keeps course files in a `course` folder and command folders in a `folder` folder; any other JSON (skins,
  // bmson metadata) is not a course.
  return (lower.endsWith('.json') && isUnderFolder(lower, 'course')) || isCommandFolderPath(lower);
}
 
/**
 * Reads one dropped course file into the course groups its folder bars show. `.lr2crs` is LR2's XML course list and a
 * `course/*.json` a beatoraja course file, each one group labelled with the file's name (without extension). A
 * `folder/*.json` is beatoraja's command-folder file: one group per command folder that holds random courses, under the
 * folder's name. An `.n2x` chart list is one course, named and labelled after the file, whose stages name their charts
 * by path from the drop's root ({@link bindCourseStagePaths} matches them). A file without a valid course gives no
 * group.
 */
export function readCourseFile(path: string, bytes: Uint8Array): CourseDefinitionGroup[] {
  const normalized = path.replaceAll('\\', '/');
  if (isCommandFolderPath(normalized.toLowerCase())) {
    return parseBeatorajaCommandFolderFile(bytes).map((folder) => ({
      label: folder.name,
      courses: [],
      randomCourses: folder.courses,
    }));
  }
  const name = normalized.split('/').at(-1) ?? normalized;
  if (name.toLowerCase().endsWith('.n2x')) {
    const label = name.replace(/\.n2x$/iu, '');
    const course = parseN2XCourseFile(bytes, label);
    if (course === undefined) return [];
    const folder = dirname(normalized);
    const stages = course.stages.map((stage) =>
      stage.path === undefined
        ? stage
        : { ...stage, path: normalizePath(folder === '' ? stage.path : `${folder}/${stage.path}`) },
    );
    return [{ label, courses: [{ ...course, stages }] }];
  }
  const isLR2 = name.toLowerCase().endsWith('.lr2crs');
  const courses = isLR2 ? parseLR2CourseFile(bytes) : parseBeatorajaCourseFile(bytes);
  if (courses.length === 0) return [];
  return [{ label: name.replace(/\.(lr2crs|json)$/iu, ''), courses }];
}
 
/** A chart of the library with its file hashes, as {@link createChartHashLookup} and {@link bindCourseStagePaths} take. */
export interface HashedLibraryChart {
  chart: LibraryChart;
  sha256?: string;
  md5?: string;
}
 
/**
 * The course groups with each stage named by path (an `.n2x` list's) bound to the chart at that path: the stage takes
 * the chart's hashes and title, so it resolves, keys records and replays like any other stage. A path matches a chart's
 * path ignoring case; failing that, the first chart (in library order) whose path ends with it, or that it ends with, at
 * a folder boundary, as a list read from inside an archive sees the charts from another root. A stage with no such chart,
 * or whose chart has no hash, keeps its path and stays missing. Courses without path stages are returned as they are.
 */
export function bindCourseStagePaths(
  groups: readonly CourseDefinitionGroup[],
  chartEntries: Iterable<HashedLibraryChart>,
): CourseDefinitionGroup[] {
  if (
    !groups.some((group) => group.courses.some((course) => course.stages.some((stage) => stage.path !== undefined)))
  ) {
    return [...groups];
  }
  const entries = [...chartEntries].map((entry) => ({
    entry,
    path: normalizePath(entry.chart.chartPath).toLowerCase(),
  }));
  const byPath = new Map<string, HashedLibraryChart>();
  for (const { entry, path } of entries) Eif (!byPath.has(path)) byPath.set(path, entry);
  const find = (stagePath: string): HashedLibraryChart | undefined => {
    const path = stagePath.toLowerCase();
    return (
      byPath.get(path) ??
      entries.find((candidate) => candidate.path.endsWith(`/${path}`) || path.endsWith(`/${candidate.path}`))?.entry
    );
  };
  return groups.map((group) => {
    let changed = false;
    const courses = group.courses.map((course) => {
      Iif (!course.stages.some((stage) => stage.path !== undefined)) return course;
      changed = true;
      const stages = course.stages.map((stage) => {
        Iif (stage.path === undefined || stage.md5 !== undefined || stage.sha256 !== undefined) return stage;
        const found = find(stage.path);
        const md5 = found?.md5?.toLowerCase();
        const sha256 = found?.sha256?.toLowerCase();
        if (found === undefined || (md5 === undefined && sha256 === undefined)) return stage;
        return {
          ...(md5 !== undefined ? { md5 } : {}),
          ...(sha256 !== undefined ? { sha256 } : {}),
          title: found.chart.title,
          ...(found.chart.artist !== undefined && found.chart.artist !== '' ? { artist: found.chart.artist } : {}),
          path: stage.path,
        };
      });
      return { ...course, stages };
    });
    return changed ? { ...group, courses } : group;
  });
}
 
/** A song lookup by chart-file hash, for {@link resolveCourseFolders}. */
export function createChartHashLookup(chartEntries: Iterable<HashedLibraryChart>): CourseChartLookup<LibraryChart> {
  const bySHA256 = new Map<string, LibraryChart>();
  const byMD5 = new Map<string, LibraryChart>();
  // The first song with a hash wins, so a chart dropped twice resolves to the copy loaded first.
  for (const { chart: chartEntry, sha256, md5 } of chartEntries) {
    const sha = sha256?.toLowerCase();
    const md = md5?.toLowerCase();
    if (sha !== undefined && !bySHA256.has(sha)) bySHA256.set(sha, chartEntry);
    if (md !== undefined && !byMD5.has(md)) byMD5.set(md, chartEntry);
  }
  return { bySHA256: (hash) => bySHA256.get(hash), byMD5: (hash) => byMD5.get(hash) };
}
 
/**
 * A course with its stages matched to local charts: a stage not in the collection keeps the course file's title for it
 * (or a placeholder) and makes the course unplayable.
 */
export function resolveCourseEntry(
  id: string,
  definition: CourseDefinition,
  lookup: CourseChartLookup<LibraryChart>,
): LibraryCourse {
  const resolved = resolveCourseStages(definition, lookup);
  return {
    id,
    definition,
    stages: resolved.stages.map((stage) => ({
      title: stage.chart?.title ?? stage.ref.title ?? 'NOT FOUND',
      ...(stage.chart !== undefined ? { chart: stage.chart } : {}),
    })),
    playable: resolved.playable,
  };
}
 
/**
 * One folder bar per course group, each listing its courses with their stages matched to local charts. A stage not
 * in the collection keeps the course file's title for it (or a placeholder), and makes its course unplayable. Groups
 * with no course are dropped.
 */
export function resolveCourseFolders(
  groups: readonly CourseDefinitionGroup[],
  lookup: CourseChartLookup<LibraryChart>,
): LibraryFolder[] {
  return groups
    .filter((group) => group.courses.length + (group.randomCourses?.length ?? 0) > 0)
    .map((group): LibraryFolder => ({
      label: group.label,
      ...(group.kind === undefined ? {} : { kind: group.kind }),
      charts: [],
      courses: [
        ...group.courses.map((definition, index) => resolveCourseEntry(`${group.label}#${index}`, definition, lookup)),
        ...(group.randomCourses ?? []).map((random, index) =>
          createRandomCourseEntry(`${group.label}#r${index}`, random),
        ),
      ],
    }));
}
 
/**
 * The course bar of a beatoraja random course: the course's name, kind and constraints with no stage drawn yet, and
 * each stage shown by its title, else its filter, else `RANDOM`. It is playable when every stage filter can be
 * evaluated; whether each stage finds a chart is only known when it is drawn ({@link drawBrowserRandomCourse}).
 */
export function createRandomCourseEntry(id: string, random: RandomCourseDefinition): LibraryCourse {
  return {
    id,
    definition: {
      name: random.name,
      kind: isClassCourseConstraints(random.constraints) ? 'grade' : 'expert',
      stages: [],
      constraints: random.constraints,
      trophies: random.trophies,
      release: false,
      source: { format: 'beatoraja-random' },
    },
    stages: random.stages.map((stage) => ({ title: stage.title ?? stage.filter ?? 'RANDOM' })),
    playable:
      random.stages.length > 0 &&
      random.stages.every((stage) => stage.filter === undefined || parseCourseChartFilter(stage.filter).ok),
    random,
  };
}
 
/** beatoraja's `Mode.id` for each play variant (24 keys is 25, 24 keys double 50). */
const MODE_IDS = { '5': 5, '7': 7, '9': 9, '10': 10, '14': 14, '24': 25, '48': 50 } as const;
 
type ResolvedChart = ReturnType<typeof resolveChart>;
 
/**
 * A song as a random-course filter sees it (`CourseChartRecord`), with the song itself under `song`. Text columns,
 * `level`, `difficulty`, `notes` and `judge` are read up front; `mode`, `minbpm` / `maxbpm`, `length`, `feature` and
 * the `information` row need the chart resolved and are worked out on first read, so a filter that never names them
 * costs nothing.
 *
 * `feature` carries the long-note bits (LN / CN / HCN by the chart's long-note mode, `UNDEFINEDLN` when the chart names
 * none), mines, `#RANDOM`, STOP and scroll changes. `content` is not filled, so it reads as 0.
 *
 * `bestRecord` gives the player's best record on the chart for the `score` row ({@link createCourseChartScore}); it is
 * asked on every read, so the row follows the records. Without one, or while it answers `undefined`, the chart reads as
 * never played (every `score` column NULL).
 */
export function createCourseChartRecord(
  chartEntry: LibraryChart,
  hashes: { md5?: string; sha256?: string } = {},
  bestRecord?: () => BestRecord | undefined,
): CourseChartRecord & { readonly chart: LibraryChart } {
  const { chart } = chartEntry;
  const level =
    typeof chartEntry.playLevel === 'number'
      ? chartEntry.playLevel
      : Number.parseInt(String(chartEntry.playLevel ?? ''), 10);
  const subartist = chart.metadata.extras.SUBARTIST ?? chart.bmson.info.subartists?.join(' ');
  const record: CourseChartRecord & { chart: LibraryChart } = {
    chart: chartEntry,
    title: chartEntry.title,
    path: chartEntry.chartPath,
    level: Number.isFinite(level) ? Math.trunc(level) : 0,
    // The chart's own `#DIFFICULTY`, else the one estimated from its names, as beatoraja's song database fills it.
    difficulty: resolveLibraryChartDifficultyValue(chartEntry) ?? 0,
    notes: chartEntry.totalNotes,
    judge: Math.trunc(chart.metadata.rank ?? 0) || 0,
    ...(hashes.md5 !== undefined ? { md5: hashes.md5.toLowerCase() } : {}),
    ...(hashes.sha256 !== undefined ? { sha256: hashes.sha256.toLowerCase() } : {}),
    ...(chartEntry.subtitle !== undefined ? { subtitle: chartEntry.subtitle } : {}),
    ...(chartEntry.artist !== undefined ? { artist: chartEntry.artist } : {}),
    ...(subartist !== undefined ? { subartist } : {}),
    ...(chartEntry.genre !== undefined ? { genre: chartEntry.genre } : {}),
  };
  let resolved: ResolvedChart | undefined;
  const resolve = (): ResolvedChart => (resolved ??= resolveChart(chart));
  const lazy = <K extends keyof CourseChartRecord>(key: K, read: () => NonNullable<CourseChartRecord[K]>): void => {
    let value: CourseChartRecord[K] | undefined;
    Object.defineProperty(record, key, { enumerable: true, get: () => (value ??= read()) });
  };
  lazy('mode', () => {
    const variant = resolveLibraryChartPlayVariant(chartEntry);
    return variant.startsWith('generic-') ? 0 : MODE_IDS[variant as keyof typeof MODE_IDS];
  });
  lazy('minbpm', () => Math.trunc(resolveChartBPMRange(chart).min));
  lazy('maxbpm', () => Math.trunc(resolveChartBPMRange(chart).max));
  lazy('length', () => {
    const last = resolve().sortedEvents.at(-1);
    return last === undefined ? 0 : Math.trunc(resolve().timing.eventToSeconds(last) * 1000);
  });
  lazy('feature', () => songFeatureBits(chart, resolve()));
  lazy('information', () => songInformation(chartEntry, resolve()));
  if (bestRecord !== undefined) {
    Object.defineProperty(record, 'score', {
      enumerable: true,
      get: () => {
        const best = bestRecord();
        return best === undefined ? undefined : createCourseChartScore(best, chartEntry.totalNotes);
      },
    });
  }
  return record;
}
 
/**
 * beatoraja's song information for a chart (`SongInformation(BMSModel)`): the notes by kind (a CN / HCN long note
 * counts its end too, as `BMSModelUtils.getTotalNotes` does), the TOTAL as beatoraja plays it (`BMSPlayerRule.validate`:
 * `#TOTAL`, a bmson `total` as a percentage of the default, else the default for the note count), the densities
 * ({@link computeBeatorajaChartDensityValues}) and the main BPM ({@link resolveShownChartMainBPM}).
 */
function songInformation(chartEntry: LibraryChart, resolved: ResolvedChart): CourseChartInformation {
  const variant = resolveLibraryChartPlayVariant(chartEntry);
  let n = 0;
  let ln = 0;
  let s = 0;
  let ls = 0;
  for (const note of resolved.notes) {
    // beatoraja drops FREE ZONE (`17` / `27`): judged by nobody, it is no note at all.
    Iif (note.freeZone === true) continue;
    const scratch = isScratchLaneForVariant(note.channel, variant);
    if (note.kind === 'ln') {
      const count = (note.lnMode ?? resolved.lnMode) === 1 ? 1 : 2;
      if (scratch) ls += count;
      else ln += count;
    } else if (scratch) s += 1;
    else n += 1;
  }
  const notes = n + ln + s + ls;
  const keyboard = variant === '24' || variant === '48';
  const fallback = keyboard
    ? Math.max(300, (7.605 * (notes + 100)) / (0.01 * notes + 6.5))
    : resolveBeatorajaDefaultTotal(notes);
  const raw = resolved.total.value;
  const total =
    raw === undefined || !(raw > 0) ? fallback : resolved.total.unit === 'percent' ? (raw / 100) * fallback : raw;
  const density = computeBeatorajaChartDensityValues(resolved);
  const mainbpm = resolveShownChartMainBPM(chartEntry.chart, chartEntry.chartPath);
  return {
    n,
    ln,
    s,
    ls,
    total,
    density: density.average,
    peakdensity: density.peak,
    enddensity: density.end,
    ...(mainbpm !== undefined ? { mainbpm } : {}),
  };
}
 
/** beatoraja's `SongData.FEATURE_*` bits that the resolved chart shows. */
function songFeatureBits(chart: BeMusicJSON, resolved: ResolvedChart): number {
  let feature = 0;
  if (resolved.notes.some(isHeldLongNote)) {
    const named = chart.sourceFormat === 'bms' ? chart.bms.lnMode : chart.bmson.info.lnType || undefined;
    feature |= named === 2 ? 16 : named === 3 ? 32 : named === 1 ? 8 : 1;
  }
  if (resolved.mines.length > 0) feature |= 2;
  Iif (resolved.hasUnresolvedControlFlow) feature |= 4;
  Iif (resolved.timing.stopPoints.length > 0) feature |= 64;
  Iif (resolved.scroll.some((point) => point.speed !== 1)) feature |= 128;
  return feature;
}
 
/**
 * Draws a random course's stages from the collection (`drawRandomCourse`) and returns the course bar to play: a fixed
 * course whose stages are the drawn songs. `candidates` are the collection's songs with their chart-file hashes, as
 * {@link createChartHashLookup} takes them; a song without a hash is never drawn. `random` returns values in `[0, 1)`.
 * `bestRecordOf` gives each song's best record, for the filters' `score` columns. A course without `random` is
 * returned as it is.
 */
export function drawBrowserRandomCourse(
  entry: LibraryCourse,
  candidates: Iterable<{ chart: LibraryChart; sha256?: string; md5?: string }>,
  random: () => number,
  bestRecordOf?: (chart: LibraryChart) => BestRecord | undefined,
): { ok: true; course: LibraryCourse } | RandomCourseDrawFailure {
  if (entry.random === undefined) return { ok: true, course: entry };
  const records = Array.from(candidates, ({ chart: chartEntry, md5, sha256 }) =>
    createCourseChartRecord(
      chartEntry,
      {
        ...(md5 !== undefined ? { md5 } : {}),
        ...(sha256 !== undefined ? { sha256 } : {}),
      },
      bestRecordOf === undefined ? undefined : () => bestRecordOf(chartEntry),
    ),
  );
  const drawn = drawRandomCourse(entry.random, records, random);
  if (!drawn.ok) return drawn;
  return {
    ok: true,
    course: {
      id: entry.id,
      definition: drawn.course,
      stages: drawn.charts.map(({ chart: chartEntry }) => ({ title: chartEntry.title, chart: chartEntry })),
      playable: true,
    },
  };
}