v1.3.1Procedural NoiseBSD-2-Clause

High-efficiency procedural noise engine, multi-scale recursive LOD, continuous $C^2$ gradient surface cascades, periodic domain wrapping, and anti-resonance multi-octave synthesis for glitch-free planetary terrain, bathymetry, and 4D atmosp

GitHub
git clone https://github.com/tty-pt/libchaff

libchaff logo

libchaff

npm C99 BSD-2-Clause Zero Floats Deterministic Zero OpenGL

High-efficiency procedural noise engine, multi-scale recursive LOD, continuous $C^2$ gradient surface cascades, periodic domain wrapping, and anti-resonance multi-octave synthesis for glitch-free planetary terrain, bathymetry, and 4D atmospheric fields. Canonical headers are <ttypt/chaff.h>, <ttypt/chaff_surf.h>, <ttypt/noise.h>, and <ttypt/chaff_glsl.h>.

1. Quickstart

Evaluate continuous multi-octave procedural terrain with analytical surface normal slopes, or step a dense 2D time-slice in under 20 lines of C99:

#include <stdio.h>
#include <ttypt/chaff.h>

int main(void) {
    /* 1. Declarative multi-octave noise field definition */
    static const chaff_layer_t layers[] = {
        { .shift = 8, .vshift = 8, .amp = 120, .seed_mode = CHAFF_SEED_SHARED }, /* Macro relief */
        { .shift = 5, .vshift = 8, .amp =  45, .seed_mode = CHAFF_SEED_SHARED }, /* Rolling hills */
        { .shift = 3, .vshift = 8, .amp =  15, .seed_mode = CHAFF_SEED_SHARED }  /* Micro crags */
    };
    chaff_field_t field = {
        .seed = 0x1337BEEFu, .dim = 2, .nlayers = 3, .layers = layers
    };

    /* 2. Sparse point query with analytical surface normal slopes (zero extra hashes) */
    chaff_sample_2d_t s = chaff_sample_grad_2d(&field, 1024, -2048);
    printf("Elevation: %d, Slope Normal: (dX=%d, dY=%d)\n",
           s.elevation, s.grad_x, s.grad_y);

    /* 3. Bulk 2D time-slice across 3D field (e.g. animating water waves at time Z=42) */
    int32_t heightmap[32 * 32];
    chaff_fill_slice_3d(&field, 42 /* z */, 0 /* x0 */, 0 /* y0 */,
                        32, 32, heightmap, NULL, NULL);
    printf("Bulk slice evaluated (origin sample: %d)\n", heightmap[0]);

    return 0;
}

Build, Link & API Docs

# Native Linux / OpenBSD compilation (links against libchaff / libnoise):
cc worldgen.c -Iinclude -Llib -lchaff -lxxhash -o worldgen
# Or link via the backwards-compatible library name:
cc worldgen.c -Iinclude -Llib -lnoise -lxxhash -o worldgen
# Generate man(3) API documentation (chaff.h.3, chaff_surf.h.3, noise.h.3, chaff_glsl.h.3 + structs):
doxygen Doxyfile

Dual-Target Compilation Pipeline

The library compiles cleanly into both a native server shared object and a freestanding WebAssembly kernel:

# 1. Native server build (-mgeneral-regs-only enforces zero float registers):
cc -Wall -Wextra -Werror -O2 -Iinclude -mgeneral-regs-only -fPIC -shared \
   -o lib/libnoise.so src/libchaff.c -lxxhash

# 2. Freestanding browser WebAssembly build:
clang --target=wasm32 -O3 -flto -nostdlib -Wl,--no-entry \
      -Wl,--export-all -Iinclude -DXXH_INLINE_ALL -o dist/noise.wasm src/libchaff.c

2. Core Architectural Principles

libchaff is built from the ground up for massive, continuous procedural worlds spanning from sub-unit ocean caustics and sand dunes all the way up to orbital planetary horizons. It addresses the fundamental failure modes of traditional floating-point noise libraries: floating-point drift, seam cracking at coordinate limits, high-frequency aliasing during zoom-out, and Cartesian lattice terracing.

