All files / player-engine/src/course maker.ts

98.55% Statements 68/69
91.93% Branches 57/62
100% Functions 21/21
98.14% Lines 53/54

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                      243x     243x   243x                                                       88x               13x               44x                     69x 68x 68x 67x 67x 65x         3x                           79x 790x 790x   79x 192x                               176x 74x 74x       176x                     74x 74x 74x                       68x 66x 660x 68x 68x                 5x 5x                         10x 9x 8x 8x 30x         8x   8x 10x       16x                                 11x 11x 11x   17x   13x   4x 14x 3x   13x       16x                 11x 11x    
import {
  type CourseConstraint,
  type CourseDefinition,
  type CourseKind,
  createCourseStageRef,
  type NonstopConnection,
  normalizeCourseConstraints,
} from './definition.ts';
import { LR2_NONSTOP_CONNECTIONS, parseLR2NonstopConnections } from './lr2crs.ts';
 
/** LR2's course maker takes at most five charts (OpenLR2 `LR2f.cpp` L12221-L12229: `count <= 4` before adding). */
export const LR2_COURSE_MAKER_MAX_STAGES = 5;
 
/** The connections LR2's select-screen buttons 240-248 edit: the one after each of stages 1-9. */
const LR2_CONNECTION_SLOTS = 9;
 
const LR2_COURSE_TYPES: Readonly<Record<CourseKind, number>> = { expert: 0, nonstop: 1, grade: 2 };
 
/** One chart picked into a course being made. */
export interface CourseDraftStage {
  /** The chart's MD5 (lowercase hex): LR2 keys a course's stages by it. */
  md5: string;
  /** The chart's key mode: every stage must match the first one's. */
  keyMode: number;
  title?: string;
  /** The chart's subtitle, which LR2's texts 160-164 show while the course is being made. */
  subtitle?: string;
  artist?: string;
}
 
/** A course being made on the select screen (LR2's `isMakingCourse` state). */
export interface CourseDraft {
  kind: CourseKind;
  name: string;
  stages: CourseDraftStage[];
  /** beatoraja's course constraints; absent, the course gets {@link defaultCourseMakerConstraints}. */
  constraints?: CourseConstraint[];
}
 
/**
 * The constraints a made course starts with: a GRADE course reads as an LR2 grade (no lane option, the LR2 gauge;
 * `grade`, `gauge_lr2`, as `parseLR2CourseFile` reads one), and the other kinds have none.
 */
export function defaultCourseMakerConstraints(kind: CourseKind): CourseConstraint[] {
  return kind === 'grade' ? ['grade', 'gauge_lr2'] : [];
}
 
/** A course with its constraints replaced (normalized: known names only, one per group). */
export function withCourseConstraints(
  course: CourseDefinition,
  constraints: readonly CourseConstraint[],
): CourseDefinition {
  return { ...course, constraints: normalizeCourseConstraints(constraints) };
}
 
/** Why a chart cannot join a course being made. */
export type CourseDraftAppendFailure = 'full' | 'key-mode' | 'no-md5';
 
/** An empty course of `kind`, named `name` (LR2 starts with a "type the course title" prompt, a host concern). */
export function createCourseDraft(kind: CourseKind, name = ''): CourseDraft {
  return { kind, name, stages: [] };
}
 
/**
 * Adds a chart to the end of a course being made, as LR2's decide on a chart bar does (OpenLR2 L12221-L12229): at most
 * {@link LR2_COURSE_MAKER_MAX_STAGES} charts, all in the first chart's key mode. The same chart may appear twice.
 */
export function appendCourseDraftStage(
  draft: CourseDraft,
  stage: CourseDraftStage,
): { ok: true; draft: CourseDraft } | { ok: false; reason: CourseDraftAppendFailure } {
  if (draft.stages.length >= LR2_COURSE_MAKER_MAX_STAGES) return { ok: false, reason: 'full' };
  const md5 = stage.md5.toLowerCase();
  if (!/^[0-9a-f]{32}$/u.test(md5)) return { ok: false, reason: 'no-md5' };
  const first = draft.stages[0];
  if (first !== undefined && first.keyMode !== stage.keyMode) return { ok: false, reason: 'key-mode' };
  return { ok: true, draft: { ...draft, stages: [...draft.stages, { ...stage, md5 }] } };
}
 
