# Hexagonal Stochastic Anti-Tiling & Seamless Surface Detail in Three.js

> Eliminate visible texture grid repetition on large floors, terrain, and cliffs in Three.js r183 by patching MeshStandardMaterial with 3-tap hexagonal barycentric stochastic UV sampling and variance-preserving blending.

- **Canonical page:** https://gamecrew.ai/techniques/three/hex-stochastic-anti-tiling
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** materials
- **Tags:** `tiling`, `hex-tiling`, `stochastic`, `texture`, `anti-tiling`, `terrain`, `materials`, `shader`, `onbeforecompile`, `webgl2`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-13)
- **Demo:** No demo

## When to Use & Field Best Practices

Repeating a single 1024 px stone, grass, sand, or cliff texture across a 100 m floor produces unmistakable checkerboard grids from elevated or overview cameras. **Hexagonal Stochastic Tiling** breaks repetition permanently using just **3 texture fetches per pixel** on standard PBR materials — with zero extra geometry or megatextures:

1. **Hexagonal Lattice + Barycentric Weights**: Partition UV space into an equilateral triangle/hex grid so every pixel sits inside one triangle of 3 hex centers. Compute smooth power-weighted barycentric weights (`w^contrast`) so hex blends remain crisp instead of blurry.
2. **Explicit `textureGrad` Derivatives (No Mipmap Seams!)**: Because each hex cell offsets (and optionally rotates) UVs discontinuously at triangle edges, naive `texture2D` causes finite-difference `dFdx`/`dFdy` spikes and ugly black/blurry seam lines. Always compute `vec2 ddx = dFdx(uv); vec2 ddy = dFdy(uv);` **before** offsetting and pass them into `textureGrad(tex, uv + off, ddx, ddy)`.
3. **Variance-Preserving Color Restoration**: Blending 3 random samples shrinks contrast toward the texture's mean color (`sqrt(w1^2 + w2^2 + w3^2) < 1`). Re-normalizing around a low-mip mean sample (or `mix` contrast boost) keeps stone grain and foliage crisp across blend zones.
4. **Stable `customProgramCacheKey`**: Always set `mat.customProgramCacheKey` when using `onBeforeCompile` so Three.js shares compiled WebGL programs across materials using the same anti-tiling config.

## Mathematical & Algorithmic Core

- **Skewed Triangular Lattice**: Transform $\mathbf{p} = \text{uv} \cdot s$ by the skew matrix $M = \begin{pmatrix} 1 & -\frac{1}{\sqrt{3}} \\ 0 & \frac{2}{\sqrt{3}} \end{pmatrix}$ to locate triangle vertices $\mathbf{v}_1, \mathbf{v}_2, \mathbf{v}_3$ and barycentric weights $(w_1, w_2, w_3)$ with $\sum w_i = 1$.
- **Contrast-Preserving Blend** with mean color $\bar{\mathbf{c}}$ and sharpness $k \in [1, 8]$:
  $$\tilde{w}_i = \frac{w_i^k}{\sum_j w_j^k}, \qquad \mathbf{c} = \bar{\mathbf{c}} + \frac{\sum_i \tilde{w}_i (\mathbf{s}_i - \bar{\mathbf{c}})}{\sqrt{\sum_i \tilde{w}_i^2}}$$

## Engine Implementation (`Assets/Game/hexTiling.ts`)

Strict erasable TypeScript patching any `THREE.MeshStandardMaterial` (albedo + optional normal/roughness maps) plus a zero-dependency procedural tileable stone/ground `DataTexture` fallback:

```ts
import * as THREE from 'three';

export interface HexTilingOptions {
  /** World/UV tile scale multiplier inside the hex lattice (default 1.0). */
  patchScale?: number;
  /** Blend sharpness between neighboring hex patches (1 = soft, 6 = crisp, default 4.0). */
  blendSharpness?: number;
  /** Per-patch UV rotation in radians (0 keeps directional bricks aligned, default 0.35). */
  rotationJitter?: number;
  /** Restore micro-contrast across 3-tap blend zones (0..1, default 0.65). */
  contrastPreserve?: number;
}

export interface HexTilingUniforms {
  uHexScale: { value: number };
  uHexSharpness: { value: number };
  uHexRotate: { value: number };
  uHexContrast: { value: number };
}

const HEX_GLSL_HELPERS = /* glsl */ `
uniform float uHexScale;
uniform float uHexSharpness;
uniform float uHexRotate;
uniform float uHexContrast;

