On this page

← All documentation

Transforming a chart

Write a modifier that rewrites the notes of a chart at the start of a play, with typed arrays, and see exactly what Rust accepts, refuses and records in the replay.

A modifier of kind chartTransform changes which notes the player plays: it can shuffle the columns, turn holds into taps, thin out chords, add notes. At the start of a play the game hands your script a copy of the notes, and your script hands back a complete replacement. Rust checks that replacement before anything is played: a replacement that is not a valid chart is dropped, and the map plays as it was.

Your script never sees the play in progress, never touches the inputs or the judgement, and never writes code into the replay. It exchanges a buffer of data, and only that.

A complete example

Thin chords keeps at most two notes of every chord. It reads the notes, picks the ones to keep and builds four new arrays. Rust loads this exact file in a test, runs it on a chart with chords, and checks the notes that come out.

/// <reference path="../../../mods/sdk/modding.d.ts" />

// Thin chords: a chart transformation that keeps at most two notes of every chord (the notes that start at the same instant): the first two
// in the order the game lists them. The game delivers `chart.transform` to the mod when a play starts; the mod reads the notes of the chart as four
// typed arrays and hands back a full replacement. Rust validates the replacement: a refused one is dropped and the map plays as it
// was. Removing notes can never overlap anything, so this one is always accepted. The play it changes is unranked and its replay
// stores the resulting notes, never this script.
const MAX_PER_CHORD = 2;

export default defineMod({
  id: "example.thin-chords",
  name: "Thin chords",
  version: "1.0.0",
  apiVersion: 2,
  author: "PVNG",
  description: "A Mods tab switch that keeps at most two notes of every chord.",
  setup() {
    gameplay.register({
      id: "thin-chords",
      name: "Thin chords",
      description: "Chords of three notes or more keep only their first two notes.",
      kind: "chartTransform",
      group: "difficulty",
      icon: "minus",
    });

    ctx.on("chart.transform", (request) => {
      // One handler receives every modifier of the mod: answer only yours.
      if (request.id !== "thin-chords") return;
      const notes = chart.getNotes();

      // The times are little-endian doubles. A view must start on a multiple of 8 bytes: take `byteOffset` into account.
      const start = new Float64Array(notes.startUs.buffer, notes.startUs.byteOffset, notes.count);
      const end = new Float64Array(notes.endUs.buffer, notes.endUs.byteOffset, notes.count);

      // The notes come sorted by start time: a chord is a run of equal start times.
      const kept: number[] = [];
      let rank = 0;
      for (let index = 0; index < notes.count; index++) {
        rank = index > 0 && start[index] === start[index - 1] ? rank + 1 : 0;
        if (rank < MAX_PER_CHORD) kept.push(index);
      }

      // Four new arrays, one entry per kept note. A tap or a mine keeps `endUs` at 0.
      const startUs = new Float64Array(kept.length);
      const endUs = new Float64Array(kept.length);
      const column = new Uint8Array(kept.length);
      const kind = new Uint8Array(kept.length);
      kept.forEach((from, to) => {
        startUs[to] = start[from];
        endUs[to] = end[from];
        column[to] = notes.column[from];
        kind[to] = notes.kind[from];
      });
      chart.setNotes({ startUs: new Uint8Array(startUs.buffer), endUs: new Uint8Array(endUs.buffer), column, kind });
    });
  },
});

Three things to see in it:

  • The mod registers a modifier with gameplay.register({ kind: "chartTransform", … }) and listens to chart.transform with ctx.on. The event carries { id }, the id of the modifier the player switched on: a mod with several modifiers has one handler and tests request.id.
  • chart.getNotes() and chart.setNotes() only work inside that handler.
  • The times are Float64Array data read from and written to bytes.

How a play goes

  1. The player switches on one or more modifiers on the Mods tab and starts a play.
  2. The game builds the chart of the play and, before the play starts, asks the mods thread to run the selected chartTransform modifiers. It waits for the answer the way it waits for a skin's setup.
  3. The modifiers run in load order (the loadOrder of each mod), not in the order the player picked them. The first gets the original chart's notes; each next one gets the notes the previous one left.
  4. For each one, the game offers the notes, delivers chart.transform to the mod, and validates what chart.setNotes received.
  5. The result applies to the chart at 1x, before the playback rate. Times stay in microseconds of the 1x chart. The native modifiers (Mirror, No long notes, Full long notes…) apply after the rate.