/** Drops the last chart of a course being made (LR2's right click, OpenLR2 L12265-L12269). */
export function removeLastCourseDraftStage(draft: CourseDraft): CourseDraft {
  return { ...draft, stages: draft.stages.slice(0, -1) };
}
 
/**
 * An LR2 course hash: a 32-character header, then each stage's MD5 (OpenLR2 `WriteCourse` L17580-L17621). The header
 * holds the connection after each of stages 1-10 (chars 0-9, `0`-`5`; `0` for a course that is not NONSTOP), the
 * course type (char 10: 0 EXPERT, 1 NONSTOP, 2 GRADE) and zeros. LR2 puts the first four characters of the player's
 * password MD5 at chars 28-31; a browser has no password, so they stay `0`.
 */
export function buildLR2CourseHash(course: {
  kind: CourseKind;
  stageMD5s: readonly string[];
  connections?: readonly NonstopConnection[];
}): string {
  const keys = Array.from({ length: 10 }, (_, index) => {
    const connection = course.kind === 'nonstop' ? course.connections?.[index] : undefined;
    return String(Math.max(0, connection === undefined ? 0 : LR2_NONSTOP_CONNECTIONS.indexOf(connection)));
  }).join('');
  const header = `${keys}${LR2_COURSE_TYPES[course.kind]}${'0'.repeat(21)}`;
  return `${header}${course.stageMD5s.map((md5) => md5.toLowerCase()).join('')}`;
}
 
/**
 * The course definition of a set of stages, in the shape `parseLR2CourseFile` reads the same course back in, except
 * that a made course starts unranked (`release: false`): LR2 inserts it with `ir = 0` (OpenLR2 `WriteCourse`
 * L17588-L17603) and beatoraja's course editor starts a new course with `release = false`, so neither sends a made
 * course to IR until the player opts in.
 */
function lr2CourseDefinition(
  name: string,
  kind: CourseKind,
  stages: readonly { md5: string; title?: string; artist?: string }[],
  keyMode: number | undefined,
  connectionKeys: readonly NonstopConnection[],
): CourseDefinition {
  const hash = buildLR2CourseHash({ kind, stageMD5s: stages.map((stage) => stage.md5), connections: connectionKeys });
  const header = hash.slice(0, 32);
  const course: CourseDefinition = {
    name,
    kind,
    stages: stages.map((stage) =>
      createCourseStageRef({
        md5: stage.md5,
        ...(stage.title !== undefined ? { title: stage.title } : {}),
        ...(stage.artist !== undefined ? { artist: stage.artist } : {}),
      })!,
    ),
    constraints: defaultCourseMakerConstraints(kind),
    trophies: [],
    release: false,
    source: { format: 'lr2crs', type: LR2_COURSE_TYPES[kind], header, hash },
  };
  Eif (keyMode !== undefined) course.keyMode = keyMode;
  if (kind === 'nonstop') course.connections = parseLR2NonstopConnections(header).slice(0, stages.length - 1);
  return course;
}
 
/**
 * Turns a course being made into a course, as LR2's finish (button 230) saves it: `undefined` for a course with no
 * chart. The course starts unranked (`release: false`), as LR2's and beatoraja's made courses do. A NONSTOP course gets `defaultConnection` (LR2's `config.course.defaultconnection`, button 268) after each of
 * stages 1-5; the per-stage connections are edited afterwards ({@link withNonstopConnection}).
 */
export function finishCourseDraft(
  draft: CourseDraft,
  options: { defaultConnection?: NonstopConnection } = {},
): CourseDefinition | undefined {
  if (draft.stages.length === 0) return undefined;
  const connection = options.defaultConnection ?? 'fade';
  const keys = Array.from({ length: 10 }, (_, index) => (index < LR2_COURSE_MAKER_MAX_STAGES ? connection : 'fade'));
  const course = lr2CourseDefinition(draft.name, draft.kind, draft.stages, draft.stages[0]?.keyMode, keys);
  return draft.constraints !== undefined ? withCourseConstraints(course, draft.constraints) : course;
}
 
