Documentation
¶
Overview ¶
Package random provides deterministic, cross-platform pseudo-random streams, procedural noise generators, and helpers for verifying simulation determinism.
Each Stream implements Xoshiro256** seeded through SplitMix64 with fixed, specification-stable arithmetic, so a given seed produces the exact same sequence of bits, integers and floats on every Go version, operating system and architecture.
Noise provides deterministic 2D and 3D value and simplex noise, multi-octave fractals (FBM, ridged, billow, domain warping), and zero-allocation 2D grid-fill helpers using pure integer hashing and explicit IEEE-754 float64 arithmetic for bit-identical procedural generation across arm64, x86_64 and WebAssembly.
A game derives independent child streams by name with Fork or keeps them together in Streams, snapshots and restores generator state for saves and replays with State and SetState, and tests simulation repeatability with CompareRuns, CheckSteps and AssertDeterministic.
Index ¶
- func AssertDeterministic[S any](t testing.TB, runs int, run func() S)
- func AssertDeterministicSteps[S any](t testing.TB, steps int, makeSim func() func(step int) S, ...)
- func CheckSteps[S any](steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)
- func CheckStepsRuns[S any](runs, steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)
- func Pick[T any](s *Stream, items []T) T
- func Shuffle[T any](s *Stream, items []T)
- type FractalConfig
- type Mismatch
- type Noise
- func (n *Noise) Billow2D(x, y float64, cfg FractalConfig) float64
- func (n *Noise) DomainWarp2D(x, y, strength float64, cfg FractalConfig) (wx, wy float64)
- func (n *Noise) FBM2D(x, y float64, cfg FractalConfig) float64
- func (n *Noise) FBM3D(x, y, z float64, cfg FractalConfig) float64
- func (n *Noise) FillFBM2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, ...)
- func (n *Noise) FillGrid2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, ...)
- func (n *Noise) FillSimplex2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)
- func (n *Noise) FillValue2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)
- func (n *Noise) Fork(purpose string) *Noise
- func (n *Noise) Ridged2D(x, y float64, cfg FractalConfig) float64
- func (n *Noise) Ridged3D(x, y, z float64, cfg FractalConfig) float64
- func (n *Noise) Seed() uint64
- func (n *Noise) Simplex2D(x, y float64) float64
- func (n *Noise) Simplex3D(x, y, z float64) float64
- func (n *Noise) Value2D(x, y float64) float64
- func (n *Noise) Value3D(x, y, z float64) float64
- type State
- type Stream
- func (s *Stream) Bool() bool
- func (s *Stream) Chance(p float64) bool
- func (s *Stream) Float32() float32
- func (s *Stream) Float64() float64
- func (s *Stream) Fork(purpose string) *Stream
- func (s *Stream) IntRange(min, max int) int
- func (s *Stream) Intn(n int) int
- func (s *Stream) Range(min, max float64) float64
- func (s *Stream) Range32(min, max float32) float32
- func (s *Stream) Reset()
- func (s *Stream) Seed() uint64
- func (s *Stream) SetSeed(seed uint64)
- func (s *Stream) SetState(st State)
- func (s *Stream) State() State
- func (s *Stream) Uint32() uint32
- func (s *Stream) Uint64() uint64
- func (s *Stream) WeightedIndex(weights []float64) int
- type Streams
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssertDeterministic ¶
AssertDeterministic runs run runs times from scratch and fails t with both diverging states if any run produces a different result from the first.
func AssertDeterministicSteps ¶
func AssertDeterministicSteps[S any](t testing.TB, steps int, makeSim func() func(step int) S, equal func(a, b S) bool)
AssertDeterministicSteps fails t if independent runs of makeSim diverge on any of the first steps steps, reporting the first divergent step and both states.
func CheckSteps ¶
func CheckSteps[S any](steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)
CheckSteps creates a fresh simulation with makeSim and runs it for steps steps multiple times, returning the earliest 0-based step where two runs diverge along with both states. If equal is nil, reflect.DeepEqual is used.
When all runs match on every step (or steps <= 0), CheckSteps returns (-1, zero, zero, true).
Example ¶
CheckSteps runs a simulation several times from scratch and reports the first step where two runs disagree, which finds hidden nondeterminism.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/random"
)
func main() {
makeSim := func() func(step int) int {
s := random.New(5)
pos := 0
return func(int) int {
pos += s.IntRange(-1, 1)
return pos
}
}
step, _, _, ok := random.CheckSteps(100, makeSim, nil)
fmt.Println(step, ok)
}
Output: -1 true
func CheckStepsRuns ¶
func CheckStepsRuns[S any](runs, steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)
CheckStepsRuns is like CheckSteps but executes runs independent runs from scratch (at least 2).
func Shuffle ¶
Shuffle randomly permutes items in place using the Fisher-Yates algorithm.
Example ¶
Shuffle and Pick use a Stream, so a shuffled deck is reproducible from its seed.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/random"
)
func main() {
deck := []string{"A", "2", "3", "4", "5"}
random.Shuffle(random.New(9), deck)
again := []string{"A", "2", "3", "4", "5"}
random.Shuffle(random.New(9), again)
fmt.Println(deck, fmt.Sprint(deck) == fmt.Sprint(again))
}
Output: [3 4 5 2 A] true
Types ¶
type FractalConfig ¶
type FractalConfig struct {
// Octaves is the number of noise layers to combine (default 4).
Octaves int
// Frequency is the starting coordinate scale (default 1).
Frequency float64
// Lacunarity multiplies frequency on each subsequent octave (default 2).
Lacunarity float64
// Persistence multiplies amplitude on each subsequent octave (default 0.5).
Persistence float64
// Gain controls ridged multifractal weight feedback (default 2) and acts as
// an amplitude-decay fallback for FBM/Billow when Persistence <= 0.
Gain float64
}
FractalConfig configures multi-octave fractal noise evaluation. Zero or negative values fall back to sensible defaults: Octaves=4, Frequency=1, Lacunarity=2, Persistence=0.5 (or Gain when set for FBM/Billow), and Gain=2 for Ridged multifractal weighting.
func DefaultFractalConfig ¶
func DefaultFractalConfig() FractalConfig
DefaultFractalConfig returns a FractalConfig populated with standard defaults suitable for terrain, clouds, and procedural textures.
type Mismatch ¶
type Mismatch[S any] struct { // Run is the 0-based index of the run that diverged from run 0. Run int // First is the result produced by run 0. First S // Other is the result produced by the diverging run. Other S }
Mismatch describes the first run whose result differed from the baseline run.
func CompareRuns ¶
CompareRuns executes run runs times from scratch and checks that every run equals the first. If equal is nil, reflect.DeepEqual is used. If runs < 2, CompareRuns runs twice.
It returns a zero Mismatch and true when all runs agree, or the first mismatch and false when a run diverges.
type Noise ¶
type Noise struct {
// contains filtered or unexported fields
}
Noise is a deterministic, cross-platform procedural noise generator seeded through SplitMix64.
All lookups use pure integer hashing and explicit IEEE-754 float64 arithmetic (without runtime transcendental functions or fused multiply-add contraction), producing bit-identical outputs across arm64, x86_64 and WebAssembly.
Construct a Noise instance with NewNoise. Once constructed, Noise is immutable and safe for concurrent use by multiple goroutines.
Example ¶
Noise gives smooth coherent noise for terrain and textures, in the range [-1, 1] and the same for the same seed.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/random"
)
func main() {
n := random.NewNoise(1)
cfg := random.DefaultFractalConfig()
h := n.FBM2D(10.5, 3.25, cfg)
fmt.Println(h >= -1 && h <= 1, h == random.NewNoise(1).FBM2D(10.5, 3.25, cfg))
grid := make([]float64, 4*4)
n.FillSimplex2D(grid, 4, 4, 0, 0, 0.1, 0.1)
fmt.Println(len(grid))
}
Output: true true 16
func (*Noise) Billow2D ¶
func (n *Noise) Billow2D(x, y float64, cfg FractalConfig) float64
Billow2D evaluates normalized 2D billow fractal noise using Simplex2D, producing soft cloud-like lobes in [-1, 1].
func (*Noise) DomainWarp2D ¶
func (n *Noise) DomainWarp2D(x, y, strength float64, cfg FractalConfig) (wx, wy float64)
DomainWarp2D displaces (x, y) by two decorrelated 2D FBM fields scaled by strength, returning the warped coordinates (wx, wy). Passing (wx, wy) to another noise method (or chaining multiple DomainWarp2D calls) creates organic swirls, marble and distorted terrain features.
func (*Noise) FBM2D ¶
func (n *Noise) FBM2D(x, y float64, cfg FractalConfig) float64
FBM2D evaluates normalized 2D fractal Brownian motion using Simplex2D, returning a value in [-1, 1].
func (*Noise) FBM3D ¶
func (n *Noise) FBM3D(x, y, z float64, cfg FractalConfig) float64
FBM3D evaluates normalized 3D fractal Brownian motion using Simplex3D, returning a value in [-1, 1].
func (*Noise) FillFBM2D ¶
func (n *Noise) FillFBM2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, cfg FractalConfig)
FillFBM2D populates dst in row-major order with 2D FBM simplex noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.
func (*Noise) FillGrid2D ¶
func (n *Noise) FillGrid2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, sample func(x, y float64) float64)
FillGrid2D populates dst in row-major order (dst[gy*width+gx]) with samples produced by sample at coordinates (originX+gx*stepX, originY+gy*stepY).
It performs zero heap allocations. If width <= 0 or height <= 0, FillGrid2D is a no-op. It panics if sample is nil or len(dst) < width*height.
func (*Noise) FillSimplex2D ¶
func (n *Noise) FillSimplex2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)
FillSimplex2D populates dst in row-major order with 2D simplex noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.
func (*Noise) FillValue2D ¶
func (n *Noise) FillValue2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)
FillValue2D populates dst in row-major order with 2D value noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.
func (*Noise) Fork ¶
Fork derives an independent, deterministic child Noise generator for purpose (such as "elevation", "moisture" or "caves") from n's seed.
func (*Noise) Ridged2D ¶
func (n *Noise) Ridged2D(x, y float64, cfg FractalConfig) float64
Ridged2D evaluates normalized 2D ridged multifractal noise using Simplex2D, returning a value in [0, 1] with sharp ridge crests near 1 and valleys near 0.
func (*Noise) Ridged3D ¶
func (n *Noise) Ridged3D(x, y, z float64, cfg FractalConfig) float64
Ridged3D evaluates normalized 3D ridged multifractal noise using Simplex3D, returning a value in [0, 1] with sharp ridge crests near 1 and valleys near 0.
func (*Noise) Simplex2D ¶
Simplex2D evaluates 2D simplex gradient noise at (x, y), returning a value in [-1, 1].
func (*Noise) Simplex3D ¶
Simplex3D evaluates 3D simplex gradient noise at (x, y, z), returning a value in [-1, 1].
type State ¶
type State struct {
// Seed is the seed that initialized the stream.
Seed uint64 `json:"seed"`
// S is the internal 256-bit Xoshiro256** generator state.
S [4]uint64 `json:"s"`
}
State is a JSON-marshalable snapshot of a Stream, suitable for save files and replays.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is a deterministic pseudo-random number generator backed by Xoshiro256** seeded through SplitMix64.
Its output is identical across Go versions, operating systems and architectures. Its zero value behaves as New(0). A Stream is not safe for concurrent use by multiple goroutines; fork a separate stream for each independent consumer.
Example ¶
A Stream gives the same sequence for the same seed on every platform, so a seeded level or replay comes out the same.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/random"
)
func main() {
a, b := random.New(42), random.New(42)
fmt.Println(a.Intn(100) == b.Intn(100), a.Float64() == b.Float64())
loot := random.New(7)
rarity := []string{"common", "rare", "epic"}
counts := map[string]int{}
for range 1000 {
counts[rarity[loot.WeightedIndex([]float64{80, 15, 5})]]++
}
fmt.Println(counts["common"] > counts["rare"], counts["rare"] > counts["epic"])
st := loot.State()
next := loot.Uint64()
loot.SetState(st)
fmt.Println(loot.Uint64() == next)
}
Output: true true true true true
func (*Stream) Chance ¶
Chance reports whether an event with probability p in [0, 1] occurs. It returns false when p <= 0 or p is NaN, and true when p >= 1.
func (*Stream) Float32 ¶
Float32 returns a uniformly distributed float32 in [0, 1) with 24 bits of precision.
func (*Stream) Float64 ¶
Float64 returns a uniformly distributed float64 in [0, 1) with 53 bits of precision.
func (*Stream) Fork ¶
Fork derives an independent, deterministic child stream for purpose (such as "loot", "particles", "ai" or "level-1") from s's seed.
Fork does not advance s or perturb sibling streams, so forking names in any order always produces the same child streams.
func (*Stream) IntRange ¶
IntRange returns a uniformly distributed integer in [min, max], inclusive. It returns min when min == max and panics if min > max.
func (*Stream) Range ¶
Range returns a uniformly distributed float64 in [min, max). It returns min when min == max and panics if min > max or either bound is NaN.
func (*Stream) Range32 ¶
Range32 returns a uniformly distributed float32 in [min, max). It returns min when min == max and panics if min > max or either bound is NaN.
func (*Stream) Reset ¶
func (s *Stream) Reset()
Reset rewinds s to the beginning of its seed's sequence.
func (*Stream) SetSeed ¶
SetSeed re-seeds s with seed and rewinds it to the beginning of seed's sequence.
func (*Stream) SetState ¶
SetState restores s from a snapshot returned by State. If st.S is all zero, the generator state is re-derived from st.Seed.
func (*Stream) State ¶
State returns a snapshot of s that can be serialized and passed to SetState to resume the exact same future sequence.
func (*Stream) Uint32 ¶
Uint32 returns a uniformly distributed pseudo-random uint32 taken from the upper 32 bits of Uint64.
func (*Stream) WeightedIndex ¶
WeightedIndex returns an index into weights chosen with probability proportional to its weight. It returns -1 when weights is empty or every weight is 0, and never returns an index whose weight is 0.
It panics if any weight is negative, NaN or infinite, or if the sum overflows.
type Streams ¶
type Streams struct {
// contains filtered or unexported fields
}
Streams manages named child streams derived from a single master seed.
Each name always resolves to the same independent stream regardless of the order in which streams are requested or advanced.
Example ¶
Streams derives an independent named stream per system from one master seed, so adding a draw in one system does not change another's results.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/random"
)
func main() {
world := random.NewStreams(1234)
enemies, weather := world.Stream("enemies"), world.Stream("weather")
first := weather.Uint32()
again := random.NewStreams(1234)
again.Stream("enemies").Uint64() // an extra draw in another system
fmt.Println(again.Stream("weather").Uint32() == first, enemies.Seed() != weather.Seed())
}
Output: true true
func NewStreams ¶
NewStreams returns a Streams manager rooted at masterSeed.
func (*Streams) Reset ¶
func (m *Streams) Reset()
Reset rewinds the root stream and every stream already obtained from m back to its initial state.
func (*Streams) Restore ¶
Restore restores m's streams from a snapshot returned by States. Streams present in states are created if not yet requested; existing streams missing from states are reset to their initial state.
func (*Streams) SetSeed ¶
SetSeed re-seeds m with masterSeed and re-derives every named stream already obtained from m so existing references draw from the new master seed.