If the final notes are the same as the original's, nothing is recorded and the play stays ranked. If they differ, the play is unranked and carries the notes (see Replays).

Reading the notes: chart.getNotes

chart.getNotes() returns:

Field Type Meaning
keys number Number of columns. Every note's column is below it.
count number Number of notes in each array.
seed number An integer the game draws for this play and this mod (see Determinism).
durationUs number Where the map ends, in microseconds. No note may end later.
startUs Uint8Array count little-endian f64: the start time of each note, in microseconds.
endUs Uint8Array count little-endian f64: the end time of a hold or a burst, 0 for a tap or a mine.
column Uint8Array count bytes: the 0-based column of each note.
kind Uint8Array count bytes: 0 tap, 1 hold, 2 burst, 3 mine.

The notes come sorted by start time. They are a copy: changing the arrays changes nothing until you call chart.setNotes.

The two time arrays are bytes, not numbers. To read them, build a Float64Array view over the same memory, and use byteOffset because the view must start on a multiple of 8 bytes:

const notes = chart.getNotes();
const start = new Float64Array(notes.startUs.buffer, notes.startUs.byteOffset, notes.count);
const firstNote = notes.count > 0 ? start[0] : null;

To change times, work on a copy (Float64Array.from(view), or new arrays as the Thin chords example above does).

Writing the notes: chart.setNotes

chart.setNotes({ startUs, endUs, column, kind }) takes the same four arrays as Uint8Array, with a count of your choice:

  • The number of notes can change, up to 100 000 (a real marathon map has about 50 000).
  • The notes can come in any order: the game sorts them by start time (a stable sort).
  • Times are rounded to whole microseconds. Hitsound indices are dropped (the game plays none).
  • You can call chart.setNotes several times in one handler: the last valid call wins, but see below what a refused call does.
  • If your handler never calls it, nothing changes.

startUs and endUs are bytes of doubles. Build a Float64Array and pass new Uint8Array(array.buffer). Passing the Float64Array itself is a type error:

ctx.on("chart.transform", () => {
  const notes = chart.getNotes();
  const start = new Float64Array(notes.count);
  chart.setNotes({ startUs: start, endUs: notes.endUs, column: notes.column, kind: notes.kind });
});

What Rust validates

The buffer is accepted only if every note is valid and the chart stays one the game's own loader would accept. Any of these refuses it, with a reason:

Rule Message (the part you will read)
at most 100 000 notes N notes exceed the limit of 100000
startUs and endUs hold 8 bytes per note, column and kind one, counted against kind.length `column` holds 3 bytes, 4 expected for 4 notes
times are finite and exact (at most 2^53) note 3: start NaN is not a finite time
kind is 0, 1, 2 or 3 note 0: kind 9 is not 0 (tap), 1 (hold), 2 (burst) or 3 (mine)
a tap or a mine ends at 0 note 0: a tap or a mine has no end time, `endUs` must be 0 (got 5)
a hold or a burst ends after it starts note 1: the end 400000 comes before the start 500000 and note 1: a hold or a burst must end after it starts (500000 us)
the column is below keys note 2: column 4 is outside the 4 columns
the note stays inside the map: from min(0, first original note) to durationUs note 3: 6000000..6000000 us is outside the map (0..5000000 us)
no two notes start at the same instant in a column note 3: two notes at 1000000 us in column 2
no note starts before the previous note of its column ends note 2: starts at 600000 us in column 1 before the note before it ends (900000 us)

What happens to a refused buffer

A refused call throws in your script with the reason, prefixed by chart.setNotes refused the buffer:. The game remembers the first refusal: even if your script catches the exception and submits another buffer, the whole modification is dropped. The play then goes on without it, the player sees a notice and the mod's log gets a warning with the reason:

Thin chords: failed (… chart.setNotes refused the buffer: note 3: two notes at 1000000 us in column 2); the map plays without it
Thin chords: chart.setNotes refused the buffer: note 3: two notes at 1000000 us in column 2; the map plays without it

The first form is an exception your handler did not catch; the second is one it caught. The reason is the same.

A mod that throws, runs out of its execution budget (30 ms per handler call by default) or of memory (16 MiB), or that has no chart.transform handler at all, is dropped the same way. Only that modification is dropped: the other modifiers and the map are untouched, and the play never starts on a half-valid chart. A failure does not disable your mod at once; three failures in a row, or three timeouts, do disable it for the session.