vec2 hexHash2(vec2 p) {
  vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
  p3 += dot(p3, p3.yzx + 33.33);
  return fract((p3.xx + p3.yz) * p3.zy);
}

mat2 hexRot2(float a) {
  float c = cos(a);
  float s = sin(a);
  return mat2(c, -s, s, c);
}

vec4 hexTileSample(sampler2D tex, vec2 uv) {
  vec2 ddx = dFdx(uv);
  vec2 ddy = dFdy(uv);

  vec2 p = uv * uHexScale;
  // Skew square grid into equilateral triangle lattice
  mat2 skew = mat2(1.0, 0.0, -0.57735027, 1.15470054);
  vec2 sp = skew * p;
  vec2 cell = floor(sp);
  vec2 f = fract(sp);

  vec2 v1 = cell;
  vec2 v2 = cell + vec2(1.0, 1.0);
  vec2 v3 = f.x > f.y ? (cell + vec2(1.0, 0.0)) : (cell + vec2(0.0, 1.0));

  float w1 = 1.0 - max(f.x, f.y);
  float w2 = min(f.x, f.y);
  float w3 = abs(f.x - f.y);

  float k = max(1.0, uHexSharpness);
  vec3 w = pow(max(vec3(w1, w2, w3), vec3(1e-4)), vec3(k));
  w /= (w.x + w.y + w.z);

  vec2 h1 = hexHash2(v1);
  vec2 h2 = hexHash2(v2);
  vec2 h3 = hexHash2(v3);

  mat2 r1 = hexRot2((h1.x - 0.5) * uHexRotate);
  mat2 r2 = hexRot2((h2.x - 0.5) * uHexRotate);
  mat2 r3 = hexRot2((h3.x - 0.5) * uHexRotate);

  vec4 s1 = textureGrad(tex, r1 * uv + h1, r1 * ddx, r1 * ddy);
  vec4 s2 = textureGrad(tex, r2 * uv + h2, r2 * ddx, r2 * ddy);
  vec4 s3 = textureGrad(tex, r3 * uv + h3, r3 * ddx, r3 * ddy);

  vec4 blended = s1 * w.x + s2 * w.y + s3 * w.z;
  if (uHexContrast > 0.001) {
    vec4 meanCol = textureLod(tex, uv, 6.0);
    float invNorm = inversesqrt(max(dot(w, w), 0.12));
    vec4 restored = meanCol + (blended - meanCol) * min(invNorm, 1.65);
    blended = mix(blended, clamp(restored, 0.0, 1.0), uHexContrast);
  }
  return blended;
}
`;

/**
 * Patches a Three.js MeshStandardMaterial in place so its albedo (map) and roughnessMap
 * sample via 3-tap hexagonal stochastic anti-tiling with derivative-safe textureGrad.
 */
export function applyHexAntiTiling(
  material: THREE.MeshStandardMaterial,
  opts: HexTilingOptions = {}
): HexTilingUniforms {
  const uniforms: HexTilingUniforms = {
    uHexScale: { value: opts.patchScale ?? 1.0 },
    uHexSharpness: { value: opts.blendSharpness ?? 4.0 },
    uHexRotate: { value: opts.rotationJitter ?? 0.35 },
    uHexContrast: { value: opts.contrastPreserve ?? 0.65 },
  };

  material.customProgramCacheKey = () => 'ccgd-hex-anti-tiling-v1';
  material.onBeforeCompile = (shader) => {
    shader.uniforms.uHexScale = uniforms.uHexScale;
    shader.uniforms.uHexSharpness = uniforms.uHexSharpness;
    shader.uniforms.uHexRotate = uniforms.uHexRotate;
    shader.uniforms.uHexContrast = uniforms.uHexContrast;

    shader.fragmentShader = shader.fragmentShader
      .replace('#include <common>', `#include <common>\n${HEX_GLSL_HELPERS}`)
      .replace(
        '#include <map_fragment>',
        /* glsl */ `
        #ifdef USE_MAP
          vec4 sampledDiffuseColor = hexTileSample( map, vMapUv );
          diffuseColor *= sampledDiffuseColor;
        #endif
        `
      )
      .replace(
        '#include <roughnessmap_fragment>',
        /* glsl */ `
        float roughnessFactor = roughness;
        #ifdef USE_ROUGHNESSMAP
          vec4 texelRoughness = hexTileSample( roughnessMap, vRoughnessMapUv );
          roughnessFactor *= texelRoughness.g;
        #endif
        `
      );
  };
  material.needsUpdate = true;
  return uniforms;
}