+-------------------------------------------------------------------------------+
|                           LIBCHAFF ARCHITECTURE                               |
+-------------------------------------------------------------------------------+
|  1. Integer Optimization    Zero FPU/SSE/AVX; register forward-difference     |
|                             stepping; >96% hash reduction in 3D slices.       |
|  2. Boundary Wrapping       2's complement int16_t modular arithmetic; zero   |
|                             seams or step discontinuities at 32767 -> -32768. |
|  3. Recursive & Band-LOD    Band-limited Nyquist thresholding (chaff_fill_lod)|
|                             and Q16 coordinate transformers (coord_scale).    |
|  4. Anti-Resonance Skew     Irrational Golden-Ratio rotation (theta ~ 31.7 deg|
|                             chaff_rotate_q15) breaks Cartesian terracing.     |
|  5. C2 Hermite Smoothstep   Perlin quintic polynomial (NOISE_FADE5) eliminates|
|                             slope creases and Mach banding at cell borders.   |
|  6. Zero-OpenGL Server      Headless OpenBSD/Linux server purity with bit-    |
|                             exact GLSL ES 3.0 WebGL2 shader parity.           |
+-------------------------------------------------------------------------------+

3. Maximizing Efficiency with Integer Operations

Traditional procedural noise libraries rely on floating-point arithmetic (sin, cos, IEEE 754 floats) and point-by-point function evaluations. For real-time chunk generation and terrain rendering, this imposes severe overhead: millions of transcendental instructions, branch mispredictions, and redundant corner hashes.

libchaff maximizes algorithmic and hardware efficiency through pure integer operations:

A. Pure C99 Integer Core (-mgeneral-regs-only)

  • The core library is strictly integer arithmetic: addition, subtraction, bitwise shifts, modular masking, and integer multiplications.
  • Compiling with -mgeneral-regs-only verifies that zero floating-point, SSE, AVX, or NEON instructions exist in the compiled binary (objdump audit confirms zero xmm/fadd/fmul instructions).
  • Eliminates IEEE 754 non-determinism across compilers (-O2 vs -O3), architectures (x86_64 vs ARM64), and execution targets (WASM32 vs native).

B. Hypercube Forward-Difference Matrix Stepping (noise_m, noise_quad)

  • Naive grid evaluation queries each point independently, repeating corner hash computations $2^{\text{dim}}$ times per point ($400,000+$ hashes for a standard chunk).
  • libchaff's matrix stepper (noise_quad) precomputes integer step deltas along hypercube axes via calc_steps(), stepping intermediate lattice points in CPU registers using integer addition:

$$\text{st}[n] = ((v[n + vl] - v[n]) \gg z) \ll y$$

  • This amortizes corner hashing to virtually ~0 hashes per cell, accelerating dense chunk rasterization by 10x to 15x.

C. 2D Slice Stepping Across 3D Fields (chaff_fill_slice_3d)

  • For animated surfaces (such as dynamic ocean waves where $Z = \text{time}$) or 2.5D diorama terrain slices:
  • Rather than evaluating 8 lattice corners for every $(x, y)$ coordinate at time $Z$, chaff_fill_slice_3d() pre-collapses the invariant $Z$ axis once per 3D lattice cell into a 2D quad in CPU registers:

$$c_0 = v_0 + (((v_4 - v_0) \cdot u_z) \gg 16), \quad c_1 = v_1 + (((v_5 - v_1) \cdot u_z) \gg 16)$$ $$c_2 = v_2 + (((v_6 - v_2) \cdot u_z) \gg 16), \quad c_3 = v_3 + (((v_7 - v_3) \cdot u_z) \gg 16)$$

  • On a $32 \times 32$ cell, this cuts corner hashes from 256 down to 8 — a 96.8% reduction in hash operations while producing bit-exact identical values to point queries.

