Skip to content

Seamless Texture — Zig source

Make images tile seamlessly or generate tileable noise textures — entirely in your browser. Nothing uploads.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! seamless-texture — tileable-texture math, Zig port: wrap-blend weights,
//! integer lattice hash, wrapping value noise, torus Worley. Zig stdlib
//! only. Zig port of the pure src/lib/seamless.ts (the TS lib has no canvas
//! or DOM dependency at all, so this is a 1:1 port); the browser island owns
//! all drawing. i32 *% saturating-free wrapping multiplication reproduces
//! Math.imul exactly.
const std = @import("std");

/// Mirrors the TS NoiseOptions: `scale` is the tile period in pixels;
/// `octaves` < 1 snaps to 1 (the default included).
pub const NoiseOptions = struct {
    seed: i32,
    scale: f64,
    octaves: i32 = 1,
};

/// Mirrors the TS WorleyOptions: `points` is the number of hashed feature
/// points scattered in the unit tile (>= 1; floored like the TS).
pub const WorleyOptions = struct {
    seed: i32,
    points: f64,
};

/// Mapped 0..1 distances to the nearest (d1) and second-nearest (d2) points.
pub const WorleyResult = struct {
    d1: f64,
    d2: f64,
};

/// Cross-fade weight for wrap-blending a texture's seams: 1 in the interior,
/// falling linearly to 0 across `feather` pixels approaching each wrapped
/// edge (axis weights multiplied, clamped 0..1). `feather <= 0` (or NaN)
/// disables the ramp.
pub fn blendWeight(x: f64, y: f64, w: f64, h: f64, feather: f64) f64 {
    if (!(feather > 0)) return 1;
    const fx = @min(x, w - x) / feather;
    const fy = @min(y, h - y) / feather;
    return @min(@as(f64, 1), @max(@as(f64, 0), fx)) * @min(@as(f64, 1), @max(@as(f64, 0), fy));
}

/// 32-bit wrapping multiplication — i32 `*%` has Math.imul's exact
/// truncating semantics.
fn imul(a: i32, b: i32) i32 {
    return a *% b;
}

/// The JS `h >>> n`: a logical right shift of the int32 bit pattern.
fn shr(h: i32, n: u5) i32 {
    const u: u32 = @bitCast(h);
    return @bitCast(u >> n);
}

/// JS Math.round (half up) — @round is half away from zero.
fn jsRound(v: f64) f64 {
    return @floor(v + 0.5);
}

/// Deterministic 0..1 hash of an integer lattice point: 32-bit integer
/// avalanche — h = x·0x9E3779B1 ^ y·0x85EBCA77 ^ seed·0xC2B2AE35 (truncated
/// to int32), then three xor-shift/multiply rounds; the unsigned result is
/// scaled by 1/2³². Same (x, y, seed) → same value on every platform and run.
pub fn hash2(x: i32, y: i32, seed: i32) f64 {
    var h = imul(x, @bitCast(@as(u32, 0x9e3779b1))) ^ imul(y, @bitCast(@as(u32, 0x85ebca77))) ^ imul(seed, @bitCast(@as(u32, 0xc2b2ae35)));
    h ^= shr(h, 15);
    h = imul(h, @bitCast(@as(u32, 0x2c1b3c6d)));
    h ^= shr(h, 12);
    h = imul(h, @bitCast(@as(u32, 0x297a2d39)));
    h ^= shr(h, 15);
    const u: u32 = @bitCast(h);
    return @as(f64, @floatFromInt(u)) / 4294967296.0;
}

/// Wrapping value noise over a unit lattice (lattice spacing 1 px, tile
/// period `scale` px): noise(x + scale, y) === noise(x, y) exactly. Octaves
/// >= 2 sum frequency-doubled, amplitude-halved layers normalized by total
/// amplitude; scale < 1 snaps to 1.
pub fn valueNoise(x: f64, y: f64, opts: NoiseOptions) f64 {
    const scale = @max(@as(f64, 1), jsRound(opts.scale));
    const octaves = @max(@as(i32, 1), opts.octaves);
    var sum: f64 = 0;
    var total: f64 = 0;
    var amp: f64 = 1;
    var freq: f64 = 1;
    var o: i32 = 0;
    while (o < octaves) : (o += 1) {
        sum += amp * layer(x * freq, y * freq, scale * freq, opts.seed +% (o *% 101));
        total += amp;
        amp /= 2;
        freq *= 2;
    }
    return sum / total;
}

/// One octave: bilinear (quintic-faded) interpolation of wrapped lattice hashes.
fn layer(x: f64, y: f64, period: f64, seed: i32) f64 {
    const x0 = @floor(x);
    const y0 = @floor(y);
    const u = fade(x - x0);
    const v = fade(y - y0);
    const xa = wrap(x0, period);
    const xb = wrap(x0 + 1, period);
    const ya = wrap(y0, period);
    const yb = wrap(y0 + 1, period);
    const top = lerp(hash2(@intFromFloat(xa), @intFromFloat(ya), seed), hash2(@intFromFloat(xb), @intFromFloat(ya), seed), u);
    const bottom = lerp(hash2(@intFromFloat(xa), @intFromFloat(yb), seed), hash2(@intFromFloat(xb), @intFromFloat(yb), seed), u);
    return lerp(top, bottom, v);
}

/// Positive modulo — lattice indices wrap onto the torus of `period` cells.
fn wrap(i: f64, period: f64) f64 {
    return @mod(@rem(i, period) + period, period);
}

/// Quintic smoothstep fade — C2-continuous interpolation curve.
fn fade(t: f64) f64 {
    return t * t * t * (t * (t * 6 - 15) + 10);
}

fn lerp(a: f64, b: f64, t: f64) f64 {
    return a + (b - a) * t;
}

/// Wrapping (torus-metric) F1-F2 field: each axis distance wraps via
/// min(d, 1-d), so the field tiles exactly with period 1 in x and y. Raw
/// torus distances top out at the half-diagonal √½, which maps to 1. Fewer
/// than one point returns the all-max {1, 1}; exactly one point leaves d2
/// at the maximum.
pub fn worley(x: f64, y: f64, opts: WorleyOptions) WorleyResult {
    // Wrap the query onto the unit tile first so shifted queries are exact.
    const wx = x - @floor(x);
    const wy = y - @floor(y);
    const n: i32 = @intFromFloat(@floor(opts.points));
    var d1: f64 = 1;
    var d2: f64 = 1;
    if (n >= 1) {
        var i: i32 = 0;
        while (i < n) : (i += 1) {
            const px = hash2(i, 0, opts.seed);
            const py = hash2(i, 1, opts.seed);
            var dx = @abs(wx - px);
            dx = @min(dx, 1 - dx);
            var dy = @abs(wy - py);
            dy = @min(dy, 1 - dy);
            const d = @sqrt(dx * dx + dy * dy) * std.math.sqrt2;
            if (d < d1) {
                d2 = d1;
                d1 = d;
            } else if (d < d2) {
                d2 = d;
            }
        }
    }
    return .{ .d1 = d1, .d2 = d2 };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →