Documentation

SeedForge Documentation

Advanced seedable pseudo-random number generator library for JavaScript with multiple algorithms, statistical distributions, and noise generators.

#Installation

npm

npm install seedforge-prng

CDN

<script src="https://unpkg.com/seedforge-prng/dist/seedforge.js"></script>

ES Modules

import { PRNG, Noise, Algorithms } from 'seedforge-prng';

CommonJS

const { PRNG, Noise, Algorithms } = require('seedforge-prng');

#Quick Start

const { PRNG } = require('seedforge-prng');

// Create a seeded generator
const rng = new PRNG('my-seed');

// Basic random values
rng.random();          // 0.0 to 1.0
rng.int(1, 100);       // Integer 1-100
rng.float(0, 10);      // Float 0-10
rng.bool(0.5);         // 50% true

// Array operations
rng.pick(['a', 'b', 'c']);  // Random element
rng.shuffle([1, 2, 3, 4]);   // Shuffled copy

// Distributions
rng.normal(100, 15);   // Gaussian
rng.exponential(1.5);  // Exponential

// Same seed = same results, every time!
πŸ’‘
Reproducibility Using the same seed will always produce the same sequence of random numbers. This is perfect for procedural generation, replays, and testing.

#Algorithms

SeedForge includes 6 PRNG algorithms. Choose based on your needs:

Algorithm Period Speed Quality Best For
sfc32 ~2¹²⁸ β˜…β˜…β˜…β˜…β˜… β˜…β˜…β˜…β˜…β˜… Best all-around
xoshiro128 2¹²⁸-1 β˜…β˜…β˜…β˜…β˜† β˜…β˜…β˜…β˜…β˜… General purpose (default)
pcg32 2⁢⁴ β˜…β˜…β˜…β˜…β˜† β˜…β˜…β˜…β˜…β˜… Simulations, statistics
mulberry32 ~2Β³Β² β˜…β˜…β˜…β˜…β˜… β˜…β˜…β˜…β˜†β˜† Maximum speed
xorshift128 2¹²⁸-1 β˜…β˜…β˜…β˜†β˜† β˜…β˜…β˜…β˜…β˜† Compatibility
lcg 2Β³Β² β˜…β˜…β˜…β˜…β˜… β˜…β˜…β˜†β˜†β˜† Legacy systems

Selecting an Algorithm

// Default (xoshiro128**)
const rng1 = new PRNG('seed');

// Specify algorithm
const rng2 = new PRNG('seed', 'sfc32');
const rng3 = new PRNG('seed', 'pcg32');
const rng4 = new PRNG('seed', 'mulberry32');
ℹ️
Recommendation Use sfc32 for the best balance of speed and quality. Use mulberry32 when you need maximum performance and don't require long periods.

#Constructor

new PRNG(seed, algorithm?)
PRNG(seed: string | number, algorithm?: string)

Creates a new seeded random number generator.

Parameters
seed string | number Seed value. Strings are hashed to numbers.
algorithm string Optional. One of: 'xoshiro128', 'sfc32', 'pcg32', 'mulberry32', 'xorshift128', 'lcg'. Default: 'xoshiro128'
Returns
PRNG β€” A new PRNG instance
// String seed (hashed internally)
const rng1 = new PRNG('my-world-seed');

// Numeric seed
const rng2 = new PRNG(12345);

// With specific algorithm
const rng3 = new PRNG('seed', 'sfc32');

#Basic Generation

.random() Instance
random(): number

Returns a random float in [0, 1).

Returns
number β€” Float from 0 (inclusive) to 1 (exclusive)
.int(min, max) Instance
int(min: number, max: number): number

Returns a random integer in [min, max] (inclusive).

Parameters
min number Minimum value (inclusive)
max number Maximum value (inclusive)
.float(min, max) Instance
float(min: number, max: number): number

Returns a random float in [min, max).

.bool(probability?) Instance
bool(probability?: number): boolean

Returns true with the given probability.

Parameters
probability number Probability of true (0-1). Default: 0.5
.sign() Instance
sign(): number

Returns -1 or 1 with equal probability.

const rng = new PRNG('example');

rng.random();       // 0.7234521
rng.int(1, 6);       // 4 (dice roll)
rng.int(0, 255);     // 182 (byte value)
rng.float(-1, 1);    // -0.3421
rng.bool();          // true (50% chance)
rng.bool(0.8);       // true (80% chance)
rng.sign();          // -1 or 1

#Statistical Distributions

SeedForge provides 17 statistical distributions for realistic data generation.

.normal(mean, stdDev) Instance
normal(mean?: number, stdDev?: number): number

Gaussian/normal distribution using Box-Muller transform.

Parameters
mean number Center of distribution. Default: 0
stdDev number Standard deviation. Default: 1
.exponential(lambda) Instance
exponential(lambda?: number): number

Exponential distribution. Good for time between events.

Parameters
lambda number Rate parameter. Default: 1
.poisson(lambda) Instance
poisson(lambda: number): number

Poisson distribution. Good for counting events.

.pareto(alpha, xMin) Instance
pareto(alpha?: number, xMin?: number): number

Pareto distribution. Good for wealth, city sizes, etc.

All Distributions

Method Description Use Case
normal(ΞΌ, Οƒ) Gaussian distribution Stats, heights, IQ scores
exponential(Ξ») Exponential distribution Time between events
poisson(Ξ») Poisson distribution Event counts
pareto(Ξ±, xMin) Pareto distribution Wealth, loot values
gamma(k, ΞΈ) Gamma distribution Wait times
beta(Ξ±, Ξ²) Beta distribution Probabilities, percentages
binomial(n, p) Binomial distribution Success counts
geometric(p) Geometric distribution Trials until success
triangular(min, max, mode) Triangular distribution Estimates with known bounds
logNormal(ΞΌ, Οƒ) Log-normal distribution Stock prices, sizes
weibull(Ξ», k) Weibull distribution Reliability, survival analysis
cauchy(x0, Ξ³) Cauchy distribution Heavy-tailed data
zipf(n, s) NEW Zipf/power-law distribution Word frequencies, rankings
chiSquared(k) NEW Chi-squared distribution Statistical testing
studentT(df) NEW Student's t-distribution Small sample statistics
vonMises(ΞΌ, ΞΊ) NEW Von Mises distribution Circular/directional data
hypergeometric(N, K, n) NEW Hypergeometric distribution Sampling without replacement
const rng = new PRNG('stats');

// IQ scores (mean 100, stddev 15)
rng.normal(100, 15);  // 94.28

// Loot gold (minimum 10, Pareto distributed)
rng.pareto(1.5, 10);  // Usually low, occasionally high

// Enemy spawn count
rng.poisson(3);       // Average of 3

// v1.1.0: Word frequency ranking (Zipf distribution)
rng.zipf(100, 1.0);   // Returns 1-100 with power-law frequency

// v1.1.0: Wind direction (Von Mises circular distribution)
rng.vonMises(0, 2);   // Concentrated around 0 radians (East)

// v1.1.0: Card draw probability (Hypergeometric)
rng.hypergeometric(52, 13, 5);  // Hearts in 5-card hand

#Array Utilities

.pick(array) Instance
pick<T>(array: T[]): T

Returns a random element from the array.

.sample(array, count) Instance
sample<T>(array: T[], count: number): T[]

Returns multiple unique random elements.

.shuffle(array) Instance
shuffle<T>(array: T[]): T[]

Returns a shuffled copy (Fisher-Yates algorithm).

.weightedPick(array, weights) Instance
weightedPick<T>(array: T[], weights: number[]): T

Picks an element with probability proportional to its weight.

.weightedPickObject(weights) Instance
weightedPickObject(weights: Record<string, number>): string

Picks a key from an object based on values as weights.

const rng = new PRNG('arrays');

// Pick random element
rng.pick(['sword', 'shield', 'potion']);  // 'shield'

// Draw 3 cards without replacement
rng.sample(['A', 'K', 'Q', 'J', '10'], 3);  // ['K', '10', 'A']

// Shuffle a deck
const deck = [1, 2, 3, 4, 5];
rng.shuffle(deck);  // [3, 1, 5, 2, 4]

// Weighted selection
rng.weightedPick(
    ['common', 'rare', 'legendary'],
    [70, 25, 5]
);  // Most likely 'common'

// Object-based weights (loot table)
rng.weightedPickObject({
    common: 60,
    uncommon: 25,
    rare: 10,
    legendary: 5
});  // 'common'

#Geometric Utilities

Generate random points in various shapes for spawn systems and spatial distribution.

.pointInCircle(radius) Instance
pointInCircle(radius?: number): {x: number, y: number}

Random point uniformly distributed inside a circle.

.pointOnCircle(radius) Instance
pointOnCircle(radius?: number): {x: number, y: number}

Random point on the circumference of a circle.

.pointInSphere(radius) Instance
pointInSphere(radius?: number): {x, y, z}

Random point uniformly distributed inside a sphere.

.pointInRect(width, height) Instance
pointInRect(width: number, height: number): {x, y}

Random point inside a rectangle.

const rng = new PRNG('geometry');

// Spawn enemy within 50 units of player
const spawn = rng.pointInCircle(50);
// { x: 23.4, y: -31.2 }

// Place items around a ring
const item = rng.pointOnCircle(100);
// { x: 87.3, y: 48.7 }

// 3D particle spawn
const particle = rng.pointInSphere(10);
// { x: 3.2, y: -5.1, z: 7.8 }