D. Scanline & Thread-Local 4-Corner Cell Caching (noise_scanline_t, noise_wcache_t, _CHAFF_TLS)

  • When rasterizing rows of pixels, noise_scanline_eval_row() and noise_wrow() cache active lattice corners in registers so corners are fetched only when crossing a cell boundary (e.g. 17 corner fetches for 256 pixels at shift 4, rather than 256 independent fetches).
  • For general 2D periodic (chaff_wpoint_periodic_2d_ex, chaff_wpoint_periodic_2d_4x) and multi-octave rotated FBM (chaff_fbm_rotated_2d) queries, thread-local (_CHAFF_TLS / _Thread_local / __thread) 4-corner lattice cell caches retain the evaluated quad corners per octave, eliminating redundant corner hashes across spatially coherent queries while remaining 100% lock-free and race-free across multi-threaded stele_wq worker pools.

E. Analytical Spatial Gradients in Registers (Zero Extra Hashes)

  • Determining surface normal slopes ($\frac{\partial H}{\partial x}, \frac{\partial H}{\partial y}, \frac{\partial H}{\partial z}$) traditionally requires finite central differences:

$$\frac{\partial H}{\partial x} \approx \frac{H(x + \epsilon, y) - H(x - \epsilon, y)}{2\epsilon}$$ This requires 2 to 4 additional noise evaluations per pixel (16 to 24 extra corner hashes in 3D).

  • chaff_sample_grad_2d() and chaff_sample_grad_3d() differentiate the cubic Hermite smoothstep analytically:

$$u(t) = t^2(3 - 2t) \implies u'(t) = 6t(1 - t)$$

  • Derivatives are computed in fixed-point integer registers directly alongside the elevation sample. Normal slopes are evaluated with zero additional corner hashes, delivering a 3x speedup over numerical finite differences.

F. 4-Wide SIMD 2D Batching, fade5 LUT & VLA-Free 2D Fast Paths

  • Header-only 4-wide batched APIs in <ttypt/chaff.h> (chaff_rot2d_i32_q15_4x, chaff_wpoint_periodic_2d_4x, chaff_fbm_rotated_2d_4x, chaff_fbm_rotated_2d_step_q12_4_4x, chaff_grad_noise2d_4x) and <ttypt/noise.h> (noise_hash2_4x, noise_wfade5_4x, noise_wstep_4x, noise_wpoint_2d_4x) use WebAssembly SIMD128 (__wasm_simd128__) when available with a bit-exact scalar fallback.
  • A 512-entry fixed-point lookup table (s_noise_fade5_q16_lut) accelerates noise_wfade5() for shifts $x \le 9$, and VLA-free dim == 2 fast paths in noise_get_v() and noise_wpoint_c() eliminate stack VLAs on 2D hot loops.

4. Seamless 2's Complement Boundary Wrapping

In open-world procedural engines, coordinate systems eventually hit data type limits. Naive floating-point or integer implementations suffer from:

  1. Coordinate Truncation Glitches: Integer overflow causing abrupt clamping or inversion.
  2. Boundary Seams: Step discontinuities between maximum positive values and negative values (e.g. $+32767 \to -32768$).
  3. Floating-Point Precision Loss: Floating-point coords far from the origin ($> 10^5$) lose sub-pixel precision, causing geometry jitter.
Coordinate Axis:  ... 32765   32766   32767 | -32768  -32767  -32766 ...
Lattice Cell:     [--------- Cell K --------] [-------- Cell K+1 -------]
                                            ^
                         Two's complement wrap: (int16_t)(32767 + 1) == -32768
                         Upper lattice corner seamlessly rolls over to -32768.
                         Hash key and Hermite offset are 100% continuous.

Mathematical Continuity Across int16_t Limits

libchaff uses two's complement int16_t coordinates spanning $[-32768 \dots 32767]$:

  1. Lattice Key Masking: The lower corner of a cell is masked by bitshift:

`c int16_t cell = (int16_t)(p & COORDMASK_LSHIFT(x)); `

  1. Modular Corner Offset: The far vertex of a quad is computed via 16-bit modular addition:

`c int16_t far_corner = (int16_t)(cell + (1 << x)); ` When cell == 32768 - (1 << x), adding $2^x$ wraps naturally to $-32768$: $$(32767 + 1) \equiv -32768 \pmod{65536}$$

  1. Identical Hash Digest: Because the hash input is the 16-bit integer coordinate itself, the digest evaluated at $+32768$ matches $-32768$ bit-for-bit.
  2. Fractional Offset Continuity: Intra-cell position $f \in [0, 2^x)$ is computed with bitwise masking:

`c uint32_t fix = (uint16_t)p & (uint16_t)~mask; ` As coordinates increment from $+32767$ to $-32768$, fix progresses smoothly from $(2^x - 1)$ to $0$, continuing the smoothstep without a single step discontinuity or missing pixel.

Result: Infinite coordinate traversal and continuously incrementing time counters ((int16_t)anim_tick) wrap around the data type boundary with zero seams, zero tearing, and zero branch penalties.


5. Recursive & Band-Limited Level of Detail (LOD)

Rendering a continuous planet from orbit down to sub-unit terrain requires smooth transitions across orders of magnitude of scale. Naive multi-octave noise causes two severe artifacts during zoom:

  1. High-Frequency Moiré Aliasing: Sampling high-frequency octaves at low sampling rates (large step sizes) produces chaotic visual noise and strobing.
  2. Abrupt LOD Popping: Dropping octaves abruptly causes visible snapping and geometric tears at chunk borders.

A. Band-Limited Nyquist Filtering (chaff_fill_lod)

chaff_fill_lod() dynamically filters the octave cascade based on the Nyquist-Shannon sampling theorem. An octave with wavelength $\lambda = 2^{\text{shift}}$ cannot be accurately represented by a sampling step size $\Delta > \frac{\lambda}{2}$.

/* Automatic Nyquist cutoff based on LOD resolution */
uint8_t min_shift = 0;
if      (lod == 0) min_shift = 6; /* Macro planetary rooms (step 64) */
else if (lod == 1) min_shift = 5; /* Distant terrain (step 16)       */
else if (lod == 2) min_shift = 3; /* Medium terrain (step 4)        */
/* LOD 3: all octaves active (step 1, full detail)                  */

uint8_t lo = 0;
while (lo < field->nlayers && field->layers[lo].shift < min_shift) {
    lo++; /* Prune sub-Nyquist high frequencies */
}
chaff_fill(field, lo, field->nlayers, origin, step_q16, n, out, stride, mode);
  • Performance Gain: Distant LOD 1 and LOD 2 evaluations skip 3 to 5 fine octaves, accelerating rendering by 2x to 4x.
  • Visual Stability: Distant hills and coastlines retain stable silhouettes without pixel flickering or moiré patterns.

B. Hierarchical Coordinate Scaling (chaff_coord_scale)

Fixed-point coordinates are scaled across recursive LOD layers without precision loss:

typedef struct {
    int16_t  cell;  /* Lattice/room units */
    uint16_t frac;  /* 1/65536 sub-unit fractional precision */
} chaff_coord_t;

chaff_coord_scale(coord, power_of_two) scales the combined 32-bit fixed-point value by $2^k$, preserving sub-pixel fractional alignments across recursive quadtree subdivisions.


6. Smooth Multi-Octave Noise Without Distortions

Standard Value Noise often exhibits objectionable visual artifacts: grid-aligned ridges, diagonal bias, and flat terraces resembling layered steps. libchaff eliminates these artifacts through mathematical formulation:

A. $C^2$ Quintic Hermite Smoothstep (NOISE_FADE5)

Standard cubic Hermite smoothing $u_3(t) = 3t^2 - 2t^3$ has a non-zero second derivative at boundaries ($u''_3(0) = 6, u''_3(1) = -6$). This discontinuity in surface curvature produces visible creases and Mach banding along cell borders.

libchaff implements Ken Perlin's quintic polynomial in integer arithmetic (NOISE_FADE5): $$u_5(t) = 6t^5 - 15t^4 + 10t^3$$ Its first and second derivatives are: $$u_5'(0) = u_5'(1) = 0, \quad u_5''(0) = u_5''(1) = 0$$ Both velocity and acceleration vanish at lattice cell edges. The resulting heightfield is $C^2$ continuous, eliminating all boundary creases and surface normal cracks.

