A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.
package random
import "github.com/nsgo-dev/game/pkg/random"Visão geral
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.
Índice
- 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, equal func(a, b S) bool)
- 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 NewNoise(seed uint64) *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, cfg FractalConfig)
- func (n *Noise) FillGrid2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, sample func(x, y float64) 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 New(seed uint64) *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
Funções
func AssertDeterministic[S any](t testing.TB, runs int, run func() S)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[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[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).
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 Pick[T any](s *Stream, items []T) TPick returns a uniformly chosen element of items. It panics if items is empty.
func Shuffle[T any](s *Stream, items []T)Shuffle randomly permutes items in place using the Fisher-Yates algorithm.
Tipos
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() FractalConfigDefaultFractalConfig returns a FractalConfig populated with standard defaults suitable for terrain, clouds, and procedural textures.
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[S any](runs int, run func() S, equal func(a, b S) bool) (Mismatch[S], bool)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 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.
func NewNoise(seed uint64) *NoiseNewNoise returns a deterministic Noise generator seeded with seed.
func (n *Noise) Billow2D(x, y float64, cfg FractalConfig) float64Billow2D evaluates normalized 2D billow fractal noise using Simplex2D, producing soft cloud-like lobes in [-1, 1].
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 (n *Noise) FBM2D(x, y float64, cfg FractalConfig) float64FBM2D evaluates normalized 2D fractal Brownian motion using Simplex2D, returning a value in [-1, 1].
func (n *Noise) FBM3D(x, y, z float64, cfg FractalConfig) float64FBM3D evaluates normalized 3D fractal Brownian motion using Simplex3D, returning a value in [-1, 1].
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 (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 (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 (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 (n *Noise) Fork(purpose string) *NoiseFork derives an independent, deterministic child Noise generator for purpose (such as "elevation", "moisture" or "caves") from n's seed.
func (n *Noise) Ridged2D(x, y float64, cfg FractalConfig) float64Ridged2D 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 (n *Noise) Ridged3D(x, y, z float64, cfg FractalConfig) float64Ridged3D 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 (n *Noise) Seed() uint64Seed returns the seed that initialized n.
func (n *Noise) Simplex2D(x, y float64) float64Simplex2D evaluates 2D simplex gradient noise at (x, y), returning a value in [-1, 1].
func (n *Noise) Simplex3D(x, y, z float64) float64Simplex3D evaluates 3D simplex gradient noise at (x, y, z), returning a value in [-1, 1].
func (n *Noise) Value2D(x, y float64) float64Value2D evaluates smooth 2D lattice value noise at (x, y), returning a value in [-1, 1].
func (n *Noise) Value3D(x, y, z float64) float64Value3D evaluates smooth 3D lattice value noise at (x, y, z), returning a value in [-1, 1].
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 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.
func (s *Stream) Bool() boolBool returns a uniformly distributed boolean.
func (s *Stream) Chance(p float64) boolChance 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 (s *Stream) Float32() float32Float32 returns a uniformly distributed float32 in [0, 1) with 24 bits of precision.
func (s *Stream) Float64() float64Float64 returns a uniformly distributed float64 in [0, 1) with 53 bits of precision.
func (s *Stream) Fork(purpose string) *StreamFork 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 (s *Stream) IntRange(min, max int) intIntRange returns a uniformly distributed integer in [min, max], inclusive. It returns min when min == max and panics if min > max.
func (s *Stream) Intn(n int) intIntn returns a uniformly distributed integer in [0, n). It panics if n <= 0.
func (s *Stream) Range(min, max float64) float64Range 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 (s *Stream) Range32(min, max float32) float32Range32 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 (s *Stream) Reset()Reset rewinds s to the beginning of its seed's sequence.
func (s *Stream) Seed() uint64Seed returns the seed that initialized s.
func (s *Stream) SetSeed(seed uint64)SetSeed re-seeds s with seed and rewinds it to the beginning of seed's sequence.
func (s *Stream) SetState(st State)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 (s *Stream) State() StateState returns a snapshot of s that can be serialized and passed to SetState to resume the exact same future sequence.
func (s *Stream) Uint32() uint32Uint32 returns a uniformly distributed pseudo-random uint32 taken from the upper 32 bits of Uint64.
func (s *Stream) Uint64() uint64Uint64 returns a uniformly distributed pseudo-random uint64.
func (s *Stream) WeightedIndex(weights []float64) intWeightedIndex 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 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.
func NewStreams(masterSeed uint64) *StreamsNewStreams returns a Streams manager rooted at masterSeed.
func (m *Streams) Reset()Reset rewinds the root stream and every stream already obtained from m back to its initial state.
func (m *Streams) Restore(states map[string]State)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 (m *Streams) SetSeed(masterSeed uint64)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.
func (m *Streams) States() map[string]StateStates returns a JSON-marshalable snapshot of every stream currently held by m.
func (m *Streams) Stream(name string) *StreamStream returns the named child stream, creating it on first use by forking from the master seed.