// Random position in room
const pos = rng.pointInRect(800, 600);
// { x: 423.5, y: 187.2 }

#Special Generators

.uuid() Instance
uuid(): string

Generates a UUID v4 string.

.color() Instance
color(): string

Generates a random hex color (#RRGGBB).

.colorRGB() Instance
colorRGB(): {r: number, g: number, b: number}

Generates random RGB values (0-255).

.colorHSL(sRange?, lRange?) Instance
colorHSL(sRange?, lRange?): {h, s, l}

Generates HSL color with optional saturation/lightness constraints.

.angle() Instance
angle(): number

Returns a random angle in radians [0, 2Ο€).

.angleDeg() Instance
angleDeg(): number

Returns a random angle in degrees [0, 360).

const rng = new PRNG('special');

rng.uuid();      // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
rng.color();     // '#7a3f9c'
rng.colorRGB();  // { r: 122, g: 63, b: 156 }
rng.colorHSL();  // { h: 274, s: 42, l: 43 }
rng.angle();     // 4.234 (radians)
rng.angleDeg();  // 242.5 (degrees)

#State Management

Save, restore, clone, and fork generators for game saves, replays, and parallel streams.

.getState() Instance
getState(): PRNGState

Returns the current internal state (serializable to JSON).

.setState(state) Instance
setState(state: PRNGState): void

Restores a previously saved state.

.clone() Instance
clone(): PRNG

Creates an independent copy with the same state.

.fork(newSeed?) Instance
fork(newSeed?: string | number): PRNG

Creates a new generator seeded from current state (for parallel streams).

const rng = new PRNG('game');

// Generate some values
rng.random();
rng.random();

// Save state
const savedState = rng.getState();
const json = JSON.stringify(savedState);

// ... later, restore state
rng.setState(JSON.parse(json));

// Clone for parallel use
const rng2 = rng.clone();
rng.random() === rng2.random();  // true

// Fork for independent streams
const weatherRng = rng.fork('weather');
const combatRng = rng.fork('combat');
πŸ’‘
Game Saves Use getState() and setState() to save/restore the exact position in the random sequence. This is essential for savegames and replay systems.

#Simplex Noise

Simplex noise is ideal for procedural terrain, textures, and organic patterns.

const { Noise } = require('seedforge-prng');

const noise = new Noise.SimplexNoise('terrain');

// 2D noise
noise.noise2D(0, 0);       // -1 to 1
noise.noise2D(0.5, 0.5);   // Smooth variation

// 3D noise
noise.noise3D(0, 0, 0);    // For volumetric data

// Fractal Brownian Motion (fBm)
noise.fbm(x, y, z, octaves, lacunarity, persistence);
new Noise.SimplexNoise(seed)
SimplexNoise(seed: string | number)

Creates a seeded Simplex noise generator.

.noise2D(x, y) Instance
noise2D(x: number, y: number): number

Returns 2D noise value at coordinates. Range: [-1, 1].

.noise3D(x, y, z) Instance
noise3D(x: number, y: number, z: number): number

Returns 3D noise value at coordinates. Range: [-1, 1].

#Value Noise

const noise = new Noise.ValueNoise('seed');

noise.noise2D(0, 0);
noise.noise3D(0, 0, 0);
noise.fbm(x, y, z, octaves, lacunarity, persistence);

#Perlin Noise NEW in v1.1.0

Classic Perlin gradient noise - the original algorithm that started it all.

const perlin = new Noise.PerlinNoise('seed');

// 2D noise (returns -1 to 1)
perlin.noise2D(1.5, 2.3);     // 0.312

// 3D noise
perlin.noise3D(1.5, 2.3, 0.8); // -0.089

// With fBm for terrain
perlin.fbm(x * 0.01, y * 0.01, null, 6, 2.0, 0.5);

#Worley Noise NEW in v1.1.0

Cellular/Voronoi noise - perfect for stone, cells, stained glass, and organic patterns.

const worley = new Noise.WorleyNoise('seed');

// Basic usage - distance to nearest point
worley.noise2D(1.5, 2.3);

// Distance types: 'euclidean', 'manhattan', 'chebyshev'
// Feature indices: 0 = F1 (nearest), 1 = F2 (second), 2 = F2-F1 (edges)

// Round cells (euclidean F1)
worley.noise2D(x, y, 'euclidean', 0);

// Diamond cells (manhattan)
worley.noise2D(x, y, 'manhattan', 0);

// Cell edges / cracks (F2-F1)
worley.noise2D(x, y, 'euclidean', 2);
πŸ’‘
Worley Use Cases F1 creates cell patterns, F2-F1 creates veins/cracks. Combine with distance types for unique textures like stone, scales, or stained glass.

#Ridged Noise NEW in v1.1.0

Sharp ridges and peaks - ideal for mountains, veins, lightning bolts.

const ridged = new Noise.RidgedNoise('mountains');

// Sharp mountain ridges
ridged.noise2D(x * 0.01, y * 0.01);

// With fBm for detailed peaks
ridged.fbm(x * 0.01, y * 0.01, null, 6, 2.0, 0.5);

#Billowed Noise NEW in v1.1.0

Soft, puffy shapes - perfect for clouds, smoke, foam.

const billowed = new Noise.BillowedNoise('clouds');

// Fluffy cloud shapes
billowed.noise2D(x * 0.01, y * 0.01);

// With fBm for detailed clouds
billowed.fbm(x * 0.01, y * 0.01, null, 4, 2.0, 0.5);

#fBm & Turbulence

fBm layers multiple octaves of noise for more natural-looking results. Turbulence uses absolute values for chaotic patterns.

.fbm(x, y, z?, octaves?, lacunarity?, persistence?) Instance
fbm(x, y, z?, octaves?, lacunarity?, persistence?): number

Fractal Brownian Motion - layered noise for natural terrain.

Parameters
x, y number Coordinates
z number? Optional Z coordinate for 3D
octaves number Number of layers. Default: 4
lacunarity number Frequency multiplier per octave. Default: 2.0
persistence number Amplitude multiplier per octave. Default: 0.5
.turbulence(x, y, z?, octaves?, lacunarity?, persistence?) Instance NEW
turbulence(x, y, z?, octaves?, lacunarity?, persistence?): number

Absolute value fBm - chaotic patterns for fire, smoke, plasma.

const noise = new Noise.SimplexNoise('fire');

// Standard fBm for terrain
noise.fbm(x * 0.01, y * 0.01, null, 6, 2.0, 0.5);

// NEW: Turbulence for fire/smoke
noise.turbulence(x * 0.03, y * 0.03, null, 6, 2.2, 0.5);
ℹ️
Octaves More octaves = more detail but slower. 4-6 octaves is usually sufficient for terrain.

#Domain Warping NEW in v1.1.0

Distort coordinates using noise for organic, flowing, otherworldly patterns.

.warp(x, y, strength?, octaves?) Instance
warp(x, y, strength?, octaves?): number

Single domain warp - organic distortion.

.warp2(x, y, strength?, octaves?) Instance
warp2(x, y, strength?, octaves?): number

Double domain warp - extreme organic patterns.

const noise = new Noise.SimplexNoise('marble');

// Single warp - subtle organic distortion
noise.warp(x * 0.02, y * 0.02, 1.5, 4);

// Double warp - extreme alien terrain
noise.warp2(x * 0.02, y * 0.02, 2.0, 4);
πŸ’‘
Warping Use Cases Single warp creates marble-like veins. Double warp creates flowing, alien landscapes perfect for fantasy or sci-fi terrain.
const noise = new Noise.SimplexNoise('world');

// Generate heightmap
function getHeight(x, y) {
    let h = noise.fbm(
        x * 0.01,     // Scale down coordinates
        y * 0.01,
        null,          // 2D (no z)
        6,             // 6 octaves
        2.0,           // Lacunarity
        0.5            // Persistence
    );
    
    // Normalize from [-1,1] to [0,1]
    return (h + 1) / 2;
}
ℹ️
Octaves More octaves = more detail but slower. 4-6 octaves is usually sufficient for terrain.

#TypeScript

SeedForge includes full TypeScript definitions.

import { PRNG, Noise, PRNGState, Point2D, RGB } from 'seedforge-prng';

const rng: PRNG = new PRNG('seed');

const value: number = rng.random();
const point: Point2D = rng.pointInCircle(10);
const color: RGB = rng.colorRGB();
const state: PRNGState = rng.getState();

const noise: Noise.SimplexNoise = new Noise.SimplexNoise('terrain');

#Browser Usage

Script Tag

<script src="https://unpkg.com/seedforge-prng/dist/seedforge.js"></script>
<script>
    const rng = new PRNG.PRNG('seed');
    const noise = new PRNG.Noise.SimplexNoise('terrain');
</script>

ES Modules

<script type="module">
    import { PRNG, Noise } from 'https://unpkg.com/seedforge-prng/dist/seedforge.mjs';
    
    const rng = new PRNG('seed');
</script>

#Performance

Benchmark results (operations per second, higher is better):

Algorithm ops/sec Notes
mulberry32 ~50M Fastest
sfc32 ~45M Recommended
xoshiro128 ~40M Default
pcg32 ~35M High quality
xorshift128 ~20M Slower in JS
lcg ~50M Lower quality
⚠️
xorshift128 Performance The xorshift128 algorithm is slower in JavaScript due to 64-bit integer emulation. Use sfc32 or mulberry32 for performance-critical code.