B. Anti-Resonance Rotational Skew (chaff_rotate_q15)

When accumulating $N$ octaves of fractal noise on aligned Cartesian grids, power-of-two lattice boundaries coincide ($x \pmod{16} == 0$, $x \pmod{32} == 0$). Their stationary points ($u'(t) = 0$) line up, creating severe grid terracing and square plateaus.

libchaff eliminates Cartesian lattice resonance by rotating consecutive octave coordinate systems by an irrational Golden-Ratio angle ($\theta \approx 31.7^\circ$):

#define CHAFF_ROT_COS 27874 /* cos(31.7 deg) * 32768 */
#define CHAFF_ROT_SIN 17227 /* sin(31.7 deg) * 32768 */

static inline void chaff_rotate_q15(int16_t *x, int16_t *y) {
    int32_t rx = ((int32_t)(*x) * CHAFF_ROT_COS - (int32_t)(*y) * CHAFF_ROT_SIN) >> 15;
    int32_t ry = ((int32_t)(*x) * CHAFF_ROT_SIN + (int32_t)(*y) * CHAFF_ROT_COS) >> 15;
    *x = (int16_t)rx;
    *y = (int16_t)ry;
}
  • Each successive octave samples terrain along an independently rotated orientation.
  • Eliminates cardinal axis alignment, diagonal banding, and staircase terracing across infinite distances.

C. Continuous Planetary 12-Octave Ladder (chaff_elevation_q12_4)

Procedural planetary elevation is evaluated via a 12-octave geometric progression:

  • Macro Shifts 14..9: Continental landmasses and oceanic basins mapped across the $65,536 \times 65,536$ room planetary lattice.
  • Fine Shifts 8..3: Sub-room topography, rolling hills, dune ripples, and coastal bathymetry in sub-pixel Q12.4 precision.
  • Calibrated Sea-Level Baseline: Continental median elevation is calibrated to the canonical sea-level zero crossing, ensuring that ocean basins, coastal shallows, and mountain ranges align across all zoom levels.

7. Glitch-Free Planet Rendering & Zero-OpenGL Invariant

NeverDark and the pure-C web stack adhere to a strict architectural rule:

The Server's Right Not to Sell GPU

  • The server runtime (nd.so, libaxil-nd.so) runs strictly as pure software C99 integer math (-mgeneral-regs-only, zero floats, zero GPU libraries).
  • Zero OpenGL Linkage: Zero #include <GL/gl.h>, <EGL/egl.h>, -lGL, or -lgbm. Headless Linux/OpenBSD server daemons run on cloud instances with zero graphics hardware.
  • All collision detection, room exits, and player physics are computed deterministically via CPU integer math.

Bit-Exact Client GPU Acceleration (<ttypt/chaff_glsl.h>)

Clients with GPU capabilities (browser WebGL2 via Web HAL or native devices via liblamina) evaluate noise shaders on GPU compute/fragment cores.

To prevent client-server desynchronization (e.g. a client rendering dry land where the server registers drowning water collision), <ttypt/chaff_glsl.h> exports a bit-exact GLSL ES 3.0 integer hash:

/* Bit-exact XXH32 integer hash matching CPU libchaff in GLSL ES 3.0 */
uint chaff_rotl32(uint x, int r) {
    return (x << uint(r)) | (x >> uint(32 - r));
}

uint chaff_hash2(ivec2 p, uint seed) {
    uint val = (uint(p.y) & 0xFFFFu) | ((uint(p.x) & 0xFFFFu) << 16u);
    uint h = seed + 0x165667B1u + 4u;
    h += val * 0xC2B2AE3Du;
    h = chaff_rotl32(h, 17) * 0x27D4EB2Fu;
    h ^= h >> 15u;
    h *= 0x85EBCA77u;
    h ^= h >> 13u;
    h *= 0xC2B2AE3Du;
    h ^= h >> 16u;
    return h;
}
  • Level-Set Equivalence: The GPU shader evaluates the exact same 32-bit corner hashes and Hermite smoothstep as the server CPU.
  • The shoreline level-set $C_{\text{shore}} = \{ (wx, wy) \mid H(wx, wy) = W \}$ matches identically between WebGL2 fragment shaders and server collision logic.

8. Public C API Reference

The library provides two primary headers: <ttypt/chaff.h> (modern declarative cascades, analytical gradients, planetary elevation) and <ttypt/noise.h> (low-level matrix steppers, point samplers, and wrapping primitives).

Data Structures

TypeHeaderDescription
chaff_coord_t<ttypt/chaff.h>Fixed-point coordinate: int16_t cell + uint16_t frac (1/65536 unit).
chaff_layer_t<ttypt/chaff.h>Octave descriptor: shift, vshift, signed amp, seed_mode, contrast.
chaff_field_t<ttypt/chaff.h>Multi-layer declarative field descriptor with seed, dimensionality, and layer array.
chaff_sample_2d_t<ttypt/chaff.h>2D query result: int32_t elevation, analytical slopes int16_t grad_x, grad_y.
chaff_sample_3d_t<ttypt/chaff.h>3D query result: int32_t val, analytical gradients grad_x, grad_y, grad_z.
chaff_sample_4d_t<ttypt/chaff.h>4D query result: int32_t val, analytical gradients grad_x, grad_y, grad_z, grad_w.
chaff_fbm_opts_t<ttypt/chaff.h>Struct-driven 2D rotated fractal octave accumulator options (min_shift, max_shift, ridged_min_shift, period_shift).
chaff_periodic_opts_t<ttypt/chaff.h>Periodic 2D domain sampler descriptor (shift, period_shift, vshift, seed, fade_flags).
noise_wcache_t<ttypt/noise.h>Lattice corner vertex cache for scanline and row stepping.
noise_scanline_t<ttypt/noise.h>Declarative multi-octave scanline stepper state.

Core Evaluation Functions

Sparse Point Samplers

  • chaff_sample_grad_2d(field, wx, wy): Evaluates continuous 2D height and analytical surface slopes in a single pass with zero extra hashes.
  • chaff_sample_grad_3d(field, x, y, z): Evaluates 3D value and spatial gradient $(dN/dx, dN/dy, dN/dz)$ using analytical Hermite derivatives in 8 corners.
  • chaff_sample_grad_4d(field, x, y, z, w): Evaluates 4D value and spatio-temporal gradients $(dN/dx, dN/dy, dN/dz, dN/dw)$ across 16 hypercube corners.
  • chaff_sample_rugged_2d(field, wx, wy): Point evaluation with irrational Golden-Ratio rotational skew applied across octaves to break lattice alignment.
  • chaff_fbm_rotated_2d(&opts, x, y) / chaff_fbm_rotated_2d_q12_4(...): Parameterized 2D rotated fractal octave accumulator with ridged folding and optional periodic domain wrapping.
  • chaff_wpoint_periodic_2d(x, y, shift, period_shift, vshift, seed): Continuous 2D periodic octave with domain period $2^{\text{period\_shift}}$.
  • chaff_wpoint_periodic_2d_4x(...), chaff_fbm_rotated_2d_4x(...), chaff_fbm_rotated_2d_step_q12_4_4x(...), chaff_grad_noise2d_4x(...): 4-wide SIMD (__wasm_simd128__ + bit-exact scalar fallback) batched 2D samplers in <ttypt/chaff.h>.
  • noise_point_n(p, seed, shift, dim): Generic $N$-dimensional zero-allocation point query ($N \in [1..4]$).
  • noise_wpoint_n_periodic(p, shift, w, seed, dim, flags, period_shift): Two's complement wrapping and periodic point query.
  • noise_hash2_4x(...), noise_wfade5_4x(...), noise_wstep_4x(...), noise_wpoint_2d_4x(...): 4-wide SIMD/scalar 2D primitives in <ttypt/noise.h>.

High-Throughput Matrix & Region Steppers

  • chaff_fill(field, lo, hi, origin, step_q16, n, out, stride, mode): Primary fixed-point multi-layer region generator.
  • chaff_fill_lod(field, min_shift, origin, step_q16, n, out, stride, mode): Band-limited region generator pruning sub-Nyquist octaves.
  • chaff_fill_slice_3d(field, z, x0, y0, w, h, out_val, out_gx, out_gy): Bulk 2D slice stepper across 3D field; collapses $Z$ axis once per cell in registers (>96% hash reduction).
  • chaff_fill_slice_4d(field, z, w, x0, y0, width, height, out_val, out_gx, out_gy, out_gz, out_gw): Bulk 2D slice stepper across 4D field; collapses $W$ and $Z$ axes once per 4D cell in registers.
  • noise_matrix_fill_2d(cfg, ox, oy, size_shift, out): Bulk macroscopic quad fill using register additions.
  • noise_scanline_eval_row(scan, sx, y, z, count, out_row): Stepper fetching corners once per cell boundary.

Coordinate Transformers & Math

  • chaff_coord_scale(coord, power_of_two): Power-of-two zoom scaling for fixed-point coordinates.
  • chaff_rotate_q15(&x, &y) / chaff_rot2d_i32_q15(&x, &y, cos_q15, sin_q15): Fixed-point rotation by Golden-Ratio angle ($\theta \approx 31.7^\circ$).
  • chaff_octave_amplitude_ex(shift, min_shift, base_amp): Parameterized $1/f$ monotonic fractal amplitude scaling.
  • noise_fdiv(a, b): Euclidean integer floor division preserving mathematical continuity across negative coordinates.
  • noise_wfade5(f, x): $C^2$ continuous quintic Hermite polynomial $6t^5 - 15t^4 + 10t^3$ mapping $[0..2^x)$ to $[0..2^x)$.

9. Performance Metrics & Benchmarks

Run the benchmark suite:

make -C external/libchaff bench

Empirical throughput measured on standard host environment:

Benchmark OperationTarget MethodThroughputLatencyHash Reductions / Speedup
Point Query 2Dnoise_point_n18.76 Mops/s53.31 ns/opBaseline 2D point lookup
Point Query 3Dnoise_point_n7.70 Mops/s129.91 ns/opBaseline 3D point lookup
Analytical 2D Gradientchaff_sample_grad_2d5.45 Mops/s183.42 ns/op3 octaves, 0 additional hashes
Analytical 3D Gradientchaff_sample_grad_3d2.32 Mops/s430.71 ns/op3 octaves, 0 additional hashes
2D Time-Slice Stepperchaff_fill_slice_3d88.44 Mops/s11.31 ns/sample37.30x speedup vs 3D point query (2.37 Mops/s); >96% corner hash reduction
1D Scanline Steppernoise_scanline_eval_row120.23 Mops/s8.32 ns/sample17 corner fetches per 256 pixels

10. Verification of Core Architectural Promises & Testing Ecosystem

Modeled after the testing and metrics architecture in external/libcorm, external/libchaff provides a modular 4-suite test harness and turnkey runner verifying numerical stability, boundary wrapping, and GPU shader parity:

# Run all 4 modular test suites:
make -C external/libchaff test

# Run the complete test suite and comprehensive operational metrics:
./external/libchaff/test.sh

# Run standalone metrics & throughput benchmarks:
make -C external/libchaff bench

Modular Test Suite Layout

  1. Core Engine Suite (bin/test_noise): 35 automated assertions verifying 1D–4D point sampling, hypercube matrix stepping, scanline caches, plane steppers, and boundary continuity.
  2. Canonical libchaff Public API Suite (bin/test_chaff): Comprehensive sections verifying point wrappers (chaff_point_1d..4d, chaff_point_n), canonical matrix/sample adapters (chaff_oct, chaff_matrix_fill_2d), chaff_coord_scale, chaff_fade_frac, 1D/3D volume chaff_fill in SET and ADD modes, coordinate skewing, periodic domain tiling (period_shift), contrast, 2D/3D/4D analytical gradients, 2D time-slice stepping (chaff_fill_slice_3d, chaff_fill_slice_4d) across multi-cell and negative coordinates, rotational skew (chaff_rotate_q15, chaff_rotate_q15_inplace), rotated FBM (chaff_fbm_rotated_2d), banded flow evaluation, and defensive NULL-safety guards.
  3. Shared Library Exported ABI Suite (bin/test_symbols): Verifies that all exported symbols in src/libchaff.c resolve cleanly and match inline header functions bit-for-bit.
  4. GLSL ES 3.0 GPU Shader Contract Suite (bin/test_glsl): Verifies shader strings, uniform buffer structure layout (chaff_gl_uniforms_t), rotl32 bit operations, bit-exact 2D/3D/4D integer hashes (chaff_hash2, chaff_hash3, chaff_hash4), continuous octave sampling, analytical gradients, and Golden-Ratio rotation parameters.
  5. Continuous Surface Cascade Suite (bin/test_cascade): Verifies <ttypt/chaff_surf.h> scalar-vs-4x parity, Nyquist stride band-limiting monotonicity, torus periodicity, analytical gradients, chaff_surf_ubo_t std140 packing, and GLSL ES 3.00 high-shift period overflow guards.

11. Spatial Index & Quadtree Integration (libareole)

libchaff is designed to pair directly with libareole (<ttypt/areole.h>) for real-time 3D planetary rendering, camera frustum culling, and multi-scale LOD management.

Canonical Sampler Binding

#include <ttypt/chaff.h>
#include <ttypt/areole.h>

void chaff_areole_sampler(void *user_ctx, uint16_t world, uint8_t level,
                          int32_t wx, int32_t wy, ar_sample_t *out)
{
    uint8_t min_shift = (level >= 6) ? 6 : (uint8_t)(2 + level);
    int32_t elev_q12_4 = chaff_fbm_rotated_2d_q12_4(
        wx, wy, min_shift, 14, 6, 2, 1,
        (uint32_t)world * 2654435761u, 0x9E3779B9u,
        CHAFF_ROT_GOLD_COS_Q15, CHAFF_ROT_GOLD_SIN_Q15);

    out->val = (int16_t)elev_q12_4;
    out->attr[0] = (elev_q12_4 > 100 * 16) ? 2 : 10;
    out->attr[3] = (elev_q12_4 < 0) ? (uint8_t)(-elev_q12_4 >> 4) : 0;
    out->rgba = (out->attr[3] > 0) ? 0xFF003080u : 0xFF208020u;
    out->flags = (out->attr[3] > 0) ? AR_NODE_FLAG_USER0 : 0;
}

The resulting spatial hierarchy can be queried with column-major $4 \times 4$ ModelView-Projection (MVP) matrices using Gribb-Hartmann 6-plane frustum extraction and pluggable vertical/3D manifold envelopes via ar_system_query_matrix().


12. Installation & Build

Prebuilt Packages

Prebuilt packages for Linux (APT / Alpine / Arch / Fedora-RHEL), macOS (Homebrew), Windows (winget / MSYS2), and OpenBSD, and mobile static sysroots for Android (https://tty.pt/android/ — arm64-v8a, armeabi-v7a, x86_64) and iOS (https://tty.pt/ios/ — libchaff.xcframework) are distributed via tty.pt packages. Use libchaff as the package name.

Build from Source

Builds use shared libstele rules (include ttypt/include.mk):

make              # builds lib/libchaff.so and lib/libnoise.so
make wasm         # builds npm/dist/chaff.wasm
make test         # runs the C & GLSL parity verification suite
make npm-test     # runs the Node.js & WebAssembly test suite
sudo make install # install headers and libraries to system

13. JavaScript & WebAssembly Bindings (@tty-pt/chaff)

For browser, Node.js, and WebGL2 shader pipelines, libchaff ships an isomorphic WebAssembly and GLSL package on npm:

npm config set @tty-pt:registry https://tty.pt/npm/
npm install @tty-pt/chaff

See npm/README.md for the full TypeScript, WebAssembly, and GLSL shader API reference.


License

BSD 2-Clause License — Copyright (c) 2026, tty-pt. See LICENSE.

Maintained by:tty-pt