/**
 * Procedural seamless stone/earth DataTexture fallback (zero network/file dependency)
 * useful when building a terrain material before generated textures are loaded.
 */
export function createSeamlessGroundTexture(
  baseHex = 0x5c6354,
  accentHex = 0x454b3f,
  size = 128
): THREE.DataTexture {
  const data = new Uint8Array(size * size * 4);
  // Extract raw sRGB channels directly (new THREE.Color(hex) converts to linear, which would double-darken SRGBColorSpace DataTextures)
  const aR = (baseHex >> 16) & 255;
  const aG = (baseHex >> 8) & 255;
  const aB = baseHex & 255;
  const bR = (accentHex >> 16) & 255;
  const bG = (accentHex >> 8) & 255;
  const bB = accentHex & 255;

  const hash = (x: number, y: number): number => {
    const wx = ((x % size) + size) % size;
    const wy = ((y % size) + size) % size;
    const n = Math.sin(wx * 12.9898 + wy * 78.233) * 43758.5453;
    return n - Math.floor(n);
  };

  const smoothTileNoise = (u: number, v: number, freq: number): number => {
    const x = u * freq;
    const y = v * freq;
    const ix = Math.floor(x);
    const iy = Math.floor(y);
    const fx = x - ix;
    const fy = y - iy;
    const sx = fx * fx * (3 - 2 * fx);
    const sy = fy * fy * (3 - 2 * fy);
    const p = Math.max(1, Math.round(freq));
    const n00 = hash(ix % p, iy % p);
    const n10 = hash((ix + 1) % p, iy % p);
    const n01 = hash(ix % p, (iy + 1) % p);
    const n11 = hash((ix + 1) % p, (iy + 1) % p);
    return (n00 * (1 - sx) + n10 * sx) * (1 - sy) + (n01 * (1 - sx) + n11 * sx) * sy;
  };

  for (let y = 0; y < size; y++) {
    for (let x = 0; x < size; x++) {
      const u = x / size;
      const v = y / size;
      const fbm =
        smoothTileNoise(u, v, 8) * 0.55 +
        smoothTileNoise(u, v, 16) * 0.30 +
        smoothTileNoise(u, v, 32) * 0.15;
      const i = (y * size + x) * 4;
      data[i] = Math.round(bR + (aR - bR) * fbm);
      data[i + 1] = Math.round(bG + (aG - bG) * fbm);
      data[i + 2] = Math.round(bB + (aB - bB) * fbm);
      data[i + 3] = 255;
    }
  }

  const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.RepeatWrapping;
  tex.generateMipmaps = true;
  tex.minFilter = THREE.LinearMipmapLinearFilter;
  tex.magFilter = THREE.LinearFilter;
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.needsUpdate = true;
  return tex;
}
```

## Browser, Mobile & Software-Renderer Budgets

- **Texture Cost**: 3 `textureGrad` taps + 1 mip-6 mean lookup per mapped channel (~`0.18 ms` at 1080p on integrated/mobile GPUs). Keep `rotationJitter = 0` on directional materials (brick, wood planks) and `0.35–1.2` on organic dirt, grass, sand, and stone.
- **Mipmaps Required**: Ensure `tex.generateMipmaps = true` and `tex.wrapS = tex.wrapT = THREE.RepeatWrapping` on any texture passed to `applyHexAntiTiling` so `textureLod(tex, uv, 6.0)` returns a true average color.
- **VR Parity**: Runs natively inside standard `MeshStandardMaterial` stereo draws with zero extra render passes — 100% WebXR safe.

## Verification Checklist

1. Run `compile` (`threeCompile`) to confirm the patched `onBeforeCompile` shader compiles cleanly in WebGL 2 with zero GLSL warnings.
2. Tile a ground plane `12 × 12` times and inspect an overview capture: confirm zero checkerboard grid lines and zero black mipmap seams along hex patch boundaries.
3. Verify `contrastPreserve` keeps terrain contrast readable rather than washing the ground into flat grey.

## Official references

- Ameobea — three-hex-tiling (MIT)
- Morten S. Mikkelsen (2022 — Practical Real-Time Hex-Tiling)
- Thomas Deliot & Eric Heitz (HPG 2018 — Procedural Stochastic Texturing by Tiling and Blending)
- Inigo Quilez (2015 — Texture Repetition Elimination)

## Open-source sources

- Takes an idea from three-hex-tiling by Ameobea (MIT License), https://github.com/Ameobea/three-hex-tiling (3-tap hexagonal barycentric stochastic UV anti-tiling formulation)

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