/**
 * The connection `delta` steps from `connection` in LR2's order (FADE, FADE+FIT, CUT, CUT+FIT, BLANK1, BLANK2),
 * wrapping around: LR2's buttons 240-248 and 268 step +1 on their right half and -1 on their left half.
 */
export function stepLR2NonstopConnection(connection: NonstopConnection, delta: number): NonstopConnection {
  const count = LR2_NONSTOP_CONNECTIONS.length;
  const index = LR2_NONSTOP_CONNECTIONS.indexOf(connection);
  return LR2_NONSTOP_CONNECTIONS[(((index + delta) % count) + count) % count]!;
}
 
/**
 * A made NONSTOP course with the connection after stage `index + 1` changed (LR2's buttons 240-248, OpenLR2
 * L11119-L11137). LR2 keeps a connection for each of stages 1-9 whatever the course's length, so `index` may pass the
 * last stage. Returns the course unchanged when it is not NONSTOP, is not an LR2 course, or `index` is outside 0-8.
 */
export function withNonstopConnection(
  course: CourseDefinition,
  index: number,
  connection: NonstopConnection,
): CourseDefinition {
  if (course.kind !== 'nonstop' || course.source.format !== 'lr2crs') return course;
  if (!Number.isInteger(index) || index < 0 || index >= LR2_CONNECTION_SLOTS) return course;
  const keys = parseLR2NonstopConnections(course.source.header);
  keys[index] = connection;
  const stages = course.stages.map((stage) => ({
    md5: stage.md5 ?? '',
    ...(stage.title !== undefined ? { title: stage.title } : {}),
    ...(stage.artist !== undefined ? { artist: stage.artist } : {}),
  }));
  const rebuilt = lr2CourseDefinition(course.name, course.kind, stages, course.keyMode, keys);
  // The hash holds the connections after stages 1-10; a longer course keeps its own past them.
  const connections = [...rebuilt.connections!, ...(course.connections ?? []).slice(rebuilt.connections!.length)];
  return { ...course, connections, source: rebuilt.source };
}
 
function escapeXML(text: string): string {
  return text.replace(/[<>&"']/gu, (char) => `&#${char.charCodeAt(0)};`);
}
 
/**
 * Writes LR2 courses as a `.lr2crs` file: a UTF-8 `<courselist>` that `parseLR2CourseFile` reads back into the same
 * courses. Courses that did not come from an LR2 hash (`source.format !== 'lr2crs'`) are rebuilt from their stage
 * MD5s, and skipped when a stage has none. The format has no room for constraints or `release`: LR2 reads a GRADE course
 * back with {@link defaultCourseMakerConstraints} and any other course with none, and every course back as released
 * (`serializeBeatorajaCourseFile` keeps both).
 *
 * `options.maxStages` writes each course's first that many stages only: a file for LR2, which plays the first five
 * (`LR2_MAX_PLAYED_STAGES`), is written with five. Without it every stage is written.
 */
export function serializeLR2CourseFile(
  courses: readonly CourseDefinition[],
  options: { maxStages?: number } = {},
): string {
  const maxStages = options.maxStages ?? Number.POSITIVE_INFINITY;
  const lines = ['<?xml version="1.0" encoding="UTF-8"?>', '<courselist>'];
  for (const course of courses) {
    let hash: string;
    if (course.source.format === 'lr2crs') {
      // The 32-character header, then one 32-character MD5 per stage.
      hash = Number.isFinite(maxStages) ? course.source.hash.slice(0, 32 * (maxStages + 1)) : course.source.hash;
    } else {
      const stages = course.stages.slice(0, maxStages);
      if (stages.some((stage) => stage.md5 === undefined)) continue;
      hash = buildLR2CourseHash({
        kind: course.kind,
        stageMD5s: stages.map((stage) => stage.md5!),
        ...(course.connections !== undefined ? { connections: course.connections } : {}),
      });
    }
    lines.push(
      '  <course>',
      `    <title>${escapeXML(course.name)}</title>`,
      `    <line>${course.keyMode ?? 7}</line>`,
      `    <type>${LR2_COURSE_TYPES[course.kind]}</type>`,
      `    <hash>${hash}</hash>`,
      '  </course>',
    );
  }
  lines.push('</courselist>', '');
  return lines.join('\n');
}