Calls outside the handler fail at once: chart.getNotes is only available inside a `chart.transform` handler, and the same for chart.setNotes. A mod only gets the notes of the delivery made to it.

What stays native

Mirror, No long notes and the ranked Full long notes are built into Prism (prism/mirror, prism/no-ln, prism/full-ln): the game applies them itself after the rate, and a play with them stays ranked. A script that turns every hold into a tap leaves the same notes as No long notes, but they are recorded as scripted, and that play is unranked. Full long notes is native because it needs the timing points and the real-time constants of the rate, which chart.getNotes() does not give. The shipped pvng.full-ln mod is the same modifier with settings the player tunes (see Gameplay modifiers).

Determinism and the seed

notes.seed is an integer the game draws for each play. It is mixed with the key of your modifier, so two mods in the same play never shuffle with the same numbers, and it is different at every launch. Use it to make a shuffle that is random for the player yet reproducible inside one run: the same seed must give the same notes.

The shipped Random does that with a small seeded generator (mulberry32) and a Fisher-Yates shuffle of the columns, never the identity:

/** A small seeded generator (mulberry32): the same seed always gives the same numbers. */
function generator(seed: number): () => number {
  let state = seed >>> 0;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = state;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/** `result[c]` is where column `c` goes: a Fisher-Yates shuffle, never the identity when there are two columns or more. */
function permutation(keys: number, seed: number): number[] {
  const random = generator(seed);
  const columns = Array.from({ length: keys }, (_, column) => column);
  if (keys < 2) return columns;
  for (let attempt = 0; attempt < 64; attempt++) {
    for (let index = keys - 1; index > 0; index--) {
      const other = Math.floor(random() * (index + 1));
      [columns[index], columns[other]] = [columns[other], columns[index]];
    }
    if (columns.some((column, index) => column !== index)) return columns;
  }
  columns.push(columns.shift() as number);
  return columns;
}

In the handler, const target = permutation(notes.keys, notes.seed); gives where each column goes, and notes.column.map((column) => target[column]) rewrites the column array.

Rules for a transformation that behaves:

  • Make it a pure function of the notes and of seed. Do not use Math.random() or the clock: the replay would still be exact, but you could not reproduce a result to debug it.
  • Do not keep state between plays. The handler runs for every play with the modifier on.
  • Keep it linear. A map has up to 100 000 notes and the handler has a 30 ms budget by default: loop over typed arrays, allocate once, never create an object per note. Measured in an unoptimized test build, one transformation takes about 0.5 ms for 500 notes, 5 ms for 5 000 and 42 to 58 ms for 50 000; the release build was not measured.

Replays

The replay of a play whose notes changed records the resulting notes, not your script, not the seed: chartMods.scripted holds the mods that ran, in order (key, name, version, at most 8) and the final notes of the 1x chart, delta-coded and in base64. The replay plays back without your mod installed: the recording alone rebuilds the chart, with the same checks as a fresh submission. See .pvreplay.

That is also why your script cannot cheat the ranking: any change of the notes is recorded and unranks the play, and a script that returns the same notes leaves the play ranked. No script can make a ranked No long notes or Full long notes play: its notes are always recorded as its own.

Pitfalls

  • notes.startUs.map(...) maps bytes, not times. Always go through a Float64Array.
  • new Float64Array(notes.startUs.buffer, 0, count) is wrong when byteOffset is not 0. Pass notes.startUs.byteOffset.
  • Moving a note in time can overlap its column. After a shift, check the end of the previous note of the column, or the whole buffer is refused.
  • A hold whose end passes durationUs is refused: clamp it.
  • Mirror, No long notes and the ranked Full long notes cannot be scripts: they are native (prism/mirror, prism/no-ln, prism/full-ln) so the play stays ranked. Do not register a modifier of kind mirror, noLn or rankedFullLn.
  • One handler serves every modifier of the mod: if (request.id !== "yours") return;.

Reference

Source in the game repository: crates/modding/src/transform.rs,crates/modding/src/modifiers.rs,crates/modding/src/runtime.rs,crates/modding/src/api.rs,crates/core/src/scripted_notes.rs,crates/core/src/chart_mods.rs,content/mods/random/main.ts,content/examples/mods/thin-chords/main.ts,crates/modding/tests/chart_transform.rs