/**
 * Deterministic RNG for the Goal Fighters engine (mulberry32).
 *
 * The state lives inside the Match object (`m.rng`), so a match created
 * with a given seed replays exactly the same, step by step: same AI
 * decisions, same particle bursts, same everything. That is what makes
 * replays, lockstep/rollback netcode and reproducible bug reports
 * possible. `Math.random()` must never be called from the simulation.
 *
 * Creating a match without a seed picks one at random (once, at creation
 * time) — that single non-deterministic moment is the seed itself.
 */
export type RngState = { s: number };

export function createRng(seed: number): RngState {
  return { s: seed >>> 0 };
}

/** One random seed for a new match. The only Math.random() in the game. */
export function randomSeed(): number {
  return (Math.random() * 0xffffffff) >>> 0;
}

/** Next pseudo-random number in [0, 1). Advances the state in place. */
export function nextRand(rng: RngState): number {
  rng.s = (rng.s + 0x6d2b79f5) >>> 0;
  let t = rng.s;
  t = Math.imul(t ^ (t >>> 15), t | 1);
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
